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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
571769a346913da20738951e | train | class | class TestDeleteSubnet(TestSubnet):
# The subnet to delete.
_subnet = network_fakes.FakeSubnet.create_one_subnet()
def setUp(self):
super(TestDeleteSubnet, self).setUp()
self.network.delete_subnet = mock.Mock(return_value=None)
self.network.find_subnet = mock.Mock(return_value=se... | class TestDeleteSubnet(TestSubnet):
# The subnet to delete.
| _subnet = network_fakes.FakeSubnet.create_one_subnet()
def setUp(self):
super(TestDeleteSubnet, self).setUp()
self.network.delete_subnet = mock.Mock(return_value=None)
self.network.find_subnet = mock.Mock(return_value=self._subnet)
# Get the command object to test
sel... | _id': self._subnet_ipv6.network_id,
'allocation_pools': self._subnet_ipv6.allocation_pools,
})
self.assertEqual(self.columns, columns)
self.assertEqual(self.data_ipv6, data)
class TestDeleteSubnet(TestSubnet):
# The subnet to delete.
| 64 | 64 | 186 | 14 | 50 | ankur-gupta91/osc-ip-cap | openstackclient/tests/network/v2/test_subnet.py | Python | TestDeleteSubnet | TestDeleteSubnet | 361 | 387 | 361 | 363 | 3de24f7ed9b0b88ec926e03f19f782fd181292af | bigcode/the-stack | train |
8c4588165a481011161e1a3d | train | class | class TestSubnet(network_fakes.TestNetworkV2):
def setUp(self):
super(TestSubnet, self).setUp()
# Get a shortcut to the network client
self.network = self.app.client_manager.network
| class TestSubnet(network_fakes.TestNetworkV2):
| def setUp(self):
super(TestSubnet, self).setUp()
# Get a shortcut to the network client
self.network = self.app.client_manager.network
| openstackclient.tests import fakes
from openstackclient.tests.identity.v3 import fakes as identity_fakes_v3
from openstackclient.tests.network.v2 import fakes as network_fakes
from openstackclient.tests import utils as tests_utils
class TestSubnet(network_fakes.TestNetworkV2):
| 64 | 64 | 47 | 11 | 52 | ankur-gupta91/osc-ip-cap | openstackclient/tests/network/v2/test_subnet.py | Python | TestSubnet | TestSubnet | 25 | 31 | 25 | 26 | 58fdb78052e6e95b7df11354d57333a2aeea8c1e | bigcode/the-stack | train |
963b27c03147ad1642c27e3d | train | class | class TestCreateSubnet(TestSubnet):
# An IPv4 subnet to be created with mostly default values
_subnet = network_fakes.FakeSubnet.create_one_subnet(
attrs={
'tenant_id': identity_fakes_v3.project_id,
}
)
# Subnet pool to be used to create a subnet from a pool
_subnet_poo... | class TestCreateSubnet(TestSubnet):
# An IPv4 subnet to be created with mostly default values
| _subnet = network_fakes.FakeSubnet.create_one_subnet(
attrs={
'tenant_id': identity_fakes_v3.project_id,
}
)
# Subnet pool to be used to create a subnet from a pool
_subnet_pool = network_fakes.FakeSubnetPool.create_one_subnet_pool()
# An IPv4 subnet to be created using... | 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITI... | 256 | 256 | 3,158 | 21 | 234 | ankur-gupta91/osc-ip-cap | openstackclient/tests/network/v2/test_subnet.py | Python | TestCreateSubnet | TestCreateSubnet | 34 | 358 | 34 | 36 | 5b9d22863ae6b94bae46e4a5dc9542e77caedfb8 | bigcode/the-stack | train |
d8f739bfbc79b1cb39243c08 | train | class | class TestShowSubnet(TestSubnet):
# The subnets to be shown
_subnet = network_fakes.FakeSubnet.create_one_subnet()
columns = (
'allocation_pools',
'cidr',
'dns_nameservers',
'enable_dhcp',
'gateway_ip',
'host_routes',
'id',
'ip_version',
... | class TestShowSubnet(TestSubnet):
# The subnets to be shown
| _subnet = network_fakes.FakeSubnet.create_one_subnet()
columns = (
'allocation_pools',
'cidr',
'dns_nameservers',
'enable_dhcp',
'gateway_ip',
'host_routes',
'id',
'ip_version',
'ipv6_address_mode',
'ipv6_ra_mode',
'name',
... | .cmd.take_action(parsed_args)
self.network.subnets.assert_called_once_with()
self.assertEqual(self.columns, columns)
self.assertEqual(self.data, list(data))
def test_subnet_list_long(self):
arglist = [
'--long',
]
verifylist = [
('long', True... | 143 | 143 | 478 | 16 | 127 | ankur-gupta91/osc-ip-cap | openstackclient/tests/network/v2/test_subnet.py | Python | TestShowSubnet | TestShowSubnet | 472 | 542 | 472 | 473 | 4b1f68b50d4f862af918f14577d8bb12e507a62f | bigcode/the-stack | train |
121f67401602c5c5419b5da5 | train | class | class TestListSubnet(TestSubnet):
# The subnets going to be listed up.
_subnet = network_fakes.FakeSubnet.create_subnets(count=3)
columns = (
'ID',
'Name',
'Network',
'Subnet',
)
columns_long = columns + (
'Project',
'DHCP',
'Name Servers',
... | class TestListSubnet(TestSubnet):
# The subnets going to be listed up.
| _subnet = network_fakes.FakeSubnet.create_subnets(count=3)
columns = (
'ID',
'Name',
'Network',
'Subnet',
)
columns_long = columns + (
'Project',
'DHCP',
'Name Servers',
'Allocation Pools',
'Host Routes',
'IP Version',
... | _subnet = mock.Mock(return_value=self._subnet)
# Get the command object to test
self.cmd = subnet_v2.DeleteSubnet(self.app, self.namespace)
def test_delete(self):
arglist = [
self._subnet.name,
]
verifylist = [
('subnet', self._subnet.name),
... | 140 | 140 | 468 | 18 | 122 | ankur-gupta91/osc-ip-cap | openstackclient/tests/network/v2/test_subnet.py | Python | TestListSubnet | TestListSubnet | 390 | 469 | 390 | 391 | 5edd8c038cd80585e68c42388d87b5dcee595e77 | bigcode/the-stack | train |
032765611351c65e1de5b123 | train | class | class Mage(AnimatedSprite):
def __init__(self, x, y, hor_v, run_v, vert_v, fps, platforms, cam=False, *box_group):
self.height = 180
self.width = 120
super().__init__(load_image('mage_pictures.png'), 8, 4, x, y, self.width, self.height)
self.movement_coefficients = [0, 0]
sel... | class Mage(AnimatedSprite):
| def __init__(self, x, y, hor_v, run_v, vert_v, fps, platforms, cam=False, *box_group):
self.height = 180
self.width = 120
super().__init__(load_image('mage_pictures.png'), 8, 4, x, y, self.width, self.height)
self.movement_coefficients = [0, 0]
self.direction = 0
self... | import pygame
from utils.load_image import load_image
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, sheet, columns, rows, x, y, *resize):
super().__init__()
self.x = x
self.y = y
self.frames = []
resize = resize or False
self.cut_sheet(sheet, colum... | 230 | 256 | 1,412 | 6 | 223 | v-like-engine/First-pygame-project | core/classes/hero_classes.py | Python | Mage | Mage | 35 | 156 | 35 | 35 | 56ef852f5cbca9d70142d4250af6b9f9b8ea18c6 | bigcode/the-stack | train |
ebc258443bca582b3f2b9d04 | train | class | class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, sheet, columns, rows, x, y, *resize):
super().__init__()
self.x = x
self.y = y
self.frames = []
resize = resize or False
self.cut_sheet(sheet, columns, rows, resize)
self.current_frame = 0
... | class AnimatedSprite(pygame.sprite.Sprite):
| def __init__(self, sheet, columns, rows, x, y, *resize):
super().__init__()
self.x = x
self.y = y
self.frames = []
resize = resize or False
self.cut_sheet(sheet, columns, rows, resize)
self.current_frame = 0
self.image = self.frames[self.current_frame]... | import pygame
from utils.load_image import load_image
class AnimatedSprite(pygame.sprite.Sprite):
| 20 | 64 | 213 | 9 | 10 | v-like-engine/First-pygame-project | core/classes/hero_classes.py | Python | AnimatedSprite | AnimatedSprite | 6 | 32 | 6 | 6 | b14dc6bd370da5cb27579979177622496d683ed2 | bigcode/the-stack | train |
a4a35ef95080702de025a9cd | train | class | class CursorIterator(six.Iterator):
"""Cursor iterator wrapper that invokes our custom row factory."""
def __init__(self, cursor):
self.cursor = cursor
self.iter = iter(cursor)
def __iter__(self):
return self
def __next__(self):
return _rowfactory(next(self.iter), sel... | class CursorIterator(six.Iterator):
| """Cursor iterator wrapper that invokes our custom row factory."""
def __init__(self, cursor):
self.cursor = cursor
self.iter = iter(cursor)
def __iter__(self):
return self
def __next__(self):
return _rowfactory(next(self.iter), self.cursor)
| .arrayvar(*args))
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
def __iter__(self):
return CursorIterator(self.cursor)
class CursorIterator(six.Iterator):
| 64 | 64 | 71 | 7 | 57 | victorgama/django | django/db/backends/oracle/base.py | Python | CursorIterator | CursorIterator | 957 | 969 | 957 | 958 | 4a51f9fb42fa2c7580f22fe3d9933f7563a0494c | bigcode/the-stack | train |
0a4b4f3ea517e03dd0ca553d | train | function | def _rowfactory(row, cursor):
# Cast numeric values as the appropriate Python type based upon the
# cursor description, and convert strings to unicode.
casted = []
for value, desc in zip(row, cursor.description):
if value is not None and desc[1] is Database.NUMBER:
precision, scale =... | def _rowfactory(row, cursor):
# Cast numeric values as the appropriate Python type based upon the
# cursor description, and convert strings to unicode.
| casted = []
for value, desc in zip(row, cursor.description):
if value is not None and desc[1] is Database.NUMBER:
precision, scale = desc[4:6]
if scale == -127:
if precision == 0:
# NUMBER column: decimal-precision floating point
... | return getattr(self.cursor, attr)
def __iter__(self):
return CursorIterator(self.cursor)
class CursorIterator(six.Iterator):
"""Cursor iterator wrapper that invokes our custom row factory."""
def __init__(self, cursor):
self.cursor = cursor
self.iter = iter(cursor)
... | 126 | 126 | 423 | 33 | 93 | victorgama/django | django/db/backends/oracle/base.py | Python | _rowfactory | _rowfactory | 972 | 1,016 | 972 | 974 | 6a177498b80b16f4f95b3fe5b9c98e05e932b95c | bigcode/the-stack | train |
11ff40cd4eb82f3da8bceee5 | train | class | class InsertIdVar(object):
"""
A late-binding cursor variable that can be passed to Cursor.execute
as a parameter, in order to receive the id of the row created by an
insert statement.
"""
def bind_parameter(self, cursor):
param = cursor.cursor.var(Database.NUMBER)
cursor._inser... | class InsertIdVar(object):
| """
A late-binding cursor variable that can be passed to Cursor.execute
as a parameter, in order to receive the id of the row created by an
insert statement.
"""
def bind_parameter(self, cursor):
param = cursor.cursor.var(Database.NUMBER)
cursor._insert_id_var = param
re... | def __getattr__(self, key):
return getattr(self.var, key)
def __setattr__(self, key, value):
if key == 'var':
self.__dict__[key] = value
else:
setattr(self.var, key, value)
class InsertIdVar(object):
| 64 | 64 | 77 | 6 | 58 | victorgama/django | django/db/backends/oracle/base.py | Python | InsertIdVar | InsertIdVar | 807 | 817 | 807 | 807 | 86dfe4b5f6ddc4eda27b26d4f6eadab9f91207f8 | bigcode/the-stack | train |
06df11397f7853837f5e6d56 | train | function | def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environment variables
# properly so that Oracle will see them.
if platform.system().upper().startswith('CYGWIN'):
try:
import ctypes
except ImportError as e:
from django.core.exceptions ... | def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environment variables
# properly so that Oracle will see them.
| if platform.system().upper().startswith('CYGWIN'):
try:
import ctypes
except ImportError as e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading ctypes: %s; "
"the Oracle backen... | .sourceforge.net/
"""
from __future__ import unicode_literals
import datetime
import decimal
import re
import platform
import sys
import warnings
def _setup_environment(environ):
# Cygwin requires some special voodoo to set the environment variables
# properly so that Oracle will see them.
| 64 | 64 | 152 | 34 | 29 | victorgama/django | django/db/backends/oracle/base.py | Python | _setup_environment | _setup_environment | 16 | 32 | 16 | 18 | 54c4ca98ddb45adf5eab83dbb10763658c561e7e | bigcode/the-stack | train |
82eed15bfda4905d9e97ef3d | train | class | class FormatStylePlaceholderCursor(object):
"""
Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
style. This fixes it -- but note that if you want to use a literal "%s" in
a query, you'll need to use "%%s".
We also do automatic conversion between Unicode on the Python sid... | class FormatStylePlaceholderCursor(object):
| """
Django uses "format" (e.g. '%s') style placeholders, but Oracle uses ":var"
style. This fixes it -- but note that if you want to use a literal "%s" in
a query, you'll need to use "%%s".
We also do automatic conversion between Unicode on the Python side and
UTF-8 -- for talking to Oracle -- ... | 0 characters as a CLOB.
self.input_size = Database.CLOB
else:
self.input_size = None
class VariableWrapper(object):
"""
An adapter class for cursor variables that prevents the wrapped object
from being converted into a string when used to instantiate an OracleParam.
Thi... | 256 | 256 | 1,250 | 7 | 248 | victorgama/django | django/db/backends/oracle/base.py | Python | FormatStylePlaceholderCursor | FormatStylePlaceholderCursor | 820 | 954 | 820 | 820 | 4b33c5f8399e1b8b7ed30912379aa6680dce6f48 | bigcode/the-stack | train |
3205e102387a8ca91216dc68 | train | class | class _UninitializedOperatorsDescriptor(object):
def __get__(self, instance, owner):
# If connection.operators is looked up before a connection has been
# created, transparently initialize connection.operators to avert an
# AttributeError.
if instance is None:
raise Attr... | class _UninitializedOperatorsDescriptor(object):
| def __get__(self, instance, owner):
# If connection.operators is looked up before a connection has been
# created, transparently initialize connection.operators to avert an
# AttributeError.
if instance is None:
raise AttributeError("operators not available as class attri... | name_length).upper()
def bulk_insert_sql(self, fields, num_values):
items_sql = "SELECT %s FROM DUAL" % ", ".join(["%s"] * len(fields))
return " UNION ALL ".join([items_sql] * num_values)
class _UninitializedOperatorsDescriptor(object):
| 64 | 64 | 96 | 8 | 56 | victorgama/django | django/db/backends/oracle/base.py | Python | _UninitializedOperatorsDescriptor | _UninitializedOperatorsDescriptor | 537 | 547 | 537 | 538 | 88f517736ea929c455b6fbfea5b862de14f6bf15 | bigcode/the-stack | train |
27d8bb3ce10268b13a6dfdf3 | train | function | def to_unicode(s):
"""
Convert strings to Unicode objects (and return all other data types
unchanged).
"""
if isinstance(s, six.string_types):
return force_text(s)
return s
| def to_unicode(s):
| """
Convert strings to Unicode objects (and return all other data types
unchanged).
"""
if isinstance(s, six.string_types):
return force_text(s)
return s
| .is_naive(value):
value = value.replace(tzinfo=timezone.utc)
elif desc[1] in (Database.STRING, Database.FIXED_CHAR,
Database.LONG_STRING):
value = to_unicode(value)
casted.append(value)
return tuple(casted)
def to_unicode(s):
| 64 | 64 | 45 | 5 | 59 | victorgama/django | django/db/backends/oracle/base.py | Python | to_unicode | to_unicode | 1,019 | 1,026 | 1,019 | 1,019 | fdf2e9b7bfb716c6bf70abf4c67c1b353cac0a7b | bigcode/the-stack | train |
0b5fa9076da898a5c4d26025 | train | class | class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'oracle'
operators = _UninitializedOperatorsDescriptor()
_standard_operators = {
'exact': '= %s',
'iexact': '= UPPER(%s)',
'contains': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
'icontains':... | class DatabaseWrapper(BaseDatabaseWrapper):
| vendor = 'oracle'
operators = _UninitializedOperatorsDescriptor()
_standard_operators = {
'exact': '= %s',
'iexact': '= UPPER(%s)',
'contains': "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)",
'icontains': "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) E... | return super(DatabaseOperations, self).combine_expression(connector, sub_expressions)
def _get_sequence_name(self, table):
name_length = self.max_name_length() - 3
return '%s_SQ' % backend_utils.truncate_name(table, name_length).upper()
def _get_trigger_name(self, table):
name_... | 256 | 256 | 1,748 | 7 | 249 | victorgama/django | django/db/backends/oracle/base.py | Python | DatabaseWrapper | DatabaseWrapper | 550 | 728 | 550 | 550 | c8ffbdb74d952016114cfd2a987d58751cce7538 | bigcode/the-stack | train |
b9598f752174e0fa00df3b2e | train | function | def _get_sequence_reset_sql():
# TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.
return """
DECLARE
table_value integer;
seq_value integer;
BEGIN
SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s;
SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences... | def _get_sequence_reset_sql():
# TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.
| return """
DECLARE
table_value integer;
seq_value integer;
BEGIN
SELECT NVL(MAX(%(column)s), 0) INTO table_value FROM %(table)s;
SELECT NVL(last_number - cache_size, 0) INTO seq_value FROM user_sequences
WHERE sequence_name = '%(sequence)s';
WHILE table_value > seq_value LOOP
... | """
Convert strings to Unicode objects (and return all other data types
unchanged).
"""
if isinstance(s, six.string_types):
return force_text(s)
return s
def _get_sequence_reset_sql():
# TODO: colorize this SQL code with style.SQL_KEYWORD(), etc.
| 64 | 64 | 124 | 24 | 39 | victorgama/django | django/db/backends/oracle/base.py | Python | _get_sequence_reset_sql | _get_sequence_reset_sql | 1,029 | 1,043 | 1,029 | 1,030 | bbf787b55aebe46470081e7c26a20727eab77d53 | bigcode/the-stack | train |
6fec1d30d8bbdff6ed981bc0 | train | class | class Oracle_datetime(datetime.datetime):
"""
A datetime object, with an additional class attribute
to tell cx_Oracle to save the microseconds too.
"""
input_size = Database.TIMESTAMP
@classmethod
def from_datetime(cls, dt):
return Oracle_datetime(dt.year, dt.month, dt.day,
... | class Oracle_datetime(datetime.datetime):
| """
A datetime object, with an additional class attribute
to tell cx_Oracle to save the microseconds too.
"""
input_size = Database.TIMESTAMP
@classmethod
def from_datetime(cls, dt):
return Oracle_datetime(dt.year, dt.month, dt.day,
dt.hour, dt.minute,... | if int(Database.version.split('.', 1)[0]) >= 5 and \
(int(Database.version.split('.', 2)[1]) >= 1 or
not hasattr(Database, 'UNICODE')):
convert_unicode = force_text
else:
convert_unicode = force_bytes
class Oracle_datetime(datetime.datetime):
| 64 | 64 | 81 | 6 | 57 | victorgama/django | django/db/backends/oracle/base.py | Python | Oracle_datetime | Oracle_datetime | 81 | 91 | 81 | 81 | 22aa5ec3caa00505e0a33a84d5a57f467390cb90 | bigcode/the-stack | train |
53e43fca2f8104278f300764 | train | class | class VariableWrapper(object):
"""
An adapter class for cursor variables that prevents the wrapped object
from being converted into a string when used to instantiate an OracleParam.
This can be used generally for any other object that should be passed into
Cursor.execute as-is.
"""
def __in... | class VariableWrapper(object):
| """
An adapter class for cursor variables that prevents the wrapped object
from being converted into a string when used to instantiate an OracleParam.
This can be used generally for any other object that should be passed into
Cursor.execute as-is.
"""
def __init__(self, var):
self.v... | attribute, use that.
self.input_size = param.input_size
elif string_size > 4000:
# Mark any string param greater than 4000 characters as a CLOB.
self.input_size = Database.CLOB
else:
self.input_size = None
class VariableWrapper(object):
| 64 | 64 | 146 | 5 | 58 | victorgama/django | django/db/backends/oracle/base.py | Python | VariableWrapper | VariableWrapper | 783 | 804 | 783 | 783 | 77a7dbf72c29f448818fce0fbb5615de85cc080b | bigcode/the-stack | train |
4e554dcebd6a501753a0dc0a | train | class | class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "django.db.backends.oracle.compiler"
# Oracle uses NUMBER(11) and NUMBER(19) for integer fields.
integer_field_ranges = {
'SmallIntegerField': (-99999999999, 99999999999),
'IntegerField': (-99999999999, 99999999999),
... | class DatabaseOperations(BaseDatabaseOperations):
| compiler_module = "django.db.backends.oracle.compiler"
# Oracle uses NUMBER(11) and NUMBER(19) for integer fields.
integer_field_ranges = {
'SmallIntegerField': (-99999999999, 99999999999),
'IntegerField': (-99999999999, 99999999999),
'BigIntegerField': (-9999999999999999999, 999999... | ):
empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
can_release_savepoints = False
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_insert = True
allow_sliced_subqueries = ... | 256 | 256 | 4,091 | 7 | 248 | victorgama/django | django/db/backends/oracle/base.py | Python | DatabaseOperations | DatabaseOperations | 126 | 534 | 126 | 126 | 77afcbf8c07d2a7c3794196564f5b5fdb454b739 | bigcode/the-stack | train |
a94ed2e39a8c0076d89853c8 | train | class | class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
can_release_savepoints = False
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_i... | class DatabaseFeatures(BaseDatabaseFeatures):
| empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
can_release_savepoints = False
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_insert = True
allow_sliced_subqueries = Fal... | , with an additional class attribute
to tell cx_Oracle to save the microseconds too.
"""
input_size = Database.TIMESTAMP
@classmethod
def from_datetime(cls, dt):
return Oracle_datetime(dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.microsecond)
c... | 76 | 76 | 255 | 7 | 69 | victorgama/django | django/db/backends/oracle/base.py | Python | DatabaseFeatures | DatabaseFeatures | 94 | 123 | 94 | 94 | 20d865917a8dc9e843158f7eaa041aac3b0d770a | bigcode/the-stack | train |
3183d01708e864d53a1a8058 | train | class | class OracleParam(object):
"""
Wrapper object for formatting parameters for Oracle. If the string
representation of the value is large enough (greater than 4000 characters)
the input size needs to be set as CLOB. Alternatively, if the parameter
has an `input_size` attribute, then the value of the `i... | class OracleParam(object):
| """
Wrapper object for formatting parameters for Oracle. If the string
representation of the value is large enough (greater than 4000 characters)
the input size needs to be set as CLOB. Alternatively, if the parameter
has an `input_size` attribute, then the value of the `input_size` attribute
wi... | self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
def is_usable(self):
try:
if hasattr(self.connection, 'ping'): # Oracle 10g R2 and higher
self.connection.ping()
else:
# Use a cx_Oracle cursor directly, bypassing Django's utilities.
... | 150 | 150 | 500 | 5 | 144 | victorgama/django | django/db/backends/oracle/base.py | Python | OracleParam | OracleParam | 731 | 780 | 731 | 731 | 6970ecbf45ad6ea3a5fcd4dc41ddb83051c4a0ae | bigcode/the-stack | train |
92b5ca0f0b1b4b7b1b4728d5 | train | class | class SampleCreateRequest(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map... | class SampleCreateRequest(object):
| """NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
... | # coding: utf-8
"""
Lightly API
Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@lightly... | 131 | 256 | 1,052 | 6 | 124 | Tekrific/lightly | lightly/openapi_generated/swagger_client/models/sample_create_request.py | Python | SampleCreateRequest | SampleCreateRequest | 22 | 176 | 22 | 22 | ed0245547ff930887133aad058f519539debf008 | bigcode/the-stack | train |
024813603ee384689ff17073 | train | function | def get_package_version(dep_name, default="NOT INSTALLED or UNKNOWN VERSION."):
"""
Try to load package and get version. If not found, return `default`.
"""
dep, has_dep = optional_import(dep_name)
if has_dep and hasattr(dep, "__version__"):
return dep.__version__
return default
| def get_package_version(dep_name, default="NOT INSTALLED or UNKNOWN VERSION."):
| """
Try to load package and get version. If not found, return `default`.
"""
dep, has_dep = optional_import(dep_name)
if has_dep and hasattr(dep, "__version__"):
return dep.__version__
return default
| else:
warnings.warn(err_msg)
return call_obj(*args, **kwargs)
if is_func:
return _wrapper
obj.__init__ = _wrapper
return obj
return _decorator
def get_package_version(dep_name, default="NOT INSTALLED or UNKNOWN VERSION."):
| 64 | 64 | 71 | 17 | 46 | nvahmadi/MONAI | monai/utils/module.py | Python | get_package_version | get_package_version | 429 | 436 | 429 | 429 | 2c3546c2bf7a0b232340f89eb6e1e4ca13e28f17 | bigcode/the-stack | train |
39d72a8d09e6d03e399136fa | train | function | def damerau_levenshtein_distance(s1: str, s2: str):
"""
Calculates the Damerau–Levenshtein distance between two strings for spelling correction.
https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
"""
if s1 == s2:
return 0
string_1_length = len(s1)
string_2_length = len(s2)
... | def damerau_levenshtein_distance(s1: str, s2: str):
| """
Calculates the Damerau–Levenshtein distance between two strings for spelling correction.
https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
"""
if s1 == s2:
return 0
string_1_length = len(s1)
string_2_length = len(s2)
if not s1:
return string_2_length
if n... | guess_at_spelling = min(edit_dists, key=edit_dists.get) # type: ignore
raise ValueError(
f"By '{opt_str}', did you mean '{guess_at_spelling}'?\n"
+ f"'{opt_str}' is not a valid value.\n"
+ supported_msg
)
raise ValueError(f"Unsupported option '{opt_str}',... | 108 | 108 | 362 | 19 | 89 | nvahmadi/MONAI | monai/utils/module.py | Python | damerau_levenshtein_distance | damerau_levenshtein_distance | 128 | 154 | 128 | 128 | 6bcaa76f473cbfcde321badbc60962bf2ce3993f | bigcode/the-stack | train |
0e8e634fdda8a0df10645be4 | train | function | def exact_version(the_module, version_str: str = "") -> bool:
"""
Returns True if the module's __version__ matches version_str
"""
if not hasattr(the_module, "__version__"):
warnings.warn(f"{the_module} has no attribute __version__ in exact_version check.")
return False
return bool(t... | def exact_version(the_module, version_str: str = "") -> bool:
| """
Returns True if the module's __version__ matches version_str
"""
if not hasattr(the_module, "__version__"):
warnings.warn(f"{the_module} has no attribute __version__ in exact_version check.")
return False
return bool(the_module.__version__ == version_str)
|
mod_version = tuple(int(x) for x in the_module.__version__.split(".")[:2])
required = tuple(int(x) for x in min_version_str.split(".")[:2])
return mod_version >= required
def exact_version(the_module, version_str: str = "") -> bool:
| 64 | 64 | 79 | 15 | 48 | nvahmadi/MONAI | monai/utils/module.py | Python | exact_version | exact_version | 252 | 259 | 252 | 252 | 7fe8ce6eee0e41590014a622e5bacafd2e46fea1 | bigcode/the-stack | train |
c8302044124d089c9690e8f8 | train | function | def require_pkg(
pkg_name: str, version: str = "", version_checker: Callable[..., bool] = min_version, raise_error: bool = True
):
"""
Decorator function to check the required package installation.
Args:
pkg_name: required package name, like: "itk", "nibabel", etc.
version: required ver... | def require_pkg(
pkg_name: str, version: str = "", version_checker: Callable[..., bool] = min_version, raise_error: bool = True
):
| """
Decorator function to check the required package installation.
Args:
pkg_name: required package name, like: "itk", "nibabel", etc.
version: required version string used by the version_checker.
version_checker: a callable to check the module version, defaults to `monai.utils.min_... | method.
"""
raise self._exception
def __call__(self, *_args, **_kwargs):
"""
Raises:
OptionalImportError: When you call this method.
"""
raise self._exception
return _LazyRaise(), False
def require_pkg(
pkg_name: ... | 90 | 90 | 302 | 34 | 55 | nvahmadi/MONAI | monai/utils/module.py | Python | require_pkg | require_pkg | 390 | 426 | 390 | 392 | db9792e54af646c5b2987f829e621eabd8aada8f | bigcode/the-stack | train |
c259ee89db063062e18168ff | train | function | def look_up_option(opt_str, supported: Union[Collection, enum.EnumMeta], default="no_default", print_all_options=True):
"""
Look up the option in the supported collection and return the matched item.
Raise a value error possibly with a guess of the closest match.
Args:
opt_str: The option strin... | def look_up_option(opt_str, supported: Union[Collection, enum.EnumMeta], default="no_default", print_all_options=True):
| """
Look up the option in the supported collection and return the matched item.
Raise a value error possibly with a guess of the closest match.
Args:
opt_str: The option string or Enum to look up.
supported: The collection of supported options, it can be list, tuple, set, dict, or Enum.... | language governing permissions and
# limitations under the License.
import enum
import os
import re
import sys
import warnings
from functools import partial, wraps
from importlib import import_module
from inspect import isclass, isfunction, ismethod
from pkgutil import walk_packages
from pydoc import locate
from re i... | 244 | 244 | 815 | 27 | 217 | nvahmadi/MONAI | monai/utils/module.py | Python | look_up_option | look_up_option | 50 | 125 | 50 | 50 | 675842228a5462ef2e8770d2d1f41298bfb5ef37 | bigcode/the-stack | train |
017db69c9ebd6699901732bb | train | function | def optional_import(
module: str,
version: str = "",
version_checker: Callable[..., bool] = min_version,
name: str = "",
descriptor: str = OPTIONAL_IMPORT_MSG_FMT,
version_args=None,
allow_namespace_pkg: bool = False,
) -> Tuple[Any, bool]:
"""
Imports an optional module specified by... | def optional_import(
module: str,
version: str = "",
version_checker: Callable[..., bool] = min_version,
name: str = "",
descriptor: str = OPTIONAL_IMPORT_MSG_FMT,
version_args=None,
allow_namespace_pkg: bool = False,
) -> Tuple[Any, bool]:
| """
Imports an optional module specified by `module` string.
Any importing related exceptions will be stored, and exceptions raise lazily
when attempting to use the failed-to-import module.
Args:
module: name of the module to be imported.
version: version string used by the version_... | (x) for x in min_version_str.split(".")[:2])
return mod_version >= required
def exact_version(the_module, version_str: str = "") -> bool:
"""
Returns True if the module's __version__ matches version_str
"""
if not hasattr(the_module, "__version__"):
warnings.warn(f"{the_module} has no attr... | 255 | 256 | 998 | 64 | 191 | nvahmadi/MONAI | monai/utils/module.py | Python | optional_import | optional_import | 279 | 387 | 279 | 287 | 87e4f36ac5fcd128c2564ba06c4fbd075632d7a8 | bigcode/the-stack | train |
da85a5ff615a7cd96daf77a0 | train | function | def get_full_type_name(typeobj):
"""
Utility to get the full path name of a class or object type.
"""
module = typeobj.__module__
if module is None or module == str.__class__.__module__:
return typeobj.__name__ # Avoid reporting __builtin__
return module + "." + typeobj.__name__
| def get_full_type_name(typeobj):
| """
Utility to get the full path name of a class or object type.
"""
module = typeobj.__module__
if module is None or module == str.__class__.__module__:
return typeobj.__name__ # Avoid reporting __builtin__
return module + "." + typeobj.__name__
| function(component) or (ismethod(component) and isclass(getattr(component, "__self__", None))):
return partial(component, **kwargs)
warnings.warn(f"Component to instantiate must represent a valid class or function, but got {path}.")
return component
def get_full_type_name(typeobj):
| 64 | 64 | 75 | 8 | 55 | nvahmadi/MONAI | monai/utils/module.py | Python | get_full_type_name | get_full_type_name | 226 | 234 | 226 | 226 | 5e788c7db2cd196ec118f62c78c4158693e3e63c | bigcode/the-stack | train |
f9eba87d64e77ab679c855ef | train | function | def version_leq(lhs: str, rhs: str):
"""
Returns True if version `lhs` is earlier or equal to `rhs`.
Args:
lhs: version name to compare with `rhs`, return True if earlier or equal to `rhs`.
rhs: version name to compare with `lhs`, return True if later or equal to `lhs`.
"""
lhs, r... | def version_leq(lhs: str, rhs: str):
| """
Returns True if version `lhs` is earlier or equal to `rhs`.
Args:
lhs: version name to compare with `rhs`, return True if earlier or equal to `rhs`.
rhs: version name to compare with `lhs`, return True if later or equal to `lhs`.
"""
lhs, rhs = str(lhs), str(rhs)
pkging, h... | not found, return `default`.
"""
dep, has_dep = optional_import(dep_name)
if has_dep and hasattr(dep, "__version__"):
return dep.__version__
return default
def get_torch_version_tuple():
"""
Returns:
tuple of ints represents the pytorch major/minor version.
"""
return ... | 100 | 100 | 334 | 12 | 88 | nvahmadi/MONAI | monai/utils/module.py | Python | version_leq | version_leq | 447 | 490 | 447 | 447 | 07706bd53e201232c3945385490b0c614ac57c79 | bigcode/the-stack | train |
40c22e3c6ad6d5351362a8eb | train | function | def instantiate(path: str, **kwargs):
"""
Create an object instance or partial function from a class or function represented by string.
`kwargs` will be part of the input arguments to the class constructor or function.
The target component must be a class or a function, if not, return the component dire... | def instantiate(path: str, **kwargs):
| """
Create an object instance or partial function from a class or function represented by string.
`kwargs` will be part of the input arguments to the class constructor or function.
The target component must be a class or a function, if not, return the component directly.
Args:
path: full pa... | import_module(name)
importer.find_module(name).load_module(name) # type: ignore
submodules.append(mod)
except OptionalImportError:
pass # could not import the optional deps., they are ignored
return submodules, err_mod
def instantiate(path: str, **kwar... | 64 | 64 | 214 | 9 | 54 | nvahmadi/MONAI | monai/utils/module.py | Python | instantiate | instantiate | 200 | 223 | 200 | 200 | 449847545baf145e46974b1655076cfead9a5429 | bigcode/the-stack | train |
da4f61014593b8a1332804f1 | train | function | def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"):
"""
Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if
`load_all` is True, excluding anything whose name matches `exclude_pattern`.
"""
s... | def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"):
| """
Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if
`load_all` is True, excluding anything whose name matches `exclude_pattern`.
"""
submodules = []
err_mod: List[str] = []
for importer, name, is_pkg in walk_packages(
... | (obj, "__aliases__", ()):
if not hasattr(mod, alias):
setattr(mod, alias, obj)
return obj
return _inner
def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"):
| 65 | 65 | 217 | 33 | 31 | nvahmadi/MONAI | monai/utils/module.py | Python | load_submodules | load_submodules | 179 | 197 | 179 | 179 | 8d0cc4c9a925d9322ed5630bdb689a45f131626b | bigcode/the-stack | train |
fa27bfe226fbc9fdab786d29 | train | class | class OptionalImportError(ImportError):
"""
Could not import APIs from an optional dependency.
"""
| class OptionalImportError(ImportError):
| """
Could not import APIs from an optional dependency.
"""
| called function or method requires a more recent
PyTorch version than that installed.
"""
def __init__(self, required_version, name):
message = f"{name} requires PyTorch version {required_version} or later"
super().__init__(message)
class OptionalImportError(ImportError):
| 64 | 64 | 22 | 8 | 56 | nvahmadi/MONAI | monai/utils/module.py | Python | OptionalImportError | OptionalImportError | 273 | 276 | 273 | 273 | 4fc8cee3c5fb9b67771522fc92f90936339d9bf2 | bigcode/the-stack | train |
2f6c4393483f1d8508ae1085 | train | function | def min_version(the_module, min_version_str: str = "") -> bool:
"""
Convert version strings into tuples of int and compare them.
Returns True if the module's version is greater or equal to the 'min_version'.
When min_version_str is not provided, it always returns True.
"""
if not min_version_st... | def min_version(the_module, min_version_str: str = "") -> bool:
| """
Convert version strings into tuples of int and compare them.
Returns True if the module's version is greater or equal to the 'min_version'.
When min_version_str is not provided, it always returns True.
"""
if not min_version_str or not hasattr(the_module, "__version__"):
return True... | module = typeobj.__module__
if module is None or module == str.__class__.__module__:
return typeobj.__name__ # Avoid reporting __builtin__
return module + "." + typeobj.__name__
def min_version(the_module, min_version_str: str = "") -> bool:
| 63 | 64 | 137 | 16 | 47 | nvahmadi/MONAI | monai/utils/module.py | Python | min_version | min_version | 237 | 249 | 237 | 237 | 534d753a7ac71e834897c2ea31c4cb614f5528d9 | bigcode/the-stack | train |
553adbb790997d28f0bdf2ab | train | function | def pytorch_after(major, minor, patch=0, current_ver_string=None) -> bool:
"""
Compute whether the current pytorch version is after or equal to the specified version.
The current system pytorch version is determined by `torch.__version__` or
via system environment variable `PYTORCH_VER`.
Args:
... | def pytorch_after(major, minor, patch=0, current_ver_string=None) -> bool:
| """
Compute whether the current pytorch version is after or equal to the specified version.
The current system pytorch version is determined by `torch.__version__` or
via system environment variable `PYTORCH_VER`.
Args:
major: major version number to be compared with
minor: minor ve... | # remove git version suffixes if present
lhs = lhs.split("+", 1)[0]
rhs = rhs.split("+", 1)[0]
# parse the version strings in this basic way without `packaging` package
lhs_ = map(_try_cast, lhs.split("."))
rhs_ = map(_try_cast, rhs.split("."))
for l, r in zip(lhs_, rhs_):
if l != r:
... | 149 | 149 | 497 | 21 | 127 | nvahmadi/MONAI | monai/utils/module.py | Python | pytorch_after | pytorch_after | 493 | 540 | 493 | 493 | 2e17c52f12193066cd0967d8cd4e286ffc836468 | bigcode/the-stack | train |
3aee57d640b658b4f1f7babe | train | class | class InvalidPyTorchVersionError(Exception):
"""
Raised when called function or method requires a more recent
PyTorch version than that installed.
"""
def __init__(self, required_version, name):
message = f"{name} requires PyTorch version {required_version} or later"
super().__init_... | class InvalidPyTorchVersionError(Exception):
| """
Raised when called function or method requires a more recent
PyTorch version than that installed.
"""
def __init__(self, required_version, name):
message = f"{name} requires PyTorch version {required_version} or later"
super().__init__(message)
| 's __version__ matches version_str
"""
if not hasattr(the_module, "__version__"):
warnings.warn(f"{the_module} has no attribute __version__ in exact_version check.")
return False
return bool(the_module.__version__ == version_str)
class InvalidPyTorchVersionError(Exception):
| 64 | 64 | 69 | 8 | 56 | nvahmadi/MONAI | monai/utils/module.py | Python | InvalidPyTorchVersionError | InvalidPyTorchVersionError | 262 | 270 | 262 | 262 | f074160d59c8a5feb52b70a666a9170929fff75f | bigcode/the-stack | train |
2024b336752f366b107f9ec0 | train | function | def export(modname):
"""
Make the decorated object a member of the named module. This will also add the object under its aliases if it has
a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias
names which conflict with package names or existing ... | def export(modname):
| """
Make the decorated object a member of the named module. This will also add the object under its aliases if it has
a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias
names which conflict with package names or existing members will be ignor... | ] == s2j:
d[(i, j)] = min(d[(i, j)], d[i - 2, j - 2] + cost) # transposition
return d[string_1_length - 1, string_2_length - 1]
def export(modname):
| 64 | 64 | 162 | 5 | 59 | nvahmadi/MONAI | monai/utils/module.py | Python | export | export | 157 | 176 | 157 | 157 | 659a9c64171748400200a97ba7924bb8532252d5 | bigcode/the-stack | train |
48ffefa92f3032f7b62cc996 | train | function | def get_torch_version_tuple():
"""
Returns:
tuple of ints represents the pytorch major/minor version.
"""
return tuple(int(x) for x in torch.__version__.split(".")[:2])
| def get_torch_version_tuple():
| """
Returns:
tuple of ints represents the pytorch major/minor version.
"""
return tuple(int(x) for x in torch.__version__.split(".")[:2])
| VERSION."):
"""
Try to load package and get version. If not found, return `default`.
"""
dep, has_dep = optional_import(dep_name)
if has_dep and hasattr(dep, "__version__"):
return dep.__version__
return default
def get_torch_version_tuple():
| 64 | 64 | 46 | 7 | 56 | nvahmadi/MONAI | monai/utils/module.py | Python | get_torch_version_tuple | get_torch_version_tuple | 439 | 444 | 439 | 439 | 56d71e7c1f62d26b43c5326c2b666e101b553140 | bigcode/the-stack | train |
eb0e3b0533908feaaf34d986 | train | function | def test_tdan_net():
"""Test TDANNet."""
# gpu (DCN is avaialble only on GPU)
if torch.cuda.is_available():
tdan = TDANNet().cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
tdan.init_weights(pretrained=None)
output = tdan(input_tensor)
assert len(output) ==... | def test_tdan_net():
| """Test TDANNet."""
# gpu (DCN is avaialble only on GPU)
if torch.cuda.is_available():
tdan = TDANNet().cuda()
input_tensor = torch.rand(1, 5, 3, 64, 64).cuda()
tdan.init_weights(pretrained=None)
output = tdan(input_tensor)
assert len(output) == 2 # (1) HR center +... | import pytest
import torch
from mmedit.models.backbones.sr_backbones.tdan_net import TDANNet
def test_tdan_net():
| 31 | 64 | 188 | 6 | 24 | ChenShuwei1001/mmediting | tests/test_models/test_backbones/test_sr_backbones/test_tdan_net.py | Python | test_tdan_net | test_tdan_net | 7 | 23 | 7 | 7 | 0277191fb2c4be92a371fd60c14531f7eb7962c6 | bigcode/the-stack | train |
be3d0146578b0c765a881bb1 | train | function | def train(images_folder, num_refinement_stages, base_lr, batch_size, batches_per_iter,
num_workers, checkpoint_path, weights_only, from_mobilenet, checkpoints_folder,
log_after, checkpoint_after,num_kps,finetune=False):
net = SinglePersonPoseEstimationWithMobileNet(num_refinement_stages=num_refi... | def train(images_folder, num_refinement_stages, base_lr, batch_size, batches_per_iter,
num_workers, checkpoint_path, weights_only, from_mobilenet, checkpoints_folder,
log_after, checkpoint_after,num_kps,finetune=False):
| net = SinglePersonPoseEstimationWithMobileNet(num_refinement_stages=num_refinement_stages,num_heatmaps=num_kps+1).cuda()
stride = 8
sigma = 7
# num of kps is default 16 ,+bg=17
# the img size is arbitrary , flip may not need
data_flag = "real" if images_folder.split("/")[-1] == "data_lip" else "... | 2
import os
import time
import torch
from torch.nn import DataParallel
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms
from datasets.lip import LipTrainDataset, LipValDataset
from datasets.anime import AnimeTrainDataset,AnimeValDataset
from datasets.transformatio... | 256 | 256 | 1,691 | 54 | 201 | XiaoSanGit/Real2Animation-video-generation | pose_estimate/gccpm-look-into/train.py | Python | train | train | 28 | 176 | 28 | 30 | 64f768cb73f72c4fb4f0aa7b607525c34dc29841 | bigcode/the-stack | train |
ab072044f8c7061ae7535a38 | train | class | class NeutronPodVIFDriver(test_base.TestCase):
@mock.patch('kuryr_kubernetes.os_vif_util.neutron_to_osvif_vif')
def test_request_vif(self, m_to_vif):
cls = neutron_vif.NeutronPodVIFDriver
m_driver = mock.Mock(spec=cls)
neutron = self.useFixture(k_fix.MockNeutronClient()).client
... | class NeutronPodVIFDriver(test_base.TestCase):
@mock.patch('kuryr_kubernetes.os_vif_util.neutron_to_osvif_vif')
| def test_request_vif(self, m_to_vif):
cls = neutron_vif.NeutronPodVIFDriver
m_driver = mock.Mock(spec=cls)
neutron = self.useFixture(k_fix.MockNeutronClient()).client
pod = mock.sentinel.pod
project_id = mock.sentinel.project_id
subnets = mock.sentinel.subnets
... | 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 applicable law or agreed to in writing, software
# distr... | 256 | 256 | 3,005 | 34 | 221 | BoringWenn/kuryr-kubernetes | kuryr_kubernetes/tests/unit/controller/drivers/test_neutron_vif.py | Python | NeutronPodVIFDriver | NeutronPodVIFDriver | 29 | 349 | 29 | 31 | 205bb3177bdd773a8dcab15c74994a07537592ef | bigcode/the-stack | train |
4d1a365b0a6c0590a39b0708 | train | function | def _duration_handler(time1, lang=None, speech=True, *, time2=None,
use_years=True, clock=False,
resolution=TimeResolution.SECONDS):
"""Convert duration in seconds to a nice spoken timespan.
Used as a handler by nice_duration and nice_duration_dt.
Accepts:
... | def _duration_handler(time1, lang=None, speech=True, *, time2=None,
use_years=True, clock=False,
resolution=TimeResolution.SECONDS):
| """Convert duration in seconds to a nice spoken timespan.
Used as a handler by nice_duration and nice_duration_dt.
Accepts:
datetime.timedelta, or
seconds (int/float), or
2 x datetime.datetime
Examples:
time1 = 60 -> "1:00" or "one minute"
time1 = 163 -> "2:4... | actual parsing. However methods may be wrapped specifically for
use in Mycroft Skills.
"""
import datetime
import warnings
from calendar import leapdays
from enum import Enum
# These are the main functions we are using lingua franca to provide
from lingua_franca import get_default_loc
# TODO 21.08 - move nice_durati... | 256 | 256 | 2,125 | 34 | 221 | PureTryOut/mycroft-core | mycroft/util/format.py | Python | _duration_handler | _duration_handler | 62 | 299 | 62 | 64 | ab33a0e254a77279c203944678888b434f081c66 | bigcode/the-stack | train |
2e8699f48fdd316c9ade3f52 | train | class | class TimeResolution(Enum):
YEARS = 1
DAYS = 2
HOURS = 3
MINUTES = 4
SECONDS = 5
MILLISECONDS = 6
| class TimeResolution(Enum):
| YEARS = 1
DAYS = 2
HOURS = 3
MINUTES = 4
SECONDS = 5
MILLISECONDS = 6
| - remove import of private method _translate_word
# Consider whether the remaining items here are necessary.
from lingua_franca.format import (NUMBER_TUPLE, DateTimeFormat,
date_time_format, expand_options,
_translate_word)
from padatious.util import ... | 64 | 64 | 45 | 5 | 58 | PureTryOut/mycroft-core | mycroft/util/format.py | Python | TimeResolution | TimeResolution | 53 | 59 | 53 | 53 | c8963cf444bf940b5c51bfac62a8ba332f971cf1 | bigcode/the-stack | train |
99a4b859869b8d5ff622ef3d | train | function | def nice_duration(duration, lang=None, speech=True, use_years=True,
clock=False, resolution=TimeResolution.SECONDS):
""" Convert duration in seconds to a nice spoken timespan
Accepts:
time, in seconds, or datetime.timedelta
Examples:
duration = 60 -> "1:00" or "one minut... | def nice_duration(duration, lang=None, speech=True, use_years=True,
clock=False, resolution=TimeResolution.SECONDS):
| """ Convert duration in seconds to a nice spoken timespan
Accepts:
time, in seconds, or datetime.timedelta
Examples:
duration = 60 -> "1:00" or "one minute"
duration = 163 -> "2:43" or "two minutes forty three seconds"
duration = timedelta(seconds=120) -> "2:00" or "two ... | TimeResolution.HOURS:
out += "hours" if speech else "h"
elif _input_resolution == TimeResolution.MINUTES:
if speech:
out = "under a minute" if seconds > 0 else "zero minutes"
else:
out = "0m"
else:
out = "zero seconds" if s... | 108 | 108 | 361 | 26 | 81 | PureTryOut/mycroft-core | mycroft/util/format.py | Python | nice_duration | nice_duration | 302 | 342 | 302 | 303 | c76c549a4dd6f6d48890c35e53f6f62bb178c387 | bigcode/the-stack | train |
d47339c245230a35657ecb2a | train | function | def nice_duration_dt(date1, date2, lang=None, speech=True, use_years=True,
clock=False, resolution=TimeResolution.SECONDS):
""" Convert duration between datetimes to a nice spoken timespan
Accepts:
2 x datetime.datetime
Examples:
date1 = datetime(2019, 3, 12),
... | def nice_duration_dt(date1, date2, lang=None, speech=True, use_years=True,
clock=False, resolution=TimeResolution.SECONDS):
| """ Convert duration between datetimes to a nice spoken timespan
Accepts:
2 x datetime.datetime
Examples:
date1 = datetime(2019, 3, 12),
date2 = datetime(2019, 1, 1) -> "seventy days"
date1 = datetime(2019, 12, 25, 20, 30),
date2 = datetime(2019, 10, 31, 8, 00),
... | TimeResolution.MILLISECONDS
NOTE: nice_duration will not produce milliseconds
unless that resolution is passed.
NOTE: clock will produce digital clock-like output appropriate to
resolution. Has no effect on resolutions DAYS or YEARS. Only
app... | 133 | 133 | 446 | 31 | 102 | PureTryOut/mycroft-core | mycroft/util/format.py | Python | nice_duration_dt | nice_duration_dt | 345 | 393 | 345 | 346 | 39c9feb372c6a618757b8f71e99af973e1140720 | bigcode/the-stack | train |
f632519cb1ade7f9b5df3ef3 | train | function | def node_repositories(
package_json=[],
node_version=DEFAULT_NODE_VERSION,
yarn_version=DEFAULT_YARN_VERSION,
vendored_node=None,
vendored_yarn=None,
node_repositories=NODE_REPOSITORIES,
yarn_repositories=YARN_REPOSITORIES,
node_urls=NODE_URLS,
yarn_urls=YARN_URLS,
preserve_symlinks=True):
"""To b... | def node_repositories(
package_json=[],
node_version=DEFAULT_NODE_VERSION,
yarn_version=DEFAULT_YARN_VERSION,
vendored_node=None,
vendored_yarn=None,
node_repositories=NODE_REPOSITORIES,
yarn_repositories=YARN_REPOSITORIES,
node_urls=NODE_URLS,
yarn_urls=YARN_URLS,
preserve_symlinks=True):
| """To be run in user's WORKSPACE to install rules_nodejs dependencies.
This rule sets up node, npm, and yarn.
The versions of these tools can be specified in one of three ways:
- Normal Usage:
Specify no explicit versions. This will download and use the latest NodeJS & Yarn that were available when the
... | arn_repositories": attr.string_list_dict(default = YARN_REPOSITORIES),
"node_urls": attr.string_list(default = NODE_URLS),
"yarn_urls": attr.string_list(default = YARN_URLS),
"preserve_symlinks": attr.bool(default = True),
},
)
def _yarn_repo_impl(repository_ctx):
# Base build file for this repository ... | 256 | 256 | 1,349 | 85 | 171 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | node_repositories | node_repositories | 449 | 578 | 449 | 459 | 20105ef5ce4a9f61cc2ab8792e9bed4308de23c0 | bigcode/the-stack | train |
42b707de8ddce0a84a791964 | train | function | def _yarn_repo_impl(repository_ctx):
# Base build file for this repository - exposes yarn
repository_ctx.file("BUILD.bazel", content="""#Generated by node_repositories.bzl
package(default_visibility = ["//visibility:public"])
alias(name = "yarn", actual = "{yarn}")
""".format(yarn = get_yarn_node_repositories_label... | def _yarn_repo_impl(repository_ctx):
# Base build file for this repository - exposes yarn
| repository_ctx.file("BUILD.bazel", content="""#Generated by node_repositories.bzl
package(default_visibility = ["//visibility:public"])
alias(name = "yarn", actual = "{yarn}")
""".format(yarn = get_yarn_node_repositories_label(repository_ctx)))
| ": attr.string_list(default = NODE_URLS),
"yarn_urls": attr.string_list(default = YARN_URLS),
"preserve_symlinks": attr.bool(default = True),
},
)
def _yarn_repo_impl(repository_ctx):
# Base build file for this repository - exposes yarn
| 64 | 64 | 80 | 21 | 43 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | _yarn_repo_impl | _yarn_repo_impl | 437 | 442 | 437 | 438 | 4a90c3c7d42523530295fa4169d11cbf1ddd545d | bigcode/the-stack | train |
3588b6dde338a49b384054f7 | train | function | def _download_node(repository_ctx):
"""Used to download a NodeJS runtime package.
Args:
repository_ctx: The repository rule context
"""
if repository_ctx.attr.vendored_node:
return
host = os_name(repository_ctx)
node_version = repository_ctx.attr.node_version
node_repositories = repository_ctx.a... | def _download_node(repository_ctx):
| """Used to download a NodeJS runtime package.
Args:
repository_ctx: The repository rule context
"""
if repository_ctx.attr.vendored_node:
return
host = os_name(repository_ctx)
node_version = repository_ctx.attr.node_version
node_repositories = repository_ctx.attr.node_repositories
node_urls = ... | "node_modules", srcs = glob(["node_modules/**/*"]), visibility = ["//visibility:public"])
# """)
# _write_node_modules = repository_rule(
# _write_node_modules_impl,
# attrs = { "package_json": attr.label() },
# )
def _download_node(repository_ctx):
| 64 | 64 | 199 | 7 | 57 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | _download_node | _download_node | 122 | 148 | 122 | 122 | d96f92d5985ac2ffa4d36dfbe76203d3b23a9c40 | bigcode/the-stack | train |
dd348c869b54719c69e50137 | train | function | def _prepare_node(repository_ctx):
"""Sets up BUILD files and shell wrappers for the versions of NodeJS, npm & yarn just set up.
Windows and other OSes set up the node runtime with different names and paths, which we hide away via
the BUILD file here.
In addition, we create a bash script wrapper around NPM tha... | def _prepare_node(repository_ctx):
| """Sets up BUILD files and shell wrappers for the versions of NodeJS, npm & yarn just set up.
Windows and other OSes set up the node runtime with different names and paths, which we hide away via
the BUILD file here.
In addition, we create a bash script wrapper around NPM that passes a given NPM command to all... | sha256 = node_repositories[node_host_version]
else:
fail("Unknown NodeJS host/version {}".format(node_host_version))
repository_ctx.download_and_extract(
url = [url.format(version = node_version, filename = filename) for url in node_urls],
output = NODE_DIR,
stripPrefix = strip_prefix,
sha256 ... | 256 | 256 | 2,553 | 7 | 249 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | _prepare_node | _prepare_node | 175 | 413 | 175 | 175 | 7366bc8695c5a83b89393ad631652c61670d3b88 | bigcode/the-stack | train |
2a0c2db9564f3da288520b72 | train | function | def _download_yarn(repository_ctx):
"""Used to download a yarn tool package.
Args:
repository_ctx: The repository rule context
"""
if repository_ctx.attr.vendored_yarn:
return
yarn_version = repository_ctx.attr.yarn_version
yarn_repositories = repository_ctx.attr.yarn_repositories
yarn_urls = re... | def _download_yarn(repository_ctx):
| """Used to download a yarn tool package.
Args:
repository_ctx: The repository rule context
"""
if repository_ctx.attr.vendored_yarn:
return
yarn_version = repository_ctx.attr.yarn_version
yarn_repositories = repository_ctx.attr.yarn_repositories
yarn_urls = repository_ctx.attr.yarn_urls
if ya... | {}".format(node_host_version))
repository_ctx.download_and_extract(
url = [url.format(version = node_version, filename = filename) for url in node_urls],
output = NODE_DIR,
stripPrefix = strip_prefix,
sha256 = sha256,
)
def _download_yarn(repository_ctx):
| 64 | 64 | 172 | 8 | 56 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | _download_yarn | _download_yarn | 150 | 173 | 150 | 150 | a4f0ceacf727f57e175bc2ecad60bb4ee95940a0 | bigcode/the-stack | train |
018c493d44454ee94a92f887 | train | function | def _nodejs_repo_impl(repository_ctx):
_download_node(repository_ctx)
_download_yarn(repository_ctx)
_prepare_node(repository_ctx)
| def _nodejs_repo_impl(repository_ctx):
| _download_node(repository_ctx)
_download_yarn(repository_ctx)
_prepare_node(repository_ctx)
| b %errorlevel%
""".format(
root = repository_ctx.path(package_json).dirname,
node = paths.relativize(node_entry, "bin"),
script = yarn_script_relative)
for package_json in repository_ctx.attr.package_json]), executable = True)
def _nodejs_repo_impl(repository_ctx):
| 64 | 64 | 31 | 9 | 55 | peterrevel/rules_nodejs | internal/node/node_repositories.bzl | Python | _nodejs_repo_impl | _nodejs_repo_impl | 415 | 418 | 415 | 415 | 1fd42a43208c6c2489f856a9a35e5652aaf09af0 | bigcode/the-stack | train |
12230399f650dc59c6991866 | train | class | class NumberOfSamplesForm(FlaskForm):
numberofsamples = IntegerField('Antal tidpunkter', validators=[DataRequired(), NumberRange(min=2)])
samplename = StringField('Testnummer', validators=[DataRequired()])
submit = SubmitField('Fortsätt')
| class NumberOfSamplesForm(FlaskForm):
| numberofsamples = IntegerField('Antal tidpunkter', validators=[DataRequired(), NumberRange(min=2)])
samplename = StringField('Testnummer', validators=[DataRequired()])
submit = SubmitField('Fortsätt')
| from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField
from wtforms.validators import DataRequired, NumberRange
class NumberOfSamplesForm(FlaskForm):
| 48 | 64 | 61 | 10 | 37 | viktorlj/MaxOvertime | app/forms.py | Python | NumberOfSamplesForm | NumberOfSamplesForm | 5 | 8 | 5 | 5 | 71b3ecb02893a51e8082438e0511ccd7135c6a56 | bigcode/the-stack | train |
75f366d2cbf076bb58d7a2d9 | train | class | class TestPerson(Record):
pass
| class TestPerson(Record):
| pass
| """
test_records.py
Test the records module
"""
from decimal import Decimal
from datetime import date, time, datetime
import unittest
from zoom.records import Record, RecordStore
from zoom.database import setup_test
class Person(Record):
pass
class TestPerson(Record):
| 60 | 64 | 9 | 6 | 53 | JW709/zoom | tests/unittests/test_records.py | Python | TestPerson | TestPerson | 19 | 20 | 19 | 19 | 64985454f2ffbc0e6d8ab3547e21a2c72e20d67c | bigcode/the-stack | train |
b54a0d3dbd800ce0e879b718 | train | class | class TestRecordStore(unittest.TestCase):
"""RecordStore Tests
Tests the normal case where the table name corresponds to the kind of
object being stored and the ID is id.
"""
def __init__(self, *a, **k):
unittest.TestCase.__init__(self, *a, **k)
self.name = 'person'
self.ke... | class TestRecordStore(unittest.TestCase):
| """RecordStore Tests
Tests the normal case where the table name corresponds to the kind of
object being stored and the ID is id.
"""
def __init__(self, *a, **k):
unittest.TestCase.__init__(self, *a, **k)
self.name = 'person'
self.key = 'id'
@property
def id_name(se... | """
test_records.py
Test the records module
"""
from decimal import Decimal
from datetime import date, time, datetime
import unittest
from zoom.records import Record, RecordStore
from zoom.database import setup_test
class Person(Record):
pass
class TestPerson(Record):
pass
class TestRecordStore(u... | 71 | 256 | 1,243 | 8 | 62 | JW709/zoom | tests/unittests/test_records.py | Python | TestRecordStore | TestRecordStore | 23 | 188 | 23 | 23 | 9b844df5140a9253e8c941bec7eeecbf5bee7410 | bigcode/the-stack | train |
b5ad575b47e63048c3a1f2a0 | train | class | class TestNamedRecordStore(TestRecordStore):
"""Named RecordStore Tests
Tests the case where the table name does not correspond to the kind of
object being stored but is passed in instead, and where the key of the
table is standard.
"""
def __init__(self, *a, **k):
TestRecordStore.__in... | class TestNamedRecordStore(TestRecordStore):
| """Named RecordStore Tests
Tests the case where the table name does not correspond to the kind of
object being stored but is passed in instead, and where the key of the
table is standard.
"""
def __init__(self, *a, **k):
TestRecordStore.__init__(self, *a, **k)
self.name = 'pers... | a, **k):
TestRecordStore.__init__(self, *a, **k)
self.name = 'person'
self.key = 'person_id'
def get_record_store(self):
return RecordStore(self.db, Person, key=self.key)
class TestNamedRecordStore(TestRecordStore):
| 64 | 64 | 118 | 9 | 55 | JW709/zoom | tests/unittests/test_records.py | Python | TestNamedRecordStore | TestNamedRecordStore | 208 | 222 | 208 | 208 | 7b6dcda293b44809a1e0405ca98a7cb413479506 | bigcode/the-stack | train |
3aae2fc31eae55a73ddabea9 | train | class | class Person(Record):
pass
| class Person(Record):
| pass
| """
test_records.py
Test the records module
"""
from decimal import Decimal
from datetime import date, time, datetime
import unittest
from zoom.records import Record, RecordStore
from zoom.database import setup_test
class Person(Record):
| 51 | 64 | 8 | 5 | 45 | JW709/zoom | tests/unittests/test_records.py | Python | Person | Person | 15 | 16 | 15 | 15 | ab48cc2fa09519ab259414aeddbb94c98fdcf460 | bigcode/the-stack | train |
ddb2341ac1402992fd24b527 | train | class | class TestKeyedRecordStore(TestRecordStore):
"""Keyed RecordStore Tests
Tests the case where the table name corresponds to the kind of
object being stored but the key of the table is not standard and is
instead passed in as a parameter.
"""
def __init__(self, *a, **k):
TestRecordStore.... | class TestKeyedRecordStore(TestRecordStore):
| """Keyed RecordStore Tests
Tests the case where the table name corresponds to the kind of
object being stored but the key of the table is not standard and is
instead passed in as a parameter.
"""
def __init__(self, *a, **k):
TestRecordStore.__init__(self, *a, **k)
self.name = '... | _person')
def test_len(self):
self.assertEqual(3, len(self.people))
def test_zap(self):
self.assertEqual(3, len(self.people))
self.people.zap()
self.assertEqual(0, len(self.people))
class TestKeyedRecordStore(TestRecordStore):
| 64 | 64 | 121 | 10 | 54 | JW709/zoom | tests/unittests/test_records.py | Python | TestKeyedRecordStore | TestKeyedRecordStore | 191 | 205 | 191 | 191 | f5b4673c0e6906bff09b26b99c9fc5f138d6403c | bigcode/the-stack | train |
0fcfcb08930ac8c97fb56bd2 | train | class | class TestNamedKeyedRecordStore(TestRecordStore):
"""Named RecordStore Tests
Tests the case where both the table name does not correspond to the kind of
object being stored but is passed in instead, and the key of the
table is passed in rather than using the usual ID column.
"""
def __init__(s... | class TestNamedKeyedRecordStore(TestRecordStore):
| """Named RecordStore Tests
Tests the case where both the table name does not correspond to the kind of
object being stored but is passed in instead, and the key of the
table is passed in rather than using the usual ID column.
"""
def __init__(self, *a, **k):
TestRecordStore.__init__(se... | , **k):
TestRecordStore.__init__(self, *a, **k)
self.name = 'person'
self.key = 'id'
def get_record_store(self):
return RecordStore(self.db, Person, name=self.name)
class TestNamedKeyedRecordStore(TestRecordStore):
| 64 | 64 | 133 | 11 | 53 | JW709/zoom | tests/unittests/test_records.py | Python | TestNamedKeyedRecordStore | TestNamedKeyedRecordStore | 225 | 239 | 225 | 225 | f57cbce3a0d0f91dc241b6abad02784e6dc788fa | bigcode/the-stack | train |
46136913d2150ab0cfb61845 | train | class | class CloudSqlHook(CloudSQLHook):
"""This class is deprecated. Please use `airflow.providers.google.cloud.hooks.sql.CloudSQLHook`."""
def __init__(self, *args, **kwargs):
warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
| class CloudSqlHook(CloudSQLHook):
| """This class is deprecated. Please use `airflow.providers.google.cloud.hooks.sql.CloudSQLHook`."""
def __init__(self, *args, **kwargs):
warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
| flow.providers.google.cloud.hooks.cloud_sql.CloudSQLDatabaseHook`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
class CloudSqlHook(CloudSQLHook):
| 64 | 64 | 72 | 9 | 55 | emilioego/airflow | airflow/contrib/hooks/gcp_sql_hook.py | Python | CloudSqlHook | CloudSqlHook | 42 | 47 | 42 | 42 | a22a772fe8e8cca3edf3a9609b7c9746f061697e | bigcode/the-stack | train |
fce5838a0dcf46c1baa422fa | train | class | class CloudSqlDatabaseHook(CloudSQLDatabaseHook):
"""
This class is deprecated.
Please use `airflow.providers.google.cloud.hooks.cloud_sql.CloudSQLDatabaseHook`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
super().__init__(*... | class CloudSqlDatabaseHook(CloudSQLDatabaseHook):
| """
This class is deprecated.
Please use `airflow.providers.google.cloud.hooks.cloud_sql.CloudSQLDatabaseHook`.
"""
def __init__(self, *args, **kwargs):
warnings.warn(self.__doc__, DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
| .google.cloud.hooks.cloud_sql import CloudSQLDatabaseHook, CloudSQLHook
warnings.warn(
"This module is deprecated. Please use `airflow.providers.google.cloud.hooks.cloud_sql`",
DeprecationWarning,
stacklevel=2,
)
class CloudSqlDatabaseHook(CloudSQLDatabaseHook):
| 64 | 64 | 79 | 11 | 53 | emilioego/airflow | airflow/contrib/hooks/gcp_sql_hook.py | Python | CloudSqlDatabaseHook | CloudSqlDatabaseHook | 31 | 39 | 31 | 31 | 6e8b5e1f5af45771affe8dccd40f5d40e273376a | bigcode/the-stack | train |
b8e192a4e15d677f86e8a905 | train | function | def _check_rows_is_arange_len_labels(rows, labels):
'''Check that 'rows' is the same node as T.arange(labels.shape[0])
Also considers the case where labels.shape[0] is constant and equal
to 1, and T.arange(labels.shape[0]) has been constant-folded into 0.
'''
if labels.owner and hasattr(labels.own... | def _check_rows_is_arange_len_labels(rows, labels):
| '''Check that 'rows' is the same node as T.arange(labels.shape[0])
Also considers the case where labels.shape[0] is constant and equal
to 1, and T.arange(labels.shape[0]) has been constant-folded into 0.
'''
if labels.owner and hasattr(labels.owner.fgraph, 'shape_feature'):
shape_of = labe... | .owner.op in (softmax, softplus, tensor.exp,
tensor.log, tensor.tanh, sigmoid):
pre_x, = x.owner.inputs
return tensor._max_and_argmax(pre_x, axis)
if x.owner and x.owner.op == softmax_with_bias:
pre_x, pre_bias = x.owner.inputs
... | 129 | 129 | 432 | 13 | 115 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | _check_rows_is_arange_len_labels | _check_rows_is_arange_len_labels | 1,451 | 1,488 | 1,451 | 1,451 | c08be89976d7f11cb723d9f0c675587bbd25c114 | bigcode/the-stack | train |
bae7e950d9ef5f12585f7607 | train | function | @gof.optimizer
def crossentropy_to_crossentropy_with_softmax(fgraph):
"""This is a stabilization optimization that is more general then
crossentropy_to_crossentropy_with_softmax_with_bias
It must be executed after local_softmax_with_bias optimization in
specialize
:todo: This is a stabilization op... | @gof.optimizer
def crossentropy_to_crossentropy_with_softmax(fgraph):
| """This is a stabilization optimization that is more general then
crossentropy_to_crossentropy_with_softmax_with_bias
It must be executed after local_softmax_with_bias optimization in
specialize
:todo: This is a stabilization optimization! How to make this more cleanly?
:note: not a local opt... |
new_nll, new_sm, new_am = crossentropy_softmax_argmax_1hot_with_bias(x, b,
one_of_n)
fgraph.replace_all_validate([(nll, new_nll), (sm, new_sm)],
reason="crossentropy_to_crossentropy_with_softmax_with_bias")
return T... | 103 | 103 | 346 | 16 | 86 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_to_crossentropy_with_softmax | crossentropy_to_crossentropy_with_softmax | 1,357 | 1,396 | 1,357 | 1,358 | b044f3a20b207515d6ce3595f8067e263fb4f32d | bigcode/the-stack | train |
dcec938360b3fb7fa848fb11 | train | function | @opt.register_specialize
@gof.local_optimizer([softmax_grad])
def local_advanced_indexing_crossentropy_onehot_grad(node):
if not (node.op == softmax_grad):
return
sm = None
try:
d_sm, sm = node.inputs
except Exception:
return
if (sm is not None) and sm.owner and (sm.owner.o... | @opt.register_specialize
@gof.local_optimizer([softmax_grad])
def local_advanced_indexing_crossentropy_onehot_grad(node):
| if not (node.op == softmax_grad):
return
sm = None
try:
d_sm, sm = node.inputs
except Exception:
return
if (sm is not None) and sm.owner and (sm.owner.op in (softmax,
softmax_with_bias)):
sm_w_bias = local_so... | if node.op == tensor.log:
pre_log = node.inputs[0].owner
if pre_log and isinstance(pre_log.op, subtensor.AdvancedSubtensor):
try:
sm, rows, labels = pre_log.inputs
except Exception:
pass
if sm is not None and sm.owner and sm.owner.op in (soft... | 255 | 256 | 1,886 | 28 | 227 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | local_advanced_indexing_crossentropy_onehot_grad | local_advanced_indexing_crossentropy_onehot_grad | 1,543 | 1,763 | 1,543 | 1,545 | 0e32f0807c61c2e288fbb2b165f89b6ecc96eb44 | bigcode/the-stack | train |
56baa7678325fb5283f1cfde | train | function | def categorical_crossentropy(coding_dist, true_dist):
"""
WARNING: THIS FUNCTION IS UNNECESSARILY POLYMORPHIC.
We ultimately don't want the polymorphism, and will move this function to pylearn.algorithms.cost.
The 1hot version will be removed.
The length of the documentation here is a form of code s... | def categorical_crossentropy(coding_dist, true_dist):
| """
WARNING: THIS FUNCTION IS UNNECESSARILY POLYMORPHIC.
We ultimately don't want the polymorphism, and will move this function to pylearn.algorithms.cost.
The 1hot version will be removed.
The length of the documentation here is a form of code smell.
Return the cross-entropy between an approxi... | exactly 0 or 1 but output must
lie strictly between 0 and 1.
@note: we could use the x log y op to support output=0
@ and output=1. The gradient would still be undefined though.
@note: We do not sum, crossentropy is computed by component.
@todo: Rewrite as a scalar, and then broadcast to tensor.
... | 124 | 124 | 416 | 11 | 113 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | categorical_crossentropy | categorical_crossentropy | 1,794 | 1,834 | 1,794 | 1,794 | 99384b4c21461c821277ab5b6da57b960f038b98 | bigcode/the-stack | train |
36a97c12c8bcca0002cf83d2 | train | function | def _is_const(z, val, approx=False):
try:
maybe = opt.get_scalar_constant_value(z)
except tensor.NotScalarConstantError:
return False
if approx:
return numpy.allclose(maybe, val)
else:
return numpy.all(maybe == val)
| def _is_const(z, val, approx=False):
| try:
maybe = opt.get_scalar_constant_value(z)
except tensor.NotScalarConstantError:
return False
if approx:
return numpy.allclose(maybe, val)
else:
return numpy.all(maybe == val)
| if shape_var.owner and shape_var.owner.op == tensor.shape:
return shape_var.owner.inputs[0] is labels
else:
shape_of = stop.owner.fgraph.shape_feature.shape_of
return shape_of[labels][0] is stop
def _is_const(z, val, approx=False):
| 64 | 64 | 62 | 11 | 52 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | _is_const | _is_const | 1,491 | 1,499 | 1,491 | 1,491 | faa0e233ea8f18ed38b32793624675fa0a445841 | bigcode/the-stack | train |
01d5e25c17fb90fa210e7a6d | train | function | @opt.register_specialize
@gof.local_optimizer([softmax])
def local_softmax_with_bias(node):
"""Try to turn softmax(sum_of_stuff) -> softmax_w_bias(matrix, bias)
"""
if node.op == softmax:
x, = node.inputs
if x.owner and x.owner.op == tensor.add:
vectors = []
non_vecto... | @opt.register_specialize
@gof.local_optimizer([softmax])
def local_softmax_with_bias(node):
| """Try to turn softmax(sum_of_stuff) -> softmax_w_bias(matrix, bias)
"""
if node.op == softmax:
x, = node.inputs
if x.owner and x.owner.op == tensor.add:
vectors = []
non_vectors = []
for x_in in x.owner.inputs:
if list(x_in.type.broadcasta... | % locals()
except theano.gof.utils.MethodNotDefined:
pass
end_row_loop = """
}
"""
return (init_decl, begin_row_loop, inside_row_loop, end_row_loop)
def c_code(self, node, name, inp, out, sub):
x, = inp
sm, = out
code_template = ''.join(... | 153 | 153 | 512 | 22 | 131 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | local_softmax_with_bias | local_softmax_with_bias | 573 | 631 | 573 | 575 | 1e60d72158f99704e337c97c62d1e46989d154a2 | bigcode/the-stack | train |
203a2a706c79f2c67cec0606 | train | class | class CrossentropySoftmaxArgmax1HotWithBias(gof.Op):
"""A special compound L{Op} for the output of neural-net classifiers.
:type x: is a matrix of floats (32 or 64)
:type b: is a [row] vector of floats (32 or 64),
length is number of cols in x
:type y_idx: a [column] vector of int (32 or 6... | class CrossentropySoftmaxArgmax1HotWithBias(gof.Op):
| """A special compound L{Op} for the output of neural-net classifiers.
:type x: is a matrix of floats (32 or 64)
:type b: is a [row] vector of floats (32 or 64),
length is number of cols in x
:type y_idx: a [column] vector of int (32 or 64),
length is number of rows in x
... | _input.owner.inputs[0]
if ((ds_order != (0, 'x')) or
(axis != (1,)) or
(sum_input is not prod_term)):
rest.append(add_in)
#print 'ds_order =', ds_order
#pr... | 255 | 256 | 2,477 | 15 | 240 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | CrossentropySoftmaxArgmax1HotWithBias | CrossentropySoftmaxArgmax1HotWithBias | 780 | 1,033 | 780 | 780 | ba07402b901590adad6dfb37127031e9555fb204 | bigcode/the-stack | train |
bf6f75c94f844bfe07976704 | train | class | class Prepend_scalar_to_each_row(gof.Op):
def __eq__(self, other):
return (type(self) == type(other))
def __hash__(self):
return tensor.hashtype(self)
def __str__(self):
return self.__class__.__name__
def make_node(self, val, mat):
#check type of input
x = tens... | class Prepend_scalar_to_each_row(gof.Op):
| def __eq__(self, other):
return (type(self) == type(other))
def __hash__(self):
return tensor.hashtype(self)
def __str__(self):
return self.__class__.__name__
def make_node(self, val, mat):
#check type of input
x = tensor.as_tensor_variable(mat)
if isin... | output[0] = numpy.empty(new_shape, dtype=mat.dtype)
out = output[0]
out[:, 0].fill(self.val.data)
out[:, 1:] = mat
def infer_shape(self, node, in_shapes):
shp = (in_shapes[0][0], in_shapes[0][1] + 1)
return [shp]
def grad(self, inp, grads):
... | 123 | 124 | 415 | 11 | 112 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | Prepend_scalar_to_each_row | Prepend_scalar_to_each_row | 1,897 | 1,947 | 1,897 | 1,897 | 26c555fffe3b511fed139c06253549603093f281 | bigcode/the-stack | train |
6cc97ec611f002ae3f0b2e96 | train | function | @gof.local_optimizer([softmax_grad])
def local_crossentropy_to_crossentropy_with_softmax_grad(node):
if node.op == softmax_grad:
g_coding_dist, coding_dist = node.inputs
if (g_coding_dist.owner and
g_coding_dist.owner.op == crossentropy_categorical_1hot_grad):
g_nll, coding_d... | @gof.local_optimizer([softmax_grad])
def local_crossentropy_to_crossentropy_with_softmax_grad(node):
| if node.op == softmax_grad:
g_coding_dist, coding_dist = node.inputs
if (g_coding_dist.owner and
g_coding_dist.owner.op == crossentropy_categorical_1hot_grad):
g_nll, coding_dist, true_one_of_n = g_coding_dist.owner.inputs
dx = crossentropy_softmax_1hot_with_bias_... |
return
optdb.register('crossentropy_to_crossentropy_with_softmax',
crossentropy_to_crossentropy_with_softmax, 2.01,
'fast_run', 'xent')
@gof.local_optimizer([softmax_grad])
def local_crossentropy_to_crossentropy_with_softmax_grad(node):
| 64 | 64 | 121 | 22 | 42 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | local_crossentropy_to_crossentropy_with_softmax_grad | local_crossentropy_to_crossentropy_with_softmax_grad | 1,403 | 1,412 | 1,403 | 1,404 | 11b36df46929e77fc5b046c2a620a902c3812213 | bigcode/the-stack | train |
bd376657b35859b7cc7bb803 | train | function | def crossentropy_softmax_1hot(x, y_idx, **kwargs):
b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs)
| def crossentropy_softmax_1hot(x, y_idx, **kwargs):
| b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs)
| def crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs):
return crossentropy_softmax_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)[0:2]
def crossentropy_softmax_1hot(x, y_idx, **kwargs):
| 64 | 64 | 49 | 16 | 48 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_softmax_1hot | crossentropy_softmax_1hot | 1,192 | 1,194 | 1,192 | 1,192 | 26073b74949025ee0aa2ca70cbd1d2c1c7cebdbe | bigcode/the-stack | train |
c863986f0f6c1ef636518daa | train | class | class CrossentropySoftmax1HotWithBiasDx (gof.Op):
nin = 3
nout = 1
"""Gradient wrt x of the CrossentropySoftmaxArgmax1HotWithBias Op"""
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
... | class CrossentropySoftmax1HotWithBiasDx (gof.Op):
| nin = 3
nout = 1
"""Gradient wrt x of the CrossentropySoftmaxArgmax1HotWithBias Op"""
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return tensor.hashtype(self)
def __str_... | ] * i);
""",
inside_row_loop,
"""
if ((y_i >= PyArray_DIMS(%(x)s)[1]) || (y_i < 0))
{
PyErr_SetString(PyExc_ValueError, "y_i value out of bounds");
%(fail)s;
}
nll_i[0] = - x_i[y_i*Sx]
... | 256 | 256 | 1,620 | 15 | 241 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | CrossentropySoftmax1HotWithBiasDx | CrossentropySoftmax1HotWithBiasDx | 1,036 | 1,178 | 1,036 | 1,036 | 74b2970d97d402a8e9e50a4f4a89c2cf3722cb88 | bigcode/the-stack | train |
58dc4a0792499e92479e0a39 | train | function | def crossentropy_softmax_max_and_argmax_1hot(x, y_idx, **kwargs):
b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)
| def crossentropy_softmax_max_and_argmax_1hot(x, y_idx, **kwargs):
| b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)
| y_idx,
**kwargs)
(max_pr, argmax) = tensor.max_and_argmax(softmax, axis=-1)
return (xent, softmax, max_pr, argmax)
def crossentropy_softmax_max_and_argmax_1hot(x, y_idx, **kwargs):
| 64 | 64 | 58 | 20 | 44 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_softmax_max_and_argmax_1hot | crossentropy_softmax_max_and_argmax_1hot | 1,215 | 1,218 | 1,215 | 1,215 | 1239925a2d0fef43ae90fa9d00d2ffc5fe69e13f | bigcode/the-stack | train |
eebd44464ea2c80aa21ecdd3 | train | class | class SoftmaxWithBias(gof.Op):
"""
An L{Op} for the output of neural-net multiclass classifiers.
@type x: is a matrix of floats (32 or 64)
@type b: is a [row] vector of floats (32 or 64),
length is number of cols in x
This L{Op}'s output is softmax(x+b).
softmax(x[i]) is the i'th ... | class SoftmaxWithBias(gof.Op):
| """
An L{Op} for the output of neural-net multiclass classifiers.
@type x: is a matrix of floats (32 or 64)
@type b: is a [row] vector of floats (32 or 64),
length is number of cols in x
This L{Op}'s output is softmax(x+b).
softmax(x[i]) is the i'th distribution over len(x[i]) opt... | """Provides neural-network specific Ops.
:note: TODO: factor this out into a neural-network toolbox.
"""
import logging
import numpy
import theano
from theano import gof
from theano.tensor import basic as tensor
from theano.tensor import subtensor
from theano.tensor import elemwise, dmatrix, fmatrix, dvector, fvector... | 150 | 256 | 2,303 | 9 | 141 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | SoftmaxWithBias | SoftmaxWithBias | 27 | 264 | 27 | 27 | c08de27c099f2988acd87956bc4035b6512480fe | bigcode/the-stack | train |
515c257efdc820d0b5eee398 | train | function | def binary_crossentropy(output, target):
"""
Compute the crossentropy of binary random variables
output and target are each expectations of binary random
variables; target may be exactly 0 or 1 but output must
lie strictly between 0 and 1.
@note: we could use the x log y op to support output=0
... | def binary_crossentropy(output, target):
| """
Compute the crossentropy of binary random variables
output and target are each expectations of binary random
variables; target may be exactly 0 or 1 but output must
lie strictly between 0 and 1.
@note: we could use the x log y op to support output=0
@ and output=1. The gradient would sti... | [0]
if big_client in [b_client[0] for b_client in b.clients]:
xx, bb, ll = big_client.inputs
mergeable_client = big_client.op(x, b, ll)
return [mergeable_client[1]]
def binary_crossentropy(output, target):
| 63 | 64 | 150 | 8 | 55 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | binary_crossentropy | binary_crossentropy | 1,780 | 1,791 | 1,780 | 1,780 | 2ecfe0d20b3d8fc305a50ca559c05b0645d15efc | bigcode/the-stack | train |
60f0e0e368ad37bd9c7477e9 | train | function | def softmax_simplifier(numerators, denominators):
for numerator in list(numerators):
#TODO: a single softmax'd vector??
if not numerator.type.dtype.startswith('float'):
continue
if not numerator.type.broadcastable == (False, False):
continue
if numerator.owne... | def softmax_simplifier(numerators, denominators):
| for numerator in list(numerators):
#TODO: a single softmax'd vector??
if not numerator.type.dtype.startswith('float'):
continue
if not numerator.type.broadcastable == (False, False):
continue
if numerator.owner and numerator.owner.op == tensor.exp:
... | our arguments have the wrong types, then
#forget about it
return
if sm_bias.type == node.outputs[0].type:
#This condition is not always true. See the test
#nnet/tests/test_nnet.py:T_SoftmaxWithBias.test_broadcast
... | 82 | 82 | 275 | 13 | 69 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | softmax_simplifier | softmax_simplifier | 634 | 667 | 634 | 634 | fc5cd0efe0273059b1cbece4bb29775cddf51418 | bigcode/the-stack | train |
0c5523ac7f7985e0b1d45c17 | train | class | class Softmax(gof.Op):
"""
WRITEME
"""
nin = 1
nout = 1
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return hash(type(self))
def __str__(self):
return s... | class Softmax(gof.Op):
| """
WRITEME
"""
nin = 1
nout = 1
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return hash(type(self))
def __str__(self):
return self.__class__.__name__
... | );
npy_intp Ssm = PyArray_STRIDES(%(sm)s)[1]/sizeof(dtype_%(sm)s);
dtype_%(dx) s* __restrict__ dx_i = (dtype_%(dx)s*) (PyArray_BYTES(%(dx)s) + PyArray_STRIDES(%(dx)s)[0] * i);
npy_intp Sdx = PyArray_STRIDES(%(dx)s)[1]/sizeof(dtype_%(dx)s);
double sum_dy_times_sm = 0.;
... | 256 | 256 | 1,713 | 7 | 249 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | Softmax | Softmax | 378 | 568 | 378 | 378 | 0d1e0f82b344d37437dba0c218966d776f61a8ef | bigcode/the-stack | train |
eec6e22da1574df8d7d27b13 | train | class | class SoftmaxGrad(gof.Op):
"""Gradient wrt x of the Softmax Op"""
nin = 2
nout = 1
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return tensor.hashtype(self)
def __str__(... | class SoftmaxGrad(gof.Op):
| """Gradient wrt x of the Softmax Op"""
nin = 2
nout = 1
def __init__(self, **kwargs):
gof.Op.__init__(self, **kwargs)
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return tensor.hashtype(self)
def __str__(self):
return self.... | _dscal(x.N, 1.0 / sum, &mat_at(s,i,0), s.n);
double sum_inv = 1.0 / sum;
for (j = 0; j < Nx[1]; ++j)
{
sm_i[j * Ssm] *= sum_inv;
}
""" % locals()
inside_row_loop = """
if(Ssm == 1){
%(inside_row_loop_contig)... | 256 | 256 | 1,109 | 8 | 248 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | SoftmaxGrad | SoftmaxGrad | 269 | 374 | 269 | 269 | c36b48938fc1d60fa873e355e694bf1bc9c0dd39 | bigcode/the-stack | train |
fb8ce049a1ff1b8783b502f0 | train | function | @opt.register_specialize
@gof.local_optimizer([softmax_with_bias])
def graph_merge_softmax_with_crossentropy_softmax(node):
if node.op == softmax_with_bias:
x, b = node.inputs
for x_client in x.clients:
if x_client[0].op == crossentropy_softmax_argmax_1hot_with_bias:
big_... | @opt.register_specialize
@gof.local_optimizer([softmax_with_bias])
def graph_merge_softmax_with_crossentropy_softmax(node):
| if node.op == softmax_with_bias:
x, b = node.inputs
for x_client in x.clients:
if x_client[0].op == crossentropy_softmax_argmax_1hot_with_bias:
big_client = x_client[0]
if big_client in [b_client[0] for b_client in b.clients]:
xx, bb, l... | 1 and x_var.ndim == 2:
return [crossentropy_softmax_1hot_with_bias_dx(out_grad, sm, labels)]
else:
return
@opt.register_specialize
@gof.local_optimizer([softmax_with_bias])
def graph_merge_softmax_with_crossentropy_softmax(node):
| 64 | 64 | 136 | 28 | 35 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | graph_merge_softmax_with_crossentropy_softmax | graph_merge_softmax_with_crossentropy_softmax | 1,766 | 1,777 | 1,766 | 1,768 | a06b60b5468b0692a369adaea4494553fae9eee8 | bigcode/the-stack | train |
be07e0daefc1671676013443 | train | class | class CrossentropyCategorical1Hot(gof.Op):
"""Compute the cross entropy between a coding distribution and
a true distribution of the form [0, 0, ... 0, 1, 0, ..., 0]
.. math::
y[i] = - \log(coding_dist[i, one_of_n[i])
:note: In the case that the coding distribution is the output of a
... | class CrossentropyCategorical1Hot(gof.Op):
| """Compute the cross entropy between a coding distribution and
a true distribution of the form [0, 0, ... 0, 1, 0, ..., 0]
.. math::
y[i] = - \log(coding_dist[i, one_of_n[i])
:note: In the case that the coding distribution is the output of a
softmax, an application of this Op will... | name__
def make_node(self, g_y, coding_dist, true_one_of_n):
return Apply(self, [g_y, coding_dist, true_one_of_n],
[coding_dist.type()])
def perform(self, node, inp, out):
g_y, coding_dist, true_one_of_n = inp
g_coding_strg, = out
g_coding = numpy.zeros_lik... | 190 | 190 | 636 | 11 | 179 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | CrossentropyCategorical1Hot | CrossentropyCategorical1Hot | 1,251 | 1,321 | 1,251 | 1,252 | 408b50091bdd4cfca72b40f5038ded216b70a03b | bigcode/the-stack | train |
616b1e62e7ba22b114e215b3 | train | function | @opt.register_stabilize
@opt.register_specialize
@gof.optimizer
def crossentropy_to_crossentropy_with_softmax_with_bias(fgraph):
"""This is a stabilization optimization
:note: not a local optimization because we are replacing outputs
from several nodes at once
"""
def search_make_one_sub():
... | @opt.register_stabilize
@opt.register_specialize
@gof.optimizer
def crossentropy_to_crossentropy_with_softmax_with_bias(fgraph):
| """This is a stabilization optimization
:note: not a local optimization because we are replacing outputs
from several nodes at once
"""
def search_make_one_sub():
for node in fgraph.toposort():
if node.op == crossentropy_categorical_1hot:
nll, = node.outputs
... | , one_of_n),
grad_not_implemented(self, 1, one_of_n)]
crossentropy_categorical_1hot = CrossentropyCategorical1Hot()
@opt.register_stabilize
@opt.register_specialize
@gof.optimizer
def crossentropy_to_crossentropy_with_softmax_with_bias(fgraph):
| 65 | 65 | 219 | 31 | 34 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_to_crossentropy_with_softmax_with_bias | crossentropy_to_crossentropy_with_softmax_with_bias | 1,326 | 1,354 | 1,326 | 1,329 | 9de3d83f6221e900ab49c4056a17acd86bdf581a | bigcode/the-stack | train |
a48b4de320e0fe19ea3aa1fb | train | function | def crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx, **kwargs):
"""
@return: The cross-entropy, the softmax output, the max probability,
and the argmax index
@todo: Since we are recomputing the argmax,
we might as well assert that it is correct.
@todo: Make this ... | def crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx, **kwargs):
| """
@return: The cross-entropy, the softmax output, the max probability,
and the argmax index
@todo: Since we are recomputing the argmax,
we might as well assert that it is correct.
@todo: Make this entire function is
unnecessary? e.g. CrossentropySoftmaxArgmax1HotWithBias ... | , y_idx, **kwargs):
b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs)
def crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx, **kwargs):
| 64 | 64 | 185 | 24 | 40 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_softmax_max_and_argmax_1hot_with_bias | crossentropy_softmax_max_and_argmax_1hot_with_bias | 1,197 | 1,212 | 1,197 | 1,197 | 3cce22f6a27f0ec94e82fd7485e7d10c1d60879a | bigcode/the-stack | train |
6d1bf94ae8423fc6645ddf2e | train | function | def crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs):
return crossentropy_softmax_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)[0:2]
| def crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs):
| return crossentropy_softmax_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)[0:2]
| _argmax_1hot_with_bias = \
CrossentropySoftmaxArgmax1HotWithBias()
crossentropy_softmax_1hot_with_bias_dx = \
CrossentropySoftmax1HotWithBiasDx()
def crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs):
| 64 | 64 | 48 | 20 | 44 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | crossentropy_softmax_1hot_with_bias | crossentropy_softmax_1hot_with_bias | 1,187 | 1,189 | 1,187 | 1,187 | ad76aa038f6faead058f19f99c81ba3f673cbfdd | bigcode/the-stack | train |
26d7829af60d73cc66e3721f | train | class | class CrossentropyCategorical1HotGrad(gof.Op):
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return tensor.hashtype(self)
def __str__(self):
return self.__class__.__name__
def make_node(self, g_y, coding_dist, true_one_of_n):
return App... | class CrossentropyCategorical1HotGrad(gof.Op):
| def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return tensor.hashtype(self)
def __str__(self):
return self.__class__.__name__
def make_node(self, g_y, coding_dist, true_one_of_n):
return Apply(self, [g_y, coding_dist, true_one_of_n],
... | max_max_and_argmax_1hot(x, y_idx, **kwargs):
b = tensor.zeros_like(x[0, :])
return crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx,
**kwargs)
class CrossentropyCategorical1HotGrad(gof.Op):
| 66 | 66 | 220 | 12 | 54 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | CrossentropyCategorical1HotGrad | CrossentropyCategorical1HotGrad | 1,221 | 1,246 | 1,221 | 1,222 | e2bccaf52110e1dbebd183bb00fa8603a760ca2f | bigcode/the-stack | train |
798ffcb8121655161737d6b5 | train | function | def make_out_pattern(X):
stabilized_X = X - X.max(axis=1).dimshuffle(0, 'x')
out_var = stabilized_X - tensor.log(tensor.exp(stabilized_X).sum(
axis=1)).dimshuffle(0, 'x')
#tell DEBUG_MODE that it's OK if the original graph produced NaN and the optimized graph does not
out_var.values_eq_approx = ... | def make_out_pattern(X):
| stabilized_X = X - X.max(axis=1).dimshuffle(0, 'x')
out_var = stabilized_X - tensor.log(tensor.exp(stabilized_X).sum(
axis=1)).dimshuffle(0, 'x')
#tell DEBUG_MODE that it's OK if the original graph produced NaN and the optimized graph does not
out_var.values_eq_approx = out_var.type.values_eq_ap... | .)
#numerically stabilize log softmax (X)
# as X-X.max(axis=1).dimshuffle(0,'x') - log(exp(X-X.max(axis=1).dimshuffle(0,'x')).sum(axis=1)).dimshuffle(0,'x)
def make_out_pattern(X):
| 64 | 64 | 103 | 6 | 58 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | make_out_pattern | make_out_pattern | 1,956 | 1,962 | 1,956 | 1,956 | 21b23766e02f46c9feeec5bd2fd02397a26ad59d | bigcode/the-stack | train |
2f32efe8e2008dce940c6cdd | train | function | @opt.register_specialize
@gof.local_optimizer([tensor._max_and_argmax])
def local_argmax_pushdown(node):
if node.op == tensor._max_and_argmax and node.inputs[0].owner and \
len(node.outputs[0].clients) > 0 and node.inputs[0].owner.op in \
(softmax, softplus, tensor.exp, tensor.log, tensor.ta... | @opt.register_specialize
@gof.local_optimizer([tensor._max_and_argmax])
def local_argmax_pushdown(node):
| if node.op == tensor._max_and_argmax and node.inputs[0].owner and \
len(node.outputs[0].clients) > 0 and node.inputs[0].owner.op in \
(softmax, softplus, tensor.exp, tensor.log, tensor.tanh, sigmoid,
softmax_with_bias):
if theano.config.warn.argmax_pushdown_bug:
... | if (g_coding_dist.owner and
g_coding_dist.owner.op == crossentropy_categorical_1hot_grad):
g_nll, coding_dist, true_one_of_n = g_coding_dist.owner.inputs
dx = crossentropy_softmax_1hot_with_bias_dx(g_nll,
coding_dist, true_one_of_n)
return [dx]
op... | 119 | 119 | 399 | 26 | 93 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | local_argmax_pushdown | local_argmax_pushdown | 1,416 | 1,446 | 1,416 | 1,418 | 7968e2d4b192ac72fa19ecfa6d252f7a905a202a | bigcode/the-stack | train |
8807661032ce34978ad2012f | train | class | class Prepend_scalar_constant_to_each_row(gof.Op):
def __init__(self, val=0):
if isinstance(val, float):
val = scalar.constant(val)
self.val = val
def __eq__(self, other):
return (type(self) == type(other)) and (self.val == other.val)
def __hash__(self):
return ... | class Prepend_scalar_constant_to_each_row(gof.Op):
| def __init__(self, val=0):
if isinstance(val, float):
val = scalar.constant(val)
self.val = val
def __eq__(self, other):
return (type(self) == type(other)) and (self.val == other.val)
def __hash__(self):
return tensor.hashtype(self) ^ hash(self.val.data)
de... | for column distributions)
:rtype: tensor of rank one-less-than `coding_dist`
:returns: the cross entropy between each coding and true distribution.
"""
if true_dist.ndim == coding_dist.ndim:
return -tensor.sum(true_dist * tensor.log(coding_dist), axis=coding_dist.ndim-1)
elif true_dist.nd... | 134 | 134 | 448 | 12 | 121 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | Prepend_scalar_constant_to_each_row | Prepend_scalar_constant_to_each_row | 1,840 | 1,894 | 1,840 | 1,840 | 0e63804487db6e945cfb4616fba291388d8974a4 | bigcode/the-stack | train |
56a794647fd6690f2ad2c68e | train | function | @opt.register_specialize
@gof.local_optimizer([subtensor.AdvancedSubtensor, tensor.log])
def local_advanced_indexing_crossentropy_onehot(node):
log = None
sm = None
# First case: log(softmax(x))[rows, labels]
if isinstance(node.op, subtensor.AdvancedSubtensor):
try:
log, rows, labels... | @opt.register_specialize
@gof.local_optimizer([subtensor.AdvancedSubtensor, tensor.log])
def local_advanced_indexing_crossentropy_onehot(node):
| log = None
sm = None
# First case: log(softmax(x))[rows, labels]
if isinstance(node.op, subtensor.AdvancedSubtensor):
try:
log, rows, labels = node.inputs
except Exception:
pass
if log and log.owner and log.owner.op == tensor.log:
sm = log.owne... | return shape_of[labels][0] is stop
def _is_const(z, val, approx=False):
try:
maybe = opt.get_scalar_constant_value(z)
except tensor.NotScalarConstantError:
return False
if approx:
return numpy.allclose(maybe, val)
else:
return numpy.all(maybe == val)
@opt.re... | 107 | 107 | 357 | 33 | 74 | mrgloom/Theano | theano/tensor/nnet/nnet.py | Python | local_advanced_indexing_crossentropy_onehot | local_advanced_indexing_crossentropy_onehot | 1,502 | 1,540 | 1,502 | 1,504 | f5774bced3ae411e12ee60f7bdf74131a6328e7b | bigcode/the-stack | train |
4b410a5a7b33e669c3643789 | train | class | class RejectReason(ModelSimple):
"""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 v... | class RejectReason(ModelSimple):
| """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... | api.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540) # noqa: E501
The version of the ... | 256 | 256 | 2,312 | 6 | 249 | AllSafeCybercurity/coinapi-sdk | oeml-sdk/python/openapi_client/model/reject_reason.py | Python | RejectReason | RejectReason | 34 | 294 | 34 | 34 | 3288e99101745da539dde9482943a3f37aaa0ae2 | bigcode/the-stack | train |
d6473d2378f6d078d941eed0 | train | class | class IsEqual(_BaseFeatureGeneration):
"""Create new columns based on value matching.
Parameters
----------
columns_a : List[str]
List of columns.
columns_b : List[str]
List of columns.
Examples
---------
* fit & transform with `pandas`
>>> import pandas as pd
... | class IsEqual(_BaseFeatureGeneration):
| """Create new columns based on value matching.
Parameters
----------
columns_a : List[str]
List of columns.
columns_b : List[str]
List of columns.
Examples
---------
* fit & transform with `pandas`
>>> import pandas as pd
>>> from gators.feature_generation impo... | # License: Apache-2.0
from feature_gen import is_equal_object
from feature_gen import is_equal
from ._base_feature_generation import _BaseFeatureGeneration
from ..util import util
from typing import List, Union
import numpy as np
import pandas as pd
import databricks.koalas as ks
class IsEqual(_BaseFeatureGeneration):
| 77 | 256 | 1,481 | 8 | 68 | Aditya-Kapadiya/gators | build/lib.macosx-10.9-x86_64-3.9/gators/feature_generation/is_equal.py | Python | IsEqual | IsEqual | 12 | 192 | 12 | 12 | b8ac21aea8666fde8c25d2d5553af9cffaf7b557 | bigcode/the-stack | train |
b0ec33608be9368ae4c12149 | train | function | def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user_model', sa.Column('create_on', sa.DateTime(), server_default=sa.text('now()'), nullable=True))
| def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
| op.add_column('user_model', sa.Column('create_on', sa.DateTime(), server_default=sa.text('now()'), nullable=True))
| sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0552a8eda419'
down_revision = '392a06e7331b'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
| 64 | 64 | 48 | 18 | 45 | borko81/parking_system_with_flask | migrations/versions/0552a8eda419_.py | Python | upgrade | upgrade | 19 | 21 | 19 | 20 | 7b66912a77cdb713a2f06c42db8205623c0d3ceb | bigcode/the-stack | train |
7e48d486df85cce942c180cc | train | function | def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user_model', 'create_on')
| def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
| op.drop_column('user_model', 'create_on')
| ic - please adjust! ###
op.add_column('user_model', sa.Column('create_on', sa.DateTime(), server_default=sa.text('now()'), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
| 63 | 64 | 30 | 18 | 45 | borko81/parking_system_with_flask | migrations/versions/0552a8eda419_.py | Python | downgrade | downgrade | 25 | 27 | 25 | 26 | 7a276736aff3e6f8d75e5ee87c874980cfeda795 | bigcode/the-stack | train |
cdb5212309b9c8189f198ade | train | class | class TestParcels(APITestCase):
def test_create_parcel(self):
url = reverse('purpleserver.manager:parcel-list')
data = PARCEL_DATA
response = self.client.post(url, data)
response_data = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CRE... | class TestParcels(APITestCase):
| def test_create_parcel(self):
url = reverse('purpleserver.manager:parcel-list')
data = PARCEL_DATA
response = self.client.post(url, data)
response_data = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertDictEqua... | import json
from unittest.mock import ANY
from django.urls import reverse
from rest_framework import status
from purpleserver.core.tests import APITestCase
from purpleserver.manager.models import Parcel
class TestParcels(APITestCase):
| 50 | 64 | 82 | 9 | 40 | blueprin4/purplship-server | src/apps/manager/purpleserver/manager/tests/test_parcels.py | Python | TestParcels | TestParcels | 9 | 19 | 9 | 10 | 955126ccb2a9c5a5d72932db0660274f8ef6197d | bigcode/the-stack | train |
9174360e7600fadd36f060c4 | train | class | class TestParcelDetails(APITestCase):
def setUp(self) -> None:
super().setUp()
self.parcel: Parcel = Parcel.objects.create(**{
"weight": 1,
"width": 20,
"height": 10,
"length": 29,
"weight_unit": "KG",
"dimension_unit": "CM",
... | class TestParcelDetails(APITestCase):
| def setUp(self) -> None:
super().setUp()
self.parcel: Parcel = Parcel.objects.create(**{
"weight": 1,
"width": 20,
"height": 10,
"length": 29,
"weight_unit": "KG",
"dimension_unit": "CM",
"user": self.user
})... | :parcel-list')
data = PARCEL_DATA
response = self.client.post(url, data)
response_data = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertDictEqual(response_data, PARCEL_RESPONSE)
class TestParcelDetails(APITestCase):
| 64 | 64 | 171 | 8 | 56 | blueprin4/purplship-server | src/apps/manager/purpleserver/manager/tests/test_parcels.py | Python | TestParcelDetails | TestParcelDetails | 22 | 43 | 22 | 22 | 92aa3707a380f197305cd6d601f9d71d9557f85d | bigcode/the-stack | train |
c7ae77dba80a1f56fe0e047e | train | class | class AmountOwed(Document):
pass
| class AmountOwed(Document):
| pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2019, Indictrans and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class AmountOwed(Document):
| 56 | 64 | 8 | 6 | 49 | patilsangram/playfunction | playfunction/playfunction/doctype/amount_owed/amount_owed.py | Python | AmountOwed | AmountOwed | 9 | 10 | 9 | 9 | 792eef59ac925b82bfadbe440227dd790b457272 | bigcode/the-stack | train |
0dc25d82e440a2fc60e37338 | train | class | class TestSingleValueQuestion(unittest.TestCase):
pass
| class TestSingleValueQuestion(unittest.TestCase):
| pass
| # -*- coding: utf-8 -*-
# Copyright (c) 2020, ElasticRun and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestSingleValueQuestion(unittest.TestCase):
| 50 | 64 | 11 | 9 | 40 | ElasticRun/FormsNext | formsnext/formsnext/doctype/single_value_question/test_single_value_question.py | Python | TestSingleValueQuestion | TestSingleValueQuestion | 9 | 10 | 9 | 9 | d56f2f3dd7a0ce3349b15440afa32efae3293904 | bigcode/the-stack | train |
6d8dead4c32650073251b335 | train | function | def lambda_handler(event, context):
""" Lambda Handler to describe cloud trails enabled or not for each region """
set_logging(level=logging.INFO)
try:
payload = json.loads(event["Records"][0]["Sns"]["Message"])
account_id = payload['account_id']
account_name = payload['account_name... | def lambda_handler(event, context):
| """ Lambda Handler to describe cloud trails enabled or not for each region """
set_logging(level=logging.INFO)
try:
payload = json.loads(event["Records"][0]["Sns"]["Message"])
account_id = payload['account_id']
account_name = payload['account_name']
# get the last region fro... | import json
import logging
from library.logger import set_logging
from library.config import Config
from library.aws.cloudtrail import CloudTrailChecker
from library.aws.utility import Account
from library.ddb_issues import IssueStatus, CloudTrailIssue
from library.ddb_issues import Operations as IssueOperations
from... | 77 | 170 | 567 | 7 | 69 | MrBakalo/hammer | hammer/identification/lambdas/cloudtrails-issues-identification/describe_cloudtrails.py | Python | lambda_handler | lambda_handler | 14 | 76 | 14 | 14 | 182b06101333a200dc583ea06789547727c5e172 | bigcode/the-stack | train |
5a718547515508644a1d727f | train | class | class IsOwnerOrReadOnlyTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email=... | class IsOwnerOrReadOnlyTests(TestCase):
| def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email="superuser@gmail.com",
passwo... | , owner=self.user)
profile.my_wallet = 1000
profile.save()
self.client = APIClient()
self.client.force_authenticate(user=self.user)
response = self.client.delete(PROJECTS_URL, payload)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
class IsOwnerOrReadOn... | 74 | 74 | 248 | 10 | 64 | tpriyanshu90/Project-Dashboard-with-Django | app/core/tests/test_permissions.py | Python | IsOwnerOrReadOnlyTests | IsOwnerOrReadOnlyTests | 110 | 137 | 110 | 111 | 1bae2005c5a699eb82bf29fe8f63ec08e3aff17a | bigcode/the-stack | train |
6bfa9b3a998dfe72dae25f06 | train | class | class IsAdminOrReadAndCreateOnlyTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
... | class IsAdminOrReadAndCreateOnlyTests(TestCase):
| def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email="superuser@gmail.com",
passwo... | .client = APIClient()
self.client.force_authenticate(user=self.user)
response = self.client.get(CHARITIES_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_superuser_can_access_unsafe_methods(self):
payload = self.charity_payload
self.client = APIClien... | 118 | 118 | 394 | 12 | 106 | tpriyanshu90/Project-Dashboard-with-Django | app/core/tests/test_permissions.py | Python | IsAdminOrReadAndCreateOnlyTests | IsAdminOrReadAndCreateOnlyTests | 63 | 107 | 63 | 64 | 993ed321ccb66680336a37cb57e3cd484ec7d351 | bigcode/the-stack | train |
a6dcb26a5e0efed3ad6e2351 | train | class | class IsAssignedAlreadyTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email="... | class IsAssignedAlreadyTests(TestCase):
| def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email="superuser@gmail.com",
passwor... | self.client.force_authenticate(user=self.user)
response = self.client.get(ISSUE_FIXED_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_random_user_cant_access_view(self):
self.client = APIClient()
self.client.force_authenticate(user=self.user_superuser)
... | 101 | 101 | 337 | 8 | 93 | tpriyanshu90/Project-Dashboard-with-Django | app/core/tests/test_permissions.py | Python | IsAssignedAlreadyTests | IsAssignedAlreadyTests | 172 | 203 | 172 | 173 | c1d9f91471458db7038274dc83e060fedf8db5b1 | bigcode/the-stack | train |
b4a781b90331123f8dc37fc4 | train | class | class IsFixingOrReadOnlyTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email... | class IsFixingOrReadOnlyTests(TestCase):
| def setUp(self):
self.user = get_user_model().objects.create_user(
email="test@gmail.com",
password="test1234",
name="Test User"
)
self.user_superuser = get_user_model().objects.create_superuser(
email="superuser@gmail.com",
passwo... | )
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_nonowner_cant_access_view(self):
self.client = APIClient()
self.client.force_authenticate(user=self.user_superuser)
response = self.client.get(TEAM_REQUIREMENTS_URL)
self.assertEqual(response.status_code, ... | 84 | 84 | 280 | 11 | 73 | tpriyanshu90/Project-Dashboard-with-Django | app/core/tests/test_permissions.py | Python | IsFixingOrReadOnlyTests | IsFixingOrReadOnlyTests | 140 | 169 | 140 | 141 | ded21be692222a92b150d263d4730036203cdb29 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.