text stringlengths 48 9.16k |
|---|
def delta(flag, ones_before, zeros_after):
if flag==0: return -ones_before
else: return +zeros_after |
def chmod(path, mode, recursive=True, use_sudo=False):
cmd = 'chmod %(mode)s %(path)s' % locals()
if recursive:
cmd += ' -R'
_conditional_sudo(cmd, use_sudo) |
def test_no_client_ip(self):
out, err = self.run_netcmd(cmd_testparm, ["--client-name=foo"],
retcode=-1)
self.assertEquals("", out)
self.assertEquals(
"ERROR: Both a DNS name and an IP address are "
"required for the host access check\n", err) |
def addError(self, test, err, details=None):
self.failed_tests += 1 |
def test_all_negative_card_type_indicators(self):
customer = Customer.create().customer
result = CreditCard.create({
"customer_id": customer.id,
"number": CreditCardNumbers.CardTypeIndicators.No,
"expiration_date": "05/2014",
"options": {"verify_card": True}
})
credit_ca... |
def test_missing_test_with_plan_adds_error(self):
# A file
# 1..3
# ok first test
# not ok 3 third test
# results in three tests, with the second being created
self.tap.write('1..3\n')
self.tap.write('ok first test\n')
self.tap.write('not ok 3 third test\n')
self.tap.seek(0)
resu... |
def set_up_done(exception_caught):
"""Set up is done, either clean up or run the test."""
if self.exception_caught == exception_caught:
fails.append(None)
return clean_up()
else:
d = self._run_user(self.case._run_test_method, self.result)
d.addCallback(fail_if_exception_caugh... |
def setUp(self):
self.snapshots = []
for x in range(50):
cb = CanonicalBuilding()
cb.save()
b = SEEDFactory.building_snapshot(canonical_building=cb)
b.extra_data = {
'my new field': 'something extra'
}
b.save()
self.snapshots.append(b) |
def add_argument(self, *args, **kwargs):
"""
This method supports the same args as ArgumentParser.add_argument(..)
as well as the additional args below.
Additional Args:
env_var: If set, the value of this environment variable will override
any config file or default values for this ... |
def test_calls_setUp_test_tearDown_in_sequence(self):
# setUp, the test method and tearDown can all return
# Deferreds. AsynchronousDeferredRunTest will make sure that each of
# these are run in turn, only going on to the next stage once the
# Deferred from the previous stage has fired.
call_log = [... |
def __init__(self, authToken=None, type=None,):
self.authToken = authToken
self.type = type |
def test_default_template_renders_image_alt(self):
html = render_uploads('<<<an-image:alt=the alt text>>>')
self.assertTrue('alt="the alt text"' in html) |
def handle(self, request, data):
self.cache_data(request, data)
if constants.ENFORCE_SECURE and not request.is_secure():
return self.render_to_response({'error': 'access_denied',
'error_description': _("A secure connection is required."),
'next': None},
status=400)
... |
def __init__(self, locale, urlnode):
self.locale = locale
self.urlnode = urlnode |
def get_fieldsets(bases, attrs):
"""Get the fieldsets definition from the inner Meta class."""
fieldsets = _get_meta_attr(attrs, 'fieldsets', None)
if fieldsets is None:
#grab the fieldsets from the first base class that has them
for base in bases:
fieldsets = getattr(base, 'base... |
def _test(self, mock_foo):
test.assertIsNot(Foo, original)
test.assertIs(Foo, mock_foo)
test.assertIsInstance(Foo, SomeClass) |
def clean_password(self):
password = self.cleaned_data.get('password')
if not password:
raise OAuthValidationError({'error': 'invalid_request'})
return password |
def __setitem__(self, name, value):
self.values[name] = value |
def to_python(self, value):
if not value:
return []
# New in Django 1.6: value may come in as a string.
# Instead of raising an `OAuthValidationError`, try to parse and
# ultimately return an empty list if nothing remains -- this will
# eventually raise an `OAuthValidationError` in `validat... |
def testUnsavedOptions(self):
c = makeConfig()
s_option = "%s%s" % ('section1', 'foo2')
c.set('section1', 'foo2', 'bar2')
self.assertFalse(s_option in c._unsaved)
c.remove_option('section1', 'foo2')
self.assertFalse(s_option in c._unsaved)
c.set_secure('section1', 'foo2', 'bar2')
self... |
def dns_type_flag(rec_type):
rtype = rec_type.upper()
if rtype == 'A':
record_type = dnsp.DNS_TYPE_A
elif rtype == 'AAAA':
record_type = dnsp.DNS_TYPE_AAAA
elif rtype == 'PTR':
record_type = dnsp.DNS_TYPE_PTR
elif rtype == 'NS':
record_type = dnsp.DNS_TYPE_NS
elif... |
def __init__(self, parent=None):
super(AddAccountWizard, self).__init__(
parent,
windowTitle="Sign In")
# TODO - remove magic numbers
self.setPage(0, AccountTypeWizardPage())
self.setPage(1, GithubCredentialsWizardPage())
self.setPage(2, Github2FAWizardPage())
self.s... |
def test_custom_cluster_name_bad(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('--cluster=/evil-this-should-not-be-created'.split())
out, err = capsys.readouterr()
assert ('--cluster: argument must start with a letter and contain only '
'letters and numbers') in e... |
def test_repo_url_default_is_none(self):
args = self.parser.parse_args('repo ceph host1'.split())
assert args.repo_url is None |
def test_get_repos_is_empty(self):
cfg = conf.cephdeploy.Conf()
cfg.sections = lambda: ['ceph-deploy-install']
assert cfg.get_repos() == [] |
def print_new_acl(self, samdb, object_dn):
desc = self.read_descriptor(samdb, object_dn)
desc_sddl = desc.as_sddl(self.get_domain_sid(samdb))
self.outf.write("new descriptor for %s:\n" % object_dn)
self.outf.write(desc_sddl + "\n") |
def test_defaults(newcfg):
cfg = newcfg('host1')
assert cfg.get('global', 'auth cluster required') == 'cephx'
assert cfg.get('global', 'auth service required') == 'cephx'
assert cfg.get('global', 'auth client required') == 'cephx' |
def register_connection(alias='default', host='localhost', port=6379, **kwargs):
global _connections
kwargs.setdefault('parser_class', PythonParser)
kwargs.setdefault('db', 0)
pool = ConnectionPool(host=host, port=port, **kwargs)
conn = redis.StrictRedis(connection_pool=pool)
_connections[ali... |
def _juliacode(expr, ):
code = sympy.printing.lambdarepr.lambdarepr(expr)
return code.replace('**', '^') |
def write_keyring(path, key, uid=-1, gid=-1):
""" create a keyring file """
# Note that we *require* to avoid deletion of the temp file
# otherwise we risk not being able to copy the contents from
# one file system to the other, hence the `delete=False`
tmp_file = tempfile.NamedTemporaryFile(delete=... |
def setSegmentStartTangent(segment, tangent):
if len(segment.points) == 2:
'''
Convert straight segment to 4-point cubic bezier.
'''
p0, p3 = segment.points
p2 = p0.midpoint(p3)
p1 = p0.plus(tangent.scale(p0.distanceTo(p3) * 0.5))
result = TFSSegment(p0, p1, p... |
@property
def urls(self):
import operator
urls_or_func = self.settings.get('source_urls') or getattr(self.rule, 'source_urls', None)
rval = urls_or_func
if operator.isCallable(urls_or_func):
rval = urls_or_func(self)
return rval or [] |
def parse(dataset):
shapes = {}
with codecs.open(dataset,'r', encoding="utf8") as dataset:
current_char = ''
current_shape = []
remaining_strokes = 1
for l in dataset.readlines():
letter = letter_re.search(l)
if letter:
current_char = lett... |
def concatenate_keyrings(args):
"""
A helper to collect all keyrings into a single blob that will be
used to inject it to mons with ``--mkfs`` on remote nodes
We require all keyring files to be concatenated to be in a directory
to end with ``.keyring``.
"""
keyring_path = os.path.abspath(ar... |
def test_hierarchy_isa(self):
""" Test hierarchical lookup.
"""
cpt = SNOMEDConcept('315004001') # Metastasis from malignant tumor of breast
child = SNOMEDConcept('128462008') # Metastatic neoplasm (disease)
self.assertTrue(cpt.isa(child.code))
child = SNOMEDConcept('363346000') # Malignant neopl... |
def __init__(self, robotdef, geom, ifunc=None):
if not ifunc:
ifunc = _id
self.rbtdef = robotdef
self.geom = geom
self.dof = self.rbtdef.dof
def sym_skew(v):
return sympy.Matrix([[0, -v[2], v[1]],
[v[2], 0, -v[0]],
... |
def __unicode__(self):
if self.event_id:
text = '{0} => {1}'.format(self.event, self.state)
else:
text = unicode(self.state)
if self.duration:
text = '{0} ({1})'.format(text, self.natural_duration)
elif self.in_transition():
text = '{0} (in transition)'.format(text)
r... |
@skipIf(django.VERSION < (1,8,), "This test needs Django >=1.8")
def test_polymorphic__complex_aggregate(self):
""" test (complex expression on) aggregate (should work for annotate either) """
Model2A.objects.create(field1='A1')
Model2B.objects.create(field1='A1', field2='B2')
Model2B.objects.creat... |
def _log_error(self, bundle, url, e):
if self.logger:
self.logger.error('Error when handle bundle: %s, url: %s' % (
str(bundle), str(url)))
self.logger.exception(e)
if url == getattr(bundle, 'error_url', None):
bundle.error_times = getattr(bundle, 'error_times', 0) + 1
el... |
def tokenize(self, string):
tokens = string.split(' ')
wrapper = self._fmt_wrapper()
_tokens, count = '', len(tokens) - 1
for k, token in enumerate(tokens):
_tokens += self._fmt(token, k, count)
return wrapper.format(_tokens) |
def is_successor(self, prev, next):
if prev >= next:
return False
return True |
@app.route('/user/<user_id>')
def user_shipments(user_id):
print('Getting shipments for user: {}'.format(user_id))
response = jsonify({
'data': {
'shipments': [
{'name': 'teddy bear 123', 'arrival_date': '12/25/2015'},
{'name': 'chocolate cookies', 'arrival_da... |
def interpret(self, code):
def _print(arg):
print(arg)
def cls(*args):
print('\n\n\n\n\n')
def sleep(arg):
return time.sleep(int(args))
control_table = dict(
_print=_print,
sleep=sleep,
cls=cls,
)
for token in code:
if len(token) > 2:
... |
def __init__(self, content):
self.content = content |
def is_unauthorized(self, request, *args, **kwargs):
if request.method != 'POST':
return super(Root, self).is_unauthorized(request, *args, **kwargs) |
def message_action(self, message):
return '[Email Message]: {}'.format(message) |
def _check_valid(self, node, data):
total = sum([prob for prob in data['edges'].values()])
# Edges must sum to 1 (e.g 0.4, 0.5, 0.1)
if total != 1:
raise InvalidProbabilityValue |
def test_delete(self):
ctx1 = DataContext(user=self.user, name='Context 1')
ctx1.save()
ctx2 = DataContext(user=self.user, name='Context 2')
ctx2.save()
ctx3 = DataContext(user=self.user, name='Context 3', session=True)
ctx3.save()
response = self.client.get('/api/contexts/',
... |
def get_coins_for_address(self, address_rec):
"""Given an address <address_rec>, return the list of coin's
straight from the DB. Note this specifically does NOT return
COIN objects.
"""
color_set = self.color_set
addr_color_set = address_rec.get_color_set()
all_coins = filter(
self.c... |
def dec_to_bcd_8421(num):
"""Convert a decimal to binary, and decompress into Binary Coded Decimal.
Adds trailing bits to the left to enforce a 4-bit "nibble" on all digits.
Uses 8421 notation [see wikipedia.org/wiki/Binary-coded_decimal]"""
bcd, binary, decimals = '', '', ''
for digit in str(num):
... |
def get_data(self):
"""Get this object as a JSON/Storage compatible dict.
Useful for storage and persistence.
"""
raw = self.prefix + to_bytes_32(self.rawPrivKey)
return {"color_set": self.color_set.get_data(),
"address_data": b2a_hashed_base58(raw)} |
def add(self, color_id, txhash, outindex, value, label):
self.execute(
self.queries['add'], (color_id, txhash, outindex, value, label)) |
def clearBackground(event, wname=wname):
widget = getattr(self, wname)
widget.setStyleSheet('')
widget.__class__.focusInEvent(widget, event) |
def __init__(self, ewctrl, orig_offer, my_offer):
super(MyEProposal, self).__init__(make_random_id(),
ewctrl, orig_offer)
self.my_offer = my_offer
if not orig_offer.matches(my_offer):
raise Exception("Offers are incongruent!")
self.etx_spec = ewctrl.make_etx... |
def intersects(self, other):
"""Given another color set <other>, returns whether
they share a color in common.
"""
return len(self.color_id_set & other.color_id_set) > 0 |
def generateInt(self, minimum=0, maximum=100):
""" Generates random integers """
return random.randint(minimum,maximum) |
def __call__(self, *args, **kwargs):
"""Compile-time decorator (turn on the tool in config).
For example::
@tools.proxy()
def whats_my_base(self):
return cherrypy.request.base
whats_my_base.exposed = True
"""
if args:
raise TypeError("The %r Tool does not ac... |
def dfs(term, recursive=False, visited={}, **kwargs):
if term in visited: # Break on cyclic relations.
return []
visited[term], a = True, []
if dict.__contains__(self, term):
a = self[term][0].keys()
for classifier in self.classifiers:
a.extend(classifier.parents(term, **kwargs) ... |
def f(self, other):
other = as_value_expr(other)
if not isinstance(other, BooleanValue):
raise TypeError(other)
op = klass(self, other)
return op.to_expr() |
def _get_option(pat, silent=False):
key = _get_single_key(pat, silent)
# walk the nested dict
root, k = _get_root(key)
return root[k] |
def update(self, top=0.5, mutation=0.5):
""" Updates the population by selecting the top fittest candidates,
and recombining them into a new generation.
"""
# 1) Selection.
# Choose the top fittest candidates.
# Including weaker candidates can be beneficial (diversity).
p = sorted(self.p... |
def __init__(self, cases, results, default):
assert len(cases) == len(results)
ValueOp.__init__(self, cases, results, default) |
def find_base_table(expr):
if isinstance(expr, TableExpr):
return expr
for arg in expr.op().flat_args():
if isinstance(arg, Expr):
r = find_base_table(arg)
if isinstance(r, TableExpr):
return r |
def _get_root(key):
path = key.split('.')
cursor = _global_config
for p in path[:-1]:
cursor = cursor[p]
return cursor, path[-1] |
def test_zeroifnull(self):
dresult = self.alltypes.double_col.zeroifnull()
iresult = self.alltypes.int_col.zeroifnull()
assert type(dresult.op()) == ops.ZeroIfNull
assert type(dresult) == ir.DoubleArray
# Impala upconverts all ints to bigint. Hmm.
assert type(iresult) == type(iresult) |
def reflect(object, quantify=True, replace=readable_types):
""" Returns the type of each object in the given object.
- For modules, this means classes and functions etc.
- For list and tuples, means the type of each item in it.
- For other objects, means the type of the object itself.
""... |
def find_lemmata(self, tokens, **kwargs):
return find_lemmata(tokens) |
def test_dtype_datetime64(self):
df = pd.DataFrame({
'col': [pd.Timestamp('2010-11-01 00:01:00'),
pd.Timestamp('2010-11-01 00:02:00.1000'),
pd.Timestamp('2010-11-01 00:03:00.300000')]})
inferred = pandas_to_ibis_schema(df)
expected = ibis.schema([('col', 'timestamp')]... |
def _timestamp_delta(translator, expr):
op = expr.op()
arg, offset = op.args
formatted_arg = translator.translate(arg)
return _timestamp_format_offset(offset, formatted_arg) |
def import_model(path):
"""
Passed a string "app.Model", will return Model registered inside app.
"""
split = path.split('.', 1)
return get_model(split[0], split[1]) |
def _case_projection_fuse_filter(self):
# Probably test this during the evaluation phase. In SQL, "fusable"
# table operations will be combined together into a single select
# statement
#
# see ibis #71 for more on this
t = ibis.table([
('a', 'int8'),
('b', 'int16'),
('c... |
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStr... |
def uint8(self, val):
write_uint8(self.buf, val)
return self |
def get_container(self, container_name):
"""
>>> driver = DummyStorageDriver('key', 'secret')
>>> driver.get_container('unknown') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ContainerDoesNotExistError:
>>> container = driver.create_container(container_name='test contain... |
def test_where_with_between(self):
t = self.con.table('alltypes')
what = t.filter([t.a > 0, t.f.between(0, 1)])
result = to_sql(what)
expected = """SELECT *
alltypes
E `a` > 0 AND
`f` BETWEEN 0 AND 1"""
assert result == expected |
def recv_Cancel(self):
(fname, mtype, rseqid) = self._iprot.readMessageBegin()
if mtype == TMessageType.EXCEPTION:
x = TApplicationException()
x.read(self._iprot)
self._iprot.readMessageEnd()
raise x
result = Cancel_result()
result.read(self._iprot)
self._iprot.readMessageEnd()
if result.suc... |
def _get_id(self, element):
return element.get('id') |
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStr... |
def find_link_by_text(self, text):
return self.find_by_xpath(
'//a[text()="%s"]' % text, original_find="link by text", original_query=text) |
def find_by_value(self, value):
return self.find_by_xpath('//*[@value="%s"]' % value, original_find='value', original_query=value) |
def refresh(self, *args, **kwargs):
"""
Fetch the result SYNCHRONOUSLY and populate the cache
"""
result = self.fetch(*args, **kwargs)
self.cache_set(self.key(*args, **kwargs),
self.expiry(*args, **kwargs),
result)
return result |
@mod.route('/threads/vote/', methods=['POST'])
@requires_login
def vote_thread():
"""
Submit votes via ajax
"""
thread_id = int(request.form['thread_id'])
user_id = g.user.id
if not thread_id:
abort(404)
thread = Thread.query.get_or_404(int(thread_id))
vote_status = thread.vote... |
def get_denominator_csv(self):
output = io.StringIO()
writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(["year", "month", "officers out on service"])
values = sorted(self.denominator_values,
key=lambda x: (x.year, x.month))
for value in values:
... |
def testIncreasingCTime(self):
# This test will check 200 different years, every month, every day,
# every hour, every minute, every second, and every weekday, using
# a delta of more or less 1 year, 1 month, 1 day, 1 minute and
# 1 second.
delta = timedelta(days=365+31+1, seconds=1+60+60*60)
dt... |
def _NextButtonActivated(self, event):
year, month, day, id = self._GetEntryFormKeys()
nextid = self.entries.get_next_id(year, month, day, id)
self._SetEntryFormDate(year, month, day, nextid) |
def __delitem__(self, key):
"""removes item with given key"""
n = self.d[key]
n.next.prev = n.prev
n.prev.next = n.next
del self.d[key] |
def __init__(self, *args, **kwargs):
webcamPreviewDialog.__init__(self, *args, **kwargs)
self.parent = self.GetParent().GetParent()
self.timer = Timer(self.callback)
self.timer.Start(250)
self.temppath = self.GetParent().temppath
self.previewokbutton.Bind(wx.EVT_BUTTON, self.close) |
def _exec_dockerinspect_slow(long_id):
try:
proc = subprocess.Popen('docker inspect %s' % long_id,
shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
inspect_data = proc.stdout.read().strip()
(out, err) = proc.communica... |
def EntryChangedListener(self, tag, entry, add=True):
"""Callback for TKEntries.store_entry()."""
year, month, day = entry.get_date()
id = entry.get_id()
wx.BeginBusyCursor()
try:
stack = self.GetTagStack(tag, year, month, day, id)
tag_path = map(unicode, tag.split('/'))
expe... |
def __init__(self, parent, MainFrame, id, title, workingdir):
wx.Frame.__init__(self, parent, -1, title, size = (1, 1),
style=wx.FRAME_NO_TASKBAR|wx.NO_FULL_REPAINT_ON_RESIZE)
self.tbicon = TaskBarIcon(self, MainFrame, workingdir)
self.Show(True)
self.MainFrame = MainFrame |
def serve(self, endpoint):
"""Serves the application at the given *endpoint*. The *endpoint* must be a tuple (<host>, <port>)."""
return Server.serve(endpoint, self.handle_connection) |
def test_post_ois_data_near_match_does_not_update(self, testapp):
''' OIS data with the same ID but different details creates a new record.
'''
# Set up the extractor
department = Department.create(name="Good Police Department", short_name="GPD", load_defaults=False)
extractor, envs = Extractor.from... |
def test_mode_to_str(self):
m = meta.Metadata()
modes = [
stat.S_ISUID,
stat.S_ISGID,
stat.S_ISVTX,
stat.S_IRUSR,
stat.S_IWUSR,
stat.S_IXUSR,
stat.S_IRGRP,
stat.S_IWGRP,
stat.S_IXGRP,
stat.S_IROTH,
stat.S_IWOTH,
s... |
def _crawl_config_files(
self,
root_dir='/',
exclude_dirs=['proc', 'mnt', 'dev', 'tmp'],
root_dir_alias=None,
known_config_files=[],
discover_config_files=False,
):
assert(self.crawl_mode is not Modes.OUTCONTAINER)
saved_args = locals()
logger.debug('Crawling config files: %s' % (s... |
def testTwoDates(self):
input = "From March 13 at 12:30pm to September 2 at 11:15am"
targets = [datetime.datetime(2014, 3, 13, 12, 30),
datetime.datetime(2014, 9, 2, 11, 15)]
self.compareDates(input, targets)
self.compareTimes(input, targets) |
@staticmethod
@raises(IOError)
def test_cannot_find_config_file_raises():
"""Tests that an exception is raised if it cannot find any yaml files
"""
with TempDirectory() as d:
with TempDirectory() as d2:
load_yaml([join(d.path, 'test.cfg'),
join(d2.path, 'test.cfg')... |
def ip_addr(data):
return ".".join([ str(a) for a in data ]) |
def get_context_data(self, **kwargs):
ctx = super(ListDetail, self).get_context_data(**kwargs)
ctx.update({
"packages": self.object.packages.all().extra(select={"lower_name": "lower(name)"}).order_by("lower_name"),
})
return ctx |
def wrapped_function(*args, **kwargs):
# Handle setting of Flask-Cors parameters
options = get_cors_options(current_app, _options)
if options.get('automatic_options') and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, ... |
def test_measmodestmt_dump():
""" Test MeasuringModeStmt to_excellon()
"""
lines = ['M71', 'M72', ]
for line in lines:
stmt = MeasuringModeStmt.from_excellon(line)
assert_equal(stmt.to_excellon(), line) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.