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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54e3e913a42f4ee3c9bef438 | train | function | def main():
module_args = oci_utils.get_common_arg_spec()
module_args.update(
dict(
tag_namespace_id=dict(type="str", required=True),
tag_name=dict(type="str", required=False, aliases=["name"]),
)
)
module = AnsibleModule(argument_spec=module_args, supports_check... | def main():
| module_args = oci_utils.get_common_arg_spec()
module_args.update(
dict(
tag_namespace_id=dict(type="str", required=True),
tag_name=dict(type="str", required=False, aliases=["name"]),
)
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=False)... | ).data
return to_dict([tag])
return to_dict(
oci_utils.call_with_backoff(
identity_client.list_tags, tag_namespace_id=tag_namespace_id
).data
)
except ServiceError as ex:
module.fail_json(msg=ex.message)
def main():
| 64 | 64 | 161 | 3 | 61 | slmjy/oci-ansible-modules | library/oci_tag_facts.py | Python | main | main | 135 | 155 | 135 | 135 | 47ebd0001f0a1b44f714c026ea660e053bcd3f6c | bigcode/the-stack | train |
6f661b8fe8229fe363b1be55 | train | function | def calibration(specs_path, csv_path, specs_path_calib, calibrated_csv_path):
"""
Arguments
---------
specs_path
csv_path
specs_path_calib
calibrated_csv_path
"""
specs_data = pd.read_excel(specs_path, sheet_name='SpecsData')
settlements_in_csv = csv_path
settlements_out_csv... | def calibration(specs_path, csv_path, specs_path_calib, calibrated_csv_path):
| """
Arguments
---------
specs_path
csv_path
specs_path_calib
calibrated_csv_path
"""
specs_data = pd.read_excel(specs_path, sheet_name='SpecsData')
settlements_in_csv = csv_path
settlements_out_csv = calibrated_csv_path
onsseter = SettlementProcessor(settlements_in_csv)... | _CAPACITY_INVESTMENT, SPE_GRID_LOSSES,
SPE_MAX_GRID_EXTENSION_DIST,
SPE_NUM_PEOPLE_PER_HH_RURAL,
SPE_NUM_PEOPLE_PER_HH_URBAN, SPE_POP, SPE_POP_FUTURE,
SPE_START_YEAR, SPE_URBAN, SPE_URBAN_FUTURE,
... | 249 | 249 | 833 | 18 | 231 | OnSSET/gep-onsset | onsset/runner.py | Python | calibration | calibration | 33 | 100 | 33 | 33 | 7671da9816a1961bb9da219ed21344489759e27c | bigcode/the-stack | train |
ac3d0236f681b19b1c1dae62 | train | function | def scenario(specs_path, calibrated_csv_path, results_folder, summary_folder):
"""
Arguments
---------
specs_path : str
calibrated_csv_path : str
results_folder : str
summary_folder : str
"""
scenario_info = pd.read_excel(specs_path, sheet_name='ScenarioInfo')
scenarios = scen... | def scenario(specs_path, calibrated_csv_path, results_folder, summary_folder):
| """
Arguments
---------
specs_path : str
calibrated_csv_path : str
results_folder : str
summary_folder : str
"""
scenario_info = pd.read_excel(specs_path, sheet_name='ScenarioInfo')
scenarios = scenario_info['Scenario']
scenario_parameters = pd.read_excel(specs_path, sheet... | = elec_calibration_results[2]
specs_data['grid_data_used'] = elec_calibration_results[3]
specs_data['grid_distance_used'] = elec_calibration_results[4]
specs_data['ntl_limit'] = elec_calibration_results[5]
specs_data['pop_limit'] = elec_calibration_results[6]
specs_data['Buffer_used'] = elec_calibr... | 256 | 256 | 2,607 | 16 | 240 | OnSSET/gep-onsset | onsset/runner.py | Python | scenario | scenario | 103 | 338 | 103 | 103 | a03b529aeef5ec539d4d0cceb51f538e78fc53f2 | bigcode/the-stack | train |
ce751ce99e82b2543231aedc | train | class | @dataclass
class AlgorithmHparams(hp.Hparams, ABC):
"""Hyperparameters for algorithms."""
@abstractmethod
def initialize_object(self) -> Algorithm:
"""Invoked by the :meth:`TrainerHparams.initialize_object` to create an instance of the :class:`Algorithm`.
Returns:
Algorithm: An... | @dataclass
class AlgorithmHparams(hp.Hparams, ABC):
| """Hyperparameters for algorithms."""
@abstractmethod
def initialize_object(self) -> Algorithm:
"""Invoked by the :meth:`TrainerHparams.initialize_object` to create an instance of the :class:`Algorithm`.
Returns:
Algorithm: An instance of the :class:`Algorithm`.
"""
... | # Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import os
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional
import yahp as hp
import composer
from composer.core.algorithm import Algorithm
@dataclass
c... | 81 | 130 | 435 | 14 | 66 | Landanjs/composer | composer/algorithms/algorithm_hparams.py | Python | AlgorithmHparams | AlgorithmHparams | 17 | 64 | 17 | 18 | 0cf6c5aba4c3ef2578782bd575dd2ac6f1edd2e9 | bigcode/the-stack | train |
43f80d1ac33793c78cb00af6 | train | class | class Visualizer(Callback):
def on_action_end(self, action, logs):
""" Render environment at the end of each action """
self.env.render(mode='human')
| class Visualizer(Callback):
| def on_action_end(self, action, logs):
""" Render environment at the end of each action """
self.env.render(mode='human')
| idx] for idx in sorted_indexes]).tolist()
# Overwrite already open file. We can simply seek to the beginning since the file will
# grow strictly monotonously.
with open(self.filepath, 'w') as f:
json.dump(sorted_data, f)
class Visualizer(Callback):
| 64 | 64 | 36 | 6 | 58 | campbelljc/keras-rl | rl/callbacks.py | Python | Visualizer | Visualizer | 370 | 373 | 370 | 370 | 2a6f73fdd82ec9326ac43d8dda66eb54f598e502 | bigcode/the-stack | train |
7610f0c15e91882d10548097 | train | class | class TestLogger(Callback):
""" Logger Class for Test """
def on_train_begin(self, logs):
""" Print logs at beginning of training"""
print('Testing for {} episodes ...'.format(self.params['nb_episodes']))
def on_episode_end(self, episode, logs):
""" Print logs at end of each episode... | class TestLogger(Callback):
| """ Logger Class for Test """
def on_train_begin(self, logs):
""" Print logs at beginning of training"""
print('Testing for {} episodes ...'.format(self.params['nb_episodes']))
def on_episode_end(self, episode, logs):
""" Print logs at end of each episode """
template = 'Epi... | :
if callable(getattr(callback, 'on_action_end', None)):
callback.on_action_end(action, logs=logs)
def save_data(self):
for callback in self.callbacks:
if callable(getattr(callback, 'save_data', None)):
callback.save_data()
class TestLogger(Callba... | 64 | 64 | 122 | 6 | 58 | campbelljc/keras-rl | rl/callbacks.py | Python | TestLogger | TestLogger | 108 | 122 | 108 | 108 | fb8258521eb61f2c22cf23a4f8e8a2657942ca5e | bigcode/the-stack | train |
a9ef6563ba89164a778fa16e | train | class | class CallbackList(KerasCallbackList):
def _set_env(self, env):
""" Set environment for each callback in callbackList """
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env)
def on_episode_begin(self, episode, logs... | class CallbackList(KerasCallbackList):
| def _set_env(self, env):
""" Set environment for each callback in callbackList """
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env)
def on_episode_begin(self, episode, logs={}):
""" Called at beginning o... | import Callback as KerasCallback, CallbackList as KerasCallbackList
from keras.utils.generic_utils import Progbar
class Callback(KerasCallback):
def _set_env(self, env):
self.env = env
def on_episode_begin(self, episode, logs={}):
"""Called at beginning of each episode"""
pass
d... | 197 | 197 | 657 | 8 | 188 | campbelljc/keras-rl | rl/callbacks.py | Python | CallbackList | CallbackList | 44 | 106 | 44 | 44 | 25f79e6a4414fa1e055bc2f5d4d0beba6f31ecbb | bigcode/the-stack | train |
232c8ead370974f0105d5bdc | train | class | class Callback(KerasCallback):
def _set_env(self, env):
self.env = env
def on_episode_begin(self, episode, logs={}):
"""Called at beginning of each episode"""
pass
def on_episode_end(self, episode, logs={}):
"""Called at end of each episode"""
pass
def on_step_... | class Callback(KerasCallback):
| def _set_env(self, env):
self.env = env
def on_episode_begin(self, episode, logs={}):
"""Called at beginning of each episode"""
pass
def on_episode_end(self, episode, logs={}):
"""Called at end of each episode"""
pass
def on_step_begin(self, step, logs={}):
... | import timeit
import json
from tempfile import mkdtemp
import numpy as np
from keras import __version__ as KERAS_VERSION
from keras.callbacks import Callback as KerasCallback, CallbackList as KerasCallbackList
from keras.utils.generic_utils import Progbar
class Callback(KerasCallback):
| 64 | 64 | 165 | 6 | 57 | campbelljc/keras-rl | rl/callbacks.py | Python | Callback | Callback | 15 | 41 | 15 | 15 | 1e89f6f211915c7a8c730a6cc79a722b7424be49 | bigcode/the-stack | train |
e1fad3021532074c1312b60d | train | class | class FileLogger(Callback):
def __init__(self, filepath, interval=None):
self.filepath = filepath
self.interval = interval
# Some algorithms compute multiple episodes at once since they are multi-threaded.
# We therefore use a dict that maps from episode to metrics array.
se... | class FileLogger(Callback):
| def __init__(self, filepath, interval=None):
self.filepath = filepath
self.interval = interval
# Some algorithms compute multiple episodes at once since they are multi-threaded.
# We therefore use a dict that maps from episode to metrics array.
self.metrics = {}
self... | self.info_names is None:
self.info_names = logs['info'].keys()
values = [('reward', logs['reward'])]
if KERAS_VERSION > '2.1.3':
self.progbar.update((self.step % self.interval) + 1, values=values)
else:
self.progbar.update((self.step % self.interval) + 1, val... | 186 | 186 | 621 | 6 | 179 | campbelljc/keras-rl | rl/callbacks.py | Python | FileLogger | FileLogger | 293 | 367 | 293 | 293 | 801ae6b22f80d1eb367fd30642d0a878f38ad913 | bigcode/the-stack | train |
6f77711c5caae030aef619c7 | train | class | class TrainEpisodeLogger(Callback):
def __init__(self):
# Some algorithms compute multiple episodes at once since they are multi-threaded.
# We therefore use a dictionary that is indexed by the episode to separate episodes
# from each other.
self.episode_start = {}
self.obser... | class TrainEpisodeLogger(Callback):
| def __init__(self):
# Some algorithms compute multiple episodes at once since they are multi-threaded.
# We therefore use a dictionary that is indexed by the episode to separate episodes
# from each other.
self.episode_start = {}
self.observations = {}
self.rewards = ... | in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs)
def on_action_end(self, action, logs={}):
""" Called at end of each action for each callback in callbackList"""
... | 256 | 256 | 935 | 7 | 249 | campbelljc/keras-rl | rl/callbacks.py | Python | TrainEpisodeLogger | TrainEpisodeLogger | 125 | 216 | 125 | 125 | 6bd8341715bf2c71b1d79ef9214ec35fdfb766ed | bigcode/the-stack | train |
5620e99b6fa29837e1e94d1a | train | class | class ModelIntervalCheckpoint(Callback):
def __init__(self, filepath, interval, verbose=0):
super(ModelIntervalCheckpoint, self).__init__()
self.filepath = filepath
self.interval = interval
self.verbose = verbose
self.total_steps = 0
def on_step_end(self, step, logs={}):... | class ModelIntervalCheckpoint(Callback):
| def __init__(self, filepath, interval, verbose=0):
super(ModelIntervalCheckpoint, self).__init__()
self.filepath = filepath
self.interval = interval
self.verbose = verbose
self.total_steps = 0
def on_step_end(self, step, logs={}):
""" Save weights at interval ste... | with open(self.filepath, 'w') as f:
json.dump(sorted_data, f)
class Visualizer(Callback):
def on_action_end(self, action, logs):
""" Render environment at the end of each action """
self.env.render(mode='human')
class ModelIntervalCheckpoint(Callback):
| 64 | 64 | 160 | 7 | 57 | campbelljc/keras-rl | rl/callbacks.py | Python | ModelIntervalCheckpoint | ModelIntervalCheckpoint | 376 | 394 | 376 | 376 | 8291bb8a5b3a5787e6f0167b8434b6b8c8463ecd | bigcode/the-stack | train |
5675b5cd58548cb62f17724f | train | class | class TrainIntervalLogger(Callback):
def __init__(self, interval=10000):
self.interval = interval
self.step = 0
self.num_episodes = 0
self.reset()
def reset(self):
""" Reset statistics """
self.interval_start = timeit.default_timer()
self.progbar = Progba... | class TrainIntervalLogger(Callback):
| def __init__(self, interval=10000):
self.interval = interval
self.step = 0
self.num_episodes = 0
self.reset()
def reset(self):
""" Reset statistics """
self.interval_start = timeit.default_timer()
self.progbar = Progbar(target=self.interval)
self.... | .rewards[episode]),
'action_mean': np.mean(self.actions[episode]),
'action_min': np.min(self.actions[episode]),
'action_max': np.max(self.actions[episode]),
'obs_mean': np.mean(self.observations[episode]),
'obs_min': np.min(self.observations[episode]),
... | 239 | 239 | 797 | 7 | 231 | campbelljc/keras-rl | rl/callbacks.py | Python | TrainIntervalLogger | TrainIntervalLogger | 219 | 290 | 219 | 219 | 10b198a857bbd2ac2e8e4718f9a35e821dc99d7d | bigcode/the-stack | train |
ca39b90b4649a494b89092df | train | class | class CategoricalDataEncoder(AppLogger):
encoder_cols = ['sex', 'smoker', 'region']
def __init__(self, dataset: pd.DataFrame(), train=False):
super(CategoricalDataEncoder, self).__init__()
self.cur_file_path = self.get_working_file_location()(__file__)
self.dataset = dataset
... | class CategoricalDataEncoder(AppLogger):
| encoder_cols = ['sex', 'smoker', 'region']
def __init__(self, dataset: pd.DataFrame(), train=False):
super(CategoricalDataEncoder, self).__init__()
self.cur_file_path = self.get_working_file_location()(__file__)
self.dataset = dataset
self.train = train
def one_hot_enco... | from src.config.logger import AppLogger
from src.helpers.file_handler import FileHandler
import pandas as pd
import category_encoders as ce
class CategoricalDataEncoder(AppLogger):
| 37 | 68 | 227 | 8 | 28 | HarishSinghoo7/Insurance-Premium-Prediction | src/data_preprocessing/categorical_data_encoding.py | Python | CategoricalDataEncoder | CategoricalDataEncoder | 8 | 31 | 8 | 9 | 35691edb17c837ede3d8c7f106208357128294c2 | bigcode/the-stack | train |
22f94457ee203d80dcae8d0d | train | class | class CompositionFunctionApproximatorError(Exception):
def __init__(self, error_value):
self.error_value = error_value
| class CompositionFunctionApproximatorError(Exception):
| def __init__(self, error_value):
self.error_value = error_value
| COMMENT
.. _CompositionFunctionApproximator_Class_Reference:
Class Reference
---------------
"""
from psyneulink.core.compositions.composition import Composition
from psyneulink.core.globals.context import Context
__all__ = ['CompositionFunctionApproximator']
class CompositionFunctionApproximatorError(Exception):... | 64 | 64 | 27 | 9 | 55 | AlirezaFarnia/PsyNeuLink | psyneulink/core/compositions/compositionfunctionapproximator.py | Python | CompositionFunctionApproximatorError | CompositionFunctionApproximatorError | 61 | 63 | 61 | 61 | 5c12643c87d70d22bd9b922a23af18cffbfcb98b | bigcode/the-stack | train |
3a72576ee62a8850f438befc | train | class | class CompositionFunctionApproximator(Composition):
"""Subclass of `Composition` that implements a FunctionApproximator as the `agent_rep
<OptimizationControlmechanism.agent>` of an `OptimizationControlmechanism`.
Parameterizes `its function <CompositionFunctionApproximator.function>` to predict a `net_out... | class CompositionFunctionApproximator(Composition):
| """Subclass of `Composition` that implements a FunctionApproximator as the `agent_rep
<OptimizationControlmechanism.agent>` of an `OptimizationControlmechanism`.
Parameterizes `its function <CompositionFunctionApproximator.function>` to predict a `net_outcome
<Controlmechanism.net_outcome>` for a set o... | and
`num_estimates <OptimizationControlMechanism.num_estimates>`
COMMENT:
.. note::
The CompositionFunctionApproximator's `adapt <CompositionFunctionApproximator.adapt>` method is provided the
`feature_values <OptimizationControlMechanism.feature_values>` and `net_outcome <ControlMechanism.net_outcome>`
from th... | 231 | 231 | 771 | 9 | 221 | AlirezaFarnia/PsyNeuLink | psyneulink/core/compositions/compositionfunctionapproximator.py | Python | CompositionFunctionApproximator | CompositionFunctionApproximator | 66 | 131 | 66 | 66 | 0904afdc7fcf0db586dd4d25b0c57ae409d579f1 | bigcode/the-stack | train |
d52e02d60209204643e996b7 | train | class | class QueryStringExtended(NamedTuple):
labels_expected: List[str]
prequeries: List[str]
sql: str
| class QueryStringExtended(NamedTuple):
| labels_expected: List[str]
prequeries: List[str]
sql: str
| ource
config = app.config
metadata = Model.metadata # pylint: disable=no-member
class SqlaQuery(NamedTuple):
extra_cache_keys: List[Any]
labels_expected: List[str]
prequeries: List[str]
sqla_query: Select
class QueryStringExtended(NamedTuple):
| 64 | 64 | 27 | 8 | 55 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | QueryStringExtended | QueryStringExtended | 73 | 76 | 73 | 73 | 00c678051d979ceff105fe3e0651262f0963ce1b | bigcode/the-stack | train |
c3b078db4649d1be332cb469 | train | class | class AnnotationDatasource(BaseDatasource):
""" Dummy object so we can query annotations using 'Viz' objects just like
regular datasources.
"""
cache_timeout = 0
def query(self, query_obj: Dict) -> QueryResult:
df = None
error_message = None
qry = db.session.query(Annot... | class AnnotationDatasource(BaseDatasource):
| """ Dummy object so we can query annotations using 'Viz' objects just like
regular datasources.
"""
cache_timeout = 0
def query(self, query_obj: Dict) -> QueryResult:
df = None
error_message = None
qry = db.session.query(Annotation)
qry = qry.filter(Annotation.l... | = Model.metadata # pylint: disable=no-member
class SqlaQuery(NamedTuple):
extra_cache_keys: List[Any]
labels_expected: List[str]
prequeries: List[str]
sqla_query: Select
class QueryStringExtended(NamedTuple):
labels_expected: List[str]
prequeries: List[str]
sql: str
class AnnotationDat... | 81 | 81 | 270 | 6 | 74 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | AnnotationDatasource | AnnotationDatasource | 79 | 110 | 79 | 79 | 9c07b9af065eed4ba8298b0128eb5aec11e73c03 | bigcode/the-stack | train |
ae38d5f8781724aed458fa0a | train | class | class SqlaTable(Model, BaseDatasource):
"""An ORM object for SqlAlchemy table references"""
type = "table"
query_language = "sql"
metric_class = SqlMetric
column_class = TableColumn
owner_class = security_manager.user_model
__tablename__ = "tables"
__table_args__ = (UniqueConstraint("... | class SqlaTable(Model, BaseDatasource):
| """An ORM object for SqlAlchemy table references"""
type = "table"
query_language = "sql"
metric_class = SqlMetric
column_class = TableColumn
owner_class = security_manager.user_model
__tablename__ = "tables"
__table_args__ = (UniqueConstraint("database_id", "table_name"),)
table_... | or self.metric_name
sqla_col = literal_column(self.expression)
return self.table.make_sqla_column_compatible(sqla_col, label)
@property
def perm(self) -> Optional[str]:
return (
("{parent_name}.[{obj.metric_name}](id:{obj.id})").format(
obj=self, parent_name... | 256 | 256 | 6,511 | 9 | 247 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | SqlaTable | SqlaTable | 309 | 1,133 | 309 | 310 | f2f4c8b965e453cf3e411761e77a43d0105166b6 | bigcode/the-stack | train |
10877900165a2976c96d3692 | train | class | class SqlMetric(Model, BaseMetric):
"""ORM object for metrics, each table can have multiple metrics"""
__tablename__ = "sql_metrics"
__table_args__ = (UniqueConstraint("table_id", "metric_name"),)
table_id = Column(Integer, ForeignKey("tables.id"))
table = relationship(
"SqlaTable",
... | class SqlMetric(Model, BaseMetric):
| """ORM object for metrics, each table can have multiple metrics"""
__tablename__ = "sql_metrics"
__table_args__ = (UniqueConstraint("table_id", "metric_name"),)
table_id = Column(Integer, ForeignKey("tables.id"))
table = relationship(
"SqlaTable",
backref=backref("metrics", cascade=... | ":
return str(seconds_since_epoch)
elif tf == "epoch_ms":
return str(seconds_since_epoch * 1000)
return "'{}'".format(dttm.strftime(tf))
else:
s = self.table.database.db_engine_spec.convert_dttm(self.type or "", dttm)
# TODO(john-b... | 119 | 120 | 402 | 8 | 111 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | SqlMetric | SqlMetric | 238 | 297 | 238 | 239 | a5b340bd3542fd29f728dcfe43bbe74a75aa4261 | bigcode/the-stack | train |
33889a8ff290395863de1cc1 | train | class | class SqlaQuery(NamedTuple):
extra_cache_keys: List[Any]
labels_expected: List[str]
prequeries: List[str]
sqla_query: Select
| class SqlaQuery(NamedTuple):
| extra_cache_keys: List[Any]
labels_expected: List[str]
prequeries: List[str]
sqla_query: Select
|
from superset.models.annotations import Annotation
from superset.models.core import Database
from superset.models.helpers import QueryResult
from superset.utils import core as utils, import_datasource
config = app.config
metadata = Model.metadata # pylint: disable=no-member
class SqlaQuery(NamedTuple):
| 64 | 64 | 37 | 8 | 55 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | SqlaQuery | SqlaQuery | 66 | 70 | 66 | 66 | 77956a4a2d88286e5a43dc6cccd26eb0ec42d4c4 | bigcode/the-stack | train |
828fe278badce74784ec9a77 | train | class | class TableColumn(Model, BaseColumn):
"""ORM object for table columns, each table can have multiple columns"""
__tablename__ = "table_columns"
__table_args__ = (UniqueConstraint("table_id", "column_name"),)
table_id = Column(Integer, ForeignKey("tables.id"))
table = relationship(
"SqlaTabl... | class TableColumn(Model, BaseColumn):
| """ORM object for table columns, each table can have multiple columns"""
__tablename__ = "table_columns"
__table_args__ = (UniqueConstraint("table_id", "column_name"),)
table_id = Column(Integer, ForeignKey("tables.id"))
table = relationship(
"SqlaTable",
backref=backref("columns", ... |
regular datasources.
"""
cache_timeout = 0
def query(self, query_obj: Dict) -> QueryResult:
df = None
error_message = None
qry = db.session.query(Annotation)
qry = qry.filter(Annotation.layer_id == query_obj["filter"][0]["val"])
if query_obj["from_dttm"]:
... | 256 | 256 | 994 | 8 | 248 | myzcid/incubator-superset | superset/connectors/sqla/models.py | Python | TableColumn | TableColumn | 113 | 235 | 113 | 114 | e9681d35697d5d3045e5ab5ed8b203a523f16096 | bigcode/the-stack | train |
ffffa6ee9dba418132ba0e0f | train | class | class ComplexQuadrilateralAllOf(
DictSchema
):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
class quadrilateralType(
_SchemaEnumMaker(
enum_value_to_name={
"Compl... | class ComplexQuadrilateralAllOf(
DictSchema
):
| """NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
class quadrilateralType(
_SchemaEnumMaker(
enum_value_to_name={
"ComplexQuadrilateral": "COMPLEXQUADRILATERAL",
... | ,
Int64Base,
Float32Base,
Float64Base,
NumberBase,
DateBase,
DateTimeBase,
BoolBase,
BinaryBase,
Schema,
_SchemaValidator,
_SchemaTypeChecker,
_SchemaEnumMaker
)
class ComplexQuadrilateralAllOf(
DictSchema
):
| 70 | 70 | 235 | 12 | 58 | JigarJoshi/openapi-generator | samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral_all_of.py | Python | ComplexQuadrilateralAllOf | ComplexQuadrilateralAllOf | 66 | 104 | 66 | 68 | d22ebbcdfa8d36e10121adc2fd453251c9a68220 | bigcode/the-stack | train |
7b3d7212fce94998533e73b5 | train | class | class NistCbcVectors(NistBlockChainingVectors):
aes_mode = AES.MODE_CBC
des_mode = DES.MODE_CBC
des3_mode = DES3.MODE_CBC
| class NistCbcVectors(NistBlockChainingVectors):
| aes_mode = AES.MODE_CBC
des_mode = DES.MODE_CBC
des3_mode = DES3.MODE_CBC
| CRYPT]":
self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
elif direction == "[DECRYPT]":
self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
else:
assert False
class NistCbcVectors(NistBlockChainingVectors):
| 64 | 64 | 42 | 13 | 50 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | NistCbcVectors | NistCbcVectors | 268 | 271 | 268 | 268 | e577852a53cfc29770928f7c27431b6fe5105b52 | bigcode/the-stack | train |
36b445de2bb01677768bf7ce | train | class | class CbcTests(BlockChainingTests):
aes_mode = AES.MODE_CBC
des3_mode = DES3.MODE_CBC
| class CbcTests(BlockChainingTests):
| aes_mode = AES.MODE_CBC
des3_mode = DES3.MODE_CBC
| self.assertRaises(TypeError, cipher.encrypt, 'test1234567890-*')
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
self.assertRaises(TypeError, cipher.decrypt, 'test1234567890-*')
class CbcTests(BlockChainingTests):
| 64 | 64 | 29 | 9 | 55 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | CbcTests | CbcTests | 169 | 171 | 169 | 169 | 8cb5807bf7142e110c57f5828b8807930bc960de | bigcode/the-stack | train |
32cd7909ddce211fe78cef24 | train | function | def get_tests(config={}):
tests = []
tests += list_test_cases(CbcTests)
tests += list_test_cases(NistCbcVectors)
tests += list_test_cases(SP800TestVectors)
return tests
| def get_tests(config={}):
| tests = []
tests += list_test_cases(CbcTests)
tests += list_test_cases(NistCbcVectors)
tests += list_test_cases(SP800TestVectors)
return tests
| ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def get_tests(config={}):
| 64 | 64 | 48 | 6 | 58 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | get_tests | get_tests | 400 | 405 | 400 | 400 | f16c860fde63379804bd5413f0240e4648167a07 | bigcode/the-stack | train |
2387f673db5f0722f5b00b3f | train | class | class SP800TestVectors(unittest.TestCase):
"""Class exercising the CBC test vectors found in Section F.2
of NIST SP 800-3A"""
def test_aes_128(self):
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f'
plaintext = '6bc1bee22e409f... | class SP800TestVectors(unittest.TestCase):
| """Class exercising the CBC test vectors found in Section F.2
of NIST SP 800-3A"""
def test_aes_128(self):
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f'
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
... | ):
self._do_kat_aes_test(file_name)
setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
for file_name in nist_aes_mct_files:
def new_func(self, file_name=file_name):
self._do_mct_aes_test(file_name)
setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
del file_name, new_func
n... | 256 | 256 | 1,073 | 9 | 246 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | SP800TestVectors | SP800TestVectors | 329 | 397 | 329 | 329 | 61e250fc8450887d3231ab4cff853fcfa565c37e | bigcode/the-stack | train |
c93a0e4cd795f95b6903e815 | train | class | class BlockChainingTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
key_192 = get_tag_random("key_192", 24)
iv_128 = get_tag_random("iv_128", 16)
iv_64 = get_tag_random("iv_64", 8)
data_128 = get_tag_random("data_128", 16)
def test_loopback_128(self):
cipher = AES.new(... | class BlockChainingTests(unittest.TestCase):
| key_128 = get_tag_random("key_128", 16)
key_192 = get_tag_random("key_192", 24)
iv_128 = get_tag_random("iv_128", 16)
iv_64 = get_tag_random("iv_64", 8)
data_128 = get_tag_random("data_128", 16)
def test_loopback_128(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
... | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIA... | 256 | 256 | 1,379 | 9 | 247 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | BlockChainingTests | BlockChainingTests | 42 | 166 | 42 | 43 | 3c2608f7ae50d07b99324b985d1bbf691551294f | bigcode/the-stack | train |
1dfe0c3bd498ceac24df7447 | train | function | def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
| def get_tag_random(tag, length):
| return SHAKE128.new(data=tobytes(tag)).read(length)
| from Cryptodome.SelfTest.st_common import list_test_cases
from Cryptodome.Util.py3compat import tobytes, b, unhexlify
from Cryptodome.Cipher import AES, DES3, DES
from Cryptodome.Hash import SHAKE128
def get_tag_random(tag, length):
| 64 | 64 | 23 | 8 | 55 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | get_tag_random | get_tag_random | 39 | 40 | 39 | 39 | 20852fe334a8f00b6bccadbe70e31f91e7e5881a | bigcode/the-stack | train |
9ff1b5bbf34716ccb1f886a9 | train | class | class NistBlockChainingVectors(unittest.TestCase):
def _do_kat_aes_test(self, file_name):
test_vectors = load_tests(("Cryptodome", "SelfTest", "Cipher", "test_vectors", "AES"),
file_name,
"AES KAT",
{ "cou... | class NistBlockChainingVectors(unittest.TestCase):
| def _do_kat_aes_test(self, file_name):
test_vectors = load_tests(("Cryptodome", "SelfTest", "Cipher", "test_vectors", "AES"),
file_name,
"AES KAT",
{ "count" : lambda x: int(x) } )
assert(test_vecto... | Equal(result, b(""))
def test_either_encrypt_or_decrypt(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
cipher.encrypt(b(""))
self.assertRaises(TypeError, cipher.decrypt, b(""))
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
cipher.decrypt(b(""... | 219 | 219 | 732 | 11 | 207 | Kronos3/pyexec | Lib/site-packages/Cryptodome/SelfTest/Cipher/test_CBC.py | Python | NistBlockChainingVectors | NistBlockChainingVectors | 174 | 265 | 174 | 175 | 42f7498cf0c26af4ff0e3f4bb838daadaec48055 | bigcode/the-stack | train |
2446b1062474221457bec5f1 | train | class | class BashJobController(JobController):
def cleanup_job(self, job_handle: JobHandle, job_runtime_env: JobRuntimeEnv):
pass
def submit_one_process(self, processor: BashProcessor, env, working_dir):
def pre_exec():
# Restore default signal disposition and invoke setsid
f... | class BashJobController(JobController):
| def cleanup_job(self, job_handle: JobHandle, job_runtime_env: JobRuntimeEnv):
pass
def submit_one_process(self, processor: BashProcessor, env, working_dir):
def pre_exec():
# Restore default signal disposition and invoke setsid
for sig in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'... | BashJobGenerator(JobGenerator):
@staticmethod
def _validate_sub_graph(sub_graph: AISubGraph):
"""
Check that all the processor in sub_graph is BashProcessor
"""
for node_name, ai_node in sub_graph.nodes.items():
processor = ai_node.get_processor()
if not ... | 256 | 256 | 944 | 7 | 248 | SteNicholas/ai-flow | ai_flow_plugins/job_plugins/bash/bash_job_plugin.py | Python | BashJobController | BashJobController | 91 | 191 | 91 | 92 | 62272e5f37c9e53fb8b86d18af4e7c9d05da15aa | bigcode/the-stack | train |
20f184e12a4c382016f530e8 | train | class | class BashJobGenerator(JobGenerator):
@staticmethod
def _validate_sub_graph(sub_graph: AISubGraph):
"""
Check that all the processor in sub_graph is BashProcessor
"""
for node_name, ai_node in sub_graph.nodes.items():
processor = ai_node.get_processor()
if... | class BashJobGenerator(JobGenerator):
@staticmethod
| def _validate_sub_graph(sub_graph: AISubGraph):
"""
Check that all the processor in sub_graph is BashProcessor
"""
for node_name, ai_node in sub_graph.nodes.items():
processor = ai_node.get_processor()
if not isinstance(processor, BashProcessor):
... | the bash child process.
key: node_id
value: Popen object
"""
self.sub_process = {}
"""It represents the serialized file of the processor."""
self.processors_file = None
"""It saves the result dict of the bash child process."""
self.lines = {}
class BashJo... | 74 | 75 | 250 | 11 | 63 | SteNicholas/ai-flow | ai_flow_plugins/job_plugins/bash/bash_job_plugin.py | Python | BashJobGenerator | BashJobGenerator | 65 | 88 | 65 | 66 | 0c59bab92dd394491981c4081f4995ba4aa81fd0 | bigcode/the-stack | train |
edf1c76517bfb17e396a5257 | train | class | class BashJobHandle(JobHandle):
def __init__(self, job: Job,
job_execution: JobExecutionInfo):
super().__init__(job=job, job_execution=job_execution)
"""
It saves the Popen object dictionary of the bash child process.
key: node_id
value: Popen object
... | class BashJobHandle(JobHandle):
| def __init__(self, job: Job,
job_execution: JobExecutionInfo):
super().__init__(job=job, job_execution=job_execution)
"""
It saves the Popen object dictionary of the bash child process.
key: node_id
value: Popen object
"""
self.sub_process = {... | field stores the serialized file of the BashProcessor
(ai_flow_plugins.job_plugins.bash.bash_processor.BashProcessor).
"""
def __init__(self, job_config: JobConfig):
super().__init__(job_config)
self.processors_file = None
class BashJobHandle(JobHandle):
| 64 | 64 | 115 | 7 | 56 | SteNicholas/ai-flow | ai_flow_plugins/job_plugins/bash/bash_job_plugin.py | Python | BashJobHandle | BashJobHandle | 48 | 62 | 48 | 49 | 97ba46ff1829deba2a6fdacbcb1b2120e78520e3 | bigcode/the-stack | train |
4a1b380d95fd4287b479d3de | train | class | class BashJob(Job):
"""
BashJob is the description of bash type job.
The processors_file field stores the serialized file of the BashProcessor
(ai_flow_plugins.job_plugins.bash.bash_processor.BashProcessor).
"""
def __init__(self, job_config: JobConfig):
super().__init__(job_config)
... | class BashJob(Job):
| """
BashJob is the description of bash type job.
The processors_file field stores the serialized file of the BashProcessor
(ai_flow_plugins.job_plugins.bash.bash_processor.BashProcessor).
"""
def __init__(self, job_config: JobConfig):
super().__init__(job_config)
self.processors_... | ai_flow.plugin_interface.scheduler_interface import JobExecutionInfo
from ai_flow.workflow.job import Job
from ai_flow.workflow.status import Status
from ai_flow_plugins.job_plugins.bash.bash_job_config import BashJobConfig
from ai_flow_plugins.job_plugins.bash.bash_processor import BashProcessor
class BashJob(Job):
| 64 | 64 | 79 | 5 | 58 | SteNicholas/ai-flow | ai_flow_plugins/job_plugins/bash/bash_job_plugin.py | Python | BashJob | BashJob | 37 | 45 | 37 | 37 | ba05ac10f50c1fd850e1a5f8c26357d35f0a9dcd | bigcode/the-stack | train |
bb5d8bfbe07225866c35b832 | train | class | class BashJobPluginFactory(JobPluginFactory):
def __init__(self) -> None:
super().__init__()
self._job_generator = BashJobGenerator()
self._job_controller = BashJobController()
def get_job_generator(self) -> JobGenerator:
return self._job_generator
def get_job_controller(se... | class BashJobPluginFactory(JobPluginFactory):
| def __init__(self) -> None:
super().__init__()
self._job_generator = BashJobGenerator()
self._job_controller = BashJobController()
def get_job_generator(self) -> JobGenerator:
return self._job_generator
def get_job_controller(self) -> JobController:
return self._job... | is None:
try:
os.killpg(os.getpgid(sub_process.pid), signal.SIGTERM)
except Exception as e:
self.log.error('Kill process {} failed! error {}'.format(sub_process.pid, str(e)))
time.sleep(1)
class BashJobPlugi... | 64 | 64 | 94 | 9 | 55 | SteNicholas/ai-flow | ai_flow_plugins/job_plugins/bash/bash_job_plugin.py | Python | BashJobPluginFactory | BashJobPluginFactory | 194 | 207 | 194 | 194 | b062593b21ecbb482d61c08e002ae92f5263adf1 | bigcode/the-stack | train |
95cb1ccf9dd9a4feb73deaa7 | train | class | class NoversionBundle(BundlePackage):
"""
Simple bundle package with no version and one dependency, which
should be rejected for lack of a version.
"""
homepage = "http://www.example.com"
depends_on('dependency-install')
| class NoversionBundle(BundlePackage):
| """
Simple bundle package with no version and one dependency, which
should be rejected for lack of a version.
"""
homepage = "http://www.example.com"
depends_on('dependency-install')
| # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class NoversionBundle(BundlePackage):
| 61 | 64 | 51 | 7 | 54 | RemoteConnectionManager/spack | var/spack/repos/builtin.mock/packages/noversion-bundle/package.py | Python | NoversionBundle | NoversionBundle | 10 | 18 | 10 | 10 | 9b5eee60c3bbcfa51e84396c385df5ac6d66e9ae | bigcode/the-stack | train |
9937157fac4fd2838633b3a2 | train | function | def parse(s):
return loads(server.parse(s))
| def parse(s):
| return loads(server.parse(s))
| from simplejson import loads
import socket
server = jsonrpclib.Server("http://localhost:8080")
pp = pprint.PrettyPrinter(indent=4)
def check():
try:
server.parse('Hello World!')
except socket.error:
return False
else:
return True
def parse(s):
| 64 | 64 | 10 | 4 | 59 | NathanZabriskie/microfiction | stanford.py | Python | parse | parse | 17 | 18 | 17 | 17 | b2fde603ebf1a3ec2401e5f59e988c978fd078c9 | bigcode/the-stack | train |
9f68a41b448d1a9fcd20e60a | train | function | def pretty_parse(s):
res = parse(s)
pp.pprint(res)
| def pretty_parse(s):
| res = parse(s)
pp.pprint(res)
| = parse(s)
res = []
for w in parsed['sentences'][0]['words']:
pos = w[1]['PartOfSpeech']
if pos in ['NN','NNS','NNP','NNPS','VBG']:
res.append(w[0])
return res
def pretty_parse(s):
| 64 | 64 | 15 | 5 | 58 | NathanZabriskie/microfiction | stanford.py | Python | pretty_parse | pretty_parse | 31 | 33 | 31 | 31 | 6575fbaeaaba826723106874f1a12182fe9149ad | bigcode/the-stack | train |
b3ded68dd0250131f5a7272f | train | function | def get_nouns(s, plural=True):
parsed = parse(s)
res = []
for w in parsed['sentences'][0]['words']:
pos = w[1]['PartOfSpeech']
if pos in ['NN','NNS','NNP','NNPS','VBG']:
res.append(w[0])
return res
| def get_nouns(s, plural=True):
| parsed = parse(s)
res = []
for w in parsed['sentences'][0]['words']:
pos = w[1]['PartOfSpeech']
if pos in ['NN','NNS','NNP','NNPS','VBG']:
res.append(w[0])
return res
| .Server("http://localhost:8080")
pp = pprint.PrettyPrinter(indent=4)
def check():
try:
server.parse('Hello World!')
except socket.error:
return False
else:
return True
def parse(s):
return loads(server.parse(s))
def get_nouns(s, plural=True):
| 64 | 64 | 70 | 9 | 55 | NathanZabriskie/microfiction | stanford.py | Python | get_nouns | get_nouns | 20 | 29 | 20 | 20 | b2f318c586a7f345f0fe7d10b34d65bbd963a3be | bigcode/the-stack | train |
8458d2fbd4ecfe9a3cc06bb8 | train | function | def check():
try:
server.parse('Hello World!')
except socket.error:
return False
else:
return True
| def check():
| try:
server.parse('Hello World!')
except socket.error:
return False
else:
return True
| import pprint
import jsonrpclib
from simplejson import loads
import socket
server = jsonrpclib.Server("http://localhost:8080")
pp = pprint.PrettyPrinter(indent=4)
def check():
| 46 | 64 | 26 | 3 | 43 | NathanZabriskie/microfiction | stanford.py | Python | check | check | 9 | 15 | 9 | 9 | 9a91e0aee56f8ff6061803d0678c9b3ba3699f3b | bigcode/the-stack | train |
d7d69c00d59335c5a0845fe6 | train | class | class Opportunity2Quotation(models.TransientModel):
_name = 'crm.quotation.partner'
_description = 'Create new or use existing Customer on new Quotation'
_inherit = 'crm.partner.binding'
@api.model
def default_get(self, fields):
result = super(Opportunity2Quotation, self).default_get(field... | class Opportunity2Quotation(models.TransientModel):
| _name = 'crm.quotation.partner'
_description = 'Create new or use existing Customer on new Quotation'
_inherit = 'crm.partner.binding'
@api.model
def default_get(self, fields):
result = super(Opportunity2Quotation, self).default_get(fields)
active_model = self._context.get('active_... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class Opportunity2Quotation(models.TransientModel):
| 52 | 99 | 330 | 9 | 42 | VaibhavBhujade/Blockchain-ERP-interoperability | odoo-13.0/addons/sale_crm/wizard/crm_opportunity_to_quotation.py | Python | Opportunity2Quotation | Opportunity2Quotation | 8 | 48 | 8 | 9 | dd0741cb60d576626dfe9771b10d6e453870d829 | bigcode/the-stack | train |
5fa3056c3551c21e9c1e415f | train | class | class WeightDrop(torch.nn.Module):
def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDrop, self).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
self.variational = variational
self._setup()
def w... | class WeightDrop(torch.nn.Module):
| def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDrop, self).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
self.variational = variational
self._setup()
def widget_demagnetizer_y2k_edition(*args... | import torch
from torch.nn import Parameter
from functools import wraps
class WeightDrop(torch.nn.Module):
| 21 | 124 | 414 | 7 | 13 | Adversarial-dropout-rnn/adversarial_dropout_lm | weight_drop.py | Python | WeightDrop | WeightDrop | 5 | 46 | 5 | 5 | 1b8c11b6eed23467e14a9e2ea37c1e7b5585f076 | bigcode/the-stack | train |
fe8419c5c545c6aeb87b055f | train | class | class WeightDropMask(torch.nn.Module):
def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDropMask, self).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
self.variational = variational
self._setup()
... | class WeightDropMask(torch.nn.Module):
| def __init__(self, module, weights, dropout=0, variational=False):
super(WeightDropMask, self).__init__()
self.module = module
self.weights = weights
self.dropout = dropout
self.variational = variational
self._setup()
def widget_demagnetizer_y2k_edition(*... | w = None
if self.variational:
mask = torch.autograd.Variable(torch.ones(raw_w.size(0), 1))
if raw_w.is_cuda: mask = mask.cuda()
mask = torch.nn.functional.dropout(mask, p=self.dropout, training=True)
w = mask.expand_as(raw_w) *... | 132 | 132 | 443 | 8 | 124 | Adversarial-dropout-rnn/adversarial_dropout_lm | weight_drop.py | Python | WeightDropMask | WeightDropMask | 48 | 91 | 48 | 48 | b356009dc755c9e4002f1960feb1163fecd85bb0 | bigcode/the-stack | train |
773818d9b23e8d4db89cf569 | train | function | def plot_lines_touched_both(application: str, data, out_dir):
bothdata = data[(data['count'] > 2)].copy()
bothdata['A64FX'] = pd.to_numeric(np.ceil(data.delta * 8 / 256), downcast='integer') + 1
bothdata['TX2'] = pd.to_numeric(np.ceil(data.delta * 8 / 64), downcast='integer') + 1
for col in ['A64FX','TX2']:
... | def plot_lines_touched_both(application: str, data, out_dir):
| bothdata = data[(data['count'] > 2)].copy()
bothdata['A64FX'] = pd.to_numeric(np.ceil(data.delta * 8 / 256), downcast='integer') + 1
bothdata['TX2'] = pd.to_numeric(np.ceil(data.delta * 8 / 64), downcast='integer') + 1
for col in ['A64FX','TX2']:
bothdata[col].clip(upper=data.components, inplace=True)
... | cut=0, palette='colorblind', orient='h', scale='count', inner='quartile', bw=.25)
plt.xticks(range(1,max(graphdata.lines)+1))
ax.set_xlabel('cache lines touched')
ax.set_ylabel('svewidth (bits)')
fig.savefig(out_dir / f'{application}-non-countiguous-{line_size}.pdf', bbox_inches='tight')
def plot_lines_to... | 102 | 102 | 343 | 16 | 86 | UoB-HPC/cache-effects-reproducibility | scripts/non-contiguous.py | Python | plot_lines_touched_both | plot_lines_touched_both | 42 | 63 | 42 | 42 | 948da5380cfdaecfac9a4416e03e4cdb16e6f251 | bigcode/the-stack | train |
c81d8614de710b6a98756bff | train | function | def plot_lines_touched_single(application: str, data, out_dir, line_size: int):
data['lines'] = pd.to_numeric(np.ceil(data.delta * 8 / line_size), downcast='integer') + 1
data.lines.clip(upper=data.components, inplace=True)
data.lines.clip(upper=data.svewidth/8, inplace=True)
fig, ax = plt.subplots()
graphd... | def plot_lines_touched_single(application: str, data, out_dir, line_size: int):
| data['lines'] = pd.to_numeric(np.ceil(data.delta * 8 / line_size), downcast='integer') + 1
data.lines.clip(upper=data.components, inplace=True)
data.lines.clip(upper=data.svewidth/8, inplace=True)
fig, ax = plt.subplots()
graphdata = data[(data['count'] > 2)]
sea.violinplot(x='lines', y='svewidth', data=g... | pd.read_csv(f'../data/{application}/bundles-{w}.csv')
next_data['svewidth'] = w
data = data.append(next_data, ignore_index=True)
return data
def plot_lines_touched_single(application: str, data, out_dir, line_size: int):
| 64 | 64 | 208 | 20 | 43 | UoB-HPC/cache-effects-reproducibility | scripts/non-contiguous.py | Python | plot_lines_touched_single | plot_lines_touched_single | 25 | 40 | 25 | 25 | d5c5b191fe8fb375f01a95c12d01f025001ceb71 | bigcode/the-stack | train |
531217c80364468da31cd207 | train | function | def read_data(application: str):
data = pd.DataFrame()
for w in [128,256,512,1024,2048]:
next_data = pd.read_csv(f'../data/{application}/bundles-{w}.csv')
next_data['svewidth'] = w
data = data.append(next_data, ignore_index=True)
return data
| def read_data(application: str):
| data = pd.DataFrame()
for w in [128,256,512,1024,2048]:
next_data = pd.read_csv(f'../data/{application}/bundles-{w}.csv')
next_data['svewidth'] = w
data = data.append(next_data, ignore_index=True)
return data
| /env python3
import os
import sys
from pathlib import Path
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas as pd
import seaborn as sea
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def read_data(application: str):
| 64 | 64 | 79 | 7 | 56 | UoB-HPC/cache-effects-reproducibility | scripts/non-contiguous.py | Python | read_data | read_data | 16 | 23 | 16 | 16 | 77d3ccb0f44ff4ddd04d5508cc29ef94ea6ef21f | bigcode/the-stack | train |
ca0ef5b61eb25fb397604608 | train | function | def main():
db = Database()
for subst in db.ask(append(L1, L2, [1, 2, 3, 4, 5])):
print(subst[L1], "+", subst[L2])
| def main():
| db = Database()
for subst in db.ask(append(L1, L2, [1, 2, 3, 4, 5])):
print(subst[L1], "+", subst[L2])
| __ = '2014-09-27'
__author__ = 'Mick Krippendorf <m.krippendorf@freenet.de>'
__license__ = 'MIT'
from hornet import Database, append
from hornet.symbols import (
L1, L2
)
def main():
| 64 | 64 | 50 | 3 | 61 | pillmuncher/hornet | src/examples/app.py | Python | main | main | 19 | 24 | 19 | 20 | b83b5896d3c8591601e6c6ac664ce61540aaa318 | bigcode/the-stack | train |
46da9b344e164329269b1571 | train | function | def create_direct_channel() -> Tuple[TxChannel, RxChannel]:
class Channel(TxChannel):
def __init__(self, observable: _RxChannel):
self._observable = observable
async def put(self, msg: Any):
await self._observable.notify(msg)
def put_nowait(self, msg: Any):
... | def create_direct_channel() -> Tuple[TxChannel, RxChannel]:
| class Channel(TxChannel):
def __init__(self, observable: _RxChannel):
self._observable = observable
async def put(self, msg: Any):
await self._observable.notify(msg)
def put_nowait(self, msg: Any):
# TODO: What if observable has async handlers?
... | for handler in self._sync_handlers:
handler(msg)
async def notify(self, msg: Any):
self.notify_sync(msg)
if self.has_async_handlers:
await wait([handler(msg) for handler in self._async_handlers])
def create_direct_channel() -> Tuple[TxChannel, RxChannel]:
| 64 | 64 | 107 | 14 | 50 | andkononykhin/plenum | plenum/common/channel.py | Python | create_direct_channel | create_direct_channel | 54 | 68 | 54 | 54 | ffd08d6d19be24b1aef5e14e54fcf9c26c0f00aa | bigcode/the-stack | train |
179b089989176e02e2cd6eaa | train | class | class QueuedChannelService:
class Channel(TxChannel):
def __init__(self, queue: deque):
self._queue = queue
async def put(self, msg: Any):
self._queue.append(msg)
def put_nowait(self, msg: Any):
self._queue.append(msg)
def __init__(self):
se... | class QueuedChannelService:
| class Channel(TxChannel):
def __init__(self, queue: deque):
self._queue = queue
async def put(self, msg: Any):
self._queue.append(msg)
def put_nowait(self, msg: Any):
self._queue.append(msg)
def __init__(self):
self._queue = deque()
... | Channel):
self._observable = observable
async def put(self, msg: Any):
await self._observable.notify(msg)
def put_nowait(self, msg: Any):
# TODO: What if observable has async handlers?
self._observable.notify_sync(msg)
return True
router... | 81 | 81 | 272 | 6 | 74 | andkononykhin/plenum | plenum/common/channel.py | Python | QueuedChannelService | QueuedChannelService | 71 | 107 | 71 | 71 | 6c0ff7b4cb686313f970f69009c04e6e37398bf2 | bigcode/the-stack | train |
caffd19081c0333f10494a8f | train | class | class _RxChannel(RxChannel):
def __init__(self):
self._sync_handlers = []
self._async_handlers = []
def subscribe(self, handler: Callable):
if iscoroutinefunction(handler):
self._async_handlers.append(handler)
else:
self._sync_handlers.append(handler)
... | class _RxChannel(RxChannel):
| def __init__(self):
self._sync_handlers = []
self._async_handlers = []
def subscribe(self, handler: Callable):
if iscoroutinefunction(handler):
self._async_handlers.append(handler)
else:
self._sync_handlers.append(handler)
@property
def has_async... | def put(self, msg: Any):
pass
@abstractmethod
def put_nowait(self, msg: Any) -> bool:
pass
class RxChannel(ABC):
@abstractmethod
def subscribe(self, handler: Callable):
pass
class _RxChannel(RxChannel):
| 64 | 64 | 149 | 8 | 55 | andkononykhin/plenum | plenum/common/channel.py | Python | _RxChannel | _RxChannel | 29 | 51 | 29 | 29 | cd3656cedd84f25e18d6206392bde1350a7d4451 | bigcode/the-stack | train |
cd7687e86aff14e8d1bdd4d0 | train | class | class AsyncRouter(RouterBase):
def __init__(self, input: RxChannel, strict: bool = True):
RouterBase.__init__(self, strict)
input.subscribe(self._process)
async def _process(self, msg: Any):
result = self._process_sync(msg)
return await result if isawaitable(result) else result
| class AsyncRouter(RouterBase):
| def __init__(self, input: RxChannel, strict: bool = True):
RouterBase.__init__(self, strict)
input.subscribe(self._process)
async def _process(self, msg: Any):
result = self._process_sync(msg)
return await result if isawaitable(result) else result
| self, strict)
input.subscribe(self._process_sync)
def add(self, msg_type: Type, handler: Callable):
if iscoroutinefunction(handler):
raise ValueError('Router works only with synchronous handlers')
RouterBase.add(self, msg_type, handler)
class AsyncRouter(RouterBase):
| 64 | 64 | 75 | 7 | 57 | andkononykhin/plenum | plenum/common/channel.py | Python | AsyncRouter | AsyncRouter | 185 | 192 | 185 | 185 | d72a2b2b9cd947e2ba56e4e96c3958efc4bcf641 | bigcode/the-stack | train |
a4d5fadafcc138261e202c52 | train | class | class RxChannel(ABC):
@abstractmethod
def subscribe(self, handler: Callable):
pass
| class RxChannel(ABC):
@abstractmethod
| def subscribe(self, handler: Callable):
pass
|
# is more appropriate.
class TxChannel(ABC):
@abstractmethod
async def put(self, msg: Any):
pass
@abstractmethod
def put_nowait(self, msg: Any) -> bool:
pass
class RxChannel(ABC):
@abstractmethod
| 64 | 64 | 23 | 11 | 52 | andkononykhin/plenum | plenum/common/channel.py | Python | RxChannel | RxChannel | 23 | 26 | 23 | 24 | 3161e62e3662a73975fdebcc9290c1fd403e117b | bigcode/the-stack | train |
610038814baa2a661986769c | train | class | class RouterBase:
def __init__(self, strict: bool = False):
self._strict = strict
self._routes = {} # type: Dict[Type, Callable]
def add(self, msg_type: Type, handler: Callable):
self._routes[msg_type] = handler
def _process_sync(self, msg: Any):
# This is done so that mes... | class RouterBase:
| def __init__(self, strict: bool = False):
self._strict = strict
self._routes = {} # type: Dict[Type, Callable]
def add(self, msg_type: Type, handler: Callable):
self._routes[msg_type] = handler
def _process_sync(self, msg: Any):
# This is done so that messages can include ... | RxChannel:
return self._observable
async def run(self):
self._is_running = True
while self._is_running:
msg = await self._queue.get()
await self._observable.notify(msg)
def stop(self):
self._is_running = False
class RouterBase:
| 64 | 64 | 205 | 4 | 59 | andkononykhin/plenum | plenum/common/channel.py | Python | RouterBase | RouterBase | 147 | 171 | 147 | 147 | a606d6d879544e9811b20f453572596de6c78cf2 | bigcode/the-stack | train |
9debd0142e2b48151578a961 | train | class | class TxChannel(ABC):
@abstractmethod
async def put(self, msg: Any):
pass
@abstractmethod
def put_nowait(self, msg: Any) -> bool:
pass
| class TxChannel(ABC):
@abstractmethod
| async def put(self, msg: Any):
pass
@abstractmethod
def put_nowait(self, msg: Any) -> bool:
pass
| import isawaitable, iscoroutinefunction
from typing import Any, Type, Callable, Tuple, Optional, Dict
# TODO: DEPRECATE
# After playing with concept a bit it feels like using EventBus
# is more appropriate.
class TxChannel(ABC):
@abstractmethod
| 64 | 64 | 46 | 11 | 53 | andkononykhin/plenum | plenum/common/channel.py | Python | TxChannel | TxChannel | 13 | 20 | 13 | 14 | bdab400a9ccbdc741cb998cdc4aabe1f01f792d3 | bigcode/the-stack | train |
c41dc04253809dd3b7c39173 | train | class | class Router(RouterBase):
def __init__(self, input: RxChannel, strict: bool = False):
RouterBase.__init__(self, strict)
input.subscribe(self._process_sync)
def add(self, msg_type: Type, handler: Callable):
if iscoroutinefunction(handler):
raise ValueError('Router works only ... | class Router(RouterBase):
| def __init__(self, input: RxChannel, strict: bool = False):
RouterBase.__init__(self, strict)
input.subscribe(self._process_sync)
def add(self, msg_type: Type, handler: Callable):
if iscoroutinefunction(handler):
raise ValueError('Router works only with synchronous handlers'... | RuntimeError("unhandled msg: {}".format(msg))
return
return handler(*msg)
def _find_handler(self, msg: Any) -> Optional[Callable]:
for cls, handler in self._routes.items():
if isinstance(msg, cls):
return handler
class Router(RouterBase):
| 64 | 64 | 87 | 6 | 57 | andkononykhin/plenum | plenum/common/channel.py | Python | Router | Router | 174 | 182 | 174 | 174 | b64a8c548b8c528dabece4cbe6ab1270ce5e154f | bigcode/the-stack | train |
1748f08b40cb4588fb92149b | train | class | class AsyncioChannelService:
class Channel(TxChannel):
def __init__(self, queue: Queue):
self._queue = queue
async def put(self, msg: Any):
await self._queue.put(msg)
def put_nowait(self, msg: Any) -> bool:
try:
self._queue.put_nowait(msg... | class AsyncioChannelService:
| class Channel(TxChannel):
def __init__(self, queue: Queue):
self._queue = queue
async def put(self, msg: Any):
await self._queue.put(msg)
def put_nowait(self, msg: Any) -> bool:
try:
self._queue.put_nowait(msg)
return True... | None) -> int:
count = 0
while len(self._queue) > 0 and (limit is None or count < limit):
count += 1
msg = self._queue.popleft()
self._observable.notify_sync(msg)
return count
class AsyncioChannelService:
| 64 | 64 | 213 | 6 | 57 | andkononykhin/plenum | plenum/common/channel.py | Python | AsyncioChannelService | AsyncioChannelService | 110 | 144 | 110 | 110 | ef424e759fac7c7af1b55d4ea47c82d234baf017 | bigcode/the-stack | train |
93208dba2024704d145d2042 | train | class | @test(groups=[tests.DBAAS_API, GROUP, tests.PRE_INSTANCES],
depends_on_groups=["services.initialize"])
class Flavors(object):
@before_class
def setUp(self):
rd_user = test_config.users.find_user(
Requirements(is_admin=False, services=["trove"]))
self.rd_client = create_dbaas_c... | @test(groups=[tests.DBAAS_API, GROUP, tests.PRE_INSTANCES],
depends_on_groups=["services.initialize"])
class Flavors(object):
@before_class
| def setUp(self):
rd_user = test_config.users.find_user(
Requirements(is_admin=False, services=["trove"]))
self.rd_client = create_dbaas_client(rd_user)
if test_config.nova_client is not None:
nova_user = test_config.users.find_user(
Requirements(servi... | doesn't start with %s" %
(href, test_config.dbaas_url))
assert_true(href.startswith(url), msg)
url = os.path.join("flavors", str(flavor.id))
msg = "REL HREF %s doesn't end in 'flavors/id'" % href
assert_true(href.endswith(url), msg)
elif "bookm... | 210 | 211 | 704 | 35 | 175 | denismakogon/trove | trove/tests/api/flavors.py | Python | Flavors | Flavors | 89 | 164 | 89 | 93 | ec83be6d1efa0c809e233a0196bd2353c9afdf73 | bigcode/the-stack | train |
da1b3be108034eb0dc598db6 | train | function | def assert_flavors_roughly_equivalent(os_flavor, dbaas_flavor):
assert_attributes_equal('name', os_flavor, dbaas_flavor)
assert_attributes_equal('ram', os_flavor, dbaas_flavor)
assert_false(hasattr(dbaas_flavor, 'disk'),
"The attribute 'disk' s/b absent from the dbaas API.")
| def assert_flavors_roughly_equivalent(os_flavor, dbaas_flavor):
| assert_attributes_equal('name', os_flavor, dbaas_flavor)
assert_attributes_equal('ram', os_flavor, dbaas_flavor)
assert_false(hasattr(dbaas_flavor, 'disk'),
"The attribute 'disk' s/b absent from the dbaas API.")
| )
expected = getattr(os_flavor, name)
actual = getattr(dbaas_flavor, name)
assert_equal(expected, actual,
'DBaas flavor differs from Open Stack on attribute ' + name)
def assert_flavors_roughly_equivalent(os_flavor, dbaas_flavor):
| 64 | 64 | 84 | 19 | 45 | denismakogon/trove | trove/tests/api/flavors.py | Python | assert_flavors_roughly_equivalent | assert_flavors_roughly_equivalent | 57 | 61 | 57 | 57 | 38236c674584c5446363de90b3349d49dece9492 | bigcode/the-stack | train |
3085b93822c305c157548144 | train | function | def assert_link_list_is_equal(flavor):
assert_true(hasattr(flavor, 'links'))
assert_true(flavor.links)
for link in flavor.links:
href = link['href']
if "self" in link['rel']:
expected_href = os.path.join(test_config.dbaas_url, "flavors",
... | def assert_link_list_is_equal(flavor):
| assert_true(hasattr(flavor, 'links'))
assert_true(flavor.links)
for link in flavor.links:
href = link['href']
if "self" in link['rel']:
expected_href = os.path.join(test_config.dbaas_url, "flavors",
str(flavor.id))
url = test_... | avor, dbaas_flavor):
assert_attributes_equal('name', os_flavor, dbaas_flavor)
assert_attributes_equal('ram', os_flavor, dbaas_flavor)
assert_false(hasattr(dbaas_flavor, 'disk'),
"The attribute 'disk' s/b absent from the dbaas API.")
def assert_link_list_is_equal(flavor):
| 82 | 83 | 278 | 9 | 73 | denismakogon/trove | trove/tests/api/flavors.py | Python | assert_link_list_is_equal | assert_link_list_is_equal | 64 | 86 | 64 | 64 | dfbdc466ce46358bc1fb2e51a0ff4422617ff79c | bigcode/the-stack | train |
37eb77e1e830eb58c91b3a92 | train | function | def assert_attributes_equal(name, os_flavor, dbaas_flavor):
"""Given an attribute name and two objects,
ensures the attribute is equal.
"""
assert_true(hasattr(os_flavor, name),
"open stack flavor did not have attribute %s" % name)
assert_true(hasattr(dbaas_flavor, name),
... | def assert_attributes_equal(name, os_flavor, dbaas_flavor):
| """Given an attribute name and two objects,
ensures the attribute is equal.
"""
assert_true(hasattr(os_flavor, name),
"open stack flavor did not have attribute %s" % name)
assert_true(hasattr(dbaas_flavor, name),
"dbaas flavor did not have attribute %s" % name)
... |
from trove.tests.util.users import Requirements
from trove.tests.util.check import AttrCheck
GROUP = "dbaas.api.flavors"
servers_flavors = None
dbaas_flavors = None
user = None
def assert_attributes_equal(name, os_flavor, dbaas_flavor):
| 64 | 64 | 134 | 16 | 47 | denismakogon/trove | trove/tests/api/flavors.py | Python | assert_attributes_equal | assert_attributes_equal | 43 | 54 | 43 | 43 | 96ad50b24791334de53d2b052dcbd31ff16d5cc6 | bigcode/the-stack | train |
e8bc93e192a8bdea85639dc6 | train | class | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
# 1st recursive solution
def helper(left, right):
if left > right or left < 0:
return []
if left == 0 and right == 1:
return [')']
addLeft = ["(" + paren for paren ... | class Solution:
| def generateParenthesis(self, n: int) -> List[str]:
# 1st recursive solution
def helper(left, right):
if left > right or left < 0:
return []
if left == 0 and right == 1:
return [')']
addLeft = ["(" + paren for paren in helper(left -... | class Solution:
| 3 | 69 | 233 | 3 | 0 | yingzhuo1994/LeetCode | 0022_GenerateParentheses.py | Python | Solution | Solution | 1 | 29 | 1 | 1 | 0dec2964d24377c941bd89be4752792ce6eac489 | bigcode/the-stack | train |
c265fab0a94af44ec7585163 | train | class | class TestLock(unittest.TestCase):
"""
测试Lock模块
"""
def setUp(self):
"""
:return:
"""
config.GuardianConfig.set({"STATE_SERVICE_HOSTS": "1.1.1.1:1",
"GUARDIAN_ID":"111"})
@mock.patch.object(kazoo.client.KazooClient, "start")
de... | class TestLock(unittest.TestCase):
| """
测试Lock模块
"""
def setUp(self):
"""
:return:
"""
config.GuardianConfig.set({"STATE_SERVICE_HOSTS": "1.1.1.1:1",
"GUARDIAN_ID":"111"})
@mock.patch.object(kazoo.client.KazooClient, "start")
def test_init(self, mock_start):
... | # -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
are/common.py test
"""
import os
import sys
import unittest
import m... | 105 | 120 | 402 | 7 | 97 | Gerogetrycode/ARK | tests/lock_test.py | Python | TestLock | TestLock | 24 | 81 | 24 | 24 | d373e5a61f4d10a3c796fd63c3432abebd5f8ee5 | bigcode/the-stack | train |
79d6d6e5eae38b850cd4ac39 | train | class | class Conveyor(CoreObject):
class_name = "manpy.Conveyor"
type = "Conveyor"
def __init__(self, id: str, name: str, length: float, speed: float, **kwargs):
CoreObject.__init__(self, id, name)
self.length = float(length) # length in meters
self.speed = float(speed) # speed in m/sec... | class Conveyor(CoreObject):
| class_name = "manpy.Conveyor"
type = "Conveyor"
def __init__(self, id: str, name: str, length: float, speed: float, **kwargs):
CoreObject.__init__(self, id, name)
self.length = float(length) # length in meters
self.speed = float(speed) # speed in m/sec
# counting the tot... | # ===========================================================================
# Copyright 2013 University of Limerick
#
# This file is part of DREAM.
#
# DREAM is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Founda... | 218 | 256 | 4,332 | 5 | 213 | datarevenue-berlin/manpy | manpy/simulation/Conveyor.py | Python | Conveyor | Conveyor | 34 | 496 | 34 | 34 | 0236cc9aa9e596a3a61d0fc40f83b4c6c3fdc036 | bigcode/the-stack | train |
9e223a1d9c642f46462f1902 | train | class | class ConveyerMover(object):
# ===========================================================================
# conveyorMover init method
# ===========================================================================
def __init__(self, conveyor):
# Process.__init__(self)
from .Global... | class ConveyerMover(object):
# ===========================================================================
# conveyorMover init method
# ===========================================================================
| def __init__(self, conveyor):
# Process.__init__(self)
from .Globals import G
self.env = G.env
self.conveyor = conveyor # the conveyor that owns the mover
self.timeToWait = 0 # the time to wait every time. This is calculated by the conveyor and corresponds
... | json = {"_class": self.class_name, "id": self.id, "results": {}}
json["results"]["working_ratio"] = self.Working
json["results"]["blockage_ratio"] = self.Blockage
json["results"]["waiting_ratio"] = self.Waiting
G.outputJSON["elementList"].append(json)
# =======================... | 110 | 110 | 368 | 21 | 89 | datarevenue-berlin/manpy | manpy/simulation/Conveyor.py | Python | ConveyerMover | ConveyerMover | 502 | 540 | 502 | 505 | c0ced3c9bbe6c64d72b2f305983b5541c591396f | bigcode/the-stack | train |
6a1e8bade6ff6d2c5da8fae8 | train | class | class Dog(models.Model):
dogName = models.CharField(max_length=200)
dogBreed = models.CharField(max_length=200)
dogColor = models.CharField(max_length=200)
dogGender = models.CharField(max_length=200)
| class Dog(models.Model):
| dogName = models.CharField(max_length=200)
dogBreed = models.CharField(max_length=200)
dogColor = models.CharField(max_length=200)
dogGender = models.CharField(max_length=200)
| from django.db import models
class Dog(models.Model):
| 11 | 64 | 53 | 5 | 5 | cs-fullstack-2019-fall/django-models-cw-marcus110379 | dogProject/dogApp/models.py | Python | Dog | Dog | 4 | 8 | 4 | 4 | 85b39a858f2c618ad74bafb148ddca64c48385ec | bigcode/the-stack | train |
61e6ba4f6c0709b6ab98477f | train | class | class newAccount(models.Model):
username =models.CharField(max_length=100)
name = models.CharField(max_length=100)
accountNumber = models.CharField(max_length=100)
balance= models.DecimalField(max_digits= 10, decimal_places = 3)
| class newAccount(models.Model):
| username =models.CharField(max_length=100)
name = models.CharField(max_length=100)
accountNumber = models.CharField(max_length=100)
balance= models.DecimalField(max_digits= 10, decimal_places = 3)
| django.db import models
class Dog(models.Model):
dogName = models.CharField(max_length=200)
dogBreed = models.CharField(max_length=200)
dogColor = models.CharField(max_length=200)
dogGender = models.CharField(max_length=200)
class newAccount(models.Model):
| 64 | 64 | 58 | 6 | 58 | cs-fullstack-2019-fall/django-models-cw-marcus110379 | dogProject/dogApp/models.py | Python | newAccount | newAccount | 11 | 15 | 11 | 11 | c41c1f46be3047191b00b99e06527c965afb3cb3 | bigcode/the-stack | train |
2f8f15239643a9f2db56cafa | train | class | class NotesModel(db.Model):
__tablename__ = 'notes'
nid = Column('nid', String(12), primary_key=True)
name = Column('name', String(128))
owner = Column('owner_uid', String(128))
creation_date = Column(DateTime)
update_date = Column(DateTime)
path = Column(postgresql.ARRAY(String(128), dimens... | class NotesModel(db.Model):
| __tablename__ = 'notes'
nid = Column('nid', String(12), primary_key=True)
name = Column('name', String(128))
owner = Column('owner_uid', String(128))
creation_date = Column(DateTime)
update_date = Column(DateTime)
path = Column(postgresql.ARRAY(String(128), dimensions=1))
pages = Column(... | from db_api.extensions import db
from db_api.models.TagsNotesTable import TagsNotesTable
from sqlalchemy.dialects import postgresql
from sqlalchemy.types import DateTime, String, Integer
from sqlalchemy.schema import Column
from sqlalchemy.orm import backref, relationship
class NotesModel(db.Model):
| 60 | 64 | 122 | 6 | 53 | biosan/AppuntiDB | db_api/models/NotesModel.py | Python | NotesModel | NotesModel | 9 | 19 | 9 | 9 | 4c58c7711e872103deaf86089d7175bcb714442d | bigcode/the-stack | train |
4936721dcfecce2f3af93811 | train | function | def main():
# parsing specific config
config = copy.deepcopy(s_config)
config.network = get_default_network_config()
config.loss = get_default_loss_config()
config = update_config_from_file(config, s_config_file, check_necessity=True)
config = update_config_from_args(config, s_args)
et = co... | def main():
# parsing specific config
| config = copy.deepcopy(s_config)
config.network = get_default_network_config()
config.loss = get_default_loss_config()
config = update_config_from_file(config, s_config_file, check_necessity=True)
config = update_config_from_args(config, s_args)
et = config.dataset.eval_target
# create log... | import os
import copy
import time
import torch
import logging
import pprint
from torch.utils.data import DataLoader
# define project dependency
import _init_paths
# project dependence
from common_pytorch.dataset.all_dataset import *
from common_pytorch.config_pytorch import update_config_from_file, update_config_fro... | 194 | 237 | 792 | 9 | 185 | Dhruv2012/Drone-based-building-assessment | win_det_heatmaps/test.py | Python | main | main | 27 | 96 | 27 | 28 | fa915dd56214d3092b2b60e6b4a8c582777d239e | bigcode/the-stack | train |
222ecfcca69672264e1515aa | train | function | def rotate_image(image, angle=90, pil=True):
"""Rotate image using specific angle
Args:
image: PIL Image or Numpy array
angle: Angle value of the rotation
pil: block type returned as PIL Image (default True)
Returns:
Image with rotation applied
Example:
>>> from P... | def rotate_image(image, angle=90, pil=True):
| """Rotate image using specific angle
Args:
image: PIL Image or Numpy array
angle: Angle value of the rotation
pil: block type returned as PIL Image (default True)
Returns:
Image with rotation applied
Example:
>>> from PIL import Image
>>> import numpy as np
... | ]
image_mean[i][j][k] = canal_value / nb_images
image_mean = np.array(image_mean, 'uint8')
if pil:
return Image.fromarray(image_mean, mode)
else:
return image_mean
def rotate_image(image, angle=90, pil=True):
| 64 | 64 | 216 | 12 | 51 | prise-3d/IPFML | ipfml/processing/movement.py | Python | rotate_image | rotate_image | 99 | 133 | 99 | 99 | 4fc385e126c7ebc68e3a9ef8715be5cfa06eda53 | bigcode/the-stack | train |
83c462ef6a956a7459a20922 | train | function | def fusion_images(images, pil=True):
'''Fusion array of images into single image
Args:
images: array of images (PIL Image or Numpy array)
pil: block type returned as PIL Image (default True)
Returns:
merged image from array of images
Raises:
ValueError: if `images` is ... | def fusion_images(images, pil=True):
| '''Fusion array of images into single image
Args:
images: array of images (PIL Image or Numpy array)
pil: block type returned as PIL Image (default True)
Returns:
merged image from array of images
Raises:
ValueError: if `images` is not an array or is empty
Nump... | """
All movements that can be applied on image such as rotations, fusions, flips
"""
# main imports
import numpy as np
# image processing imports
from PIL import Image
from skimage import transform as sk_transform
# ipfml imports
from ipfml.exceptions import NumpyShapeComparisonException
def fusion_images(images, pi... | 73 | 168 | 561 | 8 | 64 | prise-3d/IPFML | ipfml/processing/movement.py | Python | fusion_images | fusion_images | 16 | 96 | 16 | 16 | ec2f2bd78d21ffde5e25a33b23e170f3fdecb1c3 | bigcode/the-stack | train |
b1fcc9992072bf354b46e687 | train | class | class CrossDephasingAnalysis(ba.BaseDataAnalysis):
'''
Analyses measurement-induced Dephasing of qubits.
options_dict options:
- The inherited options from BaseDataAnalysis
- The inherited options from DephasingAnalysis
-
'''
def __init__(self, qubit_labels: list,
t_start: s... | class CrossDephasingAnalysis(ba.BaseDataAnalysis):
| '''
Analyses measurement-induced Dephasing of qubits.
options_dict options:
- The inherited options from BaseDataAnalysis
- The inherited options from DephasingAnalysis
-
'''
def __init__(self, qubit_labels: list,
t_start: str = None, t_stop: str = None,
lab... | '''
Toolset to analyse measurement-induced Dephasing of qubits
Hacked together by Rene Vollmer
'''
import pycqed
from pycqed.analysis_v2.quantum_efficiency_analysis import DephasingAnalysisSweep
import pycqed.analysis_v2.base_analysis as ba
import numpy as np
from collections import OrderedDict
import copy
import dat... | 127 | 256 | 2,940 | 12 | 114 | nuttamas/PycQED_py3 | pycqed/analysis_v2/cross_dephasing_analysis.py | Python | CrossDephasingAnalysis | CrossDephasingAnalysis | 22 | 292 | 22 | 22 | 3d1215d4597c35c152ee43995869bca8cb085bf7 | bigcode/the-stack | train |
9a1bafad1754720eecab5c53 | train | class | class Command(object):
"""The object for coap commands."""
def __init__(
self,
method,
path,
data=None,
*,
parse_json=True,
observe=False,
observe_duration=0,
process_result=None,
err_callback=None
):
self._method = met... | class Command(object):
| """The object for coap commands."""
def __init__(
self,
method,
path,
data=None,
*,
parse_json=True,
observe=False,
observe_duration=0,
process_result=None,
err_callback=None
):
self._method = method
self._path ... | """Command implementation."""
from copy import deepcopy
class Command(object):
| 13 | 221 | 738 | 4 | 8 | kiilerix/pytradfri | pytradfri/command.py | Python | Command | Command | 6 | 133 | 6 | 6 | eb74a9b575ad4d7077ba797b9d351aaeb76eb718 | bigcode/the-stack | train |
260a8f3bd883316ca0d5d8f7 | train | class | class DAQRunner:
"""Main runner class controlling DAQ. Primarily mediates between
faucet events, connected hosts (to test), and gcp for logging. This
class owns the main event loop and shards out work to subclasses."""
MAX_GATEWAYS = 9
_DEFAULT_RETENTION_DAYS = 30
_SITE_CONFIG = 'site_config.js... | class DAQRunner:
| """Main runner class controlling DAQ. Primarily mediates between
faucet events, connected hosts (to test), and gcp for logging. This
class owns the main event loop and shards out work to subclasses."""
MAX_GATEWAYS = 9
_DEFAULT_RETENTION_DAYS = 30
_SITE_CONFIG = 'site_config.json'
_RUNNER_C... | not found." % device
del self._devices[device.mac]
self._set_ids.remove(device.set_id)
def get(self, device_mac):
"""Get a device using its mac address"""
return self._devices.get(device_mac)
def get_by_port_info(self, port):
"""Get a device using its port info object"... | 256 | 256 | 8,993 | 5 | 250 | henry54809/daq | daq/runner.py | Python | DAQRunner | DAQRunner | 143 | 1,154 | 143 | 143 | e0c3d831e6be08fff85febd73ba6860e5faa9143 | bigcode/the-stack | train |
e3bff6040ca50d49c83f6d5f | train | class | class Devices:
"""Container for all devices"""
def __init__(self):
self._devices = {}
self._set_ids = set()
def new_device(self, mac, port_info=None, vlan=None):
"""Adding a new device"""
assert mac not in self._devices, "Device with mac: %s is already added." % mac
... | class Devices:
| """Container for all devices"""
def __init__(self):
self._devices = {}
self._set_ids = set()
def new_device(self, mac, port_info=None, vlan=None):
"""Adding a new device"""
assert mac not in self._devices, "Device with mac: %s is already added." % mac
device = Device... | None
port_no = None
class IpInfo:
"""Simple container for device ip info"""
ip_addr = None
state = None
delta_sec = None
class Device:
"""Simple container for device info"""
def __init__(self):
# Neutral change that should not impact code coverage.
self.mac = None
... | 167 | 168 | 563 | 3 | 164 | henry54809/daq | daq/runner.py | Python | Devices | Devices | 73 | 140 | 73 | 73 | 532b6a40cf8839ef80e1d8c81431128aed3291d7 | bigcode/the-stack | train |
cd443834b58e3bbd5383be73 | train | class | class IpInfo:
"""Simple container for device ip info"""
ip_addr = None
state = None
delta_sec = None
| class IpInfo:
| """Simple container for device ip info"""
ip_addr = None
state = None
delta_sec = None
| logger.get_logger('runner')
NATIVE_GATEWAY_INTF = 'pri-eth1'
NATIVE_NET_PREFIX = '10.21'
class PortInfo:
"""Simple container for device port info"""
active = False
flapping_start = None
port_no = None
class IpInfo:
| 64 | 64 | 30 | 4 | 59 | henry54809/daq | daq/runner.py | Python | IpInfo | IpInfo | 45 | 49 | 45 | 45 | bd83a2e7db2137742a81b3173b087b258efdbe77 | bigcode/the-stack | train |
f741c3f4d2a7aa292916b353 | train | class | class Device:
"""Simple container for device info"""
def __init__(self):
# Neutral change that should not impact code coverage.
self.mac = None
self.host = None
self.gateway = None
self.group = None
self.port = None
self.dhcp_ready = False
self.dhc... | class Device:
| """Simple container for device info"""
def __init__(self):
# Neutral change that should not impact code coverage.
self.mac = None
self.host = None
self.gateway = None
self.group = None
self.port = None
self.dhcp_ready = False
self.dhcp_mode = None
... | class PortInfo:
"""Simple container for device port info"""
active = False
flapping_start = None
port_no = None
class IpInfo:
"""Simple container for device ip info"""
ip_addr = None
state = None
delta_sec = None
class Device:
| 64 | 64 | 126 | 3 | 60 | henry54809/daq | daq/runner.py | Python | Device | Device | 52 | 70 | 52 | 52 | 333d59da3d89d2c1ed4dc5044c7dd2b95015a945 | bigcode/the-stack | train |
eab87aa1cc19643d329f09a2 | train | class | class PortInfo:
"""Simple container for device port info"""
active = False
flapping_start = None
port_no = None
| class PortInfo:
| """Simple container for device port info"""
active = False
flapping_start = None
port_no = None
| import stream_monitor
from wrappers import DaqException, DisconnectedException
import logger
from proto.system_config_pb2 import DhcpMode
LOGGER = logger.get_logger('runner')
NATIVE_GATEWAY_INTF = 'pri-eth1'
NATIVE_NET_PREFIX = '10.21'
class PortInfo:
| 64 | 64 | 31 | 4 | 60 | henry54809/daq | daq/runner.py | Python | PortInfo | PortInfo | 38 | 42 | 38 | 38 | ae87b59b5653fb649205165be1e320b96b26dea4 | bigcode/the-stack | train |
ed200d3a797e8229e7d8f30b | train | class | class TestImagenetRaw(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs('val', exist_ok=True)
random_array = np.random.random_sample([100,100,3]) * 255
random_array = random_array.astype(np.uint8)
random_array = random_array.astype(np.uint8)
im = Image.fro... | class TestImagenetRaw(unittest.TestCase):
@classmethod
| def setUpClass(cls):
os.makedirs('val', exist_ok=True)
random_array = np.random.random_sample([100,100,3]) * 255
random_array = random_array.astype(np.uint8)
random_array = random_array.astype(np.uint8)
im = Image.fromarray(random_array)
im.save('val/test.jpg')
... | batch_size': 2,
'dataset': {"FashionMNIST": {'root': './', 'train':False, 'download':True}},
'transform': {'Resize': {'size': 24}},
'filter': None
}
dataloader = create_dataloader('onnxrt_qlinearops', dataloader_args)
for data in dataloader:
self.... | 256 | 256 | 1,490 | 13 | 243 | intel/lp-opt-tool | test/test_dataloader.py | Python | TestImagenetRaw | TestImagenetRaw | 286 | 433 | 286 | 287 | 4aa83fd29f9b19ddc38ed7c2f381aa41853e31ee | bigcode/the-stack | train |
3e007114794d840dc98158c8 | train | class | class TestBuiltinDataloader(unittest.TestCase):
@classmethod
def tearDownClass(cls):
os.remove('./t10k-labels-idx1-ubyte.gz')
os.remove('./t10k-images-idx3-ubyte.gz')
os.remove('./train-images-idx3-ubyte.gz')
os.remove('./train-labels-idx1-ubyte.gz')
os.remove('./mnist.np... | class TestBuiltinDataloader(unittest.TestCase):
@classmethod
| def tearDownClass(cls):
os.remove('./t10k-labels-idx1-ubyte.gz')
os.remove('./t10k-images-idx3-ubyte.gz')
os.remove('./train-images-idx3-ubyte.gz')
os.remove('./train-labels-idx1-ubyte.gz')
os.remove('./mnist.npz')
def test_pytorch_dataset(self):
dataloader_args ... | """Tests for the dataloader module."""
import unittest
import os
import numpy as np
import shutil
import tensorflow as tf
from neural_compressor.utils.create_obj_from_config import create_dataset, create_dataloader
from neural_compressor.data.dataloaders.dataloader import DataLoader
from neural_compressor.data import D... | 97 | 256 | 2,677 | 13 | 83 | intel/lp-opt-tool | test/test_dataloader.py | Python | TestBuiltinDataloader | TestBuiltinDataloader | 12 | 284 | 12 | 13 | 054ca342b91ba61b857a7f7eedeeae0646fbfe68 | bigcode/the-stack | train |
bfe3a7944f392ca5434e1631 | train | class | class TestImageFolder(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.makedirs('val', exist_ok=True)
os.makedirs('val/0', exist_ok=True)
random_array = np.random.random_sample([100,100,3]) * 255
random_array = random_array.astype(np.uint8)
random_array = random_a... | class TestImageFolder(unittest.TestCase):
@classmethod
| def setUpClass(cls):
os.makedirs('val', exist_ok=True)
os.makedirs('val/0', exist_ok=True)
random_array = np.random.random_sample([100,100,3]) * 255
random_array = random_array.astype(np.uint8)
random_array = random_array.astype(np.uint8)
im = Image.fromarray(random_a... | dataloader = create_dataloader('onnxrt_integerops', dataloader_args)
for data in dataloader:
self.assertEqual(data[0][0].shape, (24,24,3))
break
with open('val/blank.txt', 'w') as f:
f.write('blank.jpg 0')
dataloader_args = {
'dataset': ... | 158 | 158 | 528 | 12 | 146 | intel/lp-opt-tool | test/test_dataloader.py | Python | TestImageFolder | TestImageFolder | 436 | 498 | 436 | 437 | d21f51fe35ab78d661067d5088837d7fbc0f7dc6 | bigcode/the-stack | train |
a2f206ae8b3795e920144659 | train | class | class TestDataloader(unittest.TestCase):
def test_iterable_dataset(self):
class iter_dataset(object):
def __iter__(self):
for i in range(100):
yield np.zeros([256, 256, 3])
dataset = iter_dataset()
data_loader = DATALOADERS['tensorflow'](datase... | class TestDataloader(unittest.TestCase):
| def test_iterable_dataset(self):
class iter_dataset(object):
def __iter__(self):
for i in range(100):
yield np.zeros([256, 256, 3])
dataset = iter_dataset()
data_loader = DATALOADERS['tensorflow'](dataset)
iterator = iter(data_loader)
... | }
dataloader = create_dataloader('pytorch', dataloader_args)
for data in dataloader:
self.assertEqual(data[0][0].shape, (3,24,24))
break
def test_mxnet(self):
dataloader_args = {
'dataset': {"ImageFolder": {'root': './val'}},
'transfo... | 256 | 256 | 9,717 | 8 | 247 | intel/lp-opt-tool | test/test_dataloader.py | Python | TestDataloader | TestDataloader | 500 | 1,349 | 500 | 500 | 24a8ec361eafba2b88f9b45f3cc15fc806e0eb45 | bigcode/the-stack | train |
013dbfd9ddba9d11261229df | train | class | class TestArithmeticOps(BaseDatetimeTests, base.BaseArithmeticOpsTests):
implements = {"__sub__", "__rsub__"}
def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
# frame & scalar
if all_arithmetic_operators in self.implements:
df = pd.DataFrame({"A": data})
... | class TestArithmeticOps(BaseDatetimeTests, base.BaseArithmeticOpsTests):
| implements = {"__sub__", "__rsub__"}
def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
# frame & scalar
if all_arithmetic_operators in self.implements:
df = pd.DataFrame({"A": data})
self.check_opname(df, all_arithmetic_operators, data[0], exc=None)... | _value_counts(self, all_data, dropna):
pass
def test_combine_add(self, data_repeated):
# Timestamp.__add__(Timestamp) not defined
pass
class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests):
def test_array_interface(self, data):
if data.tz:
# np.asarray(DT... | 114 | 114 | 380 | 14 | 100 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestArithmeticOps | TestArithmeticOps | 129 | 167 | 129 | 129 | 76a8029b5872bb89e8159eb23e5fab521f495eb6 | bigcode/the-stack | train |
10cafe0f8bd4d03d4c464486 | train | class | class Test2DCompat(BaseDatetimeTests, base.Dim2CompatTests):
pass
| class Test2DCompat(BaseDatetimeTests, base.Dim2CompatTests):
| pass
| TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
pass
class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
pass
class TestPrinting(BaseDatetimeTests, base.BasePrintingTests):
pass
class Test2DCompat(BaseDatetimeTests, base.Dim2CompatTests):
| 64 | 64 | 19 | 16 | 47 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | Test2DCompat | Test2DCompat | 200 | 201 | 200 | 200 | fba66c05badf0dc1ae6b905b729246fde0b14353 | bigcode/the-stack | train |
f72ff3cd36bcf06ec85856a5 | train | class | class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests):
def test_array_interface(self, data):
if data.tz:
# np.asarray(DTA) is currently always tz-naive.
pytest.skip("GH-23569")
else:
super().test_array_interface(data)
| class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests):
| def test_array_interface(self, data):
if data.tz:
# np.asarray(DTA) is currently always tz-naive.
pytest.skip("GH-23569")
else:
super().test_array_interface(data)
| @pytest.mark.skip(reason="Incorrect expected")
def test_value_counts(self, all_data, dropna):
pass
def test_combine_add(self, data_repeated):
# Timestamp.__add__(Timestamp) not defined
pass
class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests):
| 64 | 64 | 61 | 12 | 51 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestInterface | TestInterface | 120 | 126 | 120 | 120 | 47da4051c562e5a55f110bfeb293cd4c8bce0977 | bigcode/the-stack | train |
df4b5301e57031b51d67ee1b | train | function | @pytest.fixture
def data_missing_for_sorting(dtype):
a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
return DatetimeArray(np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype)
| @pytest.fixture
def data_missing_for_sorting(dtype):
| a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
return DatetimeArray(np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype)
| ")
b = pd.Timestamp("2000-01-02")
c = pd.Timestamp("2000-01-03")
return DatetimeArray(np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype)
@pytest.fixture
def data_missing_for_sorting(dtype):
| 64 | 64 | 65 | 11 | 53 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | data_missing_for_sorting | data_missing_for_sorting | 52 | 56 | 52 | 53 | 11c5afdfaf78fc36b0852b529bd021934c3f5474 | bigcode/the-stack | train |
125b11bc369064f2812ae65b | train | class | class TestMissing(BaseDatetimeTests, base.BaseMissingTests):
pass
| class TestMissing(BaseDatetimeTests, base.BaseMissingTests):
| pass
| ):
# GH 23287
# skipping because it is not implemented
pass
class TestCasting(BaseDatetimeTests, base.BaseCastingTests):
pass
class TestComparisonOps(BaseDatetimeTests, base.BaseComparisonOpsTests):
pass
class TestMissing(BaseDatetimeTests, base.BaseMissingTests):
| 64 | 64 | 15 | 12 | 51 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestMissing | TestMissing | 178 | 179 | 178 | 178 | 6110179ed4538fa58850c9e27eb71f2f375a03f2 | bigcode/the-stack | train |
6805860066d9835997bcde12 | train | class | class TestPrinting(BaseDatetimeTests, base.BasePrintingTests):
pass
| class TestPrinting(BaseDatetimeTests, base.BasePrintingTests):
| pass
| etimeTZBlock")
def test_concat(self, data, in_frame):
pass
class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
pass
class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
pass
class TestPrinting(BaseDatetimeTests, base.BasePrintingTests):
| 64 | 64 | 15 | 12 | 51 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestPrinting | TestPrinting | 196 | 197 | 196 | 196 | b3e8662e540aa1366366fe79825ee0c0fa815cd3 | bigcode/the-stack | train |
f6b66624745e5bcd2fbf36b9 | train | function | @pytest.fixture
def na_value():
return pd.NaT
| @pytest.fixture
def na_value():
| return pd.NaT
| , na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype
)
@pytest.fixture
def na_cmp():
def cmp(a, b):
return a is pd.NaT and a is b
return cmp
@pytest.fixture
def na_value():
| 64 | 64 | 13 | 7 | 56 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | na_value | na_value | 83 | 85 | 83 | 84 | dc163b8a3c28d1676abf82453335ef7a21474674 | bigcode/the-stack | train |
e60efdab98217c1dfc461a5b | train | class | class TestMethods(BaseDatetimeTests, base.BaseMethodsTests):
@pytest.mark.skip(reason="Incorrect expected")
def test_value_counts(self, all_data, dropna):
pass
def test_combine_add(self, data_repeated):
# Timestamp.__add__(Timestamp) not defined
pass
| class TestMethods(BaseDatetimeTests, base.BaseMethodsTests):
@pytest.mark.skip(reason="Incorrect expected")
| def test_value_counts(self, all_data, dropna):
pass
def test_combine_add(self, data_repeated):
# Timestamp.__add__(Timestamp) not defined
pass
| Series construction drops any .freq attr
data = data._with_freq(None)
super().test_series_constructor(data)
class TestGetitem(BaseDatetimeTests, base.BaseGetitemTests):
pass
class TestMethods(BaseDatetimeTests, base.BaseMethodsTests):
@pytest.mark.skip(reason="Incorrect expected")
| 64 | 64 | 64 | 22 | 41 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestMethods | TestMethods | 110 | 117 | 110 | 111 | 7dff74b6100c8d1fdec09c864ddde872e1557d97 | bigcode/the-stack | train |
5cd38da9485ac3fa76a1a638 | train | class | class BaseDatetimeTests:
pass
| class BaseDatetimeTests:
| pass
| ="datetime64[ns]"), dtype=dtype
)
@pytest.fixture
def na_cmp():
def cmp(a, b):
return a is pd.NaT and a is b
return cmp
@pytest.fixture
def na_value():
return pd.NaT
# ----------------------------------------------------------------------------
class BaseDatetimeTests:
| 64 | 64 | 8 | 5 | 58 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | BaseDatetimeTests | BaseDatetimeTests | 89 | 90 | 89 | 89 | 61896ad77aac2fa1039fe45d80feadca6a031cda | bigcode/the-stack | train |
a77b051c1f347da8cec4d03b | train | class | class TestDatetimeDtype(BaseDatetimeTests, base.BaseDtypeTests):
pass
| class TestDatetimeDtype(BaseDatetimeTests, base.BaseDtypeTests):
| pass
| , b):
return a is pd.NaT and a is b
return cmp
@pytest.fixture
def na_value():
return pd.NaT
# ----------------------------------------------------------------------------
class BaseDatetimeTests:
pass
# ----------------------------------------------------------------------------
# Tests
clas... | 64 | 64 | 18 | 15 | 48 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestDatetimeDtype | TestDatetimeDtype | 95 | 96 | 95 | 95 | 55317d16b008ca169651fec284ba3066adde0b10 | bigcode/the-stack | train |
f907074a74a3e0532a0dd620 | train | function | @pytest.fixture(params=["US/Central"])
def dtype(request):
return DatetimeTZDtype(unit="ns", tz=request.param)
| @pytest.fixture(params=["US/Central"])
def dtype(request):
| return DatetimeTZDtype(unit="ns", tz=request.param)
| pandas/tests/arrays/`.
"""
import numpy as np
import pytest
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
from pandas.core.arrays import DatetimeArray
from pandas.tests.extension import base
@pytest.fixture(params=["US/Central"])
def dtype(request):
| 64 | 64 | 27 | 12 | 51 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | dtype | dtype | 26 | 28 | 26 | 27 | 0b25265338fe69231e0587b567472f589ef86f2a | bigcode/the-stack | train |
2d1c492d3a04bac3733a6bbe | train | class | class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
pass
| class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
| pass
| ReshapingTests):
@pytest.mark.skip(reason="We have DatetimeTZBlock")
def test_concat(self, data, in_frame):
pass
class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
pass
class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests):
| 64 | 64 | 17 | 14 | 49 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestGroupby | TestGroupby | 192 | 193 | 192 | 192 | 9520795ac05cb2bd49b8b85922c1d7c494818086 | bigcode/the-stack | train |
7395045f99a1debb9f5f6eeb | train | function | @pytest.fixture
def na_cmp():
def cmp(a, b):
return a is pd.NaT and a is b
return cmp
| @pytest.fixture
def na_cmp():
| def cmp(a, b):
return a is pd.NaT and a is b
return cmp
| pd.Timestamp("2000-01-03")
na = "NaT"
return DatetimeArray(
np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype
)
@pytest.fixture
def na_cmp():
| 64 | 64 | 30 | 7 | 57 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | na_cmp | na_cmp | 75 | 80 | 75 | 76 | b6b48e856ae00a562b5f95ab9a40bfca8c704a73 | bigcode/the-stack | train |
a09132d9a39bc77c39f580e7 | train | function | @pytest.fixture
def data(dtype):
data = DatetimeArray(pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype)
return data
| @pytest.fixture
def data(dtype):
| data = DatetimeArray(pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype)
return data
| types import DatetimeTZDtype
import pandas as pd
from pandas.core.arrays import DatetimeArray
from pandas.tests.extension import base
@pytest.fixture(params=["US/Central"])
def dtype(request):
return DatetimeTZDtype(unit="ns", tz=request.param)
@pytest.fixture
def data(dtype):
| 64 | 64 | 38 | 7 | 57 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | data | data | 31 | 34 | 31 | 32 | d7d7da39ce92918921f23bf916a1dcdd6c7439a0 | bigcode/the-stack | train |
54eff0e16ff6435745420d48 | train | class | class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
pass
| class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
| pass
| MissingTests):
pass
class TestReshaping(BaseDatetimeTests, base.BaseReshapingTests):
@pytest.mark.skip(reason="We have DatetimeTZBlock")
def test_concat(self, data, in_frame):
pass
class TestSetitem(BaseDatetimeTests, base.BaseSetitemTests):
| 64 | 64 | 17 | 14 | 49 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestSetitem | TestSetitem | 188 | 189 | 188 | 188 | 01e78321dd214460c99f97a488cdcca7115cdc1d | bigcode/the-stack | train |
f0a3ec4edbd018eab32f62b9 | train | function | @pytest.fixture
def data_for_sorting(dtype):
a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
c = pd.Timestamp("2000-01-03")
return DatetimeArray(np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype)
| @pytest.fixture
def data_for_sorting(dtype):
| a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
c = pd.Timestamp("2000-01-03")
return DatetimeArray(np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype)
| .tz), dtype=dtype)
return data
@pytest.fixture
def data_missing(dtype):
return DatetimeArray(
np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
)
@pytest.fixture
def data_for_sorting(dtype):
| 64 | 64 | 75 | 10 | 54 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | data_for_sorting | data_for_sorting | 44 | 49 | 44 | 45 | 19421750ef8e8481c4eb82c89dd1d931f00f41fa | bigcode/the-stack | train |
27cca1f0662f4728a043de4d | train | class | class TestComparisonOps(BaseDatetimeTests, base.BaseComparisonOpsTests):
pass
| class TestComparisonOps(BaseDatetimeTests, base.BaseComparisonOpsTests):
| pass
| , all_arithmetic_operators)
def test_divmod_series_array(self):
# GH 23287
# skipping because it is not implemented
pass
class TestCasting(BaseDatetimeTests, base.BaseCastingTests):
pass
class TestComparisonOps(BaseDatetimeTests, base.BaseComparisonOpsTests):
| 64 | 64 | 17 | 14 | 49 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestComparisonOps | TestComparisonOps | 174 | 175 | 174 | 174 | 58f9d50050bd000cb7f84dc0db1b9dd0c4326b9a | bigcode/the-stack | train |
a329dac30863588fb9cf3b16 | train | class | class TestConstructors(BaseDatetimeTests, base.BaseConstructorsTests):
def test_series_constructor(self, data):
# Series construction drops any .freq attr
data = data._with_freq(None)
super().test_series_constructor(data)
| class TestConstructors(BaseDatetimeTests, base.BaseConstructorsTests):
| def test_series_constructor(self, data):
# Series construction drops any .freq attr
data = data._with_freq(None)
super().test_series_constructor(data)
| cmp
@pytest.fixture
def na_value():
return pd.NaT
# ----------------------------------------------------------------------------
class BaseDatetimeTests:
pass
# ----------------------------------------------------------------------------
# Tests
class TestDatetimeDtype(BaseDatetimeTests, base.BaseDtypeTe... | 64 | 64 | 50 | 14 | 49 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | TestConstructors | TestConstructors | 99 | 103 | 99 | 99 | 574452742dd1c80eb9aa1f2e872db51910a73e8e | bigcode/the-stack | train |
b000d0a3ee29bcd989aca44e | train | function | @pytest.fixture
def data_missing(dtype):
return DatetimeArray(
np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
)
| @pytest.fixture
def data_missing(dtype):
| return DatetimeArray(
np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
)
| dtype(request):
return DatetimeTZDtype(unit="ns", tz=request.param)
@pytest.fixture
def data(dtype):
data = DatetimeArray(pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype)
return data
@pytest.fixture
def data_missing(dtype):
| 64 | 64 | 43 | 8 | 55 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | data_missing | data_missing | 37 | 41 | 37 | 38 | f4fd395aacfd75cb51b778361ba01e6807207e24 | bigcode/the-stack | train |
98dddc972b79c39f0de7e5ba | train | function | @pytest.fixture
def data_for_grouping(dtype):
"""
Expected to be like [B, B, NA, NA, A, A, B, C]
Where A < B < C and NA is missing
"""
a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
c = pd.Timestamp("2000-01-03")
na = "NaT"
return DatetimeArray(
np.array([b, b... | @pytest.fixture
def data_for_grouping(dtype):
| """
Expected to be like [B, B, NA, NA, A, A, B, C]
Where A < B < C and NA is missing
"""
a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
c = pd.Timestamp("2000-01-03")
na = "NaT"
return DatetimeArray(
np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]")... | a = pd.Timestamp("2000-01-01")
b = pd.Timestamp("2000-01-02")
return DatetimeArray(np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype)
@pytest.fixture
def data_for_grouping(dtype):
| 64 | 64 | 134 | 10 | 54 | arushi-08/pandas | pandas/tests/extension/test_datetime.py | Python | data_for_grouping | data_for_grouping | 59 | 72 | 59 | 60 | dce617891d12d59c0cf6bdccc427b8952dcd671c | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.