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
cc6566cd1e1689fbaff632eb
train
function
def _maybe_convert(values, val_kind, encoding, errors): if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) values = conv(values) return values
def _maybe_convert(values, val_kind, encoding, errors):
if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) values = conv(values) return values
data = data.astype(dtype, copy=False).astype(object, copy=False) if nan_rep is None: nan_rep = 'nan' data = libwriters.string_array_replace_from_nan_rep(data, nan_rep) return data.reshape(shape) def _maybe_convert(values, val_kind, encoding, errors):
64
64
60
13
51
getschomp/pandas
pandas/io/pytables.py
Python
_maybe_convert
_maybe_convert
4,710
4,715
4,710
4,710
9b28aceeb5fdbcf8e253455c79cfab311e54527e
bigcode/the-stack
train
30dabeb96842b6fbe0ff5eb1
train
class
class LegacyFixed(GenericFixed): def read_index_legacy(self, key, start=None, stop=None): node = getattr(self.group, key) data = node[start:stop] kind = node._v_attrs.kind return _unconvert_index_legacy(data, kind, encoding=self.encoding, error...
class LegacyFixed(GenericFixed):
def read_index_legacy(self, key, start=None, stop=None): node = getattr(self.group, key) data = node[start:stop] kind = node._v_attrs.kind return _unconvert_index_legacy(data, kind, encoding=self.encoding, errors=self.errors)
, value.view('i8')) getattr( self.group, key)._v_attrs.value_type = 'timedelta64' else: self._handle.create_array(self.group, key, value) getattr(self.group, key)._v_attrs.transposed = transposed class LegacyFixed(GenericFixed):
64
64
69
6
57
getschomp/pandas
pandas/io/pytables.py
Python
LegacyFixed
LegacyFixed
2,810
2,817
2,810
2,811
5ea4e017ff19527bc5eaec2d2abaa0566e6bb0b4
bigcode/the-stack
train
d64f6383f7ce38fb69c51fc2
train
function
def _unconvert_string_array(data, nan_rep=None, encoding=None, errors='strict'): """ inverse of _convert_string_array Parameters ---------- data : fixed length string dtyped array nan_rep : the storage repr of NaN, optional encoding : the encoding of the data, op...
def _unconvert_string_array(data, nan_rep=None, encoding=None, errors='strict'):
""" inverse of _convert_string_array Parameters ---------- data : fixed length string dtyped array nan_rep : the storage repr of NaN, optional encoding : the encoding of the data, optional errors : handler for encoding errors, default 'strict' Returns ------- an object arra...
encoding, errors).values.reshape(data.shape) # create the sized dtype if itemsize is None: ensured = ensure_object(data.ravel()) itemsize = libwriters.max_len_string_array(ensured) data = np.asarray(data, dtype="S%d" % itemsize) return data def _unconvert_string_array(data,...
87
87
293
20
66
getschomp/pandas
pandas/io/pytables.py
Python
_unconvert_string_array
_unconvert_string_array
4,667
4,707
4,667
4,668
5f48341cae0561e5eb258cf8a888b9fc5a3c2cef
bigcode/the-stack
train
daf43d2606d6161193ba2348
train
class
class IndexCol(StringMixin): """ an index column description class Parameters ---------- axis : axis which I reference values : the ndarray like converted values kind : a string description of this type typ : the pytables type pos : the position i...
class IndexCol(StringMixin):
""" an index column description class Parameters ---------- axis : axis which I reference values : the ndarray like converted values kind : a string description of this type typ : the pytables type pos : the position in the pytables """ ...
= None self.auto_close = auto_close def __iter__(self): # iterate current = self.start while current < self.stop: stop = min(current + self.chunksize, self.stop) value = self.func(None, None, self.coordinates[current:stop]) current = stop ...
256
256
1,990
6
249
getschomp/pandas
pandas/io/pytables.py
Python
IndexCol
IndexCol
1,536
1,815
1,536
1,537
e76e8a092f1a77f6771343c8b4886be6fe5fd0fd
bigcode/the-stack
train
189873fc7eb3cc60cf640da9
train
class
class DataCol(IndexCol): """ a data holding column, by definition this is not indexable Parameters ---------- data : the actual data cname : the column name in the table to hold the data (typically values) meta : a string description of the metadata ...
class DataCol(IndexCol):
""" a data holding column, by definition this is not indexable Parameters ---------- data : the actual data cname : the column name in the table to hold the data (typically values) meta : a string description of the metadata metadata : the actu...
handler): """ retrieve the metadata for this columns """ self.metadata = handler.read_metadata(self.cname) def validate_metadata(self, handler): """ validate that kind=category does not change the categories """ if self.meta == 'category': new_metadata = self.metadata ...
256
256
3,247
6
249
getschomp/pandas
pandas/io/pytables.py
Python
DataCol
DataCol
1,839
2,258
1,839
1,840
674eee16a826fdc9eec0f64d63148a395ef164ec
bigcode/the-stack
train
a7a1179de67d8d80c8c548ad
train
function
def _ensure_str(name): """Ensure that an index / column name is a str (python 3) or unicode (python 2); otherwise they may be np.string dtype. Non-string dtypes are passed through unchanged. https://github.com/pandas-dev/pandas/issues/13492 """ if isinstance(name, compat.string_types): ...
def _ensure_str(name):
"""Ensure that an index / column name is a str (python 3) or unicode (python 2); otherwise they may be np.string dtype. Non-string dtypes are passed through unchanged. https://github.com/pandas-dev/pandas/issues/13492 """ if isinstance(name, compat.string_types): name = compat.text_type...
(s, np.bytes_): s = s.decode('UTF-8') return s def _ensure_encoding(encoding): # set the encoding if we need if encoding is None: if PY3: encoding = _default_encoding return encoding def _ensure_str(name):
64
64
88
6
57
getschomp/pandas
pandas/io/pytables.py
Python
_ensure_str
_ensure_str
81
90
81
81
b39f6dd7ef749f13d619d680c7134be7077f9cc6
bigcode/the-stack
train
7b620e4f54d7f7e0fd98042a
train
class
class GenericTable(AppendableFrameTable): """ a table that read/writes the generic pytables table format """ pandas_kind = u'frame_table' table_type = u'generic_table' ndim = 2 obj_type = DataFrame @property def pandas_type(self): return self.pandas_kind @property def stora...
class GenericTable(AppendableFrameTable):
""" a table that read/writes the generic pytables table format """ pandas_kind = u'frame_table' table_type = u'generic_table' ndim = 2 obj_type = DataFrame @property def pandas_type(self): return self.pandas_kind @property def storable(self): return getattr(self.gro...
'appendable_multiseries' def write(self, obj, **kwargs): """ we are going to write this as a frame table """ name = obj.name or 'values' obj, self.levels = self.validate_multiindex(obj) cols = list(self.levels) cols.append(name) obj.columns = cols return supe...
99
99
332
9
90
getschomp/pandas
pandas/io/pytables.py
Python
GenericTable
GenericTable
4,335
4,381
4,335
4,335
653c150def282cbe37093c7be459f2309808640b
bigcode/the-stack
train
20520c1d9c87ae973b5d1ccf
train
class
class Fixed(StringMixin): """ represent an object in my store facilitate read/write of various types of objects this is an abstract base class Parameters ---------- parent : my parent HDFStore group : the group node where the table resides """ pandas_k...
class Fixed(StringMixin):
""" represent an object in my store facilitate read/write of various types of objects this is an abstract base class Parameters ---------- parent : my parent HDFStore group : the group node where the table resides """ pandas_kind = None obj_type = N...
.meta = getattr(self.attrs, self.meta_attr, None) self.set_kind() def set_attr(self): """ set the data for this column """ setattr(self.attrs, self.kind_attr, self.values) setattr(self.attrs, self.meta_attr, self.meta) if self.dtype is not None: setattr(self.attr...
256
256
988
5
250
getschomp/pandas
pandas/io/pytables.py
Python
Fixed
Fixed
2,291
2,455
2,291
2,292
b490a503c75cb080a197c6a86db3ad9d4722ef33
bigcode/the-stack
train
1ec0b79629728a7acb36eb25
train
class
class IncompatibilityWarning(Warning): pass
class IncompatibilityWarning(Warning):
pass
.append(Term(w, scope_level=level)) where = wlist elif maybe_expression(where): where = Term(where, scope_level=level) return where class PossibleDataLossError(Exception): pass class ClosedFileError(Exception): pass class IncompatibilityWarning(Warning):
64
64
11
8
55
getschomp/pandas
pandas/io/pytables.py
Python
IncompatibilityWarning
IncompatibilityWarning
128
129
128
128
016f7df5aa211581ce81a5398165b9ce999acc4e
bigcode/the-stack
train
fe89944f805ef388d881853e
train
class
class PossibleDataLossError(Exception): pass
class PossibleDataLossError(Exception):
pass
): if not maybe_expression(w): wlist.append(w) else: wlist.append(Term(w, scope_level=level)) where = wlist elif maybe_expression(where): where = Term(where, scope_level=level) return where class PossibleDataLossError(Exception):
64
64
10
7
56
getschomp/pandas
pandas/io/pytables.py
Python
PossibleDataLossError
PossibleDataLossError
120
121
120
120
0b850d5f8d261a746202ab4383dc7cc29608171d
bigcode/the-stack
train
9fa9c7179b9c1c7a1dbc7a23
train
class
class TableIterator(object): """ define the iteration interface on a table Parameters ---------- store : the reference store s : the referred storer func : the function to execute the query where : the where of the query nrows : the rows to iterate on ...
class TableIterator(object):
""" define the iteration interface on a table Parameters ---------- store : the reference store s : the referred storer func : the function to execute the query where : the where of the query nrows : the rows to iterate on start : the passed sta...
and complib: raise ValueError( 'Compression not supported on Fixed format stores' ) # write the object s.write(obj=value, append=append, complib=complib, **kwargs) if s.is_table and index: s.create_index(columns=index) def _read_group(s...
180
180
602
5
175
getschomp/pandas
pandas/io/pytables.py
Python
TableIterator
TableIterator
1,439
1,533
1,439
1,440
90ef1259a9b268083001a8a2b8215929cc10647d
bigcode/the-stack
train
97084a1e3ab2c63519a1681c
train
function
def _get_info(info, name): """ get/create the info for this name """ try: idx = info[name] except KeyError: idx = info[name] = dict() return idx
def _get_info(info, name):
""" get/create the info for this name """ try: idx = info[name] except KeyError: idx = info[name] = dict() return idx
labels = ensure_index(other.unique()) & labels if not labels.equals(ax): slicer = [slice(None, None)] * obj.ndim slicer[axis] = labels obj = obj.loc[tuple(slicer)] return obj def _get_info(info, name):
64
64
45
8
55
getschomp/pandas
pandas/io/pytables.py
Python
_get_info
_get_info
4,460
4,466
4,460
4,460
0a0f24a7380b7b54d759de12a61866af0854cc29
bigcode/the-stack
train
0a7c10241a5cde8e66d0e2f9
train
class
class SparseSeriesFixed(SparseFixed): pandas_kind = u'sparse_series' attributes = ['name', 'fill_value', 'kind'] def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index('index') sp_values = self.read_array('sp_values') sp_index = self.read_index...
class SparseSeriesFixed(SparseFixed):
pandas_kind = u'sparse_series' attributes = ['name', 'fill_value', 'kind'] def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index('index') sp_values = self.read_array('sp_values') sp_index = self.read_index('sp_index') return SparseSeri...
""" kwargs = super(SparseFixed, self).validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop are not supported " "in fixed Sparse reading") return kwargs class SparseSeriesFixed(Spars...
64
64
199
8
55
getschomp/pandas
pandas/io/pytables.py
Python
SparseSeriesFixed
SparseSeriesFixed
2,876
2,897
2,876
2,876
8fb88e283485cbda22ca505db44695ed3bc5731e
bigcode/the-stack
train
14ff9fdb4056ee16aa5420b2
train
function
def _get_tz(tz): """ for a tz-aware type, return an encoded zone """ zone = timezones.get_timezone(tz) if zone is None: zone = tz.utcoffset().total_seconds() return zone
def _get_tz(tz):
""" for a tz-aware type, return an encoded zone """ zone = timezones.get_timezone(tz) if zone is None: zone = tz.utcoffset().total_seconds() return zone
return obj def _get_info(info, name): """ get/create the info for this name """ try: idx = info[name] except KeyError: idx = info[name] = dict() return idx # tz to/from coercion def _get_tz(tz):
64
64
52
8
55
getschomp/pandas
pandas/io/pytables.py
Python
_get_tz
_get_tz
4,471
4,476
4,471
4,471
927232748e8d532555368a38f0092701fc1ce6fb
bigcode/the-stack
train
aef5bd0228878756e3f7af6f
train
class
class GenericIndexCol(IndexCol): """ an index which is not represented in the data of the table """ @property def is_indexed(self): return False def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ self.values...
class GenericIndexCol(IndexCol):
""" an index which is not represented in the data of the table """ @property def is_indexed(self): return False def convert(self, values, nan_rep, encoding, errors): """ set the values from this selection: take = take ownership """ self.values = Int64Index(np.arange(self.table...
, cur_metadata)): raise ValueError("cannot append a categorical with " "different categories to the existing") def write_metadata(self, handler): """ set the meta data """ if self.metadata is not None: handler.write_metadata(self.cname, s...
64
64
101
7
57
getschomp/pandas
pandas/io/pytables.py
Python
GenericIndexCol
GenericIndexCol
1,818
1,836
1,818
1,819
49a3f50d7588893990938878f696d23b1592b90d
bigcode/the-stack
train
8f89dc4a7e138f5908f2c472
train
function
def _convert_string_array(data, encoding, errors, itemsize=None): """ we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors ...
def _convert_string_array(data, encoding, errors, itemsize=None):
""" we take a string-like that is object dtype and coerce to a fixed size string type Parameters ---------- data : a numpy array of object dtype encoding : None or string-encoding errors : handler for encoding errors itemsize : integer, optional, defaults to the max length of the st...
_unconvert_string_array(data, nan_rep=None, encoding=encoding, errors=errors) else: # pragma: no cover raise ValueError('unrecognized index type %s' % kind) return index def _convert_string_array(data, encoding, errors, itemsize=None):
64
64
204
15
48
getschomp/pandas
pandas/io/pytables.py
Python
_convert_string_array
_convert_string_array
4,636
4,664
4,636
4,636
8157adc78cf81d46e30c13056df8d00f14ec08e4
bigcode/the-stack
train
668a22946069971a88c1d5c1
train
function
def _unconvert_index(data, kind, encoding=None, errors='strict'): kind = _ensure_decoded(kind) if kind == u'datetime64': index = DatetimeIndex(data) elif kind == u'timedelta64': index = TimedeltaIndex(data) elif kind == u'datetime': index = np.asarray([datetime.fromtimestamp(v) f...
def _unconvert_index(data, kind, encoding=None, errors='strict'):
kind = _ensure_decoded(kind) if kind == u'datetime64': index = DatetimeIndex(data) elif kind == u'timedelta64': index = TimedeltaIndex(data) elif kind == u'datetime': index = np.asarray([datetime.fromtimestamp(v) for v in data], dtype=object) elif k...
dtype=np.float64), 'float', atom, index_name=index_name) else: # pragma: no cover atom = _tables().ObjectAtom() return IndexCol(np.asarray(values, dtype='O'), 'object', atom, index_name=index_name) def _unconvert_index(data, kind, encoding=None, erro...
74
74
248
16
58
getschomp/pandas
pandas/io/pytables.py
Python
_unconvert_index
_unconvert_index
4,593
4,618
4,593
4,593
96aed7b06b200611777cdb1283c1263a8faf57c4
bigcode/the-stack
train
1ab628dbbd4482e18454b80f
train
class
class LegacyFrameFixed(LegacyFixed): def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') columns = self.read_index_legacy('columns') values = self.read_array('values') return DataFrame(values, index=index, columns=columns)
class LegacyFrameFixed(LegacyFixed):
def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') columns = self.read_index_legacy('columns') values = self.read_array('values') return DataFrame(values, index=index, columns=columns)
.errors) class LegacySeriesFixed(LegacyFixed): def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') values = self.read_array('values') return Series(values, index=index) class LegacyFrameFixed(LegacyFixed):
64
64
69
9
55
getschomp/pandas
pandas/io/pytables.py
Python
LegacyFrameFixed
LegacyFrameFixed
2,829
2,836
2,829
2,830
971090e02ddae4c40aaa4631bbf38a54db1ea8cc
bigcode/the-stack
train
3459f4a9ef7ce35cffa1341c
train
function
def _unconvert_index_legacy(data, kind, legacy=False, encoding=None, errors='strict'): kind = _ensure_decoded(kind) if kind == u'datetime': index = to_datetime(data) elif kind in (u'integer'): index = np.asarray(data, dtype=object) elif kind in (u'string'): ...
def _unconvert_index_legacy(data, kind, legacy=False, encoding=None, errors='strict'):
kind = _ensure_decoded(kind) if kind == u'datetime': index = to_datetime(data) elif kind in (u'integer'): index = np.asarray(data, dtype=object) elif kind in (u'string'): index = _unconvert_string_array(data, nan_rep=None, encoding=encoding, ...
u'object': index = np.asarray(data[0]) else: # pragma: no cover raise ValueError('unrecognized index type %s' % kind) return index def _unconvert_index_legacy(data, kind, legacy=False, encoding=None, errors='strict'):
64
64
127
22
41
getschomp/pandas
pandas/io/pytables.py
Python
_unconvert_index_legacy
_unconvert_index_legacy
4,621
4,633
4,621
4,622
f68e8955d0c8c6d88de1343fa6e643c440e6dc2f
bigcode/the-stack
train
b29ee53642176c4a48757660
train
function
def _reindex_axis(obj, axis, labels, other=None): ax = obj._get_axis(axis) labels = ensure_index(labels) # try not to reindex even if other is provided # if it equals our current index if other is not None: other = ensure_index(other) if (other is None or labels.equals(other)) and label...
def _reindex_axis(obj, axis, labels, other=None):
ax = obj._get_axis(axis) labels = ensure_index(labels) # try not to reindex even if other is provided # if it equals our current index if other is not None: other = ensure_index(other) if (other is None or labels.equals(other)) and labels.equals(ax): return obj labels = ens...
these are written transposed """ if self.is_transposed: obj = obj.transpose(*self.data_orientation) return obj @property def is_transposed(self): return self.data_orientation != tuple(range(self.ndim)) def _reindex_axis(obj, axis, labels, other=None):
64
64
157
14
50
getschomp/pandas
pandas/io/pytables.py
Python
_reindex_axis
_reindex_axis
4,439
4,457
4,439
4,439
7e9a6e73c4b01826f8bb48a8981ed2e397daf672
bigcode/the-stack
train
c7c0a50931b2338efa1a7321
train
function
def _ensure_term(where, scope_level): """ ensure that the where is a Term or a list of Term this makes sure that we are capturing the scope of variables that are passed create the terms here with a frame_level=2 (we are 2 levels down) """ # only consider list/tuple here as an ndarray is aut...
def _ensure_term(where, scope_level):
""" ensure that the where is a Term or a list of Term this makes sure that we are capturing the scope of variables that are passed create the terms here with a frame_level=2 (we are 2 levels down) """ # only consider list/tuple here as an ndarray is automatically a coordinate # list ...
.string dtype. Non-string dtypes are passed through unchanged. https://github.com/pandas-dev/pandas/issues/13492 """ if isinstance(name, compat.string_types): name = compat.text_type(name) return name Term = Expr def _ensure_term(where, scope_level):
64
64
179
9
54
getschomp/pandas
pandas/io/pytables.py
Python
_ensure_term
_ensure_term
96
117
96
96
f25cd545a966e948734f4f20cf3c213ddbc6c53f
bigcode/the-stack
train
941c5ef4c3b765b6788b27e8
train
function
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs): """ store this object, close it if we opened it """ if append: f = lambda store: store.append(key, value, **kwargs) else: f = lambda store: store.put(key, value, **kwargs) pa...
def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs):
""" store this object, close it if we opened it """ if append: f = lambda store: store.append(key, value, **kwargs) else: f = lambda store: store.put(key, value, **kwargs) path_or_buf = _stringify_path(path_or_buf) if isinstance(path_or_buf, string_types): with HDFStore(pat...
ict = ( tables.file._FILE_OPEN_POLICY == 'strict') except AttributeError: pass return _table_mod # interface to/from ### def to_hdf(path_or_buf, key, value, mode=None, complevel=None, complib=None, append=None, **kwargs):
63
64
145
30
33
getschomp/pandas
pandas/io/pytables.py
Python
to_hdf
to_hdf
269
284
269
270
06e5aa8534533d402cb3180302b4515e2ec426a4
bigcode/the-stack
train
781d15456cc20a250c34424a
train
class
class AttributeConflictWarning(Warning): pass
class AttributeConflictWarning(Warning):
pass
ibilityWarning(Warning): pass incompatibility_doc = """ where criteria is being ignored as this version [%s] is too old (or not-defined), read the file in and write it out to a new file to upgrade (with the copy_to method) """ class AttributeConflictWarning(Warning):
64
64
10
7
57
getschomp/pandas
pandas/io/pytables.py
Python
AttributeConflictWarning
AttributeConflictWarning
139
140
139
139
42894c2695329f6786fa38d62e5c3f0e3fb299b2
bigcode/the-stack
train
88dae7ced4cdaaea3256989f
train
class
class SeriesFixed(GenericFixed): pandas_kind = u'series' attributes = ['name'] @property def shape(self): try: return len(getattr(self.group, 'values')), except (TypeError, AttributeError): return None def read(self, **kwargs): kwargs = self.validate...
class SeriesFixed(GenericFixed):
pandas_kind = u'series' attributes = ['name'] @property def shape(self): try: return len(getattr(self.group, 'values')), except (TypeError, AttributeError): return None def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = sel...
read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') columns = self.read_index_legacy('columns') values = self.read_array('values') return DataFrame(values, index=index, columns=columns) class SeriesFixed(GenericFixed):
64
64
160
6
58
getschomp/pandas
pandas/io/pytables.py
Python
SeriesFixed
SeriesFixed
2,839
2,860
2,839
2,839
3533650b792aac1f902d0869a0f1a71ab93abc97
bigcode/the-stack
train
781c2a94f39f17fbd26d63f1
train
class
class GenericFixed(Fixed): """ a generified fixed version """ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'} _reverse_index_map = {v: k for k, v in compat.iteritems(_index_type_map)} attributes = [] # indexer helpders def _class_to_alias(self, cls): return self._i...
class GenericFixed(Fixed):
""" a generified fixed version """ _index_type_map = {DatetimeIndex: 'datetime', PeriodIndex: 'period'} _reverse_index_map = {v: k for k, v in compat.iteritems(_index_type_map)} attributes = [] # indexer helpders def _class_to_alias(self, cls): return self._index_type_map.get(cls, '') ...
(self, other): """ validate against an existing storable """ if other is None: return return True def validate_version(self, where=None): """ are we trying to operate on an old version? """ return True def infer_axes(self): """ infer the axes of my s...
256
256
2,838
6
250
getschomp/pandas
pandas/io/pytables.py
Python
GenericFixed
GenericFixed
2,458
2,807
2,458
2,459
c19a11e9f376b424bb12b9cf7c9eebec62dac707
bigcode/the-stack
train
2f104a2bc6ab2a0e775f187c
train
function
def _set_tz(values, tz, preserve_UTC=False, coerce=False): """ coerce the values to a DatetimeIndex if tz is set preserve the input shape if possible Parameters ---------- values : ndarray tz : string/pickled tz object preserve_UTC : boolean, preserve the UTC of the result c...
def _set_tz(values, tz, preserve_UTC=False, coerce=False):
""" coerce the values to a DatetimeIndex if tz is set preserve the input shape if possible Parameters ---------- values : ndarray tz : string/pickled tz object preserve_UTC : boolean, preserve the UTC of the result coerce : if we do not have a passed timezone, coerce to M8[n...
z(tz): """ for a tz-aware type, return an encoded zone """ zone = timezones.get_timezone(tz) if zone is None: zone = tz.utcoffset().total_seconds() return zone def _set_tz(values, tz, preserve_UTC=False, coerce=False):
66
66
220
18
47
getschomp/pandas
pandas/io/pytables.py
Python
_set_tz
_set_tz
4,479
4,505
4,479
4,479
86b0b1300976a7d1076ec50d1f0b611b4abcea8e
bigcode/the-stack
train
4b224de31279d9fee855eb33
train
class
class GenericDataIndexableCol(DataIndexableCol): """ represent a generic pytables data column """ def get_attr(self): pass
class GenericDataIndexableCol(DataIndexableCol):
""" represent a generic pytables data column """ def get_attr(self): pass
=None): return self.get_atom_coltype(kind=kind)() def get_atom_datetime64(self, block): return _tables().Int64Col() def get_atom_timedelta64(self, block): return _tables().Int64Col() class GenericDataIndexableCol(DataIndexableCol):
64
64
30
11
53
getschomp/pandas
pandas/io/pytables.py
Python
GenericDataIndexableCol
GenericDataIndexableCol
2,283
2,288
2,283
2,284
0893dd5dd15b6e7654121333dd8cd04c755aa01d
bigcode/the-stack
train
48ba56fadcbb7edc7c37853a
train
function
def _need_convert(kind): kind = _ensure_decoded(kind) if kind in (u'datetime', u'datetime64', u'string'): return True return False
def _need_convert(kind):
kind = _ensure_decoded(kind) if kind in (u'datetime', u'datetime64', u'string'): return True return False
=True).to_pydatetime() elif kind == 'string': return lambda x: _unconvert_string_array(x, encoding=encoding, errors=errors) else: # pragma: no cover raise ValueError('invalid kind %s' % kind) def _need_convert(kind):
64
64
41
6
58
getschomp/pandas
pandas/io/pytables.py
Python
_need_convert
_need_convert
4,731
4,735
4,731
4,731
ff4a0ad520fd43a024754011c5b226066cb9a82a
bigcode/the-stack
train
08b0912d7e77092892100edf
train
class
class AppendablePanelTable(AppendableTable): """ suppor the new appendable table formats """ table_type = u'appendable_panel' ndim = 3 obj_type = Panel def get_object(self, obj): """ these are written transposed """ if self.is_transposed: obj = obj.transpose(*self.data_...
class AppendablePanelTable(AppendableTable):
""" suppor the new appendable table formats """ table_type = u'appendable_panel' ndim = 3 obj_type = Panel def get_object(self, obj): """ these are written transposed """ if self.is_transposed: obj = obj.transpose(*self.data_orientation) return obj @property...
df = df.set_index(self.levels) # remove names for 'level_%d' df.index = df.index.set_names([ None if self._re_levels.search(l) else l for l in df.index.names ]) return df class AppendablePanelTable(AppendableTable):
64
64
103
10
53
getschomp/pandas
pandas/io/pytables.py
Python
AppendablePanelTable
AppendablePanelTable
4,421
4,436
4,421
4,422
0a105e2850c838f532d20ac993492072684845d0
bigcode/the-stack
train
4dd80b82f5f7d2eb0aec444a
train
function
def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
def _ensure_decoded(s):
""" if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s
.io.common import _stringify_path from pandas.io.formats.printing import adjoin, pprint_thing # versioning attribute _version = '0.15.2' # encoding # PY3 encoding if we don't specify _default_encoding = 'UTF-8' def _ensure_decoded(s):
64
64
42
7
57
getschomp/pandas
pandas/io/pytables.py
Python
_ensure_decoded
_ensure_decoded
66
70
66
66
5a9ced9c6c8fa61c056d31763b47ae6d23dfa588
bigcode/the-stack
train
cec3d5be980e881b1d8e006b
train
function
def timeit(key, df, fn=None, remove=True, **kwargs): if fn is None: fn = 'timeit.h5' store = HDFStore(fn, mode='w') store.append(key, df, **kwargs) store.close() if remove: os.remove(fn)
def timeit(key, df, fn=None, remove=True, **kwargs):
if fn is None: fn = 'timeit.h5' store = HDFStore(fn, mode='w') store.append(key, df, **kwargs) store.close() if remove: os.remove(fn)
return self.table.table.get_where_list(self.condition.format(), start=start, stop=stop, sort=True) elif self.coordinates is not None: return self.coordinates return np.arange(start, stop) ...
63
64
66
16
47
getschomp/pandas
pandas/io/pytables.py
Python
timeit
timeit
4,858
4,866
4,858
4,858
a6aaf00c423bab30cb987a76342d89acee411f0e
bigcode/the-stack
train
3b258a713099148c7745b7ff
train
class
class LegacyFrameTable(LegacyTable): """ support the legacy frame table """ pandas_kind = u'frame_table' table_type = u'legacy_frame' obj_type = Panel def read(self, *args, **kwargs): return super(LegacyFrameTable, self).read(*args, **kwargs)['value']
class LegacyFrameTable(LegacyTable):
""" support the legacy frame table """ pandas_kind = u'frame_table' table_type = u'legacy_frame' obj_type = Panel def read(self, *args, **kwargs): return super(LegacyFrameTable, self).read(*args, **kwargs)['value']
objs[0] else: wp = concat(objs, axis=0, verify_integrity=False)._consolidate() # apply the selection filters & axis orderings wp = self.process_axes(wp, columns=columns) return wp class LegacyFrameTable(LegacyTable):
64
64
72
9
54
getschomp/pandas
pandas/io/pytables.py
Python
LegacyFrameTable
LegacyFrameTable
3,962
3,970
3,962
3,963
15d02c525852b7ccb4342b3e4a844c81a724079d
bigcode/the-stack
train
51f1423b3c969de26b71de39
train
function
def _get_converter(kind, encoding, errors): kind = _ensure_decoded(kind) if kind == 'datetime64': return lambda x: np.asarray(x, dtype='M8[ns]') elif kind == 'datetime': return lambda x: to_datetime(x, cache=True).to_pydatetime() elif kind == 'string': return lambda x: _unconvert...
def _get_converter(kind, encoding, errors):
kind = _ensure_decoded(kind) if kind == 'datetime64': return lambda x: np.asarray(x, dtype='M8[ns]') elif kind == 'datetime': return lambda x: to_datetime(x, cache=True).to_pydatetime() elif kind == 'string': return lambda x: _unconvert_string_array(x, encoding=encoding, ...
val_kind, encoding, errors): if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) values = conv(values) return values def _get_converter(kind, encoding, errors):
64
64
118
10
53
getschomp/pandas
pandas/io/pytables.py
Python
_get_converter
_get_converter
4,718
4,728
4,718
4,718
25f54e0a54b81688ef3896bb1212640f6a1454a2
bigcode/the-stack
train
330279906bee05142c8e4668
train
class
class AppendableSeriesTable(AppendableFrameTable): """ support the new appendable table formats """ pandas_kind = u'series_table' table_type = u'appendable_series' ndim = 2 obj_type = Series storage_obj_type = DataFrame @property def is_transposed(self): return False def ge...
class AppendableSeriesTable(AppendableFrameTable):
""" support the new appendable table formats """ pandas_kind = u'series_table' table_type = u'appendable_series' ndim = 2 obj_type = Series storage_obj_type = DataFrame @property def is_transposed(self): return False def get_object(self, obj): return obj def wr...
mgr = BlockManager([block], [cols_, index_]) frames.append(DataFrame(mgr)) if len(frames) == 1: df = frames[0] else: df = concat(frames, axis=1) # apply the selection filters & axis orderings df = self.process_axes(df, columns=columns) ...
91
91
305
11
79
getschomp/pandas
pandas/io/pytables.py
Python
AppendableSeriesTable
AppendableSeriesTable
4,277
4,317
4,277
4,277
08481166969365971b22b26de8195036ecb4651c
bigcode/the-stack
train
c0b691bff4fa88a315d5d13c
train
class
class LegacySeriesFixed(LegacyFixed): def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') values = self.read_array('values') return Series(values, index=index)
class LegacySeriesFixed(LegacyFixed):
def read(self, **kwargs): kwargs = self.validate_read(kwargs) index = self.read_index_legacy('index') values = self.read_array('values') return Series(values, index=index)
key, start=None, stop=None): node = getattr(self.group, key) data = node[start:stop] kind = node._v_attrs.kind return _unconvert_index_legacy(data, kind, encoding=self.encoding, errors=self.errors) class LegacySeriesFixed(LegacyFixed):
64
64
53
9
55
getschomp/pandas
pandas/io/pytables.py
Python
LegacySeriesFixed
LegacySeriesFixed
2,820
2,826
2,820
2,821
b5f7991f0c585c71a13f81428f6ed13dacf5371e
bigcode/the-stack
train
820dda0ae3b34c673cab9e0b
train
class
class AppendableTable(LegacyTable): """ suppor the new appendable table formats """ _indexables = None table_type = u'appendable' def write(self, obj, axes=None, append=False, complib=None, complevel=None, fletcher32=None, min_itemsize=None, chunksize=None, expectedrows=Non...
class AppendableTable(LegacyTable):
""" suppor the new appendable table formats """ _indexables = None table_type = u'appendable' def write(self, obj, axes=None, append=False, complib=None, complevel=None, fletcher32=None, min_itemsize=None, chunksize=None, expectedrows=None, dropna=False, **kwargs): ...
er = match(unique_tuples, tuple_index) indexer = ensure_platform_int(indexer) new_index = long_index.take(indexer) new_values = lp.values.take(indexer, axis=0) lp = DataFrame(new_values, index=new_index, columns=lp.columns) objs.append(lp...
256
256
1,587
9
246
getschomp/pandas
pandas/io/pytables.py
Python
AppendableTable
AppendableTable
3,980
4,207
3,980
3,981
f6c142f6156129fe77cbd660de36b768b9435468
bigcode/the-stack
train
b5a34480e54b27f016cc7160
train
class
class SparseFixed(GenericFixed): def validate_read(self, kwargs): """ we don't support start, stop kwds in Sparse """ kwargs = super(SparseFixed, self).validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop ar...
class SparseFixed(GenericFixed):
def validate_read(self, kwargs): """ we don't support start, stop kwds in Sparse """ kwargs = super(SparseFixed, self).validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop are not supported " ...
=index, name=self.name) def write(self, obj, **kwargs): super(SeriesFixed, self).write(obj, **kwargs) self.write_index('index', obj.index) self.write_array('values', obj.values) self.attrs.name = obj.name class SparseFixed(GenericFixed):
64
64
83
6
57
getschomp/pandas
pandas/io/pytables.py
Python
SparseFixed
SparseFixed
2,863
2,873
2,863
2,864
c851f199d6d33311dcf0e817ef12769b138ab922
bigcode/the-stack
train
9beabf981660db7779c9f28c
train
function
def _ensure_encoding(encoding): # set the encoding if we need if encoding is None: if PY3: encoding = _default_encoding return encoding
def _ensure_encoding(encoding): # set the encoding if we need
if encoding is None: if PY3: encoding = _default_encoding return encoding
= 'UTF-8' def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, np.bytes_): s = s.decode('UTF-8') return s def _ensure_encoding(encoding): # set the encoding if we need
64
64
38
16
47
getschomp/pandas
pandas/io/pytables.py
Python
_ensure_encoding
_ensure_encoding
73
78
73
74
08e0020dfbd8d642331072cf23d3e825eac0b5bf
bigcode/the-stack
train
41f4adaddaf91f26a08d0ecb
train
function
def _convert_index(index, encoding=None, errors='strict', format_type=None): index_name = getattr(index, 'name', None) if isinstance(index, DatetimeIndex): converted = index.asi8 return IndexCol(converted, 'datetime64', _tables().Int64Col(), freq=getattr(index, 'freq', N...
def _convert_index(index, encoding=None, errors='strict', format_type=None):
index_name = getattr(index, 'name', None) if isinstance(index, DatetimeIndex): converted = index.asi8 return IndexCol(converted, 'datetime64', _tables().Int64Col(), freq=getattr(index, 'freq', None), tz=getattr(index, 'tz', None), ...
def _set_tz(values, tz, preserve_UTC=False, coerce=False): """ coerce the values to a DatetimeIndex if tz is set preserve the input shape if possible Parameters ---------- values : ndarray tz : string/pickled tz object preserve_UTC : boolean, preserve the UTC of the result ...
238
238
795
17
220
getschomp/pandas
pandas/io/pytables.py
Python
_convert_index
_convert_index
4,508
4,590
4,508
4,508
a4343e2f7fea193194b4a6b037aa88721600ad2b
bigcode/the-stack
train
8d97a46213801bbd7f64ecc8
train
class
class Table(Fixed): """ represent a table: facilitate read/write of various types of tables Attrs in Table Node ------------------- These are attributes that are store in the main table node, they are necessary to recreate these tables when read back in. index_ax...
class Table(Fixed):
""" represent a table: facilitate read/write of various types of tables Attrs in Table Node ------------------- These are attributes that are store in the main table node, they are necessary to recreate these tables when read back in. index_axes : a list of tup...
ate() self.attrs.ndim = data.ndim for i, ax in enumerate(data.axes): if i == 0: if not ax.is_unique: raise ValueError( "Columns index has to be unique for fixed format") self.write_index('axis%d' % i, ax) # Sup...
256
256
5,933
5
251
getschomp/pandas
pandas/io/pytables.py
Python
Table
Table
3,032
3,831
3,032
3,033
263831c9b30fc89487614934d3c07e7038298b9a
bigcode/the-stack
train
4b1110d36c01618ff5cc8fba
train
class
class ClosedFileError(Exception): pass
class ClosedFileError(Exception):
pass
wlist.append(w) else: wlist.append(Term(w, scope_level=level)) where = wlist elif maybe_expression(where): where = Term(where, scope_level=level) return where class PossibleDataLossError(Exception): pass class ClosedFileError(Exception):
64
64
9
6
57
getschomp/pandas
pandas/io/pytables.py
Python
ClosedFileError
ClosedFileError
124
125
124
124
2b27b7f436506fc2ebd2edeffaae62572170c415
bigcode/the-stack
train
73571b02a79e001ec26cbb92
train
class
class HDFStore(StringMixin): """ dict-like IO interface for storing pandas objects in PyTables either Fixed or Table format. Parameters ---------- path : string File path to HDF5 file mode : {'a', 'w', 'r', 'r+'}, default 'a' ``'r'`` Read-only; no data can be m...
class HDFStore(StringMixin):
""" dict-like IO interface for storing pandas objects in PyTables either Fixed or Table format. Parameters ---------- path : string File path to HDF5 file mode : {'a', 'w', 'r', 'r+'}, default 'a' ``'r'`` Read-only; no data can be modified. ``'w'`` ...
, all other groups # should then be metadata groups for that candidate group. (This # assumes that the groups() method enumerates parent groups # before their children.) for group_to_check in groups[1:]: if not _is_metadata_of(group_to_check, candidate_onl...
256
256
7,510
7
248
getschomp/pandas
pandas/io/pytables.py
Python
HDFStore
HDFStore
422
1,423
422
423
15ef9945527b86ccaca135fa67bf93cd069c51e3
bigcode/the-stack
train
e52445957eff5888c36d436d
train
class
class DuplicateWarning(Warning): pass
class DuplicateWarning(Warning):
pass
new file to upgrade (with the copy_to method) """ class AttributeConflictWarning(Warning): pass attribute_conflict_doc = """ the [%s] attribute of the existing index is [%s] which conflicts with the new [%s], resetting the attribute to None """ class DuplicateWarning(Warning):
64
64
9
6
58
getschomp/pandas
pandas/io/pytables.py
Python
DuplicateWarning
DuplicateWarning
149
150
149
149
4c82ad1132d22c86cf4d6b65870beff2e67d1888
bigcode/the-stack
train
04df12b3de6ec4cf7379e66d
train
class
class PanelFixed(BlockManagerFixed): pandas_kind = u'wide' obj_type = Panel is_shape_reversed = True def write(self, obj, **kwargs): obj._consolidate_inplace() return super(PanelFixed, self).write(obj, **kwargs)
class PanelFixed(BlockManagerFixed):
pandas_kind = u'wide' obj_type = Panel is_shape_reversed = True def write(self, obj, **kwargs): obj._consolidate_inplace() return super(PanelFixed, self).write(obj, **kwargs)
self.write_array('block%d_values' % i, blk.values, items=blk_items) self.write_index('block%d_items' % i, blk_items) class FrameFixed(BlockManagerFixed): pandas_kind = u'frame' obj_type = DataFrame class PanelFixed(BlockManagerFixed):
64
64
63
7
56
getschomp/pandas
pandas/io/pytables.py
Python
PanelFixed
PanelFixed
3,022
3,029
3,022
3,022
34d6a02552965b2091ab74dc7adb6a2bf5249f80
bigcode/the-stack
train
0c222d8a7c2ee1fc3a2e5194
train
class
class AppendableMultiFrameTable(AppendableFrameTable): """ a frame with a multi-index """ table_type = u'appendable_multiframe' obj_type = DataFrame ndim = 2 _re_levels = re.compile(r"^level_\d+$") @property def table_type_short(self): return u'appendable_multi' def write(self...
class AppendableMultiFrameTable(AppendableFrameTable):
""" a frame with a multi-index """ table_type = u'appendable_multiframe' obj_type = DataFrame ndim = 2 _re_levels = re.compile(r"^level_\d+$") @property def table_type_short(self): return u'appendable_multi' def write(self, obj, data_columns=None, **kwargs): if data_col...
enumerate(d._v_names): dc = GenericDataIndexableCol( name=n, pos=i, values=[n], version=self.version) self._indexables.append(dc) return self._indexables def write(self, **kwargs): raise NotImplementedError("cannot write on an generic table") c...
78
78
263
12
66
getschomp/pandas
pandas/io/pytables.py
Python
AppendableMultiFrameTable
AppendableMultiFrameTable
4,384
4,418
4,384
4,385
da38509318af69f8ae7b150d67e749c88a1d31e4
bigcode/the-stack
train
1aa51025afd2e4c7874181f0
train
function
def read_hdf(path_or_buf, key=None, mode='r', **kwargs): """ Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : string, buffer or path object Path to the file to open, or an op...
def read_hdf(path_or_buf, key=None, mode='r', **kwargs):
""" Read from the store, close it if we opened it. Retrieve pandas object stored in file, optionally based on where criteria Parameters ---------- path_or_buf : string, buffer or path object Path to the file to open, or an open :class:`pandas.HDFStore` object. Supports any ...
version >= 3.0.0 is required") # set the file open policy # return the file open policy; this changes as of pytables 3.1 # depending on the HDF5 version try: _table_file_open_policy_is_strict = ( tables.file._FILE_OPEN_POLICY == 'strict') except Attr...
256
256
1,004
18
238
getschomp/pandas
pandas/io/pytables.py
Python
read_hdf
read_hdf
287
405
287
287
2cdc12e5053ea08ca1f350980d97b96a98bfe7dc
bigcode/the-stack
train
80e9f42cf15e73b9a277bc85
train
class
class LegacyTable(Table): """ an appendable table: allow append/query/delete operations to a (possibly) already existing appendable table this table ALLOWS append (but doesn't require them), and stores the data in a format that can be easily searched """ _indexables = [ ...
class LegacyTable(Table):
""" an appendable table: allow append/query/delete operations to a (possibly) already existing appendable table this table ALLOWS append (but doesn't require them), and stores the data in a format that can be easily searched """ _indexables = [ IndexCol(name='index', a...
stop], nan_rep=self.nan_rep, encoding=self.encoding, errors=self.errors ).take_data(), a.t...
236
236
787
5
231
getschomp/pandas
pandas/io/pytables.py
Python
LegacyTable
LegacyTable
3,855
3,959
3,855
3,856
9e348a73d358628bcbd1fdd91c3d006934eaae2b
bigcode/the-stack
train
95c000c174ae4685b550ff62
train
class
class Selection(object): """ Carries out a selection operation on a tables.Table object. Parameters ---------- table : a Table object where : list of Terms (or convertible to) start, stop: indices to start and/or stop selection """ def __init__(self, table, where=None, start=None...
class Selection(object):
""" Carries out a selection operation on a tables.Table object. Parameters ---------- table : a Table object where : list of Terms (or convertible to) start, stop: indices to start and/or stop selection """ def __init__(self, table, where=None, start=None, stop=None, **kwargs): ...
return data.reshape(shape) def _maybe_convert(values, val_kind, encoding, errors): if _need_convert(val_kind): conv = _get_converter(val_kind, encoding, errors) # conv = np.frompyfunc(conv, 1, 1) values = conv(values) return values def _get_converter(kind, encoding, errors): kin...
228
228
760
4
223
getschomp/pandas
pandas/io/pytables.py
Python
Selection
Selection
4,738
4,853
4,738
4,739
78f73a87e1b6ef94c77be3390e4e2bcddd54e5f6
bigcode/the-stack
train
1c4018e01c563cb50e4a8c16
train
class
class SparseFrameFixed(SparseFixed): pandas_kind = u'sparse_frame' attributes = ['default_kind', 'default_fill_value'] def read(self, **kwargs): kwargs = self.validate_read(kwargs) columns = self.read_index('columns') sdict = {} for c in columns: key = 'sparse_se...
class SparseFrameFixed(SparseFixed):
pandas_kind = u'sparse_frame' attributes = ['default_kind', 'default_fill_value'] def read(self, **kwargs): kwargs = self.validate_read(kwargs) columns = self.read_index('columns') sdict = {} for c in columns: key = 'sparse_series_%s' % c s = SparseSe...
): super(SparseSeriesFixed, self).write(obj, **kwargs) self.write_index('index', obj.index) self.write_index('sp_index', obj.sp_index) self.write_array('sp_values', obj.sp_values) self.attrs.name = obj.name self.attrs.fill_value = obj.fill_value self.attrs.kind = ...
84
84
280
8
75
getschomp/pandas
pandas/io/pytables.py
Python
SparseFrameFixed
SparseFrameFixed
2,900
2,930
2,900
2,900
db86fec763805d0cb5e35acd0ff6b2635aba45a2
bigcode/the-stack
train
06adb52cc9fd3f72d014eaa4
train
function
def _tables(): global _table_mod global _table_file_open_policy_is_strict if _table_mod is None: import tables _table_mod = tables # version requirements if LooseVersion(tables.__version__) < LooseVersion('3.0.0'): raise ImportError("PyTables version >= 3.0.0 is ...
def _tables():
global _table_mod global _table_file_open_policy_is_strict if _table_mod is None: import tables _table_mod = tables # version requirements if LooseVersion(tables.__version__) < LooseVersion('3.0.0'): raise ImportError("PyTables version >= 3.0.0 is required") ...
=config.is_bool) config.register_option( 'default_format', None, format_doc, validator=config.is_one_of_factory(['fixed', 'table', None]) ) # oh the troubles to reduce import time _table_mod = None _table_file_open_policy_is_strict = False def _tables():
64
64
158
4
59
getschomp/pandas
pandas/io/pytables.py
Python
_tables
_tables
244
264
244
244
e2e0d83a24b0576b9a40572cd9b3f1f7e7343174
bigcode/the-stack
train
62a550eae45cc24775be807d
train
class
class LegacyPanelTable(LegacyTable): """ support the legacy panel table """ table_type = u'legacy_panel' obj_type = Panel
class LegacyPanelTable(LegacyTable):
""" support the legacy panel table """ table_type = u'legacy_panel' obj_type = Panel
pandas_kind = u'frame_table' table_type = u'legacy_frame' obj_type = Panel def read(self, *args, **kwargs): return super(LegacyFrameTable, self).read(*args, **kwargs)['value'] class LegacyPanelTable(LegacyTable):
64
64
32
9
55
getschomp/pandas
pandas/io/pytables.py
Python
LegacyPanelTable
LegacyPanelTable
3,973
3,977
3,973
3,974
8ac23a133ff1dad60175a474d9d313b735f7c297
bigcode/the-stack
train
41e93e1b50ad9adf42ee8dc9
train
class
class BlockManagerFixed(GenericFixed): attributes = ['ndim', 'nblocks'] is_shape_reversed = False @property def shape(self): try: ndim = self.ndim # items items = 0 for i in range(self.nblocks): node = getattr(self.group, 'block%d...
class BlockManagerFixed(GenericFixed):
attributes = ['ndim', 'nblocks'] is_shape_reversed = False @property def shape(self): try: ndim = self.ndim # items items = 0 for i in range(self.nblocks): node = getattr(self.group, 'block%d_items' % i) shape = ge...
() sdict[c] = s.read() return SparseDataFrame(sdict, columns=columns, default_kind=self.default_kind, default_fill_value=self.default_fill_value) def write(self, obj, **kwargs): """ write it as a collection of individual spar...
189
189
631
7
182
getschomp/pandas
pandas/io/pytables.py
Python
BlockManagerFixed
BlockManagerFixed
2,933
3,014
2,933
2,933
dc88b0e434093d0b661e252ac3ebf44faaf5db64
bigcode/the-stack
train
0decc725b8cc33254cc1dbd9
train
class
class FrameFixed(BlockManagerFixed): pandas_kind = u'frame' obj_type = DataFrame
class FrameFixed(BlockManagerFixed):
pandas_kind = u'frame' obj_type = DataFrame
values before items fixed #2299 blk_items = data.items.take(blk.mgr_locs) self.write_array('block%d_values' % i, blk.values, items=blk_items) self.write_index('block%d_items' % i, blk_items) class FrameFixed(BlockManagerFixed):
64
64
22
7
57
getschomp/pandas
pandas/io/pytables.py
Python
FrameFixed
FrameFixed
3,017
3,019
3,017
3,017
2e3f59aa9f8e3fa945b01887cb32239ee59c56af
bigcode/the-stack
train
be4629280cae152f82b8e611
train
class
class AppendableFrameTable(AppendableTable): """ suppor the new appendable table formats """ pandas_kind = u'frame_table' table_type = u'appendable_frame' ndim = 2 obj_type = DataFrame @property def is_transposed(self): return self.index_axes[0].axis == 1 def get_object(self, ...
class AppendableFrameTable(AppendableTable):
""" suppor the new appendable table formats """ pandas_kind = u'frame_table' table_type = u'appendable_frame' ndim = 2 obj_type = DataFrame @property def is_transposed(self): return self.index_axes[0].axis == 1 def get_object(self, obj): """ these are written transposed...
): groups = [0] # final element if groups[-1] != ln: groups.append(ln) # initial element if groups[0] != 0: groups.insert(0, 0) # we must remove in reverse order! pg = groups.pop() for ...
146
146
487
10
135
getschomp/pandas
pandas/io/pytables.py
Python
AppendableFrameTable
AppendableFrameTable
4,210
4,274
4,210
4,211
fa1f99fd9b06290e8976531463358aeac63a4f94
bigcode/the-stack
train
91e8705efc300bbc33dbd8f2
train
class
class GameServer: """Network Game Server.""" def __init__(self, level, timeout, grading=None): self.game = Game(level, timeout) self.players = asyncio.Queue() self.viewers = set() self.current_player = None self.grading = grading self._level = level self....
class GameServer:
"""Network Game Server.""" def __init__(self, level, timeout, grading=None): self.game = Game(level, timeout) self.players = asyncio.Queue() self.viewers = set() self.current_player = None self.grading = grading self._level = level self._timeout = timeout...
"""Network Game Server.""" import argparse import asyncio import json import logging import os.path import random from collections import namedtuple from functools import reduce from operator import add import requests from requests import RequestException import websockets from consts import MAX_HIGHSCORES, GameStat...
169
256
1,012
4
165
tiagobarros99/Sokoban-AI
server.py
Python
GameServer
GameServer
33
161
33
33
65c7f296f3ece1158dd423d106c7e01d261d2e2f
bigcode/the-stack
train
88d00e09eb410f3d6cd31c12
train
class
class RouteError(Exception): def __init__(self, error): super(RouteError, self).__init__(error)
class RouteError(Exception):
def __init__(self, error): super(RouteError, self).__init__(error)
## # python-crisp-api # # Copyright 2018, Valerian Saliou # Author: Valerian Saliou <valerian@valeriansaliou.name> ## class RouteError(Exception):
45
64
25
5
40
crisp-im/python-crisp-ap
crisp_api/errors/route.py
Python
RouteError
RouteError
8
10
8
8
84714a4effe83ee6d3539e3d178e7b318197b1be
bigcode/the-stack
train
3788181ca54fdfbf2b6a339d
train
function
@numba.njit def EIF_lin_rate_response_frange(V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, w_vec): dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) r1_vec = 1j * np.ones(len(w_vec)) if DeltaT > 0: Psi = DeltaT * np.exp((V_vec - VT) / DeltaT) else: ...
@numba.njit def EIF_lin_rate_response_frange(V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, w_vec):
dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) r1_vec = 1j * np.ones(len(w_vec)) if DeltaT > 0: Psi = DeltaT * np.exp((V_vec - VT) / DeltaT) else: Psi = 0.0 * V_vec F = sig2term * ((V_vec - EL - Psi) / taum - mu) A = np.exp(dV * F) F_dummy = F.cop...
1] = p_ss[k] * A[k] + sig2term_dV q_ss[k - 1] = 1.0 for k in range(kr, 0, -1): p_ss[k - 1] = p_ss[k] * A[k] q_ss[k - 1] = 0.0 p_ss_sum = np.sum(p_ss) r_ss = 1.0 / (dV * p_ss_sum) p_ss *= r_ss q_ss *= r_ss return p_ss, r_ss, q_ss @numba.njit def EIF_lin_rate_response_frang...
171
171
570
42
128
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
EIF_lin_rate_response_frange
EIF_lin_rate_response_frange
410
449
410
411
1325177ebf30f3fa3bb29883cbf01abb988a970b
bigcode/the-stack
train
a35d3657429da0f34acfd0ef
train
function
def fit_exponential_freqdom(f, r1_mod_normalized, init_val): tau_lb = 0.001 # ms, lower bound tau_ub = 100.0 # ms, upper bound # first global brute-force optimization on a coarse grid to reduce risk of # finding a local optimum tau_step = 1.0 # ms tau_vals = np.arange(tau_lb, tau_ub, tau_ste...
def fit_exponential_freqdom(f, r1_mod_normalized, init_val):
tau_lb = 0.001 # ms, lower bound tau_ub = 100.0 # ms, upper bound # first global brute-force optimization on a coarse grid to reduce risk of # finding a local optimum tau_step = 1.0 # ms tau_vals = np.arange(tau_lb, tau_ub, tau_step) errors = np.zeros_like(tau_vals) for i, tau in enum...
1b += fw * p1b q1a = q1a_new p1a = p1a_new p1b = p1b_new r1 = -q1b / q1a return r1 # the functions above work efficiently in practice, but the integration schemes # might be improved (e.g., based on the Magnus expansion) to allow for larger # membrane voltage discretization steps def f...
114
114
381
17
96
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
fit_exponential_freqdom
fit_exponential_freqdom
550
579
550
551
b36db6eadfea62f3674d9ceb134d26f23dc42c48
bigcode/the-stack
train
45ae646378a416c3cf880a8c
train
function
@numba.njit def EIF_steady_state(V_vec, kr, taum, EL, Vr, VT, DeltaT, mu, sigma): dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) p_ss = np.zeros(n) q_ss = np.ones(n) if DeltaT > 0: Psi = DeltaT * np.exp((V_vec - VT) / DeltaT) else: Psi = 0.0 * V_vec F...
@numba.njit def EIF_steady_state(V_vec, kr, taum, EL, Vr, VT, DeltaT, mu, sigma):
dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) p_ss = np.zeros(n) q_ss = np.ones(n) if DeltaT > 0: Psi = DeltaT * np.exp((V_vec - VT) / DeltaT) else: Psi = 0.0 * V_vec F = sig2term * ((V_vec - EL - Psi) / taum - mu) A = np.exp(dV * F) F_dummy ...
"][imu] = f0 init_vals = [tau, f0] # print 'calculation for mu =', mu, 'done' # print 'calculations for sigma =', sigma, 'done' return isig, res_given_sigma_dict # CORE FUNCTIONS that calculate steady state and 1st order spike rate response # to modulations for an EIF/LIF neuron subject t...
119
119
397
31
87
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
EIF_steady_state
EIF_steady_state
377
407
377
378
eed83c1a693eed33cf9546fe1c7be32d0160bb30
bigcode/the-stack
train
4d1120478ced85fd7b29fede
train
function
def dosc_mean_sq_dist_2f(p, *args): f_val1, r1_val1, f_val2, r1_val2 = args if np.size(p) < 2: p = np.array([p[0], 0.0]) dosc_at_f1 = eval_dosc_fdom(p, f_val1) dosc_at_f2 = eval_dosc_fdom(p, f_val2) error = np.abs(dosc_at_f1 - r1_val1) ** 2 + np.abs(dosc_at_f2 - r1_val2) ** 2 # correct n...
def dosc_mean_sq_dist_2f(p, *args):
f_val1, r1_val1, f_val2, r1_val2 = args if np.size(p) < 2: p = np.array([p[0], 0.0]) dosc_at_f1 = eval_dosc_fdom(p, f_val1) dosc_at_f2 = eval_dosc_fdom(p, f_val2) error = np.abs(dosc_at_f1 - r1_val1) ** 2 + np.abs(dosc_at_f2 - r1_val2) ** 2 # correct normalization for mean squared error ...
, args=args, method="Nelder-Mead", options={"xtol": 1e-9, "ftol": 1e-9} ) tau, f0 = sol.x return tau, f0 def dosc_mean_sq_dist_2f(p, *args):
64
64
151
14
49
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
dosc_mean_sq_dist_2f
dosc_mean_sq_dist_2f
631
639
631
631
bc8827f96239e4371cd8fd5f5f50172e4b0eba79
bigcode/the-stack
train
f935620b518c71b9f8b8fc7a
train
function
def load(filepath, input_dict, quantities, param_dict): print("") print("Loading {} from file {}".format(quantities, filepath)) try: h5file = tables.open_file(filepath, mode="r") root = h5file.root for q in quantities: input_dict[q] = h5file.get_node(root, q).read() ...
def load(filepath, input_dict, quantities, param_dict):
print("") print("Loading {} from file {}".format(quantities, filepath)) try: h5file = tables.open_file(filepath, mode="r") root = h5file.root for q in quantities: input_dict[q] = h5file.get_node(root, q).read() # loading parameters # only overwrite what ...
/ (1 + 2 * np.pi * 1j * tau * (f - f0)) + 1.0 / (1 + 2 * np.pi * 1j * tau * (f + f0))) ) return out # LOAD / SAVE FUNCTIONS -------------------------------------------------------- def load(filepath, input_dict, quantities, param_dict):
74
75
252
12
62
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
load
load
679
707
679
679
8287ec26a861e595d77aa2a75b9578e80f4f292f
bigcode/the-stack
train
0c2c1fe7175fbdd0a42db14c
train
function
def fit_exp_damped_osc_freqdom( init_vals, fpeak_real_r1_mumod, peak_real_r1_mumod, fpeak_imag_r1_mumod, peak_imag_r1_mumod, firstfit ): # first global brute-force optimization on a coarse grid to reduce risk of # finding a local optimum (narrow ranges used here) # Note that some of the values set here...
def fit_exp_damped_osc_freqdom( init_vals, fpeak_real_r1_mumod, peak_real_r1_mumod, fpeak_imag_r1_mumod, peak_imag_r1_mumod, firstfit ): # first global brute-force optimization on a coarse grid to reduce risk of # finding a local optimum (narrow ranges used here) # Note that some of the values set here...
if firstfit: tau_vals = np.arange(10.0, 35, 0.025) # ms f0_vals = np.arange(0.0, 0.005, 1e-4) # kHz else: tau_vals = np.arange(np.max([0.0, init_vals[0] - 5]), init_vals[0] + 2, 0.005) f0_vals = np.arange(np.max([0.0, init_vals[1] - 0.001]), init_vals[1] + 0.02, 5e-5) args...
* 2.0 * np.pi * f * tau) # exp. function in Fourier domain error = np.sum(np.abs(exp_fdom - r1_mod_normalized) ** 2) # correct normalization for mean squared error is not important for optim. return error def fit_exp_damped_osc_freqdom( init_vals, fpeak_real_r1_mumod, peak_real_r1_mumod, fpeak_imag_r1...
172
172
576
111
60
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
fit_exp_damped_osc_freqdom
fit_exp_damped_osc_freqdom
590
628
590
597
e30bb4a9a7eda15e1934f67d81c78457ba42ee27
bigcode/the-stack
train
a91ca5c8eb0a6e0a89e25533
train
function
@numba.njit def EIF_lin_rate_response(V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, w): dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) q1a = 1.0 + 0.0 * 1j p1a = 0.0 * 1j q1b = 0.0 * 1j p1b = 0.0 * 1j fw = dV * 1j * w refterm = np.exp(-1j * w * Tre...
@numba.njit def EIF_lin_rate_response(V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, w):
dV = V_vec[1] - V_vec[0] sig2term = 2.0 / sigma ** 2 n = len(V_vec) q1a = 1.0 + 0.0 * 1j p1a = 0.0 * 1j q1b = 0.0 * 1j p1b = 0.0 * 1j fw = dV * 1j * w refterm = np.exp(-1j * w * Tref) if DeltaT > 0: Psi = DeltaT * np.exp((V_vec - VT) / DeltaT) else: Psi = 0.0 ...
abs(np.real(r1r)) elif abs_re_im == "imag": valr = abs(np.imag(r1r)) if valr > val: val = valr cval = r1r w_peak = bounds[1] dw /= 2.0 bounds = [np.max([w_min, w_peak - dw]), w_peak +...
159
159
531
39
119
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
EIF_lin_rate_response
EIF_lin_rate_response
505
542
505
506
a575b06d313a30788e0f4b10e98cd2f16b631475
bigcode/the-stack
train
2d0c6529b2ad267dfbfeae04
train
function
def save(filepath, output_dict, param_dict): print("") print("Saving {} to file {}".format(output_dict.keys(), filepath)) try: h5file = tables.open_file(filepath, mode="w") root = h5file.root for k in output_dict.keys(): h5file.create_array(root, k, output_dict[k]) ...
def save(filepath, output_dict, param_dict):
print("") print("Saving {} to file {}".format(output_dict.keys(), filepath)) try: h5file = tables.open_file(filepath, mode="w") root = h5file.root for k in output_dict.keys(): h5file.create_array(root, k, output_dict[k]) print("created array {}".format(k)) ...
: # walk group first yields the group itself, # then its children param_dict[group._v_name] = {} for subchild in group._f_walknodes("Array"): param_dict[group._v_name][subchild._v_name] = subchild.read()[0] h5file.close() except IOError:...
103
103
345
10
93
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
save
save
710
745
710
710
f50bb0207e10700850534566f6b251d439b4b3a2
bigcode/the-stack
train
19ce0dbf7cb9c6432ddef8e0
train
function
def exp_mean_sq_dist(tau, *args): f, r1_mod_normalized = args exp_fdom = 1.0 / (1.0 + 1j * 2.0 * np.pi * f * tau) # exp. function in Fourier domain error = np.sum(np.abs(exp_fdom - r1_mod_normalized) ** 2) # correct normalization for mean squared error is not important for optim. return error
def exp_mean_sq_dist(tau, *args):
f, r1_mod_normalized = args exp_fdom = 1.0 / (1.0 + 1j * 2.0 * np.pi * f * tau) # exp. function in Fourier domain error = np.sum(np.abs(exp_fdom - r1_mod_normalized) ** 2) # correct normalization for mean squared error is not important for optim. return error
# bounds=(tau_lb, tau_ub), method='bounded', # options={'disp':True, 'maxiter':500, 'xatol':1e-3}) # tau = sol.x return tau def exp_mean_sq_dist(tau, *args):
64
64
101
11
52
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
exp_mean_sq_dist
exp_mean_sq_dist
582
587
582
582
362fbc4288043410c6168461d6e97401e70cfd36
bigcode/the-stack
train
90096373f7261ac506f3fc24
train
function
def output_and_quantities_given_sigma_wrapper(arg_tuple): isig, sigma, mu_vals, params, output_names, quantity_names, save_rate_mod = arg_tuple # a few shortcuts V_vec = params["V_vals"] Vr = params["Vr"] kr = np.argmin(np.abs(V_vec - Vr)) # reset index value VT = params["VT"] taum = params...
def output_and_quantities_given_sigma_wrapper(arg_tuple):
isig, sigma, mu_vals, params, output_names, quantity_names, save_rate_mod = arg_tuple # a few shortcuts V_vec = params["V_vals"] Vr = params["Vr"] kr = np.argmin(np.abs(V_vec - Vr)) # reset index value VT = params["VT"] taum = params["taum"] EL = params["EL"] DeltaT = params["deltaT...
LN_quantities_dict[k][imu, isig] = res_given_sigma_dict[k][imu] if pool: pool.close() # also include mu_vals, sigma_vals, and freq_vals in output dictionaries EIF_output_dict["mu_vals"] = mu_vals EIF_output_dict["sigma_vals"] = sigma_vals EIF_output_dict["freq_vals"] = p...
256
256
3,215
11
245
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
output_and_quantities_given_sigma_wrapper
output_and_quantities_given_sigma_wrapper
109
370
109
109
9c4ee3a4d62dcc235fb4f2df4912e04e155199bd
bigcode/the-stack
train
5aed572d34059f51a1aafcd5
train
function
@numba.njit def dosc_mean_sq_dist_2f_tauf0grid(tau_vals, f0_vals, args): f_val1, r1_val1, f_val2, r1_val2 = args errors = np.zeros((len(tau_vals), len(f0_vals))) for i in range(len(tau_vals)): for j in range(len(f0_vals)): tau = tau_vals[i] f0 = f0_vals[j] dosc_at...
@numba.njit def dosc_mean_sq_dist_2f_tauf0grid(tau_vals, f0_vals, args):
f_val1, r1_val1, f_val2, r1_val2 = args errors = np.zeros((len(tau_vals), len(f0_vals))) for i in range(len(tau_vals)): for j in range(len(f0_vals)): tau = tau_vals[i] f0 = f0_vals[j] dosc_at_f1 = ( (1.0 + (2 * np.pi * f0 * tau) ** 2) ...
dosc_at_f2 = eval_dosc_fdom(p, f_val2) error = np.abs(dosc_at_f1 - r1_val1) ** 2 + np.abs(dosc_at_f2 - r1_val2) ** 2 # correct normalization for mean squared error is not important for optim. return error @numba.njit def dosc_mean_sq_dist_2f_tauf0grid(tau_vals, f0_vals, args):
101
101
337
29
71
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
dosc_mean_sq_dist_2f_tauf0grid
dosc_mean_sq_dist_2f_tauf0grid
642
661
642
643
4440609c69e4303b4591fa02d0e30c8d3844a166
bigcode/the-stack
train
c555058c0a8eb16a8326c9d6
train
function
def calc_EIF_output_and_cascade_quants( mu_vals, sigma_vals, params, EIF_output_dict, output_names, save_rate_mod, LN_quantities_dict, quantity_names ): N_mu_vals = len(mu_vals) N_sigma_vals = len(sigma_vals) if N_sigma_vals == 1: N_procs = 1 else: N_procs = params["N_procs"] #...
def calc_EIF_output_and_cascade_quants( mu_vals, sigma_vals, params, EIF_output_dict, output_names, save_rate_mod, LN_quantities_dict, quantity_names ):
N_mu_vals = len(mu_vals) N_sigma_vals = len(sigma_vals) if N_sigma_vals == 1: N_procs = 1 else: N_procs = params["N_procs"] # create EIF_output_dict arrays to be filled for n in output_names: # complex values dependent on mu, sigma, frequency if n in ["r1_mumod",...
# -*- coding: utf-8 -*- """ functions to calculate the quantities required by the LN cascade models, including functions to compute the steady-state and the first order rate response of an exponential/leaky integrate-and-fire neuron subject to white noise input (and modulations of the input moments) -- written by J...
178
256
867
40
138
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
calc_EIF_output_and_cascade_quants
calc_EIF_output_and_cascade_quants
23
104
23
26
aad3812240039c97f306390f5db9a9a39747f35e
bigcode/the-stack
train
d4521669aafffceb32e1811e
train
function
@numba.njit def eval_dosc_fdom(p, f): tau = p[0] f0 = p[1] out = ( (1.0 + (2 * np.pi * f0 * tau) ** 2) / 2 * (1.0 / (1 + 2 * np.pi * 1j * tau * (f - f0)) + 1.0 / (1 + 2 * np.pi * 1j * tau * (f + f0))) ) return out
@numba.njit def eval_dosc_fdom(p, f):
tau = p[0] f0 = p[1] out = ( (1.0 + (2 * np.pi * f0 * tau) ** 2) / 2 * (1.0 / (1 + 2 * np.pi * 1j * tau * (f - f0)) + 1.0 / (1 + 2 * np.pi * 1j * tau * (f + f0))) ) return out
))) ) errors[i, j] = np.abs(dosc_at_f1 - r1_val1) ** 2 + np.abs(dosc_at_f2 - r1_val2) ** 2 return errors @numba.njit def eval_dosc_fdom(p, f):
64
64
122
16
47
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
eval_dosc_fdom
eval_dosc_fdom
664
673
664
665
4c35975125154766d4ba1b3cfba97dd04aaa4b30
bigcode/the-stack
train
724902c6728515adfa210289
train
function
def EIF_find_lin_response_peak( w_vec, r1_vec, r1_f0, V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, abs_re_im ): if abs_re_im == "abs": val = np.max(abs(r1_vec)) ind = np.argmax(abs(r1_vec)) elif abs_re_im == "real": val = np.max(abs(np.real(r1_vec))) ind = np....
def EIF_find_lin_response_peak( w_vec, r1_vec, r1_f0, V_vec, kr, taum, EL, Vr, VT, DeltaT, Tref, mu, sigma, inhom, abs_re_im ):
if abs_re_im == "abs": val = np.max(abs(r1_vec)) ind = np.argmax(abs(r1_vec)) elif abs_re_im == "real": val = np.max(abs(np.real(r1_vec))) ind = np.argmax(abs(np.real(r1_vec))) elif abs_re_im == "imag": val = np.max(abs(np.imag(r1_vec))) ind = np.argmax(abs(np...
hom[k]) else: p1a_new = p1a * A[k] + sig2term_dV * q1a p1b_new = p1b * A[k] + sig2term_dV * (q1b - inhom[k]) q1b += fw * p1b q1a = q1a_new p1a = p1a_new p1b = p1b_new r1_vec[iw] = -q1b / q1a return r1_vec def EIF_fin...
174
174
580
51
122
Ronjaa95/neurolib
neurolib/models/aln/aln-precalc/precompute_quantities/methods_cascade.py
Python
EIF_find_lin_response_peak
EIF_find_lin_response_peak
452
502
452
454
981c1941b923bc1e18957a43dc5ec516cd6631b8
bigcode/the-stack
train
d24ebc76142da42a97eb4998
train
function
def get_codepath(): """Return the absolute path to where the tool is run from.""" path = __file__ if path.startswith(os.path.sep): return path dirname = os.path.dirname(path) for sys_path in sys.path: if sys_path.endswith(dirname): return sys_path return dirname
def get_codepath():
"""Return the absolute path to where the tool is run from.""" path = __file__ if path.startswith(os.path.sep): return path dirname = os.path.dirname(path) for sys_path in sys.path: if sys_path.endswith(dirname): return sys_path return dirname
_analyzer.py MyAnalyzerSketchPlugin Remark: The tool ignores OpenSearch queries. It should be fed with data that matches the expected output of the analyzer. """ import argparse import importlib.util import os import sys from timesketch.lib.analyzers import interface def get_codepath():
64
64
69
5
58
deralexxx/timesketch
test_tools/analyzer_run.py
Python
get_codepath
get_codepath
38
48
38
38
3e3aed704fedd9be507788976c07f1a5ae3610bb
bigcode/the-stack
train
1954a18df58a7fab8ee769b2
train
function
def run_analyzer(analyzer_name, analyzer_path, test_file_path): """Run an analyzer on test data and returns results from the run. Args: analyzer_name: the name of the analyzer to run. analyzer_path: the path to the analyzer file. test_file_path: the path to a test file that contains eve...
def run_analyzer(analyzer_name, analyzer_path, test_file_path):
"""Run an analyzer on test data and returns results from the run. Args: analyzer_name: the name of the analyzer to run. analyzer_path: the path to the analyzer file. test_file_path: the path to a test file that contains event data to feed to the analyzer as part of the test....
the analyzer. """ import argparse import importlib.util import os import sys from timesketch.lib.analyzers import interface def get_codepath(): """Return the absolute path to where the tool is run from.""" path = __file__ if path.startswith(os.path.sep): return path dirname = os.path.dirn...
113
113
378
15
97
deralexxx/timesketch
test_tools/analyzer_run.py
Python
run_analyzer
run_analyzer
51
96
51
51
73d56f8b1b461770e5f89c0eb7e191cd98178e0b
bigcode/the-stack
train
4ee23cbb3413f3c60bda91fa
train
function
def test_selenium_automation(toolbox): tools, slots = toolbox try: runner = execute_runner(tools, slots, scenario_get_page_source) except Exception as e: print(e) runner = None assert runner page = load_html(runner.output) assert page.title.string == "Google" runn...
def test_selenium_automation(toolbox):
tools, slots = toolbox try: runner = execute_runner(tools, slots, scenario_get_page_source) except Exception as e: print(e) runner = None assert runner page = load_html(runner.output) assert page.title.string == "Google" runner.clean()
.fixture def toolbox(): tools = { 'b': Browser(DriverFactory.local_headless()) } slots = { 'google': GoogleSearch(tools['b']), 'phrase': "doge memes" } return tools, slots def test_selenium_automation(toolbox):
64
64
75
9
54
przor3n/selenium_automation
tests/test_selenium-script.py
Python
test_selenium_automation
test_selenium_automation
31
45
31
31
32aa35864e01fb32541b6f0a52782eb1fbc060c7
bigcode/the-stack
train
90013a198df6d685a23a2a4e
train
function
@pytest.fixture def toolbox(): tools = { 'b': Browser(DriverFactory.local_headless()) } slots = { 'google': GoogleSearch(tools['b']), 'phrase': "doge memes" } return tools, slots
@pytest.fixture def toolbox():
tools = { 'b': Browser(DriverFactory.local_headless()) } slots = { 'google': GoogleSearch(tools['b']), 'phrase': "doge memes" } return tools, slots
.automation_testing.selenium_automation.selenium_automation.runner import Runner # noqa from codelib.parsing.beautifulsoup import load_html def execute_runner(t, s, i): runner = Runner(t, s, i) runner.do() return runner @pytest.fixture def toolbox():
64
64
56
6
57
przor3n/selenium_automation
tests/test_selenium-script.py
Python
toolbox
toolbox
17
28
17
18
d1930e54533548802feae0069da88e9e62c92705
bigcode/the-stack
train
2a3e66c0badb71d5ba1be33b
train
function
def test_selenium_find_doge(toolbox): tools, slots = toolbox try: runner = execute_runner(tools, slots, scenario_do_several_things) except Exception as e: print(e) runner = None assert runner search, images, alert = runner.output assert load_html(search).title.string....
def test_selenium_find_doge(toolbox):
tools, slots = toolbox try: runner = execute_runner(tools, slots, scenario_do_several_things) except Exception as e: print(e) runner = None assert runner search, images, alert = runner.output assert load_html(search).title.string.startswith("doge memes") assert al...
= execute_runner(tools, slots, scenario_get_page_source) except Exception as e: print(e) runner = None assert runner page = load_html(runner.output) assert page.title.string == "Google" runner.clean() def test_selenium_find_doge(toolbox):
64
64
88
10
54
przor3n/selenium_automation
tests/test_selenium-script.py
Python
test_selenium_find_doge
test_selenium_find_doge
48
64
48
48
1cc6d4dee4171c7276dd0bc7baac37cf53ff308d
bigcode/the-stack
train
c475821d04877ce0fc7a304a
train
function
def execute_runner(t, s, i): runner = Runner(t, s, i) runner.do() return runner
def execute_runner(t, s, i):
runner = Runner(t, s, i) runner.do() return runner
_automation.pages.google import scenario_get_page_source, scenario_do_several_things # noqa from codelib.automation_testing.selenium_automation.selenium_automation.runner import Runner # noqa from codelib.parsing.beautifulsoup import load_html def execute_runner(t, s, i):
64
64
27
9
54
przor3n/selenium_automation
tests/test_selenium-script.py
Python
execute_runner
execute_runner
10
14
10
10
9fd9377647a34fc5746f9a03d68d34d359407dde
bigcode/the-stack
train
b4d6ad05ee4721077d47b1df
train
class
class Processor(object): PROCESS_TIME_LIMIT = 30 EXCEPTION_LIMIT = 3 RESULT_LOGS_LIMIT = 1000 RESULT_RESULT_LIMIT = 100 def __init__(self, projectdb, inqueue, status_queue, newtask_queue, result_queue): self.inqueue = inqueue self.status_queue = status_queue self.newtask_qu...
class Processor(object):
PROCESS_TIME_LIMIT = 30 EXCEPTION_LIMIT = 3 RESULT_LOGS_LIMIT = 1000 RESULT_RESULT_LIMIT = 100 def __init__(self, projectdb, inqueue, status_queue, newtask_queue, result_queue): self.inqueue = inqueue self.status_queue = status_queue self.newtask_queue = newtask_queue ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-02-16 22:59:56 import sys import time import logging logger = logging.getLogger("processor") from six.moves import queue as Queue from pyspider.libs ...
133
256
942
4
128
ronaldhan/pyspider
pyspider/processor/processor.py
Python
Processor
Processor
19
153
19
19
d78f34c7fdf6a1e1fc1cc648967d802445be4ad7
bigcode/the-stack
train
690fed0e4a252b1741b010f1
train
class
class SwapXapiHostTestCase(test.NoDBTestCase): def test_swapping(self): self.assertEqual( "http://otherserver:8765/somepath", pool.swap_xapi_host( "http://someserver:8765/somepath", 'otherserver')) def test_no_port(self): self.assertEqual( "h...
class SwapXapiHostTestCase(test.NoDBTestCase):
def test_swapping(self): self.assertEqual( "http://otherserver:8765/somepath", pool.swap_xapi_host( "http://someserver:8765/somepath", 'otherserver')) def test_no_port(self): self.assertEqual( "http://otherserver/somepath", pool.sw...
.fake_aggregate, "slave") self.assertIn( (slave.compute_rpcapi.remove_aggregate_host, "CONTEXT", 98, "slave", "master", "SLAVE_INFO"), slave.compute_rpcapi._mock_calls) class SwapXapiHostTestCase(test.NoDBTestCase):
64
64
145
13
51
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
SwapXapiHostTestCase
SwapXapiHostTestCase
3,339
3,357
3,339
3,340
19777808726e7df3ce9cf6ebc77f05ad9b039448
bigcode/the-stack
train
6870b7e2594eb3fbda26f56e
train
class
class XenAPIVolumeTestCase(stubs.XenAPITestBaseNoDB): """Unit tests for Volume operations.""" def setUp(self): super(XenAPIVolumeTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, ...
class XenAPIVolumeTestCase(stubs.XenAPITestBaseNoDB):
"""Unit tests for Volume operations.""" def setUp(self): super(XenAPIVolumeTestCase, self).setUp() self.fixture = self.useFixture(config_fixture.Config(lockutils.CONF)) self.fixture.config(disable_process_locking=True, group='oslo_concurrency') self.fl...
return function(self, *args, **kwargs) finally: fake_image._FakeImageService.download = orig_image_download vm_utils.vdi_attached_here = orig_vdi_attached_here return decorated_function def create_instance_with_system_metadata(context, instance_values): inst = objects.Instanc...
166
166
556
18
147
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIVolumeTestCase
XenAPIVolumeTestCase
229
281
229
229
50aed40e192008c2d1025db2edfeb1c8f784128e
bigcode/the-stack
train
8ccf408eabec45d89998712a
train
function
def _create_service_entries(context, values={'avail_zone1': ['fake_host1', 'fake_host2'], 'avail_zone2': ['fake_host3'], }): for avail_zone, hosts in six.iteritems(values): for service_host in hosts: ...
def _create_service_entries(context, values={'avail_zone1': ['fake_host1', 'fake_host2'], 'avail_zone2': ['fake_host3'], }):
for avail_zone, hosts in six.iteritems(values): for service_host in hosts: db.service_create(context, {'host': service_host, 'binary': 'nova-compute', 'topic': 'compute', 'r...
_utils.safe_find_sr(session) self.assertEqual(session.call_xenapi('pool.get_default_SR', pool_ref), expected) def _create_service_entries(context, values={'avail_zone1': ['fake_host1', 'fake_host2'], ...
64
64
96
37
27
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
_create_service_entries
_create_service_entries
2,969
2,979
2,969
2,971
e2634f0aa02f7a4697aae79ecbd397cf61647a7b
bigcode/the-stack
train
b18825eb9f12ccd4a0b2dee9
train
class
class StubDependencies(object): """Stub dependencies for ResourcePool.""" def __init__(self): self.compute_rpcapi = MockComputeAPI() def _is_hv_pool(self, *_ignore): return True def _get_metadata(self, *_ignore): return { pool_states.KEY: {}, 'master_co...
class StubDependencies(object):
"""Stub dependencies for ResourcePool.""" def __init__(self): self.compute_rpcapi = MockComputeAPI() def _is_hv_pool(self, *_ignore): return True def _get_metadata(self, *_ignore): return { pool_states.KEY: {}, 'master_compute': 'master' } ...
host_param, host, slave_info)) def remove_aggregate_host(self, ctxt, aggregate_id, host_param, host, slave_info): self._mock_calls.append(( self.remove_aggregate_host, ctxt, aggregate_id, host_param, host, slave_info)) class StubDependencies(object):
64
64
93
5
59
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
StubDependencies
StubDependencies
3,282
3,298
3,282
3,282
8274949fcd28f32b0d0150113e94b1746b911f49
bigcode/the-stack
train
784831d8551c5cd3a418a377
train
function
def stub_vm_utils_with_vdi_attached_here(function): """vm_utils.with_vdi_attached_here needs to be stubbed out because it calls down to the filesystem to attach a vdi. This provides a decorator to handle that. """ @functools.wraps(function) def decorated_function(self, *args, **kwargs): ...
def stub_vm_utils_with_vdi_attached_here(function):
"""vm_utils.with_vdi_attached_here needs to be stubbed out because it calls down to the filesystem to attach a vdi. This provides a decorator to handle that. """ @functools.wraps(function) def decorated_function(self, *args, **kwargs): @contextlib.contextmanager def fake_vdi_atta...
'auth_method': u'CHAP'}, }, 'mount_device': 'vda', 'delete_on_termination': False}, ], 'root_device_name': '/dev/sda', 'ephemerals': [], 'swap': None, } return fake def stub_vm_utils_with_vdi_attached_here(function):
70
70
234
12
57
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
stub_vm_utils_with_vdi_attached_here
stub_vm_utils_with_vdi_attached_here
186
211
186
186
fd0d341067bbd34def5a45442d9c4954b1f81dc3
bigcode/the-stack
train
c0d48e60d63ab3703654e235
train
class
class XenAPIDiffieHellmanTestCase(test.NoDBTestCase): """Unit tests for Diffie-Hellman code.""" def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() self.alice = agent.SimpleDH() self.bob = agent.SimpleDH() def test_shared(self): alice_pub = self.alice.get_publi...
class XenAPIDiffieHellmanTestCase(test.NoDBTestCase):
"""Unit tests for Diffie-Hellman code.""" def setUp(self): super(XenAPIDiffieHellmanTestCase, self).setUp() self.alice = agent.SimpleDH() self.bob = agent.SimpleDH() def test_shared(self): alice_pub = self.alice.get_public() bob_pub = self.bob.get_public() al...
disk", fake_destroy_kernel_ramdisk) instance = self._create_instance(spawn=True, obj=True) network_info = fake_network.fake_get_instance_nw_info(self.stubs) self.conn.destroy(self.context, instance, network_info) vm_ref = vm_utils.lookup(self.conn._session, insta...
102
102
342
16
86
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIDiffieHellmanTestCase
XenAPIDiffieHellmanTestCase
1,599
1,635
1,599
1,599
726dc7d703ef4a57fd956ebabde78289b6ef651a
bigcode/the-stack
train
cbe76eb6b5decfef0a9fef4f
train
class
class XenAPIBWCountersTestCase(stubs.XenAPITestBaseNoDB): FAKE_VMS = {'test1:ref': dict(name_label='test1', other_config=dict(nova_uuid='hash'), domid='12', _vifmap={'0': "a:b:c:d...", ...
class XenAPIBWCountersTestCase(stubs.XenAPITestBaseNoDB):
FAKE_VMS = {'test1:ref': dict(name_label='test1', other_config=dict(nova_uuid='hash'), domid='12', _vifmap={'0': "a:b:c:d...", '1': "e:f:12:q..."}), 'te...
', fake_generate_swap) self.assertCalled(instance) def test_generate_ephemeral(self): # Test ephemeral disk generation. instance_values = dict(self.instance_values, instance_type_id=4) instance = create_instance_with_system_metadata(self.context, ...
249
249
831
18
231
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIBWCountersTestCase
XenAPIBWCountersTestCase
2,497
2,581
2,497
2,497
3cef55d7f9579006137aa4158951606c0bf8fd68
bigcode/the-stack
train
363314c9d08618e388f9ed2a
train
class
class HypervisorPoolTestCase(test.NoDBTestCase): fake_aggregate = { 'id': 98, 'hosts': [], 'metadata': { 'master_compute': 'master', pool_states.POOL_FLAG: {}, pool_states.KEY: {} } } def test_slave_asks_master_to_add_slave_to_poo...
class HypervisorPoolTestCase(test.NoDBTestCase):
fake_aggregate = { 'id': 98, 'hosts': [], 'metadata': { 'master_compute': 'master', pool_states.POOL_FLAG: {}, pool_states.KEY: {} } } def test_slave_asks_master_to_add_slave_to_pool(self): slave = ResourcePoolWithStubs() ...
pool_states.KEY: {}, 'master_compute': 'master' } def _create_slave_info(self, *ignore): return "SLAVE_INFO" class ResourcePoolWithStubs(StubDependencies, pool.ResourcePool): """A ResourcePool, use stub dependencies.""" class HypervisorPoolTestCase(test.NoDBTestCase): ...
70
71
239
12
58
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
HypervisorPoolTestCase
HypervisorPoolTestCase
3,305
3,336
3,305
3,306
75f0d35479ce78eecd0ef4da1818760a69b60be9
bigcode/the-stack
train
5a633bb0d083869255329b70
train
function
def get_fake_device_info(): # FIXME: 'sr_uuid', 'introduce_sr_keys', sr_type and vdi_uuid # can be removed from the dict when LP bug #1087308 is fixed fake_vdi_ref = xenapi_fake.create_vdi('fake-vdi', None) fake_vdi_uuid = xenapi_fake.get_record('VDI', fake_vdi_ref)['uuid'] fake = {'block_device_map...
def get_fake_device_info(): # FIXME: 'sr_uuid', 'introduce_sr_keys', sr_type and vdi_uuid # can be removed from the dict when LP bug #1087308 is fixed
fake_vdi_ref = xenapi_fake.create_vdi('fake-vdi', None) fake_vdi_uuid = xenapi_fake.get_record('VDI', fake_vdi_ref)['uuid'] fake = {'block_device_mapping': [{'connection_info': {'driver_volume_type': 'iscsi', 'data': {'sr_uuid': 'falseSR', ...
image_id, image_meta in IMAGE_FIXTURES.items(): image_meta = image_meta['image_meta'] image_meta['id'] = image_id image_service.create(None, image_meta) def get_fake_device_info(): # FIXME: 'sr_uuid', 'introduce_sr_keys', sr_type and vdi_uuid # can be removed from the dict when LP bug #...
86
86
289
45
41
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
get_fake_device_info
get_fake_device_info
159
183
159
161
04183687868fc1487053416522a535ab346b6919
bigcode/the-stack
train
c3f25037c8c4b93a419ca221
train
class
class XenAPIAutoDiskConfigTestCase(stubs.XenAPITestBase): def setUp(self): super(XenAPIAutoDiskConfigTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.x...
class XenAPIAutoDiskConfigTestCase(stubs.XenAPITestBase):
def setUp(self): super(XenAPIAutoDiskConfigTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0I...
.assertEqual('foo', stats['hypervisor_hostname']) class ToSupportedInstancesTestCase(test.NoDBTestCase): def test_default_return_value(self): self.assertEqual([], host.to_supported_instances(None)) def test_return_value(self): self.assertEqual([(arch.X86_64, hv_type.XEN, 'xen')], ...
256
256
1,086
17
238
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIAutoDiskConfigTestCase
XenAPIAutoDiskConfigTestCase
2,272
2,390
2,272
2,272
1d1050d66c602cefda8c7f892f42041636de1f68
bigcode/the-stack
train
ae4289de7398cfaa73593774
train
class
class XenAPIAggregateTestCase(stubs.XenAPITestBase): """Unit tests for aggregate operations.""" def setUp(self): super(XenAPIAggregateTestCase, self).setUp() self.flags(connection_url='http://test_url', connection_username='test_user', connection_password='t...
class XenAPIAggregateTestCase(stubs.XenAPITestBase):
"""Unit tests for aggregate operations.""" def setUp(self): super(XenAPIAggregateTestCase, self).setUp() self.flags(connection_url='http://test_url', connection_username='test_user', connection_password='test_pass', group='xenserver') ...
_utils.safe_find_sr(session) self.assertEqual(local_sr, expected) def test_safe_find_sr_default(self): # Ensure the default SR is found regardless of other-config. self.flags(sr_matching_filter='default-sr:true', group='xenserver') stubs.stubout_session(self.stubs...
256
256
2,584
16
239
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIAggregateTestCase
XenAPIAggregateTestCase
2,983
3,262
2,983
2,983
80ef75a602211f3917896e83bbe6dded393a9932
bigcode/the-stack
train
2d8aea5fe21154ba712d73b7
train
class
class MockComputeAPI(object): def __init__(self): self._mock_calls = [] def add_aggregate_host(self, ctxt, aggregate, host_param, host, slave_info): self._mock_calls.append(( self.add_aggregate_host, ctxt, aggregate, host_param, host,...
class MockComputeAPI(object):
def __init__(self): self._mock_calls = [] def add_aggregate_host(self, ctxt, aggregate, host_param, host, slave_info): self._mock_calls.append(( self.add_aggregate_host, ctxt, aggregate, host_param, host, slave_info)) def remove_...
.add_aggregate_host, self.context, host="fake_host", aggregate=self.aggr, slave_info=None) self.assertEqual(self.aggr.metadata[pool_states.KEY], pool_states.ERROR) self.assertEqual(self.aggr.hosts, ['fake_host'...
63
64
120
6
57
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
MockComputeAPI
MockComputeAPI
3,265
3,279
3,265
3,265
76974a5bd7f1954c6731f8f83c613fea20f23e48
bigcode/the-stack
train
10539f967b34801d1eda2248
train
class
class XenAPIGenerateLocal(stubs.XenAPITestBase): """Test generating of local disks, like swap and ephemeral.""" def setUp(self): super(XenAPIGenerateLocal, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver'...
class XenAPIGenerateLocal(stubs.XenAPITestBase):
"""Test generating of local disks, like swap and ephemeral.""" def setUp(self): super(XenAPIGenerateLocal, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.x...
IsPartitionCalled(False) @stub_vm_utils_with_vdi_attached_here def test_instance_auto_disk_config_fails_safe_bad_fstype(self): # Should not partition unless fail safes pass. self.instance_values['auto_disk_config'] = True def fake_get_partitions(dev): return [(1, 100, 200, ...
256
256
907
14
241
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIGenerateLocal
XenAPIGenerateLocal
2,394
2,494
2,394
2,394
a3c33afa600e70834d8e392be7d08f114050274b
bigcode/the-stack
train
34aeee7ad01ae4754b70ebf5
train
class
class XenAPIFakeTestCase(test.NoDBTestCase): def test_query_matches(self): record = {'a': '1', 'b': '2', 'c_d': '3'} tests = {'field "a"="1"': True, 'field "b"="2"': True, 'field "b"="4"': False, 'not field "b"="4"': True, 'field "...
class XenAPIFakeTestCase(test.NoDBTestCase):
def test_query_matches(self): record = {'a': '1', 'b': '2', 'c_d': '3'} tests = {'field "a"="1"': True, 'field "b"="2"': True, 'field "b"="4"': False, 'not field "b"="4"': True, 'field "a"="1" and field "b"="4"': False, ...
path = os.path.join(path, elem) path = os.path.realpath(path) plugin_version = None with open(path) as plugin_file: for line in plugin_file: if "PLUGIN_VERSION = " in line: plugin_version = line.strip()[17:].strip('"') self.as...
90
90
301
13
77
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIFakeTestCase
XenAPIFakeTestCase
4,148
4,178
4,148
4,148
980029afaecb537decb8c65409913cf4afd5bfb2
bigcode/the-stack
train
f79743aaf3dbc0b797a42343
train
class
class XenAPIInjectMetadataTestCase(stubs.XenAPITestBaseNoDB): def setUp(self): super(XenAPIInjectMetadataTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.vi...
class XenAPIInjectMetadataTestCase(stubs.XenAPITestBaseNoDB):
def setUp(self): super(XenAPIInjectMetadataTestCase, self).setUp() self.flags(connection_url='test_url', connection_password='test_pass', group='xenserver') self.flags(firewall_driver='nova.virt.xenapi.firewall.' 'Dom0I...
safe_find_sr", fake_find_sr) def fake_get_instance_vdis_for_sr(_session, _vm_ref, _sr_ref): self.assertEqual(conn._session, _session) self.assertEqual(vm_ref, _vm_ref) self.assertEqual("source_sr_ref", _sr_ref) return ["vdi0", "vdi1"] self.stubs.Set(vm_u...
256
256
1,612
17
239
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIInjectMetadataTestCase
XenAPIInjectMetadataTestCase
3,833
4,011
3,833
3,833
f6309d203c9bf588d5d8e80708ad65bae20387e6
bigcode/the-stack
train
104993b125c1dd81f0b79509
train
class
class ResourcePoolWithStubs(StubDependencies, pool.ResourcePool): """A ResourcePool, use stub dependencies."""
class ResourcePoolWithStubs(StubDependencies, pool.ResourcePool):
"""A ResourcePool, use stub dependencies."""
return True def _get_metadata(self, *_ignore): return { pool_states.KEY: {}, 'master_compute': 'master' } def _create_slave_info(self, *ignore): return "SLAVE_INFO" class ResourcePoolWithStubs(StubDependencies, pool.ResourcePool):
64
64
24
14
50
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
ResourcePoolWithStubs
ResourcePoolWithStubs
3,301
3,302
3,301
3,301
be8b53e21e53a66806b39ea151085b27b8b9537f
bigcode/the-stack
train
259f29c44bd580d50cc83da7
train
function
def create_instance_with_system_metadata(context, instance_values): inst = objects.Instance(context=context, system_metadata={}) for k, v in instance_values.items(): setattr(inst, k, v) inst.flavor = objects.Flavor.get_by_id(context, ...
def create_instance_with_system_metadata(context, instance_values):
inst = objects.Instance(context=context, system_metadata={}) for k, v in instance_values.items(): setattr(inst, k, v) inst.flavor = objects.Flavor.get_by_id(context, instance_values['instance_type_id']) inst.old_flavor = None...
= fake_image_download return function(self, *args, **kwargs) finally: fake_image._FakeImageService.download = orig_image_download vm_utils.vdi_attached_here = orig_vdi_attached_here return decorated_function def create_instance_with_system_metadata(context, instance_val...
64
64
101
11
52
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
create_instance_with_system_metadata
create_instance_with_system_metadata
214
226
214
214
89dbf3cbfb78332e9e44aaee2c81130eb0509e40
bigcode/the-stack
train
ab7ce98cea432be152e58c83
train
function
def set_image_fixtures(): image_service = fake_image.FakeImageService() image_service.images.clear() for image_id, image_meta in IMAGE_FIXTURES.items(): image_meta = image_meta['image_meta'] image_meta['id'] = image_id image_service.create(None, image_meta)
def set_image_fixtures():
image_service = fake_image.FakeImageService() image_service.images.clear() for image_id, image_meta in IMAGE_FIXTURES.items(): image_meta = image_meta['image_meta'] image_meta['id'] = image_id image_service.create(None, image_meta)
{'name': 'fake_ipxe_iso', 'id': 'fake-image-volume', 'properties': {'foo': 'bar'}}, }, } def get_session(): return xenapi_session.XenAPISession('test_url', 'root', 'test_pass') def set_image_fixtures():
64
64
67
7
57
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
set_image_fixtures
set_image_fixtures
150
156
150
150
c7b21c2f46f90825bc364089a9a78840ead10510
bigcode/the-stack
train
768a3f5ad83ca0a67cb3023b
train
class
class XenAPIDom0IptablesFirewallTestCase(stubs.XenAPITestBase): REQUIRES_LOCKING = True _in_rules = [ '# Generated by iptables-save v1.4.10 on Sat Feb 19 00:03:19 2011', '*nat', ':PREROUTING ACCEPT [1170:189210]', ':INPUT ACCEPT [844:71028]', ':OUTPUT ACCEPT [5149:405186]', ...
class XenAPIDom0IptablesFirewallTestCase(stubs.XenAPITestBase):
REQUIRES_LOCKING = True _in_rules = [ '# Generated by iptables-save v1.4.10 on Sat Feb 19 00:03:19 2011', '*nat', ':PREROUTING ACCEPT [1170:189210]', ':INPUT ACCEPT [844:71028]', ':OUTPUT ACCEPT [5149:405186]', ':POSTROUTING ACCEPT [5063:386098]', '# Completed on Mon D...
21024, bw_out=22048), result) self.assertIn(dict(uuid='4-5-6', mac_address="e:f:42:q...", bw_in=231337, bw_out=221212121), result) def test_get_all_bw_counters_in_failure_case(self): """Test ...
256
256
3,658
20
235
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIDom0IptablesFirewallTestCase
XenAPIDom0IptablesFirewallTestCase
2,590
2,910
2,590
2,591
e010acc20430705670c99eec30bbe3d5215a6cc9
bigcode/the-stack
train
31ce2a80048aa4e9374fb22b
train
class
class XenAPIImageTypeTestCase(test.NoDBTestCase): """Test ImageType class.""" def test_to_string(self): # Can convert from type id to type string. self.assertEqual( vm_utils.ImageType.to_string(vm_utils.ImageType.KERNEL), vm_utils.ImageType.KERNEL_STR) def _assert_r...
class XenAPIImageTypeTestCase(test.NoDBTestCase):
"""Test ImageType class.""" def test_to_string(self): # Can convert from type id to type string. self.assertEqual( vm_utils.ImageType.to_string(vm_utils.ImageType.KERNEL), vm_utils.ImageType.KERNEL_STR) def _assert_role(self, expected_role, image_type_id): s...
ox.StubOutWithMock(vm_utils, 'hard_shutdown_vm') vm_utils.is_vm_shutdown(vmops._session, "ref").AndReturn(True) self.mox.ReplayAll() vmops._resize_ensure_vm_is_shutdown(fake_instance, "ref") class XenAPIImageTypeTestCase(test.NoDBTestCase):
69
69
230
13
56
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIImageTypeTestCase
XenAPIImageTypeTestCase
2,020
2,047
2,020
2,020
9f90d73582f1ccc7fd78280272682d570ac8a19b
bigcode/the-stack
train
be1ae26a4b68abb8ecfa98e4
train
class
class XenAPIDetermineDiskImageTestCase(test.NoDBTestCase): """Unit tests for code that detects the ImageType.""" def assert_disk_type(self, image_meta, expected_disk_type): actual = vm_utils.determine_disk_image_type(image_meta) self.assertEqual(expected_disk_type, actual) def test_machine(...
class XenAPIDetermineDiskImageTestCase(test.NoDBTestCase):
"""Unit tests for code that detects the ImageType.""" def assert_disk_type(self, image_meta, expected_disk_type): actual = vm_utils.determine_disk_image_type(image_meta) self.assertEqual(expected_disk_type, actual) def test_machine(self): image_meta = objects.ImageMeta.from_dict( ...
_disk_raw(self): self._assert_role('root', vm_utils.ImageType.DISK_RAW) def test_get_image_role_disk_vhd(self): self._assert_role('root', vm_utils.ImageType.DISK_VHD) class XenAPIDetermineDiskImageTestCase(test.NoDBTestCase):
64
64
187
16
48
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPIDetermineDiskImageTestCase
XenAPIDetermineDiskImageTestCase
2,050
2,069
2,050
2,050
4f9c3c1054ec0960ae148218758343610975763d
bigcode/the-stack
train
d90a04cb0498a5f286f854ce
train
class
class XenAPISessionTestCase(test.NoDBTestCase): def _get_mock_xapisession(self, software_version): class MockXapiSession(xenapi_session.XenAPISession): def __init__(_ignore): "Skip the superclass's dirty init" def _get_software_version(_ignore): retur...
class XenAPISessionTestCase(test.NoDBTestCase):
def _get_mock_xapisession(self, software_version): class MockXapiSession(xenapi_session.XenAPISession): def __init__(_ignore): "Skip the superclass's dirty init" def _get_software_version(_ignore): return software_version return MockXapiSessi...
-']) instance = {'uuid': 'fake'} self.xenstore = { 'persist': { 'vm-data/user-metadata/a': '1', 'vm-data/user-metadata/b': '2', 'vm-data/user-metadata/c': '3', }, 'ephem': { 'vm-data/user-metadata/a':...
256
256
1,084
13
243
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
XenAPISessionTestCase
XenAPISessionTestCase
4,014
4,145
4,014
4,014
473b64c0d2fee2f8bf5e39b97ae003460753e591
bigcode/the-stack
train
0e549b0f14714aaab0b78ddd
train
function
def get_session(): return xenapi_session.XenAPISession('test_url', 'root', 'test_pass')
def get_session():
return xenapi_session.XenAPISession('test_url', 'root', 'test_pass')
xe', 'properties': {'ipxe_boot': 'true'}}, }, IMAGE_FROM_VOLUME: { 'image_meta': {'name': 'fake_ipxe_iso', 'id': 'fake-image-volume', 'properties': {'foo': 'bar'}}, }, } def get_session():
64
64
25
4
60
JohnGarbutt/nova
nova/tests/unit/virt/xenapi/test_xenapi.py
Python
get_session
get_session
146
147
146
146
c64ee0d2cb4b9bdaa88123c08a5c5b29a5533083
bigcode/the-stack
train