body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
def score(self, samples, labels):
' Measure the performance, returns success rate\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n\n Returns\n -------\n\n float: score of the model\n '
features = self.riemannian.features(samples)
return self.classifier.score(features, labels) | 7,076,869,925,505,679,000 | Measure the performance, returns success rate
Parameters
----------
samples: np.array, size=(N, C, T)
training samples
labels: np.array, size=(N)
training labels
Returns
-------
float: score of the model | multiscale_bci_python/riemannian_model.py | score | pulp-platform/multispectral-riemannian | python | def score(self, samples, labels):
' Measure the performance, returns success rate\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n\n Returns\n -------\n\n float: score of the model\n '
features = self.riemannian.features(samples)
return self.classifier.score(features, labels) |
def predict(self, samples):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n Returns\n -------\n\n np.array, size=[N]: prediction\n '
features = self.riemannian.features(samples)
return self.classifier.predict(features) | 5,834,870,184,465,553,000 | Predict some data
Parameters
----------
samples: np.array, size=(N, C, T)
training samples
Returns
-------
np.array, size=[N]: prediction | multiscale_bci_python/riemannian_model.py | predict | pulp-platform/multispectral-riemannian | python | def predict(self, samples):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n Returns\n -------\n\n np.array, size=[N]: prediction\n '
features = self.riemannian.features(samples)
return self.classifier.predict(features) |
def __init__(self, svm_c=0.1, fs=250, bands=None, riem_opt='Riemann', rho=0.1, filter_order=2, random_state=None, num_bits=8, bitshift_scale=True):
' Constructor\n\n Parameters\n ----------\n\n svm_c: float\n regularization parameter for the classifier\n\n fs: int\n sampling rate of the data\n\n bands: list of int\n bandwidths used in filterbanks (default: [2, 4, 8, 16, 32])\n\n riem_opt: str {"riemann", "Riemann_Euclid", "Whitened_Euclid", "No_Adaptation"}\n type of riemannian used\n\n rho: float\n Normalization parameter for the covariance matrix of the riemannian\n\n filter_order: int\n Order of the filter\n\n random_state: int or None\n random seed used in the SVM\n\n num_bits: int\n Number of bits used for quantization\n\n bitshift_scale: bool\n if True, make sure that all scale factors between one part and the next is a bitshift\n '
self.num_bits = num_bits
self.bitshift_scale = bitshift_scale
self.classifier = LinearSVC(C=svm_c, loss='hinge', random_state=random_state, tol=1e-05)
if (bands is None):
bandwidths = np.array([2, 4, 8, 16, 32])
else:
bandwidths = np.array(bands)
filter_bank = load_filterbank(bandwidths, fs, order=filter_order, max_freq=40, ftype='butter')
time_windows = (np.array([[2.5, 6]]) * fs).astype(int)
self.riemannian = QuantizedRiemannianMultiscale(filter_bank, time_windows, riem_opt=riem_opt, rho=rho, vectorized=True, num_bits=num_bits, bitshift_scale=bitshift_scale)
self.scale_weight = 0
self.scale_bias = 0
self.no_bands = filter_bank.shape[0]
self.no_time_windows = time_windows.shape[0]
self.no_riem = None
self.no_features = None | -988,073,680,426,644,500 | Constructor
Parameters
----------
svm_c: float
regularization parameter for the classifier
fs: int
sampling rate of the data
bands: list of int
bandwidths used in filterbanks (default: [2, 4, 8, 16, 32])
riem_opt: str {"riemann", "Riemann_Euclid", "Whitened_Euclid", "No_Adaptation"}
type of riemannian used
rho: float
Normalization parameter for the covariance matrix of the riemannian
filter_order: int
Order of the filter
random_state: int or None
random seed used in the SVM
num_bits: int
Number of bits used for quantization
bitshift_scale: bool
if True, make sure that all scale factors between one part and the next is a bitshift | multiscale_bci_python/riemannian_model.py | __init__ | pulp-platform/multispectral-riemannian | python | def __init__(self, svm_c=0.1, fs=250, bands=None, riem_opt='Riemann', rho=0.1, filter_order=2, random_state=None, num_bits=8, bitshift_scale=True):
' Constructor\n\n Parameters\n ----------\n\n svm_c: float\n regularization parameter for the classifier\n\n fs: int\n sampling rate of the data\n\n bands: list of int\n bandwidths used in filterbanks (default: [2, 4, 8, 16, 32])\n\n riem_opt: str {"riemann", "Riemann_Euclid", "Whitened_Euclid", "No_Adaptation"}\n type of riemannian used\n\n rho: float\n Normalization parameter for the covariance matrix of the riemannian\n\n filter_order: int\n Order of the filter\n\n random_state: int or None\n random seed used in the SVM\n\n num_bits: int\n Number of bits used for quantization\n\n bitshift_scale: bool\n if True, make sure that all scale factors between one part and the next is a bitshift\n '
self.num_bits = num_bits
self.bitshift_scale = bitshift_scale
self.classifier = LinearSVC(C=svm_c, loss='hinge', random_state=random_state, tol=1e-05)
if (bands is None):
bandwidths = np.array([2, 4, 8, 16, 32])
else:
bandwidths = np.array(bands)
filter_bank = load_filterbank(bandwidths, fs, order=filter_order, max_freq=40, ftype='butter')
time_windows = (np.array([[2.5, 6]]) * fs).astype(int)
self.riemannian = QuantizedRiemannianMultiscale(filter_bank, time_windows, riem_opt=riem_opt, rho=rho, vectorized=True, num_bits=num_bits, bitshift_scale=bitshift_scale)
self.scale_weight = 0
self.scale_bias = 0
self.no_bands = filter_bank.shape[0]
self.no_time_windows = time_windows.shape[0]
self.no_riem = None
self.no_features = None |
def fit(self, samples, labels):
' Training\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n '
assert (len(samples.shape) == 3)
no_channels = samples.shape[1]
self.no_riem = int(((no_channels * (no_channels + 1)) / 2))
self.no_features = ((self.no_riem * self.no_bands) * self.no_time_windows)
self.riemannian.prepare_quantization(samples)
features = self.riemannian.fit(samples)
self.classifier.fit(features, labels)
self.scale_weight = max(self.scale_weight, np.abs(self.classifier.coef_).max())
weights = quantize(self.classifier.coef_, self.scale_weight, self.num_bits, do_round=True)
self.classifier.coef_ = weights | 2,444,125,521,413,318,700 | Training
Parameters
----------
samples: np.array, size=(N, C, T)
training samples
labels: np.array, size=(N)
training labels | multiscale_bci_python/riemannian_model.py | fit | pulp-platform/multispectral-riemannian | python | def fit(self, samples, labels):
' Training\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n '
assert (len(samples.shape) == 3)
no_channels = samples.shape[1]
self.no_riem = int(((no_channels * (no_channels + 1)) / 2))
self.no_features = ((self.no_riem * self.no_bands) * self.no_time_windows)
self.riemannian.prepare_quantization(samples)
features = self.riemannian.fit(samples)
self.classifier.fit(features, labels)
self.scale_weight = max(self.scale_weight, np.abs(self.classifier.coef_).max())
weights = quantize(self.classifier.coef_, self.scale_weight, self.num_bits, do_round=True)
self.classifier.coef_ = weights |
def score(self, samples, labels):
' Measure the performance, returns success rate\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n\n Returns\n -------\n\n float: score of the model\n '
features = self.riemannian.features(samples)
return self.classifier.score(features, labels) | 7,076,869,925,505,679,000 | Measure the performance, returns success rate
Parameters
----------
samples: np.array, size=(N, C, T)
training samples
labels: np.array, size=(N)
training labels
Returns
-------
float: score of the model | multiscale_bci_python/riemannian_model.py | score | pulp-platform/multispectral-riemannian | python | def score(self, samples, labels):
' Measure the performance, returns success rate\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n labels: np.array, size=(N)\n training labels\n\n Returns\n -------\n\n float: score of the model\n '
features = self.riemannian.features(samples)
return self.classifier.score(features, labels) |
def predict(self, samples):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n Returns\n -------\n\n np.array, size=[N]: prediction\n '
features = self.riemannian.features(samples)
return self.classifier.predict(features) | 5,834,870,184,465,553,000 | Predict some data
Parameters
----------
samples: np.array, size=(N, C, T)
training samples
Returns
-------
np.array, size=[N]: prediction | multiscale_bci_python/riemannian_model.py | predict | pulp-platform/multispectral-riemannian | python | def predict(self, samples):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(N, C, T)\n training samples\n\n Returns\n -------\n\n np.array, size=[N]: prediction\n '
features = self.riemannian.features(samples)
return self.classifier.predict(features) |
def predict_with_intermediate(self, sample, verbose=True):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(C, T)\n training sample\n\n Returns\n -------\n\n ordered dictionary including every intermediate result and the output\n '
if verbose:
print('Predict sample with intermediate matrices')
assert (len(sample.shape) == 2)
result = self.riemannian.onetrial_feature_with_intermediate(sample)
features = next(reversed(result.values()))
features = features.reshape(1, (- 1))
result['svm_result'] = self.classifier.decision_function(features)
result['prediction'] = self.classifier.predict(features)
return result | 150,626,265,355,452,300 | Predict some data
Parameters
----------
samples: np.array, size=(C, T)
training sample
Returns
-------
ordered dictionary including every intermediate result and the output | multiscale_bci_python/riemannian_model.py | predict_with_intermediate | pulp-platform/multispectral-riemannian | python | def predict_with_intermediate(self, sample, verbose=True):
' Predict some data\n\n Parameters\n ----------\n\n samples: np.array, size=(C, T)\n training sample\n\n Returns\n -------\n\n ordered dictionary including every intermediate result and the output\n '
if verbose:
print('Predict sample with intermediate matrices')
assert (len(sample.shape) == 2)
result = self.riemannian.onetrial_feature_with_intermediate(sample)
features = next(reversed(result.values()))
features = features.reshape(1, (- 1))
result['svm_result'] = self.classifier.decision_function(features)
result['prediction'] = self.classifier.predict(features)
return result |
def get_data_dict(self):
' Returns a nested dictionary containing all necessary data '
return {'num_bits': self.num_bits, 'bitshift_scale': self.bitshift_scale, 'SVM': {'weights': self.classifier.coef_, 'weight_scale': self.scale_weight, 'bias': self.classifier.intercept_}, 'riemannian': self.riemannian.get_data_dict()} | -4,072,130,570,090,352,600 | Returns a nested dictionary containing all necessary data | multiscale_bci_python/riemannian_model.py | get_data_dict | pulp-platform/multispectral-riemannian | python | def get_data_dict(self):
' '
return {'num_bits': self.num_bits, 'bitshift_scale': self.bitshift_scale, 'SVM': {'weights': self.classifier.coef_, 'weight_scale': self.scale_weight, 'bias': self.classifier.intercept_}, 'riemannian': self.riemannian.get_data_dict()} |
def normpath(path: Union[(str, BasePathLike)]) -> str:
'\n Normalize a path in order to provide a more consistent output.\n\n Currently it generates a relative path but in the future we may want to\n make this user configurable.\n '
relpath = os.path.relpath(str(path))
abspath = os.path.abspath(str(path))
if (abspath in relpath):
return abspath
return relpath | -7,662,795,799,429,548,000 | Normalize a path in order to provide a more consistent output.
Currently it generates a relative path but in the future we may want to
make this user configurable. | src/ansiblelint/file_utils.py | normpath | ssato/ansible-lint | python | def normpath(path: Union[(str, BasePathLike)]) -> str:
'\n Normalize a path in order to provide a more consistent output.\n\n Currently it generates a relative path but in the future we may want to\n make this user configurable.\n '
relpath = os.path.relpath(str(path))
abspath = os.path.abspath(str(path))
if (abspath in relpath):
return abspath
return relpath |
@contextmanager
def cwd(path: Union[(str, BasePathLike)]) -> Iterator[None]:
'Context manager for temporary changing current working directory.'
old_pwd = os.getcwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(old_pwd) | -9,188,642,933,402,762,000 | Context manager for temporary changing current working directory. | src/ansiblelint/file_utils.py | cwd | ssato/ansible-lint | python | @contextmanager
def cwd(path: Union[(str, BasePathLike)]) -> Iterator[None]:
old_pwd = os.getcwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(old_pwd) |
def expand_path_vars(path: str) -> str:
'Expand the environment or ~ variables in a path string.'
path = str(path).strip()
path = os.path.expanduser(path)
path = os.path.expandvars(path)
return path | 5,595,827,192,759,286,000 | Expand the environment or ~ variables in a path string. | src/ansiblelint/file_utils.py | expand_path_vars | ssato/ansible-lint | python | def expand_path_vars(path: str) -> str:
path = str(path).strip()
path = os.path.expanduser(path)
path = os.path.expandvars(path)
return path |
def expand_paths_vars(paths: List[str]) -> List[str]:
'Expand the environment or ~ variables in a list.'
paths = [expand_path_vars(p) for p in paths]
return paths | -1,621,349,078,788,468,000 | Expand the environment or ~ variables in a list. | src/ansiblelint/file_utils.py | expand_paths_vars | ssato/ansible-lint | python | def expand_paths_vars(paths: List[str]) -> List[str]:
paths = [expand_path_vars(p) for p in paths]
return paths |
def kind_from_path(path: Path, base: bool=False) -> FileType:
"Determine the file kind based on its name.\n\n When called with base=True, it will return the base file type instead\n of the explicit one. That is expected to return 'yaml' for any yaml files.\n "
pathex = wcmatch.pathlib.PurePath(path.absolute().resolve())
kinds = (options.kinds if (not base) else BASE_KINDS)
for entry in kinds:
for (k, v) in entry.items():
if pathex.globmatch(v, flags=((wcmatch.pathlib.GLOBSTAR | wcmatch.pathlib.BRACE) | wcmatch.pathlib.DOTGLOB)):
return str(k)
if base:
return ''
if path.is_dir():
return 'role'
if (str(path) == '/dev/stdin'):
return 'playbook'
return '' | 5,608,554,062,873,105,000 | Determine the file kind based on its name.
When called with base=True, it will return the base file type instead
of the explicit one. That is expected to return 'yaml' for any yaml files. | src/ansiblelint/file_utils.py | kind_from_path | ssato/ansible-lint | python | def kind_from_path(path: Path, base: bool=False) -> FileType:
"Determine the file kind based on its name.\n\n When called with base=True, it will return the base file type instead\n of the explicit one. That is expected to return 'yaml' for any yaml files.\n "
pathex = wcmatch.pathlib.PurePath(path.absolute().resolve())
kinds = (options.kinds if (not base) else BASE_KINDS)
for entry in kinds:
for (k, v) in entry.items():
if pathex.globmatch(v, flags=((wcmatch.pathlib.GLOBSTAR | wcmatch.pathlib.BRACE) | wcmatch.pathlib.DOTGLOB)):
return str(k)
if base:
return
if path.is_dir():
return 'role'
if (str(path) == '/dev/stdin'):
return 'playbook'
return |
def discover_lintables(options: Namespace) -> Dict[(str, Any)]:
'Find all files that we know how to lint.'
git_command = ['git', 'ls-files', '-z']
out = None
try:
out = subprocess.check_output(git_command, stderr=subprocess.STDOUT, universal_newlines=True).split('\x00')[:(- 1)]
_logger.info('Discovered files to lint using: %s', ' '.join(git_command))
except subprocess.CalledProcessError as exc:
if (not ((exc.returncode == 128) and ('fatal: not a git repository' in exc.output))):
_logger.warning('Failed to discover lintable files using git: %s', exc.output.rstrip('\n'))
except FileNotFoundError as exc:
if options.verbosity:
_logger.warning('Failed to locate command: %s', exc)
if (out is None):
exclude_pattern = '|'.join(options.exclude_paths)
_logger.info('Looking up for files, excluding %s ...', exclude_pattern)
out = WcMatch('.', exclude_pattern=exclude_pattern, flags=RECURSIVE).match()
return OrderedDict.fromkeys(sorted(out)) | 4,829,897,235,746,249,000 | Find all files that we know how to lint. | src/ansiblelint/file_utils.py | discover_lintables | ssato/ansible-lint | python | def discover_lintables(options: Namespace) -> Dict[(str, Any)]:
git_command = ['git', 'ls-files', '-z']
out = None
try:
out = subprocess.check_output(git_command, stderr=subprocess.STDOUT, universal_newlines=True).split('\x00')[:(- 1)]
_logger.info('Discovered files to lint using: %s', ' '.join(git_command))
except subprocess.CalledProcessError as exc:
if (not ((exc.returncode == 128) and ('fatal: not a git repository' in exc.output))):
_logger.warning('Failed to discover lintable files using git: %s', exc.output.rstrip('\n'))
except FileNotFoundError as exc:
if options.verbosity:
_logger.warning('Failed to locate command: %s', exc)
if (out is None):
exclude_pattern = '|'.join(options.exclude_paths)
_logger.info('Looking up for files, excluding %s ...', exclude_pattern)
out = WcMatch('.', exclude_pattern=exclude_pattern, flags=RECURSIVE).match()
return OrderedDict.fromkeys(sorted(out)) |
def guess_project_dir() -> str:
'Return detected project dir or user home directory.'
try:
result = subprocess.run(['git', 'rev-parse', '--show-toplevel'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, check=False)
except FileNotFoundError:
return str(Path.home())
if (result.returncode != 0):
return str(Path.home())
return result.stdout.splitlines()[0] | 2,825,521,428,415,873,500 | Return detected project dir or user home directory. | src/ansiblelint/file_utils.py | guess_project_dir | ssato/ansible-lint | python | def guess_project_dir() -> str:
try:
result = subprocess.run(['git', 'rev-parse', '--show-toplevel'], stderr=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, check=False)
except FileNotFoundError:
return str(Path.home())
if (result.returncode != 0):
return str(Path.home())
return result.stdout.splitlines()[0] |
def expand_dirs_in_lintables(lintables: Set[Lintable]) -> None:
'Return all recognized lintables within given directory.'
should_expand = False
for item in lintables:
if item.path.is_dir():
should_expand = True
break
if should_expand:
all_files = discover_lintables(options)
for item in copy.copy(lintables):
if item.path.is_dir():
for filename in all_files:
if filename.startswith(str(item.path)):
lintables.add(Lintable(filename)) | -6,262,968,780,271,219,000 | Return all recognized lintables within given directory. | src/ansiblelint/file_utils.py | expand_dirs_in_lintables | ssato/ansible-lint | python | def expand_dirs_in_lintables(lintables: Set[Lintable]) -> None:
should_expand = False
for item in lintables:
if item.path.is_dir():
should_expand = True
break
if should_expand:
all_files = discover_lintables(options)
for item in copy.copy(lintables):
if item.path.is_dir():
for filename in all_files:
if filename.startswith(str(item.path)):
lintables.add(Lintable(filename)) |
def __init__(self, name: Union[(str, Path)], content: Optional[str]=None, kind: Optional[FileType]=None):
'Create a Lintable instance.'
self.filename: str = str(name)
self.dir: str = ''
self.kind: Optional[FileType] = None
if isinstance(name, str):
self.name = normpath(name)
self.path = Path(self.name)
else:
self.name = str(name)
self.path = name
self._content = content
self.role = ''
parts = self.path.parent.parts
if ('roles' in parts):
role = self.path
while ((role.parent.name != 'roles') and role.name):
role = role.parent
if role.exists:
self.role = role.name
if (str(self.path) in ['/dev/stdin', '-']):
self.file = NamedTemporaryFile(mode='w+', suffix='playbook.yml')
self.filename = self.file.name
self._content = sys.stdin.read()
self.file.write(self._content)
self.file.flush()
self.path = Path(self.file.name)
self.name = 'stdin'
self.kind = 'playbook'
self.dir = '/'
else:
self.kind = (kind or kind_from_path(self.path))
if (not self.dir):
if (self.kind == 'role'):
self.dir = str(self.path.resolve())
else:
self.dir = str(self.path.parent.resolve())
self.base_kind = kind_from_path(self.path, base=True) | 2,687,913,368,341,356,500 | Create a Lintable instance. | src/ansiblelint/file_utils.py | __init__ | ssato/ansible-lint | python | def __init__(self, name: Union[(str, Path)], content: Optional[str]=None, kind: Optional[FileType]=None):
self.filename: str = str(name)
self.dir: str =
self.kind: Optional[FileType] = None
if isinstance(name, str):
self.name = normpath(name)
self.path = Path(self.name)
else:
self.name = str(name)
self.path = name
self._content = content
self.role =
parts = self.path.parent.parts
if ('roles' in parts):
role = self.path
while ((role.parent.name != 'roles') and role.name):
role = role.parent
if role.exists:
self.role = role.name
if (str(self.path) in ['/dev/stdin', '-']):
self.file = NamedTemporaryFile(mode='w+', suffix='playbook.yml')
self.filename = self.file.name
self._content = sys.stdin.read()
self.file.write(self._content)
self.file.flush()
self.path = Path(self.file.name)
self.name = 'stdin'
self.kind = 'playbook'
self.dir = '/'
else:
self.kind = (kind or kind_from_path(self.path))
if (not self.dir):
if (self.kind == 'role'):
self.dir = str(self.path.resolve())
else:
self.dir = str(self.path.parent.resolve())
self.base_kind = kind_from_path(self.path, base=True) |
def __getitem__(self, key: Any) -> Any:
'Provide compatibility subscriptable support.'
if (key == 'path'):
return str(self.path)
if (key == 'type'):
return str(self.kind)
raise NotImplementedError() | -8,625,422,692,468,236,000 | Provide compatibility subscriptable support. | src/ansiblelint/file_utils.py | __getitem__ | ssato/ansible-lint | python | def __getitem__(self, key: Any) -> Any:
if (key == 'path'):
return str(self.path)
if (key == 'type'):
return str(self.kind)
raise NotImplementedError() |
def get(self, key: Any, default: Any=None) -> Any:
'Provide compatibility subscriptable support.'
try:
return self.__getitem__(key)
except NotImplementedError:
return default | 4,506,323,196,710,670,000 | Provide compatibility subscriptable support. | src/ansiblelint/file_utils.py | get | ssato/ansible-lint | python | def get(self, key: Any, default: Any=None) -> Any:
try:
return self.__getitem__(key)
except NotImplementedError:
return default |
@property
def content(self) -> str:
'Retried file content, from internal cache or disk.'
if (self._content is None):
with open(self.path, mode='r', encoding='utf-8') as f:
self._content = f.read()
return self._content | 8,205,710,333,400,251,000 | Retried file content, from internal cache or disk. | src/ansiblelint/file_utils.py | content | ssato/ansible-lint | python | @property
def content(self) -> str:
if (self._content is None):
with open(self.path, mode='r', encoding='utf-8') as f:
self._content = f.read()
return self._content |
def __hash__(self) -> int:
'Return a hash value of the lintables.'
return hash((self.name, self.kind)) | 2,416,460,979,397,695,000 | Return a hash value of the lintables. | src/ansiblelint/file_utils.py | __hash__ | ssato/ansible-lint | python | def __hash__(self) -> int:
return hash((self.name, self.kind)) |
def __eq__(self, other: object) -> bool:
'Identify whether the other object represents the same rule match.'
if isinstance(other, Lintable):
return bool(((self.name == other.name) and (self.kind == other.kind)))
return False | -8,703,419,712,621,147,000 | Identify whether the other object represents the same rule match. | src/ansiblelint/file_utils.py | __eq__ | ssato/ansible-lint | python | def __eq__(self, other: object) -> bool:
if isinstance(other, Lintable):
return bool(((self.name == other.name) and (self.kind == other.kind)))
return False |
def __repr__(self) -> str:
'Return user friendly representation of a lintable.'
return f'{self.name} ({self.kind})' | -5,344,757,360,546,887,000 | Return user friendly representation of a lintable. | src/ansiblelint/file_utils.py | __repr__ | ssato/ansible-lint | python | def __repr__(self) -> str:
return f'{self.name} ({self.kind})' |
def advanced_open(filepath, *args, **kwargs):
' Open function interface for files with different extensions.\n\n Parameters\n ----------\n filepath: str\n File path with extension.\n args: list\n Non-key arguments\n kwargs: dict\n Key arguments\n\n Returns\n -------\n\n '
open_fn = open
if filepath.endswith('.gz'):
open_fn = gzip.open
elif filepath.endswith('.bz2'):
open_fn = bz2.open
return open_fn(filepath, *args, mode='rt', **kwargs) | 8,171,895,657,630,073,000 | Open function interface for files with different extensions.
Parameters
----------
filepath: str
File path with extension.
args: list
Non-key arguments
kwargs: dict
Key arguments
Returns
------- | benchmarking/libkge/libkge/io/base.py | advanced_open | hpi-sam/GNN-Effectants | python | def advanced_open(filepath, *args, **kwargs):
' Open function interface for files with different extensions.\n\n Parameters\n ----------\n filepath: str\n File path with extension.\n args: list\n Non-key arguments\n kwargs: dict\n Key arguments\n\n Returns\n -------\n\n '
open_fn = open
if filepath.endswith('.gz'):
open_fn = gzip.open
elif filepath.endswith('.bz2'):
open_fn = bz2.open
return open_fn(filepath, *args, mode='rt', **kwargs) |
def load_kg_file(filepath, separator='\t', as_stream=False):
' Import knowledge graph from file\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n iterator\n The knowledge graph triplets obtained from the files with size [?, 3]\n '
kg_triples = []
with advanced_open(filepath) as file_content:
for line in file_content:
kg_triples.append(line.strip().split(separator))
return np.array(kg_triples) | 3,733,335,841,078,640,000 | Import knowledge graph from file
Parameters
----------
filepath: str
File path
separator: str
File column separator
Returns
-------
iterator
The knowledge graph triplets obtained from the files with size [?, 3] | benchmarking/libkge/libkge/io/base.py | load_kg_file | hpi-sam/GNN-Effectants | python | def load_kg_file(filepath, separator='\t', as_stream=False):
' Import knowledge graph from file\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n iterator\n The knowledge graph triplets obtained from the files with size [?, 3]\n '
kg_triples = []
with advanced_open(filepath) as file_content:
for line in file_content:
kg_triples.append(line.strip().split(separator))
return np.array(kg_triples) |
def load_kg_file_as_stream(filepath, separator='\t'):
' Import knowledge graph from file as a stream\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n generator\n The knowledge graph triplets obtained from the files with size [?, 3]\n '
with advanced_open(filepath) as file_content:
for line in file_content:
(yield line.strip().split(separator)) | -4,033,420,197,791,786,500 | Import knowledge graph from file as a stream
Parameters
----------
filepath: str
File path
separator: str
File column separator
Returns
-------
generator
The knowledge graph triplets obtained from the files with size [?, 3] | benchmarking/libkge/libkge/io/base.py | load_kg_file_as_stream | hpi-sam/GNN-Effectants | python | def load_kg_file_as_stream(filepath, separator='\t'):
' Import knowledge graph from file as a stream\n\n Parameters\n ----------\n filepath: str\n File path\n separator: str\n File column separator\n\n Returns\n -------\n generator\n The knowledge graph triplets obtained from the files with size [?, 3]\n '
with advanced_open(filepath) as file_content:
for line in file_content:
(yield line.strip().split(separator)) |
def __init__(self, currency_code=None, items=None, limit=None, shipping_methods=None, subtotal_amount=None):
'\n CouponFreeItemAndShippingWithSubtotal - a model defined in Swagger\n '
self._currency_code = None
self._items = None
self._limit = None
self._shipping_methods = None
self._subtotal_amount = None
self.discriminator = None
if (currency_code is not None):
self.currency_code = currency_code
if (items is not None):
self.items = items
if (limit is not None):
self.limit = limit
if (shipping_methods is not None):
self.shipping_methods = shipping_methods
if (subtotal_amount is not None):
self.subtotal_amount = subtotal_amount | 7,726,686,140,194,421,000 | CouponFreeItemAndShippingWithSubtotal - a model defined in Swagger | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | __init__ | gstingy/uc_python_api | python | def __init__(self, currency_code=None, items=None, limit=None, shipping_methods=None, subtotal_amount=None):
'\n \n '
self._currency_code = None
self._items = None
self._limit = None
self._shipping_methods = None
self._subtotal_amount = None
self.discriminator = None
if (currency_code is not None):
self.currency_code = currency_code
if (items is not None):
self.items = items
if (limit is not None):
self.limit = limit
if (shipping_methods is not None):
self.shipping_methods = shipping_methods
if (subtotal_amount is not None):
self.subtotal_amount = subtotal_amount |
@property
def currency_code(self):
'\n Gets the currency_code of this CouponFreeItemAndShippingWithSubtotal.\n The ISO-4217 three letter currency code the customer is viewing prices in\n\n :return: The currency_code of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: str\n '
return self._currency_code | -8,455,393,865,772,022,000 | Gets the currency_code of this CouponFreeItemAndShippingWithSubtotal.
The ISO-4217 three letter currency code the customer is viewing prices in
:return: The currency_code of this CouponFreeItemAndShippingWithSubtotal.
:rtype: str | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | currency_code | gstingy/uc_python_api | python | @property
def currency_code(self):
'\n Gets the currency_code of this CouponFreeItemAndShippingWithSubtotal.\n The ISO-4217 three letter currency code the customer is viewing prices in\n\n :return: The currency_code of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: str\n '
return self._currency_code |
@currency_code.setter
def currency_code(self, currency_code):
'\n Sets the currency_code of this CouponFreeItemAndShippingWithSubtotal.\n The ISO-4217 three letter currency code the customer is viewing prices in\n\n :param currency_code: The currency_code of this CouponFreeItemAndShippingWithSubtotal.\n :type: str\n '
if ((currency_code is not None) and (len(currency_code) > 3)):
raise ValueError('Invalid value for `currency_code`, length must be less than or equal to `3`')
self._currency_code = currency_code | 1,460,902,628,109,699,300 | Sets the currency_code of this CouponFreeItemAndShippingWithSubtotal.
The ISO-4217 three letter currency code the customer is viewing prices in
:param currency_code: The currency_code of this CouponFreeItemAndShippingWithSubtotal.
:type: str | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | currency_code | gstingy/uc_python_api | python | @currency_code.setter
def currency_code(self, currency_code):
'\n Sets the currency_code of this CouponFreeItemAndShippingWithSubtotal.\n The ISO-4217 three letter currency code the customer is viewing prices in\n\n :param currency_code: The currency_code of this CouponFreeItemAndShippingWithSubtotal.\n :type: str\n '
if ((currency_code is not None) and (len(currency_code) > 3)):
raise ValueError('Invalid value for `currency_code`, length must be less than or equal to `3`')
self._currency_code = currency_code |
@property
def items(self):
'\n Gets the items of this CouponFreeItemAndShippingWithSubtotal.\n A list of items that are eligible for this discount_price.\n\n :return: The items of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: list[str]\n '
return self._items | -6,865,338,245,224,918,000 | Gets the items of this CouponFreeItemAndShippingWithSubtotal.
A list of items that are eligible for this discount_price.
:return: The items of this CouponFreeItemAndShippingWithSubtotal.
:rtype: list[str] | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | items | gstingy/uc_python_api | python | @property
def items(self):
'\n Gets the items of this CouponFreeItemAndShippingWithSubtotal.\n A list of items that are eligible for this discount_price.\n\n :return: The items of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: list[str]\n '
return self._items |
@items.setter
def items(self, items):
'\n Sets the items of this CouponFreeItemAndShippingWithSubtotal.\n A list of items that are eligible for this discount_price.\n\n :param items: The items of this CouponFreeItemAndShippingWithSubtotal.\n :type: list[str]\n '
self._items = items | -9,137,725,184,073,997,000 | Sets the items of this CouponFreeItemAndShippingWithSubtotal.
A list of items that are eligible for this discount_price.
:param items: The items of this CouponFreeItemAndShippingWithSubtotal.
:type: list[str] | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | items | gstingy/uc_python_api | python | @items.setter
def items(self, items):
'\n Sets the items of this CouponFreeItemAndShippingWithSubtotal.\n A list of items that are eligible for this discount_price.\n\n :param items: The items of this CouponFreeItemAndShippingWithSubtotal.\n :type: list[str]\n '
self._items = items |
@property
def limit(self):
'\n Gets the limit of this CouponFreeItemAndShippingWithSubtotal.\n The limit of free items that may be received when purchasing multiple items\n\n :return: The limit of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: int\n '
return self._limit | 2,835,676,989,937,907,700 | Gets the limit of this CouponFreeItemAndShippingWithSubtotal.
The limit of free items that may be received when purchasing multiple items
:return: The limit of this CouponFreeItemAndShippingWithSubtotal.
:rtype: int | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | limit | gstingy/uc_python_api | python | @property
def limit(self):
'\n Gets the limit of this CouponFreeItemAndShippingWithSubtotal.\n The limit of free items that may be received when purchasing multiple items\n\n :return: The limit of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: int\n '
return self._limit |
@limit.setter
def limit(self, limit):
'\n Sets the limit of this CouponFreeItemAndShippingWithSubtotal.\n The limit of free items that may be received when purchasing multiple items\n\n :param limit: The limit of this CouponFreeItemAndShippingWithSubtotal.\n :type: int\n '
self._limit = limit | 5,774,597,195,965,673,000 | Sets the limit of this CouponFreeItemAndShippingWithSubtotal.
The limit of free items that may be received when purchasing multiple items
:param limit: The limit of this CouponFreeItemAndShippingWithSubtotal.
:type: int | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | limit | gstingy/uc_python_api | python | @limit.setter
def limit(self, limit):
'\n Sets the limit of this CouponFreeItemAndShippingWithSubtotal.\n The limit of free items that may be received when purchasing multiple items\n\n :param limit: The limit of this CouponFreeItemAndShippingWithSubtotal.\n :type: int\n '
self._limit = limit |
@property
def shipping_methods(self):
'\n Gets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n One or more shipping methods that may be free\n\n :return: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: list[str]\n '
return self._shipping_methods | -5,717,450,319,796,255,000 | Gets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.
One or more shipping methods that may be free
:return: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.
:rtype: list[str] | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | shipping_methods | gstingy/uc_python_api | python | @property
def shipping_methods(self):
'\n Gets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n One or more shipping methods that may be free\n\n :return: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: list[str]\n '
return self._shipping_methods |
@shipping_methods.setter
def shipping_methods(self, shipping_methods):
'\n Sets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n One or more shipping methods that may be free\n\n :param shipping_methods: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n :type: list[str]\n '
self._shipping_methods = shipping_methods | 8,762,765,273,655,466,000 | Sets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.
One or more shipping methods that may be free
:param shipping_methods: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.
:type: list[str] | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | shipping_methods | gstingy/uc_python_api | python | @shipping_methods.setter
def shipping_methods(self, shipping_methods):
'\n Sets the shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n One or more shipping methods that may be free\n\n :param shipping_methods: The shipping_methods of this CouponFreeItemAndShippingWithSubtotal.\n :type: list[str]\n '
self._shipping_methods = shipping_methods |
@property
def subtotal_amount(self):
'\n Gets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n The amount of subtotal required to receive the discount percent\n\n :return: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: float\n '
return self._subtotal_amount | 512,597,996,868,409,340 | Gets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.
The amount of subtotal required to receive the discount percent
:return: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.
:rtype: float | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | subtotal_amount | gstingy/uc_python_api | python | @property
def subtotal_amount(self):
'\n Gets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n The amount of subtotal required to receive the discount percent\n\n :return: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n :rtype: float\n '
return self._subtotal_amount |
@subtotal_amount.setter
def subtotal_amount(self, subtotal_amount):
'\n Sets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n The amount of subtotal required to receive the discount percent\n\n :param subtotal_amount: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n :type: float\n '
self._subtotal_amount = subtotal_amount | 8,399,218,832,283,492,000 | Sets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.
The amount of subtotal required to receive the discount percent
:param subtotal_amount: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.
:type: float | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | subtotal_amount | gstingy/uc_python_api | python | @subtotal_amount.setter
def subtotal_amount(self, subtotal_amount):
'\n Sets the subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n The amount of subtotal required to receive the discount percent\n\n :param subtotal_amount: The subtotal_amount of this CouponFreeItemAndShippingWithSubtotal.\n :type: float\n '
self._subtotal_amount = subtotal_amount |
def to_dict(self):
'\n Returns the model properties as a dict\n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result | 2,191,974,537,531,847,000 | Returns the model properties as a dict | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | to_dict | gstingy/uc_python_api | python | def to_dict(self):
'\n \n '
result = {}
for (attr, _) in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items()))
else:
result[attr] = value
return result |
def to_str(self):
'\n Returns the string representation of the model\n '
return pformat(self.to_dict()) | -3,531,024,894,346,511,000 | Returns the string representation of the model | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | to_str | gstingy/uc_python_api | python | def to_str(self):
'\n \n '
return pformat(self.to_dict()) |
def __repr__(self):
'\n For `print` and `pprint`\n '
return self.to_str() | 5,853,962,500,611,353,000 | For `print` and `pprint` | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | __repr__ | gstingy/uc_python_api | python | def __repr__(self):
'\n \n '
return self.to_str() |
def __eq__(self, other):
'\n Returns true if both objects are equal\n '
if (not isinstance(other, CouponFreeItemAndShippingWithSubtotal)):
return False
return (self.__dict__ == other.__dict__) | 5,803,635,293,539,645,000 | Returns true if both objects are equal | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | __eq__ | gstingy/uc_python_api | python | def __eq__(self, other):
'\n \n '
if (not isinstance(other, CouponFreeItemAndShippingWithSubtotal)):
return False
return (self.__dict__ == other.__dict__) |
def __ne__(self, other):
'\n Returns true if both objects are not equal\n '
return (not (self == other)) | 3,600,423,175,817,510,400 | Returns true if both objects are not equal | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | __ne__ | gstingy/uc_python_api | python | def __ne__(self, other):
'\n \n '
return (not (self == other)) |
def commit_data(data):
'\n This passes data to the data base as a single row. It then resets/empties data.\n '
url = 'http://localhost:1880/sensor'
headers = {'Accepts': 'application/json'}
print(f'1: {data[0]}')
send_jsn = json.dumps({'Movements': data[0][1], 'Cups': data[0][2], 'Gallons': data[0][3], 'Liters': data[0][4]})
try:
response = requests.post(url, data=send_jsn, headers=headers)
print(response.text)
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
data = []
return data | 6,960,748,390,919,356,000 | This passes data to the data base as a single row. It then resets/empties data. | software/read-sensor-python/waterFlow/waterFlowMeter.py | commit_data | ggreeve/add-pwo | python | def commit_data(data):
'\n \n '
url = 'http://localhost:1880/sensor'
headers = {'Accepts': 'application/json'}
print(f'1: {data[0]}')
send_jsn = json.dumps({'Movements': data[0][1], 'Cups': data[0][2], 'Gallons': data[0][3], 'Liters': data[0][4]})
try:
response = requests.post(url, data=send_jsn, headers=headers)
print(response.text)
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
data = []
return data |
def prep_and_send(data, total_rotations):
'\n Calculates measurements (cups and gallons). Prepares the data into a database-friendly tuple. Appends that tuple to a list. \n \n It then tries to connect to database. If it is not successful then it does nothing but saves the data; it will try to send \n the list of data-tuples the next time there is a water-flow event. \n \n Once the connection is successful data is emptied in commit_data().\n '
total_cups = (total_rotations / cup_movements)
total_gallons = (total_cups / 16)
total_liters = (total_gallons * 3.78541)
now = datetime.datetime.now()
print('{}: Movements: {}. \nCups: {}. \nGallons: {}. \nLiters: {}'.format(now, total_rotations, total_cups, total_gallons, total_liters))
current_data = (now, round(total_rotations, 2), round(total_cups, 2), round(total_gallons, 2), round(total_liters, 2))
data.append(current_data)
print(f'datos: {data}')
data = commit_data(data)
return data | -8,912,562,560,987,559,000 | Calculates measurements (cups and gallons). Prepares the data into a database-friendly tuple. Appends that tuple to a list.
It then tries to connect to database. If it is not successful then it does nothing but saves the data; it will try to send
the list of data-tuples the next time there is a water-flow event.
Once the connection is successful data is emptied in commit_data(). | software/read-sensor-python/waterFlow/waterFlowMeter.py | prep_and_send | ggreeve/add-pwo | python | def prep_and_send(data, total_rotations):
'\n Calculates measurements (cups and gallons). Prepares the data into a database-friendly tuple. Appends that tuple to a list. \n \n It then tries to connect to database. If it is not successful then it does nothing but saves the data; it will try to send \n the list of data-tuples the next time there is a water-flow event. \n \n Once the connection is successful data is emptied in commit_data().\n '
total_cups = (total_rotations / cup_movements)
total_gallons = (total_cups / 16)
total_liters = (total_gallons * 3.78541)
now = datetime.datetime.now()
print('{}: Movements: {}. \nCups: {}. \nGallons: {}. \nLiters: {}'.format(now, total_rotations, total_cups, total_gallons, total_liters))
current_data = (now, round(total_rotations, 2), round(total_cups, 2), round(total_gallons, 2), round(total_liters, 2))
data.append(current_data)
print(f'datos: {data}')
data = commit_data(data)
return data |
def resize_image(image, save_locaton):
' Copyright Rhyse Simpson:\n https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py\n '
im = Image.open(image)
maxsize = (512, 512)
if ((im.width and im.height) < 512):
size1 = im.width
size2 = im.height
if (im.width > im.height):
scale = (512 / size1)
size1new = 512
size2new = (size2 * scale)
else:
scale = (512 / size2)
size1new = (size1 * scale)
size2new = 512
size1new = math.floor(size1new)
size2new = math.floor(size2new)
sizenew = (size1new, size2new)
im = im.resize(sizenew)
else:
im.thumbnail(maxsize)
im.save(save_locaton, 'PNG') | -5,368,131,762,282,885,000 | Copyright Rhyse Simpson:
https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py | stdplugins/stickers.py | resize_image | FaisAFG/faisafg | python | def resize_image(image, save_locaton):
' Copyright Rhyse Simpson:\n https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py\n '
im = Image.open(image)
maxsize = (512, 512)
if ((im.width and im.height) < 512):
size1 = im.width
size2 = im.height
if (im.width > im.height):
scale = (512 / size1)
size1new = 512
size2new = (size2 * scale)
else:
scale = (512 / size2)
size1new = (size1 * scale)
size2new = 512
size1new = math.floor(size1new)
size2new = math.floor(size2new)
sizenew = (size1new, size2new)
im = im.resize(sizenew)
else:
im.thumbnail(maxsize)
im.save(save_locaton, 'PNG') |
def test_config():
' test that config magic does not raise\n can happen if Configurable init is moved too early into\n Magics.__init__ as then a Config object will be registered as a\n magic.\n '
_ip.magic('config') | 5,012,211,915,800,813,000 | test that config magic does not raise
can happen if Configurable init is moved too early into
Magics.__init__ as then a Config object will be registered as a
magic. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_config | Eviekim/waning-keyboard | python | def test_config():
' test that config magic does not raise\n can happen if Configurable init is moved too early into\n Magics.__init__ as then a Config object will be registered as a\n magic.\n '
_ip.magic('config') |
def test_config_available_configs():
' test that config magic prints available configs in unique and\n sorted order. '
with capture_output() as captured:
_ip.magic('config')
stdout = captured.stdout
config_classes = stdout.strip().split('\n')[1:]
nt.assert_list_equal(config_classes, sorted(set(config_classes))) | -8,538,739,251,610,590,000 | test that config magic prints available configs in unique and
sorted order. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_config_available_configs | Eviekim/waning-keyboard | python | def test_config_available_configs():
' test that config magic prints available configs in unique and\n sorted order. '
with capture_output() as captured:
_ip.magic('config')
stdout = captured.stdout
config_classes = stdout.strip().split('\n')[1:]
nt.assert_list_equal(config_classes, sorted(set(config_classes))) |
def test_config_print_class():
" test that config with a classname prints the class's options. "
with capture_output() as captured:
_ip.magic('config TerminalInteractiveShell')
stdout = captured.stdout
if (not re.match('TerminalInteractiveShell.* options', stdout.splitlines()[0])):
print(stdout)
raise AssertionError("1st line of stdout not like 'TerminalInteractiveShell.* options'") | 4,271,162,137,733,685,000 | test that config with a classname prints the class's options. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_config_print_class | Eviekim/waning-keyboard | python | def test_config_print_class():
" "
with capture_output() as captured:
_ip.magic('config TerminalInteractiveShell')
stdout = captured.stdout
if (not re.match('TerminalInteractiveShell.* options', stdout.splitlines()[0])):
print(stdout)
raise AssertionError("1st line of stdout not like 'TerminalInteractiveShell.* options'") |
def test_magic_parse_options():
"Test that we don't mangle paths when parsing magic options."
ip = get_ipython()
path = 'c:\\x'
m = DummyMagics(ip)
opts = m.parse_options(('-f %s' % path), 'f:')[0]
if (os.name == 'posix'):
expected = 'c:x'
else:
expected = path
nt.assert_equal(opts['f'], expected) | 3,625,923,017,169,394,000 | Test that we don't mangle paths when parsing magic options. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_magic_parse_options | Eviekim/waning-keyboard | python | def test_magic_parse_options():
ip = get_ipython()
path = 'c:\\x'
m = DummyMagics(ip)
opts = m.parse_options(('-f %s' % path), 'f:')[0]
if (os.name == 'posix'):
expected = 'c:x'
else:
expected = path
nt.assert_equal(opts['f'], expected) |
def test_magic_parse_long_options():
'Magic.parse_options can handle --foo=bar long options'
ip = get_ipython()
m = DummyMagics(ip)
(opts, _) = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
nt.assert_in('foo', opts)
nt.assert_in('bar', opts)
nt.assert_equal(opts['bar'], 'bubble') | -7,994,200,230,979,484,000 | Magic.parse_options can handle --foo=bar long options | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_magic_parse_long_options | Eviekim/waning-keyboard | python | def test_magic_parse_long_options():
ip = get_ipython()
m = DummyMagics(ip)
(opts, _) = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
nt.assert_in('foo', opts)
nt.assert_in('bar', opts)
nt.assert_equal(opts['bar'], 'bubble') |
@dec.skip_without('sqlite3')
def doctest_hist_f():
"Test %hist -f with temporary filename.\n\n In [9]: import tempfile\n\n In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')\n\n In [11]: %hist -nl -f $tfile 3\n\n In [13]: import os; os.unlink(tfile)\n " | -8,619,959,398,425,926,000 | Test %hist -f with temporary filename.
In [9]: import tempfile
In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
In [11]: %hist -nl -f $tfile 3
In [13]: import os; os.unlink(tfile) | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | doctest_hist_f | Eviekim/waning-keyboard | python | @dec.skip_without('sqlite3')
def doctest_hist_f():
"Test %hist -f with temporary filename.\n\n In [9]: import tempfile\n\n In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')\n\n In [11]: %hist -nl -f $tfile 3\n\n In [13]: import os; os.unlink(tfile)\n " |
@dec.skip_without('sqlite3')
def doctest_hist_r():
"Test %hist -r\n\n XXX - This test is not recording the output correctly. For some reason, in\n testing mode the raw history isn't getting populated. No idea why.\n Disabling the output checking for now, though at least we do run it.\n\n In [1]: 'hist' in _ip.lsmagic()\n Out[1]: True\n\n In [2]: x=1\n\n In [3]: %hist -rl 2\n x=1 # random\n %hist -r 2\n " | 2,223,701,855,043,785,000 | Test %hist -r
XXX - This test is not recording the output correctly. For some reason, in
testing mode the raw history isn't getting populated. No idea why.
Disabling the output checking for now, though at least we do run it.
In [1]: 'hist' in _ip.lsmagic()
Out[1]: True
In [2]: x=1
In [3]: %hist -rl 2
x=1 # random
%hist -r 2 | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | doctest_hist_r | Eviekim/waning-keyboard | python | @dec.skip_without('sqlite3')
def doctest_hist_r():
"Test %hist -r\n\n XXX - This test is not recording the output correctly. For some reason, in\n testing mode the raw history isn't getting populated. No idea why.\n Disabling the output checking for now, though at least we do run it.\n\n In [1]: 'hist' in _ip.lsmagic()\n Out[1]: True\n\n In [2]: x=1\n\n In [3]: %hist -rl 2\n x=1 # random\n %hist -r 2\n " |
@dec.skip_without('sqlite3')
def doctest_hist_op():
"Test %hist -op\n\n In [1]: class b(float):\n ...: pass\n ...: \n\n In [2]: class s(object):\n ...: def __str__(self):\n ...: return 's'\n ...: \n\n In [3]: \n\n In [4]: class r(b):\n ...: def __repr__(self):\n ...: return 'r'\n ...: \n\n In [5]: class sr(s,r): pass\n ...: \n\n In [6]: \n\n In [7]: bb=b()\n\n In [8]: ss=s()\n\n In [9]: rr=r()\n\n In [10]: ssrr=sr()\n\n In [11]: 4.5\n Out[11]: 4.5\n\n In [12]: str(ss)\n Out[12]: 's'\n\n In [13]: \n\n In [14]: %hist -op\n >>> class b:\n ... pass\n ... \n >>> class s(b):\n ... def __str__(self):\n ... return 's'\n ... \n >>> \n >>> class r(b):\n ... def __repr__(self):\n ... return 'r'\n ... \n >>> class sr(s,r): pass\n >>> \n >>> bb=b()\n >>> ss=s()\n >>> rr=r()\n >>> ssrr=sr()\n >>> 4.5\n 4.5\n >>> str(ss)\n 's'\n >>> \n " | -6,036,605,978,061,864,000 | Test %hist -op
In [1]: class b(float):
...: pass
...:
In [2]: class s(object):
...: def __str__(self):
...: return 's'
...:
In [3]:
In [4]: class r(b):
...: def __repr__(self):
...: return 'r'
...:
In [5]: class sr(s,r): pass
...:
In [6]:
In [7]: bb=b()
In [8]: ss=s()
In [9]: rr=r()
In [10]: ssrr=sr()
In [11]: 4.5
Out[11]: 4.5
In [12]: str(ss)
Out[12]: 's'
In [13]:
In [14]: %hist -op
>>> class b:
... pass
...
>>> class s(b):
... def __str__(self):
... return 's'
...
>>>
>>> class r(b):
... def __repr__(self):
... return 'r'
...
>>> class sr(s,r): pass
>>>
>>> bb=b()
>>> ss=s()
>>> rr=r()
>>> ssrr=sr()
>>> 4.5
4.5
>>> str(ss)
's'
>>> | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | doctest_hist_op | Eviekim/waning-keyboard | python | @dec.skip_without('sqlite3')
def doctest_hist_op():
"Test %hist -op\n\n In [1]: class b(float):\n ...: pass\n ...: \n\n In [2]: class s(object):\n ...: def __str__(self):\n ...: return 's'\n ...: \n\n In [3]: \n\n In [4]: class r(b):\n ...: def __repr__(self):\n ...: return 'r'\n ...: \n\n In [5]: class sr(s,r): pass\n ...: \n\n In [6]: \n\n In [7]: bb=b()\n\n In [8]: ss=s()\n\n In [9]: rr=r()\n\n In [10]: ssrr=sr()\n\n In [11]: 4.5\n Out[11]: 4.5\n\n In [12]: str(ss)\n Out[12]: 's'\n\n In [13]: \n\n In [14]: %hist -op\n >>> class b:\n ... pass\n ... \n >>> class s(b):\n ... def __str__(self):\n ... return 's'\n ... \n >>> \n >>> class r(b):\n ... def __repr__(self):\n ... return 'r'\n ... \n >>> class sr(s,r): pass\n >>> \n >>> bb=b()\n >>> ss=s()\n >>> rr=r()\n >>> ssrr=sr()\n >>> 4.5\n 4.5\n >>> str(ss)\n 's'\n >>> \n " |
@dec.skip_without('sqlite3')
def test_macro_run():
'Test that we can run a multi-line macro successfully.'
ip = get_ipython()
ip.history_manager.reset()
cmds = ['a=10', 'a+=1', 'print(a)', '%macro test 2-3']
for cmd in cmds:
ip.run_cell(cmd, store_history=True)
nt.assert_equal(ip.user_ns['test'].value, 'a+=1\nprint(a)\n')
with tt.AssertPrints('12'):
ip.run_cell('test')
with tt.AssertPrints('13'):
ip.run_cell('test') | 3,421,123,392,526,724,000 | Test that we can run a multi-line macro successfully. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_macro_run | Eviekim/waning-keyboard | python | @dec.skip_without('sqlite3')
def test_macro_run():
ip = get_ipython()
ip.history_manager.reset()
cmds = ['a=10', 'a+=1', 'print(a)', '%macro test 2-3']
for cmd in cmds:
ip.run_cell(cmd, store_history=True)
nt.assert_equal(ip.user_ns['test'].value, 'a+=1\nprint(a)\n')
with tt.AssertPrints('12'):
ip.run_cell('test')
with tt.AssertPrints('13'):
ip.run_cell('test') |
def test_magic_magic():
'Test %magic'
ip = get_ipython()
with capture_output() as captured:
ip.magic('magic')
stdout = captured.stdout
nt.assert_in('%magic', stdout)
nt.assert_in('IPython', stdout)
nt.assert_in('Available', stdout) | 6,610,884,545,765,770,000 | Test %magic | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_magic_magic | Eviekim/waning-keyboard | python | def test_magic_magic():
ip = get_ipython()
with capture_output() as captured:
ip.magic('magic')
stdout = captured.stdout
nt.assert_in('%magic', stdout)
nt.assert_in('IPython', stdout)
nt.assert_in('Available', stdout) |
@dec.skipif_not_numpy
def test_numpy_reset_array_undec():
"Test '%reset array' functionality"
_ip.ex('import numpy as np')
_ip.ex('a = np.empty(2)')
nt.assert_in('a', _ip.user_ns)
_ip.magic('reset -f array')
nt.assert_not_in('a', _ip.user_ns) | 6,675,929,842,528,033,000 | Test '%reset array' functionality | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_numpy_reset_array_undec | Eviekim/waning-keyboard | python | @dec.skipif_not_numpy
def test_numpy_reset_array_undec():
_ip.ex('import numpy as np')
_ip.ex('a = np.empty(2)')
nt.assert_in('a', _ip.user_ns)
_ip.magic('reset -f array')
nt.assert_not_in('a', _ip.user_ns) |
def test_reset_out():
"Test '%reset out' magic"
_ip.run_cell("parrot = 'dead'", store_history=True)
_ip.run_cell('parrot', store_history=True)
nt.assert_true(('dead' in [_ip.user_ns[x] for x in ('_', '__', '___')]))
_ip.magic('reset -f out')
nt.assert_false(('dead' in [_ip.user_ns[x] for x in ('_', '__', '___')]))
nt.assert_equal(len(_ip.user_ns['Out']), 0) | -2,866,445,605,046,621,700 | Test '%reset out' magic | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_reset_out | Eviekim/waning-keyboard | python | def test_reset_out():
_ip.run_cell("parrot = 'dead'", store_history=True)
_ip.run_cell('parrot', store_history=True)
nt.assert_true(('dead' in [_ip.user_ns[x] for x in ('_', '__', '___')]))
_ip.magic('reset -f out')
nt.assert_false(('dead' in [_ip.user_ns[x] for x in ('_', '__', '___')]))
nt.assert_equal(len(_ip.user_ns['Out']), 0) |
def test_reset_in():
"Test '%reset in' magic"
_ip.run_cell('parrot', store_history=True)
nt.assert_true(('parrot' in [_ip.user_ns[x] for x in ('_i', '_ii', '_iii')]))
_ip.magic('%reset -f in')
nt.assert_false(('parrot' in [_ip.user_ns[x] for x in ('_i', '_ii', '_iii')]))
nt.assert_equal(len(set(_ip.user_ns['In'])), 1) | 4,802,732,538,223,916,000 | Test '%reset in' magic | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_reset_in | Eviekim/waning-keyboard | python | def test_reset_in():
_ip.run_cell('parrot', store_history=True)
nt.assert_true(('parrot' in [_ip.user_ns[x] for x in ('_i', '_ii', '_iii')]))
_ip.magic('%reset -f in')
nt.assert_false(('parrot' in [_ip.user_ns[x] for x in ('_i', '_ii', '_iii')]))
nt.assert_equal(len(set(_ip.user_ns['In'])), 1) |
def test_reset_dhist():
"Test '%reset dhist' magic"
_ip.run_cell('tmp = [d for d in _dh]')
_ip.magic(('cd ' + os.path.dirname(nt.__file__)))
_ip.magic('cd -')
nt.assert_true((len(_ip.user_ns['_dh']) > 0))
_ip.magic('reset -f dhist')
nt.assert_equal(len(_ip.user_ns['_dh']), 0)
_ip.run_cell('_dh = [d for d in tmp]') | 1,902,267,024,093,031,400 | Test '%reset dhist' magic | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_reset_dhist | Eviekim/waning-keyboard | python | def test_reset_dhist():
_ip.run_cell('tmp = [d for d in _dh]')
_ip.magic(('cd ' + os.path.dirname(nt.__file__)))
_ip.magic('cd -')
nt.assert_true((len(_ip.user_ns['_dh']) > 0))
_ip.magic('reset -f dhist')
nt.assert_equal(len(_ip.user_ns['_dh']), 0)
_ip.run_cell('_dh = [d for d in tmp]') |
def test_reset_in_length():
"Test that '%reset in' preserves In[] length"
_ip.run_cell("print 'foo'")
_ip.run_cell('reset -f in')
nt.assert_equal(len(_ip.user_ns['In']), (_ip.displayhook.prompt_count + 1)) | 4,000,739,947,813,375,500 | Test that '%reset in' preserves In[] length | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_reset_in_length | Eviekim/waning-keyboard | python | def test_reset_in_length():
_ip.run_cell("print 'foo'")
_ip.run_cell('reset -f in')
nt.assert_equal(len(_ip.user_ns['In']), (_ip.displayhook.prompt_count + 1)) |
def test_tb_syntaxerror():
'test %tb after a SyntaxError'
ip = get_ipython()
ip.run_cell('for')
save_stdout = sys.stdout
try:
sys.stdout = StringIO()
ip.run_cell('%tb')
out = sys.stdout.getvalue()
finally:
sys.stdout = save_stdout
last_line = out.rstrip().splitlines()[(- 1)].strip()
nt.assert_equal(last_line, 'SyntaxError: invalid syntax') | 5,257,755,330,655,496,000 | test %tb after a SyntaxError | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_tb_syntaxerror | Eviekim/waning-keyboard | python | def test_tb_syntaxerror():
ip = get_ipython()
ip.run_cell('for')
save_stdout = sys.stdout
try:
sys.stdout = StringIO()
ip.run_cell('%tb')
out = sys.stdout.getvalue()
finally:
sys.stdout = save_stdout
last_line = out.rstrip().splitlines()[(- 1)].strip()
nt.assert_equal(last_line, 'SyntaxError: invalid syntax') |
def test_time3():
'Erroneous magic function calls, issue gh-3334'
ip = get_ipython()
ip.user_ns.pop('run', None)
with tt.AssertNotPrints('not found', channel='stderr'):
ip.run_cell('%%time\nrun = 0\nrun += 1') | 6,516,550,601,217,103,000 | Erroneous magic function calls, issue gh-3334 | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_time3 | Eviekim/waning-keyboard | python | def test_time3():
ip = get_ipython()
ip.user_ns.pop('run', None)
with tt.AssertNotPrints('not found', channel='stderr'):
ip.run_cell('%%time\nrun = 0\nrun += 1') |
def test_doctest_mode():
'Toggle doctest_mode twice, it should be a no-op and run without error'
_ip.magic('doctest_mode')
_ip.magic('doctest_mode') | -7,767,500,292,077,356,000 | Toggle doctest_mode twice, it should be a no-op and run without error | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_doctest_mode | Eviekim/waning-keyboard | python | def test_doctest_mode():
_ip.magic('doctest_mode')
_ip.magic('doctest_mode') |
def test_parse_options():
'Tests for basic options parsing in magics.'
m = DummyMagics(_ip)
nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') | -6,961,887,649,092,391,000 | Tests for basic options parsing in magics. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_parse_options | Eviekim/waning-keyboard | python | def test_parse_options():
m = DummyMagics(_ip)
nt.assert_equal(m.parse_options('foo', )[1], 'foo')
nt.assert_equal(m.parse_options(u'foo', )[1], u'foo') |
def test_dirops():
'Test various directory handling operations.'
curpath = os.getcwd
startdir = os.getcwd()
ipdir = os.path.realpath(_ip.ipython_dir)
try:
_ip.magic(('cd "%s"' % ipdir))
nt.assert_equal(curpath(), ipdir)
_ip.magic('cd -')
nt.assert_equal(curpath(), startdir)
_ip.magic(('pushd "%s"' % ipdir))
nt.assert_equal(curpath(), ipdir)
_ip.magic('popd')
nt.assert_equal(curpath(), startdir)
finally:
os.chdir(startdir) | 31,701,787,578,927,804 | Test various directory handling operations. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_dirops | Eviekim/waning-keyboard | python | def test_dirops():
curpath = os.getcwd
startdir = os.getcwd()
ipdir = os.path.realpath(_ip.ipython_dir)
try:
_ip.magic(('cd "%s"' % ipdir))
nt.assert_equal(curpath(), ipdir)
_ip.magic('cd -')
nt.assert_equal(curpath(), startdir)
_ip.magic(('pushd "%s"' % ipdir))
nt.assert_equal(curpath(), ipdir)
_ip.magic('popd')
nt.assert_equal(curpath(), startdir)
finally:
os.chdir(startdir) |
def test_cd_force_quiet():
'Test OSMagics.cd_force_quiet option'
_ip.config.OSMagics.cd_force_quiet = True
osmagics = osm.OSMagics(shell=_ip)
startdir = os.getcwd()
ipdir = os.path.realpath(_ip.ipython_dir)
try:
with tt.AssertNotPrints(ipdir):
osmagics.cd(('"%s"' % ipdir))
with tt.AssertNotPrints(startdir):
osmagics.cd('-')
finally:
os.chdir(startdir) | 5,560,686,867,166,068,000 | Test OSMagics.cd_force_quiet option | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_cd_force_quiet | Eviekim/waning-keyboard | python | def test_cd_force_quiet():
_ip.config.OSMagics.cd_force_quiet = True
osmagics = osm.OSMagics(shell=_ip)
startdir = os.getcwd()
ipdir = os.path.realpath(_ip.ipython_dir)
try:
with tt.AssertNotPrints(ipdir):
osmagics.cd(('"%s"' % ipdir))
with tt.AssertNotPrints(startdir):
osmagics.cd('-')
finally:
os.chdir(startdir) |
def doctest_who():
"doctest for %who\n \n In [1]: %reset -f\n \n In [2]: alpha = 123\n \n In [3]: beta = 'beta'\n \n In [4]: %who int\n alpha\n \n In [5]: %who str\n beta\n \n In [6]: %whos\n Variable Type Data/Info\n ----------------------------\n alpha int 123\n beta str beta\n \n In [7]: %who_ls\n Out[7]: ['alpha', 'beta']\n " | 8,755,219,741,932,612,000 | doctest for %who
In [1]: %reset -f
In [2]: alpha = 123
In [3]: beta = 'beta'
In [4]: %who int
alpha
In [5]: %who str
beta
In [6]: %whos
Variable Type Data/Info
----------------------------
alpha int 123
beta str beta
In [7]: %who_ls
Out[7]: ['alpha', 'beta'] | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | doctest_who | Eviekim/waning-keyboard | python | def doctest_who():
"doctest for %who\n \n In [1]: %reset -f\n \n In [2]: alpha = 123\n \n In [3]: beta = 'beta'\n \n In [4]: %who int\n alpha\n \n In [5]: %who str\n beta\n \n In [6]: %whos\n Variable Type Data/Info\n ----------------------------\n alpha int 123\n beta str beta\n \n In [7]: %who_ls\n Out[7]: ['alpha', 'beta']\n " |
def test_whos():
'Check that whos is protected against objects where repr() fails.'
class A(object):
def __repr__(self):
raise Exception()
_ip.user_ns['a'] = A()
_ip.magic('whos') | 5,035,898,423,616,851,000 | Check that whos is protected against objects where repr() fails. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_whos | Eviekim/waning-keyboard | python | def test_whos():
class A(object):
def __repr__(self):
raise Exception()
_ip.user_ns['a'] = A()
_ip.magic('whos') |
def doctest_precision():
"doctest for %precision\n \n In [1]: f = get_ipython().display_formatter.formatters['text/plain']\n \n In [2]: %precision 5\n Out[2]: '%.5f'\n \n In [3]: f.float_format\n Out[3]: '%.5f'\n \n In [4]: %precision %e\n Out[4]: '%e'\n \n In [5]: f(3.1415927)\n Out[5]: '3.141593e+00'\n " | 2,828,676,200,348,902,000 | doctest for %precision
In [1]: f = get_ipython().display_formatter.formatters['text/plain']
In [2]: %precision 5
Out[2]: '%.5f'
In [3]: f.float_format
Out[3]: '%.5f'
In [4]: %precision %e
Out[4]: '%e'
In [5]: f(3.1415927)
Out[5]: '3.141593e+00' | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | doctest_precision | Eviekim/waning-keyboard | python | def doctest_precision():
"doctest for %precision\n \n In [1]: f = get_ipython().display_formatter.formatters['text/plain']\n \n In [2]: %precision 5\n Out[2]: '%.5f'\n \n In [3]: f.float_format\n Out[3]: '%.5f'\n \n In [4]: %precision %e\n Out[4]: '%e'\n \n In [5]: f(3.1415927)\n Out[5]: '3.141593e+00'\n " |
def test_timeit_shlex():
'test shlex issues with timeit (#1109)'
_ip.ex('def f(*a,**kw): pass')
_ip.magic('timeit -n1 "this is a bug".count(" ")')
_ip.magic('timeit -r1 -n1 f(" ", 1)')
_ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
_ip.magic('timeit -r1 -n1 ("a " + "b")')
_ip.magic('timeit -r1 -n1 f("a " + "b")')
_ip.magic('timeit -r1 -n1 f("a " + "b ")') | -7,549,140,472,883,348,000 | test shlex issues with timeit (#1109) | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_timeit_shlex | Eviekim/waning-keyboard | python | def test_timeit_shlex():
_ip.ex('def f(*a,**kw): pass')
_ip.magic('timeit -n1 "this is a bug".count(" ")')
_ip.magic('timeit -r1 -n1 f(" ", 1)')
_ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
_ip.magic('timeit -r1 -n1 ("a " + "b")')
_ip.magic('timeit -r1 -n1 f("a " + "b")')
_ip.magic('timeit -r1 -n1 f("a " + "b ")') |
def test_timeit_special_syntax():
'Test %%timeit with IPython special syntax'
@register_line_magic
def lmagic(line):
ip = get_ipython()
ip.user_ns['lmagic_out'] = line
_ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
_ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') | -4,515,762,258,676,800,000 | Test %%timeit with IPython special syntax | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_timeit_special_syntax | Eviekim/waning-keyboard | python | def test_timeit_special_syntax():
@register_line_magic
def lmagic(line):
ip = get_ipython()
ip.user_ns['lmagic_out'] = line
_ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
_ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
def test_timeit_return():
'\n test whether timeit -o return object\n '
res = _ip.run_line_magic('timeit', '-n10 -r10 -o 1')
assert (res is not None) | 3,529,849,436,358,771,700 | test whether timeit -o return object | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_timeit_return | Eviekim/waning-keyboard | python | def test_timeit_return():
'\n \n '
res = _ip.run_line_magic('timeit', '-n10 -r10 -o 1')
assert (res is not None) |
def test_timeit_quiet():
'\n test quiet option of timeit magic\n '
with tt.AssertNotPrints('loops'):
_ip.run_cell('%timeit -n1 -r1 -q 1') | 8,973,642,439,119,941,000 | test quiet option of timeit magic | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_timeit_quiet | Eviekim/waning-keyboard | python | def test_timeit_quiet():
'\n \n '
with tt.AssertNotPrints('loops'):
_ip.run_cell('%timeit -n1 -r1 -q 1') |
@dec.skipif((execution.profile is None))
def test_prun_special_syntax():
'Test %%prun with IPython special syntax'
@register_line_magic
def lmagic(line):
ip = get_ipython()
ip.user_ns['lmagic_out'] = line
_ip.run_line_magic('prun', '-q %lmagic my line')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
_ip.run_cell_magic('prun', '-q', '%lmagic my line2')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') | -3,056,056,708,474,827,300 | Test %%prun with IPython special syntax | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_prun_special_syntax | Eviekim/waning-keyboard | python | @dec.skipif((execution.profile is None))
def test_prun_special_syntax():
@register_line_magic
def lmagic(line):
ip = get_ipython()
ip.user_ns['lmagic_out'] = line
_ip.run_line_magic('prun', '-q %lmagic my line')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
_ip.run_cell_magic('prun', '-q', '%lmagic my line2')
nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2') |
@dec.skipif((execution.profile is None))
def test_prun_quotes():
'Test that prun does not clobber string escapes (GH #1302)'
_ip.magic("prun -q x = '\\t'")
nt.assert_equal(_ip.user_ns['x'], '\t') | 2,248,573,152,805,703,700 | Test that prun does not clobber string escapes (GH #1302) | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_prun_quotes | Eviekim/waning-keyboard | python | @dec.skipif((execution.profile is None))
def test_prun_quotes():
_ip.magic("prun -q x = '\\t'")
nt.assert_equal(_ip.user_ns['x'], '\t') |
def test_file():
'Basic %%writefile'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) | -6,878,470,770,947,610,000 | Basic %%writefile | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file | Eviekim/waning-keyboard | python | def test_file():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) |
@dec.skip_win32
def test_file_single_quote():
'Basic %%writefile with embedded single quotes'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, "'file1'")
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) | 1,988,216,234,893,863,700 | Basic %%writefile with embedded single quotes | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_single_quote | Eviekim/waning-keyboard | python | @dec.skip_win32
def test_file_single_quote():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, "'file1'")
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) |
@dec.skip_win32
def test_file_double_quote():
'Basic %%writefile with embedded double quotes'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, '"file1"')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) | -7,567,954,485,837,707,000 | Basic %%writefile with embedded double quotes | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_double_quote | Eviekim/waning-keyboard | python | @dec.skip_win32
def test_file_double_quote():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, '"file1"')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) |
def test_file_var_expand():
'%%writefile $filename'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.user_ns['filename'] = fname
ip.run_cell_magic('writefile', '$filename', u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) | -6,383,253,492,045,151,000 | %%writefile $filename | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_var_expand | Eviekim/waning-keyboard | python | def test_file_var_expand():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.user_ns['filename'] = fname
ip.run_cell_magic('writefile', '$filename', u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) |
def test_file_unicode():
'%%writefile with unicode cell'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.run_cell_magic('writefile', fname, u'\n'.join([u'liné1', u'liné2']))
with io.open(fname, encoding='utf-8') as f:
s = f.read()
nt.assert_in(u'liné1\n', s)
nt.assert_in(u'liné2', s) | 7,117,541,322,255,569,000 | %%writefile with unicode cell | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_unicode | Eviekim/waning-keyboard | python | def test_file_unicode():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file1')
ip.run_cell_magic('writefile', fname, u'\n'.join([u'liné1', u'liné2']))
with io.open(fname, encoding='utf-8') as f:
s = f.read()
nt.assert_in(u'liné1\n', s)
nt.assert_in(u'liné2', s) |
def test_file_amend():
'%%writefile -a amends files'
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file2')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
ip.run_cell_magic('writefile', ('-a %s' % fname), u'\n'.join(['line3', 'line4']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line3\n', s) | 325,740,121,961,176,640 | %%writefile -a amends files | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_amend | Eviekim/waning-keyboard | python | def test_file_amend():
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file2')
ip.run_cell_magic('writefile', fname, u'\n'.join(['line1', 'line2']))
ip.run_cell_magic('writefile', ('-a %s' % fname), u'\n'.join(['line3', 'line4']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line3\n', s) |
def test_file_spaces():
'%%file with spaces in filename'
ip = get_ipython()
with TemporaryWorkingDirectory() as td:
fname = 'file name'
ip.run_cell_magic('file', ('"%s"' % fname), u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) | -4,706,583,299,978,310,000 | %%file with spaces in filename | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_file_spaces | Eviekim/waning-keyboard | python | def test_file_spaces():
ip = get_ipython()
with TemporaryWorkingDirectory() as td:
fname = 'file name'
ip.run_cell_magic('file', ('"%s"' % fname), u'\n'.join(['line1', 'line2']))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line2', s) |
def test_line_cell_info():
'%%foo and %foo magics are distinguishable to inspect'
ip = get_ipython()
ip.magics_manager.register(FooFoo)
oinfo = ip.object_inspect('foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
oinfo = ip.object_inspect('%%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
oinfo = ip.object_inspect('%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__) | -58,250,851,789,593,340 | %%foo and %foo magics are distinguishable to inspect | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_line_cell_info | Eviekim/waning-keyboard | python | def test_line_cell_info():
ip = get_ipython()
ip.magics_manager.register(FooFoo)
oinfo = ip.object_inspect('foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
oinfo = ip.object_inspect('%%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
oinfo = ip.object_inspect('%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__) |
def test_alias_magic():
'Test %alias_magic.'
ip = get_ipython()
mm = ip.magics_manager
ip.run_line_magic('alias_magic', 'timeit_alias timeit')
nt.assert_in('timeit_alias', mm.magics['line'])
nt.assert_in('timeit_alias', mm.magics['cell'])
ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
nt.assert_in('timeit_cell_alias', mm.magics['cell'])
ip.run_line_magic('alias_magic', '--line env_alias env')
nt.assert_equal(ip.run_line_magic('env', ''), ip.run_line_magic('env_alias', ''))
ip.run_line_magic('alias_magic', ('--line history_alias history --params ' + shlex.quote('3')))
nt.assert_in('history_alias', mm.magics['line']) | 4,597,338,510,386,205,700 | Test %alias_magic. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_alias_magic | Eviekim/waning-keyboard | python | def test_alias_magic():
ip = get_ipython()
mm = ip.magics_manager
ip.run_line_magic('alias_magic', 'timeit_alias timeit')
nt.assert_in('timeit_alias', mm.magics['line'])
nt.assert_in('timeit_alias', mm.magics['cell'])
ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
nt.assert_in('timeit_cell_alias', mm.magics['cell'])
ip.run_line_magic('alias_magic', '--line env_alias env')
nt.assert_equal(ip.run_line_magic('env', ), ip.run_line_magic('env_alias', ))
ip.run_line_magic('alias_magic', ('--line history_alias history --params ' + shlex.quote('3')))
nt.assert_in('history_alias', mm.magics['line']) |
def test_save():
'Test %save.'
ip = get_ipython()
ip.history_manager.reset()
cmds = [u'a=1', u'def b():\n return a**2', u'print(a, b())']
for (i, cmd) in enumerate(cmds, start=1):
ip.history_manager.store_inputs(i, cmd)
with TemporaryDirectory() as tmpdir:
file = os.path.join(tmpdir, 'testsave.py')
ip.run_line_magic('save', ('%s 1-10' % file))
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 1)
nt.assert_in('coding: utf-8', content)
ip.run_line_magic('save', ('-a %s 1-10' % file))
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 2)
nt.assert_in('coding: utf-8', content) | -6,427,175,446,546,929,000 | Test %save. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_save | Eviekim/waning-keyboard | python | def test_save():
ip = get_ipython()
ip.history_manager.reset()
cmds = [u'a=1', u'def b():\n return a**2', u'print(a, b())']
for (i, cmd) in enumerate(cmds, start=1):
ip.history_manager.store_inputs(i, cmd)
with TemporaryDirectory() as tmpdir:
file = os.path.join(tmpdir, 'testsave.py')
ip.run_line_magic('save', ('%s 1-10' % file))
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 1)
nt.assert_in('coding: utf-8', content)
ip.run_line_magic('save', ('-a %s 1-10' % file))
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 2)
nt.assert_in('coding: utf-8', content) |
def test_store():
'Test %store.'
ip = get_ipython()
ip.run_line_magic('load_ext', 'storemagic')
ip.run_line_magic('store', '-z')
ip.user_ns['var'] = 42
ip.run_line_magic('store', 'var')
ip.user_ns['var'] = 39
ip.run_line_magic('store', '-r')
nt.assert_equal(ip.user_ns['var'], 42)
ip.run_line_magic('store', '-d var')
ip.user_ns['var'] = 39
ip.run_line_magic('store', '-r')
nt.assert_equal(ip.user_ns['var'], 39) | -8,507,205,272,472,057,000 | Test %store. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_store | Eviekim/waning-keyboard | python | def test_store():
ip = get_ipython()
ip.run_line_magic('load_ext', 'storemagic')
ip.run_line_magic('store', '-z')
ip.user_ns['var'] = 42
ip.run_line_magic('store', 'var')
ip.user_ns['var'] = 39
ip.run_line_magic('store', '-r')
nt.assert_equal(ip.user_ns['var'], 42)
ip.run_line_magic('store', '-d var')
ip.user_ns['var'] = 39
ip.run_line_magic('store', '-r')
nt.assert_equal(ip.user_ns['var'], 39) |
def test_edit_interactive():
'%edit on interactively defined objects'
ip = get_ipython()
n = ip.execution_count
ip.run_cell(u'def foo(): return 1', store_history=True)
try:
_run_edit_test('foo')
except code.InteractivelyDefined as e:
nt.assert_equal(e.index, n)
else:
raise AssertionError('Should have raised InteractivelyDefined') | -8,840,566,195,997,727,000 | %edit on interactively defined objects | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_edit_interactive | Eviekim/waning-keyboard | python | def test_edit_interactive():
ip = get_ipython()
n = ip.execution_count
ip.run_cell(u'def foo(): return 1', store_history=True)
try:
_run_edit_test('foo')
except code.InteractivelyDefined as e:
nt.assert_equal(e.index, n)
else:
raise AssertionError('Should have raised InteractivelyDefined') |
def test_edit_cell():
'%edit [cell id]'
ip = get_ipython()
ip.run_cell(u'def foo(): return 1', store_history=True)
_run_edit_test('1', exp_contents=ip.user_ns['In'][1], exp_is_temp=True) | -6,894,415,927,910,532,000 | %edit [cell id] | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_edit_cell | Eviekim/waning-keyboard | python | def test_edit_cell():
ip = get_ipython()
ip.run_cell(u'def foo(): return 1', store_history=True)
_run_edit_test('1', exp_contents=ip.user_ns['In'][1], exp_is_temp=True) |
def test_timeit_arguments():
'Test valid timeit arguments, should not cause SyntaxError (GH #1269)'
if (sys.version_info < (3, 7)):
_ip.magic("timeit ('#')")
else:
_ip.magic("timeit a=('#')") | 3,697,592,057,748,278,000 | Test valid timeit arguments, should not cause SyntaxError (GH #1269) | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_timeit_arguments | Eviekim/waning-keyboard | python | def test_timeit_arguments():
if (sys.version_info < (3, 7)):
_ip.magic("timeit ('#')")
else:
_ip.magic("timeit a=('#')") |
def test_xdel(self):
'Test that references from %run are cleared by xdel.'
src = 'class A(object):\n monitor = []\n def __del__(self):\n self.monitor.append(1)\na = A()\n'
self.mktmp(src)
_ip.magic(('run %s' % self.fname))
_ip.run_cell('a')
monitor = _ip.user_ns['A'].monitor
nt.assert_equal(monitor, [])
_ip.magic('xdel a')
nt.assert_equal(monitor, [1]) | 8,204,104,169,131,365,000 | Test that references from %run are cleared by xdel. | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_xdel | Eviekim/waning-keyboard | python | def test_xdel(self):
src = 'class A(object):\n monitor = []\n def __del__(self):\n self.monitor.append(1)\na = A()\n'
self.mktmp(src)
_ip.magic(('run %s' % self.fname))
_ip.run_cell('a')
monitor = _ip.user_ns['A'].monitor
nt.assert_equal(monitor, [])
_ip.magic('xdel a')
nt.assert_equal(monitor, [1]) |
def test_cell_magic_func_deco(self):
'Cell magic using simple decorator'
@register_cell_magic
def cellm(line, cell):
return (line, cell)
self.check_ident('cellm') | 3,820,361,286,221,740,500 | Cell magic using simple decorator | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_cell_magic_func_deco | Eviekim/waning-keyboard | python | def test_cell_magic_func_deco(self):
@register_cell_magic
def cellm(line, cell):
return (line, cell)
self.check_ident('cellm') |
def test_cell_magic_reg(self):
'Cell magic manually registered'
def cellm(line, cell):
return (line, cell)
_ip.register_magic_function(cellm, 'cell', 'cellm2')
self.check_ident('cellm2') | -4,261,743,690,098,386,400 | Cell magic manually registered | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_cell_magic_reg | Eviekim/waning-keyboard | python | def test_cell_magic_reg(self):
def cellm(line, cell):
return (line, cell)
_ip.register_magic_function(cellm, 'cell', 'cellm2')
self.check_ident('cellm2') |
def test_cell_magic_class(self):
'Cell magics declared via a class'
@magics_class
class MyMagics(Magics):
@cell_magic
def cellm3(self, line, cell):
return (line, cell)
_ip.register_magics(MyMagics)
self.check_ident('cellm3') | 2,424,451,297,618,071,000 | Cell magics declared via a class | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_cell_magic_class | Eviekim/waning-keyboard | python | def test_cell_magic_class(self):
@magics_class
class MyMagics(Magics):
@cell_magic
def cellm3(self, line, cell):
return (line, cell)
_ip.register_magics(MyMagics)
self.check_ident('cellm3') |
def test_cell_magic_class2(self):
'Cell magics declared via a class, #2'
@magics_class
class MyMagics2(Magics):
@cell_magic('cellm4')
def cellm33(self, line, cell):
return (line, cell)
_ip.register_magics(MyMagics2)
self.check_ident('cellm4')
c33 = _ip.find_cell_magic('cellm33')
nt.assert_equal(c33, None) | -1,093,738,685,872,167,600 | Cell magics declared via a class, #2 | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | test_cell_magic_class2 | Eviekim/waning-keyboard | python | def test_cell_magic_class2(self):
@magics_class
class MyMagics2(Magics):
@cell_magic('cellm4')
def cellm33(self, line, cell):
return (line, cell)
_ip.register_magics(MyMagics2)
self.check_ident('cellm4')
c33 = _ip.find_cell_magic('cellm33')
nt.assert_equal(c33, None) |
@line_magic('foo')
def line_foo(self, line):
'I am line foo'
pass | -1,469,692,389,808,677,000 | I am line foo | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | line_foo | Eviekim/waning-keyboard | python | @line_magic('foo')
def line_foo(self, line):
pass |
@cell_magic('foo')
def cell_foo(self, line, cell):
'I am cell foo, not line foo'
pass | 4,865,368,112,887,540,000 | I am cell foo, not line foo | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | cell_foo | Eviekim/waning-keyboard | python | @cell_magic('foo')
def cell_foo(self, line, cell):
pass |
def _cmd(func):
'Define a wrapper to catch exceptions from the bulb.'
def _wrap(self, *args, **kwargs):
import yeelight
try:
_LOGGER.debug('Calling %s with %s %s', func, args, kwargs)
return func(self, *args, **kwargs)
except yeelight.BulbException as ex:
_LOGGER.error('Error when calling %s: %s', func, ex)
return _wrap | -7,863,031,810,190,473,000 | Define a wrapper to catch exceptions from the bulb. | homeassistant/components/light/yeelight.py | _cmd | DevRGT/home-assistant | python | def _cmd(func):
def _wrap(self, *args, **kwargs):
import yeelight
try:
_LOGGER.debug('Calling %s with %s %s', func, args, kwargs)
return func(self, *args, **kwargs)
except yeelight.BulbException as ex:
_LOGGER.error('Error when calling %s: %s', func, ex)
return _wrap |
def setup_platform(hass, config, add_devices, discovery_info=None):
'Set up the Yeelight bulbs.'
from yeelight.enums import PowerMode
if (DATA_KEY not in hass.data):
hass.data[DATA_KEY] = {}
lights = []
if (discovery_info is not None):
_LOGGER.debug('Adding autodetected %s', discovery_info['hostname'])
device_type = discovery_info['device_type']
device_type = LEGACY_DEVICE_TYPE_MAP.get(device_type, device_type)
name = ('yeelight_%s_%s' % (device_type, discovery_info['properties']['mac']))
host = discovery_info['host']
device = {'name': name, 'ipaddr': host}
light = YeelightLight(device, DEVICE_SCHEMA({}))
lights.append(light)
hass.data[DATA_KEY][host] = light
else:
for (host, device_config) in config[CONF_DEVICES].items():
device = {'name': device_config[CONF_NAME], 'ipaddr': host}
light = YeelightLight(device, device_config)
lights.append(light)
hass.data[DATA_KEY][host] = light
add_devices(lights, True)
def service_handler(service):
'Dispatch service calls to target entities.'
params = {key: value for (key, value) in service.data.items() if (key != ATTR_ENTITY_ID)}
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
target_devices = [dev for dev in hass.data[DATA_KEY].values() if (dev.entity_id in entity_ids)]
else:
target_devices = hass.data[DATA_KEY].values()
for target_device in target_devices:
if (service.service == SERVICE_SET_MODE):
target_device.set_mode(**params)
service_schema_set_mode = YEELIGHT_SERVICE_SCHEMA.extend({vol.Required(ATTR_MODE): vol.In([mode.name.lower() for mode in PowerMode])})
hass.services.register(DOMAIN, SERVICE_SET_MODE, service_handler, schema=service_schema_set_mode) | -6,626,384,890,780,107,000 | Set up the Yeelight bulbs. | homeassistant/components/light/yeelight.py | setup_platform | DevRGT/home-assistant | python | def setup_platform(hass, config, add_devices, discovery_info=None):
from yeelight.enums import PowerMode
if (DATA_KEY not in hass.data):
hass.data[DATA_KEY] = {}
lights = []
if (discovery_info is not None):
_LOGGER.debug('Adding autodetected %s', discovery_info['hostname'])
device_type = discovery_info['device_type']
device_type = LEGACY_DEVICE_TYPE_MAP.get(device_type, device_type)
name = ('yeelight_%s_%s' % (device_type, discovery_info['properties']['mac']))
host = discovery_info['host']
device = {'name': name, 'ipaddr': host}
light = YeelightLight(device, DEVICE_SCHEMA({}))
lights.append(light)
hass.data[DATA_KEY][host] = light
else:
for (host, device_config) in config[CONF_DEVICES].items():
device = {'name': device_config[CONF_NAME], 'ipaddr': host}
light = YeelightLight(device, device_config)
lights.append(light)
hass.data[DATA_KEY][host] = light
add_devices(lights, True)
def service_handler(service):
'Dispatch service calls to target entities.'
params = {key: value for (key, value) in service.data.items() if (key != ATTR_ENTITY_ID)}
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
target_devices = [dev for dev in hass.data[DATA_KEY].values() if (dev.entity_id in entity_ids)]
else:
target_devices = hass.data[DATA_KEY].values()
for target_device in target_devices:
if (service.service == SERVICE_SET_MODE):
target_device.set_mode(**params)
service_schema_set_mode = YEELIGHT_SERVICE_SCHEMA.extend({vol.Required(ATTR_MODE): vol.In([mode.name.lower() for mode in PowerMode])})
hass.services.register(DOMAIN, SERVICE_SET_MODE, service_handler, schema=service_schema_set_mode) |
def service_handler(service):
'Dispatch service calls to target entities.'
params = {key: value for (key, value) in service.data.items() if (key != ATTR_ENTITY_ID)}
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
target_devices = [dev for dev in hass.data[DATA_KEY].values() if (dev.entity_id in entity_ids)]
else:
target_devices = hass.data[DATA_KEY].values()
for target_device in target_devices:
if (service.service == SERVICE_SET_MODE):
target_device.set_mode(**params) | -4,544,214,911,477,238,300 | Dispatch service calls to target entities. | homeassistant/components/light/yeelight.py | service_handler | DevRGT/home-assistant | python | def service_handler(service):
params = {key: value for (key, value) in service.data.items() if (key != ATTR_ENTITY_ID)}
entity_ids = service.data.get(ATTR_ENTITY_ID)
if entity_ids:
target_devices = [dev for dev in hass.data[DATA_KEY].values() if (dev.entity_id in entity_ids)]
else:
target_devices = hass.data[DATA_KEY].values()
for target_device in target_devices:
if (service.service == SERVICE_SET_MODE):
target_device.set_mode(**params) |
def __init__(self, device, config):
'Initialize the Yeelight light.'
self.config = config
self._name = device['name']
self._ipaddr = device['ipaddr']
self._supported_features = SUPPORT_YEELIGHT
self._available = False
self._bulb_device = None
self._brightness = None
self._color_temp = None
self._is_on = None
self._hs = None | -8,450,211,671,903,045,000 | Initialize the Yeelight light. | homeassistant/components/light/yeelight.py | __init__ | DevRGT/home-assistant | python | def __init__(self, device, config):
self.config = config
self._name = device['name']
self._ipaddr = device['ipaddr']
self._supported_features = SUPPORT_YEELIGHT
self._available = False
self._bulb_device = None
self._brightness = None
self._color_temp = None
self._is_on = None
self._hs = None |