input
stringlengths 11
7.65k
| target
stringlengths 22
8.26k
|
---|---|
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self):
self.stride = (4, 8, 16, 32, 64)
self.short = (200, 100, 50, 25, 13)
self.long = (334, 167, 84, 42, 21) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def do_register_opts(opts, group=None, ignore_errors=False):
try:
cfg.CONF.register_opts(opts, group=group)
except:
if not ignore_errors:
raise |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def do_register_cli_opts(opt, ignore_errors=False):
# TODO: This function has broken name, it should work with lists :/
if not isinstance(opt, (list, tuple)):
opts = [opt]
else:
opts = opt
try:
cfg.CONF.register_cli_opts(opts)
except:
if not ignore_errors:
raise |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def new_tool_type(request):
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=Tool_Type())
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Created.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm()
add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request)
return render(request, 'dojo/new_tool_type.html',
{'tform': tform}) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "voir", "view")
self.schema = "<cle>"
self.aide_courte = "affiche le détail d'un chemin"
self.aide_longue = \
"Cette commande permet d'obtenir plus d'informations sur " \
"un chemin (ses flags actifs, ses salles et sorties...)." |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def edit_tool_type(request, ttid):
tool_type = Tool_Type.objects.get(pk=ttid)
if request.method == 'POST':
tform = ToolTypeForm(request.POST, instance=tool_type)
if tform.is_valid():
tform.save()
messages.add_message(request,
messages.SUCCESS,
'Tool Type Configuration Successfully Updated.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('tool_type', ))
else:
tform = ToolTypeForm(instance=tool_type)
add_breadcrumb(title="Edit Tool Type Configuration", top_level=False, request=request)
return render(request,
'dojo/edit_tool_type.html',
{
'tform': tform,
}) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def ajouter(self):
"""Méthode appelée lors de l'ajout de la commande à l'interpréteur"""
cle = self.noeud.get_masque("cle")
cle.proprietes["regex"] = r"'[a-z0-9_:]{3,}'" |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def make_data(cuda=False):
train_x = torch.linspace(0, 1, 100)
train_y = torch.sin(train_x * (2 * pi))
train_y.add_(torch.randn_like(train_y), alpha=1e-2)
test_x = torch.rand(51)
test_y = torch.sin(test_x * (2 * pi))
if cuda:
train_x = train_x.cuda()
train_y = train_y.cuda()
test_x = test_x.cuda()
test_y = test_y.cuda()
return train_x, train_y, test_x, test_y |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, train_x, train_y, likelihood):
super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5))
self.base_covar_module = ScaleKernel(RBFKernel(lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1)))
self.covar_module = InducingPointKernel(
self.base_covar_module, inducing_points=torch.linspace(0, 1, 32), likelihood=likelihood
) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return MultivariateNormal(mean_x, covar_x) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setUp(self):
if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false":
self.rng_state = torch.get_rng_state()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
random.seed(0) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def tearDown(self):
if hasattr(self, "rng_state"):
torch.set_rng_state(self.rng_state) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_sgpr_mean_abs_error(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(30):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.05) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_sgpr_fast_pred_var(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(50):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
with gpytorch.settings.max_preconditioner_size(5), gpytorch.settings.max_cg_iterations(50):
with gpytorch.settings.fast_pred_var(True):
fast_var = gp_model(test_x).variance
fast_var_cache = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - fast_var).abs()), 1e-3)
with gpytorch.settings.fast_pred_var(False):
slow_var = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - slow_var).abs()), 1e-3) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_sgpr_mean_abs_error_cuda(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
if not torch.cuda.is_available():
return
with least_used_cuda_device():
train_x, train_y, test_x, test_y = make_data(cuda=True)
likelihood = GaussianLikelihood().cuda()
gp_model = GPRegressionModel(train_x, train_y, likelihood).cuda()
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
optimizer.n_iter = 0
for _ in range(25):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.n_iter += 1
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.02) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)]) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_subclass_delayed(self):
class X(Structure):
pass
self.assertEqual(sizeof(X), 0)
X._fields_ = [("a", c_int)]
class Y(X):
pass
self.assertEqual(sizeof(Y), sizeof(X))
Y._fields_ = [("b", c_int)]
class Z(X):
pass
self.assertEqual(sizeof(X), sizeof(c_int))
self.assertEqual(sizeof(Y), sizeof(c_int)*2)
self.assertEqual(sizeof(Z), sizeof(c_int))
self.assertEqual(X._fields_, [("a", c_int)])
self.assertEqual(Y._fields_, [("b", c_int)])
self.assertEqual(Z._fields_, [("a", c_int)]) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_simple_structs(self):
for code, tp in self.formats.items():
class X(Structure):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("c%c0%c" % (code, code)), code)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_unions(self):
for code, tp in self.formats.items():
class X(Union):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_struct_alignment(self):
class X(Structure):
_fields_ = [("x", c_char * 3)]
self.assertEqual(alignment(X), calcsize("s"))
self.assertEqual(sizeof(X), calcsize("3s"))
class Y(Structure):
_fields_ = [("x", c_char * 3),
("y", c_int)]
self.assertEqual(alignment(Y), calcsize("i"))
self.assertEqual(sizeof(Y), calcsize("3si"))
class SI(Structure):
_fields_ = [("a", X),
("b", Y)]
self.assertEqual(alignment(SI), max(alignment(Y), alignment(X)))
self.assertEqual(sizeof(SI), calcsize("3s0i 3si 0i"))
class IS(Structure):
_fields_ = [("b", Y),
("a", X)]
self.assertEqual(alignment(SI), max(alignment(X), alignment(Y)))
self.assertEqual(sizeof(IS), calcsize("3si 3s 0i"))
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), alignment(X))
self.assertEqual(sizeof(XX), calcsize("3s 3s 0s")) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_emtpy(self):
# I had problems with these
#
# Although these are patological cases: Empty Structures!
class X(Structure):
_fields_ = []
class Y(Union):
_fields_ = []
# Is this really the correct alignment, or should it be 0?
self.assertTrue(alignment(X) == alignment(Y) == 1)
self.assertTrue(sizeof(X) == sizeof(Y) == 0)
class XX(Structure):
_fields_ = [("a", X),
("b", X)]
self.assertEqual(alignment(XX), 1)
self.assertEqual(sizeof(XX), 0) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_fields(self):
# test the offset and size attributes of Structure/Unoin fields.
class X(Structure):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, sizeof(c_int))
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
class X(Union):
_fields_ = [("x", c_int),
("y", c_char)]
self.assertEqual(X.x.offset, 0)
self.assertEqual(X.x.size, sizeof(c_int))
self.assertEqual(X.y.offset, 0)
self.assertEqual(X.y.size, sizeof(c_char))
# readonly
self.assertRaises((TypeError, AttributeError), setattr, X.x, "offset", 92)
self.assertRaises((TypeError, AttributeError), setattr, X.x, "size", 92)
# XXX Should we check nested data types also?
# offset is always relative to the class... |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_packed(self):
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 1
self.assertEqual(sizeof(X), 9)
self.assertEqual(X.b.offset, 1)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 2
self.assertEqual(sizeof(X), 10)
self.assertEqual(X.b.offset, 2)
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 4
self.assertEqual(sizeof(X), 12)
self.assertEqual(X.b.offset, 4)
import struct
longlong_size = struct.calcsize("q")
longlong_align = struct.calcsize("bq") - longlong_size
class X(Structure):
_fields_ = [("a", c_byte),
("b", c_longlong)]
_pack_ = 8
self.assertEqual(sizeof(X), longlong_align + longlong_size)
self.assertEqual(X.b.offset, min(8, longlong_align))
d = {"_fields_": [("a", "b"),
("b", "q")],
"_pack_": -1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
# Issue 15989
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.INT_MAX + 1}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d)
d = {"_fields_": [("a", c_byte)],
"_pack_": _testcapi.UINT_MAX + 2}
self.assertRaises(ValueError, type(Structure), "X", (Structure,), d) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_initializers(self):
class Person(Structure):
_fields_ = [("name", c_char*6),
("age", c_int)]
self.assertRaises(TypeError, Person, 42)
self.assertRaises(ValueError, Person, b"asldkjaslkdjaslkdj")
self.assertRaises(TypeError, Person, "Name", "HI")
# short enough
self.assertEqual(Person(b"12345", 5).name, b"12345")
# exact fit
self.assertEqual(Person(b"123456", 5).name, b"123456")
# too long
self.assertRaises(ValueError, Person, b"1234567", 5) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_conflicting_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
# conflicting positional and keyword args
self.assertRaises(TypeError, POINT, 2, 3, x=4)
self.assertRaises(TypeError, POINT, 2, 3, y=4)
# too many initializers
self.assertRaises(TypeError, POINT, 2, 3, 4) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_keyword_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
pt = POINT(1, 2)
self.assertEqual((pt.x, pt.y), (1, 2))
pt = POINT(y=2, x=1)
self.assertEqual((pt.x, pt.y), (1, 2)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_invalid_field_types(self):
class POINT(Structure):
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)]) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def declare_with_name(name):
class S(Structure):
_fields_ = [(name, c_int)] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_intarray_fields(self):
class SomeInts(Structure):
_fields_ = [("a", c_int * 4)]
# can use tuple to initialize array (but not list!)
self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0])
self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1])
self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0])
self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2])
self.assertEqual(SomeInts((1, 2)).a[6:4:-1], [])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4])
self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4])
# too long
# XXX Should raise ValueError?, not RuntimeError
self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_nested_initializers(self):
# test initializing nested structures
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
p = Person(b"Someone", (b"1234", b"5678"), 5)
self.assertEqual(p.name, b"Someone")
self.assertEqual(p.phone.areacode, b"1234")
self.assertEqual(p.phone.number, b"5678")
self.assertEqual(p.age, 5) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_structures_with_wchar(self):
try:
c_wchar
except NameError:
return # no unicode
class PersonW(Structure):
_fields_ = [("name", c_wchar * 12),
("age", c_int)]
p = PersonW("Someone \xe9")
self.assertEqual(p.name, "Someone \xe9")
self.assertEqual(PersonW("1234567890").name, "1234567890")
self.assertEqual(PersonW("12345678901").name, "12345678901")
# exact fit
self.assertEqual(PersonW("123456789012").name, "123456789012")
#too long
self.assertRaises(ValueError, PersonW, "1234567890123") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_init_errors(self):
class Phone(Structure):
_fields_ = [("areacode", c_char*6),
("number", c_char*12)]
class Person(Structure):
_fields_ = [("name", c_char * 12),
("phone", Phone),
("age", c_int)]
cls, msg = self.get_except(Person, b"Someone", (1, 2))
self.assertEqual(cls, RuntimeError)
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: "
"expected string, int found")
cls, msg = self.get_except(Person, b"Someone", (b"a", b"b", b"c"))
self.assertEqual(cls, RuntimeError)
if issubclass(Exception, object):
self.assertEqual(msg,
"(Phone) <class 'TypeError'>: too many initializers")
else:
self.assertEqual(msg, "(Phone) TypeError: too many initializers") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def create_class(length):
class S(Structure):
_fields_ = [('x' * length, c_int)] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_except(self, func, *args):
try:
func(*args)
except Exception as detail:
return detail.__class__, str(detail) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_abstract_class(self):
class X(Structure):
_abstract_ = "something"
# try 'X()'
cls, msg = self.get_except(eval, "X()", locals())
self.assertEqual((cls, msg), (TypeError, "abstract class")) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_methods(self): |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_positional_args(self):
# see also http://bugs.python.org/issue5042
class W(Structure):
_fields_ = [("a", c_int), ("b", c_int)]
class X(W):
_fields_ = [("c", c_int)]
class Y(X):
pass
class Z(Y):
_fields_ = [("d", c_int), ("e", c_int), ("f", c_int)]
z = Z(1, 2, 3, 4, 5, 6)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 2, 3, 4, 5, 6))
z = Z(1)
self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f),
(1, 0, 0, 0, 0, 0))
self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test(self):
# a Structure with a POINTER field
class S(Structure):
_fields_ = [("array", POINTER(c_int))]
s = S()
# We can assign arrays of the correct type
s.array = (c_int * 3)(1, 2, 3)
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [1, 2, 3])
# The following are bugs, but are included here because the unittests
# also describe the current behaviour.
#
# This fails with SystemError: bad arg to internal function
# or with IndexError (with a patch I have)
s.array[0] = 42
items = [s.array[i] for i in range(3)]
self.assertEqual(items, [42, 2, 3])
s.array[0] = 1 |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_none_to_pointer_fields(self):
class S(Structure):
_fields_ = [("x", c_int),
("p", POINTER(c_int))]
s = S()
s.x = 12345678
s.p = None
self.assertEqual(s.x, 12345678) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_contains_itself(self):
class Recursive(Structure):
pass
try:
Recursive._fields_ = [("next", Recursive)]
except AttributeError as details:
self.assertTrue("Structure or union cannot contain itself" in
str(details))
else:
self.fail("Structure or union cannot contain itself") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_vice_versa(self):
class First(Structure):
pass
class Second(Structure):
pass
First._fields_ = [("second", Second)]
try:
Second._fields_ = [("first", First)]
except AttributeError as details:
self.assertTrue("_fields_ is final" in
str(details))
else:
self.fail("AttributeError not raised") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def config(self):
settings = {
# Use SYSTEMMPI since openfoam-org doesn't have USERMPI
'mplib': 'SYSTEMMPI',
# Add links into bin/, lib/ (eg, for other applications)
'link': False,
}
# OpenFOAM v2.4 and earlier lacks WM_LABEL_OPTION
if self.spec.satisfies('@:2.4'):
settings['label-size'] = False
return settings |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self,title,richtext,text):
self.title=title
self.richtext=richtext
self.text=text |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_run_environment(self, env):
bashrc = self.prefix.etc.bashrc
try:
env.extend(EnvironmentModifications.from_sourcing_file(
bashrc, clean=True
))
except Exception as e:
msg = 'unexpected error when sourcing OpenFOAM bashrc [{0}]'
tty.warn(msg.format(str(e))) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self):
self.factory = yui.YUI.widgetFactory()
self.dialog = self.factory.createPopupDialog()
mainvbox = self.factory.createVBox(self.dialog)
frame = self.factory.createFrame(mainvbox,"Test frame")
HBox = self.factory.createHBox(frame)
self.aboutbutton = self.factory.createPushButton(HBox,"&About")
self.closebutton = self.factory.createPushButton(self.factory.createRight(HBox), "&Close") |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_dependent_build_environment(self, env, dependent_spec):
"""Location of the OpenFOAM project directory.
This is identical to the WM_PROJECT_DIR value, but we avoid that
variable since it would mask the normal OpenFOAM cleanup of
previous versions.
"""
env.set('FOAM_PROJECT_DIR', self.projectdir) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def ask_YesOrNo(self, info):
yui.YUI.widgetFactory
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO)
dlg.setTitle(info.title)
dlg.setText(info.text, info.richtext)
dlg.setButtonLabel("Yes", yui.YMGAMessageBox.B_ONE)
dlg.setButtonLabel("No", yui.YMGAMessageBox.B_TWO)
dlg.setMinSize(50, 5);
return dlg.show() == yui.YMGAMessageBox.B_ONE |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setup_dependent_run_environment(self, env, dependent_spec):
"""Location of the OpenFOAM project directory.
This is identical to the WM_PROJECT_DIR value, but we avoid that
variable since it would mask the normal OpenFOAM cleanup of
previous versions.
"""
env.set('FOAM_PROJECT_DIR', self.projectdir) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def aboutDialog(self):
yui.YUI.widgetFactory;
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createAboutDialog("About dialog title example", "1.0.0", "GPLv3",
"Angelo Naselli", "This beautiful test example shows how it is easy to play with libyui bindings", "")
dlg.show(); |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def projectdir(self):
"""Absolute location of project directory: WM_PROJECT_DIR/"""
return self.prefix # <- install directly under prefix |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def handleevent(self):
"""
Event-handler for the 'widgets' demo
"""
while True:
event = self.dialog.waitForEvent()
if event.eventType() == yui.YEvent.CancelEvent:
self.dialog.destroy()
break
if event.widget() == self.closebutton:
info = Info("Quit confirmation", 1, "Are you sure you want to quit?")
if self.ask_YesOrNo(info):
self.dialog.destroy()
break
if event.widget() == self.aboutbutton:
self.aboutDialog() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def foam_arch(self):
if not self._foam_arch:
self._foam_arch = OpenfoamOrgArch(self.spec, **self.config)
return self._foam_arch |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def archbin(self):
"""Relative location of architecture-specific executables"""
return join_path('platforms', self.foam_arch, 'bin') |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def archlib(self):
"""Relative location of architecture-specific libraries"""
return join_path('platforms', self.foam_arch, 'lib') |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def rename_source(self):
"""This is fairly horrible.
The github tarfiles have weird names that do not correspond to the
canonical name. We need to rename these, but leave a symlink for
spack to work with.
"""
# Note that this particular OpenFOAM requires absolute directories
# to build correctly!
parent = os.path.dirname(self.stage.source_path)
original = os.path.basename(self.stage.source_path)
target = 'OpenFOAM-{0}'.format(self.version)
# Could also grep through etc/bashrc for WM_PROJECT_VERSION
with working_dir(parent):
if original != target and not os.path.lexists(target):
os.rename(original, target)
os.symlink(target, original)
tty.info('renamed {0} -> {1}'.format(original, target)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def patch(self):
"""Adjust OpenFOAM build for spack.
Where needed, apply filter as an alternative to normal patching."""
self.rename_source()
add_extra_files(self, self.common, self.assets)
# Avoid WM_PROJECT_INST_DIR for ThirdParty, site or jobControl.
# Use openfoam-site.patch to handle jobControl, site.
#
# Filtering: bashrc,cshrc (using a patch is less flexible)
edits = {
'WM_THIRD_PARTY_DIR':
r'$WM_PROJECT_DIR/ThirdParty #SPACK: No separate third-party',
'WM_VERSION': str(self.version), # consistency
'FOAMY_HEX_MESH': '', # This is horrible (unset variable?)
}
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path('etc', 'bashrc'),
cshell=join_path('etc', 'cshrc')) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def configure(self, spec, prefix):
"""Make adjustments to the OpenFOAM configuration files in their various
locations: etc/bashrc, etc/config.sh/FEATURE and customizations that
don't properly fit get placed in the etc/prefs.sh file (similiarly for
csh).
"""
# Filtering bashrc, cshrc
edits = {}
edits.update(self.foam_arch.foam_dict())
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path('etc', 'bashrc'),
cshell=join_path('etc', 'cshrc'))
# MPI content, with absolute paths
user_mpi = mplib_content(spec)
# Content for etc/prefs.{csh,sh}
self.etc_prefs = {
r'MPI_ROOT': spec['mpi'].prefix, # Absolute
r'MPI_ARCH_FLAGS': '"%s"' % user_mpi['FLAGS'],
r'MPI_ARCH_INC': '"%s"' % user_mpi['PINC'],
r'MPI_ARCH_LIBS': '"%s"' % user_mpi['PLIBS'],
}
# Content for etc/config.{csh,sh}/ files
self.etc_config = {
'CGAL': {},
'scotch': {},
'metis': {},
'paraview': [],
'gperftools': [], # Currently unused
}
if True:
self.etc_config['scotch'] = {
'SCOTCH_ARCH_PATH': spec['scotch'].prefix,
# For src/parallel/decompose/Allwmake
'SCOTCH_VERSION': 'scotch-{0}'.format(spec['scotch'].version),
}
if '+metis' in spec:
self.etc_config['metis'] = {
'METIS_ARCH_PATH': spec['metis'].prefix,
}
# Write prefs files according to the configuration.
# Only need prefs.sh for building, but install both for end-users
if self.etc_prefs:
write_environ(
self.etc_prefs,
posix=join_path('etc', 'prefs.sh'),
cshell=join_path('etc', 'prefs.csh'))
# Adjust components to use SPACK variants
for component, subdict in self.etc_config.items():
# Versions up to 3.0 used an etc/config/component.sh naming
# convention instead of etc/config.sh/component
if spec.satisfies('@:3.0'):
write_environ(
subdict,
posix=join_path('etc', 'config', component) + '.sh',
cshell=join_path('etc', 'config', component) + '.csh')
else:
write_environ(
subdict,
posix=join_path('etc', 'config.sh', component),
cshell=join_path('etc', 'config.csh', component)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def build(self, spec, prefix):
"""Build using the OpenFOAM Allwmake script, with a wrapper to source
its environment first.
Only build if the compiler is known to be supported.
"""
self.foam_arch.has_rule(self.stage.source_path)
self.foam_arch.create_rules(self.stage.source_path, self)
args = []
if self.parallel: # Build in parallel? - pass via the environment
os.environ['WM_NCOMPPROCS'] = str(make_jobs)
builder = Executable(self.build_script)
builder(*args) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def install(self, spec, prefix):
"""Install under the projectdir"""
mkdirp(self.projectdir)
projdir = os.path.basename(self.projectdir)
# Filtering: bashrc, cshrc
edits = {
'WM_PROJECT_INST_DIR': os.path.dirname(self.projectdir),
'WM_PROJECT_DIR': join_path('$WM_PROJECT_INST_DIR', projdir),
}
# All top-level files, except spack build info and possibly Allwmake
if '+source' in spec:
ignored = re.compile(r'^spack-.*')
else:
ignored = re.compile(r'^(Allwmake|spack-).*')
files = [
f for f in glob.glob("*")
if os.path.isfile(f) and not ignored.search(f)
]
for f in files:
install(f, self.projectdir)
# Having wmake and ~source is actually somewhat pointless...
# Install 'etc' before 'bin' (for symlinks)
# META-INFO for 1812 and later (or backported)
dirs = ['META-INFO', 'etc', 'bin', 'wmake']
if '+source' in spec:
dirs.extend(['applications', 'src', 'tutorials'])
for d in dirs:
if os.path.isdir(d):
install_tree(
d,
join_path(self.projectdir, d),
symlinks=True)
dirs = ['platforms']
if '+source' in spec:
dirs.extend(['doc'])
# Install platforms (and doc) skipping intermediate targets
relative_ignore_paths = ['src', 'applications', 'html', 'Guides']
ignore = lambda p: p in relative_ignore_paths
for d in dirs:
install_tree(
d,
join_path(self.projectdir, d),
ignore=ignore,
symlinks=True)
etc_dir = join_path(self.projectdir, 'etc')
rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc
edits,
posix=join_path(etc_dir, 'bashrc'),
cshell=join_path(etc_dir, 'cshrc'))
self.install_links() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def install_links(self):
"""Add symlinks into bin/, lib/ (eg, for other applications)"""
# Make build log visible - it contains OpenFOAM-specific information
with working_dir(self.projectdir):
os.symlink(
join_path(os.path.relpath(self.install_log_path)),
join_path('log.' + str(self.foam_arch)))
if not self.config['link']:
return
# ln -s platforms/linux64GccXXX/lib lib
with working_dir(self.projectdir):
if os.path.isdir(self.archlib):
os.symlink(self.archlib, 'lib')
# (cd bin && ln -s ../platforms/linux64GccXXX/bin/* .)
with working_dir(join_path(self.projectdir, 'bin')):
for f in [
f for f in glob.glob(join_path('..', self.archbin, "*"))
if os.path.isfile(f)
]:
os.symlink(f, os.path.basename(f)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def linear_search(lst,size,value):
i = 0
while i < size:
if lst[i] == value:
return i
i = i + 1
return -1 |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def main():
lst = [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
size = len(lst)
original_list = ""
value = int(input("\nInput a value to search for: "))
print("\nOriginal Array: ")
for i in lst:
original_list += str(i) + " "
print(original_list)
print("\nLinear Search Big O Notation:\n--> Best Case: O(1)\n--> Average Case: O(n)\n--> Worst Case: O(n)\n")
index = linear_search(lst,size,value)
if index == -1:
print(str(value) + " was not found in that array\n")
else:
print(str(value) + " was found at index " + str(index)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def setUp(self):
self.credentials = {
'username': 'testuser',
'password': 'test1234',
'email': 'test@mail.com'}
# Create a test Group
my_group, created = Group.objects.get_or_create(name='test_group')
# Add user to test Group
User.objects.get(pk=1).groups.add(my_group) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, *args, **kwargs):
BaseConverter.__init__(self, *args, **kwargs)
self.type_ = "string"
self.regex = '[^(/;)]+' |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_user_login(self):
c = Client()
# User points the browser to the landing page
res = c.post('/', follow=True)
# the user is not logged in
self.assertFalse(res.context['user'].is_authenticated)
# and is redirected to the login page
self.assertRedirects(res, '/login/')
# The login page is being rendered by the correct template
self.assertTemplateUsed(res, 'registration/login.html')
# asks the user to login using a set of valid credentials
res = c.post('/login/', data=self.credentials, follow=True)
# The system acknowledges him
self.assertTrue(res.context['user'].is_authenticated)
# and moves him at the dashboard
self.assertTemplateUsed(res, 'app/dashboard.html') |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, *args, **kwargs):
FloatConverter.__init__(self, *args, **kwargs)
self.type_ = "float"
self.regex = '-?\\d+(\\.\\d+)?' |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_public_views(client, expectedStatus):
res = client.get('/public/task/{}/map/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus)
res = client.get('/public/task/{}/3d/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus)
res = client.get('/public/task/{}/iframe/3d/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus)
res = client.get('/public/task/{}/iframe/map/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus)
res = client.get('/public/task/{}/json/'.format(task.id))
self.assertTrue(res.status_code == expectedStatus) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_admin_views(self):
c = Client()
c.login(username='testsuperuser', password='test1234')
settingId = Setting.objects.all()[0].id # During tests, sometimes this is != 1
themeId = Theme.objects.all()[0].id # During tests, sometimes this is != 1
# Can access admin menu items
admin_menu_items = ['/admin/app/setting/{}/change/'.format(settingId),
'/admin/app/theme/{}/change/'.format(themeId),
'/admin/',
'/admin/app/plugin/',
'/admin/auth/user/',
'/admin/auth/group/',
]
for url in admin_menu_items:
res = c.get(url)
self.assertEqual(res.status_code, status.HTTP_200_OK)
# Cannot access dev tools (not in dev mode)
settings.DEV = False
self.assertEqual(c.get('/dev-tools/').status_code, status.HTTP_404_NOT_FOUND)
settings.DEV = True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, *args, **kwargs):
PathConverter.__init__(self, *args, **kwargs)
self.type_ = "string" |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_default_group(self):
# It exists
self.assertTrue(Group.objects.filter(name='Default').count() == 1)
# Verify that all new users are assigned to default group
u = User.objects.create_user(username="default_user")
u.refresh_from_db()
self.assertTrue(u.groups.filter(name='Default').count() == 1) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, *args, **kwargs):
BaseConverter.__init__(self, *args, **kwargs)
self.type_ = "string" |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def test_projects(self):
# Get a normal user
user = User.objects.get(username="testuser")
self.assertFalse(user.is_superuser)
# Create a new project
p = Project.objects.create(owner=user, name="test")
# Have the proper permissions been set?
self.assertTrue(user.has_perm("view_project", p))
self.assertTrue(user.has_perm("add_project", p))
self.assertTrue(user.has_perm("change_project", p))
self.assertTrue(user.has_perm("delete_project", p))
# Get a superuser
superUser = User.objects.get(username="testsuperuser")
self.assertTrue(superUser.is_superuser)
# He should also have permissions, although not explicitly set
self.assertTrue(superUser.has_perm("delete_project", p))
# Get another user
anotherUser = User.objects.get(username="testuser2")
self.assertFalse(anotherUser.is_superuser)
# Should not have permission
self.assertFalse(anotherUser.has_perm("delete_project", p)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def __init__(self, api, name):
super(V1Routing, self).__init__(api, name,
description='Current version of navitia API',
status='current',
index_endpoint='index') |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def looks_like_hash(sha):
return bool(HASH_REGEX.match(sha)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _get_unique_constraints(self, table):
"""Retrieve information about existing unique constraints of the table
This feature is needed for _recreate_table() to work properly.
Unfortunately, it's not available in sqlalchemy 0.7.x/0.8.x.
"""
data = table.metadata.bind.execute(
"""SELECT sql
FROM sqlite_master
WHERE
type='table' AND
name=:table_name""",
table_name=table.name
).fetchone()[0]
UNIQUE_PATTERN = "CONSTRAINT (\w+) UNIQUE \(([^\)]+)\)"
return [
UniqueConstraint(
*[getattr(table.columns, c.strip(' "')) for c in cols.split(",")],
name=name
)
for name, cols in re.findall(UNIQUE_PATTERN, data)
] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_base_rev_args(rev):
return [rev] |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _recreate_table(self, table, column=None, delta=None, omit_uniques=None):
"""Recreate the table properly
Unlike the corresponding original method of sqlalchemy-migrate this one
doesn't drop existing unique constraints when creating a new one.
"""
table_name = self.preparer.format_table(table)
# we remove all indexes so as not to have
# problems during copy and re-create
for index in table.indexes:
index.drop()
# reflect existing unique constraints
for uc in self._get_unique_constraints(table):
table.append_constraint(uc)
# omit given unique constraints when creating a new table if required
table.constraints = set([
cons for cons in table.constraints
if omit_uniques is None or cons.name not in omit_uniques
])
self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name)
self.execute()
insertion_string = self._modify_table(table, column, delta)
table.create(bind=self.connection)
self.append(insertion_string % {'table_name': table_name})
self.execute()
self.append('DROP TABLE migration_tmp')
self.execute() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def is_immutable_rev_checkout(self, url, dest):
# type: (str, str) -> bool
_, rev_options = self.get_url_rev_options(hide_url(url))
if not rev_options.rev:
return False
if not self.is_commit_id_equal(dest, rev_options.rev):
# the current commit is different from rev,
# which means rev was something else than a commit hash
return False
# return False in the rare case rev is both a commit hash
# and a tag or a branch; we don't want to cache in that case
# because that branch/tag could point to something else in the future
is_tag_or_branch = bool(
self.get_revision_sha(dest, rev_options.rev)[0]
)
return not is_tag_or_branch |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _visit_migrate_unique_constraint(self, *p, **k):
"""Drop the given unique constraint
The corresponding original method of sqlalchemy-migrate just
raises NotImplemented error
"""
self.recreate_table(p[0].table, omit_uniques=[p[0].name]) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_git_version(self):
VERSION_PFX = 'git version '
version = self.run_command(
['version'], show_stdout=False, stdout_only=True
)
if version.startswith(VERSION_PFX):
version = version[len(VERSION_PFX):].split()[0]
else:
version = ''
# get first 3 positions of the git version because
# on windows it is x.y.z.windows.t, and this parses as
# LegacyVersion which always smaller than a Version.
version = '.'.join(version.split('.')[:3])
return parse_version(version) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def patch_migrate():
"""A workaround for SQLite's inability to alter things
SQLite abilities to alter tables are very limited (please read
http://www.sqlite.org/lang_altertable.html for more details).
E. g. one can't drop a column or a constraint in SQLite. The
workaround for this is to recreate the original table omitting
the corresponding constraint (or column).
sqlalchemy-migrate library has recreate_table() method that
implements this workaround, but it does it wrong:
- information about unique constraints of a table
is not retrieved. So if you have a table with one
unique constraint and a migration adding another one
you will end up with a table that has only the
latter unique constraint, and the former will be lost
- dropping of unique constraints is not supported at all
The proper way to fix this is to provide a pull-request to
sqlalchemy-migrate, but the project seems to be dead. So we
can go on with monkey-patching of the lib at least for now.
"""
# this patch is needed to ensure that recreate_table() doesn't drop
# existing unique constraints of the table when creating a new one
helper_cls = sqlite.SQLiteHelper
helper_cls.recreate_table = _recreate_table
helper_cls._get_unique_constraints = _get_unique_constraints
# this patch is needed to be able to drop existing unique constraints
constraint_cls = sqlite.SQLiteConstraintDropper
constraint_cls.visit_migrate_unique_constraint = \
_visit_migrate_unique_constraint
constraint_cls.__bases__ = (ansisql.ANSIColumnDropper,
sqlite.SQLiteConstraintGenerator) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_current_branch(cls, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
output = cls.run_command(
args,
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
return None |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True):
"""Upgrade or downgrade a database.
Function runs the upgrade() or downgrade() functions in change scripts.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository.
:param version: Database will upgrade/downgrade until this version.
If None - database will update to the latest
available version.
:param init_version: Initial database version
:param sanity_check: Require schema sanity checking for all tables
"""
if version is not None:
try:
version = int(version)
except ValueError:
raise exception.DbMigrationError(
message=_("version should be an integer"))
current_version = db_version(engine, abs_path, init_version)
repository = _find_migrate_repo(abs_path)
if sanity_check:
_db_schema_sanity_check(engine)
if version is None or version > current_version:
return versioning_api.upgrade(engine, repository, version)
else:
return versioning_api.downgrade(engine, repository,
version) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def export(self, location, url):
# type: (str, HiddenText) -> None
"""Export the Git repository at the url to the destination location"""
if not location.endswith('/'):
location = location + '/'
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.path, url=url)
self.run_command(
['checkout-index', '-a', '-f', '--prefix', location],
show_stdout=False, cwd=temp_dir.path
) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _db_schema_sanity_check(engine):
"""Ensure all database tables were created with required parameters.
:param engine: SQLAlchemy engine instance for a given database
"""
if engine.name == 'mysql':
onlyutf8_sql = ('SELECT TABLE_NAME,TABLE_COLLATION '
'from information_schema.TABLES '
'where TABLE_SCHEMA=%s and '
'TABLE_COLLATION NOT LIKE "%%utf8%%"')
table_names = [res[0] for res in engine.execute(onlyutf8_sql,
engine.url.database)]
if len(table_names) > 0:
raise ValueError(_('Tables "%s" have non utf8 collation, '
'please make sure all tables are CHARSET=utf8'
) % ','.join(table_names)) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_revision_sha(cls, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to pre-filter the list.
output = cls.run_command(
['show-ref', rev],
cwd=dest,
show_stdout=False,
stdout_only=True,
on_returncode='ignore',
)
refs = {}
for line in output.strip().splitlines():
try:
sha, ref = line.split()
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.format(rev)
sha = refs.get(branch_ref)
if sha is not None:
return (sha, True)
sha = refs.get(tag_ref)
return (sha, False) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def db_version(engine, abs_path, init_version):
"""Show the current version of the repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
try:
return versioning_api.db_version(engine, repository)
except versioning_exceptions.DatabaseNotControlledError:
meta = sqlalchemy.MetaData()
meta.reflect(bind=engine)
tables = meta.tables
if len(tables) == 0 or 'alembic_version' in tables:
db_version_control(engine, abs_path, version=init_version)
return versioning_api.db_version(engine, repository)
else:
raise exception.DbMigrationError(
message=_(
"The database is not under version control, but has "
"tables. Please stamp the current version of the schema "
"manually.")) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def _should_fetch(cls, dest, rev):
"""
Return true if rev is a ref or is a commit that we don't have locally.
Branches and tags are not considered in this method because they are
assumed to be always available locally (which is a normal outcome of
``git clone`` and ``git fetch --tags``).
"""
if rev.startswith("refs/"):
# Always fetch remote refs.
return True
if not looks_like_hash(rev):
# Git fetch would fail with abbreviated commits.
return False
if cls.has_commit(dest, rev):
# Don't fetch if we have the commit locally.
return False
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def db_version_control(engine, abs_path, version=None):
"""Mark a database as under this repository's version control.
Once a database is under version control, schema changes should
only be done via change scripts in this repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
versioning_api.version_control(engine, repository, version)
return version |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev = rev_options.arg_rev
# The arg_rev property's implementation for Git ensures that the
# rev return value is always non-None.
assert rev is not None
sha, is_branch = cls.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not cls._should_fetch(dest, rev):
return rev_options
# fetch the requested revision
cls.run_command(
make_command('fetch', '-q', url, rev_options.to_args()),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = cls.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def is_commit_id_equal(cls, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return False
return cls.get_revision(dest) == name |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
rev_display = rev_options.to_display()
logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest))
self.run_command(make_command('clone', '-q', url, dest))
if rev_options.rev:
# Then a specific revision was requested.
rev_options = self.resolve_revision(dest, url, rev_options)
branch_name = getattr(rev_options, 'branch_name', None)
if branch_name is None:
# Only do a checkout if the current commit id doesn't match
# the requested revision.
if not self.is_commit_id_equal(dest, rev_options.rev):
cmd_args = make_command(
'checkout', '-q', rev_options.to_args(),
)
self.run_command(cmd_args, cwd=dest)
elif self.get_current_branch(dest) != branch_name:
# Then a specific branch was requested, and that branch
# is not yet checked out.
track_branch = 'origin/{}'.format(branch_name)
cmd_args = [
'checkout', '-b', branch_name, '--track', track_branch,
]
self.run_command(cmd_args, cwd=dest)
#: repo may contain submodules
self.update_submodules(dest) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
self.run_command(
make_command('config', 'remote.origin.url', url),
cwd=dest,
)
cmd_args = make_command('checkout', '-q', rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
self.update_submodules(dest) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
# First fetch changes from the default remote
if self.get_git_version() >= parse_version('1.9.0'):
# fetch tags in addition to everything else
self.run_command(['fetch', '-q', '--tags'], cwd=dest)
else:
self.run_command(['fetch', '-q'], cwd=dest)
# Then reset to wanted revision (maybe even origin/master)
rev_options = self.resolve_revision(dest, url, rev_options)
cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
#: update submodules
self.update_submodules(dest) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def has_commit(cls, location, rev):
"""
Check if rev is a commit that is available in the local repository.
"""
try:
cls.run_command(
['rev-parse', '-q', '--verify', "sha^" + rev],
cwd=location,
log_failed_cmd=False,
)
except InstallationError:
return False
else:
return True |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_revision(cls, location, rev=None):
if rev is None:
rev = 'HEAD'
current_rev = cls.run_command(
['rev-parse', rev],
show_stdout=False,
stdout_only=True,
cwd=location,
)
return current_rev.strip() |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_subdirectory(cls, location):
"""
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
show_stdout=False,
stdout_only=True,
cwd=location,
).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
repo_root = os.path.abspath(os.path.join(git_dir, '..'))
return find_path_to_setup_from_repo_root(location, repo_root) |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
"""
# Works around an apparent Git bug
# (see https://article.gmane.org/gmane.comp.version-control.git/146500)
scheme, netloc, path, query, fragment = urlsplit(url)
if scheme.endswith('file'):
initial_slashes = path[:-len(path.lstrip('/'))]
newpath = (
initial_slashes +
urllib_request.url2pathname(path)
.replace('\\', '/').lstrip('/')
)
after_plus = scheme.find('+') + 1
url = scheme[:after_plus] + urlunsplit(
(scheme[after_plus:], netloc, newpath, query, fragment),
)
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
return url, rev, user_pass |
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b)) | def update_submodules(cls, location):
if not os.path.exists(os.path.join(location, '.gitmodules')):
return
cls.run_command(
['submodule', 'update', '--init', '--recursive', '-q'],
cwd=location,
) |