prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from pycp2k.inputsection import InputSection
from ._each174 import _each174
class _diis_info3(InputSection):
def __init__(self):
InputSection.__init__(self)
| self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
self.Log_print_key = None
self.EACH = _each174()
self._name = "DIIS_INFO"
self._keywords = {'Log_print_key': 'LOG_PRINT_KEY', 'Filename': 'FILENAME', 'A... | ast': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS'}
self._subsections = {'EACH': 'EACH'}
self._attributes = ['Section_parameters']
|
imitations
# under the License.
import uuid
from keystoneclient import exceptions
from keystoneclient import fixture
from keystoneclient.tests.unit.v2_0 import utils
from keystoneclient.v2_0 import client
from keystoneclient.v2_0 import tenants
from keystoneclient.v2_0 import users
class TenantTests(utils.TestCa... | "values": [
{
"enabled": True,
"description": "A description cha | nge!",
"name": "invisible_to_admin",
"id": self.INVIS_ID,
},
{
"enabled": True,
"description": "None",
"name": "demo",
"id": self.DEMO_I... |
= 0.0000001 # Vdd rise setup time to nMCLR/Vpp rise
delayP14 = 0.00000001 # Data out Valid from SCK rise
delayP15 = 0.000002 # PGM rise setup time to nMCLR/Vpp rise
userIDLocationSize = 8
userIDLocationAddr = 0x200000
deviceIDAddr = 0x3FFFFE
configWordAddr = 0x300000
deviceIDLength = 2
v... | ge):
self.enterPM()
if len(image) > self.fuseBytes:
self.throwError("Invalid Fus | es image size %d (expected less than %d)" % \
(len(image), self.fuseBytes))
self.executeCode((0x8EA6, 0x8CA6, 0xEF00, 0xF800))
for fuseAddr in range(0,len(image)):
self.executeCode(self.getCodeAddrToTBLPTR(self.configWordAddr+fuseAddr))
if(fuseAddr & 0x01):
byte = byte2int(image[fuseAddr]) << 8
... |
from ez_setup import use_se | tuptools
use_setuptools()
from setuptools import setup, find_packages
import sys
# Define required packages.
requires = []
# Assume spidev is required on non-windows & non-mac platforms (i.e. linux).
if sys.platform != 'win32' and sys.platform != 'darwi | n':
requires.append('spidev')
setup(name = 'Adafruit_GPIO',
version = '0.8.0',
author = 'Tony DiCola',
author_email = 'tdicola@adafruit.com',
description = 'Library to provide a cross-platform GPIO interface on the Raspberry Pi and Beaglebone Bla... |
cla | ss LSA(object):
def __init__( | self,input_path,output_path):
super(LSA,self).__init__()
self.input_path = input_path
self.output_path = output_path
self.hpfx = 'k, bins: [' |
rt time
class SettingsEntry(db.Model):
valid_users_entry = db.ListProperty(str,indexed=False,default=None)
secret_hash_entry = db.StringProperty()
class TemperatureEntry(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
room = db.StringProperty()
temperature = db.FloatProperty()
target ... | y = '['+rightNow+','+furnace+'],',
room_entry = '['+rightNow+','+room+'],',
mode_entry = '['+rightNow+','+mode+'],',
outside_entry = '['+rightNow+','+outside+'] | ,'
)
newEntry.put()
self.response.headers.add_header("X-Raspberry-Pi-Data", temp +','+ \
target +','+ furnace + \
','+ room +','+ mode + \
... |
from __future__ import print_function, absolute_import
import weakref
class PDroneCreator(object):
def __init__(self, mainwindow, clipboard, title="drones"):
self._mainwindow = mainwindow
self._clipboard = clipboard
self._subwin = mainwindow.newSubWindow(title)
from . import PTree... | dronetype = ".".join(dronetype)
self._clipboard.set_dragboard_value("drone", dronetype)
def append(self, dronename):
key = tuple(dronename.split("."))
self._tree.append(key)
def remove(self, dronename):
key = tuple(dronename.spl | it("."))
self._tree.remove(key)
|
# -*- coding:UTF-8 -*-
""" pyBox Modbus"""
# !/usr/bin/python
# Python: 3.5.2
# Platform: Windows/ARMv7
# Author: Heyn
# Program: Modbus RTU & TCP
# History: 2017/02/14 V1.0.0 [Heyn]
# 2017/03/08 V1.0.1 [Heyn] Send return string.
# 2017/04/07 V1.0.2 [Heyn] Redesign PBoxModbus class functions.
... | Read String from Device.
readlist = [function code, address, data type]
"""
if self.isopened is False:
return None
try:
ret = pymodbus.read_registers(readlist[0:3], size)
except BaseException as err:
if self.platform == 'linux':... | return None
else:
if self.platform == 'linux':
led.ioctl(led.IXORA_LED4, led.RED, led.LOW)
led.ioctl(led.IXORA_LED4, led.GREEN, led.HIGH)
else:
pass
# And each hexadecimal number into ASCII code
return ''.join((lambda v: [... |
"""XKNX vers | ion."""
__version__ = "0.1 | 9.2.dev"
|
'CapsStyle',
'Class', 'Color', 'ColorMatrixFilter', 'ColorTransform', 'ContextMenu',
'ContextMenuBuiltInItems', 'ContextMenuEvent', 'ContextMenuItem',
'ConvultionFilter', 'CSMSettings', 'DataEvent', 'Date', 'DefinitionError',
'DeleteObjectSample', 'Diction... | pDrawable', 'ID3Info', 'IDataInput', 'IDataOutput', 'IDynamicPropertyOutput'
'IDynamicPropertyWriter', 'IEventDispatcher', 'IExternalizable',
'IllegalOperationError', 'IME', 'IMEConversionMode', 'IMEEvent', 'int',
'InteractiveObj | ect', 'InterpolationMethod', 'InvalidSWFError', 'InvokeEvent',
'IOError', 'IOErrorEvent', 'JointStyle', 'Key', 'Keyboard', 'KeyboardEvent', 'KeyLocation',
'LineScaleMode', 'Loader', 'LoaderContext', 'LoaderInfo', 'LoadVars', 'LocalConnection',
'Locale', 'Math', 'Matrix', ... |
from basetest import *
from zfs_autobackup.LogStub import LogStub
from zfs_autobackup.ExecuteNode import ExecuteError
class TestZfsNode(unittest2.TestCase):
def setUp(self):
prepare_zpools()
# return super().setUp()
def test_consistent_snapshot(self):
logger = LogStub()
descr... | 3
test_source2/fs3/sub
test_target1
""")
with self.subTest("second snapshot, no changes, empty snapshot"):
node.consistent_snapshot(node.selected_datasets(property_name="autobackup:test", exclude_paths=[], exclude_received=False, exclude_unchanged=False, min_change=200000), "test-20101111000002", 0... | r = shelltest("zfs list -H -o name -r -t all " + TEST_POOLS)
self.assertEqual(r, """
test_source1
test_source1/fs1
test_source1/fs1@test-20101111000001
test_source1/fs1@test-20101111000002
test_source1/fs1/sub
test_source1/fs1/sub@test-20101111000001
test_source1/fs1/sub@test-20101111000002
test_source2
tes... |
import time # about 60 s
def countBinOnes(x):
cnt = 0
while x != 0:
cnt += 1
x &= x - 1
return cnt
def isSpecialSumSet(A):
N = ( 1 << len(A) ) - 1
subset = N * [None]
for i in range(1, N):
subset[i] = 0
for j in range(len(A)):
if (i >> j) & 1 == 1:
... | rify the last element
for j in range( 1 << ( len(A) - 1 ), N ):
if i&j == 0:
if subset[i] == subset[j]: # rule i fails
return False
if subset[i] > subset[j]:
if countBinOnes(i) < countBinOnes(j): # rule ii fails
... | ue
# for loop is too ugly, recursion is beautiful
def findSpecialOptimum(a, pos):
if pos > 1:
while a[0] + a[1] > a[pos]:
if isSpecialSumSet(a[:pos + 1]) == True:
if pos == len(a) - 1: # find one, print it
print a, sum(a)
return
... |
from django.db.models import CharField, Value as V
from django.db.models.functions import Coalesce, Length, Upper
from django.test import TestCase
from django.test.utils import register_lookup
from .models import Author
class UpperBilateral(Upper):
bilateral = True
class FunctionTests(TestCase):
def test_... | hor.objects.create(name='Rhonda Simpson', alias='ronny')
authors = Author.objects.order_by(Length(Coalesce('alias', 'name')))
self.assertQuerysetEqual(
authors, [
| 'Rhonda Simpson',
'John Smith',
],
lambda a: a.name
)
authors = Author.objects.order_by(Length(Coalesce('alias', 'name')).desc())
self.assertQuerysetEqual(
authors, [
'John Smith',
'Rhonda Simpson',... |
#### NOTICE: THIS FILE IS AUTOGENERATED |
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/poi/shared_tatooine_desert_demons_camp_medium.iff"
result.attribute_template_id = -1
result.stfName("poi | _n","base_poi_building")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import unittest
from webtest import TestApp
import test_helper
class ErrorsControllerTests(unittest.Te | stCase):
def test_error_404(self):
| app = TestApp(test_helper.get_app())
assert app.get('/error/404').status == '200 OK'
def test_error_500(self):
app = TestApp(test_helper.get_app())
assert app.get('/error/500').status == '200 OK'
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2012 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y | ou 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = '1.1.1'
VERSION_DEV = True
VERSION_DATE = '20140606'
def GetVersion():
"""Returns a version information for plaso."""
if not VERSION_DEV:
return __vers... |
import datetime
import logging
from unittest.mock import patch
from django.test import TestCase
from django.test.utils import override_settings
from konfera import models
from payments import utils
from payments.models import ProcessedTransaction
def make_payment(new_data):
data = {
'date': datetime.dat... | '2016-09-26', '2016-09-29')
timezone_mock.assert_called_once_with()
class TestGetNotProcessedPayments(TestCase):
def test_no_processed_payment_is_available(self):
payments = [
make_payment({'transaction_id': '1'}),
make_payment({'transaction_id': '2'}),
]
se... | essed_payments_filtered(self):
payments = [
make_payment({'transaction_id': '1'}),
make_payment({'transaction_id': '2'}),
make_payment({'transaction_id': '3'}),
]
ProcessedTransaction.objects.create(transaction_id='2', amount=0)
self.assertEqual(
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Event CRM Sale',
'version': '1.0',
'category': 'Marketing/Events',
'website': 'ht | tps://www.odoo.com/page/events',
'description': "Add information of sale order linked to | the registration for the creation of the lead.",
'depends': ['event_crm', 'event_sale'],
'data': [
'views/event_lead_rule_views.xml',
],
'installable': True,
'auto_install': True,
}
|
"eol": "2222-07-01"
},
{
"id": 178028,
"sla": "security_fixes",
"eol": "2222-07-01"
}
],
"type": "rpm",
"active": True,
... | "name": "f26",
"slas": [
{
| "id": 646309,
"sla": "security_fixes",
"eol": "2222-07-01"
},
{
"id": 646303,
"sla": "bug_fixes",
"eol": "2222-07-01"
... |
dictionary = {"GEEKS", "FOR", "QUIZ", "GO"}
N, M = 3, 3
board = [['G','I','Z'],
['U','E','K'],
['Q','S','E']]
class Graph:
class Vertex:
def __int__(self, v):
self.val = v
self.adj = []
def findWords(board=board):
def search(node, word, visited):
if node not in visited:
visited.a | ppend(node)
word.append(node.val)
for adjNode in node.adj:
search(node, word, visited)
if word not in dictionary:
word.pop()
result = []
g = creategraph(board)
for u in g.vertices():
visited = []
visited.append(u)
word = ""
for adj in u.adj:
... | if word in dictionary:
result.append(word)
return result
if __name__=="__main__":
print(findWords()) |
# -*- encoding:ut | f-8 -*-
from flask import Flask
app = Flask(__name__)
@app.route('/config')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host="0.0.0.0", port=80 | 80)
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['aggregate | .py']
DATA_FILES = []
OPTIONS = {'argv_emulatio | n': True}
setup(
app=APP,
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
class NamespaceAlr | eadyRegistered(Exception):
pass
class NoParentFound(Exception):
pas | s
|
if subgroup == 'END_GROUP':
break
elif line[1] == '(':
while line:
line=lines.next()
line = line.replace('"','').strip()
subvalue+=line
if line[-1:]==';':
... | nrow
dataset = None
band = None
# will return '/media/Arc/eo_archive_proc/VHR_SAT_IMAGE/SPOT6/20140704_SPOT/binned_SPOT6_20140704/B0.binned_SPOT6_20140704.tif'
# the function input defined in the beginining: out_put_dir, product just we have to change the product name.....
def product_output_name(out_put_dir... | oduct_output_name)
return product_path_file
def output_file(output_name,output_array,geoTransform,proj,ncol,nrow):
format = "GTiff"
driver = gdal.GetDriverByName( format )
outDataset = driver.Create(output_name,ncol,nrow,1,GDT_Float32)
outBand = outDataset.GetRasterBand(1)
outBand.WriteArray(o... |
import cProfile
import unittest
import pstats
if __name__ == '__main__':
suite = | unittest.TestLoader().discover('.')
def runtests():
# set verbosity to 2 to see each test
unittest.TextTestRunner(verbosity=1, buffer=True).run(suite)
cProfile.run(
'runtests()', filename='test_cprofile_results.log', sort='cumtime')
p = pstats.Stats('test_cprofile_results.log')
... | rint_stats(100)
|
'''
Analysis plugin for supporting WorkspaceEmulators during analysis pass.
Finds and connects Switch Cases, most specifically from Microsoft.
'''
import envi
import envi.archs.i386 as e_i386
import vivisect
import vivisect.analysis.generic.codeblocks as vagc
def analyzeJmp(amod, emu, op, starteip):
'''
Top ... | if loc != None:
if loc[0] != vaCase:
return False
if loc[vivisect.L_LTYPE] != vivisect.LOC_OP:
return False
else:
vw.makeCode(vaCase)
#if we reach here, we're going to assume the location is valid.
| vw.verbprint( "0x%x MS Switch Case Spray: emu.getBranchNode( emu.curpath , 0x%x )" % (vaSwitch, vaCase))
vw.addXref(vaSwitch, vaCase, vivisect.REF_CODE)
return vaCase
if globals().get('vw'):
verbose = vw.verbose
vw.verbose = True
vw.vprint("Starting...")
findSwitchCase(vw)
vw.vprint("D... |
w
long ago the date represents.
Ported from PrettyDate by John Resig
"""
if not iso_datetime: return ''
import math
if isinstance(iso_datetime, basestring):
iso_datetime = datetime.datetime.strptime(iso_datetime, DATETIME_FORMAT)
now_dt = datetime.datetime.strptime(now(), DATETIME_FORMAT)
dt_diff = now_dt ... | ef expand_relative_urls(html):
# expand relative urls
url = get_url()
if url.endswith("/"): url = url[:-1]
def _expand_relative_urls(match):
to_expand = list(match.groups())
if not to_expand[2].startswith("/"):
to_expand[2] = "/" + to_expand[2]
to_expand.insert(2, url)
if 'url' in to_expand[0] and to_e... | h('(') and to_expand[-1].endswith(')'):
# background-image: url('/assets/...') - workaround for wkhtmltopdf print-media-type
to_expand.append(' !important')
return "".join(to_expand)
html = re.sub('(href|src){1}([\s]*=[\s]*[\'"]?)((?!http)[^\'" >]+)([\'"]?)', _expand_relative_urls, html)
# background-image... |
impor | t pytest
import os
def test_launch (launch):
serve = '../../atila/example/serve.py'
if not os.path.isfile (serve):
return
with launch (serve) as engine:
for i in range (2):
resp = engine.axios.get ('/apis/rest-api{}'.format (i == 1 and 2 or ''))
assert resp.status_c... | for i in range (2):
resp = engine.axios.get ('/apis/rest-api{}'.format (i == 1 and 2 or ''))
assert resp.status_code == 200
assert 'result' in resp.data
assert 'info' in resp.data ['result']
|
# This file is p | art of Mok | sha.
# Copyright (C) 2008-2010 Red Hat, Inc.
#
# 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 agree... |
# -*- coding: utf-8 -*-
import logging
import threading
from midas.compat import HTTPError
from midas.compat import Queue
from midas.crunchbase_company import CompanyList
import midas.scripts
class FetchCrunchbaseCompanies(midas.scripts.MDCommand):
"""
Crawl the companies information from crunchbase.com an... | g.info('{0}: Updating'.format(self.inst))
self.make_update(0)
self.q.task_done()
def make_update(self, tries=0):
try:
self.inst.update()
except HTTPError as e:
if e.code == 404:
logging.critical('{0}: Got 404'.format(self.inst))
... | , tries + 1)
)
self.make_update(tries + 1)
else:
logging.exception(e)
except Exception as e:
logging.critical(
'{0}: An exception occured'.format(self.inst))
logging.exception(e)
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MO | DIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_weaponsmith_trainer_02.iff"
result.attribute_template_id = 9
result.stfName("npc_name","human_base_m... | END MODIFICATIONS ####
return result |
10,
"points_possible": 10,
"contributing_assessments": 123,
"staff_id": "staff 1",
}
_, submission = self._create_workflow_with_status(
"user 1",
"test/1/1",
"peer-problem",
"peer",
steps=["peer"]
)
... | workflow_api.cancel_workflow(
submission_uuid=submission["uuid"],
| comments="Inappropriate language",
cancelled_by_id=ITEM_2['student_id'],
assessment_requirements=requirements
)
# Check workflow is cancelled.
self.assertTrue(workflow_api.is_workflow_cancelled(submission["uuid"]))
# Status for workflow should be cancel... |
patch_ | size = 1 | |
from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required
from .views import *
urlpatterns = [
# Listado
url(r'^evaluacion-lista/', login_required(evaluacion_list), name='listar_evaluacion'),
# Evaluacion paso a paso
url(r'^generar/step1/$', login_required(evaluacion_ste... | luacion_id>\d+)/$', login_required(evaluacion_step2), name='evaluacion_step2'),
url(r'^generar/step3/ | (?P<evaluacion_id>\d+)/$', login_required(evaluacion_step3), name='evaluacion_step3'),
url(r'^generar/step4/(?P<evaluacion_id>\d+)/$', login_required(evaluacion_step4), name='evaluacion_step4'),
# Evaluacion automatica
url(r'^automatica/step1/$', login_required(evaluacion_rapida_step1), name='evaluacion_rapida_step... |
## \file
## \ingroup tutorial_tdataframe
## \notebook -nodraw
## This tutorial shows how to express the concept of ranges when working with the TDataFrame.
## \macro_code
##
## \date March 2017
## \author Danilo Piparo
import ROOT
fill_tree_code = '''
void fill_tree(const char *filename, const char *treeName)
{
TF... | me, "RECREATE");
TTree t(treeName, treeName);
int b1;
float b2;
t.Branch("b1", &b1);
t.Branch("b2", &b2);
for (int i = 0; i < 100; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
return;
}
'''
# We prepare an input tree to run on
fileName = "tdf006_ranges_py... | "myTree"
ROOT.gInterpreter.Declare(fill_tree_code)
ROOT.fill_tree(fileName, treeName)
# We read the tree from the file and create a TDataFrame.
TDF = ROOT.ROOT.Experimental.TDataFrame
d = TDF(treeName, fileName)
# ## Usage of ranges
# Now we'll count some entries using ranges
c_all = d.Count()
# This is how you can ... |
from __future__ import absolute_import
from django.db import models
from django.test import TestCase
from .models import Author, Book
signal_output = []
def pre_save_test(signal, sender, instance, **kwa | rgs):
signal_output.append('pre_save signal, %s' % instance)
if kwargs.get('raw'):
signal_output.append('Is raw')
def post_save_test(signal, sender, instance, **kwargs):
signal_output.append('post_save signal, %s' % instance)
if 'created' in kwargs:
if kwargs['created']:
sig... | _output.append('Is updated')
if kwargs.get('raw'):
signal_output.append('Is raw')
def pre_delete_test(signal, sender, instance, **kwargs):
signal_output.append('pre_save signal, %s' % instance)
signal_output.append('instance.id is not None: %s' % (instance.id != None))
def post_delete_test(signal,... |
d a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""These are tests for the bodhi.server.consumers.automatic_updates module."""
from copy import deepcopy
from unittest import mock
i... | ert update.notes == f"""Automatic update for colord-1.3.4-1.fc26.
##### **Changelog**
```
{changelog}
```"""
assert len(update.bugs) > 0
assert update.bugs[0].bug_id == 112233
@mock.patch.dict(config, [('bz_exclude_rels', ['F17'])])
@mock.patch('bodhi.server.models.RpmBuild.get_changelog')
... | te_changelog):
"""Assert that a bug is not added for excluded release."""
changelog = ('* Sat Aug 3 2013 Fedora Releng <rel-eng@lists.fedoraproject.org> - 2\n'
'- Added a free money feature.\n- Fix rhbz#112233.')
mock_generate_changelog.return_value = changelog
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 20... | lse:
thrust = thrust / 2 + 0.5
if althold and self.has_ | pressure_sensor:
#thrust = int(round(JoystickReader.deadband(thrust,0.2)*32767 + 32767)) #Convert to uint16
thrust = 32767
else:
if thrust < -0.90 or emergency_stop:
thrust = 0
else:
thrust = self.min_thr... |
import types
import functools
import unittest
from .agent import Config, Agent
# XXX bring into compliance with python 2.7 unittest api
class AssertRaisesContextManager(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(se... | est('post', url, *args, **kwargs)
def follow_redirect(self):
return self._agent.follow_redirect()
def submit_form(self, form, elements=None):
return self._agent.submit_form(form, elements)
# XXX move to utu
# XXX accept kwargs |
def assert_raises(self, expected, *args):
if args:
return self.assertRaises(expected, *args)
else:
return AssertRaisesContextManager(expected)
def assert_status(self, code):
self._agent.assert_status(code)
def assert_redirected_to_uri(self, target):... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ObservationTools documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 30 14:32:48 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... | ervationTools'
copyright = '2017, IA'
author = 'IA'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
... | also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path... |
from distutils.core import setup
fr | om distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdcla | ss = {'build_ext': build_ext},
ext_modules = [Extension("capture", ["capture.pyx"])]
)
|
# -*- coding:utf-8 -*-
"""
# Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today)
# Created Time : Fri Feb 20 21:38:57 2015
# File Name: wechatService.py
# Description:
# :copyright: (c) 2015 by Pegasus Wang.
# :license: MIT, see LICENSE for more details.
"""
import json
import time
import urllib
import ... | u'您发送的是图片消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE:
respContent = u'您发送的是语音消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO:
respContent = u'您发送的是视频消息!'
| elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION:
respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK:
respContent = u'您发送的是链接消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
eventType = requestMap.get(u'Event')
... |
from .app import App as _App
class UserApp(_App):
'''
An o | bject based on the relationship between a user and an app. A subclass of :class:`steamfront.app.App`.
This will not contain any of the attributes for :class:`steamfront.app.App` until :meth unlazify: has been called.
Should not be called manually - | will be automatically generated with a :class:`steamfront.user.User` instance.
:param dict appdata: The app data that came from the API through the user.
:param steamfront.user.User user: The user to whom the app belongs.
:ivar player_id: A `str` containing the player's ID.
:ivar play_time: An `int` co... |
Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed i... | PasswordPage, VerifCodePage
__all__ = ['CICBrowser']
# Browser
class CICBrowser(Browser):
PROTOCOL = 'https'
DOMAIN = 'www.cic.fr'
CERTHASH = '9f41522275058310a6fb348504daeadd16ae852a686a91383b10ad045da76d29'
ENCODING = 'iso-8859-1'
USER_AGENT = Browser.USER_AGENTS['wget']
PAGES = {'https://... | ww.cic.fr/.*/fr/banque/situation_financiere.cgi': AccountsPage,
'https://www.cic.fr/.*/fr/banque/situation_financiere.html': AccountsPage,
'https://www.cic.fr/.*/fr/banque/espace_personnel.aspx': UserSpacePage,
'https://www.cic.fr/.*/fr/banque/mouvements.cgi.*': OperationsPage,
... |
# -*- coding: utf-8 -*-
"""
聚类和EM算法
~~~~~~~~~~~~~~~~
聚类
:copyright: (c) 2016 by the huaxz1986.
:license: lgpl-3.0, see LICENSE for more details.
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.dataset | s.samples_generator import make_blobs
# from .agglomerative_clustering import test_AgglomerativeClustering,test_AgglomerativeClustering_nclusters,test_AgglomerativeClustering_linkage
# from .dbscan import test_DBSCAN,test_DBSCAN_epsilon,test_DBSCAN_min_samples
from chapters.Cluster_EM.gmm import test_GMM,test_GMM_cov_... | pe,test_GMM_n_components
# from .kmeans import test_Kmeans,test_Kmeans_n_init,test_Kmeans_nclusters
def create_data(centers,num=100,std=0.7):
'''
生成用于聚类的数据集
:param centers: 聚类的中心点组成的数组。如果中心点是二维的,则产生的每个样本都是二维的。
:param num: 样本数
:param std: 每个簇中样本的标准差
:return: 用于聚类的数据集。是一个元组,第一个元素为样本集,第二个元素为样本集的真... |
# Copyright 2014 Google Inc. 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 required by applicable law or ... | path of the subfolder to list.
merge_local_files: boolean. If True, the returned lis | t will
contain files found on either the datastore filesystem or the
read-only local filesystem. If a file is found on both, its
datastore filesystem version will trump its local filesystem
version.
all_paths: list. A list of all file paths in the underlying file
... |
# - | *- coding: utf-8 -*-
def social_blblbl(entity, argument):
return True
#- Fine F | unzione -
|
from __future__ import unicode_literals
import importlib
import os
import sys
from django.apps import apps
from django.utils import datetime_safe, six
from django.utils.six.moves import input
from .loader import MIGRATIONS_MODULE_NAME
class MigrationQuestioner(object):
"""
Gives the autodetector responses ... | return value
except ValueError:
pass
result = input("Please select a valid option: ")
def ask_not_null_addition(self, field_name, model_name):
"Adding a NOT NULL field to a model"
if not self.dry_run:
choice = self._choice_input(
... | ault;\n" % (field_name, model_name) +
"we can't do that (the database needs something to populate existing rows).\n" +
"Please select a fix:",
[
"Provide a one-off default now (will be set on all existing rows)",
"Quit, and let me a... |
TEST | _DEFAULT = 'def | value'
|
import json
from typing import TYPE_CHECKING, Optional
from boxsdk.util.text_enum import TextEnum
from boxsdk.exception import BoxAPIException
from .base_object import BaseObject
if TYPE_CHECKING:
from boxsdk.object.user import User
from boxsdk.object.terms_of_service_user_status import TermsOfServiceUserStat... |
Indicates whether a use has accepted or rejected a terms of service.
:param user:
The :class:`User` to assign the terms of service to.
:returns:
A newly created :class:`TermsOfServiceUserStatus` object
"""
url = self._session.get_url('terms_of_service... | 'id': self.object_id,
},
'is_accepted': is_accepted,
}
if user is not None:
body['user'] = {
'type': user.object_type,
'id': user.object_id,
}
translated_response = None
try:
box_respon... |
"""
WSGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
os.environ.setdefault( | "DJANGO_SETTINGS_MODULE", "mypro | ject.settings")
from django.core.wsgi import get_wsgi_application # flake8: noqa
application = get_wsgi_application()
|
from django.db import models
from django.db.models.signals import post_save
from django.db.utils import DatabaseError
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _, ugettext
STANDARD_EMAIL = "anonymous@readthedocs.org"
class Us... | "
user = models.ForeignKey(User, verbose_name=_('User'), unique=True, related_name='profile')
whitelisted = models.BooleanField(_('Whitelisted'))
homepage = models.CharField(_('Homepage'), max_length=100, blank=True)
allow_email = models.BooleanField(_('Allow email'), help_text=_('Show your email on VCS... |
def get_absolute_url(self):
return ('profiles_profile_detail', (), {'username': self.user.username})
get_absolute_url = models.permalink(get_absolute_url)
def get_contribution_details(self):
"""
Gets the line to put into commits to attribute the author.
Returns a tuple (na... |
# -*- coding: utf-8 -*-
import pytest
from .utils import last_activity
@pytest.mark.usefixtures('versioning_manager', 'table_creator')
class TestActivityCreationWithColumnExclusion(object):
@pytest.fixture
def audit_trigger_creator(self, session, user_class):
session.execute(
'''SELECT au... | ty['changed_data'] == {}
assert activity['old_data'] == {
'id': user.id,
'name': 'John',
}
assert activity['table_name'] == 'us | er'
assert activity['native_transaction_id'] > 0
assert activity['verb'] == 'delete'
|
ttp-v10-spec-00.txt> H. Frystyk Nielsen
# Expires September 8, 1995 March 8, 1995
#
# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
#
# and
#
# Network Working Group R. Fielding
# Request for Comments: ... | d bbbb
# |
# | host: Either the DNS name or the IP number of the remote client
# | rfc931: Any information returned by identd for this person,
# | - otherwise.
# | authuser: If user sent a userid for authentication, the user name,
# | - otherwise.
# | DD: Day
... | t: The first line of the HTTP request as sent by the client.
# | ddd: the status code returned by the server, - if not available.
# | bbbb: the total number of bytes sent,
# | *not including the HTTP/1.0 header*, - if not available
# |
# | You can determine the name of the file accessed throu... |
('WRITE', AllUsers()),
('FULL_CONTROL', User(owner.name)),
],
'authenticated-read': [
('READ', AuthenticatedUsers()),
('FULL_CONTROL', User(owner.name)),
],
'bucket-owner-read': [
('READ', User(bucket_owner.name)),
(... | E and READ_ACP permissions on a bucket enables this group to write
server access logs to the bucket.
"""
uri = 'http://acs.amazonaws.com/groups/s3/LogDelivery'
def __contains__(self, key):
if ':' in key:
tenant, user = key.split(':', 1)
else:
user = key
r... | ncludes both Grantee and Permission
"""
def __init__(self, grantee, permission):
"""
:param grantee: a grantee class or its subclass
:param permission: string
"""
if permission.upper() not in PERMISSIONS:
raise S3NotImplemented()
if not isinstance(gra... |
import unittest
fr | om scrapers.journalscrapers import ElsevierScraper
class TestElsevierScraper(unittest.TestCase):
def setUp(self):
self.instance = ElsevierS | craper("../data/elsevier/2016-uncleaned.csv")
def test_strip_chars(self):
for row in self.instance.get_entries():
print row
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Marcus Müller.
#
# This 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 3, or (at your option)
# any later version.
#
# This s... | "param_type": "LIN_RANGE",
"value": list(self.range_spec),
"value_type": "float64"
},
"length": {
"param_type": "LIST",
"value": [10,20,30],
"value_type"... | ]
}
self.xml_file = open(os.path.join(os.path.dirname(__file__), "extraction_test_topblock.grc"), "r")
self.ref_task_grc["grcxml"] = self.xml_file.read()
self.xml_file.close()
self.jsonfile = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
self.jsonfilen... |
# ITERATING DICTIONARY
d = {'x | ':1, 'y':2, 'z':3}
for key in d:
print | key, 'corresponds to', d[key]
|
#!/usr/bin/python
#
# \file 0_setup.py
# \brief Setup rbank
# \date 2009-03-10-22-43-GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Setup rbank
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This program is free soft... | in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this progr... | subprocess, distutils.dir_util
sys.path.append("../../configuration")
if os.path.isfile("log.log"):
os.remove("log.log")
log = open("log.log", "w")
from scripts import *
from buildsite import *
from process import *
from tools import *
from directories import *
printLog(log, "")
printLog(log, "-------")
printLog(log... |
from jupyter_workf | low.data import get_fremont_data
import pandas as pd
def test_fremont_data():
data = get_fremont_data()
assert all(data.columns == ['West','East','Total'])
assert isinstance(data.index,pd. | DatetimeIndex)
|
# -*- coding: utf-8 -*-
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db import migrations
def clear_message_sent_by_message_type_values(a | pps, schema_editor):
# type: (StateApps, DatabaseSchemaEditor) -> None
UserCount = apps.get_model('analytics', 'UserCount')
StreamCount = apps.get_model('analytics', 'StreamCount')
RealmCount = apps.get_model('analytics', 'RealmCount')
InstallationCount = apps.get_model('analytics', 'InstallationCou... | operty = 'messages_sent:message_type:day'
UserCount.objects.filter(property=property).delete()
StreamCount.objects.filter(property=property).delete()
RealmCount.objects.filter(property=property).delete()
InstallationCount.objects.filter(property=property).delete()
FillState.objects.filter(property=p... |
class Config:
STREAMING_JOB_NAME = "streaming.job.name"
STREAMING_OP_NAME = "streaming.op_name"
TASK_JOB_ID = "streaming.task_job_id"
STREAMING_WORKER_NAME = "streaming.worker_name"
# channel
CHANNEL_TYPE = "channel_type"
MEMORY_CHANNEL = "memory_channel"
NATIVE_CHANNEL = "native_channel... | to | be written in this
# interval.
STREAMING_EMPTY_MESSAGE_INTERVAL = "streaming.empty_message_interval"
# operator type
OPERATOR_TYPE = "operator_type"
|
filetype])
self['outputtypecombo'].set_active(0)
@classmethod
def filedialog(cls, filetypes, foroutput=False, folder=False):
"""Sets up and returns a file chooser dialog for the caller to run."""
if folder:
title = 'Choose directory...'
act... | rolledwindow, True, True)
# viewport to hold everything in the scrolled window
dialogviewport = g | tk.Viewport()
dialogscrolledwindow.add(dialogviewport)
# hbox to hold the stuff for each field
scrollhbox = gtk.HBox()
dialogviewport.add(scrollhbox)
inputtypelist = gtk.ListStore(gobject.TYPE_STRING)
for fieldtype in fieldtypes:
inputtypelist.append([fieldty... |
#!/usr/bin/env python
import logging # http://docs.python.org/2/howto/logging.html#logging-basic-tutorial
import pysftp # https://code.google.com/p/pysftp/
from configobj import ConfigObj # http://www.voidspace.org.uk/python/configobj.html
import os
import sys
import time
import curses
import Image
import ImageTk
impo... | = tmp_host
config['port'] = tmp_port
config['username'] = tmp_user
config['password'] = tmp_pass
config['motion_base'] = tmp_base
config['motion_local'] = tmp_loca
config.write()
| self.loadExistingConfig()
print "Configuration parameters successfully saved."
def playVideo(filename):
os.system("open " + filename)
def gallery():
label.pack()
frame = Tkinter.Frame(root)
frame.pack()
Tkinter.Button(frame, text='Previo... |
import praw
import urllib.request
import json
import requests
import requests.auth |
import os.path
import re
from imgurpython import ImgurCli | ent
from bs4 import BeautifulSoup
imgur_gif_regex = re.compile("https?:\/\/i\.imgur\.com\/[a-z0-9]+.gif")
def gyazo_link_parser(link):
"""
Parses Gyazo links into their raw (.png or .gif) form (i.gyazo)
"""
# opens the gyazo link
response = urllib.request.urlopen(link)
# reads the reponse
... |
from L500analysis.derived_fields.derived_fields import *
from L500analysis.derived_fields.derived_field_functions import *
from L500analysis.derived_fields.collections.peak_height.derived_field_functions \
import *
from L500analysis.derived_fields.derived_field_tools.non_thermal_temperature \
import calculate_T... | combine_function=calculate_normalized_total_temperature_profile,
M_delta_key='M_total_200m', R_delta_key='r200m',
delta='200m')
add_derived_field('Ttot_500c',function=_normalized_total_temperature_profile,
combine_function=calculate_total_temperature_profile... | , M_delta_key='M_total_500c', R_delta_key='r500c',
delta='500c')
add_derived_field('Ttot_200m',function=_normalized_total_temperature_profile,
combine_function=calculate_total_temperature_profile
, M_delta_key='M_total_200m', R_delta_key='r200m',
... |
import os.path
import gwt
from ...weights import W
from warnings import warn
__author__ = "Myunghwa Hwang <mhwang4@gmail.com>"
__all__ = ["DatIO"]
class DatIO(gwt.GwtIO):
"""
Opens, reads, and writes file objects in DAT format.
Spatial weights objects in DAT format are used in
Dr. LeSage's MatLab Ec... | .dat file
Returns a pysal.weights.weights.W object
Examples
--------
Type 'dir(w)' at the interpreter to see what methods are supported.
Open .dat file and read it into a pysal weights object
>>> w = pysal.open(pysal.examples.get_path('wmat.dat'),'r').read()
| Get the number of observations from the header
>>> w.n
49
Get the mean number of neighbors
>>> w.mean_neighbors
4.7346938775510203
Get neighbor distances for a single observation
>>> w[1]
{2.0: 0.3333, 5.0: 0.3333, 6.0: 0.3333}
"""
i... |
#encoding:utf-8
__authors__ = ['"Wei Keke" <keke.wei@cs2c.com.cn>']
__version__ = "V0.1"
'''
# ChangeLog:
#---------------------------------------------------------------------------------
# Version Date Desc Author
#----------------------------------------------------... | -----------------
# V0.1 2014/10/09 初始版本 Wei Keke
#-------------------------------------------------------------- | -------------------
'''
from TestData.Template import ITC07_SetUp as ModuleData
from TestAPIs.VirtualMachineAPIs import VirtualMachineAPIs
'''---------------------------------------------------------------------------------------------------
@note: PreData
-------------------------------------------------------------... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | sions": (
{str: (bool, date, datetime, dict, float, int, list, str,)},
), # noqa: E501
"getref": (str,), # noqa: E501
}
@staticmethod
def discriminator():
return None
attribute_map = {
"empty": "empty", # noqa: E501
"extensions": "... | "_data_store",
"_check_type",
"_from_server",
"_path_to_item",
"_configuration",
]
)
def __init__(
self,
_check_type=True,
_from_server=False,
_path_to_item=(),
_configuration=None,
**kwargs
): ... |
#
# This is minimal MicroPython variant of run-tests script, which uses
# .exp files as generated by run-tests --write-exp. It is useful to run
# testsuite on systems which have neither CPython3 nor unix shell.
# This script is intended to be run by the same interpreter executable
# which is to be tested, so should use... | :
testcases = f.readlines()
testcases = [l[:-1] for l in | testcases]
assert testcases, "No tests found in dir '%s', which is implausible" % suite
#print(testcases)
for t in testcases:
if t == "native_check.py":
continue
qtest = "%s/%s" % (suite, t)
if should_skip(t):
print("skip " + qtest)
skip_count +... |
from django.contrib import admin
from Weather.models import *
from Weather.util im | port updateForecast
def update_forecast(modeladmin, request, queryset):
for forecast in queryset:
updateForecast(forecast)
update_forecast.short_description = "Force forecast update from NWS"
class forecastAdmin(admin.ModelAdmin):
actions = [update_forecast]
class WMSR | adarOverlayAdmin(admin.ModelAdmin):
pass
admin.site.register(Forecast, forecastAdmin)
admin.site.register(WMSRadarOverlay, WMSRadarOverlayAdmin) |
"""
Settings for reputation changes that apply to
user in response to various actions by the same
users or others
"""
from askbot.conf.settings_wrapper import settings
from askbot.conf.super_groups import REP_AND_BADGES
from askbot.deps.livesettings import ConfigurationGroup, IntegerValue
from django.utils.translation... | 'NICE_ANSWER_BADGE_MIN_UPVOTES',
default=5,
description=_('Nice Answer: minimum up | votes for the answer')
)
)
settings.register(
IntegerValue(
BADGES,
'GOOD_ANSWER_BADGE_MIN_UPVOTES',
default=10,
description=_('Good Answer: minimum upvotes for the answer')
)
)
settings.register(
IntegerValue(
BADGES,
'GREAT_ANSWER_BADGE_MIN_UPVOTES',
... |
from python_kemptech_api import *
# Specify the LoadMaster connection credentials here:
loadmaster_ip = ""
username = ""
password = ""
vs_ip_1 = ""
vs_ip_2 = ""
rs_ip_1 = ""
rs_ip_2 = ""
vs_port = ""
rs_port = ""
class RealServerPool(object):
healthcheck_parameters = [
"checktype",
"checkport",
... | dhealthchecks
self.rsminimum = vs.rsminimum
def apply(self, vs):
[rs.delete() for rs in vs.servers.values( | )]
for rs in self.rs:
new_rs = vs.create_real_server(rs.rs, rs.rsport)
# Apply other settings
new_rs.save()
for attr in self.rs_parameters:
print("attr: {}".format(attr))
if hasattr(rs, attr) and rs.__getattribute__(attr) is not N... |
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be... | dev3)
report = ValidationReport.from_structure(
| self.disk_selection_interface.ValidateSelectedDisks([])
)
self.assertEqual(report.is_valid(), True)
report = ValidationReport.from_structure(
self.disk_selection_interface.ValidateSelectedDisks(["dev1"])
)
self.assertEqual(report.is_valid(), False)
self.... |
import json
import os
#This helper class allows to access members of the configuration
#as c.attr1.attr2.attr3 instead of c[attr1][attr2][attr3]
class DictToAttr( object ):
def __init__( self, dictionary ):
self.dict = dict( dictionary )
def | __getattr__(self, attr):
if attr in self.dict.keys():
token = self.dict[ attr ]
if isinstance( token, dict ):
return DictToAttr( token )
else:
return token
... | '%s' does not exists in configuration" %(attr))
class Configuration( object ):
def __init__(self):
#Read configuration file
path = os.path.dirname (
os.path.abspath( os.path.expanduser( __file__ ) )
)
con... |
# LICENSE: GPLv2, see attached License
# Author: Joerg Jungermann
def get_mac():
from network import WLAN
from ubinascii import hexlify
return hexlify(W | LAN().config('mac'),'-').decode()
def sleep(sec, deepsleep = False):
import time
if deepsleep:
import machine
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
rtc.alarm(rtc.ALA | RM0, sec * 1000)
print('iotesp.sleep():', sec, 's / DEEPSLEEP')
machine.deepsleep()
time.sleep_us(100)
else:
# print('sleep:', sec, 's')
time.sleep(sec)
# vim: sw=4 ts=4 ft=python et foldmethod=indent
|
###############################################################################
# Name: nsistags.py #
# Purpose: Generate Tags for Nullsoft Installer Scripts #
# Author: Cody Precord <cprecord@editra.org> #
... | rtags.AddElement('section', taglib.Section(part, lnum))
break
elif parselib.IsToken(line, 0, u'!macro'):
parts = line.split()
if len(parts) > 1:
rtags.AddElement('macro', taglib.Ma | cro(parts[1], lnum))
elif parselib.IsToken(line, 0, u'!define'):
parts = line.split()
if len(parts) > 1 and parts[1][0].isalpha():
rtags.AddVariable(taglib.Variable(parts[1], lnum))
else:
continue
return rtags
#-------------------------------... |
ses.append(self.pkg_a.arch.name)
elif self.pkg_b:
css_classes.append(self.pkg_b.arch.name)
return ' '.join(css_classes)
def __key(self):
return (self.pkgname, hash(self.repo),
hash(self.pkg_a), hash(self.pkg_b))
def __eq__(self, other):
return self._... | user objects we will need
user_ids = {rel[1] for rel in rels}
users = User.objects.in_bulk(user_ids)
# now build a pkgbase -> [maintainers...] map
maintainers = defaultdict(list)
for rel in rels:
maintainers[rel[0]].append(users[rel[1]])
annotated = []
# and finally, attach the mai... | ge in packages:
if package is None:
continue
package.maintainers = maintainers[package.pkgbase]
annotated.append(package)
return annotated
def approved_by_signoffs(signoffs, spec):
if signoffs:
good_signoffs = sum(1 for s in signoffs if not s.revoked)
retur... |
from sys import version_info
from functools import reduce
from operator import mul
from flask_babel import gettext
if version_info[0] == 3:
unicode = str
keywords = ('min',
'max',
'avg',
'sum',
'prod')
# required answerer function
# can return a list of results (... | if len(parts) < 2:
return []
try:
args = list(map(float, parts[1:]))
except:
return []
func = parts[0]
answer = None
if func == b'min':
answer = min(args)
elif func == b'max':
answer = max(args)
elif func == b'avg':
| answer = sum(args) / len(args)
elif func == b'sum':
answer = sum(args)
elif func == b'prod':
answer = reduce(mul, args, 1)
if answer is None:
return []
return [{'answer': unicode(answer)}]
# required answerer function
# returns information about the answerer
def self_... |
# Rekall Memory Forensics
# Copyright (C) 2007,2008 Volatile Systems
# Copyright (C) 2010,2011,2012 Michael Hale Ligh <michael.ligh@mnin.org>
# Copyright 2013 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | has a unique set of windows stations.
| for session in self.session.plugins.sessions().session_spaces():
for station in self.stations_in_session(session):
yield station
def collect(self):
for window_station in self.stations():
desktops = [desk.Name for desk in window_station.desktops()]
yield (... |
# Authors: Eric Larson <larson.eric.d@gmail.com>
# Sheraz Khan <sheraz@khansheraz.com>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
from ..filter import next_fast_len
from ..source_estimate import _BaseSourceEstimate
from ..utils import verbose, _check_c... | lt is 'mean'. Can be None to return without combining.
If callable, it must accept one positional input.
For example::
combine = lambda data: np.median(data, axis=0)
orthogonalize : 'pairwise' | False
Whether to orthogonalize with the pairwise method or not.
Defaults to... | log : bool
If True (default False), square and take the log before orthonalizing
envelopes or computing correlations.
.. versionadded:: 0.22
absolute : bool
If True (default), then take the absolute value of correlation
coefficients before making each epoch's correlation mat... |
from pattern import Pattern
import itertools
import random
import colorsys
import time
class EqPattern(Pattern):
def __init__(self, meter_color=(255,100,50), background_color=(0,50,255)):
self.meter_r = meter_color[0]
self.meter_g = meter_color[1]
self.meter_b = meter_color[2]
self... | e_shift):
color_scaled = [x/255.0 for x in color]
hsv = list(colorsys.rgb_to_hsv(color_scaled[0], color_scaled[1], color_scaled[2]))
hsv[0] += hue_shift % 1
return tuple([int(x*255) for x in colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2])])
def next_frame(self, octopus, data):
... | time()
if data.beats[beat_channel] and t > self.next_shift:
self.next_shift = t + 60.0/self.max_bpm
shift = self.max_hue_shift*(2*random.random() - 1)
if int(round(random.random())):
self.meter_r, self.meter_g, self.meter_b = self.hue_shift(self.meter_color(... |
def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs):
url = Non | e
if backend.name == 'facebook':
url = "http://graph.facebook. | com/%s/picture?type=small"%response['id']
if url:
user.avatar = url
user.save()
|
from couchdbkit import ResourceNotFound
from toggle.models import Toggle
from toggle.shortcuts import update_toggle_cache, parse_toggle
def move_toggles(from_toggle_id, to_toggle_ | id):
"""
Moves all enabled items from one toggle to another.
"""
try:
from_toggle = Toggle.get(from_toggle_id)
except ResourceNotFound:
# if no source found this is a | noop
return
try:
to_toggle = Toggle.get(to_toggle_id)
except ResourceNotFound:
to_toggle = Toggle(slug=to_toggle_id, enabled_users=[])
for item in from_toggle.enabled_users:
if item not in to_toggle.enabled_users:
to_toggle.enabled_users.append(item)
... |
y 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
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CON... | 'com/example/CommonClassHelper.cl | ass'])
self.mkzip(self.root_path, 'business-component.jar', ['com/example/Service.class',
'com/example/ServiceBean.class'])
#TODO: Create sample JARs in /WEB-INF/lib
self.mkzip(self.root_path, 'sample-webapp.war', [... |
dtype)
y_np = np.random.uniform(-1, 1, [2, 3]).astype(self.dtype)
z_np = np.random.uniform(-1, 1, [6, 9]).astype(self.dtype)
x = paddle.to_tensor(x_np)
y = paddle.to_tensor(y_np)
z = paddle.to_tensor(z_np)
a = paddle.to_tensor([[1, 1], [2, 2], [3, 3]])
b = paddl... | True(
np.array_equal(x.reciprocal().numpy(), paddle.reciprocal(x).numpy(
)))
self.assertTrue(
np.array_equal(x.square().numpy(), paddle.square(x).numpy()))
self.assertTrue(
np.array_equal(x.rank().numpy(), paddle.rank(x).numpy()))
self.assertTrue(
... | ### acosh(x) = nan, need to change input
t_np = np.random.uniform(1, 2, [2, 3]).astype(self.dtype)
t = paddle.to_tensor(t_np)
self.assertTrue(
np.array_equal(t.acosh().numpy(), paddle.acosh(t).numpy()))
self.assertTrue(
np.array_equal(x.atanh().numpy(), paddle.ata... |
)
resp = self.client.getKeyRange('objects,', 'objects/')
keys = resp.wait()
self.assertEqual(len(keys), 1)
head_key = keys[0]
# policy.hash.t.s.ext.nonce-frag
nonce = head_key.rsplit('.', 1)[1]
nonce_parts = nonce.split('-')
# nonce is now a uuid with a f... | disk_chunk_size=10)
req_timestamp = time.time()
with df.create() as writer:
chunk = '\x00' * 10
for i in range(3):
writer.write(chunk)
writer.put({'X-Timestamp': req_timestamp})
with df.open() as reader:
metadata = reader.get_me... | _timestamp,
'X-Kinetic-Chunk-Count': 3,
}
for k, v in expected.items():
self.assertEqual(metadata[k], v)
def test_multi_chunk_put_and_get_with_buffer_offset(self):
disk_chunk_size = 10
write_chunk_size = 6
write_chunk_count = 7
object_size = w... |
from PythonQt import QtGui, QtCore
from uic.uiparser import UIParser
from uic.Loader.qobj | ectcreator import LoaderCreatorPolicy
class DynamicUILoader(UIParser):
def __init__(self):
UIParser.__init__(self, QtCore, QtGui, LoaderCreatorPolicy())
def createToplevelWidget(self, classname, widgetname):
if self.toplevelInst is not None:
if not isinstance(self.toplevelInst, se... | levelInst), classname)))
return self.toplevelInst
else:
return self.factory.createQObject(classname, widgetname, ())
def loadUi(self, filename, toplevelInst = None):
self.toplevelInst = toplevelInst
return self.parse(filename)
|
#!/usr/bin/env python
#
# Bzip2
#
# Bzip2 packages and versions
#
# Author P G Jones - 2014-08-15 <p.g.jones@qmul.ac.uk> : New file.
####################################################################################################
import nusoft.package.conditional as conditional_package
import os
class Bzip2(condit... | tall_path())
self._system.make(args=["install", "PREFIX=" + self.get_install_path()],
cwd=self.get_install_path())
def _update(self):
""" Nothing to do here..."""
pass
def _remove(self):
""" Remove the install directory."""
self._system.remove(s... | :
""" Check if root is installed by looking for the root executable in the bin directory.
:return: True if installed
"""
return self._system.exists(os.path.join(self.get_install_path(), "include/bzlib.h")) \
and self._system.is_library(os.path.join(self.get_install_path(), "... |
#!/usr/bin/python
import feedparser
import wget
import sqlite3
import time
RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss']
sleep=3600/len(RssUrlList)
def mkdir(path):
import os
path=path.strip()
path=path.rstrip("\\")
isExists=os.path.exists(path)
... | me=float(time.mktime(time.strptime(post.published[:-6],"%a, %d %b %Y %H:%M:%S")))
if conn.execute("SELECT MAX(DATE) FROM %s"%table).next()[0] == thisposttime:
break
if post.description.find("video_file") == -1:
continue
sourceadd= post.description.find("source src=")
... | dd:].find("type=\"video")
video_id=post.description[sourceadd:][tumblradd:][:typeadd-2]
if video_id.find("/") !=-1:
video_id=video_id[:video_id.find("/")]
try:
list(conn.execute("SELECT * FROM %s WHERE ADDRESS == '%s'"%(table,video_id)).next())
except:
... |
import requests
import json
import sqlite3
import time
#searching the api key of velib
key_file = open('jcdecaux.key','r')
api_key = key_file.readline().rstrip('\n')
key_file.close()
startime = time.time()
url = 'https://api.jcdecaux.com/vls/v1/stations?contract=Paris&apiKey=' + api_key
re | sponse = requests.get(url)
p | rint(response.status_code)
data = response.json()
conn = sqlite3.connect('velib.db')
cursor = conn.cursor()
keep = 0
request_date = int(time.time())
for station in data:
number = int(station['number'])
status = station['status']
bike_stands = int(station['bike_stands'])
available_bike_stands = int(... |
import pytest
from proposals.models import AdditionalSpeaker, TalkProposal, TutorialProposal
@pytest.fixture
def talk_proposal(user):
proposal = TalkProposal.objects.create(
id=42,
submitter=user,
title='Beyond the Style Guides<br>',
)
return proposal
@pytest.fixture
def cancell... | submitter=user,
title='Beyond the Style Guides<br>',
)
return p | roposal
@pytest.fixture
def cancelled_tutorial_proposal(tutorial_proposal):
tutorial_proposal.cancelled = True
tutorial_proposal.save()
return tutorial_proposal
@pytest.fixture(params=['talk', 'tutorial'])
def proposal_type(request):
return request.param
@pytest.fixture
def proposal(proposal_type,... |
#!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: ... | h = app_tests.TestPathHelper(
source_base, binary_base,
'apps/samcat/tests') # tests dir
# ============================================================
# A | uto-detect the binary path.
# ============================================================
path_to_program = app_tests.autolocateBinary(
binary_base, 'apps/samcat', 'samcat')
# ============================================================
# Built TestConf list.
# =============================... |
eturn local_filename
def _s3_parse_manifest(self, context, metadata, manifest):
manifest = etree.fromstring(manifest)
image_format = 'ami'
image_type = 'machine'
try:
kernel_id = manifest.find('machine_configuration/kernel_id').text
if kernel_id == 'true':
... | anifest = key.get_contents_as_string()
manifest, image, image_uuid = self._s3_parse_manifest(context,
metadata,
manifest)
def delayed_create():
"""This handles the fe... | 'image_path': image_path}
def _update_image_state(context, image_uuid, image_state):
metadata = {'properties': {'image_state': image_state}}
self.service.update(context, image_uuid, metadata,
purge_props=False)
def _up... |
fc\x80\x15\x44\x4a\
\x28\xb2\x02\x69\x4f\x00\x22\x15\x14\x59\x81\xe8\x6f\xce\x25\x04\
\x91\x02\x8a\xbc\x40\xc6\xe6\x93\x82\xa0\x46\x91\x15\xc8\xc5\xdb\
\x0b\x9c\x40\x50\xa2\x20\x03\xf9\x6d\x6b\x1f\x3c\xbe\x70\x5a\x33\
\x36\xbb\x02\xa6\x5b\x33\x9c\xd3\x3b\x74\x07\x6e\xe8\xd3\x83\x72\
\x6b\xa0\x14\x3c\xbe\x30\xfc\xb6\x85... | \x4f\xe0\x62\x60\
\x98\xce\xa8\xc1\x4e\x10\x60\x27\x08\x70\x10\xc4\x8f\xa8\xd7\x9b\
\x11\x65\x35\x2a\x72\xbe\xd3\xbf\xfb\x48\xd5\xdc\x2a\x2a\xc6\x60\
\xb3\x0e\xc2\x5a\x2d\x3c\x2c\x2a\xa2\x50\xee\x11\xc4\x11\xd4\xeb\
\xcd\x88\xea\x6e\x2f\x3b\xf4\x65\x8b\x76\x8f\x6c\xe6\xd7\xa6\x6b\
\xa2\x60\x84\xb5\x5a\xd8\x69\x68\x80\x... | \xf5\
\xdf\xbb\x44\xa9\x2c\x47\xbd\xd6\x8c\xa9\xee\xf6\xb2\x43\xaa\xe6\
\xd6\x0d\xae\x28\x5c\x30\xc8\xd0\x76\x09\x3e\x4b\x52\xa9\x72\xad\
\x31\xa7\xa2\xb1\x7b\x2a\x19\x4a\x2a\x18\xf4\xb3\xc4\x41\x10\x21\
\xd4\x6b\xcc\xb8\x2a\xd7\x1a\x73\xaa\xce\x77\x3e\x8a\x87\x92\x2a\
\x46\x58\xab\x85\x85\xd2\x52\x6a\x6c\xa1\x5e\x5f\x... |
#
# Copyright 2011 Red Hat, Inc.
#
# 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.
#
# This program is distributed in th... | g("Trying to connect to Super Vdsm")
try:
utils.retry(self._manager.connect, Exception, timeout=60, tries=3)
| except Exception as ex:
msg = "Connect to supervdsm service failed: %s" % ex
utils.panic(msg)
self._svdsm = self._manager.instance()
def __getattr__(self, name):
return ProxyCaller(self, name)
def getProxy():
global _g_singletonSupervdsmInstance
if _g_sing... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of kryptomime, a Python module for email kryptography.
# Copyright © 2013,2014 Thomas Tanner <tanner@gmx.net>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published ... | s_require={'docs': ["Sphinx>=1.1", "repoze.sphinx"]},
platforms="Linux, BSD, OSX, Windows",
download_url="https://github.com/ttanner/kryptomime/archive/master.zip",
classifiers=[
"Deve | lopment Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
... |
soup = BeautifulSoup(r.text, 'html.parser')
self.data_set = soup.find_all('div', class_='customjumbotron')
else:
print '网络连接错误'
r.raise_for_status()
else:
print 'KM对应URL不存在或错误'
sys.exit()
def km_victim_detail(self):
... | starttime='',
endtime='',
prev='',
next='',
csrfmiddlewaretoken=csrftoken_cookies,
)
r = client.post(URL, data=search_data, headers=dict(Referer=URL))
soup = BeautifulSoup(r.text, 'html.parser')
a = soup.find('table',id='kbtable'... | killmail = []
for km in a[:-1]:
for n in km.find_all('td'):
if n.find_all(href=re.compile("/pilot/0")) != []:
info.append('未知角色')
if n.find_all(style='color:grey') != []:
null_alli_tag = 1
else:
... |
#!/usr/bin/true
#
# download.py - part of autospec
# Copyright (C) 2018 Intel Corporation
#
# 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 3 of the License, or
# (a | t 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 FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detail | s.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import sys
from io import BytesIO
import pycurl
from util import print_fatal
def do_curl(url, dest=None, post=None, is_fatal=False):
"""
Perform a curl... |
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
from autopilot.matchers import Eventually
from testtools.matchers import Equals
from bmicalc import tests
class MainViewTestC | ase(tests.BaseTestCase):
"""Tests for the mainview"""
def setUp(self):
super(MainViewTestCase, self).setUp()
def test_click_button(self):
# Find and click the button
button = self.app.main_view.get_button()
self.app.pointing_device.click_object(button)
# Make an as... | ertThat(label.text, Eventually(Equals('..world!')))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.