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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b031867317e3c03e3c5ce381 | train | function | def decline_proposal(
sender, obj=None, src=None, service=None,
event=None, initial_state=None): # noqa
"""Decline proposal procedure hook."""
if not is_status_changed_to(obj.STATES.DECLINED, obj):
return
obj.declined_by = login.get_current_user()
obj.decline_datetime = datetime.datetime.utcnow()
... | def decline_proposal(
sender, obj=None, src=None, service=None,
event=None, initial_state=None): # noqa
| """Decline proposal procedure hook."""
if not is_status_changed_to(obj.STATES.DECLINED, obj):
return
obj.declined_by = login.get_current_user()
obj.decline_datetime = datetime.datetime.utcnow()
add_comment_about(obj, obj.STATES.DECLINED, obj.decline_reason)
| PLIED, obj.apply_reason)
# notify proposalable instance that proposal applied
signals.Proposal.proposal_applied.send(obj.instance.__class__,
instance=obj.instance)
def decline_proposal(
sender, obj=None, src=None, service=None,
event=None, initial_state=None): # noq... | 64 | 64 | 98 | 29 | 35 | pbedn/ggrc-core | src/ggrc/models/hooks/proposal.py | Python | decline_proposal | decline_proposal | 65 | 73 | 65 | 67 | 05c28a2130bd17cbdf64a234a49c9106ca081628 | bigcode/the-stack | train |
9a7640b81877fdbe60211811 | train | class | class HpeIloBaseAction(Action):
def __init__(self,config):
super(HpeIloBaseAction, self).__init__(config)
self.client = self._get_client()
def _get_client(self):
login_host = self.config['login_host']
login_account = self.config['login_account']
login_password = self.con... | class HpeIloBaseAction(Action):
| def __init__(self,config):
super(HpeIloBaseAction, self).__init__(config)
self.client = self._get_client()
def _get_client(self):
login_host = self.config['login_host']
login_account = self.config['login_account']
login_password = self.config['login_password']
##... | man"]
# __license__ = "Apache2.0"
# __maintainer__ = "Rick Kauffman"
# __email__ = "rick.a.kauffman@hpe.com"
import redfish
from st2common.runners.base_action import Action
class HpeIloBaseAction(Action):
| 64 | 64 | 141 | 9 | 54 | xod442/stackstorm-hpe-iloamplifier | actions/lib/actions.py | Python | HpeIloBaseAction | HpeIloBaseAction | 24 | 37 | 24 | 24 | 6d819dedafd9df8d137f4dbf411e36148302a41a | bigcode/the-stack | train |
e685a2d164a8e6f8923c009d | train | class | class FillBetweenItem(QtWidgets.QGraphicsPathItem):
"""
GraphicsItem filling the space between two PlotDataItems.
"""
def __init__(self, curve1=None, curve2=None, brush=None, pen=None):
QtWidgets.QGraphicsPathItem.__init__(self)
self.curves = None
if curve1 is not None and curve2... | class FillBetweenItem(QtWidgets.QGraphicsPathItem):
| """
GraphicsItem filling the space between two PlotDataItems.
"""
def __init__(self, curve1=None, curve2=None, brush=None, pen=None):
QtWidgets.QGraphicsPathItem.__init__(self)
self.curves = None
if curve1 is not None and curve2 is not None:
self.setCurves(curve1, cur... | from .. import functions as fn
from ..Qt import QtGui, QtWidgets
from .PlotCurveItem import PlotCurveItem
from .PlotDataItem import PlotDataItem
__all__ = ['FillBetweenItem']
class FillBetweenItem(QtWidgets.QGraphicsPathItem):
| 57 | 192 | 640 | 11 | 46 | StSav012/pyqtgraph | pyqtgraph/graphicsItems/FillBetweenItem.py | Python | FillBetweenItem | FillBetweenItem | 8 | 82 | 8 | 8 | d819849959ac6ccb108bd00a8b348ab5a529c735 | bigcode/the-stack | train |
e627a2c0cdfa2f386f301251 | train | function | def setup_logging():
handler = logging.StreamHandler(sys.stdout if settings.LOG_STDOUT else sys.stderr)
formatter = logging.Formatter(settings.LOG_FORMAT)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(settings.LOG_LEVEL)
# Make noisy librar... | def setup_logging():
| handler = logging.StreamHandler(sys.stdout if settings.LOG_STDOUT else sys.stderr)
formatter = logging.Formatter(settings.LOG_FORMAT)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(settings.LOG_LEVEL)
# Make noisy libraries less noisy
if... | import Limiter
from flask_limiter.util import get_ipaddr
from flask_migrate import Migrate
from redash import settings
from redash.query_runner import import_query_runners
from redash.destinations import import_destinations
__version__ = '4.0.1'
def setup_logging():
| 64 | 64 | 133 | 4 | 60 | haroldwoo/redash | redash/__init__.py | Python | setup_logging | setup_logging | 25 | 37 | 25 | 25 | 229897b7f883e53244feafc526a6dc4129bef0d0 | bigcode/the-stack | train |
c66624fd5e38cd1a936431d8 | train | class | class SlugConverter(BaseConverter):
def to_python(self, value):
# This is ay workaround for when we enable multi-org and some files are being called by the index rule:
# for path in settings.STATIC_ASSETS_PATHS:
# full_path = safe_join(path, value)
# if os.path.isfile(full_pa... | class SlugConverter(BaseConverter):
| def to_python(self, value):
# This is ay workaround for when we enable multi-org and some files are being called by the index rule:
# for path in settings.STATIC_ASSETS_PATHS:
# full_path = safe_join(path, value)
# if os.path.isfile(full_path):
# raise Validat... | ATSD_PREFIX)
limiter = Limiter(key_func=get_ipaddr, storage_uri=settings.LIMITER_STORAGE)
import_query_runners(settings.QUERY_RUNNERS)
import_destinations(settings.DESTINATIONS)
from redash.version_check import reset_new_version_status
reset_new_version_status()
class SlugConverter(BaseConverter):
| 64 | 64 | 96 | 7 | 57 | haroldwoo/redash | redash/__init__.py | Python | SlugConverter | SlugConverter | 79 | 90 | 79 | 79 | 6c0669b3a3c11d2e9c3598b72257db012430d13a | bigcode/the-stack | train |
13ef96609c034483021cdea2 | train | function | def create_app(load_admin=True):
from redash import extensions, handlers
from redash.handlers.webpack import configure_webpack
from redash.handlers import chrome_logger
from redash.admin import init_admin
from redash.models import db
from redash.authentication import setup_authentication
fro... | def create_app(load_admin=True):
| from redash import extensions, handlers
from redash.handlers.webpack import configure_webpack
from redash.handlers import chrome_logger
from redash.admin import init_admin
from redash.models import db
from redash.authentication import setup_authentication
from redash.metrics.request import p... | import_destinations(settings.DESTINATIONS)
from redash.version_check import reset_new_version_status
reset_new_version_status()
class SlugConverter(BaseConverter):
def to_python(self, value):
# This is ay workaround for when we enable multi-org and some files are being called by the index rule:
#... | 128 | 128 | 428 | 7 | 120 | haroldwoo/redash | redash/__init__.py | Python | create_app | create_app | 93 | 149 | 93 | 93 | 42ea4720f30c63196f1336d40c17eade5bc30cf2 | bigcode/the-stack | train |
0f543e241b0ff4ac7925b687 | train | function | def create_redis_connection():
logging.debug("Creating Redis connection (%s)", settings.REDIS_URL)
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.scheme == 'redis+socket':
qs = urlparse.parse_qs(redis_url.query)
if 'virtual_host' in qs:
db = qs['virtual_host'][0]... | def create_redis_connection():
| logging.debug("Creating Redis connection (%s)", settings.REDIS_URL)
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.scheme == 'redis+socket':
qs = urlparse.parse_qs(redis_url.query)
if 'virtual_host' in qs:
db = qs['virtual_host'][0]
else:
db =... | logging.getLogger("passlib").setLevel("ERROR")
logging.getLogger("requests.packages.urllib3").setLevel("ERROR")
logging.getLogger("snowflake.connector").setLevel("ERROR")
logging.getLogger('apiclient').setLevel("ERROR")
def create_redis_connection():
| 64 | 64 | 190 | 6 | 58 | haroldwoo/redash | redash/__init__.py | Python | create_redis_connection | create_redis_connection | 40 | 61 | 40 | 40 | dbd598fbf7ba00b9a56db36730b1d2965ffdbeaa | bigcode/the-stack | train |
e040214dc18a8f341dfd4898 | train | function | def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(HomeController.blueprint)
app.register_blueprint(FaucetController.blueprint)
| def register_blueprints(app):
| """Register Flask blueprints."""
app.register_blueprint(HomeController.blueprint)
app.register_blueprint(FaucetController.blueprint)
| extensions."""
cors.init_app(app)
webpack.init_app(app)
socketio.init_app(app, message_queue='redis://')
db.init_app(app)
if not get_debug_flag():
scheduler.init_app(app)
scheduler.start()
scheduler.run_job('missingcheck')
def register_blueprints(app):
| 64 | 64 | 35 | 6 | 58 | Grayyyyy/monkeytalks | app/app.py | Python | register_blueprints | register_blueprints | 32 | 35 | 32 | 32 | f24e141c320f8bf99b249014186e9f99e9ce42a2 | bigcode/the-stack | train |
001a1d04e2924a5c059e6dc0 | train | function | def register_commands(app):
"""Register Click commands."""
app.cli.add_command(commands.test)
app.cli.add_command(commands.dbinit)
app.cli.add_command(commands.testmessage)
app.cli.add_command(commands.deletemsg)
app.cli.add_command(commands.fixcounts) | def register_commands(app):
| """Register Click commands."""
app.cli.add_command(commands.test)
app.cli.add_command(commands.dbinit)
app.cli.add_command(commands.testmessage)
app.cli.add_command(commands.deletemsg)
app.cli.add_command(commands.fixcounts) | if not get_debug_flag():
scheduler.init_app(app)
scheduler.start()
scheduler.run_job('missingcheck')
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(HomeController.blueprint)
app.register_blueprint(FaucetController.blueprint)
def register_comma... | 64 | 64 | 57 | 5 | 59 | Grayyyyy/monkeytalks | app/app.py | Python | register_commands | register_commands | 37 | 43 | 37 | 37 | 503764dfd7a541c16c84a5418ccb7fd8d79bf2d7 | bigcode/the-stack | train |
8b56b379018ac701dda0446d | train | function | def register_extensions(app):
"""Register Flask extensions."""
cors.init_app(app)
webpack.init_app(app)
socketio.init_app(app, message_queue='redis://')
db.init_app(app)
if not get_debug_flag():
scheduler.init_app(app)
scheduler.start()
scheduler.run_job('missingcheck')
| def register_extensions(app):
| """Register Flask extensions."""
cors.init_app(app)
webpack.init_app(app)
socketio.init_app(app, message_queue='redis://')
db.init_app(app)
if not get_debug_flag():
scheduler.init_app(app)
scheduler.start()
scheduler.run_job('missingcheck')
| :
"""Application Factory Pattern"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_commands(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
return app
def register_extensions(app):
| 64 | 64 | 67 | 5 | 58 | Grayyyyy/monkeytalks | app/app.py | Python | register_extensions | register_extensions | 21 | 30 | 21 | 21 | eb43d0406da2b4d03e4a4f870e6747fc6a8e81be | bigcode/the-stack | train |
fdb17e0d2e1aad12d30f01cf | train | function | def create_app(config_object : AppConfig = ProdConfig) -> Flask:
"""Application Factory Pattern"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_commands(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
retu... | def create_app(config_object : AppConfig = ProdConfig) -> Flask:
| """Application Factory Pattern"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
register_commands(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
return app
| from app.settings import AppConfig, ProdConfig
from app.controllers import HomeController, FaucetController
from app.database import db
from app.extensions import webpack, socketio, cors, scheduler
from werkzeug.contrib.fixers import ProxyFix
def create_app(config_object : AppConfig = ProdConfig) -> Flask:
| 64 | 64 | 73 | 15 | 48 | Grayyyyy/monkeytalks | app/app.py | Python | create_app | create_app | 11 | 19 | 11 | 11 | 0872ee8d224d81fa41df4e442f820722567525ca | bigcode/the-stack | train |
b4d995a09d634990216459f0 | train | function | def test_all_builtin_models_default_constructible():
bad = []
for name, cls in Model.__class__.model_class_reverse_map.items():
try:
cls()
except:
bad.append(name)
assert bad == []
| def test_all_builtin_models_default_constructible():
| bad = []
for name, cls in Model.__class__.model_class_reverse_map.items():
try:
cls()
except:
bad.append(name)
assert bad == []
| bs[0]
assert isinstance(cb, CustomJS)
assert cb.args == dict(other=m2)
assert cb.code == "other.b = this.a"
from bokeh.models import * # NOQA
from bokeh.plotting import * # NOQA
def test_all_builtin_models_default_constructible():
| 64 | 64 | 48 | 9 | 54 | aparamon/bokeh | bokeh/tests/test_model.py | Python | test_all_builtin_models_default_constructible | test_all_builtin_models_default_constructible | 134 | 141 | 134 | 134 | 60b1fb6eed31741fe11a2e1fec79dddf99ad1d85 | bigcode/the-stack | train |
556a6c2891e580579f12f190 | train | class | class Test_js_link(object):
def test_value_error_on_bad_attr(self):
m1 = SomeModel()
m2 = SomeModel()
with pytest.raises(ValueError) as e:
m1.js_link('junk', m2, 'b')
assert str(e).endswith("ValueError: %r is not a property of self (%r)" % ("junk", m1))
def test_val... | class Test_js_link(object):
| def test_value_error_on_bad_attr(self):
m1 = SomeModel()
m2 = SomeModel()
with pytest.raises(ValueError) as e:
m1.js_link('junk', m2, 'b')
assert str(e).endswith("ValueError: %r is not a property of self (%r)" % ("junk", m1))
def test_value_error_on_bad_other(self):
... | m.js_on_change('foo', cb1)
assert m.js_property_callbacks == {"foo": [cb1]}
m.js_on_change('foo', cb2)
assert m.js_property_callbacks == {"foo": [cb1, cb2]}
def test_ignores_dupe_callbacks(self):
cb = CustomJS(code="")
m = SomeModel()
m.js_on_change('foo', cb... | 109 | 110 | 367 | 6 | 103 | aparamon/bokeh | bokeh/tests/test_model.py | Python | Test_js_link | Test_js_link | 96 | 130 | 96 | 97 | 671164b448a125c126da996cf1b3530c9c80548e | bigcode/the-stack | train |
7c13a799452b7059ac730f66 | train | class | class Test_js_on_change(object):
def test_exception_for_no_callbacks(self):
m = SomeModel()
with pytest.raises(ValueError):
m.js_on_change('foo')
def test_exception_for_bad_callbacks(self):
m = SomeModel()
for val in [10, "bar", None, [1], {}, 10.2]:
wit... | class Test_js_on_change(object):
| def test_exception_for_no_callbacks(self):
m = SomeModel()
with pytest.raises(ValueError):
m.js_on_change('foo')
def test_exception_for_bad_callbacks(self):
m = SomeModel()
for val in [10, "bar", None, [1], {}, 10.2]:
with pytest.raises(ValueError):
... | __ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh ... | 131 | 131 | 439 | 7 | 124 | aparamon/bokeh | bokeh/tests/test_model.py | Python | Test_js_on_change | Test_js_on_change | 43 | 94 | 43 | 44 | e068b4c468307400dd3fb5cbed88898d3e7b436f | bigcode/the-stack | train |
2fa1e36045911d0f41b502e0 | train | class | class SomeModel(Model):
a = Int(12)
b = String("hello")
c = List(Int, [1, 2, 3])
| class SomeModel(Model):
| a = Int(12)
b = String("hello")
c = List(Int, [1, 2, 3])
| # External imports
# Bokeh imports
from bokeh.core.properties import Int, String, List
from bokeh.models.callbacks import CustomJS
# Module under test
from bokeh.model import Model
#-----------------------------------------------------------------------------
# Setup
#------------------------------------------------... | 63 | 64 | 34 | 5 | 58 | aparamon/bokeh | bokeh/tests/test_model.py | Python | SomeModel | SomeModel | 38 | 41 | 38 | 38 | fab6351e205b329b46b273b25fe666ac80e24387 | bigcode/the-stack | train |
94131dcd786d8f1e380d1fa6 | train | class | @context.export_singleton()
class RandomRecommendedIllustHandler(AbstractHandler):
service = context.require(Service)
postman = context.require(Postman)
@classmethod
def type(cls) -> str:
return "random_recommended_illust"
@classmethod
def enabled(cls) -> bool:
return cls.conf.... | @context.export_singleton()
class RandomRecommendedIllustHandler(AbstractHandler):
| service = context.require(Service)
postman = context.require(Postman)
@classmethod
def type(cls) -> str:
return "random_recommended_illust"
@classmethod
def enabled(cls) -> bool:
return cls.conf.pixiv_random_recommended_illust_query_enabled
def parse_command_args(self, com... | import typing
from nonebot.adapters.onebot.v11 import Bot
from nonebot.adapters.onebot.v11.event import MessageEvent
from ..postman import Postman
from ..controller import Service
from .pkg_context import context
from .abstract_handler import AbstractHandler
from .utils import fill_id
@context.export_singleton()
clas... | 78 | 88 | 295 | 15 | 62 | ssttkkl/nonebot-plugin-pixiv | handler/random_recommended_illust_handler.py | Python | RandomRecommendedIllustHandler | RandomRecommendedIllustHandler | 13 | 48 | 13 | 14 | 75d2784cac57c19cd7bc8a92f1ae3a06ba590afc | bigcode/the-stack | train |
a1a248256192dc9e054817ca | train | class | class Updatable(Resource):
"""Generic Updatable class.
Used by resources that can be updated.
"""
@classmethod
def _update(cls, id: str, **data) -> Resource:
"""Update an specific resource with new data.
Performs a PUT request with the updated data.
Args:
id:... | class Updatable(Resource):
| """Generic Updatable class.
Used by resources that can be updated.
"""
@classmethod
def _update(cls, id: str, **data) -> Resource:
"""Update an specific resource with new data.
Performs a PUT request with the updated data.
Args:
id: The ID of the resource.
... | Create a resource
Performs a POST request with the data.
Args:
data (dict): Data from the resource to create.
Returns:
Resource: The created resource.
"""
response = client.post(cls._resource, data)
return cls._from_dict(response)
class Updatab... | 64 | 64 | 111 | 5 | 59 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Updatable | Updatable | 160 | 181 | 160 | 160 | 7b84c48ffc7e23a6d369c8060bb431e41a0ca08a | bigcode/the-stack | train |
89ff8817c4f6cc57c17a79b3 | train | class | class Downloadable(Resource):
"""Generic Downloadable class.
Used by resources that can be downloaded as a file.
"""
@classmethod
def download(cls, id: str, file_type: FileType) -> bytes:
"""Download a file from resource.
Performs a GET request to download a file given a
... | class Downloadable(Resource):
| """Generic Downloadable class.
Used by resources that can be downloaded as a file.
"""
@classmethod
def download(cls, id: str, file_type: FileType) -> bytes:
"""Download a file from resource.
Performs a GET request to download a file given a
resource ID.
Args:
... | data to be sure its the latest. It
performs a GET request on the resource.
Returns:
Resource: The refreshed resource.
"""
new = self.retrieve(self.id)
for attr, value in new.__dict__.items():
setattr(self, attr, value)
class Downloadable(Resource):
| 64 | 64 | 139 | 5 | 59 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Downloadable | Downloadable | 108 | 133 | 108 | 108 | c3dfd3cce02674bf1181bbd5aa65a84a1cc0f2f6 | bigcode/the-stack | train |
50eb5ebdff0b23ed394ee39c | train | class | class Deletable(Resource):
"""Generic Deletable class.
Used by resources that can be deleted.
"""
@classmethod
def _delete(cls, id: str) -> Resource:
"""Delete an specific resource.
Performs a DELETE request on the ID.
Args:
id: The ID of the resource to dele... | class Deletable(Resource):
| """Generic Deletable class.
Used by resources that can be deleted.
"""
@classmethod
def _delete(cls, id: str) -> Resource:
"""Delete an specific resource.
Performs a DELETE request on the ID.
Args:
id: The ID of the resource to delete.
Returns:
... | Performs a PUT request with the updated data.
Args:
id: The ID of the resource.
Returns:
Resource: The updated resource.
"""
response = client.put(f'/{cls._resource}/{id}', data)
return cls._from_dict(response)
class Deletable(Resource):
| 64 | 64 | 106 | 6 | 58 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Deletable | Deletable | 184 | 205 | 184 | 184 | 7578d4d612728103a0e8f4b7d213358ff960134b | bigcode/the-stack | train |
62bf8d6311aebb66596ba49d | train | class | class Creatable(Resource):
"""Generic Creatable class.
Used by resources that can be created.
"""
@classmethod
def _create(cls, **data) -> Resource:
"""Create a resource
Performs a POST request with the data.
Args:
data (dict): Data from the resource to creat... | class Creatable(Resource):
| """Generic Creatable class.
Used by resources that can be created.
"""
@classmethod
def _create(cls, **data) -> Resource:
"""Create a resource
Performs a POST request with the data.
Args:
data (dict): Data from the resource to create.
Returns:
... | of the resource.
file_type: Type of the file to be downloaded.
(zip, pdf or xml).
Returns:
bytes: Bytes of the file.
"""
return client.download_request(
f'/{cls._resource}/{id}/{file_type.value}'
)
class Creatable(Resource):
| 64 | 64 | 100 | 5 | 59 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Creatable | Creatable | 136 | 157 | 136 | 136 | 026134987aaa7431d75e359face8901b0a1c9ca3 | bigcode/the-stack | train |
c4004e12b6eb4b44ec2e88f6 | train | class | @dataclass
class Queryable(Resource):
"""Generic Queryable class.
Used by resources that can be queried in lists. Refer to this
class to see the query actions that can be performed on a
resource.
Attributes:
_query_params: A class with the parameters that
can be queried.
""... | @dataclass
class Queryable(Resource):
| """Generic Queryable class.
Used by resources that can be queried in lists. Refer to this
class to see the query actions that can be performed on a
resource.
Attributes:
_query_params: A class with the parameters that
can be queried.
"""
_query_params: ClassVar = BaseQ... | datable class.
Used by resources that can be updated.
"""
@classmethod
def _update(cls, id: str, **data) -> Resource:
"""Update an specific resource with new data.
Performs a PUT request with the updated data.
Args:
id: The ID of the resource.
Returns:
... | 216 | 216 | 720 | 8 | 208 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Queryable | Queryable | 208 | 315 | 208 | 209 | 6565c99c5c58305ae2ffb2aa293baf664bcab04c | bigcode/the-stack | train |
1da92630f59f18e49348ddc9 | train | class | @dataclass
class Resource:
"""Generic resource from Facturapi.
Generic Resource class used by Facturapi resources.
Attributes:
_resource (ClassVar[str]): Name of the resource the
class corresponds to.
id (str): ID of the resource.
"""
_resource: ClassVar[str]
_rel... | @dataclass
class Resource:
| """Generic resource from Facturapi.
Generic Resource class used by Facturapi resources.
Attributes:
_resource (ClassVar[str]): Name of the resource the
class corresponds to.
id (str): ID of the resource.
"""
_resource: ClassVar[str]
_relations: ClassVar[List[str]]... | can inherit behaviour from these classes to
perform requests and actions to the API.
"""
from dataclasses import asdict, fields
from typing import Any, ClassVar, Dict, Generator, List, Optional
from urllib.parse import urlencode
from pydantic.dataclasses import dataclass
from ..http import client
from ..types impor... | 102 | 102 | 340 | 6 | 95 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Resource | Resource | 20 | 66 | 20 | 21 | 4aa145da7dac150b6263a694d63398148633b47f | bigcode/the-stack | train |
cde18741c19e89c9d048fe12 | train | class | class Retrievable(Resource):
"""Generic Retrievable class.
Used by resources that can be retrieved, i.e: resources that can
be retrieved by a GET request to its ID.
"""
@classmethod
def retrieve(cls, id: str) -> Resource:
"""Retrieve a resource given its ID
Performs a GET req... | class Retrievable(Resource):
| """Generic Retrievable class.
Used by resources that can be retrieved, i.e: resources that can
be retrieved by a GET request to its ID.
"""
@classmethod
def retrieve(cls, id: str) -> Resource:
"""Retrieve a resource given its ID
Performs a GET request with the ID.
Ar... | obj_dict[f'{f}_uri'] = f'{f}s/{id_}'
obj_dict[f'{f}_info'] = obj_dict[f]
del obj_dict[f]
def to_dict(self) -> Dict:
return asdict(self, dict_factory=SanitizedDict)
class Retrievable(Resource):
| 64 | 64 | 195 | 5 | 59 | cuenca-mx/facturapi-python | facturapi/resources/base.py | Python | Retrievable | Retrievable | 69 | 105 | 69 | 69 | 880215e7a1158556c968b7a48cda0e8900177494 | bigcode/the-stack | train |
a2660b0e280fc8389a6c0c4d | train | function | def potential(element_symbol,functional):
"""
:param element_symbol: string, symbol of the element
:param functional: string, functional name
:return: string, GTH potential name to be used in the simulation
"""
return "GTH-"+functional
| def potential(element_symbol,functional):
| """
:param element_symbol: string, symbol of the element
:param functional: string, functional name
:return: string, GTH potential name to be used in the simulation
"""
return "GTH-"+functional
| def potential(element_symbol,functional):
| 7 | 64 | 60 | 7 | 0 | ramanishsingh/mosdef_cp2kmcpy | mosdef_cp2kmcpy/utilities/potential_setter.py | Python | potential | potential | 1 | 8 | 1 | 1 | 4034b982091ed1953ef85e15224d27efda5bae33 | bigcode/the-stack | train |
2ee56a3497436c1ee605a955 | train | class | class ActorModel(parl.Model):
def __init__(self, act_dim):
hid1_size = 64
hid2_size = 64
self.fc1 = layers.fc(
size=hid1_size,
act='relu',
param_attr=fluid.initializer.Normal(loc=0.0, scale=0.1))
self.fc2 = layers.fc(
size=hid2_size,
... | class ActorModel(parl.Model):
| def __init__(self, act_dim):
hid1_size = 64
hid2_size = 64
self.fc1 = layers.fc(
size=hid1_size,
act='relu',
param_attr=fluid.initializer.Normal(loc=0.0, scale=0.1))
self.fc2 = layers.fc(
size=hid2_size,
act='relu',
... | return self.actor_model.policy(obs)
def value(self, obs, act):
return self.critic_model.value(obs, act)
def get_actor_params(self):
return self.actor_model.parameters()
def get_critic_params(self):
return self.critic_model.parameters()
class ActorModel(parl.Model):
| 64 | 64 | 197 | 7 | 57 | starinsun/multiagent-particle-envs | model.py | Python | ActorModel | ActorModel | 24 | 47 | 24 | 24 | aaabf29c23bd217678a0568196624f3a7abdd0b2 | bigcode/the-stack | train |
8f0520561a50904ac7041a7e | train | class | class CriticModel(parl.Model):
def __init__(self):
hid1_size = 64
hid2_size = 64
self.fc1 = layers.fc(
size=hid1_size,
act='relu',
param_attr=fluid.initializer.Normal(loc=0.0, scale=0.1))
self.fc2 = layers.fc(
size=hid2_size,
... | class CriticModel(parl.Model):
| def __init__(self):
hid1_size = 64
hid2_size = 64
self.fc1 = layers.fc(
size=hid1_size,
act='relu',
param_attr=fluid.initializer.Normal(loc=0.0, scale=0.1))
self.fc2 = layers.fc(
size=hid2_size,
act='relu',
para... | =0.0, scale=0.1))
def policy(self, obs):
hid1 = self.fc1(obs)
hid2 = self.fc2(hid1)
means = self.fc3(hid2)
means = means
return means
class CriticModel(parl.Model):
| 65 | 65 | 218 | 8 | 56 | starinsun/multiagent-particle-envs | model.py | Python | CriticModel | CriticModel | 50 | 74 | 50 | 50 | a505da96d4d7c4b545af959b0d705d65746e7ef1 | bigcode/the-stack | train |
20457bac92fa478f7f40114d | train | class | class MAModel(parl.Model):
def __init__(self, act_dim):
self.actor_model = ActorModel(act_dim)
self.critic_model = CriticModel()
def policy(self, obs):
return self.actor_model.policy(obs)
def value(self, obs, act):
return self.critic_model.value(obs, act)
def get_actor... | class MAModel(parl.Model):
| def __init__(self, act_dim):
self.actor_model = ActorModel(act_dim)
self.critic_model = CriticModel()
def policy(self, obs):
return self.actor_model.policy(obs)
def value(self, obs, act):
return self.critic_model.value(obs, act)
def get_actor_params(self):
retu... | import paddle.fluid as fluid
import parl
from parl import layers
class MAModel(parl.Model):
| 23 | 64 | 103 | 8 | 14 | starinsun/multiagent-particle-envs | model.py | Python | MAModel | MAModel | 6 | 21 | 6 | 6 | 35bb5c22fa220c81b8f848b847f585e6d5672621 | bigcode/the-stack | train |
e5b5b6ab6ca380ced3b0f03e | train | function | def main(config, out_file):
logger = config.get_logger("test")
# text_encoder
if "text_encoder" in config and config["text_encoder"]["use_bpe"]:
text_encoder = CTCCharTextEncoder.from_bpe()
else:
text_encoder = CTCCharTextEncoder.get_simple_alphabet()
# setup data_loader instances
... | def main(config, out_file):
| logger = config.get_logger("test")
# text_encoder
if "text_encoder" in config and config["text_encoder"]["use_bpe"]:
text_encoder = CTCCharTextEncoder.from_bpe()
else:
text_encoder = CTCCharTextEncoder.get_simple_alphabet()
# setup data_loader instances
dataloaders = get_dataloa... | import argparse
import json
import os
from pathlib import Path
import torch
from tqdm import tqdm
import hw_asr.model as module_model
from hw_asr.datasets.utils import get_dataloaders
from hw_asr.text_encoder.ctc_char_text_encoder import CTCCharTextEncoder
from hw_asr.trainer import Trainer
from hw_asr.utils import R... | 117 | 151 | 506 | 7 | 110 | alexdrydew/asr_project_template | test.py | Python | main | main | 19 | 75 | 19 | 19 | 78eab9c76f5e2d88b4c0c7bba783ec8919eba279 | bigcode/the-stack | train |
d58b789e248683da10d349b4 | train | function | def check_long_definition_to_table(category, columns):
"""
Verifies that the included long table definitions actually
construct valid tables with SQLAlchemy.
"""
assert False, 'Unable to generate SQLAlchemy table with columns in LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
| def check_long_definition_to_table(category, columns):
| """
Verifies that the included long table definitions actually
construct valid tables with SQLAlchemy.
"""
assert False, 'Unable to generate SQLAlchemy table with columns in LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
| import sqlalchemy
import pyhcup
from pyhcup.config import LONG_TABLE_DEFINITIONS
def test_long_definitions_to_tables_generator():
for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_definition_to_table, category, columns
def check_long_definition_to_table(category, columns):
| 64 | 64 | 61 | 10 | 53 | jburke5/pyhcup | pyhcup/tests/test_long_table_definitions.py | Python | check_long_definition_to_table | check_long_definition_to_table | 12 | 17 | 12 | 12 | 8ac4743aae2917a1178ff6d4af341086d20cae4c | bigcode/the-stack | train |
f635465535b29d7086bbc073 | train | function | def test_long_definitions_to_tables_generator():
for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_definition_to_table, category, columns
| def test_long_definitions_to_tables_generator():
| for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_definition_to_table, category, columns
| import unittest
import sqlalchemy
import pyhcup
from pyhcup.config import LONG_TABLE_DEFINITIONS
def test_long_definitions_to_tables_generator():
| 32 | 64 | 34 | 9 | 22 | jburke5/pyhcup | pyhcup/tests/test_long_table_definitions.py | Python | test_long_definitions_to_tables_generator | test_long_definitions_to_tables_generator | 8 | 10 | 8 | 8 | ffbf71c6d1b3666c9589c97275c798da2c4e376a | bigcode/the-stack | train |
9efb646917284b48966e1b5f | train | function | def test_long_tables_match_definitions_generator():
for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_table_matches_definition, category, columns
| def test_long_tables_match_definitions_generator():
| for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_table_matches_definition, category, columns
| (category, columns):
"""
Verifies that the included long table definitions actually
construct valid tables with SQLAlchemy.
"""
assert False, 'Unable to generate SQLAlchemy table with columns in LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
def test_long_tables_match_definitions_generator():
| 64 | 64 | 34 | 9 | 55 | jburke5/pyhcup | pyhcup/tests/test_long_table_definitions.py | Python | test_long_tables_match_definitions_generator | test_long_tables_match_definitions_generator | 20 | 22 | 20 | 20 | ac935092c4d7926c91005aa783265f8f8527818a | bigcode/the-stack | train |
4f8d9b6c6a23ad203daa14e0 | train | function | def check_long_table_matches_definition(category, columns):
"""
Verifies that the tables generated using included long table
definitions match the columns described therein.
"""
assert False, 'Generated table does not match cols provided by LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
| def check_long_table_matches_definition(category, columns):
| """
Verifies that the tables generated using included long table
definitions match the columns described therein.
"""
assert False, 'Generated table does not match cols provided by LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
| SQLAlchemy table with columns in LONG_TABLE_DEFINITIONS[{k}]'.format(k=category)
def test_long_tables_match_definitions_generator():
for category, columns in LONG_TABLE_DEFINITIONS.iteritems():
yield check_long_table_matches_definition, category, columns
def check_long_table_matches_definition(category, ... | 64 | 64 | 61 | 10 | 53 | jburke5/pyhcup | pyhcup/tests/test_long_table_definitions.py | Python | check_long_table_matches_definition | check_long_table_matches_definition | 24 | 29 | 24 | 24 | 3b520ae04d3fcc30a298fe7cfbcdf17d3c08a17c | bigcode/the-stack | train |
5a7a414a456d1fff010657b3 | train | class | class BulkCreateWithManyToManyField(TestCase):
def setUp(self):
self.data = [
BulkCreateManyToManyModel(name="Object 1"),
BulkCreateManyToManyModel(name="Object 2"),
BulkCreateManyToManyModel(name="Object 3"),
BulkCreateManyToManyModel(name="Object 4"),
... | class BulkCreateWithManyToManyField(TestCase):
| def setUp(self):
self.data = [
BulkCreateManyToManyModel(name="Object 1"),
BulkCreateManyToManyModel(name="Object 2"),
BulkCreateManyToManyModel(name="Object 3"),
BulkCreateManyToManyModel(name="Object 4"),
BulkCreateManyToManyModel(name="Object 5"... | _create_with_history(objects, model)
self.assertEqual(result, objects)
hist_manager_mock().bulk_history_create.assert_called_with(
objects,
batch_size=None,
default_user=None,
default_change_reason=None,
default_date=None,
)
class BulkC... | 64 | 64 | 130 | 11 | 53 | jordonwii/django-simple-history | simple_history/tests/tests/test_utils.py | Python | BulkCreateWithManyToManyField | BulkCreateWithManyToManyField | 197 | 210 | 197 | 197 | 61aa49ef1b8b9cae7f15a8e5bd8e37adefd7420a | bigcode/the-stack | train |
f83264332601342f3434445b | train | class | class BulkCreateWithHistoryTransactionTestCase(TransactionTestCase):
def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.... | class BulkCreateWithHistoryTransactionTestCase(TransactionTestCase):
| def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Poll(id=4, question="Question 4", pub_date=timezo... | cluded_fields(self):
bulk_create_with_history(self.data_with_excluded_fields, PollWithExcludeFields)
self.assertEqual(Poll.objects.count(), 0)
self.assertEqual(Poll.history.count(), 0)
self.assertEqual(PollWithExcludeFields.objects.count(), 5)
self.assertEqual(PollWithExcludeFi... | 171 | 171 | 572 | 12 | 159 | jordonwii/django-simple-history | simple_history/tests/tests/test_utils.py | Python | BulkCreateWithHistoryTransactionTestCase | BulkCreateWithHistoryTransactionTestCase | 127 | 194 | 127 | 127 | 7e667c7ef19e6d231963e892adabb6d55c4ca090 | bigcode/the-stack | train |
462097fe506add780add6eff | train | class | @skipIf(django.VERSION < (2, 2,), reason="bulk_update does not exist before 2.2")
class BulkUpdateWithHistoryTestCase(TestCase):
def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
... | @skipIf(django.VERSION < (2, 2,), reason="bulk_update does not exist before 2.2")
class BulkUpdateWithHistoryTestCase(TestCase):
| def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Poll(id=4, question="Question 4", pub_date=timezo... | bulk_create_with_history(objects, model)
self.assertEqual(result, objects)
hist_manager_mock().bulk_history_create.assert_called_with(
objects,
batch_size=None,
default_user=None,
default_change_reason=None,
default_date=None,
)
clas... | 220 | 220 | 734 | 36 | 184 | jordonwii/django-simple-history | simple_history/tests/tests/test_utils.py | Python | BulkUpdateWithHistoryTestCase | BulkUpdateWithHistoryTestCase | 213 | 311 | 213 | 214 | d53f4995ae1c26c18290ae23d70c14b688a1c96e | bigcode/the-stack | train |
ed8961af2606b73dcc3ea3bc | train | class | class BulkCreateWithHistoryTestCase(TestCase):
def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Po... | class BulkCreateWithHistoryTestCase(TestCase):
| def setUp(self):
self.data = [
Poll(id=1, question="Question 1", pub_date=timezone.now()),
Poll(id=2, question="Question 2", pub_date=timezone.now()),
Poll(id=3, question="Question 3", pub_date=timezone.now()),
Poll(id=4, question="Question 4", pub_date=timezo... | from unittest import skipIf
from datetime import datetime
import django
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.test import TestCase, TransactionTestCase
from django.utils import timezone
from mock import Mock, patch
from simple_history.exceptions import NotHist... | 138 | 248 | 828 | 10 | 128 | jordonwii/django-simple-history | simple_history/tests/tests/test_utils.py | Python | BulkCreateWithHistoryTestCase | BulkCreateWithHistoryTestCase | 29 | 124 | 29 | 29 | 00d23c6df59707755c223e32310218bc69d23669 | bigcode/the-stack | train |
a1c62d003467e789353d3d8e | train | class | class UpdateChangeReasonTestCase(TestCase):
def test_update_change_reason_with_excluded_fields(self):
poll = PollWithExcludeFields(
question="what's up?", pub_date=timezone.now(), place="The Pub"
)
poll.save()
update_change_reason(poll, "Test change reason.")
most... | class UpdateChangeReasonTestCase(TestCase):
| def test_update_change_reason_with_excluded_fields(self):
poll = PollWithExcludeFields(
question="what's up?", pub_date=timezone.now(), place="The Pub"
)
poll.save()
update_change_reason(poll, "Test change reason.")
most_recent = poll.history.order_by("-history_da... | _history_with_batch_size(self):
bulk_update_with_history(self.data, Poll, fields=["question"], batch_size=2)
self.assertEqual(Poll.objects.count(), 5)
self.assertEqual(Poll.history.filter(history_type="~").count(), 5)
class UpdateChangeReasonTestCase(TestCase):
| 64 | 64 | 95 | 9 | 55 | jordonwii/django-simple-history | simple_history/tests/tests/test_utils.py | Python | UpdateChangeReasonTestCase | UpdateChangeReasonTestCase | 314 | 322 | 314 | 314 | 62dee7d052164db1e3382be35ec5665d2de7bf06 | bigcode/the-stack | train |
3fe0488624af8892f6b4caf0 | train | class | class UCX(Comm):
"""Comm object using UCP.
Parameters
----------
ep : ucp.Endpoint
The UCP endpoint.
address : str
The address, prefixed with `ucx://` to use.
deserialize : bool, default True
Whether to deserialize data in :meth:`distributed.protocol.loads`
Notes
... | class UCX(Comm):
| """Comm object using UCP.
Parameters
----------
ep : ucp.Endpoint
The UCP endpoint.
address : str
The address, prefixed with `ucx://` to use.
deserialize : bool, default True
Whether to deserialize data in :meth:`distributed.protocol.loads`
Notes
-----
The r... | a
device_array = numba_device_array
except ImportError:
def device_array(n):
raise RuntimeError(
"In order to send/recv CUDA arrays, Numba or RMM is required"
)
pool_size_str = dask.config.get("rmm.pool-size")
if pool_size_s... | 256 | 256 | 1,590 | 6 | 249 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | UCX | UCX | 134 | 337 | 134 | 134 | e0c4e810e4a5b9bdf3d2420663dea09627b8ca3d | bigcode/the-stack | train |
33dd0282b727d33b18256a86 | train | class | class UCXConnector(Connector):
prefix = "ucx://"
comm_class = UCX
encrypted = False
async def connect(self, address: str, deserialize=True, **connection_args) -> UCX:
logger.debug("UCXConnector.connect: %s", address)
ip, port = parse_host_port(address)
init_once()
try:
... | class UCXConnector(Connector):
| prefix = "ucx://"
comm_class = UCX
encrypted = False
async def connect(self, address: str, deserialize=True, **connection_args) -> UCX:
logger.debug("UCXConnector.connect: %s", address)
ip, port = parse_host_port(address)
init_once()
try:
ep = await ucx_creat... | ._ep = None
@property
def ep(self):
if self._ep is not None:
return self._ep
else:
raise CommClosedError("UCX Endpoint is closed")
def closed(self):
return self._ep is None
class UCXConnector(Connector):
| 64 | 64 | 173 | 7 | 56 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | UCXConnector | UCXConnector | 340 | 361 | 340 | 340 | 181cbb41354d61d566e2f629f3b35df605d27216 | bigcode/the-stack | train |
16ec3555cdf9b15f8bffa72b | train | function | def synchronize_stream(stream=0):
import numba.cuda
ctx = numba.cuda.current_context()
cu_stream = numba.cuda.driver.drvapi.cu_stream(stream)
stream = numba.cuda.driver.Stream(ctx, cu_stream, None)
stream.synchronize()
| def synchronize_stream(stream=0):
| import numba.cuda
ctx = numba.cuda.current_context()
cu_stream = numba.cuda.driver.drvapi.cu_stream(stream)
stream = numba.cuda.driver.Stream(ctx, cu_stream, None)
stream.synchronize()
| is also
# required to ensure Dask configuration gets propagated to UCX, which needs
# variables to be set before being imported.
ucp = None
host_array = None
device_array = None
ucx_create_endpoint = None
ucx_create_listener = None
def synchronize_stream(stream=0):
| 64 | 64 | 58 | 7 | 56 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | synchronize_stream | synchronize_stream | 34 | 40 | 34 | 34 | 0394dfefadf111ee5f2ee864dc7d0dca516a369c | bigcode/the-stack | train |
ac73e562bfc17e673bf3cf02 | train | function | def init_once():
global ucp, host_array, device_array, ucx_create_endpoint, ucx_create_listener
if ucp is not None:
return
# remove/process dask.ucx flags for valid ucx options
ucx_config = _scrub_ucx_config()
# We ensure the CUDA context is created before initializing UCX. This can't
... | def init_once():
| global ucp, host_array, device_array, ucx_create_endpoint, ucx_create_listener
if ucp is not None:
return
# remove/process dask.ucx flags for valid ucx options
ucx_config = _scrub_ucx_config()
# We ensure the CUDA context is created before initializing UCX. This can't
# be safely handl... | _host_port
from .core import Comm, CommClosedError, Connector, Listener
from .registry import Backend, backends
from .utils import ensure_concrete_host, from_frames, to_frames
logger = logging.getLogger(__name__)
# In order to avoid double init when forking/spawning new processes (multiprocess),
# we make sure only ... | 203 | 203 | 677 | 4 | 199 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | init_once | init_once | 43 | 131 | 43 | 43 | db5d6e08ba77ba6d0e4ab67d0659cff00aabc258 | bigcode/the-stack | train |
00a6399d5903d75038d7dba3 | train | function | def _scrub_ucx_config():
"""Function to scrub dask config options for valid UCX config options"""
# configuration of UCX can happen in two ways:
# 1) high level on/off flags which correspond to UCX configuration
# 2) explicitly defined UCX configuration flags
# import does not initialize ucp -- th... | def _scrub_ucx_config():
| """Function to scrub dask config options for valid UCX config options"""
# configuration of UCX can happen in two ways:
# 1) high level on/off flags which correspond to UCX configuration
# 2) explicitly defined UCX configuration flags
# import does not initialize ucp -- this will occur outside thi... | deserialize, **connection_args)
# Address handling
# This duplicates BaseTCPBackend
def get_address_host(self, loc):
return parse_host_port(loc)[0]
def get_address_host_port(self, loc):
return parse_host_port(loc)
def resolve_address(self, loc):
host, port = parse_host_p... | 168 | 168 | 563 | 8 | 160 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | _scrub_ucx_config | _scrub_ucx_config | 474 | 530 | 474 | 474 | 9272a3bf30ba08adc4f0e835e7a5cd03d0fd76f4 | bigcode/the-stack | train |
f75d824abdf6019aa2578ba3 | train | class | class UCXListener(Listener):
prefix = UCXConnector.prefix
comm_class = UCXConnector.comm_class
encrypted = UCXConnector.encrypted
def __init__(
self,
address: str,
comm_handler: None,
deserialize=False,
allow_offload=True,
**connection_args
):
... | class UCXListener(Listener):
| prefix = UCXConnector.prefix
comm_class = UCXConnector.comm_class
encrypted = UCXConnector.encrypted
def __init__(
self,
address: str,
comm_handler: None,
deserialize=False,
allow_offload=True,
**connection_args
):
if not address.startswith("u... | , address: str, deserialize=True, **connection_args) -> UCX:
logger.debug("UCXConnector.connect: %s", address)
ip, port = parse_host_port(address)
init_once()
try:
ep = await ucx_create_endpoint(ip, port)
except (
ucp.exceptions.UCXCloseError,
... | 148 | 148 | 494 | 7 | 141 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | UCXListener | UCXListener | 364 | 436 | 364 | 364 | 1030ecba417d14f8f93fcc31e59b10a2146671df | bigcode/the-stack | train |
db87ff306321eaaf48b222d7 | train | class | class UCXBackend(Backend):
# I / O
def get_connector(self):
return UCXConnector()
def get_listener(self, loc, handle_comm, deserialize, **connection_args):
return UCXListener(loc, handle_comm, deserialize, **connection_args)
# Address handling
# This duplicates BaseTCPBackend
... | class UCXBackend(Backend):
# I / O
| def get_connector(self):
return UCXConnector()
def get_listener(self, loc, handle_comm, deserialize, **connection_args):
return UCXListener(loc, handle_comm, deserialize, **connection_args)
# Address handling
# This duplicates BaseTCPBackend
def get_address_host(self, loc):
... | _port(host, port)
@property
def bound_address(self):
# TODO: Does this become part of the base API? Kinda hazy, since
# we exclude in for inproc.
return self.get_host_port()
class UCXBackend(Backend):
# I / O
| 64 | 64 | 201 | 13 | 51 | gerrymanoim/distributed | distributed/comm/ucx.py | Python | UCXBackend | UCXBackend | 439 | 468 | 439 | 441 | 1a8382d3df31d7ff110e68b020afb2ce2aaebdf5 | bigcode/the-stack | train |
d5e2dd21bca0f1d2c601dc41 | train | class | class TestAutomatonPlanning(unittest.TestCase):
def setUp(self) -> None:
spatial = Spatial()
self.planner = AutomatonPlanner()
ex = "( (G(!(blue touch red))) & (F(blue touch green)) )"
ex_tree = spatial.parse(ex)
self.planner.tree_to_dfa(ex_tree)
def test_automaton_cre... | class TestAutomatonPlanning(unittest.TestCase):
| def setUp(self) -> None:
spatial = Spatial()
self.planner = AutomatonPlanner()
ex = "( (G(!(blue touch red))) & (F(blue touch green)) )"
ex_tree = spatial.parse(ex)
self.planner.tree_to_dfa(ex_tree)
def test_automaton_creation(self):
self.planner.reset_state()
... | import unittest
from spatial.automaton_planning import AutomatonPlanner
from spatial.logic import Spatial
class TestAutomatonPlanning(unittest.TestCase):
| 30 | 152 | 508 | 9 | 20 | KTH-RPL-Planiacs/SpaTiaL | tests/test_automaton.py | Python | TestAutomatonPlanning | TestAutomatonPlanning | 7 | 56 | 7 | 8 | e4b1a28cd368330e4e8b1aaf64f3394df4c281d6 | bigcode/the-stack | train |
5183dcde5bcaaa2e0cba55e2 | train | class | class TestTokenizationApi(unittest.TestCase):
""" TokenizationApi unit test stubs """
def setUp(self):
self.api = billforward.apis.tokenization_api.TokenizationApi()
def tearDown(self):
pass
def test_auth_capture(self):
"""
Test case for auth_capture
[Note: th... | class TestTokenizationApi(unittest.TestCase):
| """ TokenizationApi unit test stubs """
def setUp(self):
self.api = billforward.apis.tokenization_api.TokenizationApi()
def tearDown(self):
pass
def test_auth_capture(self):
"""
Test case for auth_capture
[Note: this API can be invoked more simply by our clien... | : https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... | 180 | 180 | 601 | 9 | 170 | billforward/bf-python | test/test_tokenization_api.py | Python | TestTokenizationApi | TestTokenizationApi | 35 | 90 | 35 | 35 | 22a652b4613975984764d04d3952bbb377a8287e | bigcode/the-stack | train |
6466a36bc66ec5075a3bcccb | train | class | class Migration(migrations.Migration):
dependencies = [
('crash', '0018_auto_20150707_0822'),
('omaha', '0021_grant_permissions_to_public_group'),
]
operations = [
migrations.RunPython(grant_permissions, reverse_code=migrations.RunPython.noop),
]
| class Migration(migrations.Migration):
| dependencies = [
('crash', '0018_auto_20150707_0822'),
('omaha', '0021_grant_permissions_to_public_group'),
]
operations = [
migrations.RunPython(grant_permissions, reverse_code=migrations.RunPython.noop),
]
| , SELECT ON SEQUENCE crash_crash_id_seq '
'TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
cursor.execute('GRANT USAGE, SELECT ON SEQUENCE crash_crashdescription_id_seq '
'TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
class Migration(migrations.Migration):
| 64 | 64 | 68 | 7 | 57 | fiadm/omaha-server | omaha_server/crash/migrations/0019_grant_permissions_to_public_group.py | Python | Migration | Migration | 22 | 31 | 22 | 23 | add592991f6ae0c60575f83d94698e89184e0305 | bigcode/the-stack | train |
77aab7ad9c209650b86990eb | train | function | def grant_permissions(apps, schema_editor):
cursor = connection.cursor()
cursor.execute('GRANT SELECT, INSERT, UPDATE ON TABLE crash_crash, crash_crash_id_seq, '
'crash_crashdescription, crash_crashdescription_id_seq '
'TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
cursor.e... | def grant_permissions(apps, schema_editor):
| cursor = connection.cursor()
cursor.execute('GRANT SELECT, INSERT, UPDATE ON TABLE crash_crash, crash_crash_id_seq, '
'crash_crashdescription, crash_crashdescription_id_seq '
'TO GROUP %s;' % settings.DB_PUBLIC_ROLE)
cursor.execute('GRANT SELECT ON TABLE crash_symbols,... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations, connection
def grant_permissions(apps, schema_editor):
| 41 | 64 | 163 | 9 | 31 | fiadm/omaha-server | omaha_server/crash/migrations/0019_grant_permissions_to_public_group.py | Python | grant_permissions | grant_permissions | 7 | 19 | 7 | 7 | a11f0b2c8dc40979f7ae895a73bbe5389dc50709 | bigcode/the-stack | train |
e68a0a8b1b23c0800004fae3 | train | class | class ElasticUtil(object):
hosts = []
index_prefix = ''
max_result_window = 10000
known_indexes = []
def __init__(self, **kwargs):
pkg_resources.require('elasticsearch')
from elasticsearch import Elasticsearch
self.session = Elasticsearch(hosts=self.hosts, timeout=50, **kwa... | class ElasticUtil(object):
| hosts = []
index_prefix = ''
max_result_window = 10000
known_indexes = []
def __init__(self, **kwargs):
pkg_resources.require('elasticsearch')
from elasticsearch import Elasticsearch
self.session = Elasticsearch(hosts=self.hosts, timeout=50, **kwargs)
self.build_ind... | import pkg_resources
from django.utils.translation import gettext as _
from rest_framework.exceptions import ValidationError
from drf_util.utils import gt
class ElasticUtil(object):
| 33 | 256 | 1,209 | 5 | 27 | elasmd/drf-util | drf_util/elastic.py | Python | ElasticUtil | ElasticUtil | 8 | 169 | 8 | 8 | 7705417b68caddfbb91aad17e0ab2578e1e34249 | bigcode/the-stack | train |
cd8d58f8327d78368d8d3aab | train | class | class MagnetType11(MagnetPolar):
"""single magnet with polar shape"""
VERSION = 1
IS_FLAT_BOT = 0
IS_FLAT_TOP = 0
# Check ImportError to remove unnecessary dependencies in unused method
# cf Methods.Machine.MagnetType11._comp_point_coordinate
if isinstance(_comp_point_coordinate, ImportErr... | class MagnetType11(MagnetPolar):
| """single magnet with polar shape"""
VERSION = 1
IS_FLAT_BOT = 0
IS_FLAT_TOP = 0
# Check ImportError to remove unnecessary dependencies in unused method
# cf Methods.Machine.MagnetType11._comp_point_coordinate
if isinstance(_comp_point_coordinate, ImportError):
_comp_point_coordina... | coding: utf-8 -*-
"""File generated according to Generator/ClassesRef/Machine/MagnetType11.csv
WARNING! All changes made in this file will be lost!
"""
from os import linesep
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import ... | 256 | 256 | 1,445 | 8 | 247 | helene-t/pyleecan | pyleecan/Classes/MagnetType11.py | Python | MagnetType11 | MagnetType11 | 42 | 217 | 42 | 42 | f477a0687fe870f1cf86a4824b898df1af9604bd | bigcode/the-stack | train |
bd1c215f2c9a1f9987973e35 | train | function | def find_includes(basedirs, source, log=None):
"""Finds all thrift files included by the given thrift source.
:basedirs: A set of thrift source file base directories to look for includes in.
:source: The thrift source file to scan for includes.
:log: An optional logger
"""
all_basedirs = [os.p... | def find_includes(basedirs, source, log=None):
| """Finds all thrift files included by the given thrift source.
:basedirs: A set of thrift source file base directories to look for includes in.
:source: The thrift source file to scan for includes.
:log: An optional logger
"""
all_basedirs = [os.path.dirname(source)]
all_basedirs.extend(ba... | see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import re
INCLUDE_PARSER = re.compile(r'^\s*include\s+"([^"]+)"\s*([\/\/|\#].*)*$')
def find_includes(basedirs, source, log=None):
| 69 | 69 | 231 | 13 | 56 | revl/pants | contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py | Python | find_includes | find_includes | 10 | 41 | 10 | 10 | e0203bf56340b6f76c56c4da64391291572e8131 | bigcode/the-stack | train |
3e73b7194658f5232709769e | train | function | def find_root_thrifts(basedirs, sources, log=None):
"""Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger.
"""
... | def find_root_thrifts(basedirs, sources, log=None):
| """Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger.
"""
root_sources = set(sources)
for source in sourc... | }")
includes.add(include)
added = True
if not added:
raise ValueError(
"{} included in {} not found in bases {}".format(
include, source, all_basedirs
)
... | 64 | 64 | 110 | 14 | 49 | revl/pants | contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py | Python | find_root_thrifts | find_root_thrifts | 44 | 55 | 44 | 44 | fa4e3d3cb34b62a1139a41a27901733e970f547a | bigcode/the-stack | train |
1e9e52c9eeb4cfad616e9ed8 | train | function | def calculate_include_paths(targets, is_thrift_target):
"""Calculates the set of import paths for the given targets.
:targets: The targets to examine.
:is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis.
:returns: Include basedirs for the target.
"""
ba... | def calculate_include_paths(targets, is_thrift_target):
| """Calculates the set of import paths for the given targets.
:targets: The targets to examine.
:is_thrift_target: A predicate to pick out thrift targets for consideration in the analysis.
:returns: Include basedirs for the target.
"""
basedirs = set()
def collect_paths(target):
b... | files to examine.
:log: An optional logger.
"""
root_sources = set(sources)
for source in sources:
root_sources.difference_update(find_includes(basedirs, source, log=log))
return root_sources
def calculate_include_paths(targets, is_thrift_target):
| 64 | 64 | 112 | 12 | 51 | revl/pants | contrib/scrooge/src/python/pants/contrib/scrooge/tasks/thrift_util.py | Python | calculate_include_paths | calculate_include_paths | 58 | 74 | 58 | 58 | 8019724e46da2b5deed64b369859b9bb54b5fa32 | bigcode/the-stack | train |
1f1315564fba6cf69298e749 | train | class | class chatBot(object):
def __init__(self, data_dir, model_dir, task_id,
OOV=False,
memory_size=250,
random_state=None,
batch_size=32,
learning_rate=0.001,
epsilon=1e-8,
max_grad_norm=40.0,
... | class chatBot(object):
| def __init__(self, data_dir, model_dir, task_id,
OOV=False,
memory_size=250,
random_state=None,
batch_size=32,
learning_rate=0.001,
epsilon=1e-8,
max_grad_norm=40.0,
evaluat... | ", 3, "Number of hops in the Memory Network.")
tf.flags.DEFINE_integer("epochs", 250, "Number of epochs to train for.")
tf.flags.DEFINE_integer("embedding_size", 20, "Embedding size for embedding matrices.")
tf.flags.DEFINE_integer("memory_size", 250, "Maximum size of memory.")
tf.flags.DEFINE_integer("task_id", 1, "ta... | 256 | 256 | 2,324 | 5 | 251 | janarthanan-rajendran/l2l-from-related-tasks | MemN2N-split-memory/single_dialog.py | Python | chatBot | chatBot | 36 | 290 | 36 | 36 | 81160631f815cb9816ff101f96de98a495013e0c | bigcode/the-stack | train |
9485da306b8c4d3108a6b24e | train | function | def test_scale():
state = {}
assert numpy.allclose(scale(data=[1, 2, 3], _state=state), [-1, 0, 1])
assert state == {"center": 2.0, "scale": 1.0, "ddof": 1}
assert numpy.allclose(scale(data=[5, 6, 7], _state=state), [3, 4, 5])
state = {}
assert numpy.allclose(
scale(data=[1, 2, 3], cent... | def test_scale():
| state = {}
assert numpy.allclose(scale(data=[1, 2, 3], _state=state), [-1, 0, 1])
assert state == {"center": 2.0, "scale": 1.0, "ddof": 1}
assert numpy.allclose(scale(data=[5, 6, 7], _state=state), [3, 4, 5])
state = {}
assert numpy.allclose(
scale(data=[1, 2, 3], center=False, _state=s... | import numpy
import pytest
import scipy.sparse as spsparse
from formulaic.errors import DataMismatchWarning
from formulaic.materializers.transforms import center, scale
def test_scale():
| 39 | 129 | 431 | 4 | 34 | fabio-rosa-ors/formulaic | tests/materializers/transforms/test_scale.py | Python | test_scale | test_scale | 9 | 42 | 9 | 9 | eca8d06f4d1b3633bf9c9ed5111f2106a477c1e3 | bigcode/the-stack | train |
d734137799fa4b4e8b5f02c0 | train | function | def test_center():
state = {}
assert numpy.allclose(center(data=[1, 2, 3], _state=state), [-1, 0, 1])
assert state == {"center": 2, "scale": None, "ddof": 1}
assert numpy.allclose(center(data=[5, 6, 7], _state=state), [3, 4, 5])
| def test_center():
| state = {}
assert numpy.allclose(center(data=[1, 2, 3], _state=state), [-1, 0, 1])
assert state == {"center": 2, "scale": None, "ddof": 1}
assert numpy.allclose(center(data=[5, 6, 7], _state=state), [3, 4, 5])
| scale(data=[1, 2, 3], center=1, scale=2, _state=state), [0, 0.5, 1]
)
assert state == {"center": 1, "scale": 2, "ddof": 1}
def test_center():
| 64 | 64 | 90 | 4 | 60 | fabio-rosa-ors/formulaic | tests/materializers/transforms/test_scale.py | Python | test_center | test_center | 45 | 49 | 45 | 45 | 7edeeb912acee078f50eb47a92926410e240ddca | bigcode/the-stack | train |
abe3f3e4ff28e51e0afc710a | train | function | def test_center_sparse():
state = {}
m = spsparse.csc_matrix([1, 2, 3]).transpose()
assert numpy.allclose(center(data=m, _state=state), [-1, 0, 1])
| def test_center_sparse():
| state = {}
m = spsparse.csc_matrix([1, 2, 3]).transpose()
assert numpy.allclose(center(data=m, _state=state), [-1, 0, 1])
| , 0, 1])
assert state == {"center": 2, "scale": None, "ddof": 1}
assert numpy.allclose(center(data=[5, 6, 7], _state=state), [3, 4, 5])
def test_center_sparse():
| 64 | 64 | 52 | 5 | 59 | fabio-rosa-ors/formulaic | tests/materializers/transforms/test_scale.py | Python | test_center_sparse | test_center_sparse | 52 | 55 | 52 | 52 | 75b8ff7a1e4b0416f1e2dc8eb4722d4f0be0f809 | bigcode/the-stack | train |
e56b519d79234fa43e23a4d1 | train | function | def test_upgrade_does_not_get_into_loop_if_reinstall_and_failed(
looper, tconf, nodeSet, validUpgrade, sdk_pool_handle, sdk_wallet_trustee, monkeypatch):
new_version = bumpedVersion(validUpgrade['version'])
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
... | def test_upgrade_does_not_get_into_loop_if_reinstall_and_failed(
looper, tconf, nodeSet, validUpgrade, sdk_pool_handle, sdk_wallet_trustee, monkeypatch):
| new_version = bumpedVersion(validUpgrade['version'])
upgr1 = deepcopy(validUpgrade)
upgr1[VERSION] = new_version
upgr1[REINSTALL] = True
clear_aq_stash(nodeSet)
# An upgrade scheduled, it should pass
sdk_ensure_upgrade_sent(looper, sdk_pool_handle, sdk_wallet_trustee, upgr1)
looper.run... | node',
'failed upgrade',
'This problem may have external reasons, check syslog for more information']
def test_upgrade_does_not_get_into_loop_if_reinstall_and_failed(
looper, tconf, nodeSet, validUpgrade, sdk_pool_handle, sdk_wallet_trustee, monkeypatch):
| 64 | 64 | 191 | 41 | 23 | Rob-S/indy-node | indy_node/test/upgrade/test_pool_upgrade_no_loop_reinstall_unsuccessful.py | Python | test_upgrade_does_not_get_into_loop_if_reinstall_and_failed | test_upgrade_does_not_get_into_loop_if_reinstall_and_failed | 17 | 38 | 17 | 18 | bf098568721016c1dbc9c615a47931935549f092 | bigcode/the-stack | train |
409cde959a57b39c776639c6 | train | class | class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
newhead = ListNode()
newhead.next = head
prev_node = newhead
while head and head.next:
firstnode = head
secondnode = head.next
prev_node.next = secondnode
firstnode.next =... | class Solution:
| def swapPairs(self, head: ListNode) -> ListNode:
newhead = ListNode()
newhead.next = head
prev_node = newhead
while head and head.next:
firstnode = head
secondnode = head.next
prev_node.next = secondnode
firstnode.next = secondnode.next... | iterative step, so the nodes are swapped on the go and attached to the previously swapped list. And in the end we get the final swapped list.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
| 64 | 64 | 103 | 3 | 60 | cccccccccccccc/Myleetcode | 24/Swap Nodes in Pairs.py | Python | Solution | Solution | 14 | 27 | 14 | 14 | 07738fe667a0f32f52517b01b01a4626ef5742a4 | bigcode/the-stack | train |
e96971a078d3bacce03be509 | train | class | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
| class ListNode:
| def __init__(self, val=0, next=None):
self.val = val
self.next = next
| next to the head of swapped pair this step would ensure the currently swapped pair is linked correctly to the end of previously swapped list.
This is an iterative step, so the nodes are swapped on the go and attached to the previously swapped list. And in the end we get the final swapped list.
"""
class ListNode:
| 64 | 64 | 30 | 4 | 60 | cccccccccccccc/Myleetcode | 24/Swap Nodes in Pairs.py | Python | ListNode | ListNode | 10 | 13 | 10 | 10 | 6d57ae6ce0c3fca23153f37d4914c293ee270856 | bigcode/the-stack | train |
b3cfa1068911b61ccb2d32f9 | train | class | class SourceState(Enum):
"""
These states are for recording the previous state from a transition action (Created, Pilot, Start, Stop) on the experiment. * `CREATED`: Result state for the 'Create' action. Experiment has been created. * `ENABLED`: Result state for the 'Pilot' a... | class SourceState(Enum):
| """
These states are for recording the previous state from a transition action (Created, Pilot, Start, Stop) on the experiment. * `CREATED`: Result state for the 'Create' action. Experiment has been created. * `ENABLED`: Result state for the 'Pilot' action. Experiment configu... | /apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
# the specific language governing permissions and limitations under the License.
#
import pprint
import re # noq... | 116 | 116 | 388 | 5 | 110 | alexa-labs/alexa-apis-for-python | ask-smapi-model/ask_smapi_model/v1/skill/experiment/source_state.py | Python | SourceState | SourceState | 28 | 67 | 28 | 28 | f2858a38ffade1784d73ee2106144df5f4966e22 | bigcode/the-stack | train |
46f32bb484bbbeb65e2971b3 | train | function | def rf_lw101(num_classes, imagenet=False, pretrained=True, **kwargs):
model = ResNetLW(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '101_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:... | def rf_lw101(num_classes, imagenet=False, pretrained=True, **kwargs):
| model = ResNetLW(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '101_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:
dataset = data_info.get(num_classes, None)
if dataset... | '50_' + dataset.lower()
key = 'rf_lw' + bname
url = models_urls[bname]
model.load_state_dict(maybe_download(key, url), strict=False)
return model
def rf_lw101(num_classes, imagenet=False, pretrained=True, **kwargs):
| 64 | 64 | 153 | 18 | 45 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | rf_lw101 | rf_lw101 | 258 | 271 | 258 | 258 | 541efa0a8f3826d7216cd4b3af90266f7d0480ff | bigcode/the-stack | train |
1a4cfdf4e60e6d5a3e0ae0bf | train | class | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = ... | class BasicBlock(nn.Module):
| expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
... | 4d8f.pth',
'152_imagenet': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}
stages_suffixes = {0 : '_conv',
1 : '_conv_relu_varout_dimred'}
class BasicBlock(nn.Module):
| 64 | 64 | 207 | 6 | 58 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | BasicBlock | BasicBlock | 70 | 99 | 70 | 70 | dbc50134bf9a62c206fe2bd8b5cf0ebe6be90aa6 | bigcode/the-stack | train |
c0c0d76fb59164bab09d6f44 | train | class | class ResNetLW(nn.Module):
def __init__(self, block, layers, num_classes=21):
self.inplanes = 64
super(ResNetLW, self).__init__()
self.do = nn.Dropout(p=0.5)
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1... | class ResNetLW(nn.Module):
| def __init__(self, block, layers, num_classes=21):
self.inplanes = 64
super(ResNetLW, self).__init__()
self.do = nn.Dropout(p=0.5)
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
... | 1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes ... | 256 | 256 | 1,311 | 7 | 248 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | ResNetLW | ResNetLW | 141 | 240 | 141 | 142 | ec703d8193a276bd953aa985c21d86ebd796d543 | bigcode/the-stack | train |
1b2855ba240bb3f410f4e079 | train | function | def rf_lw152(num_classes, imagenet=False, pretrained=True, **kwargs):
model = ResNetLW(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '152_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:... | def rf_lw152(num_classes, imagenet=False, pretrained=True, **kwargs):
| model = ResNetLW(Bottleneck, [3, 8, 36, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '152_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:
dataset = data_info.get(num_classes, None)
if dataset... | '101_' + dataset.lower()
key = 'rf_lw' + bname
url = models_urls[bname]
model.load_state_dict(maybe_download(key, url), strict=False)
return model
def rf_lw152(num_classes, imagenet=False, pretrained=True, **kwargs):
| 64 | 64 | 153 | 18 | 45 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | rf_lw152 | rf_lw152 | 273 | 286 | 273 | 273 | 632ec6f1d2aa6a71f27ab71623870513ebdbc89f | bigcode/the-stack | train |
8342a8c51d0e5d762faa80d9 | train | class | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, pla... | class Bottleneck(nn.Module):
| expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=st... | forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out... | 88 | 88 | 294 | 6 | 81 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | Bottleneck | Bottleneck | 102 | 138 | 102 | 102 | bd77cb9cba46ea8148f06a6c10edc0eba7e4fc60 | bigcode/the-stack | train |
f14a32f2456d011f1f787c30 | train | function | def rf_lw50(num_classes, imagenet=False, pretrained=True, **kwargs):
model = ResNetLW(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '50_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:
... | def rf_lw50(num_classes, imagenet=False, pretrained=True, **kwargs):
| model = ResNetLW(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, **kwargs)
if imagenet:
key = '50_imagenet'
url = models_urls[key]
model.load_state_dict(maybe_download(key, url), strict=False)
elif pretrained:
dataset = data_info.get(num_classes, None)
if dataset:
... | x1 = x1 + x2
x1 = F.relu(x1)
x1 = self.mflow_conv_g4_pool(x1)
out = self.clf_conv(x1)
return out
def rf_lw50(num_classes, imagenet=False, pretrained=True, **kwargs):
| 64 | 64 | 153 | 18 | 45 | Miguel-Jiahao-Wang/InstanceSegmentation_NeuralTransfer | semantic_segmentation/light-weight-refinenet/models/resnet.py | Python | rf_lw50 | rf_lw50 | 243 | 256 | 243 | 243 | 0c627fe4790ac55b5170eba56f54fee6c48dcff9 | bigcode/the-stack | train |
c14faf02d259522b2a046c8c | train | function | def loss_computation(logits_list, labels, losses, edges=None):
check_logits_losses(logits_list, losses)
loss_list = []
for i in range(len(logits_list)):
logits = logits_list[i]
loss_i = losses['types'][i]
coef_i = losses['coef'][i]
if loss_i.__class__.__name__ in ('BCELoss',... | def loss_computation(logits_list, labels, losses, edges=None):
| check_logits_losses(logits_list, losses)
loss_list = []
for i in range(len(logits_list)):
logits = logits_list[i]
loss_i = losses['types'][i]
coef_i = losses['coef'][i]
if loss_i.__class__.__name__ in ('BCELoss',
'FocalLoss') and loss... | _list)
len_losses = len(losses['types'])
if len_logits != len_losses:
raise RuntimeError(
'The length of logits_list should equal to the types of loss config: {} != {}.'
.format(len_logits, len_losses))
def loss_computation(logits_list, labels, losses, edges=None):
| 69 | 69 | 230 | 15 | 54 | DaoDaoer/PaddleSeg | contrib/CityscapesSOTA/scripts/train.py | Python | loss_computation | loss_computation | 36 | 57 | 36 | 36 | 205b85a1ac2dcb945c66cc8a5e49d0fa855a32df | bigcode/the-stack | train |
13bbbf9b45f1a01a303e359b | train | function | def train(model,
train_dataset,
val_dataset=None,
aug_eval=False,
flip_horizontal_eval=False,
optimizer=None,
save_dir='output',
iters=10000,
batch_size=2,
resume_model=None,
save_interval=1000,
log_iters=10,
... | def train(model,
train_dataset,
val_dataset=None,
aug_eval=False,
flip_horizontal_eval=False,
optimizer=None,
save_dir='output',
iters=10000,
batch_size=2,
resume_model=None,
save_interval=1000,
log_iters=10,
... | """
Launch training.
Args:
model(nn.Layer): A sementic segmentation model.
train_dataset (paddle.io.Dataset): Used to read and process training datasets.
val_dataset (paddle.io.Dataset, optional): Used to read and process validation datasets.
aug_eval (bool, optional): Wheth... | ['coef'][i]
if loss_i.__class__.__name__ in ('BCELoss',
'FocalLoss') and loss_i.edge_label:
# If use edges as labels According to loss type.
loss_list.append(coef_i * loss_i(logits, edges))
elif loss_i.__class__.__name__ == 'MixedLoss':
... | 256 | 256 | 2,012 | 88 | 167 | DaoDaoer/PaddleSeg | contrib/CityscapesSOTA/scripts/train.py | Python | train | train | 60 | 282 | 60 | 75 | 69b8ebe50468047774fca19d3b69d18b1367f633 | bigcode/the-stack | train |
11fa5709ef242e5b805f688d | train | function | def check_logits_losses(logits_list, losses):
len_logits = len(logits_list)
len_losses = len(losses['types'])
if len_logits != len_losses:
raise RuntimeError(
'The length of logits_list should equal to the types of loss config: {} != {}.'
.format(len_logits, len_losses))
| def check_logits_losses(logits_list, losses):
| len_logits = len(logits_list)
len_losses = len(losses['types'])
if len_logits != len_losses:
raise RuntimeError(
'The length of logits_list should equal to the types of loss config: {} != {}.'
.format(len_logits, len_losses))
| the License.
import os
import time
from collections import deque
import shutil
import paddle
import paddle.nn.functional as F
from paddleseg.utils import TimeAverager, calculate_eta, resume, logger
from paddleseg.core.val import evaluate
def check_logits_losses(logits_list, losses):
| 64 | 64 | 71 | 10 | 53 | DaoDaoer/PaddleSeg | contrib/CityscapesSOTA/scripts/train.py | Python | check_logits_losses | check_logits_losses | 27 | 33 | 27 | 27 | 2546bbaaef3c98132d3d8e4a1076677de5172a87 | bigcode/the-stack | train |
44d20d1c59a061c2831a0b60 | train | class | class BTMAssemblyFeature887(ModelComposed):
"""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_na... | class BTMAssemblyFeature887(ModelComposed):
| """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... | _mate64"]
try:
from onshape_client.oas.models import btm_mate_connector66
except ImportError:
btm_mate_connector66 = sys.modules["onshape_client.oas.models.btm_mate_connector66"]
try:
from onshape_client.oas.models import btm_mate_group65
except ImportError:
btm_mate_group65 = sys.modules["onshape_clien... | 255 | 256 | 2,322 | 10 | 245 | toebes/onshape-clients | python/onshape_client/oas/models/btm_assembly_feature887.py | Python | BTMAssemblyFeature887 | BTMAssemblyFeature887 | 114 | 335 | 114 | 114 | a86e270273bbff0c8ee3018d86c3392689973c48 | bigcode/the-stack | train |
e952d98c273bda8ce415c7aa | train | class | class AngrRemoveFakeretEdges(Transformer):
def __init__(self):
pass
def transform(self, graph):
remove = []
for e in graph.edges:
if e.meta['jumpkind'] == 'Ijk_FakeRet':
remove.append(e)
for r in remove:
graph.remove_edge(r)
| class AngrRemoveFakeretEdges(Transformer):
| def __init__(self):
pass
def transform(self, graph):
remove = []
for e in graph.edges:
if e.meta['jumpkind'] == 'Ijk_FakeRet':
remove.append(e)
for r in remove:
graph.remove_edge(r)
| c in cs:
for e in graph.edges:
if e.src == c and e.dst != n:
found = True
break
if not found:
remove.add(c)
for r in remove:
graph.remove_node(r)
class Ang... | 64 | 64 | 72 | 11 | 53 | fanyao/bingraphvis | bingraphvis/angr/transform.py | Python | AngrRemoveFakeretEdges | AngrRemoveFakeretEdges | 79 | 89 | 79 | 79 | 7dd08d2b9f2f324491f0c843147ac18d968fb9fd | bigcode/the-stack | train |
e0812a58cef204d4db643cdc | train | class | class AngrRemoveSimProcedures(Transformer):
def __init__(self):
pass
def transform(self, graph):
remove = []
for n in graph.nodes:
if n.obj.is_simprocedure:
remove.append(n)
cs = []
for e in graph.edges:
... | class AngrRemoveSimProcedures(Transformer):
| def __init__(self):
pass
def transform(self, graph):
remove = []
for n in graph.nodes:
if n.obj.is_simprocedure:
remove.append(n)
cs = []
for e in graph.edges:
if e.dst == n:
... | for n in graph.nodes:
if hasattr(n.obj, 'is_simprocedure') and n.obj.is_simprocedure and n.obj.simprocedure_name == 'PathTerminator':
remove.append(n)
for r in remove:
graph.remove_node(r)
class AngrRemoveSimProcedures(Transformer):
| 64 | 64 | 135 | 10 | 54 | fanyao/bingraphvis | bingraphvis/angr/transform.py | Python | AngrRemoveSimProcedures | AngrRemoveSimProcedures | 20 | 42 | 20 | 20 | 69e281e3366b5ee534e99ad7491893022d3c3a4c | bigcode/the-stack | train |
839fa78682e04742a02cde76 | train | class | class AngrRemoveImports(Transformer):
def __init__(self, project):
self.project = project
self.eaddrs = self.import_addrs(project)
def import_addrs(self, project):
eaddrs=[]
for _ in project.loader.main_bin.imports.values():
if _.resolvedby != None:
... | class AngrRemoveImports(Transformer):
| def __init__(self, project):
self.project = project
self.eaddrs = self.import_addrs(project)
def import_addrs(self, project):
eaddrs=[]
for _ in project.loader.main_bin.imports.values():
if _.resolvedby != None:
eaddrs.append(_.value)
... |
for c in cs:
for e in graph.edges:
if e.src == c and e.dst != n:
found = True
break
if not found:
remove.append(c)
for r in remove:
graph.r... | 64 | 64 | 204 | 8 | 56 | fanyao/bingraphvis | bingraphvis/angr/transform.py | Python | AngrRemoveImports | AngrRemoveImports | 45 | 75 | 45 | 45 | aeb9276c82398e530a4fc3b9f18cf010b952d8d9 | bigcode/the-stack | train |
22dd8af2e5a9fa8ce608d058 | train | class | class AngrDDGRemoveGarbageNodes(Transformer):
def __init__(self, project):
super(AngrDDGRemoveGarbageNodes, self).__init__()
self.project = project
def transform(self, graph):
offsets = set()
offsets.add(self.project.arch.registers['cc_op'][0])
offsets.add(self... | class AngrDDGRemoveGarbageNodes(Transformer):
| def __init__(self, project):
super(AngrDDGRemoveGarbageNodes, self).__init__()
self.project = project
def transform(self, graph):
offsets = set()
offsets.add(self.project.arch.registers['cc_op'][0])
offsets.add(self.project.arch.registers['cc_ndep'][0])
... | pass
def transform(self, graph):
remove = []
for e in graph.edges:
if e.meta['jumpkind'] == 'Ijk_FakeRet':
remove.append(e)
for r in remove:
graph.remove_edge(r)
class AngrDDGRemoveGarbageNodes(Transformer):
| 65 | 65 | 219 | 12 | 53 | fanyao/bingraphvis | bingraphvis/angr/transform.py | Python | AngrDDGRemoveGarbageNodes | AngrDDGRemoveGarbageNodes | 93 | 120 | 93 | 93 | 14094e59489ce9d482a3b3ae248607dab0095516 | bigcode/the-stack | train |
1ff475707c279b47007aef11 | train | class | class AngrRemovePathTerminator(Transformer):
def __init__(self):
pass
def transform(self, graph):
remove = []
for n in graph.nodes:
if hasattr(n.obj, 'is_simprocedure') and n.obj.is_simprocedure and n.obj.simprocedure_name == 'PathTerminator':
... | class AngrRemovePathTerminator(Transformer):
| def __init__(self):
pass
def transform(self, graph):
remove = []
for n in graph.nodes:
if hasattr(n.obj, 'is_simprocedure') and n.obj.is_simprocedure and n.obj.simprocedure_name == 'PathTerminator':
remove.append(n)
for r in remov... |
from ..base import *
import networkx
class AngrRemovePathTerminator(Transformer):
| 20 | 64 | 85 | 10 | 9 | fanyao/bingraphvis | bingraphvis/angr/transform.py | Python | AngrRemovePathTerminator | AngrRemovePathTerminator | 6 | 17 | 6 | 6 | 5b578da145c84c89dfc0805b465dfcce5cab559a | bigcode/the-stack | train |
411e1154989a27d70af148a6 | train | function | def make_aprox(
P_light,
P_albedo = IceRayCpp.GraphTypeColorRGB().fill( 0.75 ),
P_specular = IceRayCpp.GraphTypeColorRGB().load( 0.91, 0.92, 0.93 ),
P_alphaX = IceRayCpp.GraphTypeColorRGB().load( 0.50, 0.50, 0.50 ),
P_alphaY = IceRayCpp.GraphTypeColorRGB().load( 0.10, 0.10, 0.10 ),
... | def make_aprox(
P_light,
P_albedo = IceRayCpp.GraphTypeColorRGB().fill( 0.75 ),
P_specular = IceRayCpp.GraphTypeColorRGB().load( 0.91, 0.92, 0.93 ),
P_alphaX = IceRayCpp.GraphTypeColorRGB().load( 0.50, 0.50, 0.50 ),
P_alphaY = IceRayCpp.GraphTypeColorRGB().load( 0.10, 0.10, 0.10 ),
... | surface = IceRayCpp.MaterialSurface()
cargo = {}
cargo['1'] = IceRayCpp.MaterialLightGenerator( P_light['this'], 0 )
#MaterialLightSpotSwarmB( [coord]point, [light]light, [spot]start, [size]count )
cargo['2A'] = IceRayCpp.MaterialLightSpotSwarmA( 0, 0, 0, 0 )
#MaterialLightSpotCull( [coor... | import IceRayCpp
def make_aprox(
P_light,
P_albedo = IceRayCpp.GraphTypeColorRGB().fill( 0.75 ),
P_specular = IceRayCpp.GraphTypeColorRGB().load( 0.91, 0.92, 0.93 ),
P_alphaX = IceRayCpp.GraphTypeColorRGB().load( 0.50, 0.50, 0.50 ),
P_alphaY = IceRayCpp.GraphTypeColorRGB().load( 0.10,... | 159 | 190 | 635 | 154 | 4 | dmilos/IceRay | example/test/core/material/illumination/ward/unit.py | Python | make_aprox | make_aprox | 4 | 45 | 4 | 12 | 645edb8ff3336dcbb4e0a9e80fde16f5d5f9bfc4 | bigcode/the-stack | train |
29999daacca38c6547691ba7 | train | function | def make_isotropic( P_light ):
surface = IceRayCpp.MaterialSurface()
cargo = {}
cargo['1'] = IceRayCpp.MaterialLightGenerator( P_light['this'], 0 )
#MaterialLightSpotSwarmA( [size]count, [light]light, [coord]point, [spot]start )
cargo['2A'] = IceRayCpp.MaterialLightSpotSwarmA( 0, 0, 0, 0 )
... | def make_isotropic( P_light ):
| surface = IceRayCpp.MaterialSurface()
cargo = {}
cargo['1'] = IceRayCpp.MaterialLightGenerator( P_light['this'], 0 )
#MaterialLightSpotSwarmA( [size]count, [light]light, [coord]point, [spot]start )
cargo['2A'] = IceRayCpp.MaterialLightSpotSwarmA( 0, 0, 0, 0 )
#MaterialLightSpotCull( [coor... | 0, 1,2,3, 3, 0 )
surface.append( cargo['1'] )
surface.append( cargo['2A'] )
surface.append( cargo['2B'] )
surface.append( cargo['3'] )
surface.append( cargo['4'] )
surface.append( cargo['5'] )
surface.append( cargo['6'] )
surface.append( cargo['7'] )
surface.append( carg... | 138 | 138 | 460 | 9 | 129 | dmilos/IceRay | example/test/core/material/illumination/ward/unit.py | Python | make_isotropic | make_isotropic | 47 | 75 | 47 | 48 | 412d02e3bfb6ff9cf93306c8a65a7fd486d2804f | bigcode/the-stack | train |
b76335ce532808b3751afab9 | train | function | def make_real( P_light ):
surface = IceRayCpp.MaterialSurface()
cargo = {}
cargo['1'] = IceRayCpp.MaterialLightGenerator( P_light['this'], 0 )
#MaterialLightSpotSwarmA( [size]count, [light]light, [coord]point, [spot]start )
cargo['2A'] = IceRayCpp.MaterialLightSpotSwarmA( 0, 0, 0, 0 )
... | def make_real( P_light ):
| surface = IceRayCpp.MaterialSurface()
cargo = {}
cargo['1'] = IceRayCpp.MaterialLightGenerator( P_light['this'], 0 )
#MaterialLightSpotSwarmA( [size]count, [light]light, [coord]point, [spot]start )
cargo['2A'] = IceRayCpp.MaterialLightSpotSwarmA( 0, 0, 0, 0 )
#MaterialLightSpotCull( [coor... | )
#MaterialIlluminationWardIsotropic( [coord]point, [coord]normal, [size]lightCount, [color]specular, [color]alpha )
cargo['7'] = IceRayCpp.MaterialIlluminationWardIsotropic( 0,1, 0, 1,2, 0 )
surface.append( cargo['1'] )
surface.append( cargo['2A'] )
surface.append( cargo['2B'] )
surfac... | 174 | 174 | 581 | 8 | 166 | dmilos/IceRay | example/test/core/material/illumination/ward/unit.py | Python | make_real | make_real | 77 | 111 | 77 | 78 | 0b1bd0a1a3864452d3f6546731eb49c03ef23365 | bigcode/the-stack | train |
442a78d8ada1fbb4fbc0501e | train | class | class _UnreadVariable(ResourceVariable):
"""Represents a future for a read of a variable.
Pretends to be the tensor if anyone looks.
"""
def __init__(self, handle, dtype, # pylint: disable=super-init-not-called
shape, in_graph_mode, deleter, parent_op, unique_id):
# We do not call super in... | class _UnreadVariable(ResourceVariable):
| """Represents a future for a read of a variable.
Pretends to be the tensor if anyone looks.
"""
def __init__(self, handle, dtype, # pylint: disable=super-init-not-called
shape, in_graph_mode, deleter, parent_op, unique_id):
# We do not call super init on purpose.
self._trainable = Fals... | _other):
raise RuntimeError("Variable **= value not supported. Use "
"value and variable = variable ** value to get a new "
"Tensor object.")
pywrap_tensorflow.TFE_Py_RegisterResourceVariableType(ResourceVariable)
math_ops._resource_variable_type = ResourceVariable #... | 124 | 124 | 416 | 7 | 116 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _UnreadVariable | _UnreadVariable | 1,037 | 1,092 | 1,037 | 1,037 | cd5885166a875d470c152e3e43d3068dc474bf8a | bigcode/the-stack | train |
0bcca2f41297dbc105be009c | train | function | def _to_proto_fn(v, export_scope=None):
"""Converts Variable and ResourceVariable to VariableDef for collections."""
return v.to_proto(export_scope=export_scope)
| def _to_proto_fn(v, export_scope=None):
| """Converts Variable and ResourceVariable to VariableDef for collections."""
return v.to_proto(export_scope=export_scope)
| array_ops.concat([size, params_shape[1:]], 0)
values = array_ops.reshape(grad, values_shape)
indices = array_ops.reshape(indices, size)
return (ops.IndexedSlices(values, indices, params_shape), None)
def _to_proto_fn(v, export_scope=None):
| 64 | 64 | 36 | 11 | 53 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _to_proto_fn | _to_proto_fn | 1,131 | 1,133 | 1,131 | 1,131 | 500c39bb556526b143f3115ae830d942e5606abd | bigcode/the-stack | train |
8a3bfd000d41e5ad63418559 | train | function | @ops.RegisterGradient("ResourceGather")
def _GatherGrad(op, grad):
"""Gradient for gather op."""
# Build appropriately shaped IndexedSlices
handle = op.inputs[0]
indices = op.inputs[1]
params_shape = gen_resource_variable_ops.variable_shape(handle)
size = array_ops.expand_dims(array_ops.size(indices), 0)
... | @ops.RegisterGradient("ResourceGather")
def _GatherGrad(op, grad):
| """Gradient for gather op."""
# Build appropriately shaped IndexedSlices
handle = op.inputs[0]
indices = op.inputs[1]
params_shape = gen_resource_variable_ops.variable_shape(handle)
size = array_ops.expand_dims(array_ops.size(indices), 0)
values_shape = array_ops.concat([size, params_shape[1:]], 0)
valu... | =protected-access
ResourceVariable._OverloadAllOperators()
ops.register_dense_tensor_like_type(ResourceVariable)
@ops.RegisterGradient("ReadVariableOp")
def _ReadGrad(_, grad):
"""Gradient for read op."""
return grad
@ops.RegisterGradient("ResourceGather")
def _GatherGrad(op, grad):
| 64 | 64 | 131 | 16 | 47 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _GatherGrad | _GatherGrad | 1,117 | 1,128 | 1,117 | 1,118 | f81a56c55e51fa912835ee1635b4facdafe148f2 | bigcode/the-stack | train |
513e6e530d860a6a2e146ab9 | train | function | def _from_proto_fn(v, import_scope=None):
"""Creates Variable or ResourceVariable from VariableDef as needed."""
if v.is_resource:
return ResourceVariable.from_proto(v, import_scope=import_scope)
return variables.Variable.from_proto(v, import_scope=import_scope)
| def _from_proto_fn(v, import_scope=None):
| """Creates Variable or ResourceVariable from VariableDef as needed."""
if v.is_resource:
return ResourceVariable.from_proto(v, import_scope=import_scope)
return variables.Variable.from_proto(v, import_scope=import_scope)
| )
return (ops.IndexedSlices(values, indices, params_shape), None)
def _to_proto_fn(v, export_scope=None):
"""Converts Variable and ResourceVariable to VariableDef for collections."""
return v.to_proto(export_scope=export_scope)
def _from_proto_fn(v, import_scope=None):
| 64 | 64 | 58 | 11 | 53 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _from_proto_fn | _from_proto_fn | 1,136 | 1,140 | 1,136 | 1,136 | 3609ae57a9bc92c48099f662178e5f7de0a6269c | bigcode/the-stack | train |
47e6c371429ea93ad0d05842 | train | function | def is_resource_variable(var):
""""Returns True if `var` is to be considered a ResourceVariable."""
return isinstance(var, ResourceVariable) or hasattr(
var, "_should_act_as_resource_variable")
| def is_resource_variable(var):
| """"Returns True if `var` is to be considered a ResourceVariable."""
return isinstance(var, ResourceVariable) or hasattr(
var, "_should_act_as_resource_variable")
| .VariableDef,
to_proto=_to_proto_fn,
from_proto=_from_proto_fn)
ops.register_proto_function(
ops.GraphKeys.GLOBAL_STEP,
proto_type=variable_pb2.VariableDef,
to_proto=_to_proto_fn,
from_proto=_from_proto_fn)
def is_resource_variable(var):
| 64 | 64 | 44 | 6 | 58 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | is_resource_variable | is_resource_variable | 1,175 | 1,178 | 1,175 | 1,175 | f4b245b8bf2fd8938a3711c364cbc80e0d4720f1 | bigcode/the-stack | train |
1c7651ff33fd083dafecfac2 | train | class | class ResourceVariable(variables.Variable):
"""Variable based on resource handles.
See the @{$variables$Variables How To} for a high level overview.
A `ResourceVariable` allows you to maintain state across subsequent calls to
session.run.
The `ResourceVariable` constructor requires an initial value for the... | class ResourceVariable(variables.Variable):
| """Variable based on resource handles.
See the @{$variables$Variables How To} for a high level overview.
A `ResourceVariable` allows you to maintain state across subsequent calls to
session.run.
The `ResourceVariable` constructor requires an initial value for the variable,
which can be a `Tensor` of any ... | ():
with ops.device(self._handle_device):
gen_resource_variable_ops.destroy_resource_op(
self._handle, ignore_lookup_error=True)
except TypeError:
# Suppress some exceptions, mainly for the case when we're running on
# module deletion. Things that can go wrong include the... | 256 | 256 | 7,538 | 7 | 249 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | ResourceVariable | ResourceVariable | 184 | 1,026 | 184 | 184 | f02b4dfffbfac833828e0f26bcee2c9fcdf8eba0 | bigcode/the-stack | train |
876e20d7cb57376ff43947fc | train | function | def _eager_safe_variable_handle(shape, dtype, shared_name, name, graph_mode):
"""Creates a variable handle with information to do shape inference."""
container = ops.get_default_graph()._container # pylint: disable=protected-access
if container is None:
container = ""
handle = gen_resource_variable_ops.var... | def _eager_safe_variable_handle(shape, dtype, shared_name, name, graph_mode):
| """Creates a variable handle with information to do shape inference."""
container = ops.get_default_graph()._container # pylint: disable=protected-access
if container is None:
container = ""
handle = gen_resource_variable_ops.var_handle_op(shape=shape, dtype=dtype,
... | card-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_resource_variable_ops import *
# pylint: enable=wildcard-import
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import compat
def get_resource_handle_data(graph_op):
assert ops._USE_... | 181 | 181 | 605 | 19 | 162 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _eager_safe_variable_handle | _eager_safe_variable_handle | 58 | 117 | 58 | 58 | 162e1da6f247da49fa506645d3b1d709f1b10294 | bigcode/the-stack | train |
f9a87591d7f6f65a0e5b31d0 | train | function | def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):
return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
| def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):
| return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access
| ** value to get a new "
"Tensor object.")
pywrap_tensorflow.TFE_Py_RegisterResourceVariableType(ResourceVariable)
math_ops._resource_variable_type = ResourceVariable # pylint: disable=protected-access
def _dense_var_to_tensor(var, dtype=None, name=None, as_ref=False):
| 64 | 64 | 48 | 18 | 45 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _dense_var_to_tensor | _dense_var_to_tensor | 1,033 | 1,034 | 1,033 | 1,033 | ec485dd175938935b5abdbd263e48ce873896c38 | bigcode/the-stack | train |
4a7cacf0bd005e2ba6e98ed8 | train | function | def get_resource_handle_data(graph_op):
assert ops._USE_C_SHAPES # pylint: disable=protected-access
assert type(graph_op) == ops.Tensor # pylint: disable=unidiomatic-typecheck
handle_data = pywrap_tensorflow.GetResourceHandleShapeAndType(
graph_op.graph._c_graph, graph_op._as_tf_output()) # pylint: disa... | def get_resource_handle_data(graph_op):
| assert ops._USE_C_SHAPES # pylint: disable=protected-access
assert type(graph_op) == ops.Tensor # pylint: disable=unidiomatic-typecheck
handle_data = pywrap_tensorflow.GetResourceHandleShapeAndType(
graph_op.graph._c_graph, graph_op._as_tf_output()) # pylint: disable=protected-access
return cpp_shape... | go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_resource_variable_ops import *
# pylint: enable=wildcard-import
from tensorflow.python.training.checkpointable import base as checkpointable
from tensorflow.python.util import compat
def get_resource_handle_data(graph_op):
| 64 | 64 | 111 | 8 | 55 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | get_resource_handle_data | get_resource_handle_data | 47 | 55 | 47 | 47 | 639e11dd9b4d35dbc5fbc0c621f81863d7858577 | bigcode/the-stack | train |
15eda2a8499d18339025d646 | train | function | def shape_safe_assign_variable_handle(handle, shape, value, name=None):
"""Helper that checks shape compatibility and assigns variable."""
with _handle_graph(handle):
value_tensor = ops.convert_to_tensor(value)
shape.assert_is_compatible_with(value_tensor.shape)
return gen_resource_variable_ops.assign_varia... | def shape_safe_assign_variable_handle(handle, shape, value, name=None):
| """Helper that checks shape compatibility and assigns variable."""
with _handle_graph(handle):
value_tensor = ops.convert_to_tensor(value)
shape.assert_is_compatible_with(value_tensor.shape)
return gen_resource_variable_ops.assign_variable_op(handle,
val... | handle has been
# partially unloaded.
except AttributeError:
pass # 'NoneType' object has no attribute 'eager_mode' when context has
# been unloaded. Will catch other module unloads as well.
def shape_safe_assign_variable_handle(handle, shape, value, name=None):
| 64 | 64 | 73 | 15 | 49 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | shape_safe_assign_variable_handle | shape_safe_assign_variable_handle | 174 | 181 | 174 | 174 | 1686c7b02fcb82a7dffb978cf34ddb3745604900 | bigcode/the-stack | train |
a4ecf10f1e835e870b0b4b05 | train | function | @contextlib.contextmanager
def _handle_graph(handle):
# Note: might have an eager tensor but not be executing eagerly when building
# functions.
if (context.executing_eagerly() or isinstance(handle, ops.EagerTensor)
or ops.has_default_graph()):
yield
else:
with handle.graph.as_default():
yie... | @contextlib.contextmanager
def _handle_graph(handle):
# Note: might have an eager tensor but not be executing eagerly when building
# functions.
| if (context.executing_eagerly() or isinstance(handle, ops.EagerTensor)
or ops.has_default_graph()):
yield
else:
with handle.graph.as_default():
yield
| the attributes for
# the Graph and op we created.
h.__dict__ = {}
graph.__dict__ = {}
return handle
@contextlib.contextmanager
def _handle_graph(handle):
# Note: might have an eager tensor but not be executing eagerly when building
# functions.
| 64 | 64 | 75 | 33 | 30 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _handle_graph | _handle_graph | 120 | 129 | 120 | 123 | 11e1e6bf94d7513e5a2d63c180213b1913fe36f5 | bigcode/the-stack | train |
94b41d05003bc012c54ae755 | train | function | @ops.RegisterGradient("ReadVariableOp")
def _ReadGrad(_, grad):
"""Gradient for read op."""
return grad
| @ops.RegisterGradient("ReadVariableOp")
def _ReadGrad(_, grad):
| """Gradient for read op."""
return grad
| _conversion_function(
variables.Variable, variables.Variable._TensorConversionFunction) # pylint: disable=protected-access
# pylint: disable=protected-access
ResourceVariable._OverloadAllOperators()
ops.register_dense_tensor_like_type(ResourceVariable)
@ops.RegisterGradient("ReadVariableOp")
def _ReadGrad(_, grad... | 64 | 64 | 27 | 16 | 48 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | _ReadGrad | _ReadGrad | 1,111 | 1,114 | 1,111 | 1,112 | 9edd45b796fd481e57ea4be4f066533230b1414f | bigcode/the-stack | train |
ebac22f37a8389b6bb5b5e7b | train | class | class EagerResourceDeleter(object):
"""An object which cleans up a resource handle.
An alternative to defining a __del__ method on an object. The intended use is
that ResourceVariables or other objects with resource handles will maintain a
single reference to this object. When the parent object is collected, t... | class EagerResourceDeleter(object):
| """An object which cleans up a resource handle.
An alternative to defining a __del__ method on an object. The intended use is
that ResourceVariables or other objects with resource handles will maintain a
single reference to this object. When the parent object is collected, this
object will be too. Even if th... | clean up our own reference cycles by clearing all of the attributes for
# the Graph and op we created.
h.__dict__ = {}
graph.__dict__ = {}
return handle
@contextlib.contextmanager
def _handle_graph(handle):
# Note: might have an eager tensor but not be executing eagerly when building
# functions.
if (c... | 125 | 125 | 418 | 9 | 115 | SurpriseLee/tensorflow | tensorflow/python/ops/resource_variable_ops.py | Python | EagerResourceDeleter | EagerResourceDeleter | 132 | 170 | 132 | 132 | 742cf9e22133bfa78e6f4fc5a6929747c9d6804f | bigcode/the-stack | train |
fc433ae42753f926a04751e8 | train | function | def get_domain(dkim_key_size: Optional[int] = None,
dkim_selector: Optional[str] = None,
name: Optional[str] = None,
region: Optional[str] = None,
smtp_password: Optional[str] = None,
spam_action: Optional[str] = None,
wildcard: O... | def get_domain(dkim_key_size: Optional[int] = None,
dkim_selector: Optional[str] = None,
name: Optional[str] = None,
region: Optional[str] = None,
smtp_password: Optional[str] = None,
spam_action: Optional[str] = None,
wildcard: O... | """
`Domain` provides details about a Mailgun domain.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
import pulumi_mailgun as mailgun
domain = mailgun.get_domain(name="test.example.com")
mailgun_mx = aws.route53.Record("mailgun-mx",
name=data["mailgun"][... | Result(
dkim_key_size=self.dkim_key_size,
dkim_selector=self.dkim_selector,
id=self.id,
name=self.name,
receiving_records=self.receiving_records,
region=self.region,
sending_records=self.sending_records,
smtp_login=self.smtp... | 175 | 175 | 586 | 93 | 82 | pulumi/pulumi-mailgun | sdk/python/pulumi_mailgun/get_domain.py | Python | get_domain | get_domain | 157 | 218 | 157 | 164 | d1c2150d64bb73a3daa81674bbdd785983ebcbcb | bigcode/the-stack | train |
f34ffbe8efe8468060759f14 | train | class | class AwaitableGetDomainResult(GetDomainResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetDomainResult(
dkim_key_size=self.dkim_key_size,
dkim_selector=self.dkim_selector,
id=self.id,
nam... | class AwaitableGetDomainResult(GetDomainResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetDomainResult(
dkim_key_size=self.dkim_key_size,
dkim_selector=self.dkim_selector,
id=self.id,
name=self.name,
receiving_records=self.receiving_records,
region=self.... | umi.getter
def wildcard(self) -> Optional[bool]:
"""
Whether or not the domain will accept email for sub-domains.
"""
return pulumi.get(self, "wildcard")
class AwaitableGetDomainResult(GetDomainResult):
# pylint: disable=using-constant-test
| 64 | 64 | 122 | 21 | 43 | pulumi/pulumi-mailgun | sdk/python/pulumi_mailgun/get_domain.py | Python | AwaitableGetDomainResult | AwaitableGetDomainResult | 138 | 154 | 138 | 139 | f559bfabf4beb03537612e5d8652de870aa50bd7 | bigcode/the-stack | train |
3b82bb893efd8e59e746e3f8 | train | class | @pulumi.output_type
class GetDomainResult:
"""
A collection of values returned by getDomain.
"""
def __init__(__self__, dkim_key_size=None, dkim_selector=None, id=None, name=None, receiving_records=None, region=None, sending_records=None, smtp_login=None, smtp_password=None, spam_action=None, wildcard=N... | @pulumi.output_type
class GetDomainResult:
| """
A collection of values returned by getDomain.
"""
def __init__(__self__, dkim_key_size=None, dkim_selector=None, id=None, name=None, receiving_records=None, region=None, sending_records=None, smtp_login=None, smtp_password=None, spam_action=None, wildcard=None):
if dkim_key_size and not isin... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 120 | 256 | 1,045 | 11 | 109 | pulumi/pulumi-mailgun | sdk/python/pulumi_mailgun/get_domain.py | Python | GetDomainResult | GetDomainResult | 18 | 135 | 18 | 19 | 946cb7f7a103ea0f494b7c3baac9de7634c584c5 | bigcode/the-stack | train |
603fab465bfed7787436a9f4 | train | function | def nanany(values, axis=None, skipna=True):
values, mask, dtype, _ = _get_values(values, skipna, False, copy=skipna)
return values.any(axis)
| def nanany(values, axis=None, skipna=True):
| values, mask, dtype, _ = _get_values(values, skipna, False, copy=skipna)
return values.any(axis)
| :
return fill_value
else:
result_shape = (values.shape[:axis] +
values.shape[axis + 1:])
result = np.empty(result_shape, dtype=values.dtype)
result.fill(fill_value)
return result
def nanany(values, axis=None, skipna=True):
| 64 | 64 | 42 | 12 | 51 | jmcclenon/pandas | pandas/core/nanops.py | Python | nanany | nanany | 318 | 320 | 318 | 318 | 47f4df90aea0f7c63a4ea0b1769c39f8ed337c5a | bigcode/the-stack | train |
8985eed51c57247ee7b4c77f | train | function | def _bn_ok_dtype(dt, name):
# Bottleneck chokes on datetime64
if (not is_object_dtype(dt) and not is_datetime_or_timedelta_dtype(dt)):
# GH 15507
# bottleneck does not properly upcast during the sum
# so can overflow
# GH 9422
# further we also want to preserve NaN when... | def _bn_ok_dtype(dt, name):
# Bottleneck chokes on datetime64
| if (not is_object_dtype(dt) and not is_datetime_or_timedelta_dtype(dt)):
# GH 15507
# bottleneck does not properly upcast during the sum
# so can overflow
# GH 9422
# further we also want to preserve NaN when all elements
# are NaN, unlinke bottleneck/numpy which co... | # e.g. this is normally a disallowed function on
# object arrays that contain strings
if is_object_dtype(values):
raise TypeError(e)
raise
return result
return f
def _bn_ok_dtype(dt, name):
# Bottleneck choke... | 64 | 64 | 134 | 19 | 44 | jmcclenon/pandas | pandas/core/nanops.py | Python | _bn_ok_dtype | _bn_ok_dtype | 147 | 163 | 147 | 148 | 9171926218a7d76c9b0310084ea7a6f690aa50f1 | bigcode/the-stack | train |
00eedfd5bb4ba169cf0a2628 | train | class | class disallow(object):
def __init__(self, *dtypes):
super(disallow, self).__init__()
self.dtypes = tuple(np.dtype(dtype).type for dtype in dtypes)
def check(self, obj):
return hasattr(obj, 'dtype') and issubclass(obj.dtype.type,
self... | class disallow(object):
| def __init__(self, *dtypes):
super(disallow, self).__init__()
self.dtypes = tuple(np.dtype(dtype).type for dtype in dtypes)
def check(self, obj):
return hasattr(obj, 'dtype') and issubclass(obj.dtype.type,
self.dtypes)
def __call_... | TLENECK = False
def set_use_bottleneck(v=True):
# set/unset to use bottleneck
global _USE_BOTTLENECK
if _BOTTLENECK_INSTALLED:
_USE_BOTTLENECK = v
set_use_bottleneck(get_option('compute.use_bottleneck'))
class disallow(object):
| 75 | 76 | 256 | 5 | 70 | jmcclenon/pandas | pandas/core/nanops.py | Python | disallow | disallow | 58 | 87 | 58 | 59 | 29a590e3738c7cbe60d92e4119dde028b1a4001e | bigcode/the-stack | train |
dcc5ad6b71f0693499c9d8a5 | train | function | def _ensure_numeric(x):
if isinstance(x, np.ndarray):
if is_integer_dtype(x) or is_bool_dtype(x):
x = x.astype(np.float64)
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except:
x = x.astype(np.float64)
else:
... | def _ensure_numeric(x):
| if isinstance(x, np.ndarray):
if is_integer_dtype(x) or is_bool_dtype(x):
x = x.astype(np.float64)
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
except:
x = x.astype(np.float64)
else:
if not n... | notna(a) & notna(b)
if not valid.all():
a = a[valid]
b = b[valid]
if len(a) < min_periods:
return np.nan
return np.cov(a, b)[0, 1]
def _ensure_numeric(x):
| 64 | 64 | 155 | 6 | 58 | jmcclenon/pandas | pandas/core/nanops.py | Python | _ensure_numeric | _ensure_numeric | 808 | 829 | 808 | 808 | 52c232c344ebd2add0d0b57d90cec9111896a0a8 | bigcode/the-stack | train |
c0c69278feef0175a665cf11 | train | function | def _nanminmax(meth, fill_value_typ):
@bottleneck_switch()
def reduction(values, axis=None, skipna=True):
values, mask, dtype, dtype_max = _get_values(
values, skipna, fill_value_typ=fill_value_typ, )
if ((axis is not None and values.shape[axis] == 0) or
values.size ... | def _nanminmax(meth, fill_value_typ):
@bottleneck_switch()
| def reduction(values, axis=None, skipna=True):
values, mask, dtype, dtype_max = _get_values(
values, skipna, fill_value_typ=fill_value_typ, )
if ((axis is not None and values.shape[axis] == 0) or
values.size == 0):
try:
result = getattr(values... | = _get_counts_nanvar(mask, axis, ddof, values.dtype)
var = nanvar(values, axis, skipna, ddof=ddof)
return np.sqrt(var) / np.sqrt(count)
def _nanminmax(meth, fill_value_typ):
@bottleneck_switch()
| 64 | 64 | 170 | 19 | 45 | jmcclenon/pandas | pandas/core/nanops.py | Python | _nanminmax | _nanminmax | 493 | 513 | 493 | 494 | 985d45a1fa24456e7fc2c6732e6c3a31f491e401 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.