prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from django.contrib.auth.models import User
from django.db import models
from oauth2client.django_orm import FlowField
from oauth2client.django_orm import CredentialsField
class Flow(models.Model):
"""
class to save flow objects in a multitreaded environment
"""
id = models.ForeignKey(User, prima... | )
class Credentials(models.Model):
"""
saves user oauth credentials for later use
"""
id = models.ForeignKey(User, primary_key | =True)
credential = CredentialsField()
|
#!/usr/bin/env python
# encoding: utf-8
import logging
import telegram
import random
import json
from giphypop import translate
with open('quotes.json') as data | _file:
quotes = json.load(data_file)
quotes = quotes["quotes"]
def main():
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
bot = telegram.Bot(token='YOUR BOT AUTHORIZATION TOKEN')
try:
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except I... | t_id = update.message.chat.id
update_id = update.update_id
if '/start' in text:
custom_keyboard = [["/quote", "/gif"]]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
bot.sendMessage(chat_id=chat_id,
... |
#!/usr/bin/env python
from __future__ import division
from __future__ import unicode_literals
import sys, math
import argparse
from volk_test_funcs import (create_connection, list_tables, get_results,
helper, timeit, format_results)
try:
import matplotlib
import matplotlib.pyplot ... | nitems = res[0]['nitems']
if args.percent is None:
s0.set_ylabel("Processing time (sec) [{0:G} items]".format(nitems),
fontsize=22, fontweight='bold',
horizon | talalignment='center')
else:
s0.set_ylabel("% Improvement over {0} [{1:G} items]".format(
args.percent, nitems),
fontsize=22, fontweight='bold')
s0.legend()
s0.set_xticks(x0)
s0.set_xticklabels(name_reg)
for label in s0.xaxis.get_ticklabels():
l... |
from ConfigParser import SafeConfigParser
import os.path
import pytest
import re
import textwrap
from amazonproduct import utils
def pytest_addoption(parser):
group = parser.getgroup('amazonproduct',
'custom options for testing python-amazon-product-api')
group._addoption('--locale', action='append', ... | can use the following
method::
configfiles.load_from_string('''
# file: /etc/boto.cfg
[Credentials]
aws_access_key_id = Hhdjksaiunkljfl
aws_secret_access_key = difioemLjdks02
# file: /home/user/.amazon-product-api
[Credentials]
locale = de
... | argvalue('tmpdir')
monkeypatch = request.getfuncargvalue('monkeypatch')
def prepend_tmppath(dir, files):
return [tmpdir.join(os.path.expanduser(fn)).strpath for fn in files]
monkeypatch.setattr(utils, 'CONFIG_FILES',
prepend_tmppath(tmpdir, utils.CONFIG_FILES))
cfg = DummyConfig(tmpdir... |
#!/usr/bin/env python
import server
import time
from Sensoria.stereotypes.TimeControlData import TimeControlData
from Sensoria.stereotypes.InstantMessageData import InstantMessageData
class TemperatureSensor (server.TemperatureS | ensor):
def __init__ (self):
super (TemperatureSensor, self).__init__ ("HD", "Heater Temperature")
class HeaterController (server.ControlledRelayActuator):
def __init__ (self):
super (HeaterController, self).__init__ ("HC", "Heater Controller")
#TL1:10 TL2:18 TL3:21
class HeaterTimer (server.TimedActuator):
de... | _ (self):
super (HeaterTimer, self).__init__ ("HT", "Heater Timer")
initData = TimeControlData ()
initData.unmarshal ("PMO:000000001000000003222110 PTU:000000001000000003222110 PWE:000000001000000003222110 PTH:000000001000000003222110 PFR:000000001000000003222111 PSA:000000000322222222222211 PSU:00000000032222222... |
.base.datasource import BaseDatasource
class Datasource(BaseDatasource):
base_url = "http://www.elections.state.md.us/elections/%(year)s/election_data/"
# PUBLIC INTERFACE
def mappings(self, year=None):
"""Return array of dicts containing source url and
standardized filename for raw resu... | n_slug(elec)
races[rtype] = elec
return races['general'], ra | ces['primary'], races['special']
def _race_type(self, election):
if election['special']:
return 'special'
return election['race_type'].lower()
def _build_metadata(self, year, elections):
year_int = int(year)
if year_int == 2002:
general, primary, specia... |
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import ActivateCode
import uuid
import os
from django.http import HttpRespo... | r(username=username,
email=email, password=password)
user.is_active = False
user.save()
new_code = str(uuid.uuid4()).replace("-", "")
expire_time = datetime.datetime.now() + datetime.timedelta(days=2)
code_record = ActivateCode(owner=user | , code=new_code,
expire_timestamp=expire_time)
code_record.save()
activate_link = "http://%s%s" % (request.get_host(), reverse(
"user_activate", args=[new_code]))
send_mail('[python论坛]激活邮件',
... |
index = self._index
buffer = self._buffer
while index < len(buffer):
size, type_ = struct.unpack_from("<2L", self._buffer, offset=index)
try:
name = ProxyGraphicTypes(type_).name.lower()
except ValueError:
logger.debug(f"Unsupported... | attribs["center"] = circle.center
attribs["radius"] = circle.radius
return self._factory("CIRCLE", dxfattribs=attribs)
def circular_arc(self, data: bytes):
bs = ByteStream(data)
attribs | = self._build_dxf_attribs()
center = Vec3(bs.read_vertex()) # in WCS
attribs["radius"] = bs.read_float()
normal = Vec3(bs.read_vertex()) # UCS z-axis
start_vec = Vec3(bs.read_vertex()) # UCS x-axis
# sweep angle around normal vector!
sweep_angle = bs.read_float() # i... |
import logging
import os
# URL to clone product_details JSON files from.
# Include trailing slash.
PROD_DETAILS_URL = 'http://svn.mozilla.org/ | libs/product-details/json/'
# Target dir to drop JSON files into (must be writable)
PROD_DETAILS_DIR = os.path.join(os.path.dirname(__file__), 'j | son')
# log level.
LOG_LEVEL = logging.INFO
|
from collections import Counter
def answer(q, | inf):
s = Counter(q.split(' ')); r = [-1,-1]
for i,j in enumerate(inf):
check = sum(s.get(w,0) for w in j.split(' '))
if check != 0 and check > r[1]: r = [i,check]
return None if r == | [-1,-1] else inf[r[0]]
|
# Standard Library Imports
from datetime import datetime
# 3rd Party Imports
# Local Imports
from PokeAlarm import Unknown
from . import BaseEvent
from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \
get_waze_link, get_dist_as_str, get_base_types, get_type_emoji
from PokeAlarm.Utilities.QuestUtils impo... | self.monster_id, self.monster_costume_id)
type1 = locale.get_type_name(self.monster_types[0])
type2 = locale.get_type_name(self.monster_types[1])
| dts = self.custom_dts.copy()
dts.update({
# Identification
'stop_id': self.stop_id,
'stop_name': self.stop_name,
'stop_image': self.stop_image,
# Location
'lat': self.lat,
'lng': self.lng,
'lat_5': "{:.5f}".format(s... |
)")
warn(NumbaInvalidConfigWarning(msg))
options['debug'] = False
irs = [str(mod) for mod in self.modules]
if options.get('debug', False):
# If we're compiling with debug, we need to compile modules with
# NVVM one at a time, because it does not ... | our linked libraries are modified by the finalization, and we
# won't be able to finalize again after adding new ones
self._raise_if_finalized()
self._linking_libraries.add(library)
def add_linking_file(self, filepath):
| self._linking_files.add(filepath)
def get_function(self, name):
for fn in self._module.functions:
if fn.name == name:
return fn
raise KeyError(f'Function {name} not found')
@property
def modules(self):
return [self._module] + [mod for lib in self... |
# debuggin
from lxml import etree
# 3rd-party modules
from lxml.builder import E
# module packages
from jnpr.junos.cfg import Resource
from jnpr.junos import jxml as JXML
from jnpr.junos.cfg.srx.shared_ab_addr import SharedAddrBookAddr
from jnpr.junos.cfg.srx.shared_ab_set import SharedAddrBookSet
class SharedAddrB... | xml, to_py)
Resource.copyifexists(as_xml, 'description', to_py)
to_py['$addrs'] = [name.text for name in as_xml.xpath('address/name')]
to_py['$sets'] = [
name.text for name in as_xml.xpath('address-set/name')]
# -------------------------------------- | ---------------------------------
# XML writing
# -----------------------------------------------------------------------
def _xml_change_zone_list(self, xml):
x_attach = E('attach')
self._xml_list_property_add_del_names(x_attach,
prop_name='zon... |
from django.db.models import Aggregate, CharF | ield
class Sql_GroupConcat(Aggregate):
function = 'GROUP_CONCAT'
allow_distinct = True
def __init__(self, expression, separator, distinct=False, ordering=None, **extra):
self.separator = separator
super(Sql_GroupConcat, self).__init__(expression,
... | % ordering if ordering is not None else '',
separator=' SEPARATOR "%s"' % separator,
output_field=CharField(),
**extra)
def as_mysql(self, compiler, connection):
return... |
import functools
import os
import re
import shutil
import subprocess
import sys
import tempfile
from io import StringIO
from subprocess import TimeoutExpired
from catkin_tools.commands.catkin import main as catkin_main
TESTS_DIR = os.path.dirname(__file__)
MOCK_DIR = os.path.join(TESTS_D | IR, 'mock_resources')
def catkin_success(args, env={}):
orig_environ = dict(os.environ)
try:
os.environ.update(env)
catkin_main(args)
except SystemExit as exc:
ret = exc.code
if ret != 0:
import traceback
traceback.print_exc()
finally:
os... | gs, env={}):
orig_environ = dict(os.environ)
try:
os.environ.update(env)
catkin_main(args)
except SystemExit as exc:
ret = exc.code
finally:
os.environ = orig_environ
return ret != 0
class AssertRaisesContext(object):
def __init__(self, expected, expected_regex... |
#!/usr/bin/env python
#
# Copyright (c) 2007-2009 Corey Goldberg (corey@goldb.org)
# License: GNU GPLv3
#
#
# This file is part of Pylot.
#
# 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
# ... | url = args[1]
post_data = args[4]
headers = args[5]
print ' <url>%s</url>' % | url
if post_data:
print ' <method>POST</method>'
print ' <body><![CDATA[%s]]></body>' % post_data
if headers:
print ' <add_header>%s</add_header>' % headers
print " </case>"
stop_event.set()
def OnQuit(self):
... |
from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from addons.urls import ADDON_ID
from amo.urlresolvers import reverse
from . import views
urlpatterns = patterns('',
# AMO stuff.
url(... | ),
url('^price-tiers$', views.price_tiers, name='zadmin.price_tiers'),
# The Django admin.
url('^models/', include(admin.site.urls)),
url('^models/(?P<app_id>.+)/(?P<model_id>.+)/search.json$',
views.general_search, name='zadmin.search'),
)
# Hijack the admin's login to use our pages.
def lo... | missions.
if request.user.is_authenticated():
raise PermissionDenied
else:
return redirect('%s?to=%s' % (reverse('users.login'), request.path))
admin.site.login = login
|
# Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
import deform
import colander
from pyramid.view import view_config
from dace.objectofcollaboration.principal.util import get_current
from dace.processinstance.core im... | MultipleView
from la | c.views.widget import EmailInputWidget
from lac.content.processes.lac_view_manager.behaviors import (
Improve)
from lac.content.lac_application import CreationCulturelleApplication
from lac import _
class ImproveStudyReport(BasicView):
title = 'Alert improve'
name = 'alertimprove'
template = 'lac:view... |
# -*- coding: utf-8 -*-
from ...query.expression import QueryExpression
from .relation import Relation
class HasManyThrough(Relation):
_first_key = None
_second_key = None
_far_parent = None
def __init__(self, query, far_parent, parent, first_key, second_key):
"""
:param query: A Bu... | r_parent: Model
:param parent: The parent model
:type parent: Model
:type first_key: str
:type second_key: str
"""
self._first_key = first_key
self._second_key = second_key
self._far_parent = far_parent
| super(HasManyThrough, self).__init__(query, parent)
def add_constraints(self):
"""
Set the base constraints on the relation query.
:rtype: None
"""
parent_table = self._parent.get_table()
self._set_join()
if self._constraints:
self._que... |
"""
WSGI config for first | _app 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.7/howto/deployment/wsgi/
"""
import | os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "first_app.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
# Rekall Memory Forensics
#
# Copyright 2014 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 as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
""... |
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hp.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use th | is 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, W | ITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pecan
from designate.central import rpcapi as central_rpcapi
from designate.openstack.common import log as logging
from designate.api.v... |
import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_na... | payment_info = None
template = get_template('pretixplugins/banktransfer/control.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settings,
'payment_info': payment_info, ' | order': order}
return template.render(ctx)
|
# This file is part of ICLS.
#
# ICLS 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
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will ... | ('cyan',strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000")),1)
output+=colorize('gray','ID: '+entry.name,0)
else:
output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H: | %M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = ... |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.generic.edit import FormView
from .forms import SignUpForm, ExamSignUpForm
from .models import Notification
from .utils import send_email, send_sms
class ExamSignUpView(FormView):
kind =... | sword=password) |
sms_error = False
sms_code = request.GET.get('sms_code')
if sms_code:
if sms_code == notification.sms_code:
notification.sms_verified = True
notification.save()
else:
sms_error = True
mail_error = False
mail_code = request.GET.get('mail_code')
... |
import logging
import os
from collections import namedtuple
from zope.interface import Interface
from bowerstatic import (
Bower,
InjectorTween,
PublisherTween,
)
from pyramid.interfaces import IApplicationCreated
from pyramid.path import AssetResolver
from pyramid.exceptions import ConfigurationError
lo... | y)
registry.registerUtility(info, IBowerComponents, name=name)
config.action(discr, register)
def add_bower_component(config, path, components_name=None):
"""
"""
registry = config.registry
resolver = AssetResolver()
directory = resolver.resolve(path).abspath()
if not os.path.isf... | .format(directory)
)
bower = get_bower(registry)
if components_name is None:
components_name = bower.components_name
discr = ('djed:static', directory, components_name)
def register():
info = BowerComponentInfo(directory, components_name)
registry.registerUtility(info... |
#-*- coding: utf-8 -*-
import unittest
import ModelADDAC as adda
import api_convertors.type_conv as tc
''' Просто заглушка '''
def printRpt( value, valueDisplacemented, valueScaled, valueCode, Kda ):
#print '\nvalueDisplacemented : '+str(valueDisplacemented)
pass
''' Класс тестов '''
class TestCaseModelADDAC(unitt... | _valueDict, printRpt, adda.calcZeroDisplacmentX )
# Проверка кода числ
self.assertEqual( tc.byte4strhex( code ), '0x00E5' )
''' Проверка расчета по току, без смещения '''
def testCurrADCZeroXZ0( self ):
# Constants and coeff.
R1 = 5.11
R2 = 10.0
Splitter = R2/(R1+R2)
Vmax = 5000.0 #mV
capacity = ... | iu = 188.0 # mV/A
dI = 0.0 # A
I = 10 # A
# проверяем
self._valueDict[ 'value' ] = I
self._valueDict['displacement'] = dI
self._valueDict['converter' ] = Kiu
self._valueDict['scale'] = Splitter
self._valueDict['capacity'] = capacity
self._valueDict['Vmax'] = Vmax
code, Kda = adda.modelADC( s... |
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache Lic | ense, 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 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 gover... |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants
from numpy imp... | bansim_constant':{
'cell_size': array([150]),
'near_arterial_threshold': array([100]),
'units': array(['meters']),
}
}
)
should_be = array( [True, True, True, False, False, False] )
tester.t... | qual_for_variable_defined_by_this_module(self, should_be)
if __name__=='__main__':
opus_unittest.main() |
.algorithms.lasso import instance
from selection.algorithms.forward_step import forward_stepwise, info_crit_stop, sequential, data_carving_IC
def test_FS(k=10):
n, p = 100, 200
X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None]
X /= (X.std(0)[None,:] * np.sqrt(n))
Y... | dard_normal(n)[:,None]
X /= (X.std(0)[None,:] * np.sqrt(n))
Y = np.random.standard_normal(100) * 0.5
FS = forward_stepwise(X, Y)
for i in range(k):
FS.next | ()
print 'first %s variables selected' % k, FS.variables
print 'pivots for last variable of 3rd selected model knowing that we performed %d steps of forward stepwise' % k
print FS.model_pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=5000, ndraw=5000)
def test_subset(k=10):
n, p = 10... |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2012 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.xmlstream import ElementBase, ET
clas | s UserGaming(Ele | mentBase):
name = 'gaming'
namespace = 'urn:xmpp:gaming:0'
plugin_attrib = 'gaming'
interfaces = set(['character_name', 'character_profile', 'name',
'level', 'server_address', 'server_name', 'uri'])
sub_interfaces = interfaces
|
'''
A segment which is a literal string
A FakeLargeFile composed entirely of LiteralSegments is not fake, but may
still be more useful than a plain old file.
'''
COPYING = """\
Copyright 2014 Lauritz Vesteraas Thaulow
This file is part of the FakeLargeFile python package.
FakeLargeFile is free software:... | :param str string: The string this segment should contain.
"""
start = parse_unit(start)
super(LiteralSegment, self).__init__(start, start + len(string))
self.string = string
def subsegment(self, start, stop):
sl = Slice(start, stop, self.start, self.stop)
i... | cal_slice])
else:
return None
@classmethod
def example(cls, start, stop):
basis = pkg_resources.resource_stream(
"fakelargefile", "GPLv3.txt").read()
start = parse_unit(start)
stop = parse_unit(stop)
size = stop - start
basis = basis * (si... |
"""
Project: | flask-rest
Author: Saj Arora
Description: All of the r | est methods...
"""
class SageMethod:
GET = 'get'
POST = 'post'
DELETE = 'delete'
PUT = 'put'
ALL = [GET, POST, DELETE, PUT] |
# | !/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "Replica set status" | )
|
fr | om vertex.filters import IdListFilterSe | t
from ..models import Note
class NoteFilterSet(IdListFilterSet):
class Meta:
model = Note
|
import threading
import solr
from django.conf import settings
class SolrConne | ction(threading.local):
_connection = None
def __init__(self, core):
threading.local.__init__(co | re)
self.core = core
@property
def connection(self):
if self._connection:
return self._connection
else:
return solr.Solr(settings.SOLR_HOST + '/' + self.core)
valid_core_names = ['comment', 'group']
local = {}
def get_local(core):
assert core in valid_c... |
YSTEM.sys_set_bootdev_no_override()
cls.cv_SYSTEM.goto_state(OpSystemState.OS)
cls.c = cls.cv_SYSTEM.host().get_ssh_connection()
else:
cls.cv_SYSTEM.sys_set_bootdev_setup()
cls.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)
... | s unified diff of two lists
'''
unified_output = difflib.unified_diff(
[_f for _f in listA if _f],
[_f for _f in listB if _f],
fromfile=listA_name,
tofile=listB_name,
lineterm="")
unified_list = list(unified_output)
log.debug("u... | ified_list={}".format(unified_list))
return unified_list
def compare_boot_devices(self):
'''
This is best leveraged in the suite pci-regression,
where both the skiroot/host softboot and the
skiroot/host hardboot get done in the same wave,
so that the global variables... |
# -*- coding: utf-8 -*-
###############################################################################
#
# GetExerciseFollowUp
# Retrieves user data about all excercises which have the specified excercise as a prerequisite.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apach... | e for which you want to retrieve follwow up exercises (e.g. "simplifying_fractions").)
"""
super(GetExerciseFollowUpInputSet, self)._set_input('ExerciseName', value)
def set_OAuthTokenSecret(self, value):
"""
Set the value of the OAuthTokenSecret input for this Choreo. ((required, st... | iseFollowUpInputSet, self)._set_input('OAuthTokenSecret', value)
def set_OAuthToken(self, value):
"""
Set the value of the OAuthToken input for this Choreo. ((required, string) The OAuth Token retrieved during the OAuth process.)
"""
super(GetExerciseFollowUpInputSet, self)._set_inpu... |
# RANDOM PASSWORD GENERATOR
# Author: Dan Barrese (danbarrese.com)
# Version: 1.01
# Description: Yep. This is my first Python script.
# Skills exemplified in this script:
# * Random nu | mber generation
# * Command line interface
# * List comprehension
# * Loops
#
# Update History:
# 2013.12.25 [DRB][1.0] Initial implementation.
# 2013.12.29 [DRB][1.01] Defaulted to 10 passwords and length of 5.
import random
import string
import sys
import argparse
# Parse arguments.
parser = argparse.ArgumentP... | etavar='L', type=int, nargs=1,
dest='length', default=[5],
help='the number (L) of characters in the generated password')
parser.add_argument('--count', '-c', metavar='C', type=int, nargs=1,
dest='count', default=[10],
help='the number (C) ... |
#!/usr/bin/env python
import io
import os
import sys
try:
from setuptools import setup, Command, find_packages
except ImportError:
from distutils.core import setup, Command, find_packages
__version__ = "1.4.3"
with io.open('README.rst', encoding='utf-8') as readme_file:
long_description = readme_file.r... | Python :: Implementation :: PyPy',
'Programming Language :: Python',
'Topic :: Se | curity :: Cryptography',
],
)
|
ut prepare for fireing in rapidfire
for task in self.flow.unconverged_tasks:
try:
logger.info("Flow will try restart task %s" % task)
fired = task.restart()
if fired:
self.nlaunch += 1
max_nlaunch -= 1
... | ancel()
cprint("Killed %d tasks" % num_cancelled, "yellow")
except Exception as exc:
cprint("Exception while trying to kill jobs:\n%s" % str(exc), | "red")
self.shutdown("\n".join(err_lines))
return len(self.exceptions)
def cleanup(self):
"""Cleanup routine: remove the pid file and save the pickle database"""
try:
os.remove(self.pid_file)
except OSError as exc:
logger.critical("Could not re... |
#!/usr/bin/env python
#
#===- check_clang_tidy.py - ClangTidy Test Helper ------------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===--------------------------------------... | ---------------\n' +
diff_output.decode() +
'\n------------------------------------------------------------------')
if has_check_fixes:
try:
subprocess.check_output(
['FileCheck', '-input-file=' + temp_file_name, input_file_name,
'-check-prefix=' + check_fixes_prefix, '... | ss.CalledProcessError as e:
print('FileCheck failed:\n' + e.output.decode())
raise
if has_check_messages:
messages_file = temp_file_name + '.msg'
write_file(messages_file, clang_tidy_output)
try:
subprocess.check_output(
['FileCheck', '-input-file=' + messages_file, input_file... |
ort tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buffer_to_jpeg,
parse_buffer_to_png
)
from .exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
TRANSPARENT_FILE_TYPES = ['png',... | if output_file in f:
| images.append(Image.open(os.path.join(output_folder, f)))
if in_ |
#!/usr/bin/python3
import struct
import sys
if len(sys.argv) == 1:
print("python karel_mdo_convert.py mundo.mdo")
sys.exit(1)
f = open(sys.argv[1], "rb")
data = f.read()
f.close()
worldname = sys.argv[1]
if '/' in worldname:
worldname = worldname[wo | rldname.rfind('/')+1:]
if '.' in worldname:
worldname = worldname[:worldname.rfind('.')]
kec = False
for extension in ("kec", "KEC"):
try:
f = open(sys.argv[1][:sys.argv[1].rfind(".")] + "." + extension, "rb")
kec = f.read()
f.close()
break
except Exception:
pass
if not kec:
print("%s.kec not found" % w... | th, height, buzzers, karelx, karely, karelorient, wallcount, heapcount, x10) = struct.unpack("HHHHHHHHHH", data[10:30])
tuples = [struct.unpack("HHH", data[i:i+6]) for i in range(30, len(data), 6)]
kec = [struct.unpack("HHH", kec[i:i+6]) for i in range(0, len(kec), 6)]
maxlines = kec[0][1] if kec[0][0] else 10000000
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Ole André Vadla Ravnås <oleavr@gmail.com>
# Copyright (C) 2006-2007 Ali Sabil <ali.sabil@gmail.com>
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Gene... | lin St, Fifth Floor, Boston, MA 02110-1301 USA
#
from papyon.gnet.constants import *
from papyon.gnet.proxy.proxyfiable import ProxyfiableClient
from sock import SocketClient
import gobject
__all__ = ['TCPClient']
class TCPClient(SocketClient, ProxyfiableClient):
"""Asynchronous TCP client class.
@sor... | init__, open, send, close
@undocumented: do_*, _watch_*, __io_*, _connect_done_handler
@since: 0.1"""
def __init__(self, host, port):
"""initializer
@param host: the hostname to connect to.
@type host: string
@param port: the port number to connect to.... |
import sys
import unittest
i | mport restserver
import json
from flask import jsonify
class RestServerTest(un | ittest.TestCase):
def setUp(self):
self.app = restserver.create_app(static=True).test_client()
def tearDown(self):
pass
def test_struct_graph(self):
rv = self.app.post('/struct_graph')
# not posting any data should be a 'Bad Request'
# ideally, with an error messag... |
.
#
# 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 th... | l | og.error("Twisted is not available")
sys.exit(1)
options.supported_reactors = [TwistedConnection]
else:
options.supported_reactors = supported_reactors
if not have_libev:
log.warning("Not benchmarking libev reactor because libev is not available")
return options,... |
"""CloseSpider is an extension that forces spiders to be closed after certain
conditions are met.
See documentation in docs/topics/extensions.rst
"""
from collections import defaultdict
from twisted.internet import reactor
from scrapy import signals
from scrapy.exceptions import NotConfigured
class CloseSpider(ob... | losed)
@classmethod
def from_crawler(cls, crawler):
return cls(crawler)
def error_count(self, failure, response, spider):
self.counter['errorcount'] += 1
if self.counter['errorcount'] == self.close_on['errorcount']:
self | .crawler.engine.close_spider(spider, 'closespider_errorcount')
def page_count(self, response, request, spider):
self.counter['pagecount'] += 1
if self.counter['pagecount'] == self.close_on['pagecount']:
self.crawler.engine.close_spider(spider, 'closespider_pagecount')
def spider_op... |
from __future__ import absolute_import, division, print_function, with_statement
import pytest
import sys
from tornado import concurrent
import tornado.gen
import tornado.testing
import rw.scope
# def test_low_level_api():
# scope = rw.scope.Scope()
# current_user = object()
#
# def get_current_user():... | hared') == 1
assert 'value_2' not in rw.scope.get('my_sub_scope')
def checks_inside_scope2():
assert rw.scope.get('my_sub_scope') == get_sub_scope()
| assert rw.scope.get('my_sub_scope')['value_1'] == 1
assert get_sub_scope_var('value_1') == 1
assert rw.scope.get('my_sub_scope')['value_2'] == 2
assert get_sub_scope_var('value_2') == 2
assert rw.scope.get('my_sub_scope')['shared'] == 2
assert get_sub_scope_var('shared') ==... |
#!/usr/bin/python
# encoding: utf-8
# Jan 2011 (markus kossner) Cleaned up the code, added some documentation
# somwhere around Aug 2008 (markus kossner) created
#
# This script extracts the molecular framework for a database of molecules.
# You can use two modes (hard coded):
# - Scaff: The molecular fr... | rence
#
from __future__ import print_function
import os,sys
from Chem import AllChem as Chem
def flatten(x):
"""flatten(sequence) -> list
Re | turns a single, flat list which contains all elements retrieved
from the sequence and all nested sub-sequences (iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
... |
elf.type.endswith("Array"):
string += "\tnAttr.setArray(true);\n"
string += "\tnAttr.setDefault({0});\n".format(",".join(self.default.split(":")))
string += "\tCHECK_MSTATUS(addAttribute( {0} ));\n\n".format(self.name)
return string
class ShaderNode(object):
def __init__(self, n... | rogress = False
newContent.ap | pend(line)
fh = open(destAEPath, "w")
fh.writelines(newContent)
fh.close()
def printPluginLoadInfo(self):
for node in self.nodesToCreate:
includeString = '#include "textures/{0}.h"'.format(node.name)
p... |
import glob
import os
import shutil
import sys
import tarfile
import traceback
from model import Model
from subprocess import Popen, PIPE
class Apsim75(Model):
def run(self, latidx, lonidx):
try:
apsim_bin = self.config.get('executable')
# The apsim 'executable' is a gzipped tarba... | .isfile(old_xml):
os.remove(old_xml)
if os.path.islink(xml_file):
link = os.readlink(xml_file)
shutil.copy(link, model_dir)
else:
shutil.copy(xml_file, model_dir)
# Create si... | sim', shell=True, executable='/bin/bash', stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
stdout_file = open('RESULT.OUT', 'w')
stdout_file.write(stdout)
if p.returncode != 0:
rc = p.returncode
# Run apsim for each sim file
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from aldryn_client import forms
class Form(forms.BaseForm) | :
plugin_module = forms.CharField('Plugin module name', initial='Generic')
plugin_name = forms.CharField('Plugin name', initial='Facebook Comments')
plugin_template = forms.CharField('Plugin Template', initial='djangocms_fbcomments/default.html')
app_id = forms.CharField('Facebook App ID', required=Fals... | settings['DJANGOCMS_FBCOMMENTS_PLUGIN_NAME'] = data['plugin_name']
settings['DJANGOCMS_FBCOMMENTS_PLUGIN_TEMPLATE'] = data['plugin_template']
settings['DJANGOCMS_FBCOMMENTS_APP_ID'] = data['app_id']
return settings
|
ss'
CONF_OPERATION_MODE_STATE_ADDRESS = 'operation_mode_state_address'
CONF_CONTROLLER_STATUS_ADDRESS = 'controller_status_address'
CONF_CONTROLLER_STATUS_STATE_ADDRESS = 'controller_status_state_address'
CONF_CONTROLLER_MODE_ADDRESS = 'controller_mode_address'
CONF_CONTROLLER_MODE_STATE_ADDRESS = 'controller_mode_stat... | n discovery_info[ATTR_DISCOVER_DEVICES]:
device = hass.data[DATA_KNX].xknx.devices[device_name]
entities.append(KNXClimate(device))
async_add_entities(entities)
@callback
def async_add_entities_config(hass, config, async_add_entities):
"""Set up climate for KNX platform configured | within platform."""
import xknx
climate_mode = xknx.devices.ClimateMode(
hass.data[DATA_KNX].xknx,
name=config.get(CONF_NAME) + " Mode",
group_address_operation_mode=config.get(CONF_OPERATION_MODE_ADDRESS),
group_address_operation_mode_state=config.get(
CONF_OPERATI... |
of type
:class:`~kivy.uix.button.Button`.
.. versionchanged:: 1.8.0
If you set a string, the :class:`~kivy.factory.Factory` will be used to
resolve the class.
'''
sizable_from = OptionProperty('left', options=(
'left', 'right', 'top', 'bottom'))
'''Specifies whether the w... | _widget(widget)
if widget == self._container:
self._container = None
def clear_widgets(self):
self.remove_widget(self._container)
def strip_down(self, instance, touch):
if not instance.collid | e_point(*touch.pos):
return False
touch.grab(self)
self.dispatch('on_press')
def on_press(self):
pass
def _rebind_parent(self, instance, new_parent):
if self._bound_parent is not None:
self._bound_parent.unbind(size=self.rescale_parent_proportion)
... |
p/local-downcast-namespaces-{0}.i"\n'.format(name))
fileOut.write(' "bindings/csharp/local-packages-{0}.i"\n\n'.format(name))
fileOut.write(' # java bindings\n')
fileOut.write(' "bindings/java/local-downcast-extension-{0}.i"\n'.format(name))
fileOut.write(' "bindings/java/local-downcast-namespaces-{0}.i"\n'.for... | rary(LIBSBML_LIBS \n')
fileOut.write(' NAMES libsbml.lib sbml\n')
fileOut.write(' PATHS ${LIBSBML_SOURCE} \n')
fileOut.write(' ${LIBSBML_SOURCE/lib}\n')
fileOut.write(' ${LIBSBML_SOURCE/src/.libs}\n')
fileOut.write(' /usr/lib /usr/local/lib \n')
fileOut.write(' ${LIBSBML_ROOT_SOURCE_DIR}... | rite(' )\n\n')
fileOut.write(' make_directory(${CMAKE_CURRENT_BINARY_DIR}/include/sbml/')
fileOut.write('{0})\n\n'.format(name))
fileOut.write(' # copy header files to facilitate build\n')
fileOut.write(' foreach(dir common extension sbml validator validator/constraints)\n\n')
fileOut.write(' # ... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import inspect
from datetime import datetime
import freezegun
import pytest
from sqlalchemy import DateTi... | keypatch.setattr('{}.{}'.format(target, name), method)
return _monkeypatch_methods
@pytest.fixture
def freeze_time(monkeypatch):
"""Returns a function that freezes the current time
It affects datetime.now, date.today, etc. and also SQLAlchemy's `func.now()`
which simply returns the current time from... | erator_call(self, *args, **kwargs):
if self._FunctionGenerator__names == ['now']:
return cast(datetime.now().isoformat(), DateTime)
return orig_call(self, *args, **kwargs)
monkeypatch.setattr(_FunctionGenerator, '__call__', FunctionGenerator_call)
def _freeze_time(time_to_freeze):
... |
from tests.subscriptions import Subscription_tests
from tests.messaging import Event_publisher_tests
from tests.callbacks import Callback_tests
from tests.shortcut_subscriptions import Decorator_tests
import unittest
import logging
def configure_logger():
hand | ler = logging.FileHandler('log.txt')
formatter = logging.Formatter("%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s")
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(handler)
if __name_ | _ == '__main__':
configure_logger()
unittest.main()
|
# | !/usr/bin/env python3
import sys
import text_parsers as tp
import os
infilenames = sys.argv[1:len(sys.argv)-1]
nameprefix = sys.argv[len(sys.argv)-1]
for infilename in infilenames:
outfilename = f'{os.environ["HOME"]}/{os.path.basename(infilename)}.h5'
data = tp.parse_txt_xy(infilename)
data['metadata']['na | me'] = f'{nameprefix}: {os.path.basename(infilename)}'
tp.save_sample_file(outfilename, data['data'], data['metadata'])
sys.exit(0)
|
name, join
sys.path.insert(0, join(dirname(dirname(dirname(abspath(__file__)))), 'py-bindings'))
from functools import partial
from time import clock
from math import fabs
import unittest
import copy
import ompl.util as ou
import ompl.base as ob
import ompl.control as oc
from ompl.util import setLogLevel, LogLevel
SOL... | le()
cdim.extend([1, 1])
| ope = MyProjectionEvaluator(si.getStateSpace(), cdim)
planner.setProjectionEvaluator(ope)
return planner
class PlanTest(unittest.TestCase):
def setUp(self):
self.env = Environment(dirname(abspath(__file__))+'/../../tests/resources/env1.txt')
if self.env.width * self.env.height =... |
# Copyright 2013 Mirantis, 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, s... | 'Table creation failed', 'create table', create_table)
LOG.info('create table')
self.verify(20, master_ssh_client.exec_command, 4,
'Can not insert data in created table', 'data insertion',
create_record)
LOG.info('create data')
# Verify that dat... | |
import logging
class BaseDebugInterface(object):
def __init__(self, debuger):
self.robotDebuger = debuger
self.debugCtx = debuger.debugCtx
self.logger = logging.getLogger("rbt.int")
self.bp_id = 0
def start(self, settings):
"""start debug interface."""
... | return e
elif not match_kw and e.name == name:
return e
return None
def add_telnet_monitor(self, monitor):
"""this is IPAMml special feature."""
self.robotDebuger.add_telnet_monitor(monitor)
def add_debug_listener(self, l) | :
self.debugCtx.add_listener(l)
def remove_debug_listener(self, l):
self.debugCtx.remove_listener(l)
class Listener:
def __init__(self):
pass
def pause(self, breakpoint):
pass
def go_on(self):
pass
def start_keyword(self, keyword):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-25 11:53
fro | m __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consent', '0013_auto_20170217_1606'),
]
operations = [
migrations.AlterField(
model_ | name='educationdetail',
name='college_passout_year',
field=models.CharField(default=2017, max_length=4),
preserve_default=False,
),
]
|
for parsers in self.parsers:
log.debug(parsers)
heading_parser = parsers[0]
value_parser = parsers[1] if len(parsers) > 1 else None
disallowed_parser = parsers[2] if len(parsers) > 2 else None
allowed = False
disallowe... | e.id in cell.references))
# if footnote.id in cell.references:
# log.debug('Adding footnote %s to column %s: %s' % (footnote.id, i, [c.to_primitive() for c in footnote.records]))
# # print('Footnote records: %s' % [c.to_primitive() for c in footnote.re... | nd(footnote.records)
# If no parsers, skip processing table
if value_parsers:
# If no CompoundCellParser() in value_parsers and value_parsers[0] == [] then set CompoundCellParser()
if not seen_compound_col and 0 not in value_parsers:
log.debug('No compound colum... |
from | bongo.apps.bongo import models
from rest_framework import serializers
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = models.Even | t
fields = ('id', )
|
from __future__ import print_function
import numpy as np
import datetime
import csv
import pickle
import sys
species_map = {'CULEX RESTUANS' : "100000",
'CULEX TERRITANS' : "010000",
'CULEX PIPIENS' : "001000",
'CULEX PIPIENS/RESTUANS' : "101000",
'CULEX ER... |
for repeat in range(scaled_count(b)):
X.append(case)
X = np.asarray(X, dtype=np.float32)
return X
class AdjustVariable(object):
def __init__(self, variable, target, half_life=20):
self.variable = variable
self.target = target
self.half_life = half_life
d... | t_value() - self.target
delta /= 2**(1.0/self.half_life)
self.variable.set_value(np.float32(self.target + delta))
def submit(net, mean, std, testfile, weatherfile):
weather = load_weather(weatherfile)
testing = load_testing(testfile)
X = assemble_X(testing, weather)
normalize(X, mean, ... |
# -*- coding: utf-8 -*-
"""Startup utilities"""
# pylint:skip-file
import os
import sys
from functools import partial
import paste.script.command
import werkzeug.script
etc = partial(os.path.join, 'parts', 'etc')
DEPLOY_INI = etc('deploy.ini')
DEPLOY_CFG = etc('deploy.cfg')
DEBUG_INI = etc('debug.ini')
DEBUG_CFG =... | _serve('status', dry_run=dry_run)
# bin/flask-ctl stop
def action_stop(dry_run=False):
"""
Stop the application.
"""
_serve('stop', dry_run=dry_run)
werkzeug.script.run()
def download_xml():
"""
Download xml files from stx website.
"""
import urllib
... | urllib.urlretrieve(url, 'runtime/data/users.xml')
|
" --log-error='%s'" %
(init_file.name, err_log_file.name)
)
try:
i = child.expect(['Starting mysqld daemon'])
if i == 0:
LOG.info(_("Starting MySQL"))
except pexpect.TIMEOUT:
... | root_helper="sudo",
run_as_root=True)
self.poll_until_then_raise(
self.mysql_is_not_running,
base.RestoreError("Reset root password failed: "
| "mysqld did not stop!"))
def reset_root_password(self):
with tempfile.NamedTemporaryFile() as init_file:
utils.execute_with_timeout("sudo", "chmod", "a+r", init_file.name)
self._writelines_one_per_line(init_file,
self.RESET_ROOT_MYS... |
date = dateutil.parser.parse('2015-08-01')
trimester = main.get_trimester(date)
session = models.Session()
session.completed_time = date
session.model_based = self.model_session1
list_percentiles = []
for i in range(0, 10):
list_percentiles.append(mod... | main.get_average_data(None, [], [])
self.assertIsNone(p)
self.assertIsNone(m)
def test_with_data(self):
self.tmp = 0
def mock_get_percentile(older, session):
self.tmp += 1
return self.tmp
main.get_percentile = mock_get_percentile
ms1 = mod... | erate_model_session(3)
sessions = [
models_tests.generate_session(model=ms1),
models_tests.generate_session(model=ms1),
models_tests.generate_session(model=ms1)
]
p, m = main.get_average_data(None, sessions, [ms2, ms3])
self.assertIsNone(p)
s... |
# -*- encoding: utf-8 -*-
###################################################### | ########################
#
# OpenERP, Open | Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# ThinkOpen Solutions Brasil
# Copyright (C) Thinkopen Solutions <http://www.tkobr.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lic... |
ignKey')(related_name='likes', to=orm['spa.Mix'])),
))
db.send_create_signal('spa', ['ActivityLike'])
def backwards(self, orm):
# Deleting model 'ActivityLike'
db.delete_table(u'spa_activitylike')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'... |
},
'spa.chatmessage': {
'Meta': {'object_name': 'ChatMessage'},
| u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.Fo... |
from datetime import datetime
import fixtures
import constants
from authomatic.providers import oauth2
conf = fixtures.get_configuration('yammer')
LINK = 'https://www.yammer.com/peterhudec.com/users/{0}'\
.format(conf.user_username)
# Yammer allows users to only set month and day of their birth day.
# The year ... | ser_phone,
'picture': conf.user_picture,
'postal_code': None,
'timezone': conf.user_timezone,
'username': conf.user_username,
},
'content_should_contain': [
conf.user_city,
conf.user_country,
conf.user_email,
conf.user_first_name,
conf.user... | conf.user_timezone.replace('&', '\\u0026'),
conf.user_username,
# User info JSON keys
'type', 'id', 'network_id', 'state', 'guid', 'job_title', 'location',
'significant_other', 'kids_names', 'interests', 'summary', 'expertise',
'full_name', 'activated_at', 'show_ask_for_ph... |
from __future__ import absolute_import
input_name = '../examples/dg/advection_2D.py'
output_name = 'advec | tion_sol.msh'
from tests_basic import TestInput
class Test( TestInput ) | :
pass |
#!/usr/bin/python2.7
from app import app
if __name__ == '__main__':
a | pp.run(debug=True)
| |
import os
D | EBUG = False
try:
from local_se | ttings import * # noqa
except ImportError:
pass
|
ve copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CON | SEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Settings/Master/EquippedBadgeSettings.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from go... | _probability_bonus', index=2,
number=3, type=2, cpp_type=6, label=3,
has_default_value=Fal | se, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
ser... |
"""
Different implementations of the ``./setup.py test`` command depending on
what's locally available.
If Astropy v1.1 or later is available it should be possible to import
AstropyTest from ``astropy.tests.command``. Otherwise there is a skeleton
impleme | ntation that allows users to at least discover the ``./setup.py test``
command and learn that they need Astropy to run it.
"""
import os
from ..utils import import_file
# Previously these except statements caught only ImportErrors, but there | are
# some other obscure exceptional conditions that can occur when importing
# astropy.tests (at least on older versions) that can cause these imports to
# fail
try:
# If we are testing astropy itself, we need to use import_file to avoid
# actually importing astropy (just the file we need).
command_file ... |
from .analyzer import Pep8Analyzer
from .issues_data import issues_data
analyzers = {
'pep8' :
| {
'title' : 'Pep-8',
'class' : Pep8Analyzer,
| 'language' : 'python',
'issues_data' : issues_data,
},
}
|
#!env/bin/python
"""Migrate the database"""
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
migration = SQLALCHEMY_MIGRATE_REPO + | ('/versions/%03d_migration.py' % (v+1))
tmp_module = imp.new_module('old_model')
old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
exec(old_model, tmp_module.__dict__)
script = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI,
SQLALCHEMY_MIG... | tmp_module.meta, db.metadata)
open(migration, "wt").write(script)
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('New migration saved as ' + migration)
print('Current database version: ' + str(v... |
# Copyright FuseSoC contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
def test_generators():
import os
import tempfile
from fusesoc.config import Config
from fusesoc.coremanager import CoreManager
from fusesoc.edalizer import ... | esoc.librarymanager import Library
from fusesoc.vlnv import Vlnv
tests_ | dir = os.path.dirname(__file__)
cores_dir = os.path.join(tests_dir, "capi2_cores", "misc", "generate")
lib = Library("edalizer", cores_dir)
cm = CoreManager(Config())
cm.add_library(lib)
core = cm.get_core(Vlnv("::generate"))
build_root = tempfile.mkdtemp(prefix="export_")
cache_root = t... |
from ConfigParser import SafeConfigParser
import requests
class Client(object):
def __init__(self, configFileName):
self.config = SafeConfigParser()
self.config.read(configFileName)
def send(self, recepient, message):
if message.platform == "facebook":
return self.sendFacebookMessage(recep | ient, | message)
else:
raise Exception('Unknown Message\' Platform')
def sendFacebookMessage(self,recepient, message):
token = self.config.get('onechat','FACEBOOK_MESSENGER_TOKEN')
sendUrl = "https://graph.facebook.com/v2.6/me/messages?access_token=" + token
try:
response = requests.post(sendUrl, json=messa... |
# Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# 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
# (at your ... | file(request):
if request.method == "POST":
form = EditProfileForm(request.POST)
if form.is_valid():
if not request.user.check_password(form.cleaned_data['password']):
form._ | errors['password'] = ErrorList([u'The password you entered is incorrect.'])
else:
request.user.email = form.cleaned_data['email']
if form.cleaned_data['password1']:
request.user.set_password(form.cleaned_data['password1'])
request.user... |
#!/usr/bin/python
###########################################################################
# (C) Vrije Universiteit, Amsterdam (the Netherlands) #
# #
# This file is part of AmCAT - The Amsterdam Content Analysis Toolkit ... | ############################################
import loggi | ng; log = logging.getLogger(__name__)
import collections
import itertools
import pprint
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
from amcat.scripts.script import Script
from amcat.models import ArticleSet
try:
import Levenshtein
except ImportEr... |
'''
Test change cpu and memory configuration when VM is running
@author: quarkonics
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
#import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpe... | .cpuNum != instance_offering.cpuNum * 2):
test_util.test_fail("cpuNum is expected to change")
if (vm.get_vm().memorySize != instance_offering.memorySize * 2):
test_util.test_fail("memorySize is expected to change")
vm.stop()
vm.update()
if (vm.get_vm().cpuNum != instance_offering... | ed to change")
if (vm.get_vm().memorySize != instance_offering.memorySize * 2):
test_util.test_fail("memorySize is expected to change")
vm.start()
if (vm.get_vm().cpuNum != instance_offering.cpuNum * 2):
test_util.test_fail("cpuNum change is expected to take effect after Vm restart")
... |
import _plotly_utils.basevalidators
class XValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="x | ", parent_name="streamtube.starts", **kwargs):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("ed | it_type", "calc"),
**kwargs
)
|
0)
self.assertEqual(out, 'foo bar')
(rc, out, err) = self.module.run_command("/bin/echo -n 'foo bar'", use_unsafe_shell=True)
self.assertEqual(rc, 0)
self.assertEqual(out, 'foo bar')
# test run_command with an array of args (with both use_unsafe_shell=True|False)
def test_run_c... | tial cornercases that we need to check. Go ahead and test at
this level that the functions are behaving even though their API may
change and we'd have to rewrite these tests so that we know that we
need to check for those problems in any rewrite.
In the future we might want to restructure higher level... | unittests so that we can test at the level that the public
is interacting with the APIs.
'''
MANY_RECORDS = 7000
URL_SECRET = 'http://username:pas:word@foo.com/data'
SSH_SECRET = 'username:pas:word@foo.com/data'
def cleanup_temp_file(self, fd, path):
try:
os.close(fd)
... |
from urllib.parse import urlparse
from urllib.request import url2pathname
from django.conf import settings
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.views import serve
from django.http import Http404
from .http import AsgiHandler
class StaticFilesWrapper:
"""
ASGI applicat... | path), insecure=True)
def get_response(se | lf, request):
"""
Always tries to serve a static file as you don't even get into this
handler subclass without the wrapper directing you here.
"""
try:
return self.serve(request)
except Http404 as e:
if settings.DEBUG:
from django.v... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from astrobin.models import SolarSystem_Acquisition
class SolarSystem_AcquisitionForm(forms.ModelForm):
error_css_class = 'error'
date = forms.DateField(
required=False,
input_formats=['%Y-%m-%d'],
widge... | ror(_("Please enter a value between 1 and 5."))
return data
def clean_transparency(self):
data = | self.cleaned_data['transparency']
if data and data not in list(range(1, 11)):
raise forms.ValidationError(_("Please enter a value between 1 and 10."))
return data
class Meta:
model = SolarSystem_Acquisition
fields = (
'date',
'time',
... |
# Generated by Django 2.0.3 on 2018-12-21 15:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependenci | es = [
('marketing', '0005_auto_20180123_1157'),
]
operations = [
migrations.AlterField(
model_name='uploadedcell',
name='content',
field=models.TextField(blank=True, default=''),
),
migrations.AlterField(
model_name='uploadedrow',... | Field(blank=True, default='', max_length=255),
),
]
|
"""
escape/unescape routines available for backends which need
alphanumeric usernames, services, or other values
"""
import re
import string
import sys
# True if we are running on Python 3.
# taken from six.py
PY3 = sys.version_info[0] == 3
# allow use of unicode literals
if PY3:
def u(s):
return s
d... |
or getattr(string, 'ascii_letters') # Python 3
) + string.digits
ESCAPE_FMT = "_%02X"
def _escape_char(c):
"Single char escape. Return the char, escaped if not already legal"
if isinstance(c, int):
c = _unichr(c)
return c if c in LEGAL_CHARS else ESCAPE_FMT % ord(c)
def escape(value):
"... | ring so the result consists of alphanumeric chars and
underscore only.
"""
return "".join(_escape_char(c) for c in value.encode('utf-8'))
def _unescape_code(regex_match):
ordinal = int(regex_match.group('code'), 16)
if sys.version_info >= (3,):
return bytes([ordinal])
return chr(ordinal... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2011 Openstack, LLC.
# 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... | t_chars)]
return salt
def _create_temp_password_file(user, password, filename):
"""Read original passwd file, generating a new temporary file.
Returns: The temporary filename
"""
with open(filename) as f:
file_data = f.readlines()
stat_info = os.stat(filename)
tmpfile = '%s.tmp.% | d' % (filename, os.getpid())
# We have to use os.open() so that we can create the file with
# the appropriate modes. If we create it and set modes later,
# there's a small point of time where a non-root user could
# potentially open the file and wait for data to be written.
fd = os.open(tmpfile,
... |
#!/usr/bin/env pytho | n
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
print("picture")
command = "sudo raspi | still -o " + imageName + " -q 100 -t " + camera_pause
print(command)
os.system(command)
while(True):
if(up==True):
if(GPIO.input(24)==False):
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo-"+timeString+".jpg"
takepic(filename)
subp... |
# This file starts the WSGI web application.
# - Heroku starts gunicorn, which loads Procfile, which starts manage.py
# - Developers can run it from the command line: python runserver.py
import logging
from logging.handlers import RotatingFileHandler
f | rom app import create_app
app = create_app()
# Start a development web server if executed from the command line
if __name__ == "__main__":
# Manage the command line parameters su | ch as:
# - python manage.py runserver
# - python manage.py db
from app import manager
manager.run()
|
import httplib
import functools
from modularodm.exceptions im | port NoResultsFound
from modularodm.storage.base import KeyExistsEx | ception
from framework.auth.decorators import must_be_signed
from framework.exceptions import HTTPError
from addons.osfstorage.models import OsfStorageFileNode, OsfStorageFolder
from osf.models import OSFUser, AbstractNode
from website.files import exceptions
from website.project.decorators import (
must_not_be_r... |
mails(src, user, stat_result, url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_SIZE_EXCEEDED_DESK,
user=user,
src=src,
stat_result=stat_result,
can_change_preferences=False,
url=url,
)
mails.send_mail(
to_addr=user.... | ation_tree(save=True)
def archive_provider_for(node, user):
"""A generic function to get the archive provider for some node, user p | air.
:param node: target node
:param user: target user (currently unused, but left in for future-proofing
the code for use with archive providers other than OSF Storage)
"""
return node.get_addon(settings.ARCHIVE_PROVIDER)
def has_archive_provider(node, user):
"""A generic function for checkin... |
from pylab import figure,show,connect,hist,plot,legend
from numpy import array, append, arange, empty, exp
from shogun import Gaussian, GMM
from shogun import RealFeatures
import util
util.set_title('EM for 1d GMM example')
#set the parameters
min_cov=1e-9
max_iter=1000
min | _change=1e-9
#setup the real GMM
real_gmm=GMM(3)
real_gmm.set_nth_mean(array([-2.0]), 0)
real_gmm.set_nth_mean(array([0.0]), 1)
real_gmm.set_nth_mea | n(array([2.0]), 2)
real_gmm.set_nth_cov(array([[0.3]]), 0)
real_gmm.set_nth_cov(array([[0.1]]), 1)
real_gmm.set_nth_cov(array([[0.2]]), 2)
real_gmm.set_coef(array([0.3, 0.5, 0.2]))
#generate training set from real GMM
generated=array([real_gmm.sample()])
for i in range(199):
generated=append(generated, array([re... |
).eps
def chanvese(I,init_mask,max_its=200,alpha=0.2,thresh=0,color='r',display=False):
I = I.astype('float')
#-- Create a signed distance map (SDF) from mask
phi = mask2phi(init_mask)
if display:
plt.ion()
showCurveAndPhi(I, phi, color)
plt.savefig('levelset_start.pd... | #set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]);
print 'iteration:', its
showCurveAndPhi(I, phi, color)
| else:
if np.mod(its,10) == 0:
print 'iteration:', its
#set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]);
#drawnow;
#-- find interior and exterior mean
upts = np.flatnonzero(phi<=0) ... |
# Copyright (C) 2015 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 u... | izer(2))
class HashTestCase(unittest.TestCase):
""" Test hashing properties. """
_RECS = [
LazyRecognizer(),
ManyRecognizer(2),
NoRecognizer(),
YesRecognizer()
]
def setUp(self):
self._recs = | [r.initializeNew() for r in self._RECS]
def testEqualNew(self):
""" Test that newly initialized recognizers hash to same value. """
for r in self._RECS:
self.assertEqual(hash(r), hash(r.initializeNew()))
|
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Bc Rx Recorded
# Generated: Sun Jun 8 13:46:34 2014
##################################################
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import ... | ##################################################
# Connections
##################################################
self.connect((self.blocks_file_source_0, 0), (self.wxgui_fftsink2_0, 0))
self.connect((self.blocks_file_source_0, 0), (self.analog_wfm_rcv_0, 0))
self.connect((sel... | return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_fftsink2_0.set_sample_rate(self.samp_rate)
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.