prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# coding=utf-8
"""Definitions for basic report.
"""
from __future__ import absolute_import
from safe.utilities.i18n import tr
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
# Meta description about component
# component... | uct_tag',
'name': tr('Fina | l Product'),
'description': tr(
'Tag this component as a Final Product of report generation.')
}
infographic_product_tag = {
'key': 'infographic_product_tag',
'name': tr('Infographic'),
'description': tr(
'Tag this component as an Infographic related product.')
}
map_product_tag = {
... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | ools.JsonConverter import json_serialize
from cairis.tools.MessageDefinitions import ConceptReferenceMessage
from cairis.tools.ModelDefinitions import ConceptReferenceModel
from cairis.tools.SessionValidator import get_session_id
__author__ = 'Shamal Faily'
class ConceptReferencesAPI(Resource):
def get(self):
... | dao = ConceptReferenceDAO(session_id)
crs = dao.get_concept_references(constraint_id=constraint_id)
dao.close()
resp = make_response(json_serialize(crs, session_id=session_id))
resp.headers['Content-Type'] = "application/json"
return resp
def post(self):
session_id = get_session_id(sessio... |
import json
import os
import shutil
import zipfile
from build import cd
def create_template(name, path, **kw):
os.makedirs(os.path.join(path, 'module'))
with open(os.path.join(path, 'module', 'manifest.json'), 'w') as manifest_file:
manifest = {
"name": name,
"version": "0.1",
"description": "My module t... | le_path)
else:
zip_path = shutil.make_archive(zip_base, 'zip', root_dir=modul | e_path)
return zip_path
def _make_partial_archive(zip_base, subdirs, root_dir):
zip = zipfile.ZipFile(zip_base + ".zip", "w")
with cd(root_dir):
for subdir in subdirs:
if not os.path.exists(subdir):
continue
for root, dirs, files in os.walk(subdir):
for file in files:
zip.write(os.path.join(ro... |
"""
WSGI config for server_admin project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | gates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os, sys
sys.path.append('/home/terrywong/server_admin')
sys.path.append('/home/terrywong/server_admin/server_admin')
# We defer to a DJANGO_SETTINGS_MODU... | s own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "server_admin.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server_admin.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
#... |
ent_id = raven.captureException(request=request)
context = {
'detail': 'Internal Error',
'errorId': event_id,
}
response = Response(context, status=500)
response.exception = True
return response
def create_audit_entry(self, req... | name=environment_param,
organization_id=organization_id,
)
request._cached_environment = environment
re | turn request._cached_environment
class StatsMixin(object):
def _parse_args(self, request, environment_id=None):
resolution = request.GET.get('resolution')
if resolution:
resolution = self._parse_resolution(resolution)
assert resolution in tsdb.get_rollups()
end = r... |
import json
from PIL import Image
import collections
with open('../config/nodes.json') as data_file:
nodes = json.load(data_file)
# empty fucker
ordered_nodes = [None] * len(nodes)
# populate fucker
for i, pos in nodes.items():
ordered_nodes[int(i)] = [pos['x'], pos['y']]
filename = "04_rgb_vertical_lines"
i... | )
frame_data = []
# do something to im
img = im.convert('RGB')
if resize == True:
print "Resizing"
img.thumbnail(target_size, Image.ANTIALIAS)
for x, y in ordered_nodes:
frame_data.append(img.getpixel((x, y)))
#print r, g, b
data.append(frame_data)
# write to json... | int frame_num
frame_num+=1
except EOFError:
pass # end of sequence
#print data
#print r, g, b
with open(filename+'.json', 'w') as outfile:
json.dump({
"meta": {},
"data": data
}, outfile)
print im.size #Get the width and hight of the image for iterating over
#print pix[,y] #Get the RGBA... |
import os.path
from crumbs.utils.bin_utils import create_get_binary_path
from | bam_crumbs.settings import get_se | tting
BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', 'bin'))
get_binary_path = create_get_binary_path(os.path.split(__file__)[0],
get_setting)
|
from django.contrib import admin
from .models impo | rt Line
# Register your models here.
admin.sit | e.register(Line)
|
"""
Runs peaktrough.py, which generates Cooley-Rupert figures for specified
series from FRED.
Execute peaktrough.py first, then run this program.
Written by Dave Backus under the watchful eye of Chase Coleman and Spencer Lyon
Date: July 10, 2014
"""
# import functions from peaktrough.py. * means all of them
# genera... | PC1", saveshow="show")
print("aaaa")
# do plots all at once with map
fred_series = ["GDPC1", "PCECC96", "GPDIC96", "OPHNFB"]
# uses default saveshow parameter
g | dpc1, pcecc96, gpdic96, ophnfb = map(manhandle_freddata, fred_series)
print("xxxx")
# lets us change saveshow parameter
gdpc1, pcecc96, gpdic96, ophnfb = map(lambda s:
manhandle_freddata(s, saveshow="save"), fred_series)
print("yyyy")
# skip lhs (this doesn't seem to work, not sure why)
map(lambda s:
manhandl... |
# -*- | coding: utf-8 | -*-
from django.apps import AppConfig
class PostsConfig(AppConfig):
name = 'posts'
verbose_name = '图片列表'
|
#!/usr/bin/env python
#
# PyGab - Python Jabber Framework
# Copyright (c) 2008, Patrick Kennedy
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must r... | s and the following disclaimer.
#
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS... | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTER... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.api.app_identity.app_identity import get_default_gcs_bucket_name
from google.appengine.ext.blobstore import blobstore
from blob_app import blob_facade
from config.template_middleware import TemplateResponse
from gaec... | t RedirectResponse
@no_csrf
def index(_logged_user):
success_url = router.to_path(upload)
bucket = | get_default_gcs_bucket_name()
url = blobstore.create_upload_url(success_url, gs_bucket_name=bucket)
cmd = blob_facade.list_blob_files_cmd(_logged_user)
blob_files = cmd()
delete_path = router.to_path(delete)
download_path = router.to_path(download)
blob_file_form = blob_facade.blob_file_form()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests that all containers are imported correctly."""
import unittest
from tests import test_lib
class ContainersImportTest(test_lib.ImportCheckTestCase):
"""Tests that container classes are imported correctly."""
_IGNORABLE_FILES = frozenset(['manager.py', 'int... | (self):
"""Tests that all parsers are imported."""
| self._AssertFilesImportedInInit(
test_lib.CONTAINERS_PATH, self._IGNORABLE_FILES)
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python3
import unittest
from gppylib.operations.test.regress.test_package import GppkgTestCase, GppkgSpec, BuildGppkg, RPMSpec, BuildRPM, run_command, run_remote_command
class SimpleGppkgTestCase(GppkgTestCase):
"""Covers simple build/install/remove/update test cases"""
def test00_simple_build... | update_gppkg_spec = GppkgSpec("al | pha", "1.1")
update_gppkg_file = self.build(update_gppkg_spec, update_rpm_spec)
self.update(update_gppkg_file)
#Check for the packages
self.check_rpm_install(update_rpm_spec.get_package_name())
def test03_simple_uninstall(self):
gppkg_file = self.alpha_spec.get_filename... |
"""
Test basic std::vector functionality but with a declaration from
the debug info (the Foo struct) as content.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestDbgInfoContentVector(TestBase):
mydir = TestBase.compute_mydir(__file__)... | (int) $5 = 2'])
self.expect("expr (int)(a.rbegin()->a)", substrs=['(int) $6 = 3'])
self.expect("expr a.pop_back()")
self.expect("expr (int)a.back().a", substrs=['(int) $7 = 1'])
self.expect("expr (size_t)a.size()", substrs=['(size_t) $8 = 2'])
self.expect("expr (int)a.at(0).a",... | _back({4})")
self.expect("expr (int)a.back().a", substrs=['(int) $10 = 4'])
self.expect("expr (size_t)a.size()", substrs=['(size_t) $11 = 3'])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import inselect
REQUIREMENTS = [
# TODO How to specify OpenCV? 'cv2>=3.1.0',
'numpy>=1.11.1,<1.12',
'Pillow>=3.4.2,<3.5',
'python-dateutil>=2.6.0,<2.7',
'pytz>=2016.7',
'PyYAML>=3.12,<3.2',
'schematics>=1.1.1,<1.2',
'scikit-lea... | 'xml', 'xmlrpc',
'inselect.tests',
] + ex | clude_packages,
'includes': [
],
'include_files': include_files,
'include_msvcr': True,
'optimize': 2,
},
'bdist_msi': {
'upgrade_code': '{fe2ed61d-cd5e-45bb-9d16-146f725e522f}'
}
... |
e(self):
luigi.run(['--local-scheduler', '--no-lock', 'Baz'])
self.assertEqual(Baz._val, False)
def test_bool_true(self):
luigi.run(['--local-scheduler', '--no-lock', 'Baz', '--bool'])
self.assertEqual(Baz._val, True)
def test_forgot_param(self):
self.assertRaises(luigi... | f.assertEqual(MyConfig().mc_p, 99)
self.a | ssertEqual(MyConfig().mc_q, 73)
self.assertEqual(MyConfigWithoutSection().mc_r, 55)
self.assertEqual(MyConfigWithoutSection().mc_s, 99)
def test_use_config_class_more_args(self):
self.run_and_check(['--MyConfig-mc-p', '99', '--mc |
# -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2012 Serge Noiraud
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eithe... | Initialize the dummy layer
"""
GObject.GObject.__init__(self)
def do_draw(self, gpsmap, gdkdrawable):
"""
Draw the layer
"""
pass
def do_render(self, gpsmap):
"""
Render the layer
"""
pass
def do_busy(self):
"... | is busy
"""
return False
def do_button_press(self, gpsmap, gdkeventbutton):
"""
Someone press a button
"""
return False
GObject.type_register(DummyLayer)
|
epare_class__(cls):
cls.__dispatch = {}
for resultclass in resultclasses:
cls.__dispatch[resultclass] = {}
for type_ in reversed(resultclass.mro()):
for (k, v) in type_.__dict__.items():
# All __promise__ return the same... | p __reduce__ from being
# called. So, we define __getstate__ in a way that cooperates with the way
# that pickle interprets this class. This fails when the wrapped class is a
# builtin, but it is better than nothing.
def __getstate__(self):
| if self._wrapped is empty:
self._setup()
return self._wrapped.__dict__
# Need to pretend to be the wrapped class, for the sake of objects that care
# about this (especially in equality tests)
__class__ = property(new_method_proxy(operator.attrgetter("__class__")))
__eq__ = n... |
invalid' : recID is an error code, i.e. in the interval [-99,-1]
@param return: body of the page
"""
_ = gettext_set_language(ln)
if status == 'inexistant':
body = _("Sorry, the record %s does not seem to exist.") % (recID,)
elif status in ('nan', 'invalid'):
... | collapse: separate; border-spacing: 5px; padding: 5px; width: 100%%">
| %(comment_rows)s
</table>
%(view_all_comments_link)s
%(write_button_form)s<br />
""" % \
{ 'comment_title' : _("Rate this document"),
'score_label' : score,
'useful_label' ... |
from sopel import module
from sopel.tools import Identifier
import time
import re
TIMEOUT = 36000
@module.rule('^(</?3)\s+([a-zA-Z0-9\[\]\\`_\^\{\|\}-]{1,32})\s*$')
@module.intent('ACTION')
@module.require_chanmsg("You may only modify someone's rep in a channel.")
def heart_cmd(bot, trigger):
luv_h8(... | d_rep(bot, caller, target, change):
rep = get_rep(bot, target) or 0
rep += change
set_rep(bot, caller, target, rep)
return rep
def get_rep_used(bot, nick):
return bot.db.get_nick_value(Identifier(nick), 'rep_used') or 0
def set_rep_used(bo | t, nick):
bot.db.set_nick_value(Identifier(nick), 'rep_used', time.time())
def rep_used_since(bot, nick):
now = time.time()
last = get_rep_used(bot, nick)
return abs(last - now)
def rep_too_soon(bot, nick):
since = rep_used_since(bot, nick)
if since < TIMEOUT:
bot.notice... |
the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or... | \
"}")
by_subt | ype_and_initiator = ViewField('notification',
language = 'javascript',
map_fun = "function (doc) {" \
"if (doc.doctype === 'NotificationDocument' && doc.subtype && doc.initiator) {" \
... |
isinstance(resource['Tags'], dict):
tags = resource['Tags']
else:
tags = {tag['Key']: tag['Value'] for tag in resource['Tags']}
targets = []
for target_tag_key in target_tag_keys:
if target_tag_key in tags:
targets.append(tags[target_tag_key])
return targets
def ge... | )
elif resource_type == 'rds':
return "%s %s %s %s" % (
resource['DBInstanceIdentifier'],
"%s-%s" % (
resource['Engine'], resource['EngineVersion']),
re | source['DBInstanceClass'],
resource['AllocatedStorage'])
elif resource_type == 'rds-cluster':
return "%s %s %s" % (
resource['DBClusterIdentifier'],
"%s-%s" % (
resource['Engine'], resource['EngineVersion']),
resource['AllocatedStorage'])
e... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2019-11-24 03:04
from __future__ import unicode_literals
from django.db import migratio | ns, models
class Migration(migrations.Migration):
dependencies = [
('logger', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='logentry',
name='log_type',
field=models.IntegerField(choices=[(0, 'Debug'), (1, 'Info'), (2, 'Warning'),... | ),
migrations.AlterField(
model_name='logentry',
name='message',
field=models.TextField(default=''),
),
]
|
#!/usr/bin/env python
############################################################################
#
# Copyright (C) 2012, 2013 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | identity != None:
cmd = " ".join(["git", | "--git-dir", args.git_identity + "/.git", "describe", "--always", "--dirty"])
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
desc['git_identity'] = str(p.read().strip())
p.close()
if args.parameter_xml != None:
f = open(args.parameter_xml, "rb")
bytes = f.read()
desc['parameter_xml_size'] =... |
# -*- coding: utf-8 -*-
import pytest
import turnstile.models.message as message
from turnstile.checks import CheckIgnore
from turnstile.checks.commit_msg.specification import check
def test_check():
commit_1 = message.CommitMessage('something', 'https://github.com/jmcs/turnstile/issues/42 m€sságe')
result_... | 'allowed_schemes': ['https']}}, commit_4)
assert not result_4.suc | cessful
assert result_4.details == ['ftp://example.com/spec is not a valid specification.']
commit_5 = message.CommitMessage('something', 'ftp://example.com/spec')
result_5 = check(None, {'specification': {'allowed_schemes': ['https', 'ftp']}}, commit_5)
assert result_5.successful
assert result_5.d... |
import logging, time, commands
from autotest.client.shared import error
from virttest import utils_test, aexpect
def run_timedrift(test, params, env):
"""
Time drift test (mainly for Windows guests):
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Run load on the guest and... | PID pid.
Do this recursively for all child processes as well.
@param pid: The process ID.
| @param mask: The CPU affinity mask.
@return: A dict containing the previous mask for each thread.
"""
tids = commands.getoutput("ps -L --pid=%s -o lwp=" % pid).split()
prev_masks = {}
for tid in tids:
prev_mask = commands.getoutput("taskset -p %s" % tid).split()[-... |
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import, divisio | n)
import os as os_module
import xbmc
from lib.constants import *
userdatafolder = os_module.path.join(xbmc.translate | Path("special://profile").decode("utf-8"), "addon_data", addonid, "test data")
libpath = os_module.path.join(userdatafolder, "Library")
|
from mybottle import Bottle, run, ServerAdapter, get, post, request
import KalutServer.conf as myconf
class SSLWSGIRefServer(ServerAdapter):
def run(self, handler, quiet=False):
from wsgiref.simple_server import make_server, WSGIRequestHandler
import ssl
if quiet:
class QuietHand... | ): pass
self.options['handler_class'] = QuietHandler
srv = ma | ke_server(self.host, self.port, handler, **self.options)
srv.socket = ssl.wrap_socket (
srv.socket,
certfile=myconf.certfile, # path to chain file
keyfile=myconf.keyfile, # path to RSA private key
server_side=True)
srv.serve_forever()
|
from django.conf.urls import patterns, url
from publicaciones import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<ar | ticulo_titulo>[ | \W\w]+)/$', views.ver_articulo, name='ver_articulo'),
) |
"""
@package mi.dataset.driver.optaa_dj.cspp
@file mi-dataset/mi/dataset/driver/optaa_dj/cspp/optaa_dj_cspp_telemetered_driver.py
@author Joe Padula
@brief Telemetered driver for the optaa_dj_cspp instrument
Release notes:
Initial Release
"""
__author__ = 'jpadula'
from mi.dataset.dataset_driver import SimpleDatase... | er, \
OptaaDjCsppMetadataTelemeteredDataParticle, \
OptaaDjCsppInstrumentTelemeteredDataParticle
from mi.core.versioning import version
@version("15.6.1")
def parse(basePythonCodePath, sourceFilePath, particleDataHdlrObj):
"""
This is the method called by Uframe
:param basePythonCodePath This is t... | Path This is the full path and filename of the file to be parsed
:param particleDataHdlrObj Java Object to consume the output of the parser
:return particleDataHdlrObj
"""
with open(sourceFilePath, 'rU') as stream_handle:
# create an instance of the concrete driver class defined below
... |
#!/usr/bin/env python
#
# Copyright (c) 2014 Hamilton Kibbe <ham@hamiltonkib.be>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation ... | D, EXPRESS
# OR IMPLIED, INCLUDING | BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECT... |
from pymongo import MongoClient
import schedule
import time
##############
## This script will be deployed in bluemix with --no-route set to true
##############
con = MongoClient( | "mongodb://abcd:qwerty@ds111798.mlab.com:11798/have_a_seat")
db = con.have_a_seat
cursor = db.Bookings.find()
#Bookings is {customerName:"", customerEmail: "", customerPhone: "", Slot: ""}
dict = {}
db.Exploration.delete_many({})
db.Exploitation.delete_many({})
for i in range(4): # Finding for all slots
for c ... | = 1
elif c['Slot'] == i and c['customerEmail'] in dict.keys():
dict[c['customerEmail']] += 1
tuples_list = sorted(dict.items(), key=lambda x: x[1], reverse=True)
print tuples_list
print 'Completed for slot ', i
db.Exploitation.insert({'Slot': i, 'customerEmail': tuples_list[0][0... |
print | 28433 * 2**7830457 + 1
| |
from collections import Counter
def unalk_coeff(l):
'''Source: https://ww2.amstat.org/publications/jse/v15n2/kader.html'''
n = len(l)
freq = Counter(l)
freqsum = 0
for key, freq in freq.items():
p = freq / n
freqsum += p**2
unalk_coeff = 1 - freqsum
return unalk_coeff
def... | v * (v - 1)
d = s / (n * n - 1)
return 1 - d
# TEST, Source: https://ww2.amstat.org/publications/jse/v15n2/kader | .html
# print(unalk_coeff(['A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B']))
# print(unalk_coeff(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']))
# print(unalk_coeff(['A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'])) |
from flask_admin.contrib.sqla.type | fmt import DEFAULT_FORMATTERS as BASE_FORMATTERS
import json
from jinja2 import Markup
from wtforms.widgets import html_params
from geoalchemy2.shape import to_shape
from geoalchemy2.elements im | port WKBElement
from sqlalchemy import func
from flask import current_app
def geom_formatter(view, value):
params = html_params(**{
"data-role": "leaflet",
"disabled": "disabled",
"data-width": 100,
"data-height": 70,
"data-geometry-type": to_shape(value).geom_type,
... |
print "!!! begin SVGCanvas.transform", a, b, c, d, e, f
tr = self.currGroup.getAttribute("transform")
t = 'matrix(%f, %f, %f, %f, %f, %f)' % (a,b,c,d,e,f)
if (a, b, c, d, e, f) != (1, 0, 0, 1, 0, 0):
self.currGroup.setAttribute("transform", "%s %s" % (tr, t))
def translate(self... | recursive method called for each node in the tree.
"""
if self.verbose: print "### begin _SVGRenderer.drawNode(%r)" % node
self._canvas.comment('begin node %s'%`node`)
color = self._canvas._color
style = self._canvas.style.copy()
if not (isinstance(node, Path) an | d node.isClipPath):
pass # self._canvas.saveState()
#apply state changes
deltas = getStateDelta(node)
self._tracker.push(deltas)
self.applyStateChanges(deltas, {})
#draw the object, or recurse
self.drawNodeDispatcher(node)
rDeltas = self._tracker.po... |
import struct
from coinpy.lib.serialization.common.serializer import Serializer
from coinpy.lib.serialization.exceptions import MissingDataException
class VarintSerializer(Serializer):
def __init__(self, desc=""):
self.desc = desc
def serialize(self, value):
if (value < 0xfd):
... | singDataException("Decoding error: not enough data for varint of type : %d" % (prefix))
if (prefix == 0xFD):
return (struct.unpack_from("<H", data, cursor)[0], cursor + 2)
if (prefix == 0xFE):
return (struct.unpack_from("<I", data, cursor)[0], cursor + 4)
return (struct.u... | |
recvdContentChecksum = sha.sha(Contents).hexdigest().upper()
if recvdContentChecksum != ContentChecksum:
# data is corrupt do not proceed further
LOG_ACTION.log(LogType.Error, 'Content received did not match checksum with sha1, exit | ing Set')
return [-1]
(ConfigType, ConfigID, Contents, Ensure, ContentChecksum) = init_vars(ConfigType, ConfigID, Contents, Ensure, ContentChecksum)
retval = Set(ConfigType, ConfigID, Contents, Ensure, ContentChecksum)
return retval
def Test_Marshall(ConfigType, ConfigID, Contents | , Ensure, ContentChecksum):
recvdContentChecksum = md5.md5(Contents).hexdigest().upper()
if recvdContentChecksum != ContentChecksum:
LOG_ACTION.log(LogType.Info, 'Content received did not match checksum with md5, trying with sha1')
# validate with sha1
recvdContentChecksum = sha.sha(Cont... |
[]
rst_prolog = \
'''\
.. role:: bash(code)
:language: bash
.. role:: python(code)
:language: python
'''
rst_prolog = _dedent(rst_prolog)
nitpicky = True
# FIXME: encapsulate this in a Sphinx extension. make ``rfc_uri_tmpl`` a
# Sphinx config setting
rfc_uri_tmpl = 'https://tool... | rted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to | template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split... |
import os
import sys
import string
filenames = os.listdir(os.getcwd())
for file in filenames:
if os.path.splitext(file)[1] == ".o" or os.path.splitext(file)[1] == ".elf" :
print "objdumparm.exe -D "+file
os.system("C:/WindRiver/gnu/4.1.2-vxworks-6.8/x86- | win32/bin/objdumparm.exe -D "+file +" > " +file + ". | txt")
os.system("pause")
|
"""
WSGI config for cloudlynt project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... | ION
# setting points here.
from django.core.wsgi import ge | t_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
# stupid 2.7.2 by peterm, patch by Smack
# http://robotgame.org/viewrobot/5715
import random
import math
import rg
def around(l):
return rg.locs_around(l)
def around2(l):
return [(l[0]+2, l[1]), (l[0]+1, l[1]+1), (l[0], l[1]+2), (l[0]-1, l[1]+1),
(l[0]-2, l[1]), (l[0]-1, l[1]-1), (l[0], l[1]-2), (l[0]+1... | suicide()
##print "Too many enemies around, panic!"
return panic()
elif len(enemies) == 1:
if self.hp <= 10:
if robots[enemies[0]]['hp'] > | 15:
##print "Enemy will kill me, panic!"
return panic()
elif robots[enemies[0]]['hp'] <= 10:
##print "I will kill enemy, attack!"
return attack()
#else:
# # might tweak this
... |
ts=root.findall(".//"+self.ELEMENT_VARIABLE)
gads=[]
for e in elements:
gads.append(self.__getVariableDesc(e))
return gads
def getColumnDesc(self, columnName):
pass
def getGlobalAttributeDesc(self, attributeName):
element=self.__getGlobalAttributeE... | iableName=variableName
self.variableType=variableType
self.attribut | es=attributes
self.variableAttributeStrategyDesc=variableAttributeStrategyDesc
def getVariableName(self):
return self.variableName
def getVariableType(self):
return self.variableType
def getAttributes(self):
return self.attributes
def getVariableAttributeStrategyD... |
"""phial's custom errors."""
class ArgumentValidationError(Exception):
"""Excep | tion indicating argum | ent validation has failed."""
pass
class ArgumentTypeValidationError(ArgumentValidationError):
"""Exception indicating argument type validation has failed."""
pass
|
# Copyright (c) 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | eturn self._list("/flavors", "flavors")
def get(self, flavor):
"""
Get a specific flavor.
:rtype: :class:`Flavor`
"""
return self._get("/flavors/%s" % base. | getid(flavor),
"flavor")
|
']
wx.MessageBox('{} is down'.format(cb.GetValue()),
APPNAME,
style=wx.OK | wx.CENTRE | wx.ICON_ERROR)
def OnClickFullScreen(self, evt):
geometry = wx.Display().GetGeometry()
self._input['x'].SetValue(str(geometry[0]))
self._in... | mat(remote_ip, remote_port)
logging.info('url = {}'.format(url))
logging.info(' json = {}'.format(data_as_json))
req = urllib2.Request(url, data_as_json,
| {'Content-Type': 'application/json'})
response = urllib2.urlopen(req, None, 5)
result = response.read()
logging.info('result: {}'.format(result))
result = json.loads(result)
#switch back to json with pretty format
logging.debug(json.dump... |
(name):
raise StackException, 'Patch "%s" already exists' % name
# TODO: move this out of the stgit.stack module, it is really
# for higher level commands to handle the user interaction
def sign(msg):
return add_sign_line(msg, sign_str,
... | atch.set_authname(author_name)
patch.set_authemail(author_email)
patch.set_authdate(author_date)
patch.set_commname(committer_name)
patch.set_commemail(committer_email)
if before_existing:
insert_string(self.__applied_file, patch.get_name())
| elif unapplied:
patches = [patch.get_name()] + self.get_unapplied()
write_strings(self.__unapplied_file, patches)
set_head = False
else:
append_string(self.__applied_file, patch.get_name())
set_head = True
if commit:
if top:
... |
ver,
checkpoint_dir=checkpoint_dir,
checkpoint_filename_with_path=checkpoint_filename_with_path,
wait_for_checkpoint=wait_for_checkpoint,
max_wait_secs=max_wait_secs,
config=config)
if not is_loaded_from_checkpoint:
if init_op is None and not init_fn and self._local_ini... | of the TensorFlow m | aster to use.
config: Optional ConfigProto proto used to configure the session.
max_wait_secs: Maximum time to wait for the session to become available.
Returns:
A `Session`. May be None if the operation exceeds the timeout
specified by config.operation_timeout_in_ms.
Raises:
tf.... |
{
"name": "rmap1_ipv4",
"direction": "in",
}
]
... | "vrf": "RED_B",
"address_family": {
"ipv4": {
"unicast": {
"neighbor": {
"red1": {
"dest_link": {
| "r1-link2": {
"route_maps": [
{
"name": "rmap1_ipv4",
"direction": "in",
... |
cept Exception:
fs_enc = 'ascii'
if fs_enc == 'ascii':
raise RuntimeError('Click will abort further execution '
'because Python 3 was configured to use '
'ASCII as encoding for the environment. '
... | ams(ctx):
rv = param.get_help_record(ctx)
if rv is not None:
opts.append(rv)
if opts:
with formatter.section('Options'):
formatter.write_dl(opts)
def format_epilog(self, ctx, form | atter):
"""Writes the epilog into the formatter if it exists."""
if self.epilog:
formatter.write_paragraph()
with formatter.indentation():
formatter.write_text(self.epilog)
def parse_args(self, ctx, args):
parser = self.make_parser(ctx)
opts, ... |
job_execution = prepared_job_params['job_execution']
job_params = self._get_oozie_job_params(hdfs_user,
path_to_workflow,
oozie_params,
use_hbase_lib)
cli... | def get_possible_job_config(job_type):
return workflow_factory.get_possible_job_config(job_type)
@staticmethod
def get_supported_job_types():
return [edp.JOB_TYPE_HIVE,
edp.JOB_TYPE_JAVA,
edp.JOB_TYPE_MAPREDUCE,
edp.JOB_TYPE_MAPREDUCE_STREAMING,
... | r jb in job_binaries:
jb_manager.JOB_BINARIES.get_job_binary_by_url(jb.url). \
prepare_cluster(jb, remote=r)
def _upload_job_files_to_hdfs(self, where, job_dir, job, configs,
proxy_configs=None):
mains = list(job.mains) if job.mains else []
... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt'), encoding='utf-8') as f:
CHANGES = f.read()
setup(
name='sloth',
v... | thor_email='',
url='https://bitbucket.org/pride/sloth/',
# TODO: add keywords
#keywords='',
install_requires = ['python-dateutil', 'arrow'],
classifiers = [
"License :: OSI Approved :: GNU Affero General Public License v3"
"Operating System :: MacOS :: MacOS X",
"Operatin | g System :: Microsoft :: Windows",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
packages=find_packages(include=['sloth']),
include_package_data=True,
zip_s... |
#!/usr/bin/python
import unittest
from biosignalformat import *
class TestBaseObjects(unittest.TestCase):
def test_MinimalExperiment(self):
provider = XArchiveProvider("experiment001.7z")
#provider = ZipArchiveProvider("experiment001.zip")
experiment = Experiment({
"name": "Exp!... | })
experiment.addSubject(subject)
session = Session({
"name": "Subject001-Session001",
"description": "description-subject-session!"
})
subject.addSession(session)
channel = Channel({
"name": "AF8"
})
session.addChannel(cha... | nnel.setData([c/1e-12 for c in range(500000)])
experiment.write()
metadata = experiment.readMetadata()
self.assertEqual(metadata["name"], "Exp!")
self.assertEqual(metadata["description"], "blah!")
class TestPlugins(unittest.TestCase):
def test_plugins(self):
from biosignalf... |
e(obj, 'foo__' + constants.COMPARISON_ISNULL)
assert value is None
assert comparison == constants.COMPARISON_ISNULL, comparison
def test_get_attribute_returns_nested_object_value(self):
obj = MagicMock(child=MagicMock(foo='test'))
value, comparison = utils.get_attribute(obj, 'child_... | des_object_in_results_when_match(self, get_attr_mock):
source = [
MagicMock(foo=1),
MagicMock(foo=2),
]
get_attr_mock.return_value = None, None
results = utils.matches(*source, | foo__gt=0)
for x in source:
assert x in results
@patch('django_mock_queries.utils.get_attribute')
@patch('django_mock_queries.utils.is_match', MagicMock(return_value=False))
def test_matches_excludes_object_from_results_when_not_match(self, get_attr_mock):
source = [
... |
import talkey
from gtts import gTTS
import vlc
import time
import wave
import contextlib
class Speaker:
def __init__(self):
self.engine =talkey.Talkey()
def say(self, text_to_say):
self.engine.say(text_to_say)
def google_say(self, text_to_say, fname="1.mp3"):
tts = gTTS(text=text... | self.player.play()
self.player.stop()
os.re | move(fname)
|
# This file is part of cloud-init. See LICENSE file for license information.
"""cloud-init Integration Test Verify Script."""
from tests.cloud_tests.testcases import base
class TestSshKeysGenerate(base.CloudTestCase):
"""Test ssh keys module."""
# TODO: Check cloud-init-output for the correct keys being gen... | ertIsNotNone(out)
def test_ed25519_private(self):
"""Test ed25519 public key generated."""
out = self.get_data_file('ed25519_private')
self.assertIsNotNone(out)
| # vi: ts=4 expandtab
|
models.fields.AutoField', [], {'primary_key': 'True'}),
'low': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}),
'name': ('tx_tecreports.fields.MaxCharField', [], {'max_length': '250'}),
'report': ('django.db.models.fields.related.ForeignKey',... | rts.employer': {
'Meta': {'object_name': 'Employer'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('tx_tecreports.fields.MaxCharField', [], {'max_length': '250 | '})
},
u'tx_tecreports.filer': {
'Meta': {'object_name': 'Filer'},
'filer_id': ('tx_tecreports.fields.MaxCharField', [], {'max_length': '250'}),
'filer_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'filers'", 'to': u"orm['tx_tecreports.Fi... |
# -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2014 CERN | .
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but... | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Integrate Sphi... |
class StadisticRouter(object):
"""A router to control all database operations on models in
the stadistic application"""
def db_for_read(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'stadistic':
return 'nonrel'
retur... |
if model._meta.app_label == 'stadistic':
return 'nonrel'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"Deny an | y relation if a model in stadistic is involved"
if obj1._meta.app_label == 'stadistic' or obj2._meta.app_label == 'stadistic':
return True
return True
def allow_syncdb(self, db, model):
"Make sure the stadistic app only appears on the 'nonrel' db"
if db == 'nonrel':
... |
)]
def init(self):
self.event_map = {'allDownloadsProcessed': "all_downloads_processed",
'packageDeleted' : "package_deleted" }
self.queue = ArchiveQueue(self, "Queue")
self.failed = ArchiveQueue(self, "Failed")
self.interval = 60
... | delete,
keepbroken,
fid)
thread.ad | dActive(pyfile)
archive.init()
try:
new_files = self._extract(pyfile, archive, pypack.password)
finally:
pyfile.setProgress(100)
thread.fi... |
e', 'blank': 'True'}),
'feed_type': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
'frequency': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '8'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'r... | tification_subscriptions'", ' | to': "orm['auth.User']"})
},
'askbot.favoritequestion': {
'Meta': {'object_name': 'FavoriteQuestion', 'db_table': "u'favorite_question'"},
'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.... |
# cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation... | , out_path):
'''
Checkout a single file to out_path
@param url: file URL
@type url: str
@param out_path: output path
|
@type revision: str
'''
shell.call('svn export --force %s %s' % (url, out_path))
|
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer.CLI import template
from SoftLayer.CLI import virt
from SoftLayer import utils
import click
@click.command(epilog="See 'sl vs create-options' for valid opt... | l', '-i', help="Post-install script to download")
@click.option('--key', '-k',
multiple=True,
help="SSH keys to add to the root user")
@click.option('--disk', multiple=True, help="Disk sizes")
@click.option('--private',
is_flag=True,
help="Forces the VS to only ha... | k.option('--network', '-n', help="Network port speed in Mbps")
@click.option('--tag', '-g', multiple=True, help="Tags to add to the instance")
@click.option('--template', '-t',
help="A template file that defaults the command-line options",
type=click.Path(exists=True, readable=True, resolve_... |
ort Calendar, vCalAddress, vText
import icalendar
from datetime import timedelta
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
#fro... | cal_event = icalendar.Event()
cal_event.add('summary', event.eve | nt_name)
cal_event.add('dtstart', event.event_date)
cal_event.add('description', event.event_desc)
cal_event.add('categories',event.event_type)
cal_event.add('duration',timedelta(hours=1))
cal_event.add('url',"http://" + host + reverse('event_event_view',kwargs={'org_short_name':... |
"""SCons.Tool.sgiar
Tool-specific initialization for SGI ar (library archive). If CC
exists, static libraries should be built with it, so the prelinker has
a chance to resolve C++ template instantiations.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the gen... | , WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sgiar.py 4369 2009/09/19 15:58:29 scons"
import SCons.Defaults
import SCons.Tool
import SCons.Util
def generate(env)... | Detect('CC'):
env['AR'] = 'CC'
env['ARFLAGS'] = SCons.Util.CLVar('-ar')
env['ARCOM'] = '$AR $ARFLAGS -o $TARGET $SOURCES'
else:
env['AR'] = 'ar'
env['ARFLAGS'] = SCons.Util.CLVar('r')
env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES'... |
import unittest
from tow.dockerfile import Dockerfile
class DockerfileTest(unittest.TestCase):
def test_parse_spaced_envs(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile = ["ENV test 1"]
envs = d.envs()
self.assertEqual(envs, {"test": "1"})
def test_parse_many_e... | ")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'ENTRYPOINT /bin/sh', 'CMD ["-c"]']
self.assertEqual(d.find_entrypoint_or_cmd(), (["/bin/sh"], ["-c"]))
def test_find_entrypoint_or_cmd_cmd_only(self):
d = Docker | file("Dockerfile")
d._Dockerfile__dockerfile = ['FROM ubuntu', 'CMD ["/bin/sh", "-c", "-x"]']
self.assertEqual(d.find_entrypoint_or_cmd(), (None, ["/bin/sh", "-c", "-x"]))
def test_find_entrypoint_or_cmd_entrypoint_only(self):
d = Dockerfile("Dockerfile")
d._Dockerfile__dockerfile =... |
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance(), bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance
# 2of3 test from different nodes
bal = self.nodes[2].getbalance()
add... | self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
# decoderawtransaction tests
# witness transacti | on
encrawtx = "010000000001010000000000000072c1a6a246ae63f74f931e8365e15a089c68d61900000000000000000000ffffffff0100e1f50500000000000102616100000000"
decrawtx = self.nodes[0].decoderawtransaction(encrawtx, True) # decode as witness transaction
assert_equal(decrawtx['vout'][0]['value'], Decimal('1... |
from inspect import getmembers
from django.shortcuts import render
from utilities import get_wps_service_engine, list_wps_service_engines, abstract_is_link
def home(request):
"""
Home page for Tethys WPS tool. Lists all the WPS services that are linked.
"""
wps_services = list_wps_service_engines()
... | service.
"""
wps = get_wps_service_engine(service)
context = {'wps': wps,
'service': service}
return render(request, 'tethys_wps/service.html', context)
def process(request, service, identifier):
"""
View that displays a detailed description for a WPS process.
"""
wp... | rocess,
'service': service,
'is_link': abstract_is_link(wps_process)}
return render(request, 'tethys_wps/process.html', context)
|
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsComposerEffects.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
""... | angle)
self.mComposerRect1.setBackgroundColor(QColor.fromRgb(255, 150, 0))
self.mComposition.addComposerShape(self.mComposerRect1)
self.mComposerRect2 = | QgsComposerShape(50, 50, 150, 100, self.mComposition)
self.mComposerRect2.setShapeType(QgsComposerShape.Rectangle)
self.mComposerRect2.setBackgroundColor(QColor.fromRgb(0, 100, 150))
self.mComposition.addComposerShape(self.mComposerRect2)
def testBlendModes(self):
"""Test that blen... |
import traceback
class EnsureExceptionHandledGuard:
"""Helper for ensuring that Future's exceptions were handled.
This solves a nasty problem with Futures and Tasks that have an
exception set: if nobody asks for the exception, the exception is
never logged. This violates the Zen of Python: 'Errors s... | ) method that logs the traceback, where we ensure
that the helper object doesn't participate in cycles, and only the
Future has a reference to it.
The helper object is added when set_exception() is called. When
the Future is collected, and the helper is present, the helper
object is also collected... | its __del__() method will log the
traceback. When the Future's result() or exception() method is
called (and a helper object is present), it removes the the helper
object, after calling its clear() method to prevent it from
logging.
One downside is that we do a fair amount of work to extract the
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exampleLoaderTemplate.ui'
#
# Created: Sat Dec 17 23:46:27 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
... | t.setMargin(0)
self.gri | dLayout.setSpacing(0)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.splitter = QtGui.QSplitter(Form)
self.splitter.setOrientation(QtCore.Qt.Horizontal)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.layoutWidget = QtGui.QWidget(self.splitter)
self.l... |
# -*- coding: utf | -8 -*-
# Generated by Django 1.10.5 on 2017-03-22 11:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cotacao', '0003_auto_20170312_2049'),
]
operations = [
migr... | ='itens',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='itens', to='cotacao.Item'),
),
]
|
'''Python sys.excepthook hook to generate apport crash dumps.'''
# Copyright (c) 2006 - 2009 Canonical Ltd.
# Authors: Robert Collins <robert@ubuntu.com>
# Martin Pitt <martin.pitt@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Publ... | crash_counter)
with os.fdopen(os.open(pr_filename,
os.O_WRONLY | os.O_CREAT | | os.O_EXCL, 0o640), 'wb') as f:
pr.write(f)
finally:
# resume original processing to get the default behaviour,
# but do not trigger an AttributeError on interpreter shutdown.
if sys:
sys.__excepthook__(exc_type, exc_obj, exc_tb)
def dbus_service_unknown_analysis(... |
from fabric.api import run
from fabric.decorators import with_settings
from fabric.colors import green, yellow
|
from deployer.tasks.requirements import install_requirements
@with_settings(warn_only=True)
def setup_virtualenv(python_version='', app_name='', app_dir='', repo_url=''):
print(green("Setting up virtualenv on {}".format(app_dir)))
print(green('C | reating virtualenv'))
if run("pyenv virtualenv {0} {1}-{0}".format(python_version, app_name)).failed:
print(yellow("Virtualenv already exists"))
install_requirements(app_name, python_version)
|
#! usr/bin/python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
import datetime
from flask import redirect, url_for, flash, g
from flask_babel import gettext
from flask_login import login_required
from . import flicket_bp
from application import app, db
from application.flicket.mode... | icket_id=ticket_id))
# set status to open
status = FlicketStatus.query.filter_by(status='Open').first()
ticket.current_status = status
ticket.last_updated = datetime.datetime.now()
user = ticket.assigned
ticket.assigned = None
user.total_ | assigned -= 1
db.session.commit()
# add action record
add_action(ticket, 'release')
# send email to state ticket has been released.
f_mail = FlicketMail()
f_mail.release_ticket(ticket)
flash(gettext('You released ticket: %(value)s', value=ticket.id), category=... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | operations.PeeringsOperations
:ivar peering_service_locations: PeeringServiceLocationsOperations operations
:vartype peering_service_locations: azure.mgmt.peering.aio.operations.PeeringServiceLocationsOperations
:ivar peering_service_prefixes: PeeringServicePrefixesOperations operations
:vartype peering... | efixesOperations
:ivar prefixes: PrefixesOperations operations
:vartype prefixes: azure.mgmt.peering.aio.operations.PrefixesOperations
:ivar peering_service_providers: PeeringServiceProvidersOperations operations
:vartype peering_service_providers: azure.mgmt.peering.aio.operations.PeeringServiceProvide... |
#!python3
"""
This script downloads the favicons
Usage:
python3 update_alexa path/to/data.csv
"""
import os
import requests
favicon_path = os.path.join(os.path.dirname(__file__), "..", "icons")
def download_favicons(links):
for link in links:
netloc = link['netloc']
url = 'http://' + netloc... | print(url)
response = requests.get(
"https | ://realfavicongenerator.p.rapidapi.com/favicon/icon",
params={'platform': 'desktop', "site": url},
headers={'X-Mashape-Key': os.environ.get("mashape_key")}
)
except:
pass
else:
if response:
... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyid | f.daylighting import OutputControlIlluminanceMapStyle
log = logging.getLogger(__name__)
class TestOutputControlIlluminanceMapStyle(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
| def tearDown(self):
os.remove(self.path)
def test_create_outputcontrolilluminancemapstyle(self):
pyidf.validation_level = ValidationLevel.error
obj = OutputControlIlluminanceMapStyle()
# alpha
var_column_separator = "Comma"
obj.column_separator = var_column_separa... |
'''
Created on 24.03.2011
@author: michi
'''
from PyQt4.QtGui import QItemDelegate
from sqlalchemy import Table
from sqlalchemy.sql import Alias,Select
from ems import qt4
class ColumnSectionMapper(object):
def __init__(self,alchemySelect=None, parent=None):
self.__columnConfigs = []
self.__colu... | ect
self.__delegate = MapperDelegate(self,parent)
pass
def addColumn(self,columnName,translatedName=None, delegate=None):
if self.__columnConfigIdByName.has_key(columnName):
raise KeyError("Column %s already assigned" % columnName)
index = len(self.__columnConfigs)
... | 'translatedName':translatedName,
'delegate':delegate})
self.__columnConfigIdByName[columnName] = index
@property
def translatedColumnNames(self):
names = {}
for config in self.__columnConfigs:
names[config['name'... |
'sahara_proxy_domain')
job, job_exec = u.create_job_exec(job_type, proxy=True)
res = workflow_factory.get_workflow_xml(
job, u.create_cluster(), job_exec, input_data, output_data,
'hadoop')
self.assertIn("""
<property>
<name>fs... | ob_dict(job_dict, exec_job_dict)
self.assertEqual(job_dict,
{'edp_configs': edp_configs,
'configs': {'default1': 'value1',
'default2': 'changed'},
'params': {'param1': 'changed',
... | 'param2': 'value2'},
'args': ['replaced']})
self.assertEqual(orig_exec_job_dict, exec_job_dict)
def test_inject_swift_url_suffix(self):
w = workflow_factory.BaseFactory()
self.assertEqual(w.inject_swift_url_suffix("swift://ex/o"),
"swift:/... |
def __load():
import im | p, os, sys
ext = 'pygame/font.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dyn | amic(__name__, ext_path)
break
else:
raise ImportError(repr(ext) + " not found")
__load()
del __load
|
import re
source = [
('assert', 0x00, False, 'vreg'),
('raise', 0x05, False, 'vreg'),
('constant', 0x10, True, 'constant'),
('list', 0x20, True, 'vreg*'),
('move', 0x30, False, 'vreg vreg'),
('call', 0x40, True, 'vreg vreg*'),
('not', 0x41, True, 'vreg'),
('con... | g'),
('getglob', 0xF0, True, 'string'),
('setglob', 0xF1, True, 'string vreg'),
('loglob', 0xFF, False, 'vreg'),
]
enc = {}
dec = {}
names = {}
for opname, opcode, has_result, form in source:
assert opcode not in dec, opcode
pattern = re.split(r"\s+", form.rstrip('*'))
if form.endswith('... | = pattern.pop()
else:
variadic = None
enc[opname] = opcode, has_result, pattern, variadic
dec[opcode] = opname, has_result, pattern, variadic
names[opcode] = opname
|
from __future__ import (absolute_import, division, print_function)
import unittest
from testhelpers import Work | spaceCreationHelper
class SpectrumInfoTest(unittest.TestCase):
_ws = None
def setUp(self):
if self.__class__._ws is None:
self.__class__._ws = WorkspaceCreationHelper.create2DWorkspace | WithFullInstrument(2, 1, False) # no monitors
self.__class__._ws.getSpectrum(0).clearDetectorIDs()
def test_hasDetectors(self):
info = self._ws.spectrumInfo()
self.assertEquals(info.hasDetectors(0), False)
self.assertEquals(info.hasDetectors(1), True)
def test_isMasked(self... |
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from ..models import MyUser, Profile
from ..utils import perform_reputation_check
class CreateUserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'}
... | class ProfileSerializer(ser | ializers.ModelSerializer):
user = UserSerializer(read_only=True)
reputation = serializers.CharField(max_length=8, read_only=True)
follows = FollowSerializer(read_only=True, many=True)
url = serializers.HyperlinkedIdentityField(view_name='profiles:profile-detail')
questions_count = serializers.Seria... |
# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login
import notifications.urls
import not | ifications.tests.views
urlpatterns = [
url(r'^login/$', login, name='login'), # needed for Django 1.6 tests
url(r'^admin/', include(admin.site.urls)),
url(r'^test_make/', notifications.tests.views.make_notification),
url(r'^test/', notifications.tests.views.live_tester),
url(r'^', include(notifica... | ons.urls, namespace='notifications')),
]
|
ed Ut dolor exercitation consequat. qui Duis velit aliquip nulla culpa non consequat. qui elit, amet, esse velit ea ad veniam, Excepteur aliqua. ut deserunt Ut aliquip deserunt elit, occaecat ullamco dolore aliquip voluptate laborum. elit, sit in dolore est.
Ullamco ut velit non culpa veniam, in consequat. nostrud sint... | dent, aliqua. d | olore anim commodo ullamco do labore non ullamco non enim ipsum consectetur irure sint Lorem deserunt dolor commodo cillum velit dolore Excepteur laborum. in tempor anim mollit magna in quis consequat. non ex Duis undefined eiusmod pariatur. dolore dolor dolore pariatur. incididunt eiusmod Excepteur non id Duis et adip... |
y = lambda x: x["Number"])
self.FieldNameList = [x["Name"] for x in sortedFields] # *ordered*
class FITMessageGenerator:
def __init__(self):
self._types = {}
self._messageTemplates = {}
self._definitions = {}
self._result = []
# All our convience functions for preparing the field types to be packed.
de... | return struct.pack("<I", 0xFFFFFFFF)
return struct.pack("<I", round(input * 100))
def altitudeFormatter(input):
| # UINT16
if input is None:
return struct.pack("<H", 0xFFFF)
return struct.pack("<H", round((input + 500) * 5)) # Increments of 1/5, offset from -500m :S
def semicirclesFormatter(input):
# SINT32
if input is None:
return struct.pack("<i", 0x7FFFFFFF) # FIT-defined invalid value
return struct.p... |
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('Virt... | rl("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscrip | tionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_metho... |
remove deselect and select the text in the new tab
self.deselectText()
#display
texts_widget = Viewer.ListTexts(element, lvalued,
self.listeObjetsTextes, self)
#TODO sorting by date/score, filter
for sem, tri in texts_widget.sort():
txt = self.l... | self.tr("Sentences"))
for | i in range(0, self.tab_sentences.count()):
if (self.tab_sentences.tabText(i) == item):
self.tab_sentences.removeTab(i)
show_sentences_widget = QtGui.QWidget()
show_sentences_box = QtGui.QVBoxLayout()
# on prend toute la place
... |
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
try:
from thrift.protocol import fastbinary
exce... | , '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self._ | _dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
|
self.request_id,
self.host_id,
self.region))
# Common error responses listed here
# http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.htmlRESTErrorResponses
class Known... |
class En | tityTooLarge(KnownResponseError):
message = 'Your proposed upload exceeds the maximum allowed object size.'
class ExpiredToken(KnownResponseError):
message = 'The provided token has expired.'
class IllegalVersioningConfigurationException(KnownResponseError):
message = 'Indicates that the versioning config... |
# coding: utf-8
from mongomock import MongoClient as MockMongoClient
from .base import *
# For tests, don't use KoBoCAT's DB
DATABASES = {
'default': dj_database_url.config(default='sqlite:///%s/db.sqlite3' % BASE_DIR),
}
|
DATABASE_ROUTERS = ['kpi.db_routers.TestingDatabaseRouter']
TESTING = True
# Decrease prod value to speed-up tests
SUBMISSION_LIST_LIMIT = 100
ENV = 'testing'
# Run all Celery tasks synchronously during testing
CELERY_TASK_ALWAYS_EAGER = True
MONGO_CONNECTION_URL = 'mongodb://fakehost/formhub_test'
MONGO_CONNECT... | True)
MONGO_DB = MONGO_CONNECTION['formhub_test']
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2015, P | hilipp Klaus. All rights reserved.
License: GPLv3
"""
from distutils.core import setup
setup(name='netio230a',
version = '1.1.9',
description = 'Python package to control the Koukaam NETIO-230A',
long_description = 'Python software to access the Koukaam NETIO-230A and NETIO-230B: power distribution... | interface',
author = 'Philipp Klaus',
author_email = 'philipp.l.klaus@web.de',
url = 'https://github.com/pklaus/netio230a',
license = 'GPL3+',
packages = ['netio230a'],
scripts = ['scripts/netio230a_cli', 'scripts/netio230a_discovery', 'scripts/netio230a_fakeserver'],
zip_safe ... |
stances to interact with the same
SpiNNaker boards.
A very simple protocol is used between the client and server. Clients may send
the following new-line delimited commands to the server:
* ``VERSION,[versionstring]\n`` The server will disconnect any client with an
incompatible version number reported for ``[versio... | i") == __version__
sock.send(b"OK\n")
def handle_led(self, sock, args):
"""Handle "LED" commands.
Set the state of a diagnostic LED on a board.
Arguments: c,f,b,led,state
Returns: OK
"""
c, f, b, led, state = map(int, args.split(b","))
self.se | t_led(sock, c, f, b, led, state)
sock.send(b"OK\n")
def handle_target(self, sock, args):
"""Handle "TARGET" commands.
Determine what is at the other end of a given link.
Arguments: c,f,b,d
Returns: c,f,b,d or None
"""
c, f, b, d = map(int, args.split(b","))
target = self.wiring_probe... |
from . import Renderer
from PIL import Image, ImageFont, ImageQt, ImageDraw
from PyQt5 import QtGui
'''
Renders a single line of text at a given position.
'''
class TextRenderer(Renderer):
MSFACTOR = 8
def __init__(self, gl, text, pos, size = 64):
super().__init__(gl)
self.text = te... | ear.
textSize = font.getsize(self.text)
border = 5
image = Image.new("RGBA", (textSize[0] + 2*border, textSize[1] + 2*border), None)
draw = ImageDraw.Draw(image)
draw.text((border, border), self.text, font=font, fill="white")
del draw
imgWidth = float(... | s =[0.0, self.fSize - imgHeight, 2.0,
0.0, float(self.fSize), 2.0,
imgWidth, float(self.fSize), 2.0,
imgWidth, self.fSize - imgHeight, 2.0]
self.texCoords=[0.0, 0.0, 2.0,
0.0, 1.0, 2.0,
1.0, 1... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ef cached_novaclient(request, version=None):
(
username,
token_id,
project | _id,
project_domain_id,
nova_url,
auth_url
) = get_auth_params_from_request(request)
if version is None:
version = VERSIONS.get_active_version()['version']
c = nova_client.Client(version,
username,
token_id,
... |
import doctest
from insig | hts.parsers import ls_var_cache_pulp
from insights.parsers.ls_var_cache_pulp import LsVarCachePulp
from insights.tests import context_wrap
LS_VAR_CACHE_PULP = """
total 0
drwxrwxr-x. 5 48 1000 216 Jan 21 12:56 .
drwxr-xr-x. 10 0 0 121 Jan 20 13:57 ..
lrwxrwxr | wx. 1 0 0 19 Jan 21 12:56 cache -> /var/lib/pulp/cache
drwxr-xr-x. 2 48 48 6 Jan 21 13:03 reserved_resource_worker-0@dhcp130-202.gsslab.pnq2.redhat.com
drwxr-xr-x. 2 48 48 6 Jan 21 02:03 reserved_resource_worker-1@dhcp130-202.gsslab.pnq2.redhat.com
drwxr-xr-x. 2 48 48 6 Jan 20 14:03 resource_manage... |
)
def set_terminated(self, status):
self.terminated = True
self.status = status
MockExperiment = namedtuple("MockExperiment", ["name", "experiment_id"])
class MockMlflowClient:
def __init__(self, tracking_uri=None, registry_uri=None):
self.tracking_uri = tracking_uri
self.re... | xisting_experiment"
logger = MLflowLoggerCallback()
logger.setup()
self.assertListEqual(logger.client.experiment_names,
["existing_experiment"])
self.assertEqual(logger.experiment_id, 0)
# Pass in existing experiment id as env var.
clear_env_... | LflowLoggerCallback()
logger.setup()
self.assertListEqual(logger.client.experiment_names,
["existing_experiment"])
self.assertEqual(logger.experiment_id, "0")
# Pass in non existing experiment id as env var.
clear_env_vars()
os.environ["MLFLO... |
# __main__.py is used when a package is exec | uted | as a module, i.e.: `python -m pptx_downsizer`
if __name__ == '__main__':
from .pptx_downsizer import cli
cli()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.