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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8af8ba6f78a223e36990c0b9 | train | function | def _build_legacy_data(deltat_data, deltat_preds, leap_second_dat):
data_end_time = deltat_data[0, -1]
i = np.searchsorted(deltat_preds[0], data_end_time, side='right')
delta_t_recent = np.concatenate([deltat_data, deltat_preds[:,i:]], axis=1)
leap_dates, leap_offsets = leap_second_dat
return delta_... | def _build_legacy_data(deltat_data, deltat_preds, leap_second_dat):
| data_end_time = deltat_data[0, -1]
i = np.searchsorted(deltat_preds[0], data_end_time, side='right')
delta_t_recent = np.concatenate([deltat_data, deltat_preds[:,i:]], axis=1)
leap_dates, leap_offsets = leap_second_dat
return delta_t_recent, leap_dates, leap_offsets
| import locale
import numpy as np
from datetime import datetime, timedelta
from threading import Lock
from .timelib import julian_date
_lock = Lock()
def _build_legacy_data(deltat_data, deltat_preds, leap_second_dat):
| 52 | 64 | 101 | 19 | 33 | facorazza/python-skyfield | skyfield/io_timescale.py | Python | _build_legacy_data | _build_legacy_data | 10 | 15 | 10 | 10 | 479e08514cdedb1f228ced38fad22c11f6c36b7a | bigcode/the-stack | train |
55c88512a36b3e0d07f03a4f | train | function | def parse_leap_seconds(fileobj):
"""Parse the IERS file ``Leap_Second.dat``.
The leap dates array can be searched with::
index = np.searchsorted(leap_dates, jd, 'right')
The resulting index allows (TAI - UTC) to be fetched with::
offset = leap_offsets[index]
"""
lines = iter(fil... | def parse_leap_seconds(fileobj):
| """Parse the IERS file ``Leap_Second.dat``.
The leap dates array can be searched with::
index = np.searchsorted(leap_dates, jd, 'right')
The resulting index allows (TAI - UTC) to be fetched with::
offset = leap_offsets[index]
"""
lines = iter(fileobj)
for line in lines:
... | year_float, delta_t = np.loadtxt(lines, usecols=[0, 1]).T
else:
# Format in use since 2019 February
year_float, delta_t = np.loadtxt(lines, usecols=[1, 2]).T
year = year_float.astype(int)
month = 1 + (year_float * 12.0).astype(int) % 12
return np.array((julian_date(year, month, ... | 114 | 114 | 382 | 8 | 106 | facorazza/python-skyfield | skyfield/io_timescale.py | Python | parse_leap_seconds | parse_leap_seconds | 63 | 104 | 63 | 63 | 838899cdfb74aef5b96b2d037f3bfcbe63d2ab59 | bigcode/the-stack | train |
ec2f768ae3ba75d17b9d77b0 | train | function | def parse_deltat_preds(fileobj):
"""Parse the United States Naval Observatory ``deltat.preds`` file.
The old format supplies a floating point year, the value of Delta T,
and one or two other fields::
2015.75 67.97 0.210 0.02
The new format adds a modified Julian day as ... | def parse_deltat_preds(fileobj):
| """Parse the United States Naval Observatory ``deltat.preds`` file.
The old format supplies a floating point year, the value of Delta T,
and one or two other fields::
2015.75 67.97 0.210 0.02
The new format adds a modified Julian day as the first field:
58484.000 ... | 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values.
"""
array = np.loadtxt(fileobj)
year, month, day, delta_t = array.T
return np.array((julian_date(year, month, day), delta_t))
def parse_deltat_preds(fileobj):
| 85 | 85 | 286 | 9 | 76 | facorazza/python-skyfield | skyfield/io_timescale.py | Python | parse_deltat_preds | parse_deltat_preds | 32 | 61 | 32 | 32 | 25d97ababa6619522fa8c9e65e731404c094056e | bigcode/the-stack | train |
2d2ad71c5306dbd552314312 | train | function | def parse_deltat_data(fileobj):
"""Parse the United States Naval Observatory ``deltat.data`` file.
Each line file gives the date and the value of Delta T::
2016 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values.
"""
array = np.loadtxt(fileob... | def parse_deltat_data(fileobj):
| """Parse the United States Naval Observatory ``deltat.data`` file.
Each line file gives the date and the value of Delta T::
2016 2 1 68.1577
This function returns a 2xN array of raw Julian dates and matching
Delta T values.
"""
array = np.loadtxt(fileobj)
year, month, day, delta_t... | data_end_time, side='right')
delta_t_recent = np.concatenate([deltat_data, deltat_preds[:,i:]], axis=1)
leap_dates, leap_offsets = leap_second_dat
return delta_t_recent, leap_dates, leap_offsets
def parse_deltat_data(fileobj):
| 64 | 64 | 119 | 9 | 54 | facorazza/python-skyfield | skyfield/io_timescale.py | Python | parse_deltat_data | parse_deltat_data | 17 | 30 | 17 | 17 | 90467a54ca2d72d4ad762a5e3d75ab2a0471fc36 | bigcode/the-stack | train |
fcb984c640b9c11476b733ba | train | class | class PresentingfeaturesConfig(AppConfig):
name = 'presentingfeatures'
| class PresentingfeaturesConfig(AppConfig):
| name = 'presentingfeatures'
| from django.apps import AppConfig
class PresentingfeaturesConfig(AppConfig):
| 15 | 64 | 16 | 8 | 6 | fahimfarhan/cancer-web-app | presentingfeatures/apps.py | Python | PresentingfeaturesConfig | PresentingfeaturesConfig | 4 | 5 | 4 | 4 | 70dd47f1fa2bb612da6690f33b624393af033f38 | bigcode/the-stack | train |
dc1b607c93d4641dfbe08504 | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | VariableWrapper | VariableWrapper | 788 | 809 | 788 | 788 | 77a7dbf72c29f448818fce0fbb5615de85cc080b | bigcode/the-stack | train |
5526c0e48027476b59ce1d9a | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | Oracle_datetime | Oracle_datetime | 81 | 91 | 81 | 81 | 22aa5ec3caa00505e0a33a84d5a57f467390cb90 | bigcode/the-stack | train |
cbdd7e1844ef3ad4718e08ae | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | to_unicode | to_unicode | 1,024 | 1,031 | 1,024 | 1,024 | fdf2e9b7bfb716c6bf70abf4c67c1b353cac0a7b | bigcode/the-stack | train |
5668ec05e1fbc4d9becc6746 | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | FormatStylePlaceholderCursor | FormatStylePlaceholderCursor | 825 | 959 | 825 | 825 | 4b33c5f8399e1b8b7ed30912379aa6680dce6f48 | bigcode/the-stack | train |
8c18cf17fc29665521fff216 | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | _get_sequence_reset_sql | _get_sequence_reset_sql | 1,034 | 1,048 | 1,034 | 1,035 | bbf787b55aebe46470081e7c26a20727eab77d53 | bigcode/the-stack | train |
df8f6121ba91418f7e509c1b | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | _setup_environment | _setup_environment | 16 | 32 | 16 | 18 | 54c4ca98ddb45adf5eab83dbb10763658c561e7e | bigcode/the-stack | train |
0ceabc86a4cfc282c6a8611e | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | _UninitializedOperatorsDescriptor | _UninitializedOperatorsDescriptor | 537 | 547 | 537 | 538 | 88f517736ea929c455b6fbfea5b862de14f6bf15 | bigcode/the-stack | train |
957eb9544229af2d268f2733 | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | CursorIterator | CursorIterator | 962 | 974 | 962 | 963 | 4a51f9fb42fa2c7580f22fe3d9933f7563a0494c | bigcode/the-stack | train |
fde8f0f7974d0ce9e31abc0d | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | _rowfactory | _rowfactory | 977 | 1,021 | 977 | 979 | 6a177498b80b16f4f95b3fe5b9c98e05e932b95c | bigcode/the-stack | train |
d09cb18dda558eb9b3d54ca0 | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | OracleParam | OracleParam | 736 | 785 | 736 | 736 | 6970ecbf45ad6ea3a5fcd4dc41ddb83051c4a0ae | bigcode/the-stack | train |
022ec239a5a24477c601bb94 | 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... | Features):
empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_insert = True
allow_sliced_subqueries = False
supports_subqueri... | 256 | 256 | 4,091 | 7 | 248 | dnozay/django | django/db/backends/oracle/base.py | Python | DatabaseOperations | DatabaseOperations | 126 | 534 | 126 | 126 | 77afcbf8c07d2a7c3794196564f5b5fdb454b739 | bigcode/the-stack | train |
75adf98c7c33deb8f467c2a3 | 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,810 | 7 | 249 | dnozay/django | django/db/backends/oracle/base.py | Python | DatabaseWrapper | DatabaseWrapper | 550 | 733 | 550 | 550 | cd62371051baf50e38f98f61acc7db4194485e28 | bigcode/the-stack | train |
4cdc29d80ecdc091b673f50b | train | class | class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_insert = True
allow_sliced_subqu... | class DatabaseFeatures(BaseDatabaseFeatures):
| empty_fetchmany_value = ()
needs_datetime_string_cast = False
interprets_empty_strings_as_nulls = True
uses_savepoints = True
has_select_for_update = True
has_select_for_update_nowait = True
can_return_id_from_insert = True
allow_sliced_subqueries = False
supports_subqueries_in_group... | , 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 | 254 | 7 | 69 | dnozay/django | django/db/backends/oracle/base.py | Python | DatabaseFeatures | DatabaseFeatures | 94 | 123 | 94 | 94 | 25c5f9e67356339d8aceea781602d699f737678a | bigcode/the-stack | train |
d9646615a7402deabd9acc8f | 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 | dnozay/django | django/db/backends/oracle/base.py | Python | InsertIdVar | InsertIdVar | 812 | 822 | 812 | 812 | 86dfe4b5f6ddc4eda27b26d4f6eadab9f91207f8 | bigcode/the-stack | train |
4af35615e96f450629f3fa2e | train | function | def underachiever_killer(ensemble,**kwargs):
pass
| def underachiever_killer(ensemble,**kwargs):
| pass
| = num.random.randint(0,len(ensemble))
logging.info("("+str(i)+"/"+str(times)+") Killing "+str(ensemble[randomnum]))
ensemble.remove(randomnum)
def qualified_killer(ensemble,**kwargs):
pass
def underachiever_killer(ensemble,**kwargs):
| 64 | 64 | 15 | 12 | 51 | kreveik/Kreveik | kreveik/family/killer.py | Python | underachiever_killer | underachiever_killer | 59 | 60 | 59 | 59 | 30bf5f309e4ebdf0fd81acb53f9426c0d96a9c22 | bigcode/the-stack | train |
eed9c8e90028fccaa9c04ecc | train | function | def qualified_killer(ensemble,**kwargs):
pass
| def qualified_killer(ensemble,**kwargs):
| pass
| str(times)+" individuals")
for i in range(times):
randomnum = num.random.randint(0,len(ensemble))
logging.info("("+str(i)+"/"+str(times)+") Killing "+str(ensemble[randomnum]))
ensemble.remove(randomnum)
def qualified_killer(ensemble,**kwargs):
| 63 | 64 | 13 | 10 | 53 | kreveik/Kreveik | kreveik/family/killer.py | Python | qualified_killer | qualified_killer | 56 | 57 | 56 | 56 | b1909adc4e8db6768fc1f7daa29fa98fa392da47 | bigcode/the-stack | train |
012448ce242b87641079c958 | train | function | def random_killer(ensemble,times):
import numpy as num
import logging
"""
Kills randomly from an ensemble
Kills a number of random individuals disregarding any properties of them.
Args:
----
ensemble: An object of Ensemble type (probably a Family) in which
individ... | def random_killer(ensemble,times):
| import numpy as num
import logging
"""
Kills randomly from an ensemble
Kills a number of random individuals disregarding any properties of them.
Args:
----
ensemble: An object of Ensemble type (probably a Family) in which
individuals will be randomly killed.
... | the License.
"""
family.killer module
====================
Houses functions that kill a portion of a population.
Functions
---------
random_killer: Kills randomly from an ensemble
qualified_killer: TODO
underachiever_killer: TODO
"""
def random_killer(ensemble,times):
| 63 | 64 | 159 | 9 | 54 | kreveik/Kreveik | kreveik/family/killer.py | Python | random_killer | random_killer | 31 | 54 | 31 | 31 | e9e175e8f6096b0f83ec7eb77833ef465ff8dcdd | bigcode/the-stack | train |
81c7fb55577c803b360fc706 | train | function | def replacetext(string):
string = string.split(" ")
string = "-".join(string)
return string
| def replacetext(string):
| string = string.split(" ")
string = "-".join(string)
return string
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# program to replace all the spaces in an entered string with a hyphen"-"
def replacetext(string):
| 39 | 64 | 25 | 6 | 33 | 224alpha/Python | replacetext.py | Python | replacetext | replacetext | 4 | 7 | 4 | 4 | 5c321805a88bffd36484386bedb0ea38e0d9239f | bigcode/the-stack | train |
5560670df7b5e210fac9deae | train | class | @mock.patch.object(eventlet.greenthread, 'sleep', lambda _: None)
class TestRetryOnConflict(unittest.TestCase):
def test_retry_on_conflict(self):
call = mock.Mock()
call.side_effect = ([exceptions.Conflict()] * (utils.RETRY_COUNT - 1)
+ [mock.sentinel.result])
res... | @mock.patch.object(eventlet.greenthread, 'sleep', lambda _: None)
class TestRetryOnConflict(unittest.TestCase):
| def test_retry_on_conflict(self):
call = mock.Mock()
call.side_effect = ([exceptions.Conflict()] * (utils.RETRY_COUNT - 1)
+ [mock.sentinel.result])
res = utils.retry_on_conflict(call, 1, 2, x=3)
self.assertEqual(mock.sentinel.result, res)
call.ass... | def test_disabled(self):
conf.CONF.set('discoverd', 'authenticate', 'false')
request = mock.Mock(headers={'X-Identity-Status': 'Invalid'})
utils.check_auth(request)
@mock.patch.object(eventlet.greenthread, 'sleep', lambda _: None)
class TestRetryOnConflict(unittest.TestCase):
| 68 | 68 | 228 | 26 | 42 | OpenDaisy/daisy-discoverd | ironic_discoverd/test/test_utils.py | Python | TestRetryOnConflict | TestRetryOnConflict | 68 | 86 | 68 | 69 | 5badb515cb6e5fc180d789b2bb3abf41a5c0a37e | bigcode/the-stack | train |
41b182b81f439095c86086de | train | class | class TestCheckAuth(base.BaseTest):
def setUp(self):
super(TestCheckAuth, self).setUp()
conf.CONF.set('discoverd', 'authenticate', 'true')
@mock.patch.object(auth_token, 'AuthProtocol')
def test_middleware(self, mock_auth):
conf.CONF.set('discoverd', 'os_username', 'admin')
... | class TestCheckAuth(base.BaseTest):
| def setUp(self):
super(TestCheckAuth, self).setUp()
conf.CONF.set('discoverd', 'authenticate', 'true')
@mock.patch.object(auth_token, 'AuthProtocol')
def test_middleware(self, mock_auth):
conf.CONF.set('discoverd', 'os_username', 'admin')
conf.CONF.set('discoverd', 'os_tenan... | or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import eventlet
fro... | 116 | 116 | 387 | 8 | 107 | OpenDaisy/daisy-discoverd | ironic_discoverd/test/test_utils.py | Python | TestCheckAuth | TestCheckAuth | 26 | 65 | 26 | 26 | 286858a51b93bfaee7c4f28b19a6dcddb4730ad0 | bigcode/the-stack | train |
97546ff67c6aab974474c8e3 | train | function | @asyncer.asyncme
def restore(hmacs, port):
url = restore_url_get(port)
if not url:
return
while not restore._die.is_set():
for hmac in hmacs:
try:
r = requests.post(
url, headers=secure.gen_hmac_headers("", hmac))
if r.status_... | @asyncer.asyncme
def restore(hmacs, port):
| url = restore_url_get(port)
if not url:
return
while not restore._die.is_set():
for hmac in hmacs:
try:
r = requests.post(
url, headers=secure.gen_hmac_headers("", hmac))
if r.status_code == 403:
continue
... | name__)
_RUNTIME_CONF_DIR = "/var/run/netmet/"
_RUNTIME_CONF_FILE = _RUNTIME_CONF_DIR + "restore_api_%s"
_RESTORE_API = "%(server)s/api/v1/clients/%(host)s/%(port)s"
@asyncer.asyncme
def restore(hmacs, port):
| 64 | 64 | 195 | 14 | 50 | godaddy/netmet | netmet/client/conf.py | Python | restore | restore | 20 | 50 | 20 | 21 | e094de798050d90d8b7158c4e9a78c121b35aa30 | bigcode/the-stack | train |
ea3f22fc0c9392259c8d0540 | train | function | def restore_url_clear(port):
try:
os.remove(_RUNTIME_CONF_FILE % port)
except OSError:
pass
| def restore_url_clear(port):
| try:
os.remove(_RUNTIME_CONF_FILE % port)
except OSError:
pass
| host": host, "port": port}
json.dump({"refresh_conf_url": _RESTORE_API % data}, f)
else:
json.dump({"refresh_conf_url": None}, f)
except Exception:
LOG.exception("Failed to store runtime info refresh_conf_url")
def restore_url_clear(port):
| 64 | 64 | 28 | 6 | 58 | godaddy/netmet | netmet/client/conf.py | Python | restore_url_clear | restore_url_clear | 87 | 91 | 87 | 87 | b842ef24009f790e6362628e13baba67029d1756 | bigcode/the-stack | train |
15284cdb3cf4d37d458e88b8 | train | function | def restore_url_set(netmet_server, host, port):
LOG.info("Setting new netmet restore_conf_url %s"
% (_RUNTIME_CONF_FILE % port))
try:
if not os.path.exists(_RUNTIME_CONF_DIR):
LOG.info("Creating directory: %s" % _RUNTIME_CONF_DIR)
os.makedirs(_RUNTIME_CONF_DIR)
... | def restore_url_set(netmet_server, host, port):
| LOG.info("Setting new netmet restore_conf_url %s"
% (_RUNTIME_CONF_FILE % port))
try:
if not os.path.exists(_RUNTIME_CONF_DIR):
LOG.info("Creating directory: %s" % _RUNTIME_CONF_DIR)
os.makedirs(_RUNTIME_CONF_DIR)
with open(_RUNTIME_CONF_FILE % port, "w+") a... | .load(f).get("refresh_conf_url", None)
except IOError:
LOG.info("Didn't find previous config: %s" % path)
except Exception:
LOG.exception("Failed to load restore_conf_url from previous run")
return None
def restore_url_set(netmet_server, host, port):
| 64 | 64 | 169 | 12 | 51 | godaddy/netmet | netmet/client/conf.py | Python | restore_url_set | restore_url_set | 68 | 84 | 68 | 68 | 78b76284e0d78554e6b8fd5108ecbf5354a5c365 | bigcode/the-stack | train |
d747b0745d023146733d8145 | train | function | def restore_url_get(port):
try:
path = _RUNTIME_CONF_FILE % port
with open(path, "rw") as f:
LOG.info("Loading restore conf url from previous run: %s" % path)
return json.load(f).get("refresh_conf_url", None)
except IOError:
LOG.info("Didn't find previous config:... | def restore_url_get(port):
| try:
path = _RUNTIME_CONF_FILE % port
with open(path, "rw") as f:
LOG.info("Loading restore conf url from previous run: %s" % path)
return json.load(f).get("refresh_conf_url", None)
except IOError:
LOG.info("Didn't find previous config: %s" % path)
except Ex... | "
% (url, e))
except Exception:
LOG.exception("Something went wrong during the attempt "
"to call netmet server to referesh config.")
return
if url != restore_url_get(port):
break
restore.... | 64 | 64 | 104 | 6 | 58 | godaddy/netmet | netmet/client/conf.py | Python | restore_url_get | restore_url_get | 53 | 65 | 53 | 53 | dfa9ee389908d5722b257611ac2d48fe445725c8 | bigcode/the-stack | train |
1cf0dacb6a4f96173f08dcfb | train | function | def get_rule():
return ChromeExtraRule, RuleDetails(name="Chrome extension", executable="chrome")
| def get_rule():
| return ChromeExtraRule, RuleDetails(name="Chrome extension", executable="chrome")
| ",
"Facebook": "https://www.facebook.com",
}),
IntegerRefST("n", 1, 100),
IntegerRefST("m", 1, 10)
]
defaults = {"n": 1, "m":"", "nth": ""}
def get_rule():
| 63 | 64 | 21 | 4 | 60 | gtrifonov/azure-voice-assist-pack | rules/apps/browser/chrome-extra.py | Python | get_rule | get_rule | 104 | 105 | 104 | 104 | e616af610aa2acf8501562ea306c9df3d214e259 | bigcode/the-stack | train |
b6bb2a2d92cbca7294974fd6 | train | class | class ChromeExtraRule(MappingRule):
mapping = {
"jump <jumpchoice>":
R(Key("f6/10,c-a/10,del/10") + Text(
"%(jumpchoice)s") + Key("enter")),
"[show] (extensions|plugins)":
R(Key("a-f/20, l, e/15, enter")),
"more tools":
R(Key("a-f/... | class ChromeExtraRule(MappingRule):
| mapping = {
"jump <jumpchoice>":
R(Key("f6/10,c-a/10,del/10") + Text(
"%(jumpchoice)s") + Key("enter")),
"[show] (extensions|plugins)":
R(Key("a-f/20, l, e/15, enter")),
"more tools":
R(Key("a-f/5, l")),
"... |
from dragonfly import Repeat, Pause, Function, Choice, MappingRule
from castervoice.lib.actions import Key, Mouse, Text
from castervoice.lib.merge.additions import IntegerRefST
from castervoice.lib.ctrl.mgr.rule_details import RuleDetails
from castervoice.lib.merge.state.short import R
from castervoice.lib import g... | 91 | 231 | 772 | 8 | 82 | gtrifonov/azure-voice-assist-pack | rules/apps/browser/chrome-extra.py | Python | ChromeExtraRule | ChromeExtraRule | 13 | 101 | 13 | 13 | 2d5fef0fdbd98810710ec2d130795539ac8f85f9 | bigcode/the-stack | train |
a290145679d272c453f348f2 | train | function | @click.command()
@click.argument("input_filepath", type=click.Path(exists=True))
@click.argument("output_filepath", type=click.Path())
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) trough
all processing steps (saved in ../processed).
"""
l... | @click.command()
@click.argument("input_filepath", type=click.Path(exists=True))
@click.argument("output_filepath", type=click.Path())
def main(input_filepath, output_filepath):
| """ Runs data processing scripts to turn raw data from (../raw) trough
all processing steps (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info("making final data sets from raw data")
| :synopsis:
"""
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
@click.command()
@click.argument("input_filepath", type=click.Path(exists=True))
@click.argument("output_filepath", type=click.Path())
def main(input_filepath, output_filepath):
| 64 | 64 | 86 | 36 | 27 | TuomoKareoja/product-associations-discovery | src/data/make_datasets.py | Python | main | main | 13 | 21 | 13 | 16 | 4b6fd1ad6a9b8cb31ab05489f875156401a13e60 | bigcode/the-stack | train |
037c69e17dfbf18b55e82169 | train | function | def pre_process(fid=None):
fid = Path(fid)
df = pd.read_csv('gender-classifier-DFE-791531.csv', encoding='latin-1')
girls_tweets = df[df['gender']=='female'][['text','gender']]
boys_tweets = df[df['gender']=='male'][['text','gender']]
df = pd.concat([girls_tweets,boys_tweets])
df['binary'] = p... | def pre_process(fid=None):
| fid = Path(fid)
df = pd.read_csv('gender-classifier-DFE-791531.csv', encoding='latin-1')
girls_tweets = df[df['gender']=='female'][['text','gender']]
boys_tweets = df[df['gender']=='male'][['text','gender']]
df = pd.concat([girls_tweets,boys_tweets])
df['binary'] = pd.get_dummies(df.gender, pr... | import pandas as pd
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import os
import json
def pre_process(fid=None):
| 33 | 70 | 235 | 6 | 26 | fdsig/bechdel | classifier.py | Python | pre_process | pre_process | 8 | 25 | 8 | 8 | 47c58ab130f7cc40999a7442d86e2d90d64cff8c | bigcode/the-stack | train |
8c6aade15f49df9b5da66d4d | train | function | def inference(json_fid=None):
with open(json_fid,'r') as fid:
text_dict = json.load(json_fid)
| def inference(json_fid=None):
| with open(json_fid,'r') as fid:
text_dict = json.load(json_fid)
| {args.task}'
sub_args+= f' --max_models {args.max_models}'
os.system(sub_args)
if args.train:
sub_args = f'autonlp train '
sub_args+= f' --project {args.project}'
os.system(sub_args)
def inference(json_fid=None):
| 64 | 64 | 29 | 7 | 57 | fdsig/bechdel | classifier.py | Python | inference | inference | 55 | 57 | 55 | 55 | 382eb751497f5ce98f577e2c287aa827407bbbb6 | bigcode/the-stack | train |
68b6ff707d2578648159825a | train | function | def train_hf_api(args):
if args.login:
sub_args = ('autonlp login --api-key ')
os.system(sub_args+args.api_key)
if args.send:
sub_args = f'autonlp upload '
sub_args+= f' --project {args.project}'
sub_args+= f' --split {args.split}'
sub_args+= f' --col_mappi... | def train_hf_api(args):
| if args.login:
sub_args = ('autonlp login --api-key ')
os.system(sub_args+args.api_key)
if args.send:
sub_args = f'autonlp upload '
sub_args+= f' --project {args.project}'
sub_args+= f' --split {args.split}'
sub_args+= f' --col_mapping {args.col_mapping}'
... | train.drop(valid.index)
train.to_csv('gender_text_train.csv', mode='w', index=False)
test.to_csv('gender_text_test.csv', mode='w', index=False)
valid.to_csv('gender_text_valid.csv', mode='w', index=False)
def train_hf_api(args):
| 63 | 64 | 214 | 7 | 56 | fdsig/bechdel | classifier.py | Python | train_hf_api | train_hf_api | 27 | 53 | 27 | 28 | 436e80cad69338eedfeb6e493931b53416138a1e | bigcode/the-stack | train |
ecd70442891436f7965b134f | train | function | def f(x,y):
return ((x-2) / 3)**2 + y**2 + y**4
| def f(x,y):
| return ((x-2) / 3)**2 + y**2 + y**4
| from ReadDate import *
from ThreadClasses import *
from AminoData import *
import pylab as pl
import copy as cp
import minuit
class vars:
def __init__(self):
self.x = 10.0
self.y = 15.0
def f(x,y):
| 64 | 64 | 26 | 5 | 58 | youdar/Threading-LHBH | Minuit_test.py | Python | f | f | 16 | 17 | 16 | 16 | 03d91989207bc8d4b74826776f1fe88af901d570 | bigcode/the-stack | train |
59bda8bb6b95084dbe7430a0 | train | class | class vars:
def __init__(self):
self.x = 10.0
self.y = 15.0
| class vars:
| def __init__(self):
self.x = 10.0
self.y = 15.0
| import numpy as nm
import string as st
from TheaderCommonFunctions import *
from ReadDate import *
from ThreadClasses import *
from AminoData import *
import pylab as pl
import copy as cp
import minuit
class vars:
| 51 | 64 | 28 | 3 | 47 | youdar/Threading-LHBH | Minuit_test.py | Python | vars | vars | 11 | 14 | 11 | 11 | 99007398960b3ee56c131fd7ef362bd10a04f4c7 | bigcode/the-stack | train |
27235bfc91a6b5c49a4a578d | train | class | class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None,{'fields':('email', 'password')}),
(_('Persinal Info'), {'fields':('name',)}),
(
_('Permissions'),
{'fields': ('is_active', 'is_staff', 'is_superuser')}
... | class UserAdmin(BaseUserAdmin):
| ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None,{'fields':('email', 'password')}),
(_('Persinal Info'), {'fields':('name',)}),
(
_('Permissions'),
{'fields': ('is_active', 'is_staff', 'is_superuser')}
),
(_('Important dat... | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from core import models
from django.utils.translation import gettext as _
class UserAdmin(BaseUserAdmin):
| 39 | 64 | 137 | 7 | 32 | Sahinovic/Ucenje | app/core/admin.py | Python | UserAdmin | UserAdmin | 8 | 25 | 8 | 8 | a6e23d90ff6972ca0aaf8042ffa854de0c1d889b | bigcode/the-stack | train |
6f9678f28cf9ad9b23b25140 | train | class | class SRTMReprojector():
def __init__(self):
self.logfile = open("reproject_log.txt", "w+")
def ReprojectFile(self, src_filepath, dest_filepath):
filename = dest_filepath.split("/")[-1]
translate_command = "gdal_translate {0} interm.tif".format(src_filepath)
reproject_co... | class SRTMReprojector():
| def __init__(self):
self.logfile = open("reproject_log.txt", "w+")
def ReprojectFile(self, src_filepath, dest_filepath):
filename = dest_filepath.split("/")[-1]
translate_command = "gdal_translate {0} interm.tif".format(src_filepath)
reproject_command = "gdalwarp -s_srs ... | from osgeo import gdal
import subprocess
import matplotlib.pyplot as plt
import os
from tqdm import tqdm
# Reprojecting SRTM data from WGS84 to EPSG:3395 (Mercator)
# gdal_translate <filename>.hgt <filename>.tif
# gdalwarp -s_srs EPSG:4326 -t_srs EPSG:3395 -r bilinear <in>.tif <out>.tif
class SRTMReprojector():
| 106 | 115 | 385 | 8 | 97 | Landslide-Analytics-System/GLAS | data collection and processing/elevation/reproject_srtm.py | Python | SRTMReprojector | SRTMReprojector | 11 | 44 | 11 | 11 | 158eb0cfd7d0e5af28dea56171a6eefdcfe35d8e | bigcode/the-stack | train |
2f25ebd371212bcf911b6894 | train | function | @pytest.fixture
def oracle_with_table(oracle_engine, request) -> Tuple[Engine, Table]:
TEST_TABLE_METADATA.metadata.create_all(oracle_engine)
def finalize():
metadata = MetaData(bind=oracle_engine)
metadata.reflect()
reflected_table = metadata.tables[TEST_TABLE_METADATA.name]
re... | @pytest.fixture
def oracle_with_table(oracle_engine, request) -> Tuple[Engine, Table]:
| TEST_TABLE_METADATA.metadata.create_all(oracle_engine)
def finalize():
metadata = MetaData(bind=oracle_engine)
metadata.reflect()
reflected_table = metadata.tables[TEST_TABLE_METADATA.name]
reflected_table.drop()
request.addfinalizer(finalize)
return oracle_engine, TES... | return verify_connection()
def _oracle_connection_helper(host):
return cx_Oracle.connect(ORACLE_USER, ORACLE_PWD, '{}:{}/{}'.format(host, ORACLE_LISTENER_PORT, ORACLE_DB))
@pytest.fixture
def oracle_with_table(oracle_engine, request) -> Tuple[Engine, Table]:
| 64 | 64 | 83 | 20 | 44 | jzcruiser/doltpy | tests/sql_sync/fixtures/oracle.py | Python | oracle_with_table | oracle_with_table | 54 | 66 | 54 | 55 | 39907093c72fac300fcaa46f15002a2923135157 | bigcode/the-stack | train |
6f9c67903f9050e49fd8ad76 | train | function | def _oracle_connection_helper(host):
return cx_Oracle.connect(ORACLE_USER, ORACLE_PWD, '{}:{}/{}'.format(host, ORACLE_LISTENER_PORT, ORACLE_DB))
| def _oracle_connection_helper(host):
| return cx_Oracle.connect(ORACLE_USER, ORACLE_PWD, '{}:{}/{}'.format(host, ORACLE_LISTENER_PORT, ORACLE_DB))
| acle://', creator=lambda: _oracle_connection_helper(docker_ip))
@retry(delay=10, tries=12, exceptions=(sqlalchemy.exc.DatabaseError))
def verify_connection():
conn = engine.connect()
conn.close()
return engine
return verify_connection()
def _oracle_connection_helper(host):
| 64 | 64 | 40 | 7 | 57 | jzcruiser/doltpy | tests/sql_sync/fixtures/oracle.py | Python | _oracle_connection_helper | _oracle_connection_helper | 50 | 51 | 50 | 50 | c23609b6eccdf46912773f7545b75561fd6f4ab5 | bigcode/the-stack | train |
50ab37b002c1641f3701028e | train | function | @pytest.fixture(scope='session')
def oracle_service_def():
"""
Provides the Docker service definitions for running an instance of Oracle Express Edition, result is converted to
YAML file and then used to create a Docker compose file. Note this assumes the existence of a container image named
'oracle/dat... | @pytest.fixture(scope='session')
def oracle_service_def():
| """
Provides the Docker service definitions for running an instance of Oracle Express Edition, result is converted to
YAML file and then used to create a Docker compose file. Note this assumes the existence of a container image named
'oracle/database:18.4.0-xe' in a registry that your local copy of Dock... | _oracle'
ORACLE_DB = 'XEPDB1'
ORACLE_USER = 'py_test'
ORACLE_PWD = 'py_test_password'
ORACLE_LISTENER_PORT = 1521
ORACLE_OEM_EXPRESS_PORT = 5500
@pytest.fixture(scope='session')
def oracle_service_def():
| 64 | 64 | 193 | 11 | 52 | jzcruiser/doltpy | tests/sql_sync/fixtures/oracle.py | Python | oracle_service_def | oracle_service_def | 19 | 34 | 19 | 20 | b330c166462ff01247188377417233f58dc829ad | bigcode/the-stack | train |
e69099e4b27a28a8c17d0661 | train | function | @pytest.fixture
def oracle_engine(docker_ip, docker_services) -> Engine:
engine = create_engine('oracle+cx_oracle://', creator=lambda: _oracle_connection_helper(docker_ip))
@retry(delay=10, tries=12, exceptions=(sqlalchemy.exc.DatabaseError))
def verify_connection():
conn = engine.connect()
... | @pytest.fixture
def oracle_engine(docker_ip, docker_services) -> Engine:
| engine = create_engine('oracle+cx_oracle://', creator=lambda: _oracle_connection_helper(docker_ip))
@retry(delay=10, tries=12, exceptions=(sqlalchemy.exc.DatabaseError))
def verify_connection():
conn = engine.connect()
conn.close()
return engine
return verify_connection()
| 'container_name': ORACLE_CONTAINER_NAME,
'ports': ['{port}:{port}'.format(port=ORACLE_LISTENER_PORT),
'{port}:{port}'.format(port=ORACLE_OEM_EXPRESS_PORT)]
}
@pytest.fixture
def oracle_engine(docker_ip, docker_services) -> Engine:
| 64 | 64 | 83 | 16 | 48 | jzcruiser/doltpy | tests/sql_sync/fixtures/oracle.py | Python | oracle_engine | oracle_engine | 37 | 47 | 37 | 38 | 0566163ac1788446dcc5e2483d15c249ed59f676 | bigcode/the-stack | train |
95a0473b66613b3d4c3faf3c | train | class | class I3Proxy:
def __init__(self,
i3_connection: i3ipc.Connection,
dry_run: bool = True):
self.i3_connection = i3_connection
self.dry_run = dry_run
# i3 tree is cached for performance. Timing the i3ipc get_tree function
# using `%timeit` in ipython ... | class I3Proxy:
| def __init__(self,
i3_connection: i3ipc.Connection,
dry_run: bool = True):
self.i3_connection = i3_connection
self.dry_run = dry_run
# i3 tree is cached for performance. Timing the i3ipc get_tree function
# using `%timeit` in ipython shows about 1-2m... | from typing import Dict, List, Optional
import i3ipc
from i3wsgroups import logger
logger = logger.logger
class I3Proxy:
| 33 | 256 | 859 | 5 | 27 | b0o/i3-workspace-groups | i3wsgroups/i3_proxy.py | Python | I3Proxy | I3Proxy | 9 | 99 | 9 | 10 | e830b561c35bd11454a8abe461c9331b9e0b669a | bigcode/the-stack | train |
0fbebbd53f6bffb27a3733f7 | train | class | class Fib(luigi.Task):
n = luigi.IntParameter(default=100)
def requires(self):
if self.n >= 2:
return [Fib(self.n - 1), Fib(self.n - 2)]
else:
return []
def output(self):
return File('/tmp/fib_%d' % self.n)
def run(self):
if self.n == 0:
... | class Fib(luigi.Task):
| n = luigi.IntParameter(default=100)
def requires(self):
if self.n >= 2:
return [Fib(self.n - 1), Fib(self.n - 2)]
else:
return []
def output(self):
return File('/tmp/fib_%d' % self.n)
def run(self):
if self.n == 0:
s = 0
elif... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import unittest
import luigi
import luigi.interface
from luigi.mock import MockFile
File = MockFile
# Calculates Fibonacci numbers :)
class Fib(luigi.Task):
| 63 | 64 | 162 | 7 | 56 | RUNDSP/luigi | test/fib_test.py | Python | Fib | Fib | 29 | 54 | 29 | 29 | fc1ed8a22fdcef3594fd04e01f170ca07e27aa95 | bigcode/the-stack | train |
0e35d327dd8f3c13efe2706d | train | class | class FibTestBase(unittest.TestCase):
def setUp(self):
global File
File = MockFile
MockFile.fs.clear()
| class FibTestBase(unittest.TestCase):
| def setUp(self):
global File
File = MockFile
MockFile.fs.clear()
| else:
s = 0
for input in self.input():
for line in input.open('r'):
s += int(line.strip())
f = self.output().open('w')
f.write('%d\n' % s)
f.close()
class FibTestBase(unittest.TestCase):
| 64 | 64 | 30 | 8 | 56 | RUNDSP/luigi | test/fib_test.py | Python | FibTestBase | FibTestBase | 57 | 62 | 57 | 58 | 512bf77f13aed768cee5fd5f5d002179efa1c316 | bigcode/the-stack | train |
0901b418b51bf4519ec8550d | train | class | class FibTest(FibTestBase):
def test_invoke(self):
w = luigi.worker.Worker()
w.add(Fib(100))
w.run()
w.stop()
self.assertEqual(MockFile.fs.get_data('/tmp/fib_10'), '55\n')
self.assertEqual(MockFile.fs.get_data('/tmp/fib_100'), '354224848179261915075\n')
def test... | class FibTest(FibTestBase):
| def test_invoke(self):
w = luigi.worker.Worker()
w.add(Fib(100))
w.run()
w.stop()
self.assertEqual(MockFile.fs.get_data('/tmp/fib_10'), '55\n')
self.assertEqual(MockFile.fs.get_data('/tmp/fib_100'), '354224848179261915075\n')
def test_cmdline(self):
luigi... | s += int(line.strip())
f = self.output().open('w')
f.write('%d\n' % s)
f.close()
class FibTestBase(unittest.TestCase):
def setUp(self):
global File
File = MockFile
MockFile.fs.clear()
class FibTest(FibTestBase):
| 68 | 68 | 228 | 8 | 60 | RUNDSP/luigi | test/fib_test.py | Python | FibTest | FibTest | 65 | 85 | 65 | 66 | c1f7a0fc0a9b6ad4561a1faab8f6dfadce725177 | bigcode/the-stack | train |
c4dbe0353d7b8699b6e730b2 | train | class | class RuleBased(object):
def __init__(self, gateway):
self.gateway = gateway
def close(self):
pass
def getInformation(self, frameData, isControl):
self.frameData = frameData
self.cc.setFrameData(self.frameData, self.player)
def roundEnd(self, x, y, z):
print(x)
print(y)... | class RuleBased(object):
| def __init__(self, gateway):
self.gateway = gateway
def close(self):
pass
def getInformation(self, frameData, isControl):
self.frameData = frameData
self.cc.setFrameData(self.frameData, self.player)
def roundEnd(self, x, y, z):
print(x)
print(y)
print(z)
def ge... | from py4j.java_gateway import get_field
class RuleBased(object):
| 15 | 219 | 733 | 5 | 9 | Darthpab/Redes-Reuronales-y-Reinforcement-Learning-Aplicada-a-Videojuegos-TFG | RuleBased/RuleBased.py | Python | RuleBased | RuleBased | 3 | 99 | 3 | 3 | 4949e3d7017695a490a0b97de95f95d91e861e5e | bigcode/the-stack | train |
645f2c8d1fa03a94ac2fc07d | train | function | def parse_int_or_404(x):
if x:
try:
parsed = int(x)
return parsed
except ValueError:
raise Http404("Invalid argument")
return Http404("No argument specified")
| def parse_int_or_404(x):
| if x:
try:
parsed = int(x)
return parsed
except ValueError:
raise Http404("Invalid argument")
return Http404("No argument specified")
| from django.http import Http404
def parse_int_or_404(x):
| 15 | 64 | 47 | 8 | 6 | petgo3/katago-server | src/frontend/utils/parse_util.py | Python | parse_int_or_404 | parse_int_or_404 | 3 | 10 | 3 | 3 | 7f1a49795860249728342bf6789b876c7c1371a9 | bigcode/the-stack | train |
e6c33b20973c873462cad048 | train | class | class TransitionInfoVisitor(NodeVisitor):
def visit_weighted_state(self, node: WeightedState):
return TransitionInfo()
def visit_alternatives(self, node: Alternatives):
has_action = True
has_state = True
has_outcome = True
for alternative in node.alternatives:
... | class TransitionInfoVisitor(NodeVisitor):
| def visit_weighted_state(self, node: WeightedState):
return TransitionInfo()
def visit_alternatives(self, node: Alternatives):
has_action = True
has_state = True
has_outcome = True
for alternative in node.alternatives:
has_state = has_state and alternative.tr... | non-homogeneous alternatives!" % node)
def visit_reward(self, node: Reward):
pass
def visit_weighted_state(self, node: WeightedState):
self.fail(node)
def visit_state(self, node: State):
pass
def visit_mapping(self, node: Mapping):
self.fail(node)
def visit_conj... | 112 | 112 | 376 | 7 | 104 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | TransitionInfoVisitor | TransitionInfoVisitor | 304 | 343 | 304 | 304 | 5e8ef087039888996d3fc1a101c475f373bc5c47 | bigcode/the-stack | train |
e00d08d52bb27a3f80d7322a | train | class | class SupportMapping(object):
def __gt__(self: Node, outcome):
return Mapping(self, outcome)
| class SupportMapping(object):
| def __gt__(self: Node, outcome):
return Mapping(self, outcome)
| return Alternatives([self]) | other
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.__dict__)
class SupportConjunction(object):
def __and__(self: Node, right):
return Conjunction(self, right)
class SupportMapping(object):
| 64 | 64 | 23 | 5 | 59 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | SupportMapping | SupportMapping | 69 | 71 | 69 | 69 | 696ca5e62cef639f1b0b903a5baa32b19b2c805a | bigcode/the-stack | train |
1001bcf5120e937b922a9ea2 | train | class | class Mapping(Node):
def __init__(self, trigger: Node, outcome: Node):
super().__init__()
trigger.apply(TriggerTypeVerifier())
outcome.apply(OutcomeTypeVerifier())
self.trigger = trigger
self.outcome = outcome
if self.transition_info.fully_specified:
co... | class Mapping(Node):
| def __init__(self, trigger: Node, outcome: Node):
super().__init__()
trigger.apply(TriggerTypeVerifier())
outcome.apply(OutcomeTypeVerifier())
self.trigger = trigger
self.outcome = outcome
if self.transition_info.fully_specified:
compile_transitions(sel... | TypeVerifier())
# else: Mapping has already verified itself.
self.left = left
self.right = right
if self.transition_info.fully_specified:
compile_transitions(self)
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_conjunction(self)
class Mapping(Nod... | 64 | 64 | 87 | 4 | 60 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Mapping | Mapping | 190 | 204 | 190 | 190 | 7f3b6563348b6038d70efd69e283a34ae8a68ba4 | bigcode/the-stack | train |
b308a0317ced88d33990f368 | train | function | def compile_transitions(node):
transitions = node.apply(TransitionVisitor([Transition()]))
for transition in transitions:
if transition.state.terminal_state:
raise DslSyntaxError('Attempted to specify transition %s for terminal state!' % transition)
context.mdp_spec.transition(transi... | def compile_transitions(node):
| transitions = node.apply(TransitionVisitor([Transition()]))
for transition in transitions:
if transition.state.terminal_state:
raise DslSyntaxError('Attempted to specify transition %s for terminal state!' % transition)
context.mdp_spec.transition(transition.state, transition.action, ... | TypeVerifier())
outcome.apply(OutcomeTypeVerifier())
self.trigger = trigger
self.outcome = outcome
if self.transition_info.fully_specified:
compile_transitions(self)
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_mapping(self)
def compile_transit... | 64 | 64 | 70 | 6 | 58 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | compile_transitions | compile_transitions | 207 | 212 | 207 | 207 | c6e0f77cc3041e459489c7180f425717a75d6379 | bigcode/the-stack | train |
82d288e17d4bda0dbe7bc33f | train | class | class TransitionInfo(object):
"""Whether an expression has a state, action or outcome set."""
def __init__(self, has_action=False, has_state=False, has_outcome=False):
# Whether there is an action column
self.has_action = has_action
# Whether there is a state column
self.has_sta... | class TransitionInfo(object):
| """Whether an expression has a state, action or outcome set."""
def __init__(self, has_action=False, has_state=False, has_outcome=False):
# Whether there is an action column
self.has_action = has_action
# Whether there is a state column
self.has_state = has_state
# Wheth... | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import typing
from hiive.visualization import mdpviz
from hiive.visualization.mdpviz.dsl import context
class DslSyntaxError(SyntaxError):
pass
class TransitionInfo(object):
| 64 | 64 | 160 | 5 | 58 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | TransitionInfo | TransitionInfo | 24 | 41 | 24 | 24 | 6dfefbd87cfb076877c924ccf54760506f13a3bc | bigcode/the-stack | train |
73753d58c039b86e356356e4 | train | class | class SupportConjunction(object):
def __and__(self: Node, right):
return Conjunction(self, right)
| class SupportConjunction(object):
| def __and__(self: Node, right):
return Conjunction(self, right)
| Visitor') -> typing.Any:
return visitor.visit_atom(self)
def __or__(self, other):
return Alternatives([self]) | other
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.__dict__)
class SupportConjunction(object):
| 64 | 64 | 25 | 6 | 58 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | SupportConjunction | SupportConjunction | 64 | 66 | 64 | 64 | 902f1720d5026a33f88267d382ef0147bd208b4a | bigcode/the-stack | train |
eeea297476633eeeb3126ca7 | train | class | class Action(Node, SupportConjunction, SupportMapping):
def __init__(self, action):
super().__init__()
self.action = action
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_action(self)
| class Action(Node, SupportConjunction, SupportMapping):
| def __init__(self, action):
super().__init__()
self.action = action
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_action(self)
| __()
self.reward = reward
def __mul__(self, other):
return Reward(mdpviz.Reward(self.reward.outcome, self.reward.weight * other))
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_reward(self)
class Action(Node, SupportConjunction, SupportMapping):
| 64 | 64 | 49 | 11 | 53 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Action | Action | 130 | 137 | 130 | 130 | fc6a68c2a5c7dab3935f0bddb1fdf43354b47b56 | bigcode/the-stack | train |
bb415ac7f3be38fabe0b1f5d | train | class | class TriggerTypeVerifier(NodeVisitor):
"""Verifies that all types are valid as triggers."""
def fail(self, node):
raise DslSyntaxError('%s not a valid trigger for a transition (either a State or an Action)!' % node)
def visit_alternatives(self, node: Alternatives):
for alternative in node... | class TriggerTypeVerifier(NodeVisitor):
| """Verifies that all types are valid as triggers."""
def fail(self, node):
raise DslSyntaxError('%s not a valid trigger for a transition (either a State or an Action)!' % node)
def visit_alternatives(self, node: Alternatives):
for alternative in node.alternatives:
alternative.a... | self.fail(node)
def visit_conjunction(self, node: Conjunction):
# A conjunction cannot be an outcome.
self.fail(node)
def visit_reward(self, node: Reward):
pass
def visit_state(self, node: State):
pass
class TriggerTypeVerifier(NodeVisitor):
| 64 | 64 | 209 | 7 | 56 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | TriggerTypeVerifier | TriggerTypeVerifier | 272 | 301 | 272 | 272 | bfd36d172210ff32208a632267907ee950b43262 | bigcode/the-stack | train |
5e2cd09df70a5405520210da | train | class | class Node(object):
def __init__(self):
self._transition_info = None
@property
def transition_info(self) -> TransitionInfo:
if not self._transition_info:
self._transition_info = self.apply(TransitionInfoVisitor())
return self._transition_info
def apply(self, visitor... | class Node(object):
| def __init__(self):
self._transition_info = None
@property
def transition_info(self) -> TransitionInfo:
if not self._transition_info:
self._transition_info = self.apply(TransitionInfoVisitor())
return self._transition_info
def apply(self, visitor: 'NodeVisitor') -> ... | return '%s(%s)' % (self.__class__.__name__, self.__dict__)
@property
def fully_specified(self):
"""Whether all three attributes have been provided and transitions are thus fully specified."""
return self.has_state and self.has_action and self.has_outcome
class Node(object):
| 64 | 64 | 128 | 4 | 59 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Node | Node | 44 | 61 | 44 | 44 | 6830b8e6507ca3eb12564b0fd481ac2978dd9d81 | bigcode/the-stack | train |
d3f74f8b45885ec56f9f8870 | train | class | class Reward(Node):
def __init__(self, reward: mdpviz.Reward):
super().__init__()
self.reward = reward
def __mul__(self, other):
return Reward(mdpviz.Reward(self.reward.outcome, self.reward.weight * other))
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_rewa... | class Reward(Node):
| def __init__(self, reward: mdpviz.Reward):
super().__init__()
self.reward = reward
def __mul__(self, other):
return Reward(mdpviz.Reward(self.reward.outcome, self.reward.weight * other))
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_reward(self)
| return Alternatives(self.alternatives + other.alternatives)
else:
return Alternatives(self.alternatives + [other])
def __mul__(self, prob):
# noinspection PyUnresolvedReferences
return Alternatives([alternative * prob for alternative in self.alternatives])
class Reward(Node):
| 63 | 64 | 76 | 4 | 59 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Reward | Reward | 117 | 127 | 117 | 117 | 3b4c9cd9ea6887296ecc16baabbb547b0a41745b | bigcode/the-stack | train |
9c274b1530149cd1f9384990 | train | class | class TransitionVisitor(NodeVisitor):
"""Returns a generator yielding all transitions.
Assumes that the root node's transition info is fully specified."""
def __init__(self, iterator: typing.Iterable[Transition]):
self.iterator = iterator
def visit_action(self, node: Action):
for trans... | class TransitionVisitor(NodeVisitor):
| """Returns a generator yielding all transitions.
Assumes that the root node's transition info is fully specified."""
def __init__(self, iterator: typing.Iterable[Transition]):
self.iterator = iterator
def visit_action(self, node: Action):
for transition in self.iterator:
yi... | or right_transition_info.has_state,
has_outcome=right_transition_info.has_outcome)
def visit_mapping(self, node: Mapping):
return TransitionInfo(has_action=node.trigger.transition_info.has_action,
has_state=node.trigger.transition_info.has_state,... | 64 | 64 | 189 | 6 | 58 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | TransitionVisitor | TransitionVisitor | 346 | 370 | 346 | 346 | 04e77ac062e2c7bc6738e26fc6afe0c6452ba1d6 | bigcode/the-stack | train |
12fdb7d22d39717dfbb1b404 | train | class | class WeightedState(Node):
def __init__(self, next_state: mdpviz.NextState):
super().__init__()
self.next_state = next_state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.next_state.outcome, self.next_state.weight * other))
def apply(self, visitor: 'NodeVisi... | class WeightedState(Node):
| def __init__(self, next_state: mdpviz.NextState):
super().__init__()
self.next_state = next_state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.next_state.outcome, self.next_state.weight * other))
def apply(self, visitor: 'NodeVisitor'):
return visit... | state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.state, other))
def __gt__(self, other):
return Mapping(self, other)
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_state(self)
class WeightedState(Node):
| 64 | 64 | 85 | 5 | 59 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | WeightedState | WeightedState | 156 | 166 | 156 | 156 | 310f4c5f75e300d236377eeb8d29b9fe85a1daee | bigcode/the-stack | train |
7ee90d7e4befbd5cfb9fdd5d | train | class | class OutcomeTypeVerifier(NodeVisitor):
"""Verifies that all nodes are valid as outcomes."""
def fail(self, node):
raise DslSyntaxError('%s not a valid outcome of a transition (either Reward or State)!' % node)
def visit_weighted_state(self, node: WeightedState):
pass
def visit_altern... | class OutcomeTypeVerifier(NodeVisitor):
| """Verifies that all nodes are valid as outcomes."""
def fail(self, node):
raise DslSyntaxError('%s not a valid outcome of a transition (either Reward or State)!' % node)
def visit_weighted_state(self, node: WeightedState):
pass
def visit_alternatives(self, node: Alternatives):
... | )
def visit_weighted_state(self, node: WeightedState):
return self.visit_atom(node)
def visit_conjunction(self, node: Conjunction):
return self.visit_atom(node)
def visit_mapping(self, node: Mapping):
return self.visit_atom(node)
class OutcomeTypeVerifier(NodeVisitor):
| 64 | 64 | 191 | 7 | 57 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | OutcomeTypeVerifier | OutcomeTypeVerifier | 241 | 269 | 241 | 241 | c7a74e1a616dc7dd6988d7c1f78bbc117ad94b82 | bigcode/the-stack | train |
e8a97c71080f6e78c2c155d5 | train | class | class Transition(object):
"""Immutable transition call (by gentleman's agreement)."""
def __init__(self, state=None, action=None, outcome=None):
self.state = state
self.action = action
self.outcome = outcome
def replace(self, state=None, action=None, outcome=None):
def not_... | class Transition(object):
| """Immutable transition call (by gentleman's agreement)."""
def __init__(self, state=None, action=None, outcome=None):
self.state = state
self.action = action
self.outcome = outcome
def replace(self, state=None, action=None, outcome=None):
def not_already_set(new, current):... | % (self.__class__.__name__, self.__dict__)
class SupportConjunction(object):
def __and__(self: Node, right):
return Conjunction(self, right)
class SupportMapping(object):
def __gt__(self: Node, outcome):
return Mapping(self, outcome)
class Transition(object):
| 64 | 64 | 181 | 4 | 60 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Transition | Transition | 74 | 93 | 74 | 74 | bf3b8e60ee3254f43341f1af6642c2d584353535 | bigcode/the-stack | train |
115fee063c17a14923dd8bd1 | train | class | class State(Node, SupportConjunction, SupportMapping):
def __init__(self, state):
super().__init__()
self.state = state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.state, other))
def __gt__(self, other):
return Mapping(self, other)
def apply(s... | class State(Node, SupportConjunction, SupportMapping):
| def __init__(self, state):
super().__init__()
self.state = state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.state, other))
def __gt__(self, other):
return Mapping(self, other)
def apply(self, visitor: 'NodeVisitor'):
return visitor.vi... | .visit_reward(self)
class Action(Node, SupportConjunction, SupportMapping):
def __init__(self, action):
super().__init__()
self.action = action
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_action(self)
class State(Node, SupportConjunction, SupportMapping):
| 64 | 64 | 88 | 11 | 53 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | State | State | 140 | 153 | 140 | 140 | b113352efad9a6407545ca29faa5de9bfecabfc0 | bigcode/the-stack | train |
0b9f1bb4f0190dd6d31536e8 | train | class | class NodeVisitor(object):
def visit_atom(self, node: Node):
raise AssertionError('This should be unreachable!')
def visit_alternatives(self, node: Alternatives):
return self.visit_atom(node)
def visit_reward(self, node: Reward):
return self.visit_atom(node)
def visit_action(s... | class NodeVisitor(object):
| def visit_atom(self, node: Node):
raise AssertionError('This should be unreachable!')
def visit_alternatives(self, node: Alternatives):
return self.visit_atom(node)
def visit_reward(self, node: Reward):
return self.visit_atom(node)
def visit_action(self, node: Action):
... | (TransitionVisitor([Transition()]))
for transition in transitions:
if transition.state.terminal_state:
raise DslSyntaxError('Attempted to specify transition %s for terminal state!' % transition)
context.mdp_spec.transition(transition.state, transition.action, transition.outcome)
class No... | 64 | 64 | 152 | 5 | 59 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | NodeVisitor | NodeVisitor | 215 | 238 | 215 | 215 | bcf9eda38a67c5720d1b044f601cfdea74bb90a5 | bigcode/the-stack | train |
3e535f84c0ead91a9f6e8fde | train | class | class TransitionOutcomeVisitor(NodeVisitor):
def __init__(self, iterator: typing.Iterable[Transition]):
self.iterator = iterator
def visit_alternatives(self, node: Alternatives):
transitions = list(self.iterator)
for alternative in node.alternatives:
yield from alternative.a... | class TransitionOutcomeVisitor(NodeVisitor):
| def __init__(self, iterator: typing.Iterable[Transition]):
self.iterator = iterator
def visit_alternatives(self, node: Alternatives):
transitions = list(self.iterator)
for alternative in node.alternatives:
yield from alternative.apply(TransitionOutcomeVisitor(transitions))
... | (TransitionVisitor(transitions))
def visit_mapping(self, node: Mapping):
return node.outcome.apply(TransitionOutcomeVisitor(node.trigger.apply(self)))
def visit_conjunction(self, node: Conjunction):
return node.right.apply(TransitionVisitor(node.left.apply(self)))
class TransitionOutcomeVisito... | 63 | 64 | 156 | 7 | 56 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | TransitionOutcomeVisitor | TransitionOutcomeVisitor | 373 | 392 | 373 | 373 | 4c13e5ad86710646d914e1a0587cf20994a836cd | bigcode/the-stack | train |
49f7b2652e31832cb9551814 | train | class | class DslSyntaxError(SyntaxError):
pass
| class DslSyntaxError(SyntaxError):
| pass
| WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import typing
from hiive.visualization import mdpviz
from hiive.visualization.mdpviz.dsl import context
class DslSyntaxError(SyntaxError):
| 64 | 64 | 12 | 9 | 54 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | DslSyntaxError | DslSyntaxError | 20 | 21 | 20 | 20 | 8a3730a6cc97886efd012f4ac13ed09b8017eec0 | bigcode/the-stack | train |
3934c7ec751131cdd393eca1 | train | class | class Alternatives(Node, SupportConjunction, SupportMapping):
def __init__(self, alternatives: typing.List[Node]):
super().__init__()
self.alternatives = alternatives
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_alternatives(self)
def __or__(self, other: Node):
... | class Alternatives(Node, SupportConjunction, SupportMapping):
| def __init__(self, alternatives: typing.List[Node]):
super().__init__()
self.alternatives = alternatives
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_alternatives(self)
def __or__(self, other: Node):
if isinstance(other, Alternatives):
# Mergin... | not_already_set(outcome, self.outcome), (outcome, self.outcome)
state = state or self.state
action = action or self.action
outcome = outcome or self.outcome
return Transition(state, action, outcome)
class Alternatives(Node, SupportConjunction, SupportMapping):
| 64 | 64 | 146 | 11 | 53 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Alternatives | Alternatives | 96 | 114 | 96 | 96 | df77fb5582112f32c1f38045e57f1484f6d4b036 | bigcode/the-stack | train |
9ed26a651f89136c4d1d800d | train | class | class Conjunction(Node, SupportMapping):
def __init__(self, left: Node, right: Node):
super().__init__()
left.apply(TriggerTypeVerifier())
# right can be either a mapping (so have an outcome) or be a trigger
if not right.transition_info.has_outcome:
# right must be a tri... | class Conjunction(Node, SupportMapping):
| def __init__(self, left: Node, right: Node):
super().__init__()
left.apply(TriggerTypeVerifier())
# right can be either a mapping (so have an outcome) or be a trigger
if not right.transition_info.has_outcome:
# right must be a trigger
right.apply(TriggerTypeV... | _state = next_state
def __mul__(self, other):
return WeightedState(mdpviz.NextState(self.next_state.outcome, self.next_state.weight * other))
def apply(self, visitor: 'NodeVisitor'):
return visitor.visit_weighted_state(self)
class Conjunction(Node, SupportMapping):
| 64 | 64 | 138 | 8 | 56 | fordb/hiivemdptoolbox | hiive/visualization/mdpviz/dsl/ast.py | Python | Conjunction | Conjunction | 169 | 187 | 169 | 169 | e82d2953e37cdddd91601cf56fb2879a8e9e5a09 | bigcode/the-stack | train |
c6fd8ae33b440d73686c5269 | train | class | class GRUCell(nn.Module):
def __init__(self, inp_size,
size, norm=False, act=torch.tanh, update_bias=-1):
super(GRUCell, self).__init__()
self._inp_size = inp_size
self._size = size
self._act = act
self._norm = norm
self._update_bias = update_bias
self._layer = nn.Linear(in... | class GRUCell(nn.Module):
| def __init__(self, inp_size,
size, norm=False, act=torch.tanh, update_bias=-1):
super(GRUCell, self).__init__()
self._inp_size = inp_size
self._size = size
self._act = act
self._norm = norm
self._update_bias = update_bias
self._layer = nn.Linear(inp_size+size, 3*size,
... | dist = tools.OneHotDist(x)
elif self._dist == 'onehot_gumble':
x = self._dist_layer(x)
temp = self._temp
dist = tools.ContDist(torchd.gumbel.Gumbel(x, 1/temp))
else:
raise NotImplementedError(self._dist)
return dist
class GRUCell(nn.Module):
| 81 | 81 | 271 | 7 | 73 | TachikakaMin/dreamer-torch | networks.py | Python | GRUCell | GRUCell | 641 | 670 | 641 | 642 | 41a7a9846c23b38c2a4602cb49d8db64445101b7 | bigcode/the-stack | train |
4e134fe27ec8f56e76906bfd | train | class | class ConvEncoder(nn.Module):
def __init__(self, grayscale=False,
depth=32, act=nn.ReLU, kernels=(4, 4, 4, 4)):
super(ConvEncoder, self).__init__()
self._act = act
self._depth = depth
self._kernels = kernels
layers = []
for i, kernel in enumerate(self._kernels):
if i == ... | class ConvEncoder(nn.Module):
| def __init__(self, grayscale=False,
depth=32, act=nn.ReLU, kernels=(4, 4, 4, 4)):
super(ConvEncoder, self).__init__()
self._act = act
self._depth = depth
self._kernels = kernels
layers = []
for i, kernel in enumerate(self._kernels):
if i == 0:
if grayscale:
... | 1):
x = x.squeeze(0)
mean, std = torch.split(x, 2, -1)
std = F.softplus(std + self._init_std) + self._min_std
dist = torchd.normal.Normal(mean, std)
dist = tools.ContDist(torchd.independent.Independent(dist, 1))
return dist
class ConvEncoder(nn.Module):
| 84 | 84 | 280 | 6 | 77 | TachikakaMin/dreamer-torch | networks.py | Python | ConvEncoder | ConvEncoder | 313 | 342 | 313 | 314 | 01e513e62804114ad838c607a3b16fa2ec74f97e | bigcode/the-stack | train |
22576963b51d263fed949fb3 | train | class | class ActionHead(nn.Module):
def __init__(
self, inp_dim, size, layers, units, act=nn.ELU, dist='trunc_normal',
init_std=0.0, min_std=0.1, action_disc=5, temp=0.1, outscale=0):
super(ActionHead, self).__init__()
self._size = size
self._layers = layers
self._units = units
self._dist = ... | class ActionHead(nn.Module):
| def __init__(
self, inp_dim, size, layers, units, act=nn.ELU, dist='trunc_normal',
init_std=0.0, min_std=0.1, action_disc=5, temp=0.1, outscale=0):
super(ActionHead, self).__init__()
self._size = size
self._layers = layers
self._units = units
self._dist = dist
self._act = act
s... | (self._shape)))
raise NotImplementedError(self._dist)
# use obs train actor
class ObsDenseHead(nn.Module):
def __init__(
self, inp_dim,
shape, layers, units, act=nn.ELU, dist='normal', std=1.0):
super(ObsDenseHead, self).__init__()
self._shape = (shape,) if isinstance(shape, int) else shape
... | 256 | 256 | 892 | 6 | 249 | TachikakaMin/dreamer-torch | networks.py | Python | ActionHead | ActionHead | 474 | 554 | 474 | 475 | f4cf12e2324a462b71f4c284254a4c6dcd572eb9 | bigcode/the-stack | train |
e4d12cd1abaf2fd55f06f46c | train | class | class ObsActor(nn.Module):
def __init__(
self, inp_dim, size, layers, units, act=nn.ELU, dist='trunc_normal',
init_std=0.0, min_std=0.1, action_disc=5, temp=0.1, outscale=0):
super(ObsActor, self).__init__()
self._size = size
self._layers = layers
self._units = units
self._dist = dist... | class ObsActor(nn.Module):
| def __init__(
self, inp_dim, size, layers, units, act=nn.ELU, dist='trunc_normal',
init_std=0.0, min_std=0.1, action_disc=5, temp=0.1, outscale=0):
super(ObsActor, self).__init__()
self._size = size
self._layers = layers
self._units = units
self._dist = dist
self._act = act
sel... | == 'normal_1':
x = self._dist_layer(x)
dist = torchd.normal.Normal(x, 1)
dist = tools.ContDist(torchd.independent.Independent(dist, 1))
elif self._dist == 'trunc_normal':
x = self._dist_layer(x)
mean, std = torch.split(x, [self._size]*2, -1)
mean = torch.tanh(mean)
std = 2... | 256 | 256 | 895 | 6 | 249 | TachikakaMin/dreamer-torch | networks.py | Python | ObsActor | ObsActor | 557 | 638 | 557 | 558 | a3dc359bf80a5408475a3409dee9d06b299a6586 | bigcode/the-stack | train |
00c8f9ebfd7dd26a4e470ed3 | train | class | class ConvActor(nn.Module):
def __init__(self, config, grayscale=False,
depth=32, act=nn.ReLU, kernels=(4, 4, 4, 4),
fc_layer_num=3, init_std=0.0, min_std=0.1,
units=400):
super(ConvActor, self).__init__()
if config.size[0] == 64 and config.size[1] == 64:
e... | class ConvActor(nn.Module):
| def __init__(self, config, grayscale=False,
depth=32, act=nn.ReLU, kernels=(4, 4, 4, 4),
fc_layer_num=3, init_std=0.0, min_std=0.1,
units=400):
super(ConvActor, self).__init__()
if config.size[0] == 64 and config.size[1] == 64:
embed_size = 2 ** (len(config... | dist(rhs) if self._discrete else dist(rhs)._dist)
loss = torch.mean(torch.maximum(value, free))
else:
value_lhs = value = kld(dist(lhs) if self._discrete else dist(lhs)._dist,
dist(sg(rhs)) if self._discrete else dist(sg(rhs))._dist)
value_rhs = kld(dist(sg(lhs)) if ... | 195 | 195 | 650 | 6 | 188 | TachikakaMin/dreamer-torch | networks.py | Python | ConvActor | ConvActor | 244 | 310 | 244 | 244 | d9212afb7801fa5b065059e0e0d08d57bf0d4f29 | bigcode/the-stack | train |
e1edfee8b8b77d9b5b0a56f4 | train | class | class RSSM(nn.Module):
def __init__(
self, config, stoch=30, deter=200, hidden=200, layers_input=1, layers_output=1,
rec_depth=1, shared=False, discrete=False, act=nn.ELU,
mean_act='none', std_act='softplus', temp_post=True, min_std=0.1,
cell='gru',
num_actions=None, embed = None, devic... | class RSSM(nn.Module):
| def __init__(
self, config, stoch=30, deter=200, hidden=200, layers_input=1, layers_output=1,
rec_depth=1, shared=False, discrete=False, act=nn.ELU,
mean_act='none', std_act='softplus', temp_post=True, min_std=0.1,
cell='gru',
num_actions=None, embed = None, device=None):
super(RSSM,... | import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch import distributions as torchd
import tools
class RSSM(nn.Module):
| 37 | 256 | 2,383 | 6 | 30 | TachikakaMin/dreamer-torch | networks.py | Python | RSSM | RSSM | 11 | 241 | 11 | 12 | 3ee3c4e1c046c561005a68e8e9beeb1cc47cc92a | bigcode/the-stack | train |
d6ce1857da62f56ea4e887e7 | train | class | class DenseHead(nn.Module):
def __init__(
self, inp_dim,
shape, layers, units, act=nn.ELU, dist='normal', std=1.0):
super(DenseHead, self).__init__()
self._shape = (shape,) if isinstance(shape, int) else shape
if len(self._shape) == 0:
self._shape = (1,)
self._layers = layers
se... | class DenseHead(nn.Module):
| def __init__(
self, inp_dim,
shape, layers, units, act=nn.ELU, dist='normal', std=1.0):
super(DenseHead, self).__init__()
self._shape = (shape,) if isinstance(shape, int) else shape
if len(self._shape) == 0:
self._shape = (1,)
self._layers = layers
self._units = units
self._a... | x = self._linear_layer(features)
x = x.reshape([-1, 2, 2, 32 * self._depth])
x = x.permute(0,3,1,2)
x = self._cnnt_layers(x)
mean = x.reshape(features.shape[:-1] + self._shape)
mean = mean.permute(0, 1, 3, 4, 2)
return tools.ContDist(torchd.independent.Independent(
torchd.normal.... | 125 | 126 | 423 | 6 | 119 | TachikakaMin/dreamer-torch | networks.py | Python | DenseHead | DenseHead | 398 | 442 | 398 | 399 | bb9073b3e4e284317709d636548adc59037f5ee1 | bigcode/the-stack | train |
891931e576be74f26debaea1 | train | class | class ConvDecoder(nn.Module):
def __init__(
self, inp_depth,
depth=32, act=nn.ReLU, shape=(3, 64, 64), kernels=(5, 5, 6, 6),
thin=True):
super(ConvDecoder, self).__init__()
self._inp_depth = inp_depth
self._act = act
self._depth = depth
self._shape = shape
self._kernels = ke... | class ConvDecoder(nn.Module):
| def __init__(
self, inp_depth,
depth=32, act=nn.ReLU, shape=(3, 64, 64), kernels=(5, 5, 6, 6),
thin=True):
super(ConvDecoder, self).__init__()
self._inp_depth = inp_depth
self._act = act
self._depth = depth
self._shape = shape
self._kernels = kernels
self._thin = thin
... | 2 ** (i-1) * self._depth
depth = 2 ** i * self._depth
layers.append(nn.Conv2d(inp_dim, depth, kernel, 2))
layers.append(act())
self.layers = nn.Sequential(*layers)
def __call__(self, obs):
x = obs['image'].reshape((-1,) + tuple(obs['image'].shape[-3:]))
x = x.permute(0, 3, 1, 2)
x =... | 162 | 162 | 542 | 6 | 156 | TachikakaMin/dreamer-torch | networks.py | Python | ConvDecoder | ConvDecoder | 345 | 395 | 345 | 346 | 274078dbf8fabe6583300528c99a58381c5d8515 | bigcode/the-stack | train |
db7f93948e0a98ca1765a404 | train | class | class ObsDenseHead(nn.Module):
def __init__(
self, inp_dim,
shape, layers, units, act=nn.ELU, dist='normal', std=1.0):
super(ObsDenseHead, self).__init__()
self._shape = (shape,) if isinstance(shape, int) else shape
if len(self._shape) == 0:
self._shape = (1,)
self._layers = layers
... | class ObsDenseHead(nn.Module):
| def __init__(
self, inp_dim,
shape, layers, units, act=nn.ELU, dist='normal', std=1.0):
super(ObsDenseHead, self).__init__()
self._shape = (shape,) if isinstance(shape, int) else shape
if len(self._shape) == 0:
self._shape = (1,)
self._layers = layers
self._units = units
self... | (self._shape)))
if self._dist == 'binary':
return tools.Bernoulli(torchd.independent.Independent(
torchd.bernoulli.Bernoulli(logits=mean), len(self._shape)))
raise NotImplementedError(self._dist)
# use obs train actor
class ObsDenseHead(nn.Module):
| 69 | 69 | 231 | 7 | 61 | TachikakaMin/dreamer-torch | networks.py | Python | ObsDenseHead | ObsDenseHead | 445 | 471 | 445 | 446 | 0ab95d207715fb088f1538de7bffc2c56566e483 | bigcode/the-stack | train |
a21296c6f9947e21af76ded0 | train | function | async def check_half_closeable_stream(stream_maker, clogged_stream_maker):
"""Perform a number of generic tests on a custom half-closeable stream
implementation.
This is similar to :func:`check_two_way_stream`, except that the maker
functions are expected to return objects that implement the
:class... | async def check_half_closeable_stream(stream_maker, clogged_stream_maker):
| """Perform a number of generic tests on a custom half-closeable stream
implementation.
This is similar to :func:`check_two_way_stream`, except that the maker
functions are expected to return objects that implement the
:class:`~trio.abc.HalfCloseableStream` interface.
This function tests a *sup... | .receive_some(r.randint(1, CHUNK_SIZE_MAX))
assert chunk
got += chunk
assert got == data
async with _core.open_nursery() as nursery:
nursery.start_soon(sender, s1, test_data, 0)
nursery.start_soon(sender, s2, test_data[::-1], 1)
nu... | 186 | 186 | 621 | 16 | 170 | gilbertekalea/booking.com_crawler | venv/Lib/site-packages/trio/testing/_check_streams.py | Python | check_half_closeable_stream | check_half_closeable_stream | 450 | 512 | 450 | 450 | 14e6116f35eadaffe816019fee8e54c663f2549a | bigcode/the-stack | train |
cbea36dca677500d28573373 | train | function | async def check_one_way_stream(stream_maker, clogged_stream_maker):
"""Perform a number of generic tests on a custom one-way stream
implementation.
Args:
stream_maker: An async (!) function which returns a connected
(:class:`~trio.abc.SendStream`, :class:`~trio.abc.ReceiveStream`)
... | async def check_one_way_stream(stream_maker, clogged_stream_maker):
| """Perform a number of generic tests on a custom one-way stream
implementation.
Args:
stream_maker: An async (!) function which returns a connected
(:class:`~trio.abc.SendStream`, :class:`~trio.abc.ReceiveStream`)
pair.
clogged_stream_maker: Either None, or an async function... | # Generic stream tests
from contextlib import contextmanager
import random
from .. import _core
from .._highlevel_generic import aclose_forcefully
from .._abc import SendStream, ReceiveStream, Stream, HalfCloseableStream
from ._checkpoints import assert_checkpoints
class _ForceCloseBoth:
def __init__(self, both... | 205 | 256 | 3,049 | 15 | 190 | gilbertekalea/booking.com_crawler | venv/Lib/site-packages/trio/testing/_check_streams.py | Python | check_one_way_stream | check_one_way_stream | 37 | 376 | 37 | 37 | 042fcbbf11774e82a409565c04a9608b76c098ff | bigcode/the-stack | train |
e06ceaf41c0ad2434c298227 | train | function | @contextmanager
def _assert_raises(exc):
__tracebackhide__ = True
try:
yield
except exc:
pass
else:
raise AssertionError("expected exception: {}".format(exc))
| @contextmanager
def _assert_raises(exc):
| __tracebackhide__ = True
try:
yield
except exc:
pass
else:
raise AssertionError("expected exception: {}".format(exc))
| aenter__(self):
return self._both
async def __aexit__(self, *args):
try:
await aclose_forcefully(self._both[0])
finally:
await aclose_forcefully(self._both[1])
@contextmanager
def _assert_raises(exc):
| 64 | 64 | 48 | 11 | 53 | gilbertekalea/booking.com_crawler | venv/Lib/site-packages/trio/testing/_check_streams.py | Python | _assert_raises | _assert_raises | 26 | 34 | 26 | 27 | 4fcd4429bc5813c9499d4c73d5f4dac97c0867cb | bigcode/the-stack | train |
ca4fff24c1b0da481256da20 | train | class | class _ForceCloseBoth:
def __init__(self, both):
self._both = list(both)
async def __aenter__(self):
return self._both
async def __aexit__(self, *args):
try:
await aclose_forcefully(self._both[0])
finally:
await aclose_forcefully(self._both[1])
| class _ForceCloseBoth:
| def __init__(self, both):
self._both = list(both)
async def __aenter__(self):
return self._both
async def __aexit__(self, *args):
try:
await aclose_forcefully(self._both[0])
finally:
await aclose_forcefully(self._both[1])
| tests
from contextlib import contextmanager
import random
from .. import _core
from .._highlevel_generic import aclose_forcefully
from .._abc import SendStream, ReceiveStream, Stream, HalfCloseableStream
from ._checkpoints import assert_checkpoints
class _ForceCloseBoth:
| 64 | 64 | 81 | 6 | 57 | gilbertekalea/booking.com_crawler | venv/Lib/site-packages/trio/testing/_check_streams.py | Python | _ForceCloseBoth | _ForceCloseBoth | 12 | 23 | 12 | 12 | a5799646f1fd3a7f5e9ec087e912845646c5e8c9 | bigcode/the-stack | train |
a6ec76bb44765273f5794d37 | train | function | async def check_two_way_stream(stream_maker, clogged_stream_maker):
"""Perform a number of generic tests on a custom two-way stream
implementation.
This is similar to :func:`check_one_way_stream`, except that the maker
functions are expected to return objects implementing the
:class:`~trio.abc.Stre... | async def check_two_way_stream(stream_maker, clogged_stream_maker):
| """Perform a number of generic tests on a custom two-way stream
implementation.
This is similar to :func:`check_one_way_stream`, except that the maker
functions are expected to return objects implementing the
:class:`~trio.abc.Stream` interface.
This function tests a *superset* of what :func:`... | it to wake up.
async def close_soon(s):
await _core.wait_all_tasks_blocked()
await aclose_forcefully(s)
async with _ForceCloseBoth(await clogged_stream_maker()) as (s, r):
async with _core.open_nursery() as nursery:
nursery.start_soon(close_soon, s)
... | 179 | 179 | 597 | 15 | 164 | gilbertekalea/booking.com_crawler | venv/Lib/site-packages/trio/testing/_check_streams.py | Python | check_two_way_stream | check_two_way_stream | 379 | 447 | 379 | 379 | d70da88b4a1b3af6ba331026460d7e87fbdf1340 | bigcode/the-stack | train |
11b57fdf9b3e8da0a48a53b0 | train | class | @tvm._ffi.register_object("tir.Block")
class Block(Stmt):
"""Block node.
Parameters
----------
iter_vars : List[IterVar]
The block Variable.
reads : List[BufferRegion]
The read buffer regions of the block.
writes: List[BufferRegion]
The write buffer regions of the bloc... | @tvm._ffi.register_object("tir.Block")
class Block(Stmt):
| """Block node.
Parameters
----------
iter_vars : List[IterVar]
The block Variable.
reads : List[BufferRegion]
The read buffer regions of the block.
writes: List[BufferRegion]
The write buffer regions of the block.
name_hint: str
the name_hint of the block.... | _api.BufferRegion, buffer, region) # type: ignore
@tvm._ffi.register_object("tir.MatchBufferRegion")
class MatchBufferRegion(Object):
"""MatchBufferRegion node.
Parameters
----------
buffer : Buffer
The target buffer
source : BufferRegion
The region of source buffer
"""
... | 140 | 140 | 467 | 16 | 124 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | Block | Block | 535 | 614 | 535 | 536 | aa850724bddaa211ebc80e461dbec1ca511bf2ca | bigcode/the-stack | train |
dc1a3cc5cff9699b5d7f21e5 | train | class | @tvm._ffi.register_object("tir.ProducerStore")
class ProducerStore(Stmt):
"""ProducerStore node.
Parameters
----------
producer : DataProducer
The data producer.
value : PrimExpr
The value to be stored.
indices : list of Expr
The index arguments of the store.
span... | @tvm._ffi.register_object("tir.ProducerStore")
class ProducerStore(Stmt):
| """ProducerStore node.
Parameters
----------
producer : DataProducer
The data producer.
value : PrimExpr
The value to be stored.
indices : list of Expr
The index arguments of the store.
span : Optional[Span]
The location of this itervar in the source code.... | , buffer, bounds, condition, body, span=None):
self.__init_handle_by_constructor__(
_ffi_api.BufferRealize, buffer, bounds, condition, body, span # type: ignore
)
@tvm._ffi.register_object("tir.ProducerStore")
class ProducerStore(Stmt):
| 64 | 64 | 138 | 19 | 45 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | ProducerStore | ProducerStore | 275 | 297 | 275 | 276 | 4cdd39c2dc0d4de2f5f73c5c8a30ff52722d71da | bigcode/the-stack | train |
288a436849389c8de96f4a1b | train | class | @tvm._ffi.register_object("tir.BufferRealize")
class BufferRealize(Stmt):
"""Buffer realize node.
Parameters
----------
buffer : Buffer
The buffer.
bounds : List[Range]
The value we to be stored.
condition : PrimExpr
The realize condition.
body : Stmt
The ... | @tvm._ffi.register_object("tir.BufferRealize")
class BufferRealize(Stmt):
| """Buffer realize node.
Parameters
----------
buffer : Buffer
The buffer.
bounds : List[Range]
The value we to be stored.
condition : PrimExpr
The realize condition.
body : Stmt
The body of the statement.
span : Optional[Span]
The location of ... | __init__(self, buffer, value, indices, span=None):
self.__init_handle_by_constructor__(
_ffi_api.BufferStore, buffer, value, indices, span # type: ignore
)
@tvm._ffi.register_object("tir.BufferRealize")
class BufferRealize(Stmt):
| 64 | 64 | 152 | 20 | 44 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | BufferRealize | BufferRealize | 247 | 272 | 247 | 248 | 368b24864830958248eb8276b4c9ff4f5993913b | bigcode/the-stack | train |
2c83b294d2601b5d1ff80b9a | train | class | @tvm._ffi.register_object("tir.AssertStmt")
class AssertStmt(Stmt):
"""AssertStmt node.
Parameters
----------
condition : PrimExpr
The assert condition.
message : PrimExpr
The error message.
body : tvm.tir.Stmt
The body statement.
span : Optional[Span]
The... | @tvm._ffi.register_object("tir.AssertStmt")
class AssertStmt(Stmt):
| """AssertStmt node.
Parameters
----------
condition : PrimExpr
The assert condition.
message : PrimExpr
The error message.
body : tvm.tir.Stmt
The body statement.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __ini... | def __init__(self, var, value, body, span=None):
self.__init_handle_by_constructor__(
_ffi_api.LetStmt, var, value, body, span # type: ignore
)
@tvm._ffi.register_object("tir.AssertStmt")
class AssertStmt(Stmt):
| 64 | 64 | 134 | 18 | 46 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | AssertStmt | AssertStmt | 70 | 92 | 70 | 71 | 4f2c79a610b786feb1dba4856cdd8ba838500d73 | bigcode/the-stack | train |
658dff5e9244df2d172cc2c1 | train | class | @tvm._ffi.register_object("tir.For")
class For(Stmt):
"""For node.
Parameters
----------
loop_var : Var
The loop variable.
min_val : PrimExpr
The beginning value.
extent : PrimExpr
The length of the loop.
kind : ForKind
The type of the for.
body : Stm... | @tvm._ffi.register_object("tir.For")
class For(Stmt):
| """For node.
Parameters
----------
loop_var : Var
The loop variable.
min_val : PrimExpr
The beginning value.
extent : PrimExpr
The length of the loop.
kind : ForKind
The type of the for.
body : Stmt
The body statement.
thread_binding: Opt... | of the loop and need to be considered in all TIR passes.
"""
SERIAL = 0
PARALLEL = 1
VECTORIZED = 2
UNROLLED = 3
THREAD_BINDING = 4
@tvm._ffi.register_object("tir.For")
class For(Stmt):
| 71 | 71 | 238 | 16 | 54 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | For | For | 111 | 164 | 111 | 112 | 2773d01358d2c984ee768d67835722b479edd672 | bigcode/the-stack | train |
ea7b939a3284c9a477a5c18b | train | class | @tvm._ffi.register_object("tir.MatchBufferRegion")
class MatchBufferRegion(Object):
"""MatchBufferRegion node.
Parameters
----------
buffer : Buffer
The target buffer
source : BufferRegion
The region of source buffer
"""
buffer: Buffer
source: BufferRegion
def __i... | @tvm._ffi.register_object("tir.MatchBufferRegion")
class MatchBufferRegion(Object):
| """MatchBufferRegion node.
Parameters
----------
buffer : Buffer
The target buffer
source : BufferRegion
The region of source buffer
"""
buffer: Buffer
source: BufferRegion
def __init__(self, buffer: Buffer, source: BufferRegion):
self.__init_handle_by_con... | List[Range]
def __init__(self, buffer: Buffer, region: List[Range]):
self.__init_handle_by_constructor__(_ffi_api.BufferRegion, buffer, region) # type: ignore
@tvm._ffi.register_object("tir.MatchBufferRegion")
class MatchBufferRegion(Object):
| 64 | 64 | 110 | 19 | 44 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | MatchBufferRegion | MatchBufferRegion | 513 | 532 | 513 | 514 | 259fc814b5738ad35bd46c7263c90caac1be1d43 | bigcode/the-stack | train |
ac33a76241bb0ccabd94d946 | train | function | def stmt_seq(*args):
"""Make sequence of statements
Parameters
----------
args : list of Expr or Var
List of statements to be combined as sequence.
Returns
-------
stmt : Stmt
The combined statement.
"""
ret = []
for value in args:
if not isinstance(valu... | def stmt_seq(*args):
| """Make sequence of statements
Parameters
----------
args : list of Expr or Var
List of statements to be combined as sequence.
Returns
-------
stmt : Stmt
The combined statement.
"""
ret = []
for value in args:
if not isinstance(value, Stmt):
... | if isinstance(predicate, bool):
predicate = const(predicate, "bool")
self.__init_handle_by_constructor__(
_ffi_api.BlockRealize, # type: ignore
iter_values,
predicate,
block,
span,
) # type: ignore
def stmt_seq(*args):
| 64 | 64 | 106 | 6 | 57 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | stmt_seq | stmt_seq | 659 | 679 | 659 | 659 | 866cc0e61534a67a5c87747c04741d82dfb59a17 | bigcode/the-stack | train |
d4bc5ff442a279eaf38054b1 | train | class | @tvm._ffi.register_object("tir.BufferStore")
class BufferStore(Stmt):
"""Buffer store node.
Parameters
----------
buffer : Buffer
The buffer.
value : PrimExpr
The value we to be stored.
indices : List[PrimExpr]
The indices location to be stored.
span : Optional[Sp... | @tvm._ffi.register_object("tir.BufferStore")
class BufferStore(Stmt):
| """Buffer store node.
Parameters
----------
buffer : Buffer
The buffer.
value : PrimExpr
The value we to be stored.
indices : List[PrimExpr]
The indices location to be stored.
span : Optional[Span]
The location of this itervar in the source code.
"""
... | _api.const_true(value.dtype, span) # type: ignore
self.__init_handle_by_constructor__(
_ffi_api.Store, buffer_var, value, index, predicate, span # type: ignore
)
@tvm._ffi.register_object("tir.BufferStore")
class BufferStore(Stmt):
| 64 | 64 | 136 | 18 | 46 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | BufferStore | BufferStore | 222 | 244 | 222 | 223 | 58bfb8942956d4bdd9c1e7f31277d711535d97d9 | bigcode/the-stack | train |
b7ea0a1a8efb68d0b5ac0491 | train | class | @tvm._ffi.register_object("tir.While")
class While(Stmt):
"""While node.
Parameters
----------
condition : PrimExpr
The termination condition.
body : Stmt
The body statement.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init... | @tvm._ffi.register_object("tir.While")
class While(Stmt):
| """While node.
Parameters
----------
condition : PrimExpr
The termination condition.
body : Stmt
The body statement.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, condition, body, span=None):
self.__init_... | .__init_handle_by_constructor__(
_ffi_api.For, # type: ignore
loop_var,
min_val,
extent,
kind,
body,
thread_binding,
annotations,
span,
)
@tvm._ffi.register_object("tir.While")
class While(Stmt):
| 64 | 64 | 117 | 17 | 47 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | While | While | 167 | 189 | 167 | 168 | 637c243808906b0245d295aa0a0941fca9e11f98 | bigcode/the-stack | train |
f7395b27dcb1013f97d08df9 | train | class | class Stmt(Object):
"""Base class of all the statements."""
| class Stmt(Object):
| """Base class of all the statements."""
|
from typing import List, Mapping, Optional, Union
import tvm._ffi
from tvm.ir import PrimExpr, Range, Span
from tvm.runtime import Object, const
from . import _ffi_api
from .buffer import Buffer
from .expr import IterVar
class Stmt(Object):
| 64 | 64 | 14 | 5 | 58 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | Stmt | Stmt | 41 | 42 | 41 | 41 | 0f150baec0291d09b654f3c9411b9fc7883c60f0 | bigcode/the-stack | train |
ca35752e18ae8f93dd8a58a1 | train | class | @tvm._ffi.register_object("tir.Evaluate")
class Evaluate(Stmt):
"""Evaluate node.
Parameters
----------
value : PrimExpr
The expression to be evalued.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, value, span=None):
s... | @tvm._ffi.register_object("tir.Evaluate")
class Evaluate(Stmt):
| """Evaluate node.
Parameters
----------
value : PrimExpr
The expression to be evalued.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, value, span=None):
self.__init_handle_by_constructor__(_ffi_api.Evaluate, value, spa... | __(self, condition, then_case, else_case, span=None):
self.__init_handle_by_constructor__(
_ffi_api.IfThenElse, condition, then_case, else_case, span # type: ignore
)
@tvm._ffi.register_object("tir.Evaluate")
class Evaluate(Stmt):
| 64 | 64 | 99 | 17 | 47 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | Evaluate | Evaluate | 456 | 470 | 456 | 457 | 3353829a2d85dcbe10ca917d1b22b8489f479e36 | bigcode/the-stack | train |
cdf886556b1efbe1e6a05396 | train | class | @tvm._ffi.register_object("tir.IfThenElse")
class IfThenElse(Stmt):
"""IfThenElse node.
Parameters
----------
condition : PrimExpr
The expression
then_case : Stmt
The statement to execute if condition is true.
else_case : Stmt
The statement to execute if condition is f... | @tvm._ffi.register_object("tir.IfThenElse")
class IfThenElse(Stmt):
| """IfThenElse node.
Parameters
----------
condition : PrimExpr
The expression
then_case : Stmt
The statement to execute if condition is true.
else_case : Stmt
The statement to execute if condition is false.
span : Optional[Span]
The location of this iterva... | ffi_api.SeqStmt, seq, span) # type: ignore
def __getitem__(self, i):
return self.seq[i]
def __len__(self):
return len(self.seq)
@tvm._ffi.register_object("tir.IfThenElse")
class IfThenElse(Stmt):
| 64 | 64 | 149 | 20 | 44 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | IfThenElse | IfThenElse | 431 | 453 | 431 | 432 | e01fa41cfc6b5434afc9cd1feb318be55f0324fe | bigcode/the-stack | train |
9704c2a6f07ed68d40544f3b | train | class | @tvm._ffi.register_object("tir.Prefetch")
class Prefetch(Stmt):
"""Prefetch node.
Parameters
----------
buffer : Buffer
The buffer to be prefetched.
bounds : list of Range
The bounds to be prefetched.
span : Optional[Span]
The location of this itervar in the source cod... | @tvm._ffi.register_object("tir.Prefetch")
class Prefetch(Stmt):
| """Prefetch node.
Parameters
----------
buffer : Buffer
The buffer to be prefetched.
bounds : list of Range
The bounds to be prefetched.
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, buffer, bounds, span=None):
... | ervar in the source code.
"""
def __init__(self, value, span=None):
self.__init_handle_by_constructor__(_ffi_api.Evaluate, value, span) # type: ignore
@tvm._ffi.register_object("tir.Prefetch")
class Prefetch(Stmt):
| 64 | 64 | 121 | 19 | 44 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | Prefetch | Prefetch | 473 | 490 | 473 | 474 | e986f378b91a267a01a0934258293af2a80219ec | bigcode/the-stack | train |
1b67c9fe386f1b1ba37cdc69 | train | class | @tvm._ffi.register_object("tir.SeqStmt")
class SeqStmt(Stmt):
"""Sequence of statements.
Parameters
----------
seq : List[Stmt]
The statements
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, seq, span=None):
self.__init... | @tvm._ffi.register_object("tir.SeqStmt")
class SeqStmt(Stmt):
| """Sequence of statements.
Parameters
----------
seq : List[Stmt]
The statements
span : Optional[Span]
The location of this itervar in the source code.
"""
def __init__(self, seq, span=None):
self.__init_handle_by_constructor__(_ffi_api.SeqStmt, seq, span) # type:... | ):
self.__init_handle_by_constructor__(
_ffi_api.ProducerRealize,
producer,
bounds,
condition,
body,
storage_scope,
span, # type: ignore
)
@tvm._ffi.register_object("tir.SeqStmt")
class SeqStmt(Stmt):
| 64 | 64 | 128 | 19 | 45 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | SeqStmt | SeqStmt | 408 | 428 | 408 | 409 | 802482aa1e83b663c1e7bd86415af9ff8371ff3f | bigcode/the-stack | train |
6b06aa62e9c043fbe367b0db | train | function | def stmt_list(stmt):
"""Make list of stmt from blocks.
Parameters
----------
stmt : A block statement
Returns
-------
stmt_list : list of Stmt
The unpacked list of statements
"""
if isinstance(stmt, SeqStmt):
res = []
for x in stmt:
res += stmt_... | def stmt_list(stmt):
| """Make list of stmt from blocks.
Parameters
----------
stmt : A block statement
Returns
-------
stmt_list : list of Stmt
The unpacked list of statements
"""
if isinstance(stmt, SeqStmt):
res = []
for x in stmt:
res += stmt_list(x)
retur... |
The combined statement.
"""
ret = []
for value in args:
if not isinstance(value, Stmt):
value = Evaluate(value)
ret.append(value)
if len(ret) == 1:
return ret[0]
return SeqStmt(ret)
def stmt_list(stmt):
| 64 | 64 | 84 | 5 | 59 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | stmt_list | stmt_list | 682 | 699 | 682 | 682 | ef55b483542b713269e1fccfbc0f7abdc81c0ce9 | bigcode/the-stack | train |
3df8395cfc71c3063ee1f33b | train | class | @tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Parameters
----------
node : Node
The node to annotate the attribute
attr_key : str
Attribute type key.
value : PrimExpr
The value of the attribute
body : Stmt
The body state... | @tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
| """AttrStmt node.
Parameters
----------
node : Node
The node to annotate the attribute
attr_key : str
Attribute type key.
value : PrimExpr
The value of the attribute
body : Stmt
The body statement.
span : Optional[Span]
The location of this it... | self.__init_handle_by_constructor__(
_ffi_api.Allocate, # type: ignore
buffer_var,
dtype,
extents,
condition,
body,
annotations,
span,
)
@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
| 64 | 64 | 153 | 19 | 45 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | AttrStmt | AttrStmt | 343 | 368 | 343 | 344 | 62a3335431aab27389e90bd593eaaa47e74aef56 | bigcode/the-stack | train |
7df6c59005099bca2aa0dc29 | train | class | @tvm._ffi.register_object("tir.Allocate")
class Allocate(Stmt):
"""Allocate node.
Parameters
----------
buffer_var : Var
The buffer variable.
dtype : str
The data type of the buffer.
extents : list of Expr
The extents of the allocate
condition : PrimExpr
T... | @tvm._ffi.register_object("tir.Allocate")
class Allocate(Stmt):
| """Allocate node.
Parameters
----------
buffer_var : Var
The buffer variable.
dtype : str
The data type of the buffer.
extents : list of Expr
The extents of the allocate
condition : PrimExpr
The condition.
body : Stmt
The body statement.
... | def __init__(self, producer, value, indices, span=None):
self.__init_handle_by_constructor__(
_ffi_api.ProducerStore, producer, value, indices, span # type: ignore
)
@tvm._ffi.register_object("tir.Allocate")
class Allocate(Stmt):
| 64 | 64 | 207 | 17 | 47 | BaldLee/tvm | python/tvm/tir/stmt.py | Python | Allocate | Allocate | 300 | 340 | 300 | 301 | e2888b65c36c5377047ddd258953b0bbf33d5d19 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.