prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
*
from ie_stats import *
from ie_action import ACT_LEFT, ACT_RIGHT
from ie_spells import *
from ie_restype import RES_2DA
#################################################################
# this is in the operator module of the standard python lib
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(... | (actor, BookType, level, i)
if Spell0["SpellResRef"] in spellResRefs:
continue
spellResRefs.append (Spell0["SpellResRef"])
Spell = GemRB.GetSpell(Spell0["SpellResRef"])
Spell['BookType'] = Boo | kType # just another sorting key
knownSpells.append (Spell)
return knownSpells
def index (list, value):
for i in range(len(list)):
if list[i]==value:
return i
return -1
def GetMemorizedSpells(actor, BookType, level):
memoSpells = []
spellResRefs = []
spellCount = GemRB.GetMemorizedSpellsCount (actor, B... |
# Refer to the following link for help:
# http://docs.gunicorn.org/en/latest/settings.html
command = '/home/lucas/www/reddit.lucasou.com/reddit-env/bin/gunicorn'
pythonpath = '/home/lucas/www/reddit.lucasou.com/reddit-env/flask_reddit'
bin | d = '127.0.0.1:8040'
workers | = 1
user = 'lucas'
accesslog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-access.log'
errorlog = '/home/lucas/logs/reddit.lucasou.com/gunicorn-error.log'
|
import unittest
from katas.kyu_7.guess_my_number import guess_my_number
class GuessMyNumberTestCase(unittest.TestCase):
def test_equals(self):
| self.assertEqual | (guess_my_number('0'), '###-###-####')
def test_equals_2(self):
self.assertEqual(guess_my_number('01'), '1##-##1-####')
def test_equals_3(self):
self.assertEqual(guess_my_number('012'), '12#-##1-2###')
def test_equals_4(self):
self.assertEqual(guess_my_number('0123'), '123-##1-23#... |
RPOSE. See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available on the World
# Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also
# obtain it by writing to the Free Software Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA... | l_btn.pressed.connect(task.kill)
self.progressBar.setValue(0)
# configure QgsMessageBar
action = self.tabWidget.tabText(self.tabWidget.currentIndex())
messageBar = self.iface.messageBar().createMessage(action, '')
msgProgressBar = QtGui.QProgressBar()
| msgProgressBar.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
cancelButton = QtGui.QPushButton()
cancelButton.setText('Cancel')
cancelButton.clicked.connect(self.cancel_btn.click)
messageBar.layout().addWidget(msgProgressBar)
messageBar.layout().addWidget(cancelButt... |
#!/usr/bin/env python
#
# GrovePi Example for using the Grove Light Sensor and the LED together to turn the LED On and OFF if the background light is greater than a threshold.
# Modules:
# http://www.seeedstudio.com/wiki/Grove_-_Light_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
#
# The GrovePi con... | s hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc | umentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:... |
lay_music('search6', -1)
if self.game.ball_count.position == 7:
self.game.sound.play_music('search7', -1)
if self.game.ball_count.position == 8:
self.game.sound.play_music('search8', -1)
def sw_tilt_active(self, sw):
if self.game.tilt.status == False:
sel... | # begin immediately upon the first ball landing in the hole.
# I suspect that the best, fastest way to complete the search is actually to reimplement the mechanical
# search activity. For each revolution of the search disc (which happens about every 5-7 seconds), the
# game will activate() e... | t of rivets on the search disc.
# Replay counters also need to be implemented to prevent the supplemental searches from scoring.
for i in range(0, 100):
if i <= 50:
self.r = self.closed_search_relays(self.game.searchdisc.position)
self.game.searchdisc.spin()
... |
# encoding: utf-8
#
# Copyright (C) 2013 midnightBITS/Marcin Zdun
#
# 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 the rights to use, c... | y, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notic | e and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN ... |
fwhm = sigma * sigma_to_fwhm
R = ckms / fwhm
width = Rsigma
assert np.size(sigma) == 1, "`resolution` must be scalar for `smoothtype`='R'"
# convert inres from Rsigma to sigma (km/s)
try:
kwargs['inres'] = ckms / kwargs['inres']
except(KeyError):
... | numerate(outwave):
x = (np.log(w) - lnwave) / sigma_eff
if nsigma > 0:
good = np.abs(x) < nsigma
x = x[good]
_ | spec = spec[good]
else:
_spec = spec
f = np.exp(-0.5 * x**2)
flux[i] = np.trapz(f * _spec, x) / np.trapz(f, x)
return flux
def smooth_vel_fft(wavelength, spectrum, outwave, sigma_out, inres=0.0,
**extras):
"""Smooth a spectrum in velocity space, using FFT... |
# -*- coding: utf-8 -*-
'''Python command line tool to maange a local cache of content fom DataONE.
Output is a folder w | ith structure:
cache/
meta.json: Basic metadata about the content in the cache
index.json: An index to entries in the cache. Downlaods are renamed using a
| hash of the identifier as the identifier is not file system safe
0/
.
.
f/
Note that this process runs as a single thread and so will take quite a while
to complete.
Note also that the libraries used emit error messages that may be more
appropriately handled in logic. As a result the output fro... |
def passChecker(password):
import re
passlength = 8
uppercaseRege | x = re.compile(r'[A-Z]')
lowercaseRegex = re.compile(r'[a-z]')
numberRegex = re.compile(r'[0-9]')
if ((uppercaseRegex.search(password) == None) or (lowercaseRegex.search(password) == None) or (numberRegex.search(password) == None) or (len(password) < passlength)):
ret | urn False
return True
|
import win32ras
stateStrings = {
win32ras.RASCS_OpenPort : "OpenPort",
win32ras.RASCS_PortOpened : "PortOpened",
win32ras.RASCS_ConnectDevice : "ConnectDevice",
win32ras.RASCS_DeviceConnected : "DeviceConnected",
win32ras.RASCS_AllDevicesConnected : "AllDevicesConnected",
win32ras.RASCS_Authentica... | ",
win32ras.RASCS_Connected : "Connected",
win32ras.RASCS_Disconnected : "Disconnected"
}
def TestCallback( hras, msg, state, error, exterror):
print "Callback called with ", hras, msg, stateSt | rings[state], error, exterror
def test(rasName = "_ Divert Off"):
return win32ras.Dial(None, None, (rasName,),TestCallback) |
"""
Logger di varie info per ogni host
"""
from novaclient import client as novaclient
from ceilometerclient import client as ceiloclient
import os
from os import environ as env
import time
def start(hosts, sleep_sec, base_dir):
print 'You must be admin to use this script'
# start logger
time_dir = get_... | host_cpu_util = (host_cpu_util[0].counter_volume)/100
content = get_string_to_write(str(host_cpu_util))
path_file = get_path_to_file(path, "meter_host_cpu_util")
write_file(path_file, content)
def log_meter_host_mem_util(ceilo, host_id, path):
# sample of ram usage in percentage
host_mem_usage = ... | q=[{'field':'resource_id',
'op':'eq',
'value':host_id}])
host_mem_usage = (host_mem_usage[0].counter_volume)/100
content = get_string_to_write(str(host_mem_usage))
path_file = get_path_to_file(p... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# import funkcí z jiného adresáře
import os.path
path_to_script = os.path.dirname(os.path.abspath(__file__))
# sys.path.append(os.path.join(path_to_script, "../extern/pyseg_base/src/"))
import unittest
import numpy as np
import os
from imtools import qmisc
from imtools i... | kle')
| self.assertTrue(saved_object['a'] == 1)
self.assertTrue(saved_object['data'][1, 1, 1] == testdata[1, 1, 1])
shutil.rmtree(dirname)
if __name__ == "__main__":
unittest.main()
|
# coding: utf-8
from .graphviz_wrapper import board, add_digraph, add_digraph_node, add_digraph_edge
fr | om .jupyter_helper import jupyter_pan_and_zoom, jupyter_show_as_svg
__author__ = "akimach"
__version__ = "0.0.7"
__licens | e__ = "MIT"
|
llsign
self.__messages = []
self._conn = None
def __ssid(self):
return "[DRATS-%s-B2FHIM$]" % version.DRATS_VERSION
def _send(self, string):
print " -> %s" % string
self._conn.send(string + "\r")
def __recv(self):
resp = ""
while not resp.endswith(... | f._conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._conn | .connect((self.__server, self.__port))
def _disconnect(self):
self._conn.close()
def _login(self):
resp = self._recv()
resp = self._recv()
if not resp.startswith("Callsign :"):
raise Exception("Conversation error (never saw login)")
self._send(self._callsi... |
ps,
| weights,
randomizer_scale=randomizer_scale * sigma_)
signs = conv.fit()
nonzero = conv.selection_variable['directions'].keys()
if target == 'full':
(observed_target,
group_assignments,
cov_target,
cov_target_score,
alternatives... | conv._W,
nonzero,
conv.penalty)
elif target == 'selected':
(observed_target,
group_assignments,
cov_target,
cov_target_score,
alternatives) = selected_targ... |
"""Mac-only module to find the home file | of a resource."""
import sstruct
import array
import calldll
import macfs, Res
def HomeResFile(res):
"""Return a path to the file in which resource 'res' lives."""
return GetFileLocation(res.HomeResFile())
def GetFileLocation(refNum):
"""Return a path to the open file identified with refNum."""
pb = ParamBloc... | nal cruft, adapted from MoreFiles
#
_InterfaceLib = calldll.getlibrary("InterfaceLib")
GetVRefNum = calldll.newcall(_InterfaceLib.GetVRefNum, "None", "InShort", "OutShort")
_getInfo = calldll.newcall(_InterfaceLib.PBGetFCBInfoSync, "Short", "InLong")
_FCBPBFormat = """
qLink: l
qType: h
ioTrap: ... |
ets["particle_18 geometry"]=s
s= marker_sets["particle_18 geometry"]
mark=s.place_marker((11842.6, 9383.56, 9068.83), (0.7, 0.7, 0.7), 789.529)
if "particle_19 geometry" not in marker_sets:
s=new_marker_set('particle_19 geometry')
marker_sets["particle_19 geometry"]=s
s= marker_sets["particle_19 geometry"]
mark=s.p... | ('particle_40 geometry')
marker_sets["particle_40 geometry"]=s
s= marker_sets["particle_40 geometry"]
mark=s.place_marker((553.737, 3534.85, 4213.84), (0.7, 0.7, 0.7), 622.571)
if "particle_41 geometry" not in marker_sets:
s=new_marker_set( | 'particle_41 geometry')
marker_sets["particle_41 geometry"]=s
s= marker_sets["particle_41 geometry"]
mark=s.place_marker((1601.81, 4124.33, 4851.28), (0.7, 0.7, 0.7), 466.865)
if "particle_42 geometry" not in marker_sets:
s=new_marker_set('particle_42 geometry')
marker_sets["particle_42 geometry"]=s
s= marker_set... |
import json
from multiprocessing import Pool, Manager
import os |
import requests
import Quandl as quandl
# set working directory to script directory.
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
errors = []
def get_url(url, vars=None):
if vars is not None:
var_string = '?'
for key, value in vars.items():
var_string += '{0}={1}&'.f... |
def get_csv(url):
results = requests.get(url['url'])
fname = os.path.join(dname, 'meta/zhv_index/{0}.csv'.format(url['page']))
print(fname)
with open(fname, 'w') as f:
for d in results['datasets']:
f.write(l + '\n')
return
def main():
requests = []
url = 'https://www.quandl.com/api/v3/datasets.csv'
... |
import os, sys
from array import array
try:
from distance import cdistance
except ImportError:
cdistance = None
from distance import _pyimports as pydistance
if sys.version_info.major < 3:
t_unicode = unicode
t_bytes = lambda s: s
else:
t_unicode = lambda s: s
t_bytes = lambda s: s.encode()
all_types = [
("un... | y: func(1, t("foo"))
except ValueError: pass
itor = func(t("foo"), [t("foo"), 3333])
next(itor)
try: next(itor)
except ValueError: pass
# values drop
itor = func(t("aa"), [t("aa"), t("abcd"), t("ba")])
assert next(itor) == (0, t("aa"))
assert next(itor) == (1, t("ba" | ))
def ilevenshtein(func, t, **kwargs):
itors_common(lambda a, b: func(a, b, max_dist=2), t, **kwargs)
def ifast_comp(func, t, **kwargs):
itors_common(func, t, **kwargs)
#transpositions
g = func(t("abc"), [t("bac")], transpositions=False)
assert next(g) == (2, t('bac'))
g = func(t("abc"), [t("bac")], transpo... |
import json
from util import d
import os
__home = os.path.expanduser("~").replace('\\', '/') + "/PixelWeb/"
BASE_SERVER_CONFIG = d({
"id":"server_config",
"display": "server_config",
"preconfig": False,
"presets":[],
"params": [{
"id": "exter... | "label": "Allow External Ac | cess",
"type": "bool",
"default": True,
"help":"On: Other computers on your network can access PixelWeb. Off: LocalHost access only."
},{
"id": "port",
"label": "Server Port",
"type": "int",
"defa... |
# Copyright (c) 2011 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 ... | er(__name__)
class ComputeCapabilitiesFilter(filters.BaseHostFilter):
"""HostFilter hard-coded to work with InstanceType records."""
# Instance type and host capabilities do not change within a request
run_filter_once_per_request = True
def _get_capabilities(self, host_state, scope):
cap = h... | ):
try:
if isinstance(cap, six.string_types):
try:
cap = jsonutils.loads(cap)
except ValueError as e:
LOG.debug("%(host_state)s fails. The capabilities "
"'%(cap)s' could... |
#!/usr/bin/env python
"""
.. module:: camerastation.py
:platform: Unix, Windows
:synopsis: Ulyxes - an open source project to drive total stations and
publish observation results. GPL v2.0 license Copyright (C)
2010- Zoltan Siki <siki.zoltan@epito.bme.hu>
.. moduleauthor:: Bence Turak <bence.turak... | hz'] = Angle(1/math.sin(ang['v'].GetAngle('RAD'))*(self._affinParams[0,1]*(picCoord[0] - round(self._affinParams[0,0])) + self._affinParams[0,2]*(picCoord[1] - round(self._affinParams[1,0]))))
angles['v'] = Angle(self._affinParams[1,1]*(picCoord[0] - round(self._affinParams[0,0])) + self._affinParams | [1,2]*(picCoord[1] - round(self._affinParams[1,0])))
return angles
def GetAbsAngles(self, targetType = None):
"""Get absolute angles with automatical target recognition (not prism)
:param targetType: type of target (None)
:returns: corrected horinzontas (hz) and vertical (... |
#!/usr/bin/env python
from subprocess import Popen, PIPE
from sys import argv
__autor__ = "Jose Jiménez"
__email__ = "jjimenezlopez@gmail.com"
__date__ = "2012/05/03"
if len(argv) == 1 or len(argv) > 2:
| print 'Wrong execution format.'
print 'Correct format: any2utf /path/to/the/files'
exit(0)
path = argv[1]
if not path.endswith('/'):
path = path + '/'
path = path.replace(' ', '\ ')
p | roc = Popen('ls ' + path + '*.srt', stdout=PIPE, stderr=PIPE, shell=True)
result = proc.communicate()
if proc.returncode == 2:
print 'SRT files not found in path \'' + path + '\''
list = result[0].splitlines()
for f in list:
aux_f = f
aux_f.replace(' ', '\ ')
# file --mime /path/to/file.srt
... |
# -*- c | oding:utf-8 -*-
from . import load | ing
from . import registry
|
#!/usr/bin/env python
# Note: this module is not a demo per se, but is used by many of
# the demo modules for various purposes.
import wx
#---------------------------------------------------------------------------
class ColoredPanel(wx.Window):
def __init__(self, parent, color):
wx.Window.__init__(se... | , -1, style = wx.SIMPLE_BORDER)
self.SetBack | groundColour(color)
if wx.Platform == '__WXGTK__':
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
#---------------------------------------------------------------------------
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you ... | rget to activate a virtual environment?"
| ) from exc
execute_from_command_line(sys.argv)
|
from skimage.data import coffee, camera
from sklearn_theano.feature_extraction.caffe.googlenet import (
GoogLeNetTransformer, GoogLeNetClassifier)
import numpy as np
from nose import SkipTest
import os
co = coffee().astype(np.float32)
ca = camera().astype(np.float | 32)[:, :, np.newaxis] * np.ones((1, 1, 3),
dtype='float32')
def test_googlenet_transformer():
"""smoke test for googlenet transformer"""
if os.envi | ron.get('CI', None) is not None:
raise SkipTest("Skipping heavy data loading on CI")
t = GoogLeNetTransformer()
t.transform(co)
t.transform(ca)
def test_googlenet_classifier():
"""smoke test for googlenet classifier"""
if os.environ.get('CI', None) is not None:
raise SkipTest("Ski... |
'''
Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
This module creates N nodes and sends X messages randomly between nodes and records
any failures. The messages are sent in blocks of 100 and then it waits and does it again.
Created on Jul 7, 2014
@author... | f.myIP = NetworkUtils.getNonLoopbackIP (None, None)
self.allNodes = []
self.timeout = (numNodes * 5) + numMessages # How many seconds to tr | y before erroring out
self.connectedNodeList = [] # How many are currently connected?
self.testCounter = -1
def tearDown(self):
# Stop the nodes
# self.leave(None, self.bsNode)
# self.leave(None, self.normalNode)
# #print("Tearing down...")
pass
... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.template.context_processors import csrf
from common import post_required, login_required, redirect_if_loggedin, __redirect
# Create your views here.
def index(request):
data | = {'title': 'Error', 'page':'home'};
# return HttpResponse ('This is Invalid Request')
file = device.get_template(request, 'error_erro | r.html')
return render(request, file, data)
def invalid_request_view(request):
data = {'title': 'Invalid Request', 'page':'home'};
# return HttpResponse ('This is Invalid Request')
file = device.get_template(request, 'error_invalid_request.html')
return render(request, file, data)
def under_construction_view(requ... |
from django import template
from django.conf import settings
from django.db.m | odels import get_model
from django.template import defaultfilters, loader
from .. import library
from .. import renderers
from ..dashboard import forms
ContentType = get_model('contenttypes', 'ContentType')
register = template.Library()
@register.assignment_tag
def update_blocks_form(page, container_name):
con... | tag(takes_context=True)
def render_attribute(context, attr_name, *args):
"""
Render an attribute based on editing mode.
"""
block = context.get(renderers.BlockRenderer.context_object_name)
value = getattr(block, attr_name)
for arg in args:
flt = getattr(defaultfilters, arg)
if f... |
#!/usr/bin/python
## Download files from Amazon S3 (e.g. raw photos for 3D models)
## Andy Bevan 15-Jun-2014, updated 21-Nov-2014
## Daniel Pett updated 05-Jan-2016
__author__ = 'ahb108'
## Currently for Python 2.7.5 (tested on MacOSX 10.9.2) launched in a virtual environment:
from PIL import Image # Pillow with libj... | micropasts.org'
###################################
# Get the raw jpg files from working directory
ext = ['.JPG', '.jpg', '.jpeg', '.JPEG']
files = [ f for f in os.listdir('.') if f.endswith(tuple(ext)) ]
print("Masking each individual photograph...")
for q in range(0, len(files)):
# Open an example image
im... | os.path.splitext(files[q])[0]
# Get JSON data for tasks and find task ID for this file
downloadURL = str(pybinst) + '/project/' + str(app) + '/tasks/export?type=task&format=json'
outputFilename = str(app) + '_task.json'
# Download JSON file to working direcory
response = urllib2.urlopen(downlo... |
"""Copyright 2011 The University of Michigan
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 writi... | ry)
used_time = self.used_time()
logging.msg('%-15s %d\n' % ('chess_runs', runs))
logging.m | sg('%-15s %f\n' % ('chess_time', used_time))
class RaceTestCase(race_testing.TestCase):
""" Run race detector to find all racy instructions.
"""
def __init__(self, test, mode, threshold, profiler):
race_testing.TestCase.__init__(self, test, mode, threshold, profiler)
class ChessRaceTestCase(testin... |
from __future__ import print_function
from ADSOr | cid.models import ClaimsLog
from ADSOrcid import tasks
from collections import defaultdict
app = tasks.app
def run():
stats = defaultdict(lambda: 0)
authors = {}
i = 0
with app.session_scope() as session:
for r in session.query(Clai | msLog).order_by(ClaimsLog.id.asc()).yield_per(1000):
stats[r.status] += 1
if r.orcidid and r.bibcode:
if r.orcidid not in authors:
authors[r.orcidid] = {'claimed': 0, 'forced': 0, '#full-import': 0, 'updated': 0, 'removed': 0, 'unchanged': 0}
a... |
from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization
from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import... | ser_data
bundle.data['content_type'] = bundle.obj.content_type.model
| return bundle
def hydrate(self,bundle):
# preserve data
if bundle.request.method == 'PATCH':
#preserve original fields
fields = ['user', 'published', 'content_type', 'object_id', 'created', 'client_domain']
orig_obj = Comment.objects.get(pk=i... |
"""
A special type of hypothesis whose value is a function.
The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle
This can also be called like a function, as in fh(data)!
"""
from Hypothesis import Hypothesis
from copy import copy
clas... | pickle
This can also be called like a function, as in fh(data)!
"""
def __init__(self, value=None, f=None, display="lambda x: | %s", **kwargs):
"""
*value* - the value of this hypothesis
*f* - defaultly None, in which case this uses self.value2function
*args* - the arguments to the function
"""
# this initializes prior and likleihood variables, so keep it here!
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Packing metadata for setuptools."""
from io import open
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
with open('README.rst', encoding='utf-8') as readme_file:
readme = readme_file.read()
wit | h open('HISTORY.rst', encoding='utf-8') as | history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
'orderedset',
'hamster-lib >= 0.13.0',
]
setup(
name='hamster-gtk',
version='0.11.0',
description="A GTK interface to the hamster time tracker.",
long_description=readme + '\n\n' + history,
auth... |
import numpy as np
NR_PER_CONDITION = 1000
neuro_sigma = 4
neuro_mean = 0
satis_sigma = 4
satis_mean = 0
print "Start drawing"
bins = {
5: np.array([-6, -3, 0, 3, 6]),
7: np.array([-6, -4, -2, 0, 2, 4, 6])
}
borders = {
5: np.array([-4.5,-1.5,1.5,4.5]),
7: np.array([-5.,-3.,-1.,1,3,5])
}
'outpu... | r(i+1))
outfile.write('\n')
for cond in conditions:
print "Writing con | dition ", cond['cond']
for i in range(12):
neuro = neuro_sigma * np.random.randn(NR_PER_CONDITION) + neuro_mean
neuro_index = np.digitize(neuro, borders[cond['first']])
neuro_vals[i] = bins[cond['first']][neuro_index]
satis = satis_sigma * np.random.randn(NR_PER_CONDITION) + satis_m... |
from _ | _future__ import | unicode_literals
from django.apps import AppConfig
class ImagerImagesConfig(AppConfig):
name = 'imager_images'
def ready(self):
"""Run when app ready."""
from imager_images import signals
|
class ProjectManager(object):
def create(self | , project_name):
pass
def delete(self, project_name):
pass
def list_projects(self):
pass
def up | load_file(self, project_name, filename):
pass
|
import pytest
class TestService:
@pytest.mark.complete("service ")
def test_1(self | , completion): |
assert completion
|
ute_import
from setuptools import setup, find_packages, Extension, Command
from setuptools.command.build_ext import build_ext
from setuptools.command.egg_info import egg_info
from distutils.file_util import copy_file
from distutils.dir_util import mkpath, remove_tree
from dis | tutils.util import get_platform
from distutils import log
import os
import sys
import subprocess
if sys.version_info[:2] < (3, 6):
sys.exit(
"error: Python 3.6 is required to run setup.py. \n"
"The generated wheel will be compatible with both py27 and py3+"
)
cmdclass = {}
try:
from wheel.... | n ("py2.py3", "none") + bdist_wheel.get_tag(self)[2:]
cmdclass["bdist_wheel"] = UniversalBdistWheel
class Download(Command):
user_options = [
("version=", None, "ots source version number to download"),
("sha256=", None, "expected SHA-256 hash of the source archive"),
("download-dir=... |
orial2.py
This performs the same features as the C++ tutorial2.
It creates a room and a 3D sprite.
===========================================================================
There are two ways to use the CsPython module.
Either as a plugin within CS (pysimp),
or as a pure Python module (this example).
This is just... | None or self.loader==None:
FatalError("Error: in object registry query")
| if not csInitializer.OpenApplication(object_reg):
FatalError("Could not open the application!")
txtmgr=self.g3d.GetTextureManager()
room=self.SetupRoom() # creates & returns the room
self.CreateLights(room)
self.LoadSprites(room)
self.Crea... |
attrs:
priority.append(u'tiny-repeat')
del attrs[u'tiny-repeat']
return priority + attrs.keys()
def evaluate(self,node,binding=None):
if node[u'__name__'] == u'__root__':
map(lambda x:self.evaluate_node(x,binding),node[u'__children__'])
else:
... | ain tree
replace_in_parent(content_index_tracker,brother_index_tracker,evaluated)
# delegate evalution of new evaluated nodes
map(lambda x:self.evaluate_node(x,binding),evaluated)
| # hand out control already
# stop processing
return
# here,means node not changed in main tree,
# process children
for child in node[u'__children__']:
self.evaluate_node(child,binding)
def _e... |
#!/usr/bin/python2
"""fkmonthgraph - graph of enemy fighter kills & losses, by month
Requires matplotlib, see http://matplotlib.org or search your package
manager (Debian: apt-get install python-matplotlib)
"""
import sys
import hdata, fighterkill
from extra_data import Fighters as extra
import matplotlib.pyplot as p... | xt()
month = next
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
dates = sorted(monthly.keys())
for fi,f in enumerate(hdata.Fighter | s):
def ins(m):
return hdata.inservice(m, f) or hdata.inservice(m.nextmonth(), f)
gp = plt.plot_date([d.ordinal() for d in dates if ins(d)], [monthly[d]['kills'][fi] for d in dates if ins(d)], fmt='o-', mew=0, color=extra[f['name']]['colour'], tz=None, xdate=True, ydate=False, label=f['name'], zorder=0)
gl = p... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLE | ASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/attachment/engine/shared_hutt_medium_engine_s02.iff"
result.attribute_template_id = 8
result.stfName("item_n","ship_attachment")
#### BEGIN MODIFICATIONS ... | return result |
from django.db import | models
class Author(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self | ):
return self.name
class Book(models.Model):
name = models.CharField(max_length=20)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.name
|
#
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | __init__(self) :
self._undefaction = ""
@property
def undefaction(self) :
ur"""Action to perform when policy evaluation creates an UNDEF condition. Available settings function as follows:
* NOOP - Send the request to the protected server.
* RESET - Reset the request and notify the user's browser, so that the... | return self._undefaction
except Exception as e:
raise e
@undefaction.setter
def undefaction(self, undefaction) :
ur"""Action to perform when policy evaluation creates an UNDEF condition. Available settings function as follows:
* NOOP - Send the request to the protected server.
* RESET - Reset the reque... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple lib to connect to a Zabbix agent and request the value of an item.
"""
import socket
def query_agent(**kwarg | s):
"""
Open a socket to port 10050 on the remote server and query for the number of
processes running via proc.num[<FOO>], where FOO is either zabbix_server or
zabbix_proxy.
"""
query_string = kwargs.get('query_string', 'agent.ping')
query_host = kwargs.get('query_host', '127.0.0.1')
query_port = kwar... | query_port', '10050')
try:
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((query_host, query_port))
except:
return (99999, 'ERROR: {} :: {}:{}'.format(e, query_host, query_port))
else:
connection.send(query_string)
result = connection.recv(8192)
connecti... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
trusted_scons_files = [
'src/shared/ppapi/build.scons',
'src/shared/ppapi_proxy/build.scons',
'src/trusted/plugin/build.scons',
'tests/p... | ce/nacl.scons',
'tests/ppapi_browser/ppb_memory/nacl.scons',
'tests/ppapi_browser/ppb_pdf/nacl.scons',
'tests/ppapi_browser/ppb_scrollbar/nacl.scons',
'tests/ppapi_browser/ppb_url_loader/nacl.scons',
'tests/ppapi_browser/ppb_url_request_info/nacl.scons',
'tests/ppapi_browser/ppb_var/nacl.scons',... | ns',
'tests/ppapi_browser/ppp_instance/nacl.scons',
'tests/ppapi_browser/progress_events/nacl.scons',
'tests/ppapi_browser/stress_many_nexes/nacl.scons',
'tests/ppapi_example_2d/nacl.scons',
'tests/ppapi_example_audio/nacl.scons',
'tests/ppapi_example_events/nacl.scons',
# TODO(dspringer): r... |
ppool_name2_rev1_v6 = {
'apiVersion': API_VERSION,
'kind': 'IPPool',
'metadata': {
'name': 'ippool-name2'
},
'spec': {
'cidr': "fed0:8001::/64",
'ipipMode': 'Never',
'blockSize': 123
}
}
#
# BGPPeers
#
bgppeer_name1_rev1_v4 = {
'apiVersion': API_VERSION,
... | 'selector': "type=='application'",
},
'protocol': 'TCP',
'source': {
'notNets': ['10.1.0.0/16'],
'notPorts': [1050],
'notSelector': "type=='database'",
'nets': ['10.0.0.0/16'],
... | r': "type=='application'",
'namespaceSelector': 'has(role)',
}
}
],
}
}
networkpolicy_name1_rev2 = {
'apiVersion': API_VERSION,
'kind': 'NetworkPolicy',
'metadata': {
'name': 'policy-mypolicy1',
'namespace': 'default'
},
's... |
_ import with_statement
import socket
import sys
from collections import defaultdict, deque
from functools import partial
from itertools import count
from . import serialization
from .entity import Exchange, Queue
from .log import Log
from .messaging import Consumer as _Consumer
from .utils import uuid
__all__ = ["... |
# we cache the channel for subsequent calls, this has to be
# reset on revival.
channel = conn.default_channel
revive = partial(revive_connection, conn, on_revive=on_revive)
insured = con | n.autoretry(fun, channel, errback=errback,
on_revive=revive, **opts)
retval, _ = insured(*args, **dict(kwargs, connection=conn))
return retval
def ipublish(pool, fun, args=(), kwargs={}, errback=None, on_revive=None,
**retry_policy):
with pool.acquire(block... |
#!/usr/bin/python
#
# Copyright 2014, Intel 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; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
#... | n(spec_file,"r") as spec_fd:
for line in spec_fd:
if "License:" in line:
return line.split("License:")[1].replace("\n","").replace("\t","").replace(" ","")
return license
class CheckRpmSrc(cmdln.Cmdln):
name = "createVersionYoctoTizen"
version = "0.1"
@cmdln.option( "--rpmsSRCDI... | n = "store",
default = "Tizen-rpm-source.html",
help = "the Tizen rpms source dir" )
def do_status(self, subcmd, opts):
"""generate status
${cmd_usage}--
${cmd_option_list}
"""
for package_rpm in os.listdir(opts.rpmsSRCDIR):
... |
###############################################################################
##
## Copyright (C) 2014 Tavendo GmbH
##
## 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:/... | d.
## See the License for the spec | ific language governing permissions and
## limitations under the License.
##
###############################################################################
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import CallResult
from autobahn.twisted.wamp im... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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 retain the above copyright notice, this
... | ED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package co | ntenant la commande 'scripting alerte info'."""
from primaires.interpreteur.masque.parametre import Parametre
from primaires.format.fonctions import echapper_accolades
from primaires.format.date import get_date
class PrmInfo(Parametre):
"""Commande 'scripting alerte info'"""
def __init__(self):
... |
from typing import List, Any, Mapping
from .utils import clean_filters
class DockerTasks(object):
def __init__(self, docker):
self.docker = docker
async def list(self, *, filters: Mapping=None) -> List[Mapping]:
"""
Return a list of tasks
Args:
filters: a collecti... | k
Args:
task_id: is ID | of the task
"""
response = await self.docker._query_json(
"tasks/{task_id}".format(task_id=task_id),
method='GET',
)
return response
|
import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnec... | HOST, cond)
# disconnect mn_host1
host = cluster1_host[0]
host_ops.update_kvm_host(host.uuid, 'username', "root1")
try:
host_ops.reconnect_host(host.uuid)
except:
test_util.test_logger("host: [%s] is disconnected" % host.uuid)
disconnect = True
# create_volume on 2 clusters... | "volumeProvisioningStrategy::ThickProvisioning", "capability::virtio-scsi",
"miniStorage::clusterUuid::%s" % cluster1.uuid]
volume_creation_option = test_util.VolumeOption()
volume_creation_option.set_name("cluster1_volume")
volume_creation_option.set_primary_storage_uuid(ps.uuid)
vol... |
# 1. Convert 1024 to binary | and hexadecimal representation:
x = 1024
y = bin(x)
z | = hex(x) |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/getaddons.ui'
#
# Created: Fri Aug 22 00:57:31 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
ex... | AL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_("Install Add-on"))
self.label.setText(_("To browse add-ons, please click the browse button below.<br><br>When you\'ve found an add-on you like, ... | |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | se for the specific language g | overning permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for GetFinding
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, e... |
nascii, pyasn1, pyasn1.codec.ber.decoder, pycurl, StringIO
SIGNATURE_NONE = b'\x00'
SIGNATURE_ECDSA_SHA256_SECP224R1 = b'\x01'
# Dump integer to a C array, used for debugging only
def c_array(name, val):
length = len(val)
res = ""
for i in range(0, length):
if (i % 16) == 0:
res = res ... | '
ei_class = output[4]
assert ei_class == b'\x01', 'Only 32-bit ELF files are supported'
ei_data = output[5]
assert ei_class == b'\x01', "Only LE ELF | files are supported"
ei_version = output[6]
assert ei_version == b'\x01', "Only ELF version 1 is supported"
e_shoff = elf_read_le(output, 0x20, 4) # Start of section header table
e_shentsize = elf_read_le(output, 0x2e, 2) # Size of a section header table entry
e_shnum = elf_read_le(output, 0x30,... |
must be grayscale.
"""
if image.shape[-1] in (3, 4):
msg = "threshold_otsu is expected to work correctly only for " \
"grayscale images; image shape {0} looks like an RGB image"
warnings.warn(msg.format(image.shape))
hist, bin_centers = histogram(image.ravel(), nbins)
his... | y zero.
crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) *
(P1[:-1] * (1.0 - P1[:-1])) ** 2)
return bin_centers[crit.argmax()]
|
def threshold_isodata(image, nbins=256, return_all=False):
"""Return threshold value(s) based on ISODATA method.
Histogram-based threshold, known as Ridler-Calvard method or inter-means.
Threshold values returned satisfy the following equality:
`threshold = (image[image <= threshold].mean() +`
... |
# -*- coding: utf-8 -*-
#
# privacyIDEA is a fork of LinOTP
# May 08, 2014 Cornelius Kölbel
# License: AGPLv3
# contact: http://www.privacyidea.org
#
# 2014-10-17 Fix the empty result problem
# Cornelius Kölbel, <cornelius@privacyidea.org>
#
# Copyright (C) 2010 - 2014 LSE Leading Security Experts G... | auditdata": pagination.auditdata,
"prev": pagination.prev,
"next": pagination.next,
"current": pagin | ation.page,
"count": pagination.total}
return ret
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Sou | rce Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redis | tribute 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... |
build configuration.
All build configuration data is composed of basic python builtin types and higher-level
configuration objects that aggregate configuration data. Configuration objects can carry a name
in which case they become addressable and can be reused.
"""
# Internal book-keeping fields to exclude... | ncrete configuration instance that is a type compatible with
this configuration or this configurations superclasses.
:param **kwargs: The configurat | ion parameters.
"""
self._kwargs = kwargs
self._kwargs['abstract'] = abstract
self.extends = extends
self.merges = merges
# Allow for configuration items that are directly constructed in memory. These can have an
# address directly assigned (vs. inferred from name + source file location)... |
dation; 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 FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more deta... | session=self._session,
location=self.get_location(),
)
location = None
| if self.download:
if self.is_hunt():
location = self._config.server.hunt_vfs_path_for_client(
self.flow_id, vfs_type="files",
path_template="{client_id}/{subpath}",
expiration=self.expiration())
else:
... |
"""Custom exceptions for ExecutionContext package
"""
from generic_utils.exceptions import GenUtilsException
from generic_utils.exceptions import GenUtilsKeyError
from generic_utils.exceptions import GenUtilsRuntimeError
class ExecutionContextStackEmptyError(GenUtilsException):
"""Raised when stack is empty and ... | ey = None
class ExecutionContextRuntimeError(GenUtilsRuntimeError):
"""Raised when ExecutionContextStack | can not recover from an unknown problem."""
message = "ExecutionContextStack could not complete operation due to reason={reason}."
reason = None
|
# decodex - simple enigma decoder.
#
# Copyright (c) 2013 Paul R. Tagliamonte <tag@pault.ag>
#
# This program 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 ... | def __init__(self, dictionary):
self.path = "/usr/share/dict/%s" % (dictionary)
self.mapping = defaultdict(set)
self.word_hash = {}
self._build_map()
def _build_map(self):
for line in (cleanup(x) for x in open(self.path, 'r')):
self.word_hash[line] = line |
self.mapping["".join(sorted(line))].add(line)
def anagram(self, word, depth=2):
if depth == 0:
return
l_hash = "".join(sorted(word))
# OK. Let's start simple.
if l_hash in self.mapping:
for entry in self.mapping[l_hash]:
yield [e... |
, 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 FRO... | form_p | attern = models.BooleanField(blank=False, null=False, default=False)
small_cell_signet_ring = models.BooleanField(blank=False, null=False, default=False)
hypernephroid_pattern = models.BooleanField(blank=False, null=False, default=False)
mucinous = models.BooleanField(blank=False, null=False, default=False)... |
def transform(dataset, XRANGE=None, YRANGE=None, ZRANGE=None):
"""Define this method for Python operators that
transform input scalars"""
import numpy as np
array = dataset.active_scalars
if array is None:
raise RuntimeError("No scalars found!")
# Transform the dataset.
result = ... | py(array)
result[XRANGE[0]:XRANGE[1], YRANGE[0]:YRANGE[1], ZRANGE[0]:ZRANGE[1]] = 0
# Set the result as | the new scalars.
dataset.active_scalars = result
|
#
# Copyright 2011 Twitter, 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 agreed to in writing, so... | ields_to_keep = list(it | ertools.chain(fields_to_keep))
else:
fields_to_keep = fields_to_keep[0]
return Apply(fields_to_keep, Identity(Fields.ARGS), Fields.RESULTS)
def _discard(fields_to_discard):
# In 2.0 there's a builtin function this, Discard
# In 1.2 there is nothing for this
raise Exception('Discard only wo... |
# -*- coding: utf-8 -*-
"""
@file: tasks.py
@author: lyn
@contact: tonylu716@gmail.com
@python: 3.5
@editor: Vim
@create: 3/29/17 2:20 AM
@description:
用于反爬虫的一些异步任务,主要是刷新数据表中某些临时记录。
"""
from __future__ import absolute_import, unicode_literals
from celery import task as celery_task
from .model... | ("clear {} acts from acti | vities".format(ip_activity.ip))
clear_act_ips.append(ip_activity.ip)
return clear_act_ips
|
import random as rd
class Pile:
def __init__(self, data=None):
if data:
self.data = [i for i in data]
else:
self.data = []
def __repr__(self):
max_sp = len(str(max(self.data)))
out = ""
for i in range(len(self.data) - 1, -1, -1):
out... | carre = racine * racine
# print("{} -> {}".format(n, racine))
# return racine
#
#
# # print(suite_newton | (3, 8))
# # sqrt_newton(3, 0.01)
#
# def dichoto(r, error):
# mini = 0
# maxi = r
# racine = (maxi + mini) / 2
# racine_carre = racine * racine
# while not -error < r - racine_carre < error:
# if racine * racine > r:
# maxi = racine
# if racine * racine < r:
# ... |
import os
from rbm import RBM
from au import AutoEncoder
import tensorflow as tf
import input_data
from utilsnn import show_image, min_max_scale
import matplotlib.pyplot as plt
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
flags.DEFINE_integer('epo... | , 20), (25, 10))
rbmobject3.save_weights('./out/rbmw3.chp')
# Train Third RBM
print('fourth rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
# Transform features
batch_xs = rbmobject1.transform(batch_xs)
batch_xs = rbmobject2... | bmobject4.compute_cost(rbmobject3.transform(rbmobject2.transform(rbmobject1.transform(trX)))))
rbmobject4.save_weights('./out/rbmw4.chp')
# Load RBM weights to Autoencoder
autoencoder.load_rbm_weights('./out/rbmw1.chp', ['rbmw1', 'rbmhb1'], 0)
autoencoder.load_rbm_weights('./out/rbmw2.chp', ['rbmw2', 'rbmhb2'], 1)
au... |
from django.shortcuts import render
from moth.views.base.vulnerable_template_view import VulnerableTemplateView
class EchoHeadersView(VulnerableTemplateView):
description = title = 'Echoes all request headers'
url_path = 'echo-headers.py'
| KNOWN_HEADERS = ('CONTENT_LENGTH',)
def is_http_header(self, hname):
return hname.startswith('HTTP_') or hname in self.KNOWN_HEADERS
def translate_header(self, hname):
hname = hname.replace('HTTP_', '')
hname = hname.replace('_', '-')
hname = hname.lower()
hname = hnam... | t_context_data()
html = ''
msg_fmt = 'Header "%s" with value "%s" <br/>\n'
for hname in request.META:
if self.is_http_header(hname):
html += msg_fmt % (self.translate_header(hname),
request.META[hname])
... |
# Copyright 2018 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# for py2/py3 compatibility
from __future__ import print_function
import signal
from . import base
from testrunner.local import utils
class SignalProc(... | Proc, self).setup(*args, **kwargs)
# It should be called after processors are chained together to not loose
# catched signal.
signal.signal(signal.SIGINT, self._on_ctrlc)
signal.signal(signal.SIGTERM, self._on_sigterm)
def _on_ctrlc(self, _signum, _stack_frame):
print('>>> Ctrl-C detected, early ... | self.exit_code = utils.EXIT_CODE_TERMINATED
self.stop()
|
# coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "Li | cense");
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
distributed under the License is distributed on an "AS IS" BASIS,
... | g permissions and
limitations under the License.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
class SeriesActors(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
... |
import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
h... | nextpos = random.randint(0, self.lsize)
| if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
ret... |
from setuptools import setup
from os import path, environ
from sys import argv
here = path.abspath(path.dirname(__file__))
try:
if argv[1] == "test":
environ['PYTHONPATH'] = here
except IndexError:
pass
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
... |
test_suite="test/test_all.py",
scripts=['scripts/libfs.py'],
| keywords='fuse multimedia',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :... |
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | y the Free Software Foundation, either version 3 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 FITNESS FOR A PARTICULAR PURPOSE. See the
# ... | lic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Sale Require Purchase Order Number',
... |
# coding=utf-8
import unittest
from types import MethodType
from parameterized import parameterized
from six import StringIO
from conans.client.output import ConanOutput, colorama_initialize
from mock import mock
class ConanOutputTest(unittest.TestCase):
def test_blocked_output(self):
# https://github... | with mock.patch("time.sleep") as sleep:
out.write("Hello world")
sleep.assert_any_call(0.02)
self.assertEqual("Hello world", stream.getvalue())
@parameterized.expand([(False, {}),
(False, {"CONAN_COLOR_DISPLAY": "0"}),
(True, {... | "PYCHARM_HOSTED": "1"}),
(True, {"PYCHARM_HOSTED": "1", "CONAN_COLOR_DISPLAY": "0"}),
(True, {"NO_COLOR": ""}),
(True, {"CLICOLOR": "0"}),
(True, {"CLICOLOR": "0", "CONAN_COLOR_DISPLAY": "1"}),
... |
ry:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog, tkMessageBox
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
from tkinter import filedialog as tkFileDialog
from tkinter import messagebox as t... | mport sys, os
from scipy.io.wavfile import read
import hps | Model_function
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../models/'))
import utilFunctions as UF
class HpsModel_frame:
def __init__(self, parent):
self.parent = parent
self.initUI()
def initUI(self):
choose_label = "Input file (.wav, mono and 44100 sampling... |
number = input()
number_array = [(int)(x) for x in raw_input().s | plit()]
total = 0
for i in range(1, number):
for j in range(i):
ii = number_array[i]
jj = number_a | rray[j]
if ii < jj:
total += i - j
number_array = number_array[:j] + [ii] + [jj] + number_array[j+1:i] + number_array[i+1:]
break
print total
|
import json
import requests
import time
import csv
from datetime import datetime
#------------------------------------------------------------- | ---------
def login(client_id, client_secret, username, password):
"""logs into reddit using Oauth2"""
client_auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
post_data = {"grant_type": "password", "username": username,
"password": password}
response = requests.post("https:... | auth=client_auth, data=post_data)
print response
token_json = response.json()
headers = {"Authorization": "%s %s" % (token_json["token_type"],
token_json["access_token"]),
"User-Agent": user_agent}
return headers
#-----------------------------... |
a_str1 = "Craig McBean"
a_str2 = "Sheree-Annm Lewis-McBean"
a_str3 = 'Sheyenne Lewis'
a_str4 = raw_input("E | nter fourth Name: ")
print "{:>30}".format(a_str1)
print "{:>30}".format(a_str2)
print "{:>30}".format(a_str3)
print "{ | :>30}".format(a_str4)
|
# 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
# distributed under t... | ge governing permissions and limitations
# under the License.
import mock
from openstack.tests.unit import base
from openstack.identity.v2 import extension
IDENTIFIER = 'IDENTIFIER'
EXAMPLE = {
'alias': '1',
'description': '2',
'links': '3',
'name': '4',
'namespace': '5',
'updated': '2015-03-... | ey)
self.assertEqual('extensions', sot.resources_key)
self.assertEqual('/extensions', sot.base_path)
self.assertFalse(sot.allow_create)
self.assertTrue(sot.allow_fetch)
self.assertFalse(sot.allow_commit)
self.assertFalse(sot.allow_delete)
self.assertTrue(sot.allow... |
#!/usr/bin/env/python
"""
We treat each silica atom as its own residue. As a consequence,
we have more than 10000 residues | in the system.
The silly PDB format only allows up to 9999 residues. We solve
this issue by manually creating a .gro file | , which allows for
up to 99999 residues
"""
from __future__ import print_function
import re
import MDAnalysis as mda
pdbf = 'SiO2carved_ovl1.5_protein_0.17.pdb'
# retrieve atom info
u = mda.Universe(pdbf)
GRO_FMT = ('{resid:>5d}{resname:<5s}{name:>5s}{id:>5d}'
'{pos[0]:8.3f}{pos[1]:8.3f}{pos[2]:8.3f}'
... |
lta) # [3, 6, 9, 12, 15]
start = 3
limit = 1
delta = -0.5
tf.range(start, limit, delta) # [3, 2.5, 2, 1.5]
limit = 5
tf.range(limit) # [0, 1, 2, 3, 4]
```
Args:
start: A 0-D `Tensor` (scalar). Acts as first entry in the range if
`limit` is not None; otherwise, acts as range limit and fir... | fault),
reduces all dimensions. Must be in the range
`[-rank(input_tensor), rank(input_tensor))`.
keep_dims: If true, retains reduced dimensions with length 1.
dtype: The output dtype; defaults to `tf.int64`.
name: A name for the operati | on (optional).
reduction_indices: The old (deprecated) name for axis.
Returns:
The reduced tensor (number of nonzero values).
"""
with ops.name_scope(name, "count_nonzero", [input_tensor]):
input_tensor = ops.convert_to_tensor(input_tensor, name="input_tensor")
zero = input_tensor.dtype.as_numpy_... |
eline
The PatternCounter is responsible for creating a CountCombiner and a
DecompGenerator, then running the DecompGenerator, getting DPTable
objects from the CountCombiner for the decompositions, and returning
the final count from the whole graph.
"""
def __init__(self, G, multi, td_list, col... | d_file
self.dp_table_file = dp_table_file
self.dp_table = None
self.colset_count_file = colset_count_file
self.combiners = [combiner_class(len(multi[idx]), coloring, table_hints, td=td_list[idx],
ex | ecdata_file=colset_count_file) for idx in range(len(multi))]
before_color_set_callbacks = [combiner.before_color_set for combiner in self.combiners]
after_color_set_callbacks = [combiner.after_color_set for combiner in self.combiners]
# TODO: calculate a lower bound on treedepth
self.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-01-10 18:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0028_auto_20170113_2133'),
]
operations = [
migrations.RemoveFi... | ,
),
migrations.RemoveField(
model_name='profile',
name='address2',
),
migrations.RemoveField(
model_name='profile',
name='address3',
),
migrations.AddField(
model_name='profile',
| name='address',
field=models.CharField(blank=True, max_length=100, null=True),
),
]
|
__version__ = '1.2.0'
from .oss_authorizers import OssA | uthorizer
from .oss_file_operation import OssFileOperation
from .oss_fs import OssFS
from .oss_fs_impl import | OssFsImpl
|
etypes
import os
import posixpath
import re
from time import time
from urlparse import urlsplit, urlunsplit
from werkzeug.exceptions import NotFound
from werkzeug.http import is_resource_modified, http_date
from spa.static.handlers import StaticHandler
from spa.utils import clean_path
class HashCache(object):
d... | s_url_patterns:
| converter = self.get_converter(tpl)
contents = pat.sub(converter, contents)
self.hash_cache.set_contents(filepath, contents)
headers.extend((
('Content-Type', file.mimetype),
('Content-Length', len(contents)),... |
from __future__ import unicode_literals
import frappe, unittest
from werkzeug.wrappers import Request
from werkzeug.test import EnvironBuilder
from frapp | e.website import render
def set_request(**kwargs):
builder = EnvironBuilder(**kwargs)
frappe.local.request = Request(builder.get_environ())
class TestWebsite(unittest.TestCase):
def test_page_load(self):
set_request(method='POST', path='login')
response = render.render()
self.assertTrue(response.status_cod... | in.js' in html)
self.assertTrue('<!-- login.html -->' in html)
|
idget: gtk widget
"""
GrampsTab.__init__(self, dbstate, uistate, track, name)
eventbox = Gtk.EventBox()
eventbox.add(widget)
self.pack_start(eventbox, True, True, 0)
self._set_label(show_image=False)
eventbox.connect('key_press_event', self.key_pressed)
se... | te'), vboxnote)
self.track_ref_for_deletion("ntab")
self.build_interface()
def _setup_fields(self):
"""Get control widgets | and attach them to Note's attributes."""
self.type_selector = MonitoredDataType(
self.top.get_object('type'),
self.obj.set_type,
self.obj.get_type,
self.db.readonly,
custom_values=self.get_custom_notetypes(),
ignore_values=self.obj.get_type... |
#!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : Libs/IOST_WAboutDialog/IOST_AboutDialog.py
# Date : Sep 21, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT Licen... | ()
self.IOST_AboutDialog_Builder.add_from_file(glade_filename)
self.IOST_AboutDialog_Builder.connect_signals(self)
else:
self.IOST_AboutDi | alog_Builder = main_builder
# self.IOST_Objs[window_name][window_name+ object_name] = self.IOST_AboutDialog_Builder.get_object(window_name+object_name)
# self.IOST_Objs[window_name][window_name+ object_name].set_version(self.IOST_Data["ProjectVersion"])
self.CreateObjsDictFromDict(self... |
self.setGeometry(100, 150, 600, 400)
self.setWindowTitle('Configure Destinations')
# Let's make ourselves a nice little layout
conf_hbox = self.getChooser(self)
# Let's make the menubar
menubar = self.makeMenubar()
self.setMenuBar(menubar)
# Save changes?
save = self.makeSaveButton()
... | lid place
if not duplicate:
self.configObject.append({'name' : str(name), 'destination' : str(value), 'user' : str(user), 'pw' : str(pw)})
# Displays in the dialog
QtGui.QListWidgetItem(name + '\t' + value, self.siteList)
# Flag the current entry as change | d
self.changes = True
# Sorting is fun!
self.siteList.sortItems()
else:
print 'Duplicate detected'
QtGui.QMessageBox.warning(self, 'Duplicate Detected', 'That entry already exists, ignoring.')
else:
print 'Rejecting'
def delEntry(self):
item = self.siteList.takeItem(self.siteList.curren... |
from collections import OrderedDict
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.translation import ugettext_lazy as _
from oscar.apps.search import facets
FACET_COUNTS = {
u'dates': {},
u'fields': {
'category': [('Fiction', 12), ('Horror', 6), ('... | field': 'product_class'}),
('rating', {'name': _('Rating'), 'field': 'rating'}),
('category', {'name': _('Category'), 'field': 'category'}),
]),
'queries': OrderedDict([
('price_range',
{
'name': _('Price range'),
'field': 'price',
'queries... | _('20 to 40'), u'[20 TO 40]'),
(_('40 to 60'), u'[40 TO 60]'),
(_('60+'), u'[60 TO *]'),
]
}),
]),
}
@override_settings(OSCAR_SEARCH_FACETS=SEARCH_FACETS)
class TestFacetMunger(TestCase):
def test_with_no_facets_selected(self):
munger = facets.Fa... |
#
| # Autogenerated by Thrift Compiler (0.8.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException
from ttypes | import *
|
.extmath import logsumexp
from .utils.fixes import unique
from .utils import check_arrays, array2d
__all__ = ['LDA']
class LDA(BaseEstimator, ClassifierMixin, TransformerMixin):
"""
Linear Discriminant Analysis (LDA)
A classifier with a linear decision boundary, generated
by fitting class conditiona... | ercept_ = (-0.5 * np.sum(self.coef_ ** 2, axis=1) +
np.log(self.priors_))
| return self
@property
def classes(self):
warnings.warn("LDA.classes is deprecated and will be removed in 0.14. "
"Use LDA.classes_ instead.", DeprecationWarning,
stacklevel=2)
return self.classes_
def _decision_function(self, X):
X... |
"""
simpleSetup2: runs POST the JS setup
NOTE: for 1.2 USERS (and their signatures) still done here. Next jsSetup will take this over and the User setup part
will be removed from here.
"""
import os
import sys
import logging
import time
sys.path = ['rasUtilities'] + sys.path
import OSEHRASetup
from OSEHRAHelper impo... | @#$")
# Add a Pharmacist
OSEHRASetup.addPharmacist(VistA,"SHARMA,FRED","FS","000000031","M","fakepharma1","2Pha!@#$");
#Create a new Order Menu
OSEHRASetup.c | reateOrderMenu(VistA)
#Give all users of the instance permission to mark allergies as "Entered in error')
OSEHRASetup.addAllergiesPermission(VistA)
#Give Mary Smith permission to create shared templates
OSEHRASetup.addTemplatePermission(VistA,"MS")
# Add clinic via the XUP menu to allow sched... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.