prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
def Setup(Settings,DefaultModel):
# set1-test_of_models_against_datasets/osm299.py
Settings["experiment_name"] = "set1_Mix_model_versus_datasets_299px"
Settings["graph_histories"] = ['together'] #['all','together',[],[1,0],[0,0,0],[]]
# 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5... | = 2
Settings["models"][n]["epochs"] = 800
Settings["models"].append(DefaultModel.copy())
n+=1
Settings["models"][n]["dataset_pointer"] = -1
Settings["models"][n]["dataset_name"] = "5556x_reslen20_299px"
Settings["models"][n]["dump_ | file_override"] = 'SegmentsData_marked_R100_4Tables.dump'
Settings["models"][n]["pixels"] = 299
Settings["models"][n]["model_type"] = 'img_osm_mix'
Settings["models"][n]["unique_id"] = 'mix_minlen20_299px'
Settings["models"][n]["top_repeat_FC_block"] = 2
Settings["models"][n]["epochs"] = 800
Se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from gui.dwidgets import DMenu
class SettingsMenu(DMenu):
"""docstring for SettingsMenu"""
def __init__(self, parent=None):
super(SettingsMenu, self).__init__(parent)
self.parent = parent
self.menuItems = [
{
'na... | },
]
},
{
'name': self.tr('Document'),
'trigger': 'Document',
'type': 'submenu',
'actions': [
| {
'name': 'Android developer guide',
'icon': u'',
'shortcut': u'',
'trigger': 'AndroidDeveloper',
"checkable": False
},
{
'name... |
import sys
import os
import os.path
from jinja2 import Template
from ConfigParser import ConfigParser
import StringIO
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: <program> <deploy_cfg_template_file> <file_with_properties>")
print("Properties from <file_with_properties> will be a... | URE", "false") + "\n"
config.readfp(StringIO.StringIO(props))
else:
raise ValueError('Neither ' + sys.argv[2] + ' file nor KBASE_ENDPOINT env-variable found')
props = dict(config.items( | "global"))
output = t.render(props)
with open(sys.argv[1] + ".orig", 'w') as f:
f.write(text)
with open(sys.argv[1], 'w') as f:
f.write(output)
|
# typeclasses, an educational implementation of Haskell-style type
# classes, in Python
#
# Copyright (C) 2010 Nicolas Trangez <eikke eikke com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Fou... | List
assert eq([1, 2, 3], [1, 2, 3])
assert ne([0, 1, 2], [1, 2, 3])
# Tuple
assert eq((1, 2, 3, ), (1, 2, 3, ))
assert ne((0, 1, 2, ), (1, 2, 3, ))
# Maybe
assert eq(Nothing, Nothing)
assert eq(Just(1), Just(1))
assert ne(Just(1), Just(2))
assert ne(Just(1), Nothing)
# Tree
assert eq(Branch(B | ranch(Leaf(0), Leaf(1)), Leaf(2)),
Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)))
assert ne(Branch(Branch(Leaf(0), Leaf(1)), Leaf(2)),
Branch(Branch(Leaf(0), Leaf(1)), Branch(Leaf(2), Leaf(3))))
|
from __future__ import absolute_import
import sys
from kombu.transport import amqplib
from kombu.connection import BrokerConnection
from kombu.tests.utils import TestCase
from kombu.tests.utils import mask_modules, Mock
class MockConnection(dict):
def __setattr__(self, key, value):
self[key] = value
... | s test_amqplib(TestCase):
def test_default_port(self):
class Transport(amqplib.Transport):
Connection = MockConnection
c = BrokerConnection(port=None, transport=Transport).connect()
self.assertEqual(c["host"],
"127.0.0.1:%s" % (Transport.default_port, ... | ockConnection
c = BrokerConnection(port=1337, transport=Transport).connect()
self.assertEqual(c["host"], "127.0.0.1:1337")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
fabfile.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
try:
f | rom config import MACHINES
except ImportError as e:
print "You should cp config.py.sample | config.py, and modify it then"
raise e
for node in MACHINES['slave']:
print node
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 - 2011, University of New Orleans
#
# 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 o... | Heatmap generator.
#
# This application could be used like this, too:
#
# python generate_rpy_heatmap.py -a ABUNDANCE_FILE -p 10 -m 1 --row-text-size=1.5 --column-text-size=1 --margin-right=20 --margin-bottom=10 --width=1000 --height=1200 -l
#
import os
import sys
import math
import numpy
import numpy.core.numeric
f... | ort importr
from optparse import OptionParser
def main(options, analyses_dir = ''):
if len(analyses_dir):
sample_color_map_file = os.path.join(analyses_dir, options.sample_color_map_file)
abundance_file = os.path.join(analyses_dir, options.abundance_file)
options.output_file = os.path.join... |
from .components_generic import System
from .ports | _library import FluidPort, MechPort, CustomPort
class Duct(System):
def __init__(self, name='n/a'):
super().__init__()
self.name = name
self.params['fl_in | '] = FluidPort()
self.outputs['fl_out'] = FluidPort()
self.set()
self.cst_loss = 0.99
def run(self):
self.fl_out.Pt = self.cst_loss*self.fl_in.Pt
self.fl_out.W = self.fl_in.W
self.fl_out.Tt = self.fl_in.Tt
class Splitter(System):
def __init__(self, name='n/a'):... |
get('params', {})
params['capacity'] = capacity
self._vol_api_submit(vol_id, method='POST', action='grow',
params=params, **kwargs)
def _snap_api_submit(self, vol_id, snap_id, **kwargs):
vol_id = urllib.parse.quote(vol_id, '')
snap_id = urllib.parse.quo... | project_id=volume['project_id'])
def create_snapshot(self, snapshot):
"""Create snapshot of existing volume.
:param snapshot: shapshot reference
"""
create_params = {
'name': self._get_dbref_name(snapshot),
}
| LOG.debug("Creating snapshot of volume %(volume_id)s", snapshot,
resource=snapshot)
return self._create_snapshot(snapshot['volume_id'],
snapshot['id'],
create_params,
user_id... |
#
# Copyright (C) 2013 UNINETT AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | eferences:
# This happens when navlet is added directly in sql and no
# preference is set
navlet.preferences = {REFRESH_INTERVAL: self.refresh_interval}
navlet.save()
context['interval'] = navlet.preferences.get(
REFRESH_INTERVA... | ) / 1000
return context
def post(self, request):
"""Save refresh interval for this widget"""
account = get_account(request)
try:
interval = int(request.POST.get('interval')) * 1000
except ValueError:
return HttpResponse(status=400)
try:
... |
# ----------------------------------------------------------- | ---------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------- | ----------------------------------------------
# AZURE CLI EventHub - NAMESPACE TEST DEFINITIONS
import time
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer)
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
class EHConsumerGroupCURDScenarioTest(ScenarioTest):
@ResourceGrou... |
# -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use sendgrid to send emails
- Use MEMCACHIER on Heroku
'''
from configurations import values
# See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings... | EATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False |
# see: https://github.com/antonagestam/collectfast
AWS_PRELOAD_METADATA = True
INSTALLED_APPS += ('collectfast', )
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
AWS_HEADERS = {
'Cache-Control': 'max-age=%d, s-maxage=%d, must-revali... |
, 'is_closed'):
closed = loop.is_closed()
else:
closed = loop._closed # XXX
if not closed:
loop.call_soon(loop.stop)
loop.run_forever()
loop.close()
@pytest.fixture(scope='session')
def unused_port():
"""Gets random free port."""
de... | dis-server executable,"
" defaults to `%(default)s`")
parser.addoption('--ssl-cafile', default='tests/ssl/cafile.crt',
help="Path to testing SSL CA file")
parser.addoption('--ssl-dhparam', default='tests/ssl/dhparam.pem',
help="Path to testing ... | em',
help="Path to testing SSL CERT file")
parser.addoption('--uvloop', default=False,
action='store_true',
help="Run tests with uvloop")
def _read_server_version(redis_bin):
args = [redis_bin, '--version']
with subprocess.Popen(args, stdout=s... |
# @author Jeff Lockhart <jwlock@umich.edu>
# Script for drawing the tripartite network underlying analysis.
# version 1.0
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import sys
#add the parent directory to the current session's path
sys.path.insert(0, '../')
from network_utils import *
#... | des to align with excerpt column height
pos.update( (n, (1, i*5.57)) for i, n in enumerate(st) )
pos.update( (n, (2, i)) for i, n in enumerate(ex) )
| pos.update( (n, (3, i*90)) for i, n in enumerate(code_cols) )
#make our figure big so we can see
plt.figure(figsize=(20,20))
#draw our nodes
nx.draw_networkx_nodes(g, pos, nodelist=st, node_color='r',
node_shape='^')
nx.draw_networkx_nodes(g, pos, nodelist=ex, node_color='b',
... |
# -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from datetime import date
from weboob.deprecated.browser import Page
from weboob.capabilities... | in_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit()
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table =... |
s.
#
# 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 und... | 6)
def test_torch_Recall():
from bigdl.orca.learn.pytorch.pytorch_metrics import Recall
target = torch.tensor([0, 1, 1, 0, 1, 1])
preds = torch.tensor([0, 0.2, 1.0, 0.8, 0.6, 0.5])
recall = Recall()
recall(preds, target)
assert (recall.compute() - 0.75 < 10e-6)
def | test_torch_PrecisionRecallCurve():
from bigdl.orca.learn.pytorch.pytorch_metrics import PrecisionRecallCurve
target = torch.tensor([0, 1, 1, 0, 1, 1])
preds = torch.tensor([0, 0.2, 1.0, 0.8, 0.6, 0.5])
curve = PrecisionRecallCurve()
curve(preds, target)
print(curve.compute())
precision, rec... |
# -*- coding: utf-8 -*-
### denote lines that need to be changed for different categories
import sys
reload(sys)
sys.setdefaultencoding("utf-8") # to handle UnicodeDecode errors
from math import ceil # top 20% of rankings
from traceback import format_exc # to handle errors
import pickle # to store art... | ki', title.replace(' ', '_')])
categ = 'Category:All_NPOV_disputes' ###
pageviews = article_views(title)
print cnt+1, title, pageviews
d.append([title, link, pageviews, categ])
cnt = cnt+1
# od = OrderedDict(sorted(d.items(), key=lambda t:t[1][1], reverse=True)) # ordered dict in descending order of final s... | orted(d, key=itemgetter(2), reverse=True) # ordered list in descending order of pageviews
print '\n\nArticle rankings based on pageviews:\n'
for item in od:
print item
#with open('npov_b_ranking.pkl', 'wb') as f:
with open('TL_pickles/npov_m_ranking.pkl', 'wb') as f: ###
pickle.dump(od, f)
# if __name__ == '_... |
to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Knowledge database models."""
import os
from invenio_base.globals import cfg
from invenio.ext.sqlalchemy import db
from invenio.ext.sqlalchemy.utils import session_manager
from invenio_collections.models import Colle... | ssion
self.kbdefs.collection = collection
db.session.merge(self.kbdefs)
else:
# insert
self.kbdefs = KnwKBDDEF(output_tag=field,
| search_expression=expression,
collection=collection)
@staticmethod
def generate_slug(name):
"""Generate a slug for the knowledge.
:param name: text to slugify
:return: slugified text
"""
slug = slugify(name)
i... |
#
# Copyright (c) 1996-2000 Tyler C. Sarna <tsarna@sarna.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# not... | QrCodeWidget,
BarcodeECC200DataMatrix,
):
registerWidget(widget)
_reset()
from reportlab.rl_config import register_reset
register_reset(_reset)
def getCodes():
"""Returns a dict mapping code names to widgets"""
#the module exports a dictionary of na... |
for widget in _widgets:
codeName = widget.codeName
codes[codeName] = widget
return codes
def getCodeNames():
"""Returns sorted list of supported bar code names"""
return sorted(getCodes().keys())
def createBarcodeDrawing(codeName, **options):
"""This creates and return... |
import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... | on_netloc = get_swapped_origin_netloc(parsed.netloc)
destination_url = urlparse.urlunsplit(urlparse.SplitResult(
scheme = parsed.scheme,
netloc = destination_netloc,
path = parsed.path,
query = None,
fragment = None))
return destination_url
def redirect(url, response)... | response.add_required_headers = False
response.writer.write_status(301)
response.writer.write_header("access-control-allow-origin", "*")
response.writer.write_header("location", url)
response.writer.end_headers()
response.writer.write("")
def preprocess_redirection(request, response):
if "r... |
line += "%6i angles\n"%(self.count_angles())
if(self.count_dihedrals()):
line += "%6i dihedrals\n"%(self.count_dihedrals())
if(self.count_impropers()):
line += "%6i impropers\n"%(self.count_impropers())
#line += "%12.5f mass"%()
#line += "%12.5f %12.5f %12.5f c... | he two oxygen atoms an orientation that deviates randomly
from the default (lying along the x-axis). |
"""
try:
return self._O_coord
except AttributeError:
self._O_coord = self.RCO*np.array([[-1., 0., 0.],[1., 0., 0.]])
#if angle == 0.:
# return self._O_coord
#else:
# generate a random axis for rotation.
axis... |
from django.conf.urls import patterns, incl | ude, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'students.views.home', name='home'),
# url(r'^students/', include('students.foo.urls')),
# App 'Index Classic'
url(r"^index_cl... | on:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
|
#!/usr/bin/python
import os,sys,string
i | f __name__ == "__main__":
# Check the argument list size
if (len(sys.argv) < 3):
sys.stderr.write("USAGE: " + sys.argv[0] + " <input file> <output file>\n")
sys.exit(1)
infi | lename = sys.argv[1]
outfilename = sys.argv[2]
# U is the mode to open the file with universal newline support.
infile = open(infilename, "rU")
outfile = open(outfilename, "w")
# Now read the lines
lines = map( lambda x: string.strip(x, string.whitespace+"\\"),
infile.readline... |
from sanic import Sanic
from sanic.views import CompositionView
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
from sanic.blueprints import Blueprint
from sanic.response import stream, text
bp = Blueprint('blueprint_request_stream')
app = Sanic('request_stream')
class Simpl... | sponse.write(body)
return stream(streaming)
@bp | .put('/bp_stream', stream=True)
async def bp_handler(request):
result = ''
while True:
body = await request.stream.get()
if body is None:
break
result += body.decode('utf-8').replace('1', 'A')
return text(result)
async def post_handler(request):
result = ''
whil... |
import json
from urllib import urlencode
from nose.tools import ok_
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.settings import api_settings
from access.middleware import ACLMiddleware
from amo.tests import TestCase
from users.models import UserPro... | ef test_get_detail_permission_curator(self):
self.give_permission()
| self.make_curator()
ok_(self.is_authorized_object(self.request('GET')))
def test_post_detail(self):
ok_(not self.is_authorized_object(self.request('POST')))
def test_post_detail_permission(self):
self.give_permission()
ok_(self.is_authorized_object(self.request('POST')))
... |
#!/usr/bin/python
# make-unicode.py -- build the Unicode version of btcrecover from the ASCII version
# Copyright (C) 2014, 2015 Christopher Gurnee
#
# This file is part of btcrecover.
#
# btcrecover is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as pub... | t the block of code up until the next "key" string
for line in ascii_version:
if line.startswith("# Uncomment for ASCII-only support"):
unicode_version.write(line)
break
unicode_version.write(line[1:] if line.startswith("#") else line)
... | code up until the first empty line
for line in ascii_version:
if line.strip() == "":
unicode_version.write(line)
break
unicode_version.write("#")
unicode_version.write(line)
# Copy the rest of the file
... |
height = letterImage.get_height()
width = letterImage.get_width()
x = 0
y = 0
while y+charheight < height and x < width:
letters.append( letterImage.subsurface(pygame.Rect(x, y, charwidth, charheight) ) )
y = y + charheight
return letters
def big_Alpha():
char_wid... | bet, data, (0,10))
class GUI_Scoreboard(pygame.Surface):
def __init__(self, timeLimit):
pygame.Surface.__init__(self, (windowDimension[0], 55), SRCALPHA)
self.xoffset = 10
self.yoffset = 10
self.score = 0
self.started = 0
self.time = timeLimit
self.image = ""... | ore):
self.fill(black)
drawBorder(self)
self.score = self.score + score
self.time = self.time - int(time - self.started) + int(score*25)
if self.time < 0 :
return "TIMESUP"
addText(self, small_alphabet, str(self.time), (windowDimension[0]/2-25, self.get_height... |
self._info = {
'threshold': self.threshold,
'similarity_name': self.similarity_name,
'window': self.window,
'ngram_length': self.ngram_length,
'min_match_length': self.min_match_length,
'accepted_semtypes': sorted(self.ac... | (self._is_stop_term(tok) and tok.lemma_ not in self.negations) or
tok.pos_ == 'ADP' or tok.pos_ == 'DET' or tok.pos_ == 'CONJ'
)
def _is_stop_term(self, tok):
return tok.is_stop or tok.lemma_ == 'time'
| def _is_valid_end_token(self, tok):
return not(
tok.is_punct or tok.is_space or self._is_stop_term(tok) or
tok.pos_ == 'ADP' or tok.pos_ == 'DET' or tok.pos_ == 'CONJ'
)
def _is_valid_middle_token(self, tok):
return (
not(tok.is_punct or tok.is_space) ... |
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (https:// | www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this for something useful or delete this method
self | .do_something_before_all_tests()
def tearDown(self, *args, **kwargs):
# TODO Replace this for something useful or delete this method
self.do_something_after_all_tests()
return super(SomethingCase, self).tearDown(*args, **kwargs)
def test_something(self):
"""First line of docst... |
# -*- coding: utf-8 -*-
import cx_Oracle
db = cx_Oracle.connect("username", "pass | word", "10.17.1.220:1521/db")
cursor = db.cursor()
cursor.execute("select loginid from sys_user")
for loginid in cursor:
print("loginid: ", loginid)
cursor.close()
cursor = db.cursor()
#插入一条记录
cursor.execu | te("""insert into tb_user values(1,'admin','password')""");
#再插入一条数据
param = {'id': 2, 'n': 'admin', 'p': 'password'}
cursor.execute('insert into tb_user values(:id,:n,:p)', param);
#一次插入多条数据,参数为字典列表形式
param = [{'id': 3, 'n': 'admin', 'p': 'password'}, {'id': 4, 'n': 'admin','p': 'password'}, {'id': 5, 'n': 'admin',... |
from .relationship_manager import RelationshipManager, ZeroOrMore # noqa
class ZeroOrOne(RelationshipManager):
description = "zero or one relationship"
def single(self):
nodes = super(ZeroOrOne, self).all()
if len(nodes) == 1:
return nodes[0]
if len(nodes) > 1:
... | s[0]
else:
raise CardinalityViolation(self, len(nodes))
else:
raise CardinalityViolation(self, 'none')
def all(self):
return [self.single()]
| def disconnect(self, obj):
raise AttemptedCardinalityViolation("Cardinality one, cannot disconnect use reconnect")
def connect(self, obj, properties=None):
if not hasattr(self.source, '_id'):
raise ValueError("Node has not been saved cannot connect!")
if len(self):
... |
ize) == 2 and size[1] != out.rows():
# flow/fixed widgets rendered too large/small
out = CompositeCanvas(out)
out.pad_trim_top_bottom(0, size[1] - out.rows())
return out
def get_cursor_coords(self, size):
"""Return the cursor coordinates of the focus widget."""
... | if item_rows is None:
item_rows = self.get_item_rows(size, focus=True)
for r in item_rows[:i]:
y += r
return x, y
def rows(self, size, focus=False ):
return sum(self.get_item_rows(size, focus))
def keypress(self, size, key ):
"""Pass the k... | m_rows = None
if len(size) == 2:
item_rows = self.get_item_rows(size, focus=True)
i = self.focus_position
if self.selectable():
tsize = self.get_item_size(size, i, True, item_rows)
key = self.focus.keypress(tsize, key)
if self._command_map[key] no... |
import numpy as np
from scipy.optimize import check_grad
## Two-layer NN with ReLU
# Two-layer NN, with 200 units per layer with ReLu ai = max(0,oi)
# X - (W01) - Layer1 - (W12) - Layer2 - (W23) - Output
# ((D+1)*nh) + ((nh+1)*nh) + ((nh+1)*K)
nh = 200
def getAvgGradient(w, X, y, L, K):
[N,D] = X.shape
W01,... | (dh1, axis=0, keepdims=True)/N
g = np.concatenate((dW01.flatten(), db1.flatten(), dW12.flatten(), db2.flatten(), dW23.flatten(), db3.flatten()), axis=0)
return (g, l)
def predict(w, X, K):
N,D = X.shape
W01,b1,W12,b2,W23,b3 = parseParams(w,D,K)
# Forward pass
h1 = | np.maximum(0, np.dot(X, W01) + np.tile(b1,(N,1))) # N x nh, ReLU
h2 = np.maximum(0, np.dot(h1, W12) + np.tile(b2,(N,1))) # N x nh, ReLU
scores = np.dot(h2, W23) + np.tile(b3,(N,1)) # N x K
#exp_scores = np.exp(scores-np.tile(np.max(scores,axis=1,keepdims=True),(1,K)))
#probs = exp_scores / np.tile(exp_... |
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name = 'simplui',
version = '1.0.4',
author = | 'Tristam MacDonald',
author_email = 'swiftcoder@gmail.com',
description = 'Light-weight GUI toolkit for pyglet',
url = 'http://simplui.googlecode.com/',
platforms = ['all'],
license = 'BSD',
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD ... | :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Scientific/Engineering :: Human Machine Interfaces',
'Topic :: Software Development :: User Interfaces',
],
packages = find_packages(),
install_requires = ['simplejson >= 2.0', 'pyglet >= 1.1']
)
|
DELETE FROM animalvaccination WHERE ID >= %s;" % START_ID
print "DELETE FROM log WHERE ID >= %s;" % START_ID
print "DELETE FROM owner WHERE ID >= %s;" % START_ID
print "DELETE FROM adoption WHERE ID >= %s;" % START_ID
print "DELETE FROM media;" # They want media cleared out, shouldn't be enough to worry about orphans
... | ["Log_Description"], "N/A", d["Log_Notes"]) )
elif d["Action"] == "Veterinary":
animalmedicals.append( asm.animal_regimen_single(a.ID, ed, d["Log_Description"], "N/A", d["Log_Notes"]) )
elif d["Action"] == "Vaccination":
vacctypes = {
"C3": | 16,
"C5": 18,
"F3": 22,
"F4": 23
}
av = asm.AnimalVaccination()
animalvaccinations.append(av)
av.AnimalID = a.ID
av.VaccinationID = 8
for k, i in vacctypes.iteritems():
if d["Log_Description"].find(k) != -1: av.VaccinationID... |
import logging
def registerLoggingHander(dependencies):
plexHandler = PlexLoggerHandler()
for dependency in dependencies:
Log.Debug("Registering LoggerHandler for dependency: %s" % dependency)
log = logging.getLogger(dependency)
log.setLevel('DEBUG')
log.addHandler(plexH... | emit(self, record):
if record.levelno == logging.DEBUG:
Log.Debug(self.getFormattedString(record | ))
elif record.levelno == logging.INFO:
Log.Info(self.getFormattedString(record))
elif record.levelno == logging.WARNING:
Log.Warn(self.getFormattedString(record))
elif record.levelno == logging.ERROR:
Log.Error(self.getFormattedString(record))
elif re... |
# -*- coding: utf-8 -*-
from collections import Counter
from .design_pattern import singleton
@singleton()
class ListUtilsClass(object):
def most_common_inspect(self, list1):
new_list = []
for s1 in list1:
if not isinstance(s1, unicode):
s1 = str(s1).decode("UTF-8")
... | (set(seqs))
__uniq = set([])
__remove_idxes = []
for idx1, seq1 in enumerate(seqs[:]):
__id = uniq_lambda(seq1)
if __id in __uniq:
__remove_idxes.append(idx1)
else:
__uniq.add(__id)
new_seqs = []
for idx1, seq... | emove_idxes:
new_seqs.append(seq1)
seqs = new_seqs
return seqs
ListUtils = ListUtilsClass()
uniq_seqs = ListUtils.uniq_seqs
|
'''
Copyright 2015
This file is part of Orbach.
Orbach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
th | e Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Orbach 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 details.
You should have received a copy of the GNU General Public License
along with Orbach. If not, see <http://www.gnu.org/licenses/>.
'''
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
fr... |
import glob
from pythonforandroid.toolchain import (
CythonRecipe,
Recipe,
current_directory,
info,
shprint,
)
from os.path import join
import sh
class TwistedRecipe(CythonRecipe):
version = '17.9.0'
url = 'https://github.com/twisted/twisted/archive/twisted-{version}.t | ar.gz'
depends = ['setuptools', 'zope_interface', 'incremental', 'constantly']
call_hostpython_via_targetpython = False
install_in_hostpython = True
def prebuild_arch(self, arch):
super(TwistedRecipe, self).prebuild_arch(arch)
# TODO Need to whitelist tty.pyo and termios.so here
... | tests etc. here, but skipping for now')
def get_recipe_env(self, arch):
env = super(TwistedRecipe, self).get_recipe_env(arch)
# We add BUILDLIB_PATH to PYTHONPATH so twisted can find _io.so
env['PYTHONPATH'] = ':'.join([
self.ctx.get_site_packages_dir(),
env['BUILDLI... |
import numpy as np
from sverchok.utils.testing import *
from sverchok.utils.logging import debug, info
from sverchok.utils.geom import CubicSpline
class CubicSplineTests(SverchokTestCase):
def setUp(self):
super().setUp()
vertices = [(-1, -1, 0), (0, 0, 0), (1, 2, 0), (2, 3, 0)]
self.spli... | result = self.spline.eval(t_in)
#info(result)
expected_result = np.array(
[[-1.0, -1.0, 0.0 ],
[-0.60984526, -0.66497986, 0.0 ],
[ 0.29660356, 0.5303721, 0.0 | ],
[ 0.5, 1.0, 0.0 ],
[ 0.94256655, 1.91347161, 0.0 ],
[ 2.0, 3.0, 0.0 ]])
self.assert_numpy_arrays_equal(result, expected_result, precision=8)
def test_tangent(self):
t_in = np.array([0.0, 0.1, 0.4, 0.5, 0.7, 1.0... |
from components.base.automotive_component import AutomotiveComponent
from config import project_registration as proj
from tools.ecu_logging import ECULogger as L
import random
class AbstractECU(AutomotiveComponent):
'''
This abstract class defines the interface of
an ECU as it is found in an automotive n... | cu_id string id of the corresponding AbstractECU
data_rate float datarate of the ecu
Output: -
'''
AutomotiveComponent.__init__(self, sim_env)
self._ABSTRACT_ECU = True
self._ecu_id = ecu_id ... | proj.BUS_MSG_CLASS # what kind of messages are exchanged
self.connected_bus = None # Bus that is connected to the ECU
self.data_rate = proj.BUS_ECU_DATARATE # Datarate with which bits are put on the bus
self._effective_datarate = 0 # Bit per second
self._effective_bi... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | xport_dae" in locals():
imp.reload(export_dae)
import bpy
from bpy.props import StringProperty, BoolProperty, FloatProperty, EnumProperty
from bpy_extras.io_utils import (ExportHelper,
path_reference_mode,
axis_conversion,
... | ass ExportDAE(bpy.types.Operator, ExportHelper):
'''Selection to DAE'''
bl_idname = "export_scene.dae"
bl_label = "Export DAE"
bl_options = {'PRESET'}
filename_ext = ".dae"
filter_glob = StringProperty(default="*.dae", options={'HIDDEN'})
# List of operator properties, the attributes will ... |
#! /usr/bin/env python
# This file is part of the dvbobjects library.
#
# Copyright 2009-2013 Lorenzo Pallara l.pallara@avalpa.com
#
# 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 vers... | import *
######################################################################
class update_notification_section(Section):
table_id = 0x4B
section_max_siz | e = 4096
def pack_section_body(self):
self.table_id_extension = self.action_type << 8 | ((self.OUI >> 16) ^ ((self.OUI >> 8) & 0xFF) ^ (self.OUI & 0xFF))
# pack common_descriptor_loop
common_bytes = string.join(
map(lambda x: x.pack(),
self.common_d... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Is this a triangle?
#Problem level: 7 kyu
def is_tri | angle(a, b, c):
return (a+b>c) and (b+c>a) and | (c+a>b)
|
from django.contrib import admin
from .models import *
class ProductAdmin(admin.ModelAdmin):
list_display = ('id', 'prd_process_id', 'prd_name',
'prd_display_name', 'prd_owner', 'prd_product_id', 'prd_date',
'prd_class', 'prd_filter', 'prd_is_public', 'prd_is_permanent',)
... | ster(ProductContent, ProductContentAdmin)
admin.site.register(ProductContentAssociation, ProductContentAssociationAdmin)
admin.site.register(ProductContentSetting, ProductContentSettingAdmin)
admin.site.register(ProductSetting, ProductSettingAdmin)
admin.site.register(CurrentSetting, CurrentSettingAdmin)
admin.site.reg... | .register(WorkgroupUser, WorkgroupUserAdmin)
admin.site.register(Filterset, FiltersetdAdmin)
admin.site.register(FilterCondition, FilterConditionAdmin)
admin.site.register(BookmarkProduct, BookmarkedAdmin)
|
#!/usr/bin/env python
# -*- coding: ut | f-8 -*-
import re
import urlparse
from scrapy import log
from scrapy.http import Request
from base.base_wolf import Base_Wolf
class Wolf(Base_Wolf):
def __init__(self, *args, **kwargs):
super(Wolf, self).__init__(*args, **kwargs)
self.name = 'cnscg'
self.seed_urls = [
'http://... | 'follow'] = re.compile(r'show-')
self.anchor['desc'] = "//*[@class='intro']"
def get_resource(self, item, response, tree):
item = super(Wolf, self).get_resource(item, response, tree)
resource = tree.xpath("//*[@class='original download']//a/@href")
downloads = [urlparse.urljoin(sel... |
#!/usr/bin/env python
"""
Installation script:
To release a new version to PyPi:
- Ensure the version is correctly set in oscar.__init__.py
- Run: python setup.py sdist upload
"""
from setuptools import setup, find_packages
import os
import sys
from oscar import get_version
PROJECT_DIR = os.path.dirname(__file__)
... | ngo',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
| 'Programming Language :: Python',
'Topic :: Other/Nonlisted Topic']
)
# Show contributing instructions if being installed in 'develop' mode
if len(sys.argv) > 1 and sys.argv[1] == 'develop':
docs_url = 'http://django-oscar.readthedocs.org/en/latest/internals/contributing/index.html'
maili... |
self.reversed_operands = True
self.ifm, self.ifm2 = self.ifm2, self.ifm
self.valid_broadcast = True
else:
self.valid_broadcast = False
def is_valid(self):
"""
This function checks whether BinaryElementwise has compatible attributes with the NPU
""... | identity operator requiring ofm != int32 for now
| if np.dtype(self.ofm) == np.int32 and len(self.ofm.shape) < 4:
return False
if len(self.ifm.shape) > 4 or len(self.ifm2.shape) > 4:
return False
if len(self.ifm.shape) == 4 and self.ifm.shape[0] != 1:
return False
if len(self.ifm2.shape) == 4 and self.ifm... |
##
## pyGBot - Versatile IRC Bot
## Copyright (C) 2008 Morgan Lokhorst-Blight, Alex Soborov
| ##
## Th | is 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 option) any later version.
##
## This program is distributed in the hope that it will be... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
try:
with open('README.rst') as file:
long_description = file.read()
except IOError:
long_descr | iption = 'Python lib for sniffets.com'
setup(
name='sniffets',
packages=['sniffets'],
version='0.1.8',
long_description=long_description,
description='Python lib for sniffets.com',
author='Doniyor Jurabayev',
author_email='behconsci@gmail.com',
url='https://github.com/behconsci/sniffets... | |
"""
Concurrent downloaders
"""
import os
import sys
import signal
import logging
import itertools
from functools import partial
from concurrent.futures import ProcessPoolExecutor
from pomp.core.base import (
BaseCrawler, BaseDownloader, BaseCrawlException,
)
from pomp.contrib.urllibtools import UrllibDownloadWorke... | nt
signal.signal(signal.SIGINT, lambda s, f: s)
super(ConcurrentDownloader, self).__init__()
d | ef process(self, crawler, request):
# delegate request processing to the executor
future = self.executor.submit(
_run_download_worker, self.worker_params, request,
)
# build Planned object
done_future = Planned()
# when executor finish request - fire done_f... |
def descriptor(rcut=4, desc_type='se_ar', mneiba=150):
smth_frac = 0.85
if desc_type == 'se_ar':
rmult = 1.5
mneibr = 500
ar_smth = rcut*smth_frac
desc = {
'type': 'se_ar',
'a': {
'sel': [mneiba],
'rcut_smth': ar_smth,
'rcut': rcut,
'neuron': [10, 20, 40],... | stop_batch,
}
display = {
'disp_file': 'lcurve.out',
'disp_freq': 1000,
'numb_test': 64,
'disp_training': True,
'time_training': True,
'profiling': False,
'profiling_file': 'timeline.json',
}
checkpoint = {
'save_ckpt': 'model.ckpt',
'load | _ckpt': 'model.ckpt',
'save_freq': 10000,
}
tr.update(display)
tr.update(checkpoint)
return tr
def default_input(stop_batch=100000, batch_size=32,
desc_kws=None,
lr_kws=None,
):
if desc_kws is None:
desc_kws = dict()
if lr_kws is None:
lr_kws = dict()
dpmd_input = {
'model': {
... |
ng count returned by weapi.
:return: a Song object.
"""
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
LOG.warning('Song %s not existed!', song_name)
raise SearchNotFound('Song {} not existed.'.format(song_name... | e))
else:
users = result['result']['userprofiles']
if quiet:
user_id, user_name = users[0]['userId'], users[0]['nickname']
user = User(user_id, user_name)
return user
else:
return self.display.select_one_user(use... | er's all playlists.
warning: login is required for private playlist.
:params user_id: user id.
:params limit: playlist count returned by weapi.
:return: a Playlist Object.
"""
url = 'http://music.163.com/weapi/user/playlist?csrf_token='
csrf = ''
params ... |
from __future__ import print_function
# bench related imports
import numpy as np
import shutil
import bquery
import pandas as pd
import itertools as itt
import cytoolz
import cytoolz.dicttoolz
from toolz import valmap, compose
from cytoolz.curried import pluck
import blaze as blz
# other imports
import contextlib
impor... | tt.izip(ga, gb, gx, gy)),
dtype='S2,S2,i8,i8', count=n_rows)
ct = bquery.ctable(z, rootdir=rootdir, )
print(ct)
# -- pandas --
df = pd.DataFrame(z)
with ctime(m | essage='pandas'):
result = df.groupby(['f0'])['f2'].sum()
print(result)
t_pandas = t_elapsed
# -- cytoolz --
with ctime(message='cytoolz over bcolz'):
# In Memory Split-Apply-Combine
# http://toolz.readthedocs.org/en/latest/streaming-analytics.html?highlight=reduce#split-apply-combine-with-groupby-and-redu... |
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings |
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^add/$', 'cart.views.add'),
url(r'^clear/$', 'cart.views.clear'),
url(r'^show/$', 'cart.views.show'),
url... | '),
)
|
"""autogenerated by genpy from hoverboard/ServoRaw.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class ServoRaw(genpy.Message):
_md5sum = "cf1c9d17f7bbedbe8dd2c29cdb7700f8"
_type = "hoverboard/ServoRaw"
_has_header = True ... | x = _x.encode('utf-8')
length = len(_x)
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_2b.pack(_x.port, _x.value))
except struct.error as se: self._check_types(se)
except TypeError as te: self._check_types(te)
def deserialize_numpy(self, str, numpy)... | rray types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
end = 0
_x = self
start = end
end += 12
(_x.header.seq, _x.header.stamp.secs, _x.header.stam... |
import sys
import struct
ULL_BYTES = struct.calcsize('!Q')
SHORT_BYTES = struct.calcsize('!h')
INDEX_HEADER = 'IDX'
def search(dbfile, prefix):
"""Returns all words having a given prefix using a dbfile."""
idx = Index.from_file(dbfile)
for letter in prefix:
if letter not in idx.nodes:
... | X_HEADER), size_data)
| if header != INDEX_HEADER:
import ipdb; ipdb.set_trace()
data = f.read(index_size - ULL_BYTES - len(INDEX_HEADER))
return Index(data)
def parse(self):
node_count, = struct.unpack_from('!Q', self.data)
offset = ULL_BYTES
# Read nodes
for n in range(no... |
import numpy as np
import struct
import wave
from winsou | nd import PlaySound, SND_FILENAME, SND_ASYNC
import matplotlib.pyplot as plt
CHUNK = 1 << 8
def play(filename):
PlaySound(filename, SND_FILENAME | SND_ASYNC)
fn = r"D:\b.wav"
f = wave.open(fn)
print(f.getparams())
ch = f.getnchannels()
sw = f.getsampwidth()
n = f.getnframes()
data = bytearray()
while len(data)... | fft.fftfreq(len(w))
module = np.abs(w)
idmax = module.argmax()
print(abs(freqs[idmax]) * f.getframerate())
plt.specgram(data)
plt.show()
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | -----------------------------------------
# Setup
#-----------------------------------------------------------------------------
| ALL = (
'data',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
Test___all__ = pytest.mark.sampledata(verify_all("bokeh.sampledata.commits", ALL))
@pytest.mark.sampledata
def test_data(pd... |
# -*- coding: UTF-8 -*-
_ | _copyright__ = """\
Copyright (c) 2012-2013 Luc Saffre.
This software comes with ABSOLUTELY NO WARRANTY and is
distributed under the terms of the GNU Lesser General Public License.
See file COPYING.txt for | more information."""
|
# coding=utf8
#
# Copyright 2013 Dreamlab Onet.pl
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;
# version 3.0.
# This library is distributed in the hope that it will be useful,
# bu... | ger.info("proxying request to: %s", mock.name)
return mock._rmock_data.register_call_and_get_re | sult(
funcname, args, kwargs,
headers=headers
)
|
#!/usr/bin/env python
# Copyright 2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# standard library modules, , ,
import unittest
import os
import tempfile
# internal modules:
from yotta.lib.fsutils import mkDirP, rmRf
from yotta.lib.detect import systemDefaultTarg... | return test_dir
class TestPackIgnores(u | nittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_dir = writeTestFiles(Test_Files)
@classmethod
def tearDownClass(cls):
rmRf(cls.test_dir)
def test_absolute_ignores(self):
c = component.Component(self.test_dir)
self.assertTrue(c.ignores('moo'))
s... |
kpc
_FEHTAG= 'FE_H'
_AFETAG= 'AVG_ALPHAFE'
_AFELABEL= r'$[\left([\mathrm{O+Mg+Si+S+Ca}]/5\right)/\mathrm{Fe}]$'
catpath = '../catalogues/'
selectFile= '../savs/selfunc-nospdata.sav'
if os.path.exists(selectFile):
with open(selectFile,'rb') as savefile:
apo= pickle.load(savefile)
def get_rgbsample(logg... | _correction == True:
data['MH50_DIST'] *= 1.05
XYZ= bovy_coords.lbd_to_XYZ(data['GLON'],
data['GLAT'],
data['MH50_DIST'],
degree=True)
RphiZ= bovy_coords.XYZ_to_galcencyl(XYZ[:,0],
... | ALPHI']= RphiZ[:,1]
data['MH50_GALZ']= RphiZ[:,2]
data['M_J'] = data['J0']-data['HAYDEN_DISTMOD_50']
data['M_H'] = data['H0']-data['HAYDEN_DISTMOD_50']
data['M_K'] = data['K0']-data['HAYDEN_DISTMOD_50']
data['AVG_ALPHAFE'] = avg_alphafe_dr12(data)
data[_FEHTAG] += -0.1
#remove locations not in the apogee selecti... |
from ems.typehint import accepts
from ems.resource.repository import Repository
class DictAttributeRepository(Repository):
@accepts(Repository)
def __init__(self, sourceRepo, sourceAttribute='data'):
self._sourceRepo = sourceRepo
self.sourceAttribute = sourceAttribute
def get(self, id_):... | antiate an object
:returns: object
"""
model = self._sourceRepo.new()
data = getattr(model, self.sourceAttribute)
for key in attributes:
data[key] = attributes[key]
return data
def store(self, attributes, obj=None):
"""
Store a new obje... | Error("Obj has to be None")
sourceAttributes = {self.sourceAttribute:self.new(attributes)}
if 'ID' not in sourceAttributes:
raise KeyError("attributes have to contain ")
model = self._sourceRepo.store(sourceAttributes)
return getattr(model, self.sourceAttribute)
def u... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.Account import Account
from module.plugins.internal.Plugin import set_cookie
class ShareonlineBiz(Account):
__name__ = "ShareonlineBiz"
__type__ = "account"
__version__ = "0.41"
__status__ = "testing"
__description__ = """Sha... | = [("Walter Purcaro", "vuolter@gmail.com")]
def api_response(self, user, passwor | d):
res = self.load("https://api.share-online.biz/cgi-bin",
get={'q' : "userdetails",
'aux' : "traffic",
'username': user,
'password': password},
decode=False)
... |
# -*- coding: utf-8 -*-
"""
CSS Testing
:copyright: (C) 2014 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
from os.path import join
from cssutils imp | ort CSSParser
import unittest
import trytond.tests.test_tryton
dir = 'static/css/'
class CSSTest(unittest.TestCase):
"""
Test case for CSS.
"""
def validate(self, filename):
"""
Uses cssutils to validate a css file.
Prints output using a logger.
"""
CSSParser... | r, 'style.css')
self.validate(cssfile)
def suite():
"""
Define suite
"""
test_suite = trytond.tests.test_tryton.suite()
test_suite.addTests(
unittest.TestLoader().loadTestsFromTestCase(CSSTest)
)
return test_suite
if __name__ == '__main__':
unittest.TextTestRunner(verb... |
token = strategy.session_get('partial_pipeline_token')
partial_object = strategy.partial_load(token)
pipeline_data = None
if partial_object:
pipeline_data = {'kwargs': partial_object.kwargs, 'backend': partial_object.backend}
return pipeline_data
def get_real_social_auth_object(request):
... | social = running_pipeline['kwargs']['social']
if isinstance(social, dict):
social = social_django.models.UserSocialAuth.objects.get(**social)
return social
def quarantine_session(request, locations):
"""
Set a session variable indicating that the session is restricted
to being ... | views contained in the modules listed by string
in the `locations` argument.
Example: ``quarantine_session(request, ('enterprise.views',))``
"""
request.session['third_party_auth_quarantined_modules'] = locations
def lift_quarantine(request):
"""
Remove the session quarantine variable.
"... |
import discord
import random
import aiohttp
from lxml import html as l
async def cyanideandhappiness(cmd, message, args):
comic_number = random.randint(1, 4562)
comic_url = f'http://explosm.net/comics/{comic_number}/'
async with aiohttp.ClientSession() as session:
async with session.get(comic_ | url) as data:
page = await data.text()
root = l.fromstring(page)
comic_element = root.cssselect('#main-comic')
comic_img_url = comic_element[0].attrib['src']
if comic_img_url.startswith('//'):
comic_img_url = 'https:' + comic_img_url
embed = discord.Embed(color=0x1ABC9C)
| embed.set_image(url=comic_img_url)
await message.channel.send(None, embed=embed)
|
import multiprocessing
import socket
import re
import time
def handle(connection, address):
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("process-%r" % (address,))
try:
logger.debug("Connected %r at %r", connection, address)
while True:
d... | ocess.daemon = True
process.start()
server = Server("0.0.0.0", 9000)
server.allow_reuse_address=True
try:
logging.info("Listening")
server.start()
except:
logging.exception("Unexpec | ted exception")
finally:
logging.info("Shutting down")
for process in multiprocessing.active_children():
logging.info("Shutting down process %r", process)
process.terminate()
process.join()
logging.info("All done")
|
# Copyright 2021 Camptocamp SA
# License AGPL-3.0 or later (https | ://www.gnu.org/licenses/agpl.html)
from | . import measuring_device
|
import time
import sys
def createDots(length, delay):
fo | r i in range(length):
print('.', end='')
sys.stdout.flush()
time.sleep(delay)
def createHash(length, delay):
for i in range(length):
print('#', end='')
sys.stdout.flush()
time.sleep(delay)
def createVrD | ots(length, delay):
for i in range(length):
print('.')
time.sleep(delay)
def deGa():
time.sleep(.3)
|
'''
Created on 30 Jun 2015
@author: @willu47
'''
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from SALib.sample.ff import sample, find_smallest, extend_bounds
from SALib.analyze.ff import analyze, interactions
def test_find_smallest():
'''
'''
num_vars = [1, 2, 3, 4, 5, 6, 7... | ,
[ 2.5, 0, 1, 0],
[ 2.5, 1, 0, 0],
[ 2.5, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]], dtype=np.float)
assert_equal(ac... | oblem = {'bounds': [[0., 2.5], [0., 1.], [0., 1.], [0., 1.]],
'num_vars': 4,
'names': ['x1', 'x2', 'x3', 'x4']}
X = np.array([[ 1, 1, 1, 1],
[ 1, 0, 1, 0],
[ 1, 1, 0, 0],
[ 1, 0, 0, 1],
[0, 0, 0, 0],
... |
#
# Copyright (c) 2001 - 2015 The SCons Foundation
#
# 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, copy, modify, merge... | OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__doc__ = """
SCons compatibility package for old Python versions
This subpackage holds modules that provide backwards-compatible
impleme... | y reference things in this package through
the SCons.compat namespace. The modules included here add things to
the builtins namespace or the global module list so that the rest
of our code can use the objects and names imported here regardless of
Python version.
Simply enough, things that go in the builtins name spac... |
from django.conf.urls.defa | ults import *
urlpatterns = patterns('',
(r'^(\d+)/$', 'onpsx.gallery.views.index'),
(r'^$', 'onpsx.gallery.views.index') | ,
)
|
from logging import StreamHandler
from django.conf import settings
from celery import current_task
from celery.signals import task_prerun, task_postrun
from kombu import Connection, Exchange, Queue, Producer
from kombu.mixins import ConsumerMixin
from .utils import get_celery_task_log_path
routing_key = 'celery_log'... | lizer='json', exchange=celery_log_exc | hange,
declare=[celery_log_exchange], routing_key=routing_key
)
def log(self, task_id, msg):
payload = {'task_id': task_id, 'msg': msg, 'action': self.ACTION_TASK_LOG}
return self.publish(payload)
def read(self):
pass
def flush(self):
pass
def task... |
#!/usr/bin/env python
# coding:utf-8
import urllib
domain = 'http://www.liaoxuefeng.com' #廖雪峰的域名
path = r'C:\Users\cyhhao2013\Desktop\temp\\' #html要保存的路径
# 一个html的头文件
input = open(r'C:\Users\cyhhao2013\Desktop\0.html', 'r')
head = input.read()
# 打开python教程主界面
f = urllib.urlopen("http://www.liaoxuefeng.c | om/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000")
home = f.read()
f.close()
# 替换所有空格回车(这样容易好获取url)
geturl = home.replace("\n", "")
geturl = geturl.replace(" ", "")
# 得到包含url的字符串
list = geturl.split(r'em;"><ahref="')[1:]
# 强迫症犯了,一定要把第一个页面也加进去才完美
list.insert(0, '/wiki | /001374738125095c955c1e6d8bb493182103fac9270762a000">')
# 开始遍历url List
for li in list:
url = li.split(r'">')[0]
url = domain + url #拼凑url
print url
f = urllib.urlopen(url)
html = f.read()
# 获得title为了写文件名
title = html.split("<title>")[1]
title = title.split(" - 廖雪峰的官方网站</ti... |
n hash")
tx['hash'] = util.double_sha256(tx['__data__'])
else:
tx['hash'] = chain.transaction_hash(tx['__data__'])
tx_hash_array.append(tx['hash'])
tx['tx_id'] = store.tx_find_id_and_value(tx, pos == 0)
if tx['tx_id']:
... | satoshis * (b['nTime'] - prev_nTime)
b['total_ss'] = prev_total_ss + ss_created
if b['height'] is None or b['height'] < 2:
b['search_block_id'] = None
else:
b['search_block_id'] = store.get_block_id_at_height(
util.get_search_height(int(b['height'])),... | k (
block_id, block_hash, block_version, block_hashMerkleRoot,
block_nTime, block_nBits, block_nNonce, block_height,
prev_block_id, block_chain_work, block_value_in,
block_value_out, block_total_satoshis,
block_total_sec... |
from django.forms import ModelForm, inlineformset_factory, HiddenInput, ModelChoiceField
from .models import BirthForm, SanityPillars, InnateAbility, StabilitySources
class CharBirthForm(ModelForm):
class Meta:
model = BirthForm
fields = ['name', 'pronoun', 'age', 'birthplace', 'drive', 'occupation... |
#formset for pillars of sanity
PillarsOfSanity = inlineformset_factory(
BirthForm,
SanityPillars,
fields = ['pillar', 'description'],
extra = 0,
| min_num = 1,
max_num = 3,
can_delete = True,
validate_min = True,
validate_max = True,
)
#formset for abilities
Abilities = inlineformset_factory(
BirthForm,
InnateAbility,
fields = ['ability', 'value'],
can_delete=True,
)
#formset for sources of Stability
SourcesOfStab... |
# -*- | coding: utf-8 -*-
"""
Copyright (C) 2018-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
import xbmc
if __name__ == '__main__':
xbmc.executebuiltin("Contain | er.Refresh")
|
import os
import sys
sys. | path.append(os.path.join(os.path.dirname(__file__), '../tools'))
import files
import tree
def main(argv):
dna = files.read_line(argv[0])
st = tree.SuffixTree(dna)
print '\n'.join(st.traverse())
if __name__ == "__main__":
m | ain(sys.argv[1:])
|
#
# Copyright 2012 IBM, Inc.
# Copyright 2012-2014 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# T... | class FakeNetInfo(object):
def __init__(self):
self.bondings = ['god', 'bless', 'potatoes']
with self.assertRaises(errors.ConfigNetworkError) as cne:
api._buildBondOptions('jamesbond', {}, _netinfo=FakeNetInfo())
self.assertEquals(cne.exception.errCode, error... | elf):
attrs = dict(nic='dummy', remove=True,
bridged=True)
networks = {'test-netowrk': attrs}
with self.assertRaises(errors.ConfigNetworkError) as cneContext:
api._validateNetworkSetup(networks, {})
self.assertEqual(cneContext.exception.errCode,
... |
__author__ = 'Richard Lincoln, r.w.lincoln@gmail.com'
""" This example demonstrates how optimise power flow with Pyreto. """
import sys
import logging
import numpy
import scipy.io
import pylab
import pylon
import pyreto
from pyreto.util import plotGenCost
from pybrain.rl.agents import LearningAgent
from pybrain.rl.... | setLineStyle(linewidth=2)
plot.update()
# Give the agent its task in an experiment.
#experiment = EpisodicExperiment(task, agent)
experiment = p | yreto.rlopf.OPFExperiment(task, agent)
weeks = 52 * 2
days = 5 # number of samples per gradient estimate
for week in range(weeks):
all_rewards = experiment.doEpisodes(number=days)
tot_reward = numpy.mean(agent.history.getSumOverSequences('reward'))
# print learner._allEvaluations#[-:-1]
# Plot the rew... |
# -*- coding: utf-8 -*-
##############################################################################
#
# This file is part of mozaik_communication | , an Odoo module.
#
# Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
# mozaik_communication 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 Li... | without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the
# GNU Affero General Public License
# along with mozaik_communication.
# If not, see <http://www.g... |
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.test import TestCase, tag
import factories
from formlibrary.models import CustomForm
@tag('pkg')
class CustomFormTest(TestCase):
def setUp(self):
self.organization = factories.Organization()
self.user = factori... |
organization=self.organization,
name="Humanitec's Survey",
fields="{ | }",
public={}
)
self.assertRaises(ValidationError, custom_form.save)
def test_save_without_public_org_info(self):
custom_form = CustomForm(
organization=self.organization,
name="Humanitec's Survey",
fields="{}",
public={'url': Tru... |
import argparse
import numpy as np
from PIL import Image
import ocppaths
import ocpcarest
import zindex
import anydbm
import multiprocessing
import pdb
#
# ingest the PNG files into the database
#
"""This file is super-customized for Mitya's FlyEM data."""
# Stuff we make take from a config or the command line i... | lue = anydb.get( key )
newdata[i,j] = int(dictvalue)
slab[b,:,:] = newdata
print "end of slice:",sl+b
anydb.close()
print "Entering commit phase"
# Now we have a 1024x1024x16 z-aligned cube.
# Send it to the database.
for y in range ( 0, yimagesz, ycubedim... | cubedata = np.zeros ( [zcubedim, ycubedim, xcubedim], dtype=np.uint32 )
xmin = x
ymin = y
xmax = min ( ximagesz, x+xcubedim )
ymax = min ( yimagesz, y+ycubedim )
zmin = 0
zmax = min(sl+zcubedim,endslice+1)
cubedata[0:zmax-zmin,0:ymax-ymin,0:xmax-xmin] = sla... |
"""
To plot this, you need to provide the experiment directory plus an output stem.
I use this for InvertedPendulum:
python plot.py outputs/InvertedPendulum-v1 --envname InvertedPendulum-v1 \
--out figures/InvertedPendulum-v1
(c) May 2017 by Daniel Seita
"""
import argparse
import matplotlib
matplotl... | xis='x', labelsize=tick_size)
axes[i].tick_params(axis='y', labelsize=tick_size)
axes[i].set_title("Mean Episode Rewards ({})".format(dd), fontsize=title_size)
axes[i].set_xlabel("ES Iterations", fontsize=xsize)
axes[i].set_ylabel("Rewards", fontsize=ysize)
plt.tight_layout()
plt... | :
"""
Handle logic with argument parsing.
"""
parser = argparse.ArgumentParser()
parser.add_argument("expdir", help="experiment dir, e.g., /tmp/experiments")
parser.add_argument("--out", type=str, help="full directory where to save")
parser.add_argument("--envname", type=str)
args = pa... |
import pandas as pd
import numpy as np
from os.path import join as opj
import sys
from fg_shared import *
sys.path.append(opj(_git, 'utils'))
import quickr
corncob = """
require(dplyr)
require(tidyr)
require(purr)
require(corncob)
#####################################################################################... | f Clonotype (TCRDIST0 basically EXACT CLONOTYPE)
# M total counts
# AGE age in years
# SEX "Male" or "Female"
# DAYS 1 if > 2 days post diagnosis, 0 otherwise
# HLA "MATCH" or "NON-MATCH" (in this case A*01)
########################################################################################### |
#' do_corncob
#'
#' Define the beta-binomial we are attempting to fit
#'
#' @param mydata data.frame
do_corncob <- function(mydata, frm = as.formula('cbind(W, M - W) ~ AGE+SEX+DAYS+HLA')){
cb1 = bbdml(formula = frm,
phi.formula = ~ 1,
data = mydata)
return(cb1)
}
# This wrapper i... |
# functions that implement analysis and synthesis of sounds using the Sinusoidal plus Stochastic Model
# (for example usage check the models_interface directory)
import numpy as np
from scipy.signal import resample, blackmanharris, triang, hanning
from scipy.fftpack import fft, ifft, fftshift
import math
import utilFu... | rate, w: analysis window,
N: FFT size (minimum 512), t: threshold in negative dB,
stocf: decimation factor of mag spectrum for stochastic analysis
returns y: output sound, ys: sinusoidal component, yst: stochastic component
"""
hN = N/2 | # size of positive spectrum
hM1 = int(math.floor((w.size+1)/2)) # half analysis window size by rounding
hM2 = int(math.floor(w.size/2)) # half analysis window size by floor
Ns = 512 ... |
def get_all(tordb):
return tordb.find()
def delete(tordb, obj_id):
tordb.remove([obj_id])
def insert(tordb, obj):
return tordb.insert(obj)
def update_full(tordb, id, obj):
tordb.update({'_id': | id} | , {'$set': obj})
|
def clip_matrix(image_as_matrix, width, height, top, left, expand | _by=0):
x1 = left
x2 = left + width
y1 = top
y2 = top + height
crop_img = image | _as_matrix[y1-expand_by:y2+expand_by, x1-expand_by:x2+expand_by]
return crop_img
|
#!/usr/bin/python
import sys
if (len(sys.argv) < 2):
fn = '/usr/share/ldraw/LDConfig.ldr'
else:
fn = sys.argv[1]
f = open(fn)
for line in f:
if '!COLOUR' in line:
line = line.strip()
ns = line.split()
category = ''
if 'RUBBER' in line:
category = 'material... |
category = 'material_glitter'
elif 'LUMINANCE' in line:
category = 'material_luminant'
elif 'PEARLESCENT' in line:
category = 'material_pearlescent'
elif 'CHROME' in line:
category = 'material_chrome'
elif 'ALPHA' in line:
cate... | parent'
else:
category = 'material_normal'
name = '"' + ns[2].replace('_', ' ')
idx = int(ns[4])
color = ns[6][1:]
edge = ns[8][1:]
cr = int(color[0:2], 16)
cg = int(color[2:4], 16)
cb = int(color[4:6], 16)
ca = 255
lumi = 0... |
#!/usr/bin/env python3
"""
Perform frequency analysis on text. This is already provided by !f, this script
exists for other reasons.
"""
import sys
import argparse
import re
from collections import Counter
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", t... | {highw}}) {}"
.format(letter, frequency,
"-" * int(width * frequency / highest),
highw=highw)
for letter, frequency in hist.most_common()))))
def histogram(text, start, interval):
ret... | interval])
if __name__ == "__main__":
args = parse_args()
plain = args.input.read()
for i in range(args.length):
print(printchart(histogram(plain, i, args.length), i, args.length))
|
# -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2017 CERN.
#
# INSPIRE 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 ... | of the GNU General Public License
# along with INSPIRE. If not, see <http://www.gnu.org/licenses/>.
#
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organiz | ation
# or submit itself to any jurisdiction.
"""RefExtract integration."""
from __future__ import absolute_import, division, print_function
|
from Confi | gParser import SafeConfigParser
def load_ini_file(file_name, defaults={}):
config = SafeConfigParser()
config.readfp(open(file_name))
results = {}
for section in config.sections():
for key, value in config.items(section):
results[section + '.' + key] = value
results.update(de... | turn results
|
.ElementTree as ET
import xml.dom.minidom
STATE_NONE = 0
STATE_DRAW = 1
STATE_DELETE = 2
POINT_RADIUS = 3
POINT_COLOR_CANDIDATE = (0,127,255)
LINE_COLOR_CANDIDATE = (0,127,255)
LINE_THICK_CANDIDATE = 2
LINE_COLOR = (0,192,0)
LINE_THICK = 2
windowName = "parking"
parkingName = "deib"
def point_inside_polygon(point,p... | "rectangles":[],
"ro | tatedRectangles":[],
}
cv2.setMouseCallback(windowName,onMouse,drawingStatus)
pressedKey = -1
while (pressedKey != ord('q')):
pressedKey = cv2.waitKey(0)
if (pressedKey==ord('n')):
drawingStatus['status'] = STATE_DRAW
drawingStatus['cand... |
# coding=utf-8
"""
Binary class deconstruct, reconstruct packet
"""
import copy
class Binary(object):
@staticmethod
def deconstruct_packet(packet):
"""
Replaces every bytearray in packet with a numbered placeholder.
:param packet:
:return: dict with packet and list of buffers
... | return data
if type(data) is list:
for i in xrange(len(data)):
data[i] = _reconstruct_packet(data[i])
return data
return data
packet['data'] = _reconstruct_packet(packet['data'])
| del packet['attachments']
return packet
@staticmethod
def remove_blobs(data):
def _remove_blobs(obj, cur_key=None, containing_obj=None):
if not obj:
return obj
try:
# Try to read it as a file
buf = bytearray(obj.rea... |
e(self, buddy, text):
self.emit('msg_buddy', buddy, text)
def update_turn(self):
self.set_sensitive(self.current_player == self.myself)
self.emit('change-turn', self.current_player)
def change_turn(self):
if len(self.players) <= 1:
self.current_player = self.players... | '1':
if self.last_flipped == -1 and identifier \
>= (len(self.model.grid) // 2):
return
if self.last_flipped != -1 and identifier \
< (len(self.model.grid) // 2):
return
# do not process flips when flipping back
... | ation):
self.emit('flip-card', identifier, full_animation)
if not signal:
self.emit('flip-card-signal', identifier)
snd = self.model.grid[identifier].get('snd', None)
if snd is not None:
sound_file = join(self.model.data.get('pathsnd'), snd)
... |
from distutils.core import setup
setup(
name='jenkins_cli_tool',
version='3.1',
packages=['cli', 'cli.startjob', 'cli.startAndMonitor', 'tests'],
url='https://github.com/hermco/jenkins_cli_tool',
license='MIT',
author='chermet',
author_email='chermet@axway.com',
de | scription='CLI tool for Jen | kins',
install_requires=[
'click',
'python-jenkins'
],
entry_points={
'console_scripts': [
'jenkins-cli-tool = cli.cli:entry_point'
]
}
)
|
#!/usr/bin/env python3
'''
* Copyright 2015 by Benjamin J. Land (a.k.a. BenLand100)
*
* This file is part of chatlogs.
*
* chatlogs 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 ... | GNU General Public License for more details.
*
* You should have received a copy of the GNU Genera | l Public License
* along with chatlogs. If not, see <http://www.gnu.org/licenses/>.
'''
import collections
import nltk
import string
import tools
import json
import sys
import re
import multiprocessing
import enchant
if len(sys.argv) < 5:
print('./wordprofile.py database num splittype maxlen src+')
print('\... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# Copyright (C) Gabriel Potter <gabriel@potter.fr>
# This program is published under a GPLv2 license
"""
Python 2 and 3 link classes.
"""
from __future__ import absolute_impor... | Ensure that the given object is bytes.
If the parameter is a packe | t, raw() should be preferred.
"""
if isinstance(x, str):
return x.encode()
return bytes(x)
if sys.version_info[0:2] <= (3, 4):
def plain_str(x):
"""Convert basic byte objects to str"""
if isinstance(x, bytes):
return x.decode(error... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.