input
stringlengths 11
7.65k
| target
stringlengths 22
8.26k
|
---|---|
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def compute_svm_cv(K, y, C=100.0, n_folds=5,
scoring=balanced_accuracy_scoring):
"""Compute cross-validated score of SVM with given precomputed kernel.
"""
cv = StratifiedKFold(y, n_folds=n_folds)
clf = SVC(C=C, kernel='precomputed', class_weight='auto')
scores = cross_val_score(clf, K, y,
scoring=scoring, cv=cv)
return scores.mean() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def compute_svm_subjects(K, y, n_folds=5):
"""
"""
cv = KFold(len(K)/2, n_folds)
scores = np.zeros(n_folds)
for i, (train, test) in enumerate(cv):
train_ids = np.concatenate((train, len(K)/2+train))
test_ids = np.concatenate((test, len(K)/2+test))
clf = SVC(kernel='precomputed')
clf.fit(K[train_ids, :][:, train_ids], y[train_ids])
scores[i] = clf.score(K[test_ids, :][:, train_ids], y[test_ids])
return scores.mean() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def permutation_subjects(y):
"""Permute class labels of Contextual Disorder dataset.
"""
y_perm = np.random.randint(0, 2, len(y)/2)
y_perm = np.concatenate((y_perm, np.logical_not(y_perm).astype(int)))
return y_perm |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def permutation_subjects_ktst(y):
"""Permute class labels of Contextual Disorder dataset for KTST.
"""
yp = np.random.randint(0, 2, len(y)/2)
yp = np.concatenate((yp, np.logical_not(yp).astype(int)))
y_perm = np.arange(len(y))
for i in range(len(y)/2):
if yp[i] == 1:
y_perm[i] = len(y)/2+i
y_perm[len(y)/2+i] = i
return y_perm |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def compute_svm_score_nestedCV(K, y, n_folds,
scoring=balanced_accuracy_scoring,
random_state=None,
param_grid=[{'C': np.logspace(-5, 5, 25)}]):
"""Compute cross-validated score of SVM using precomputed kernel.
"""
cv = StratifiedKFold(y, n_folds=n_folds, shuffle=True,
random_state=random_state)
scores = np.zeros(n_folds)
for i, (train, test) in enumerate(cv):
cvclf = SVC(kernel='precomputed')
y_train = y[train]
cvcv = StratifiedKFold(y_train, n_folds=n_folds,
shuffle=True,
random_state=random_state)
clf = GridSearchCV(cvclf, param_grid=param_grid, scoring=scoring,
cv=cvcv, n_jobs=1)
clf.fit(K[train, :][:, train], y_train)
# print clf.best_params_
scores[i] = clf.score(K[test, :][:, train], y[test])
return scores.mean() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def apply_svm(K, y, n_folds=5, iterations=10000, subjects=False, verbose=True,
random_state=None):
"""
Compute the balanced accuracy, its null distribution and the p-value.
Parameters:
----------
K: array-like
Kernel matrix
y: array_like
class labels
cv: Number of folds in the stratified cross-validation
verbose: bool
Verbosity
Returns:
-------
acc: float
Average balanced accuracy.
acc_null: array
Null distribution of the balanced accuracy.
p_value: float
p-value
"""
# Computing the accuracy
param_grid = [{'C': np.logspace(-5, 5, 20)}]
if subjects:
acc = compute_svm_subjects(K, y, n_folds)
else:
acc = compute_svm_score_nestedCV(K, y, n_folds, param_grid=param_grid,
random_state=random_state)
if verbose:
print("Mean balanced accuracy = %s" % (acc))
print("Computing the null-distribution.")
# Computing the null-distribution
# acc_null = np.zeros(iterations)
# for i in range(iterations):
# if verbose and (i % 1000) == 0:
# print(i),
# stdout.flush()
# y_perm = np.random.permutation(y)
# acc_null[i] = compute_svm_score_nestedCV(K, y_perm, n_folds,
# param_grid=param_grid)
# if verbose:
# print ''
# Computing the null-distribution
if subjects:
yis = [permutation_subjects(y) for i in range(iterations)]
acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_subjects)(K, yis[i], n_folds) for i in range(iterations))
else:
yis = [np.random.permutation(y) for i in range(iterations)]
acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_score_nestedCV)(K, yis[i], n_folds, scoring=balanced_accuracy_scoring, param_grid=param_grid) for i in range(iterations))
# acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_cv)(K, yis[i], C=100., n_folds=n_folds) for i in range(iterations))
p_value = max(1.0 / iterations, (acc_null > acc).sum()
/ float(iterations))
if verbose:
print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations))
return acc, acc_null, p_value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def apply_ktst(K, y, iterations=10000, subjects=False, verbose=True):
"""
Compute MMD^2_u, its null distribution and the p-value of the
kernel two-sample test.
Parameters:
----------
K: array-like
Kernel matrix
y: array_like
class labels
verbose: bool
Verbosity
Returns:
-------
mmd2u: float
MMD^2_u value.
acc_null: array
Null distribution of the MMD^2_u
p_value: float
p-value
"""
assert len(np.unique(y)) == 2, 'KTST only works on binary problems'
# Assuming that the first m rows of the kernel matrix are from one
# class and the other n rows from the second class.
m = len(y[y == 0])
n = len(y[y == 1])
mmd2u = MMD2u(K, m, n)
if verbose:
print("MMD^2_u = %s" % mmd2u)
print("Computing the null distribution.")
if subjects:
perms = [permutation_subjects_ktst(y) for i in range(iterations)]
mmd2u_null = compute_null_distribution_given_permutations(K, m, n,
perms,
iterations)
else:
mmd2u_null = compute_null_distribution(K, m, n, iterations,
verbose=verbose)
p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum()
/ float(iterations))
if verbose:
print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations))
return mmd2u, mmd2u_null, p_value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_login(self, mock_login_with_token, mock_input, mock_open_url):
quilt3.login()
url = quilt3.session.get_registry_url()
mock_open_url.assert_called_with(f'{url}/login')
mock_login_with_token.assert_called_with('123456') |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def decode(value):
if isinstance(value, bytes):
value = value.decode(errors="surrogateescape")
for char in ("\\", "\n", "\t"):
value = value.replace(
char.encode(encoding="unicode-escape").decode(), char
)
return value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def test_login_with_token(self, mock_save_credentials, mock_save_auth):
url = quilt3.session.get_registry_url()
mock_auth = dict(
refresh_token='refresh-token',
access_token='access-token',
expires_at=123456789
)
self.requests_mock.add(
responses.POST,
f'{url}/api/token',
json=mock_auth,
status=200
)
self.requests_mock.add(
responses.GET,
f'{url}/api/auth/get_credentials',
json=dict(
AccessKeyId='access-key',
SecretAccessKey='secret-key',
SessionToken='session-token',
Expiration="2019-05-28T23:58:07+00:00"
),
status=200
)
quilt3.session.login_with_token('123456')
mock_save_auth.assert_called_with({url: mock_auth})
mock_save_credentials.assert_called_with(dict(
access_key='access-key',
secret_key='secret-key',
token='session-token',
expiry_time="2019-05-28T23:58:07+00:00"
)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def encode(value):
if isinstance(value, bytes):
value = value.decode(errors="surrogateescape")
for char in ("\\", "\n", "\t"):
value = value.replace(
char, char.encode(encoding="unicode-escape").decode()
)
return value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def format_date(date):
return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
"""Cast raw string to appropriate type."""
return decode(value) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
"""Convert value back to string for saving."""
if value is None:
return ""
return str(value) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
return DeprecatedValue() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
return DeprecatedValue() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, optional=False, choices=None):
self._required = not optional
self._choices = choices |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value).strip()
validators.validate_required(value, self._required)
if not value:
return None
validators.validate_choice(value, self._choices)
return value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
if value is None:
return ""
return encode(value) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, optional=False, choices=None):
self._required = not optional
self._choices = None # Choices doesn't make sense for secrets |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
if value is not None and display:
return "********"
return super().serialize(value, display) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(
self, minimum=None, maximum=None, choices=None, optional=False
):
self._required = not optional
self._minimum = minimum
self._maximum = maximum
self._choices = choices |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value)
validators.validate_required(value, self._required)
if not value:
return None
value = int(value)
validators.validate_choice(value, self._choices)
validators.validate_minimum(value, self._minimum)
validators.validate_maximum(value, self._maximum)
return value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, optional=False):
self._required = not optional |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value)
validators.validate_required(value, self._required)
if not value:
return None
if value.lower() in self.true_values:
return True
elif value.lower() in self.false_values:
return False
raise ValueError(f"invalid value for boolean: {value!r}") |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
if value is True:
return "true"
elif value in (False, None):
return "false"
else:
raise ValueError(f"{value!r} is not a boolean") |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value)
if "\n" in value:
values = re.split(r"\s*\n\s*", value)
else:
values = re.split(r"\s*,\s*", value)
values = tuple(v.strip() for v in values if v.strip())
validators.validate_required(values, self._required)
return tuple(values) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
if not value:
return ""
return "\n " + "\n ".join(encode(v) for v in value if v) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value)
validators.validate_choice(value.lower(), log.COLORS)
return value.lower() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
if value.lower() in log.COLORS:
return encode(value.lower())
return "" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value)
validators.validate_choice(value.lower(), self.levels.keys())
return self.levels.get(value.lower()) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize(self, value, display=False):
lookup = {v: k for k, v in self.levels.items()}
if value in lookup:
return encode(lookup[value])
return "" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value, display=False):
value = decode(value).strip()
validators.validate_required(value, self._required)
if not value:
return None
socket_path = path.get_unix_socket_path(value)
if socket_path is not None:
path_str = Path(not self._required).deserialize(socket_path)
return f"unix:{path_str}"
try:
socket.getaddrinfo(value, None)
except OSError:
raise ValueError("must be a resolveable hostname or valid IP")
return value |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, choices=None, optional=False):
super().__init__(
minimum=0, maximum=2 ** 16 - 1, choices=choices, optional=optional
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __new__(cls, original, expanded):
return super().__new__(cls, expanded) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, original, expanded):
self.original = original |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def deserialize(self, value):
value = decode(value).strip()
expanded = path.expand_path(value)
validators.validate_required(value, self._required)
validators.validate_required(expanded, self._required)
if not value or expanded is None:
return None
return _ExpandedPath(value, expanded) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, msg):
super(TransactionError, self).__init__(msg) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, branch, package):
Base.__init__(self)
self.branch = branch
self.package = package
self.sp_obj = None |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, filename, errors):
"""
:param filename: The name of the transaction file being replayed
:param errors: a list of error classes or a string with an error description
"""
# store args in case someone wants to read them from a caught exception
self.filename = filename
if isinstance(errors, (list, tuple)):
self.errors = errors
else:
self.errors = [errors]
if filename:
msg = _('The following problems occurred while replaying the transaction from file "{filename}":').format(filename=filename)
else:
msg = _('The following problems occurred while running a transaction:')
for error in self.errors:
msg += "\n " + str(error)
super(TransactionReplayError, self).__init__(msg) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def parse(self):
f = tempfile.NamedTemporaryFile(delete=True)
cmd_str = "curl http://pkgs.fedoraproject.org/cgit/rpms/%s.git/plain/%s.spec > %s"
runCommand(cmd_str % (self.package, self.package, f.name))
self.sp_obj = SpecParser(f.name)
if not self.sp_obj.parse():
self.err = self.sp_obj.getError()
f.close()
return False
f.close()
return True |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, filename, msg):
super(IncompatibleTransactionVersionError, self).__init__(filename, msg) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def getProvides(self):
"""Fetch a spec file from pkgdb and get provides from all its [sub]packages"""
if self.sp_obj == None:
return {}
return self.sp_obj.getProvides() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _check_version(version, filename):
major, minor = version.split('.')
try:
major = int(major)
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid major version "{major}", number expected.').format(major=major)
)
try:
int(minor) # minor is unused, just check it's a number
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid minor version "{minor}", number expected.').format(minor=minor)
)
if major != VERSION_MAJOR:
raise IncompatibleTransactionVersionError(
filename,
_('Incompatible major version "{major}", supported major version is "{major_supp}".')
.format(major=major, major_supp=VERSION_MAJOR)
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def getPackageCommits(self):
if self.sp_obj == None:
return ""
return self.sp_obj.getMacro("commit") |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def serialize_transaction(transaction):
"""
Serializes a transaction to a data structure that is equivalent to the stored JSON format.
:param transaction: the transaction to serialize (an instance of dnf.db.history.TransactionWrapper)
"""
data = {
"version": VERSION,
}
rpms = []
groups = []
environments = []
if transaction is None:
return data
for tsi in transaction.packages():
if tsi.is_package():
rpms.append({
"action": tsi.action_name,
"nevra": tsi.nevra,
"reason": libdnf.transaction.TransactionItemReasonToString(tsi.reason),
"repo_id": tsi.from_repo
})
elif tsi.is_group():
group = tsi.get_group()
group_data = {
"action": tsi.action_name,
"id": group.getGroupId(),
"packages": [],
"package_types": libdnf.transaction.compsPackageTypeToString(group.getPackageTypes())
}
for pkg in group.getPackages():
group_data["packages"].append({
"name": pkg.getName(),
"installed": pkg.getInstalled(),
"package_type": libdnf.transaction.compsPackageTypeToString(pkg.getPackageType())
})
groups.append(group_data)
elif tsi.is_environment():
env = tsi.get_environment()
env_data = {
"action": tsi.action_name,
"id": env.getEnvironmentId(),
"groups": [],
"package_types": libdnf.transaction.compsPackageTypeToString(env.getPackageTypes())
}
for grp in env.getGroups():
env_data["groups"].append({
"id": grp.getGroupId(),
"installed": grp.getInstalled(),
"group_type": libdnf.transaction.compsPackageTypeToString(grp.getGroupType())
})
environments.append(env_data)
if rpms:
data["rpms"] = rpms
if groups:
data["groups"] = groups
if environments:
data["environments"] = environments
return data |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(
self,
base,
filename="",
data=None,
ignore_extras=False,
ignore_installed=False,
skip_unavailable=False
):
"""
:param base: the dnf base
:param filename: the filename to load the transaction from (conflicts with the 'data' argument)
:param data: the dictionary to load the transaction from (conflicts with the 'filename' argument)
:param ignore_extras: whether to ignore extra package pulled into the transaction
:param ignore_installed: whether to ignore installed versions of packages
:param skip_unavailable: whether to skip transaction packages that aren't available
"""
self._base = base
self._filename = filename
self._ignore_installed = ignore_installed
self._ignore_extras = ignore_extras
self._skip_unavailable = skip_unavailable
if not self._base.conf.strict:
self._skip_unavailable = True
self._nevra_cache = set()
self._nevra_reason_cache = {}
self._warnings = []
if filename and data:
raise ValueError(_("Conflicting TransactionReplay arguments have been specified: filename, data"))
elif filename:
self._load_from_file(filename)
else:
self._load_from_data(data) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _load_from_file(self, fn):
self._filename = fn
with open(fn, "r") as f:
try:
replay_data = json.load(f)
except json.decoder.JSONDecodeError as e:
raise TransactionReplayError(fn, str(e) + ".")
try:
self._load_from_data(replay_data)
except TransactionError as e:
raise TransactionReplayError(fn, e) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _load_from_data(self, data):
self._replay_data = data
self._verify_toplevel_json(self._replay_data)
self._rpms = self._replay_data.get("rpms", [])
self._assert_type(self._rpms, list, "rpms", "array")
self._groups = self._replay_data.get("groups", [])
self._assert_type(self._groups, list, "groups", "array")
self._environments = self._replay_data.get("environments", [])
self._assert_type(self._environments, list, "environments", "array") |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _raise_or_warn(self, warn_only, msg):
if warn_only:
self._warnings.append(msg)
else:
raise TransactionError(msg) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _assert_type(self, value, t, id, expected):
if not isinstance(value, t):
raise TransactionError(_('Unexpected type of "{id}", {exp} expected.').format(id=id, exp=expected)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _verify_toplevel_json(self, replay_data):
fn = self._filename
if "version" not in replay_data:
raise TransactionReplayError(fn, _('Missing key "{key}".'.format(key="version")))
self._assert_type(replay_data["version"], str, "version", "string")
_check_version(replay_data["version"], fn) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _replay_pkg_action(self, pkg_data):
try:
action = pkg_data["action"]
nevra = pkg_data["nevra"]
repo_id = pkg_data["repo_id"]
reason = libdnf.transaction.StringToTransactionItemReason(pkg_data["reason"])
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in an rpm.').format(key=e.args[0])
)
except IndexError as e:
raise TransactionError(
_('Unexpected value of package reason "{reason}" for rpm nevra "{nevra}".')
.format(reason=pkg_data["reason"], nevra=nevra)
)
subj = hawkey.Subject(nevra)
parsed_nevras = subj.get_nevra_possibilities(forms=[hawkey.FORM_NEVRA])
if len(parsed_nevras) != 1:
raise TransactionError(_('Cannot parse NEVRA for package "{nevra}".').format(nevra=nevra))
parsed_nevra = parsed_nevras[0]
na = "%s.%s" % (parsed_nevra.name, parsed_nevra.arch)
query_na = self._base.sack.query().filter(name=parsed_nevra.name, arch=parsed_nevra.arch)
epoch = parsed_nevra.epoch if parsed_nevra.epoch is not None else 0
query = query_na.filter(epoch=epoch, version=parsed_nevra.version, release=parsed_nevra.release)
# In case the package is found in the same repo as in the original
# transaction, limit the query to that plus installed packages. IOW
# remove packages with the same NEVRA in case they are found in
# multiple repos and the repo the package came from originally is one
# of them.
# This can e.g. make a difference in the system-upgrade plugin, in case
# the same NEVRA is in two repos, this makes sure the same repo is used
# for both download and upgrade steps of the plugin.
if repo_id:
query_repo = query.filter(reponame=repo_id)
if query_repo:
query = query_repo.union(query.installed())
if not query:
self._raise_or_warn(self._skip_unavailable, _('Cannot find rpm nevra "{nevra}".').format(nevra=nevra))
return
# a cache to check no extra packages were pulled into the transaction
if action != "Reason Change":
self._nevra_cache.add(nevra)
# store reasons for forward actions and "Removed", the rest of the
# actions reasons should stay as they were determined by the transaction
if action in ("Install", "Upgrade", "Downgrade", "Reinstall", "Removed"):
self._nevra_reason_cache[nevra] = reason
if action in ("Install", "Upgrade", "Downgrade"):
if action == "Install" and query_na.installed() and not self._base._get_installonly_query(query_na):
self._raise_or_warn(self._ignore_installed,
_('Package "{na}" is already installed for action "{action}".').format(na=na, action=action))
sltr = dnf.selector.Selector(self._base.sack).set(pkg=query)
self._base.goal.install(select=sltr, optional=not self._base.conf.strict)
elif action == "Reinstall":
query = query.available()
if not query:
self._raise_or_warn(self._skip_unavailable,
_('Package nevra "{nevra}" not available in repositories for action "{action}".')
.format(nevra=nevra, action=action))
return
sltr = dnf.selector.Selector(self._base.sack).set(pkg=query)
self._base.goal.install(select=sltr, optional=not self._base.conf.strict)
elif action in ("Upgraded", "Downgraded", "Reinstalled", "Removed", "Obsoleted"):
query = query.installed()
if not query:
self._raise_or_warn(self._ignore_installed,
_('Package nevra "{nevra}" not installed for action "{action}".').format(nevra=nevra, action=action))
return
# erasing the original version (the reverse part of an action like
# e.g. upgrade) is more robust, but we can't do it if
# skip_unavailable is True, because if the forward part of the
# action is skipped, we would simply remove the package here
if not self._skip_unavailable or action == "Removed":
for pkg in query:
self._base.goal.erase(pkg, clean_deps=False)
elif action == "Reason Change":
self._base.history.set_reason(query[0], reason)
else:
raise TransactionError(
_('Unexpected value of package action "{action}" for rpm nevra "{nevra}".')
.format(action=action, nevra=nevra)
) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _create_swdb_group(self, group_id, pkg_types, pkgs):
comps_group = self._base.comps._group_by_id(group_id)
if not comps_group:
self._raise_or_warn(self._skip_unavailable, _("Group id '%s' is not available.") % group_id)
return None
swdb_group = self._base.history.group.new(group_id, comps_group.name, comps_group.ui_name, pkg_types)
try:
for pkg in pkgs:
name = pkg["name"]
self._assert_type(name, str, "groups.packages.name", "string")
installed = pkg["installed"]
self._assert_type(installed, bool, "groups.packages.installed", "boolean")
package_type = pkg["package_type"]
self._assert_type(package_type, str, "groups.packages.package_type", "string")
try:
swdb_group.addPackage(name, installed, libdnf.transaction.stringToCompsPackageType(package_type))
except libdnf.error.Error as e:
raise TransactionError(str(e))
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in groups.packages.').format(key=e.args[0])
)
return swdb_group |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_group_install(self, group_id, pkg_types, pkgs):
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.install(swdb_group) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_group_upgrade(self, group_id, pkg_types, pkgs):
if not self._base.history.group.get(group_id):
self._raise_or_warn( self._ignore_installed, _("Group id '%s' is not installed.") % group_id)
return
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.upgrade(swdb_group) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_group_remove(self, group_id, pkg_types, pkgs):
if not self._base.history.group.get(group_id):
self._raise_or_warn(self._ignore_installed, _("Group id '%s' is not installed.") % group_id)
return
swdb_group = self._create_swdb_group(group_id, pkg_types, pkgs)
if swdb_group is not None:
self._base.history.group.remove(swdb_group) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _create_swdb_environment(self, env_id, pkg_types, groups):
comps_env = self._base.comps._environment_by_id(env_id)
if not comps_env:
self._raise_or_warn(self._skip_unavailable, _("Environment id '%s' is not available.") % env_id)
return None
swdb_env = self._base.history.env.new(env_id, comps_env.name, comps_env.ui_name, pkg_types)
try:
for grp in groups:
id = grp["id"]
self._assert_type(id, str, "environments.groups.id", "string")
installed = grp["installed"]
self._assert_type(installed, bool, "environments.groups.installed", "boolean")
group_type = grp["group_type"]
self._assert_type(group_type, str, "environments.groups.group_type", "string")
try:
group_type = libdnf.transaction.stringToCompsPackageType(group_type)
except libdnf.error.Error as e:
raise TransactionError(str(e))
if group_type not in (
libdnf.transaction.CompsPackageType_MANDATORY,
libdnf.transaction.CompsPackageType_OPTIONAL
):
raise TransactionError(
_('Invalid value "{group_type}" of environments.groups.group_type, '
'only "mandatory" or "optional" is supported.'
).format(group_type=grp["group_type"])
)
swdb_env.addGroup(id, installed, group_type)
except KeyError as e:
raise TransactionError(
_('Missing object key "{key}" in environments.groups.').format(key=e.args[0])
)
return swdb_env |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_environment_install(self, env_id, pkg_types, groups):
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.install(swdb_env) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_environment_upgrade(self, env_id, pkg_types, groups):
if not self._base.history.env.get(env_id):
self._raise_or_warn(self._ignore_installed,_("Environment id '%s' is not installed.") % env_id)
return
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.upgrade(swdb_env) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _swdb_environment_remove(self, env_id, pkg_types, groups):
if not self._base.history.env.get(env_id):
self._raise_or_warn(self._ignore_installed, _("Environment id '%s' is not installed.") % env_id)
return
swdb_env = self._create_swdb_environment(env_id, pkg_types, groups)
if swdb_env is not None:
self._base.history.env.remove(swdb_env) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_data(self):
"""
:returns: the loaded data of the transaction
"""
return self._replay_data |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_warnings(self):
"""
:returns: an array of warnings gathered during the transaction replay
"""
return self._warnings |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def run(self):
"""
Replays the transaction.
"""
fn = self._filename
errors = []
for pkg_data in self._rpms:
try:
self._replay_pkg_action(pkg_data)
except TransactionError as e:
errors.append(e)
for group_data in self._groups:
try:
action = group_data["action"]
group_id = group_data["id"]
try:
pkg_types = libdnf.transaction.stringToCompsPackageType(group_data["package_types"])
except libdnf.error.Error as e:
errors.append(TransactionError(str(e)))
continue
if action == "Install":
self._swdb_group_install(group_id, pkg_types, group_data["packages"])
elif action == "Upgrade":
self._swdb_group_upgrade(group_id, pkg_types, group_data["packages"])
elif action == "Removed":
self._swdb_group_remove(group_id, pkg_types, group_data["packages"])
else:
errors.append(TransactionError(
_('Unexpected value of group action "{action}" for group "{group}".')
.format(action=action, group=group_id)
))
except KeyError as e:
errors.append(TransactionError(
_('Missing object key "{key}" in a group.').format(key=e.args[0])
))
except TransactionError as e:
errors.append(e)
for env_data in self._environments:
try:
action = env_data["action"]
env_id = env_data["id"]
try:
pkg_types = libdnf.transaction.stringToCompsPackageType(env_data["package_types"])
except libdnf.error.Error as e:
errors.append(TransactionError(str(e)))
continue
if action == "Install":
self._swdb_environment_install(env_id, pkg_types, env_data["groups"])
elif action == "Upgrade":
self._swdb_environment_upgrade(env_id, pkg_types, env_data["groups"])
elif action == "Removed":
self._swdb_environment_remove(env_id, pkg_types, env_data["groups"])
else:
errors.append(TransactionError(
_('Unexpected value of environment action "{action}" for environment "{env}".')
.format(action=action, env=env_id)
))
except KeyError as e:
errors.append(TransactionError(
_('Missing object key "{key}" in an environment.').format(key=e.args[0])
))
except TransactionError as e:
errors.append(e)
if errors:
raise TransactionReplayError(fn, errors) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def has_ext_modules(self):
return True |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, host, loginUser, debug = False, trace = False, log=None, port=22, pexpectObject=None):
self.pexpect = pexpect if not pexpectObject else pexpectObject
self.debug = debug
self.trace = trace
self.host = host
self._port = port
self._connection = None
self.modeList = []
self._log = log
self._bufferedCommands = None
self._bufferedMode = None
self._loginUser = loginUser
self._resetExpect() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def finalize_options(self):
ret = InstallCommandBase.finalize_options(self)
self.install_headers = os.path.join(self.install_purelib,
'tensorflow', 'include')
return ret |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __del__(self):
self.closeCliConnectionTo() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def initialize_options(self):
self.install_dir = None
self.force = 0
self.outfiles = [] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def showOutputOnScreen(self):
self.debug = True
self.trace = True
self._log = None
self._setupLog() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def finalize_options(self):
self.set_undefined_options('install',
('install_headers', 'install_dir'),
('force', 'force')) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def connectWithSsh(self):
self._debugLog("Establishing connection to " + self.host)
self._connection = self.pexpect.spawn(
'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s -p %d' %
(self._loginUser.username, self.host, self._port))
if self._connection is None:
raise Exception("Unable to connect via SSH perhaps wrong IP!")
self._secure = True
self._setupLog()
self._loginUser.commandLine(self)
self.modeList = [self._loginUser] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def mkdir_and_copy_file(self, header):
install_dir = os.path.join(self.install_dir, os.path.dirname(header))
# Get rid of some extra intervening directories so we can have fewer
# directories for -I
install_dir = re.sub('/google/protobuf_archive/src', '', install_dir)
# Copy eigen code into tensorflow/include.
# A symlink would do, but the wheel file that gets created ignores
# symlink within the directory hierarchy.
# NOTE(keveman): Figure out how to customize bdist_wheel package so
# we can do the symlink.
if 'external/eigen_archive/' in install_dir:
extra_dir = install_dir.replace('external/eigen_archive', '')
if not os.path.exists(extra_dir):
self.mkpath(extra_dir)
self.copy_file(header, extra_dir)
if not os.path.exists(install_dir):
self.mkpath(install_dir)
return self.copy_file(header, install_dir) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def resetLoggingTo(self, log):
self._connection.logfile = log |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def run(self):
hdrs = self.distribution.headers
if not hdrs:
return
self.mkpath(self.install_dir)
for header in hdrs:
(out, _) = self.mkdir_and_copy_file(header)
self.outfiles.append(out) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def write(self, s):
sys.stdout.buffer.write(s) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_inputs(self):
return self.distribution.headers or [] |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def flush(self):
sys.stdout.flush() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_outputs(self):
return self.outfiles |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def loginSsh(self):
self._setupLog()
self._debugLog("Login in as "+self._loginUser.username)
try:
self._loginUser.sendPassword()
return True
except Exception as e:
self.forceCloseCliConnectionTo()
raise Exception('Exception ('+str(e)+') '+'Expected CLI response: "Password:"' + "\n Got: \n" + self._lastExpect()) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def find_files(pattern, root):
"""Return all the files matching pattern below root dir."""
for path, _, files in os.walk(root):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _exit_modes_beyond(self, thisMode):
if not self.modeList: return
while len(self.modeList) > thisMode + 1:
self.modeList.pop().exit() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def exitMode(self, mode):
if mode in self.modeList:
self.modeList.remove(mode) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def check_prereq(self, prereqMode = 0):
self._exit_modes_beyond(prereqMode)
if len(self.modeList) <= prereqMode:
raise Exception("Attempted to enter menu when prerequist mode was not entered, expected: %d" % prereqMode) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def execute_as(self, user):
self.check_prereq(self.LOGGED_IN)
self._exit_modes_beyond(self.LOGGED_IN)
user.commandLine(self)
user.login()
self.modeList.append(user)
return user |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def closeCliConnectionTo(self):
if self._connection == None:
return
self._exit_modes_beyond(-1)
self.modeList = []
self._debugLog("Exited all modes.")
self.forceCloseCliConnectionTo() |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def forceCloseCliConnectionTo(self):
self.modeList = None
if self._connection:
self._debugLog("Closing connection.")
self._connection.close()
self._connection = None |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _debugLog(self, message):
if self.debug:
print(message) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _resetExpect(self):
self.previousExpectLine = ""
if self._connection is not None and isinstance(self._connection.buffer, str):
self.previousExpectLine = self._connection.buffer
self._connection.buffer = "" |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def _lastExpect(self):
constructLine = self.previousExpectLine
if self._connection is not None and isinstance(self._connection.before, str):
constructLine += self._connection.before
if self._connection is not None and isinstance(self._connection.after, str):
constructLine += self._connection.after
return constructLine |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def send(self, command):
if self._bufferedCommands is None:
self._bufferedCommands = command
else:
self._bufferedCommands += "\n" + command |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def flush(self):
if self._bufferedCommands is None:
return
self._connection.sendline(str(self._bufferedCommands))
self._bufferedCommands = None |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def buffering(self):
return self._bufferedMode |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def bufferedMode(self, mode = True):
if mode is None:
self.flush()
self._bufferedMode = mode |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def create_node(self, *args, **kwargs):
nbparam = len(args) + len(kwargs)
assert nbparam in (0, len(Fields)), \
"Bad argument number for {}: {}, expecting {}".\
format(Name, nbparam, len(Fields))
self._fields = Fields
self._attributes = Attributes
for argname, argval in zip(self._fields, args):
setattr(self, argname, argval)
for argname, argval in kwargs.items():
assert argname in Fields, \
"Invalid Keyword argument for {}: {}".format(Name, argname)
setattr(self, argname, argval) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def parse(*args, **kwargs):
return ast_to_gast(_ast.parse(*args, **kwargs)) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def literal_eval(node_or_string):
if isinstance(node_or_string, AST):
node_or_string = gast_to_ast(node_or_string)
return _ast.literal_eval(node_or_string) |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def get_dpo_proto(addr):
if ip_address(addr).version == 6:
return DpoProto.DPO_PROTO_IP6
else:
return DpoProto.DPO_PROTO_IP4 |
def emit(self, level, message):
raise NotImplementedError('Please implement an emit method') | def __init__(self, addr):
self.addr = addr
self.ip_addr = ip_address(text_type(self.addr)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.