Upload folder using huggingface_hub (part 38)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pool/shard002/Python/0025232_http_mixin.py +51 -0
- pool/shard002/Python/0025242_test_pluginmanager.py +90 -0
- pool/shard002/Python/0025243_group.py +64 -0
- pool/shard002/Python/0025247_getSynapseIDS.py +103 -0
- pool/shard002/Python/0025256_commands.py +53 -0
- pool/shard002/Python/0025257_hist.py +20 -0
- pool/shard002/Python/0025258_test_welcomedialog.py +40 -0
- pool/shard002/Python/0025265_tests.py +38 -0
- pool/shard002/Python/0025275_inputhook.py +170 -0
- pool/shard002/Python/0025279_vertex_attrib_integer_64bit.py +72 -0
- pool/shard002/Python/0025283_point.py +69 -0
- pool/shard002/Python/0025287_clausometer.py +96 -0
- pool/shard002/Python/0025290_Finding_a_Motif_in_DNA.py +32 -0
- pool/shard002/Python/0025292_graphline.py +41 -0
- pool/shard002/Python/0025294_dumpFunctionDefine.py +57 -0
- pool/shard002/Python/0025303_test_del_windows_host.py +53 -0
- pool/shard002/Python/0025305_para_handler.py +74 -0
- pool/shard002/Python/0025311_basepathstestcase.py +113 -0
- pool/shard002/Python/0025315_init__.py +261 -0
- pool/shard002/Python/0025319_synth.py +74 -0
- pool/shard002/Python/0025326_NLP11.py +13 -0
- pool/shard002/Python/0025327_bot.py +99 -0
- pool/shard002/Python/0025328_simple_model.py +52 -0
- pool/shard002/Python/0025330_main.py +173 -0
- pool/shard002/Python/0025331_American.py +50 -0
- pool/shard002/Python/0025335_admin.py +105 -0
- pool/shard002/Python/0025344_import_codex.py +185 -0
- pool/shard002/Python/0025345_check.py +48 -0
- pool/shard002/Python/0025356_flip.py +49 -0
- pool/shard002/Python/0025357_setup.py +238 -0
- pool/shard002/Python/0025359_transfer.py +238 -0
- pool/shard002/Python/0025361_load_as_driver.py +37 -0
- pool/shard002/Python/0025362_ptest.py +70 -0
- pool/shard002/Python/0025370_orderedset.py +92 -0
- pool/shard002/Python/0025372_custom_freeze_graph.py +69 -0
- pool/shard002/Python/0025379_routes.py +101 -0
- pool/shard002/Python/0025385_data_to_text_file.py +28 -0
- pool/shard002/Python/0025387_stats.py +85 -0
- pool/shard002/Python/0025391_urls.py +88 -0
- pool/shard002/Python/0025397_sitemap.py +45 -0
- pool/shard002/Python/0025398_test_parse_omim.py +109 -0
- pool/shard002/Python/0025400_sparql.py +103 -0
- pool/shard002/Python/0025403_handshake.py +133 -0
- pool/shard002/Python/0025409_vcftobedpeconverter_tests.py +62 -0
- pool/shard002/Python/0025418_feedback_tags.py +83 -0
- pool/shard002/Python/0025419_disk_filter.py +81 -0
- pool/shard002/Python/0025420_committees.py +68 -0
- pool/shard002/Python/0025434_kernel.py +186 -0
- pool/shard002/Python/0025443_get_oss.py +51 -0
- pool/shard002/Python/0025448_test1.py +159 -0
pool/shard002/Python/0025232_http_mixin.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
import httpretty
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class HttpMixin(object):
|
| 8 |
+
"""Mixin for tests which perform mocked http interactions"""
|
| 9 |
+
def setUp(self):
|
| 10 |
+
super(HttpMixin, self).setUp()
|
| 11 |
+
httpretty.enable()
|
| 12 |
+
|
| 13 |
+
def tearDown(self):
|
| 14 |
+
super(HttpMixin, self).tearDown()
|
| 15 |
+
httpretty.disable()
|
| 16 |
+
httpretty.reset()
|
| 17 |
+
|
| 18 |
+
def expect_json_http(self, json_dict=None, **kwargs):
|
| 19 |
+
"""Wraps httpretty.register_uri with some defaults for JSON"""
|
| 20 |
+
if json_dict is None:
|
| 21 |
+
json_dict = {"key": "value"}
|
| 22 |
+
kwargs['body'] = json.dumps(json_dict)
|
| 23 |
+
kwargs['content_type'] = 'text/json'
|
| 24 |
+
self.expect_http(**kwargs)
|
| 25 |
+
|
| 26 |
+
def expect_xml_http(self, xml_str=None, **kwargs):
|
| 27 |
+
"""Wraps httpretty.register_uri with some defaults for XML"""
|
| 28 |
+
if xml_str is None:
|
| 29 |
+
xml_str = '<ROOT></ROOT>'
|
| 30 |
+
kwargs['body'] = xml_str
|
| 31 |
+
kwargs['content_type'] = 'text/xml'
|
| 32 |
+
self.expect_http(**kwargs)
|
| 33 |
+
|
| 34 |
+
def expect_http(self, **kwargs):
|
| 35 |
+
"""Wraps httpretty.register_uri with some defaults"""
|
| 36 |
+
kwargs['body'] = kwargs.get('body', b'')
|
| 37 |
+
kwargs['content_type'] = kwargs.get('content_type',
|
| 38 |
+
'application/octet-stream')
|
| 39 |
+
kwargs['method'] = kwargs.get('method', httpretty.GET)
|
| 40 |
+
# Default to catching all requests
|
| 41 |
+
kwargs['uri'] = kwargs.get('uri', re.compile(".*"))
|
| 42 |
+
httpretty.register_uri(**kwargs)
|
| 43 |
+
|
| 44 |
+
def last_http_params(self):
|
| 45 |
+
return httpretty.last_request().querystring
|
| 46 |
+
|
| 47 |
+
def last_http_headers(self):
|
| 48 |
+
return httpretty.last_request().headers.dict
|
| 49 |
+
|
| 50 |
+
def last_http_body(self):
|
| 51 |
+
return httpretty.last_request().parsed_body
|
pool/shard002/Python/0025242_test_pluginmanager.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4
|
| 3 |
+
|
| 4 |
+
###############################################################################
|
| 5 |
+
# OpenLP - Open Source Lyrics Projection #
|
| 6 |
+
# --------------------------------------------------------------------------- #
|
| 7 |
+
# Copyright (c) 2008-2015 OpenLP Developers #
|
| 8 |
+
# --------------------------------------------------------------------------- #
|
| 9 |
+
# This program is free software; you can redistribute it and/or modify it #
|
| 10 |
+
# under the terms of the GNU General Public License as published by the Free #
|
| 11 |
+
# Software Foundation; version 2 of the License. #
|
| 12 |
+
# #
|
| 13 |
+
# This program is distributed in the hope that it will be useful, but WITHOUT #
|
| 14 |
+
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #
|
| 15 |
+
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #
|
| 16 |
+
# more details. #
|
| 17 |
+
# #
|
| 18 |
+
# You should have received a copy of the GNU General Public License along #
|
| 19 |
+
# with this program; if not, write to the Free Software Foundation, Inc., 59 #
|
| 20 |
+
# Temple Place, Suite 330, Boston, MA 02111-1307 USA #
|
| 21 |
+
###############################################################################
|
| 22 |
+
"""
|
| 23 |
+
Package to test the openlp.core.lib.pluginmanager package.
|
| 24 |
+
"""
|
| 25 |
+
import sys
|
| 26 |
+
import shutil
|
| 27 |
+
import gc
|
| 28 |
+
from tempfile import mkdtemp
|
| 29 |
+
from unittest import TestCase
|
| 30 |
+
|
| 31 |
+
from PyQt4 import QtGui
|
| 32 |
+
|
| 33 |
+
from openlp.core.common import Registry, Settings
|
| 34 |
+
from openlp.core.lib.pluginmanager import PluginManager
|
| 35 |
+
from tests.interfaces import MagicMock
|
| 36 |
+
from tests.helpers.testmixin import TestMixin
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TestPluginManager(TestCase, TestMixin):
|
| 40 |
+
"""
|
| 41 |
+
Test the PluginManager class
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def setUp(self):
|
| 45 |
+
"""
|
| 46 |
+
Some pre-test setup required.
|
| 47 |
+
"""
|
| 48 |
+
Settings.setDefaultFormat(Settings.IniFormat)
|
| 49 |
+
self.build_settings()
|
| 50 |
+
self.temp_dir = mkdtemp('openlp')
|
| 51 |
+
Settings().setValue('advanced/data path', self.temp_dir)
|
| 52 |
+
Registry.create()
|
| 53 |
+
Registry().register('service_list', MagicMock())
|
| 54 |
+
self.setup_application()
|
| 55 |
+
self.main_window = QtGui.QMainWindow()
|
| 56 |
+
Registry().register('main_window', self.main_window)
|
| 57 |
+
|
| 58 |
+
def tearDown(self):
|
| 59 |
+
Settings().remove('advanced/data path')
|
| 60 |
+
self.destroy_settings()
|
| 61 |
+
del self.main_window
|
| 62 |
+
# On windows we need to manually garbage collect to close sqlalchemy files
|
| 63 |
+
# to avoid errors when temporary files are deleted.
|
| 64 |
+
gc.collect()
|
| 65 |
+
shutil.rmtree(self.temp_dir)
|
| 66 |
+
|
| 67 |
+
def find_plugins_test(self):
|
| 68 |
+
"""
|
| 69 |
+
Test the find_plugins() method to ensure it imports the correct plugins
|
| 70 |
+
"""
|
| 71 |
+
# GIVEN: A plugin manager
|
| 72 |
+
plugin_manager = PluginManager()
|
| 73 |
+
|
| 74 |
+
# WHEN: We mock out sys.platform to make it return "darwin" and then find the plugins
|
| 75 |
+
old_platform = sys.platform
|
| 76 |
+
sys.platform = 'darwin'
|
| 77 |
+
plugin_manager.find_plugins()
|
| 78 |
+
sys.platform = old_platform
|
| 79 |
+
|
| 80 |
+
# THEN: We should find the "Songs", "Bibles", etc in the plugins list
|
| 81 |
+
plugin_names = [plugin.name for plugin in plugin_manager.plugins]
|
| 82 |
+
self.assertIn('songs', plugin_names, 'There should be a "songs" plugin')
|
| 83 |
+
self.assertIn('bibles', plugin_names, 'There should be a "bibles" plugin')
|
| 84 |
+
self.assertIn('presentations', plugin_names, 'There should be a "presentations" plugin')
|
| 85 |
+
self.assertIn('images', plugin_names, 'There should be a "images" plugin')
|
| 86 |
+
self.assertIn('media', plugin_names, 'There should be a "media" plugin')
|
| 87 |
+
self.assertIn('custom', plugin_names, 'There should be a "custom" plugin')
|
| 88 |
+
self.assertIn('songusage', plugin_names, 'There should be a "songusage" plugin')
|
| 89 |
+
self.assertIn('alerts', plugin_names, 'There should be a "alerts" plugin')
|
| 90 |
+
self.assertIn('remotes', plugin_names, 'There should be a "remotes" plugin')
|
pool/shard002/Python/0025243_group.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gitosis functions to find what groups a given user belongs to.
|
| 3 |
+
"""
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
_GROUP_PREFIX = 'group '
|
| 7 |
+
|
| 8 |
+
def _getMembership(config, user, seen):
|
| 9 |
+
"""
|
| 10 |
+
Internal implementation of getMembership.
|
| 11 |
+
Generate groups ``user`` is member of, according to ``config``.
|
| 12 |
+
Groups already seen are tracked by ``seen``.
|
| 13 |
+
|
| 14 |
+
:type config: RawConfigParser
|
| 15 |
+
:type user: str
|
| 16 |
+
:type seen: Set
|
| 17 |
+
"""
|
| 18 |
+
log = logging.getLogger('gitosis.group.getMembership')
|
| 19 |
+
|
| 20 |
+
for section in config.sections():
|
| 21 |
+
if not section.startswith(_GROUP_PREFIX):
|
| 22 |
+
continue
|
| 23 |
+
group = section[len(_GROUP_PREFIX):]
|
| 24 |
+
if group in seen:
|
| 25 |
+
continue
|
| 26 |
+
|
| 27 |
+
members = config.get(section, 'members', "").split()
|
| 28 |
+
|
| 29 |
+
# @all is the only group where membership needs to be
|
| 30 |
+
# bootstrapped like this, anything else gets started from the
|
| 31 |
+
# username itself
|
| 32 |
+
if (user in members
|
| 33 |
+
or '@all' in members):
|
| 34 |
+
log.debug('found %(user)r in %(group)r' % dict(
|
| 35 |
+
user=user,
|
| 36 |
+
group=group,
|
| 37 |
+
))
|
| 38 |
+
seen.add(group)
|
| 39 |
+
yield group
|
| 40 |
+
|
| 41 |
+
for member_of in _getMembership(
|
| 42 |
+
config, '@%s' % group, seen,
|
| 43 |
+
):
|
| 44 |
+
yield member_of
|
| 45 |
+
for member_of in _getMembership(
|
| 46 |
+
config, '@all', seen,
|
| 47 |
+
):
|
| 48 |
+
yield member_of
|
| 49 |
+
|
| 50 |
+
def getMembership(config, user):
|
| 51 |
+
"""
|
| 52 |
+
Generate groups ``user`` is member of, according to ``config``
|
| 53 |
+
|
| 54 |
+
:type config: RawConfigParser
|
| 55 |
+
:type user: str
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
seen = set()
|
| 59 |
+
for member_of in _getMembership(config, user, seen):
|
| 60 |
+
yield member_of
|
| 61 |
+
|
| 62 |
+
# everyone is always a member of group "all"
|
| 63 |
+
yield 'all'
|
| 64 |
+
|
pool/shard002/Python/0025247_getSynapseIDS.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2014 NeuroData (http://neurodata.io)
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import numpy as np
|
| 17 |
+
import urllib, urllib2
|
| 18 |
+
import cStringIO
|
| 19 |
+
import sys
|
| 20 |
+
import h5py
|
| 21 |
+
import tempfile
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
|
| 25 |
+
parser = argparse.ArgumentParser(description='Request a list of RAMON object ids that match specified type and status values')
|
| 26 |
+
parser.add_argument('--status', type=int, action="store", default=None )
|
| 27 |
+
parser.add_argument('--type', type=int, action="store", default=None )
|
| 28 |
+
parser.add_argument('--cutout', action="store", help='Cutout arguments of the form resolution/x1,x2/y1,y2/z1,z2.', default=None)
|
| 29 |
+
parser.add_argument('baseurl', action="store" )
|
| 30 |
+
parser.add_argument('token', action="store" )
|
| 31 |
+
|
| 32 |
+
result = parser.parse_args()
|
| 33 |
+
|
| 34 |
+
url = 'http://%s/emca/%s/list/' % ( result.baseurl, result.token )
|
| 35 |
+
if result.type != None:
|
| 36 |
+
url += 'type/%s/' % ( result.type )
|
| 37 |
+
if result.status != None:
|
| 38 |
+
url += 'status/%s/' % ( result.status )
|
| 39 |
+
|
| 40 |
+
print url
|
| 41 |
+
|
| 42 |
+
if not result.cutout:
|
| 43 |
+
|
| 44 |
+
# Get cube in question
|
| 45 |
+
try:
|
| 46 |
+
f = urllib2.urlopen ( url )
|
| 47 |
+
except urllib2.URLError, e:
|
| 48 |
+
print "Failed URL", url
|
| 49 |
+
print "Error %s" % (e.read())
|
| 50 |
+
sys.exit(0)
|
| 51 |
+
|
| 52 |
+
# POST if we have a cutout
|
| 53 |
+
else:
|
| 54 |
+
|
| 55 |
+
tmpfile = tempfile.NamedTemporaryFile ( )
|
| 56 |
+
h5f = h5py.File ( tmpfile.name )
|
| 57 |
+
|
| 58 |
+
[ resstr, xstr, ystr, zstr ] = result.cutout.split('/')
|
| 59 |
+
( xlowstr, xhighstr ) = xstr.split(',')
|
| 60 |
+
( ylowstr, yhighstr ) = ystr.split(',')
|
| 61 |
+
( zlowstr, zhighstr ) = zstr.split(',')
|
| 62 |
+
|
| 63 |
+
resolution = int(resstr)
|
| 64 |
+
xlow = int(xlowstr)
|
| 65 |
+
xhigh = int(xhighstr)
|
| 66 |
+
ylow = int(ylowstr)
|
| 67 |
+
yhigh = int(yhighstr)
|
| 68 |
+
zlow = int(zlowstr)
|
| 69 |
+
zhigh = int(zhighstr)
|
| 70 |
+
|
| 71 |
+
h5f.create_dataset ( "RESOLUTION", (1,), np.uint32, data=resolution )
|
| 72 |
+
h5f.create_dataset ( "XYZOFFSET", (3,), np.uint32, data=[xlow,ylow,zlow] )
|
| 73 |
+
h5f.create_dataset ( "CUTOUTSIZE", (3,), np.uint32, data=[xhigh-xlow,yhigh-ylow,zhigh-zlow] )
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
h5f.flush()
|
| 77 |
+
tmpfile.seek(0)
|
| 78 |
+
req = urllib2.Request ( url, tmpfile.read())
|
| 79 |
+
f = urllib2.urlopen(req)
|
| 80 |
+
except urllib2.URLError, e:
|
| 81 |
+
print "Failed URL", url
|
| 82 |
+
print "Error %s" % (e.read())
|
| 83 |
+
sys.exit(-1)
|
| 84 |
+
|
| 85 |
+
# Now we are processing the return. New tmpfile, new h5f
|
| 86 |
+
tmpfile = tempfile.NamedTemporaryFile ( )
|
| 87 |
+
tmpfile.write ( f.read() )
|
| 88 |
+
tmpfile.tell()
|
| 89 |
+
h5f = h5py.File ( tmpfile.name, driver='core', backing_store=False )
|
| 90 |
+
|
| 91 |
+
if h5f.get('ANNOIDS'):
|
| 92 |
+
if len(h5f['ANNOIDS']) != 0:
|
| 93 |
+
print "Found %s matching annotations." % ( len(h5f['ANNOIDS'][:]))
|
| 94 |
+
print "values = %s" % ( np.array(h5f['ANNOIDS'][:]) )
|
| 95 |
+
else:
|
| 96 |
+
print "Found no annotations matching type and status"
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
|
pool/shard002/Python/0025256_commands.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from __future__ import absolute_import, unicode_literals
|
| 3 |
+
from gaebusiness.gaeutil import SaveCommand, ModelSearchCommand
|
| 4 |
+
from gaeforms.ndb.form import ModelForm
|
| 5 |
+
from gaegraph.business_base import UpdateNode
|
| 6 |
+
from linguagem_app.model import Linguagem
|
| 7 |
+
|
| 8 |
+
class LinguagemPublicForm(ModelForm):
|
| 9 |
+
"""
|
| 10 |
+
Form used to show properties on app's home
|
| 11 |
+
"""
|
| 12 |
+
_model_class = Linguagem
|
| 13 |
+
_include = [Linguagem.descricao]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LinguagemForm(ModelForm):
|
| 17 |
+
"""
|
| 18 |
+
Form used to save and update operations on app's admin page
|
| 19 |
+
"""
|
| 20 |
+
_model_class = Linguagem
|
| 21 |
+
_include = [Linguagem.descricao]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LinguagemDetailForm(ModelForm):
|
| 25 |
+
"""
|
| 26 |
+
Form used to show entity details on app's admin page
|
| 27 |
+
"""
|
| 28 |
+
_model_class = Linguagem
|
| 29 |
+
_include = [Linguagem.creation,
|
| 30 |
+
Linguagem.descricao]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LinguagemShortForm(ModelForm):
|
| 34 |
+
"""
|
| 35 |
+
Form used to show entity short version on app's admin page, mainly for tables
|
| 36 |
+
"""
|
| 37 |
+
_model_class = Linguagem
|
| 38 |
+
_include = [Linguagem.creation,
|
| 39 |
+
Linguagem.descricao]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class SaveLinguagemCommand(SaveCommand):
|
| 43 |
+
_model_form_class = LinguagemForm
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class UpdateLinguagemCommand(UpdateNode):
|
| 47 |
+
_model_form_class = LinguagemForm
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class ListLinguagemCommand(ModelSearchCommand):
|
| 51 |
+
def __init__(self):
|
| 52 |
+
super(ListLinguagemCommand, self).__init__(Linguagem.query_by_creation())
|
| 53 |
+
|
pool/shard002/Python/0025257_hist.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# x.startswith("_")
|
| 3 |
+
f = open('/Users/yadvika/.bash_history')
|
| 4 |
+
l = f.readlines()
|
| 5 |
+
l.reverse()
|
| 6 |
+
short = []
|
| 7 |
+
cmdline_included = 0
|
| 8 |
+
for s in l:
|
| 9 |
+
if s.startswith("#"):
|
| 10 |
+
if cmdline_included == 1:
|
| 11 |
+
short.append(s.rstrip())
|
| 12 |
+
continue
|
| 13 |
+
# marked not-include unless we really add it to short
|
| 14 |
+
cmdline_included = 0
|
| 15 |
+
if s.rstrip() not in short:
|
| 16 |
+
cmdline_included = 1
|
| 17 |
+
short.append(s.rstrip())
|
| 18 |
+
short.reverse()
|
| 19 |
+
for s in short:
|
| 20 |
+
print s
|
pool/shard002/Python/0025258_test_welcomedialog.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test for welcome screen.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from PyQt4.QtGui import QAction
|
| 6 |
+
|
| 7 |
+
from ...resources import icon_loader
|
| 8 |
+
|
| 9 |
+
from ..welcomedialog import WelcomeDialog, decorate_welcome_icon
|
| 10 |
+
|
| 11 |
+
from ...gui.test import QAppTestCase
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestDialog(QAppTestCase):
|
| 15 |
+
def test_dialog(self):
|
| 16 |
+
d = WelcomeDialog()
|
| 17 |
+
loader = icon_loader()
|
| 18 |
+
icon = loader.get("icons/default-widget.svg")
|
| 19 |
+
action1 = QAction(decorate_welcome_icon(icon, "light-green"),
|
| 20 |
+
"one", self.app)
|
| 21 |
+
action2 = QAction(decorate_welcome_icon(icon, "orange"),
|
| 22 |
+
"two", self.app)
|
| 23 |
+
d.addRow([action1, action2])
|
| 24 |
+
|
| 25 |
+
action3 = QAction(decorate_welcome_icon(icon, "light-green"),
|
| 26 |
+
"three", self.app)
|
| 27 |
+
d.addRow([action3])
|
| 28 |
+
|
| 29 |
+
self.assertTrue(d.buttonAt(1, 0).defaultAction() == action3)
|
| 30 |
+
|
| 31 |
+
d.show()
|
| 32 |
+
action = [None]
|
| 33 |
+
|
| 34 |
+
def p(a):
|
| 35 |
+
print str(a.text())
|
| 36 |
+
action[0] = a
|
| 37 |
+
|
| 38 |
+
d.triggered.connect(p)
|
| 39 |
+
self.app.exec_()
|
| 40 |
+
self.assertIs(action[0], d.triggeredAction())
|
pool/shard002/Python/0025265_tests.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from connectionmon import ConnectionMonitor
|
| 4 |
+
|
| 5 |
+
class ConnectionMonitorTest(unittest.TestCase):
|
| 6 |
+
""""""
|
| 7 |
+
|
| 8 |
+
def test_get_tcp(self):
|
| 9 |
+
"""Tests that procfs can get tcp connections"""
|
| 10 |
+
monitor = ConnectionMonitor()
|
| 11 |
+
self.assertIn('rem_address',monitor._get_tcp()[0])
|
| 12 |
+
|
| 13 |
+
def test_get_nonblank_connections(self):
|
| 14 |
+
"""Tests that NULL addresses in procfs are removed."""
|
| 15 |
+
monitor = ConnectionMonitor()
|
| 16 |
+
ip = []
|
| 17 |
+
for item in monitor._get_nonblank_connections(monitor._get_tcp()):
|
| 18 |
+
ip.append(item['rem_address'][0])
|
| 19 |
+
self.assertNotIn('0.0.0.0',ip)
|
| 20 |
+
|
| 21 |
+
def test_clean_connections(self):
|
| 22 |
+
"""Tests the ability to remove useless data."""
|
| 23 |
+
monitor = ConnectionMonitor()
|
| 24 |
+
conn = monitor._get_nonblank_connections(monitor._get_tcp())
|
| 25 |
+
conn = monitor._clean_connections(conn, 'tcp')
|
| 26 |
+
self.assertEqual(len(conn[0]),9)
|
| 27 |
+
self.assertEqual('local_address' in conn[0], True)
|
| 28 |
+
self.assertEqual('local_port' in conn[0], True)
|
| 29 |
+
self.assertEqual('rem_address' in conn[0], True)
|
| 30 |
+
self.assertEqual('rem_port' in conn[0], True)
|
| 31 |
+
self.assertEqual('domain' in conn[0], True)
|
| 32 |
+
self.assertEqual('name' in conn[0], True)
|
| 33 |
+
self.assertEqual('transport_layer' in conn[0], True)
|
| 34 |
+
self.assertEqual('time_established' in conn[0], True)
|
| 35 |
+
self.assertEqual('time_connected' in conn[0], True)
|
| 36 |
+
|
| 37 |
+
if __name__ == '__main__':
|
| 38 |
+
unittest.main()
|
pool/shard002/Python/0025275_inputhook.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Similar to `PyOS_InputHook` of the Python API, we can plug in an input hook in
|
| 3 |
+
the asyncio event loop.
|
| 4 |
+
|
| 5 |
+
The way this works is by using a custom 'selector' that runs the other event
|
| 6 |
+
loop until the real selector is ready.
|
| 7 |
+
|
| 8 |
+
It's the responsibility of this event hook to return when there is input ready.
|
| 9 |
+
There are two ways to detect when input is ready:
|
| 10 |
+
|
| 11 |
+
The inputhook itself is a callable that receives an `InputHookContext`. This
|
| 12 |
+
callable should run the other event loop, and return when the main loop has
|
| 13 |
+
stuff to do. There are two ways to detect when to return:
|
| 14 |
+
|
| 15 |
+
- Call the `input_is_ready` method periodically. Quit when this returns `True`.
|
| 16 |
+
|
| 17 |
+
- Add the `fileno` as a watch to the external eventloop. Quit when file descriptor
|
| 18 |
+
becomes readable. (But don't read from it.)
|
| 19 |
+
|
| 20 |
+
Note that this is not the same as checking for `sys.stdin.fileno()`. The
|
| 21 |
+
eventloop of prompt-toolkit allows thread-based executors, for example for
|
| 22 |
+
asynchronous autocompletion. When the completion for instance is ready, we
|
| 23 |
+
also want prompt-toolkit to gain control again in order to display that.
|
| 24 |
+
"""
|
| 25 |
+
import asyncio
|
| 26 |
+
import os
|
| 27 |
+
import select
|
| 28 |
+
import selectors
|
| 29 |
+
import threading
|
| 30 |
+
from asyncio import AbstractEventLoop, get_event_loop
|
| 31 |
+
from selectors import BaseSelector
|
| 32 |
+
from typing import Callable
|
| 33 |
+
|
| 34 |
+
from prompt_toolkit.utils import is_windows
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
"new_eventloop_with_inputhook",
|
| 38 |
+
"set_eventloop_with_inputhook",
|
| 39 |
+
"InputHookSelector",
|
| 40 |
+
"InputHookContext",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def new_eventloop_with_inputhook(
|
| 45 |
+
inputhook: Callable[["InputHookContext"], None]
|
| 46 |
+
) -> AbstractEventLoop:
|
| 47 |
+
"""
|
| 48 |
+
Create a new event loop with the given inputhook.
|
| 49 |
+
"""
|
| 50 |
+
selector = InputHookSelector(selectors.DefaultSelector(), inputhook)
|
| 51 |
+
loop = asyncio.SelectorEventLoop(selector)
|
| 52 |
+
return loop
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def set_eventloop_with_inputhook(
|
| 56 |
+
inputhook: Callable[["InputHookContext"], None]
|
| 57 |
+
) -> AbstractEventLoop:
|
| 58 |
+
"""
|
| 59 |
+
Create a new event loop with the given inputhook, and activate it.
|
| 60 |
+
"""
|
| 61 |
+
loop = new_eventloop_with_inputhook(inputhook)
|
| 62 |
+
asyncio.set_event_loop(loop)
|
| 63 |
+
return loop
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class InputHookSelector(BaseSelector):
|
| 67 |
+
"""
|
| 68 |
+
Usage:
|
| 69 |
+
|
| 70 |
+
selector = selectors.SelectSelector()
|
| 71 |
+
loop = asyncio.SelectorEventLoop(InputHookSelector(selector, inputhook))
|
| 72 |
+
asyncio.set_event_loop(loop)
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self, selector: BaseSelector, inputhook: Callable[["InputHookContext"], None]
|
| 77 |
+
) -> None:
|
| 78 |
+
self.selector = selector
|
| 79 |
+
self.inputhook = inputhook
|
| 80 |
+
self._r, self._w = os.pipe()
|
| 81 |
+
|
| 82 |
+
def register(self, fileobj, events, data=None):
|
| 83 |
+
return self.selector.register(fileobj, events, data=data)
|
| 84 |
+
|
| 85 |
+
def unregister(self, fileobj):
|
| 86 |
+
return self.selector.unregister(fileobj)
|
| 87 |
+
|
| 88 |
+
def modify(self, fileobj, events, data=None):
|
| 89 |
+
return self.selector.modify(fileobj, events, data=None)
|
| 90 |
+
|
| 91 |
+
def select(self, timeout=None):
|
| 92 |
+
# If there are tasks in the current event loop,
|
| 93 |
+
# don't run the input hook.
|
| 94 |
+
if len(get_event_loop()._ready) > 0:
|
| 95 |
+
return self.selector.select(timeout=timeout)
|
| 96 |
+
|
| 97 |
+
ready = False
|
| 98 |
+
result = None
|
| 99 |
+
|
| 100 |
+
# Run selector in other thread.
|
| 101 |
+
def run_selector() -> None:
|
| 102 |
+
nonlocal ready, result
|
| 103 |
+
result = self.selector.select(timeout=timeout)
|
| 104 |
+
os.write(self._w, b"x")
|
| 105 |
+
ready = True
|
| 106 |
+
|
| 107 |
+
th = threading.Thread(target=run_selector)
|
| 108 |
+
th.start()
|
| 109 |
+
|
| 110 |
+
def input_is_ready() -> bool:
|
| 111 |
+
return ready
|
| 112 |
+
|
| 113 |
+
# Call inputhook.
|
| 114 |
+
# The inputhook function is supposed to return when our selector
|
| 115 |
+
# becomes ready. The inputhook can do that by registering the fd in its
|
| 116 |
+
# own loop, or by checking the `input_is_ready` function regularly.
|
| 117 |
+
self.inputhook(InputHookContext(self._r, input_is_ready))
|
| 118 |
+
|
| 119 |
+
# Flush the read end of the pipe.
|
| 120 |
+
try:
|
| 121 |
+
# Before calling 'os.read', call select.select. This is required
|
| 122 |
+
# when the gevent monkey patch has been applied. 'os.read' is never
|
| 123 |
+
# monkey patched and won't be cooperative, so that would block all
|
| 124 |
+
# other select() calls otherwise.
|
| 125 |
+
# See: http://www.gevent.org/gevent.os.html
|
| 126 |
+
|
| 127 |
+
# Note: On Windows, this is apparently not an issue.
|
| 128 |
+
# However, if we would ever want to add a select call, it
|
| 129 |
+
# should use `windll.kernel32.WaitForMultipleObjects`,
|
| 130 |
+
# because `select.select` can't wait for a pipe on Windows.
|
| 131 |
+
if not is_windows():
|
| 132 |
+
select.select([self._r], [], [], None)
|
| 133 |
+
|
| 134 |
+
os.read(self._r, 1024)
|
| 135 |
+
except OSError:
|
| 136 |
+
# This happens when the window resizes and a SIGWINCH was received.
|
| 137 |
+
# We get 'Error: [Errno 4] Interrupted system call'
|
| 138 |
+
# Just ignore.
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
# Wait for the real selector to be done.
|
| 142 |
+
th.join()
|
| 143 |
+
return result
|
| 144 |
+
|
| 145 |
+
def close(self) -> None:
|
| 146 |
+
"""
|
| 147 |
+
Clean up resources.
|
| 148 |
+
"""
|
| 149 |
+
if self._r:
|
| 150 |
+
os.close(self._r)
|
| 151 |
+
os.close(self._w)
|
| 152 |
+
|
| 153 |
+
self._r = self._w = -1
|
| 154 |
+
self.selector.close()
|
| 155 |
+
|
| 156 |
+
def get_map(self):
|
| 157 |
+
return self.selector.get_map()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class InputHookContext:
|
| 161 |
+
"""
|
| 162 |
+
Given as a parameter to the inputhook.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def __init__(self, fileno: int, input_is_ready: Callable[[], bool]) -> None:
|
| 166 |
+
self._fileno = fileno
|
| 167 |
+
self.input_is_ready = input_is_ready
|
| 168 |
+
|
| 169 |
+
def fileno(self) -> int:
|
| 170 |
+
return self._fileno
|
pool/shard002/Python/0025279_vertex_attrib_integer_64bit.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''Autogenerated by xml_generate script, do not edit!'''
|
| 2 |
+
from OpenGL import platform as _p, arrays
|
| 3 |
+
# Code generation uses this
|
| 4 |
+
from OpenGL.raw.GL import _types as _cs
|
| 5 |
+
# End users want this...
|
| 6 |
+
from OpenGL.raw.GL._types import *
|
| 7 |
+
from OpenGL.raw.GL import _errors
|
| 8 |
+
from OpenGL.constant import Constant as _C
|
| 9 |
+
|
| 10 |
+
import ctypes
|
| 11 |
+
_EXTENSION_NAME = 'GL_NV_vertex_attrib_integer_64bit'
|
| 12 |
+
def _f( function ):
|
| 13 |
+
return _p.createFunction( function,_p.PLATFORM.GL,'GL_NV_vertex_attrib_integer_64bit',error_checker=_errors._error_checker)
|
| 14 |
+
GL_INT64_NV=_C('GL_INT64_NV',0x140E)
|
| 15 |
+
GL_UNSIGNED_INT64_NV=_C('GL_UNSIGNED_INT64_NV',0x140F)
|
| 16 |
+
@_f
|
| 17 |
+
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLint64Array)
|
| 18 |
+
def glGetVertexAttribLi64vNV(index,pname,params):pass
|
| 19 |
+
@_f
|
| 20 |
+
@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLuint64Array)
|
| 21 |
+
def glGetVertexAttribLui64vNV(index,pname,params):pass
|
| 22 |
+
@_f
|
| 23 |
+
@_p.types(None,_cs.GLuint,_cs.GLint64EXT)
|
| 24 |
+
def glVertexAttribL1i64NV(index,x):pass
|
| 25 |
+
@_f
|
| 26 |
+
@_p.types(None,_cs.GLuint,arrays.GLint64Array)
|
| 27 |
+
def glVertexAttribL1i64vNV(index,v):pass
|
| 28 |
+
@_f
|
| 29 |
+
@_p.types(None,_cs.GLuint,_cs.GLuint64EXT)
|
| 30 |
+
def glVertexAttribL1ui64NV(index,x):pass
|
| 31 |
+
@_f
|
| 32 |
+
@_p.types(None,_cs.GLuint,arrays.GLuint64Array)
|
| 33 |
+
def glVertexAttribL1ui64vNV(index,v):pass
|
| 34 |
+
@_f
|
| 35 |
+
@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT)
|
| 36 |
+
def glVertexAttribL2i64NV(index,x,y):pass
|
| 37 |
+
@_f
|
| 38 |
+
@_p.types(None,_cs.GLuint,arrays.GLint64Array)
|
| 39 |
+
def glVertexAttribL2i64vNV(index,v):pass
|
| 40 |
+
@_f
|
| 41 |
+
@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT)
|
| 42 |
+
def glVertexAttribL2ui64NV(index,x,y):pass
|
| 43 |
+
@_f
|
| 44 |
+
@_p.types(None,_cs.GLuint,arrays.GLuint64Array)
|
| 45 |
+
def glVertexAttribL2ui64vNV(index,v):pass
|
| 46 |
+
@_f
|
| 47 |
+
@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT)
|
| 48 |
+
def glVertexAttribL3i64NV(index,x,y,z):pass
|
| 49 |
+
@_f
|
| 50 |
+
@_p.types(None,_cs.GLuint,arrays.GLint64Array)
|
| 51 |
+
def glVertexAttribL3i64vNV(index,v):pass
|
| 52 |
+
@_f
|
| 53 |
+
@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT)
|
| 54 |
+
def glVertexAttribL3ui64NV(index,x,y,z):pass
|
| 55 |
+
@_f
|
| 56 |
+
@_p.types(None,_cs.GLuint,arrays.GLuint64Array)
|
| 57 |
+
def glVertexAttribL3ui64vNV(index,v):pass
|
| 58 |
+
@_f
|
| 59 |
+
@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT)
|
| 60 |
+
def glVertexAttribL4i64NV(index,x,y,z,w):pass
|
| 61 |
+
@_f
|
| 62 |
+
@_p.types(None,_cs.GLuint,arrays.GLint64Array)
|
| 63 |
+
def glVertexAttribL4i64vNV(index,v):pass
|
| 64 |
+
@_f
|
| 65 |
+
@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT)
|
| 66 |
+
def glVertexAttribL4ui64NV(index,x,y,z,w):pass
|
| 67 |
+
@_f
|
| 68 |
+
@_p.types(None,_cs.GLuint,arrays.GLuint64Array)
|
| 69 |
+
def glVertexAttribL4ui64vNV(index,v):pass
|
| 70 |
+
@_f
|
| 71 |
+
@_p.types(None,_cs.GLuint,_cs.GLint,_cs.GLenum,_cs.GLsizei)
|
| 72 |
+
def glVertexAttribLFormatNV(index,size,type,stride):pass
|
pool/shard002/Python/0025283_point.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logger = logging.getLogger(__name__)
|
| 5 |
+
|
| 6 |
+
class Point(np.ndarray):
|
| 7 |
+
"""
|
| 8 |
+
n-dimensional point used for locations.
|
| 9 |
+
inherits +, -, * (as dot-product)
|
| 10 |
+
> p1 = Point([1, 2])
|
| 11 |
+
> p2 = Point([4, 5])
|
| 12 |
+
> p1 + p2
|
| 13 |
+
Point([5, 7])
|
| 14 |
+
See ``test()`` for more usage.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __new__(cls, coordinates=None, **kwargs):
|
| 18 |
+
"""
|
| 19 |
+
:param cls:
|
| 20 |
+
:param input_array: Defaults to 2d origin
|
| 21 |
+
"""
|
| 22 |
+
if not coordinates:
|
| 23 |
+
coordinates = (0, 0)
|
| 24 |
+
logger.info("No coordinates given for point. Defaulting to 2d origin (0,0)")
|
| 25 |
+
obj = np.asarray(coordinates).view(cls)
|
| 26 |
+
return obj
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def x(self):
|
| 30 |
+
return self[0]
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def y(self):
|
| 34 |
+
return self[1]
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def z(self):
|
| 38 |
+
"""
|
| 39 |
+
:return: 3rd dimension element. 0 if not defined
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
return self[2]
|
| 43 |
+
except IndexError:
|
| 44 |
+
return 0
|
| 45 |
+
|
| 46 |
+
def __eq__(self, other):
|
| 47 |
+
return np.array_equal(self, other)
|
| 48 |
+
|
| 49 |
+
def __ne__(self, other):
|
| 50 |
+
return not np.array_equal(self, other)
|
| 51 |
+
|
| 52 |
+
def __iter__(self):
|
| 53 |
+
for x in np.nditer(self):
|
| 54 |
+
yield x.item()
|
| 55 |
+
|
| 56 |
+
def __repr__(self):
|
| 57 |
+
return str(self.serialized)
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def serialized(self):
|
| 61 |
+
s = {'coordinates': tuple(pos.item() for pos in np.nditer(self))}
|
| 62 |
+
return s
|
| 63 |
+
|
| 64 |
+
def dist(self, other):
|
| 65 |
+
"""
|
| 66 |
+
Both points must have the same dimensions
|
| 67 |
+
:return: Euclidean distance
|
| 68 |
+
"""
|
| 69 |
+
return np.linalg.norm(self - other)
|
pool/shard002/Python/0025287_clausometer.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Python Twitter monitor for Raspberry Pi
|
| 3 |
+
#
|
| 4 |
+
# See https://learn.sparkfun.com/tutorials/raspberry-pi-twitter-monitor
|
| 5 |
+
#
|
| 6 |
+
# For Twitter keys, see:
|
| 7 |
+
# https://developer.twitter.com/
|
| 8 |
+
# https://apps.twitter.com/
|
| 9 |
+
#
|
| 10 |
+
# Provided under MIT licence. (mostly meaning: use it for anything, don't sue me for anything)
|
| 11 |
+
|
| 12 |
+
import time
|
| 13 |
+
import RPi.GPIO as GPIO
|
| 14 |
+
from twython import TwythonStreamer
|
| 15 |
+
from threading import Thread
|
| 16 |
+
|
| 17 |
+
# Search terms
|
| 18 |
+
TERMS = '#xmas, #santa, #christmas, #navidad' # separate terms with commas. '#xmas, #holiday, #christmas'
|
| 19 |
+
|
| 20 |
+
# Christmas spirit tracker: 0 to 100
|
| 21 |
+
spirit = 50.0
|
| 22 |
+
|
| 23 |
+
GPIO.setmode(GPIO.BOARD)
|
| 24 |
+
# set GPIO18 to be a PWM output = pin 12
|
| 25 |
+
GPIO.setup(12, GPIO.OUT)
|
| 26 |
+
servo = GPIO.PWM(12, 50)
|
| 27 |
+
servo.start(7.5)
|
| 28 |
+
|
| 29 |
+
# Twitter application authentication
|
| 30 |
+
TWITTER_CONSUMER_KEY = 'xxxxxxx'
|
| 31 |
+
TWITTER_CONSUMER_SECRET = 'xxxxxxx'
|
| 32 |
+
TWITTER_ACCESS_TOKEN = 'xxxxxxx'
|
| 33 |
+
TWITTER_ACCESS_TOKEN_SECRET = 'xxxxxxx'
|
| 34 |
+
|
| 35 |
+
# To stop twitter thread on app exit
|
| 36 |
+
stopping = False
|
| 37 |
+
|
| 38 |
+
# Setup callbacks from Twython Streamer
|
| 39 |
+
class ClausometerStreamer(TwythonStreamer):
|
| 40 |
+
def on_success(self, data):
|
| 41 |
+
global spirit, stopping
|
| 42 |
+
if stopping:
|
| 43 |
+
#print('disconnecting from twitter...')
|
| 44 |
+
self.disconnect()
|
| 45 |
+
if 'text' in data:
|
| 46 |
+
#print (data['text'].encode('utf-8'))
|
| 47 |
+
#print ('spirit++')
|
| 48 |
+
spirit = spirit + 1.0
|
| 49 |
+
if spirit > 100.0 :
|
| 50 |
+
spirit = 100.0
|
| 51 |
+
|
| 52 |
+
def start_twitter_monitoring():
|
| 53 |
+
global stream
|
| 54 |
+
stream = ClausometerStreamer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)
|
| 55 |
+
while True:
|
| 56 |
+
try:
|
| 57 |
+
stream.statuses.filter(track=TERMS)
|
| 58 |
+
except:
|
| 59 |
+
print("Twitter oops. carrying on.")
|
| 60 |
+
# this can happen when connection is lost
|
| 61 |
+
# the while loop will start it up again
|
| 62 |
+
|
| 63 |
+
# 0 degrees = 2.5
|
| 64 |
+
# 90 degrees = 7.5
|
| 65 |
+
# 180 degrees = 12.5
|
| 66 |
+
previousDutyCycle = 3.0
|
| 67 |
+
def setServoPercent(percent):
|
| 68 |
+
global previousDutyCycle, servo
|
| 69 |
+
newDutyCycle = 3.0 + percent / 14.3
|
| 70 |
+
#print('New duty cycle = ', newDutyCycle)
|
| 71 |
+
increment = (newDutyCycle - previousDutyCycle) / 100.0
|
| 72 |
+
for step in range(0, 100, 1):
|
| 73 |
+
servo.ChangeDutyCycle(previousDutyCycle + increment*step)
|
| 74 |
+
time.sleep(0.02)
|
| 75 |
+
previousDutyCycle = newDutyCycle
|
| 76 |
+
|
| 77 |
+
def spirit_fader(): # reduces spirit over time
|
| 78 |
+
global spirit
|
| 79 |
+
while True:
|
| 80 |
+
time.sleep(1)
|
| 81 |
+
if spirit > 0 :
|
| 82 |
+
spirit = spirit - 1.0
|
| 83 |
+
|
| 84 |
+
# Start the Clausometer
|
| 85 |
+
try:
|
| 86 |
+
Thread(target=start_twitter_monitoring).start()
|
| 87 |
+
Thread(target=spirit_fader).start()
|
| 88 |
+
while True:
|
| 89 |
+
print ('spirit = ', spirit)
|
| 90 |
+
setServoPercent(spirit)
|
| 91 |
+
|
| 92 |
+
except KeyboardInterrupt:
|
| 93 |
+
stopping = True
|
| 94 |
+
print ('Exiting app')
|
| 95 |
+
#GPIO.cleanup()
|
| 96 |
+
|
pool/shard002/Python/0025290_Finding_a_Motif_in_DNA.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
class Namespace:
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
ns = Namespace()
|
| 10 |
+
ns.dna = sys.argv[1]
|
| 11 |
+
repeat = sys.argv[2]
|
| 12 |
+
positions = []
|
| 13 |
+
cur_pos = 0
|
| 14 |
+
|
| 15 |
+
while(1):
|
| 16 |
+
try:
|
| 17 |
+
# index throws an exception when it does not find string :/
|
| 18 |
+
p = ns.dna.index(repeat)
|
| 19 |
+
except ValueError:
|
| 20 |
+
break
|
| 21 |
+
|
| 22 |
+
if p:
|
| 23 |
+
positions.append(p + cur_pos + 1) # 1 added for string numbering to start with 1
|
| 24 |
+
cur_pos += p + 1
|
| 25 |
+
ns.dna = ns.dna[p + 1:]
|
| 26 |
+
else: break
|
| 27 |
+
|
| 28 |
+
print str(positions)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if __name__ == "__main__":
|
| 32 |
+
main()
|
pool/shard002/Python/0025292_graphline.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
|
| 3 |
+
#
|
| 4 |
+
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
|
| 5 |
+
# http://www.kamaelia.org/AUTHORS - please extend this file,
|
| 6 |
+
# not this notice.
|
| 7 |
+
#
|
| 8 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 9 |
+
# you may not use this file except in compliance with the License.
|
| 10 |
+
# You may obtain a copy of the License at
|
| 11 |
+
#
|
| 12 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 13 |
+
#
|
| 14 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 15 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 16 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 17 |
+
# See the License for the specific language governing permissions and
|
| 18 |
+
# limitations under the License.
|
| 19 |
+
|
| 20 |
+
dir = "/home/jlei/Kamaelia/files"
|
| 21 |
+
|
| 22 |
+
for i in range(1,16):
|
| 23 |
+
imgs.append(dir + '/' + str(i) + '.jpg')
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Graphline(
|
| 27 |
+
CHOOSER = Chooser(imgs),
|
| 28 |
+
IMAGE = Image(size=(800,600), position=(8,48)),
|
| 29 |
+
NEXT = Button(caption="Next", msg="NEXT", position=(72,8) ),
|
| 30 |
+
PREVIOUS = Button(caption="Previous", msg="PREV" ,position=(8,8) ),
|
| 31 |
+
FIRST = Button(caption="First", msg="FIRST",position=(256,8) ),
|
| 32 |
+
LAST = Button(caption="Last", msg="LAST" ,position=(320,8) ),
|
| 33 |
+
linkages = {
|
| 34 |
+
("NEXT", "outbox") : ("CHOOSER", "inbox"),
|
| 35 |
+
("PREVIOUS", "outbox") : ("CHOOSER", "inbox"),
|
| 36 |
+
("FIRST", "outbox") : ("CHOOSER", "inbox"),
|
| 37 |
+
("LAST", "outbox") : ("CHOOSER", "inbox"),
|
| 38 |
+
|
| 39 |
+
("CHOOSER", "outbox") : ("IMAGE", "inbox"),
|
| 40 |
+
}
|
| 41 |
+
).run()
|
pool/shard002/Python/0025294_dumpFunctionDefine.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__author__ = 'Sean Yu'
|
| 2 |
+
'''created @2015/6/16'''
|
| 3 |
+
import os, sys
|
| 4 |
+
pardir =os.path.dirname(os.path.realpath(os.getcwd()))
|
| 5 |
+
libpath = os.path.sep.join([pardir,'lib'])
|
| 6 |
+
if libpath not in sys.path:
|
| 7 |
+
sys.path.insert(0,libpath)
|
| 8 |
+
import inspect
|
| 9 |
+
from Case import Case
|
| 10 |
+
caseInit = inspect.getsource(Case.__init__)
|
| 11 |
+
print(caseInit)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
#dump description of function
|
| 16 |
+
import pydoc
|
| 17 |
+
des = pydoc.help(Case.__init__)
|
| 18 |
+
class testclass( object):
|
| 19 |
+
'''class description'''
|
| 20 |
+
def fun1(self,aaa,
|
| 21 |
+
bbb,
|
| 22 |
+
ccc='aaa'):
|
| 23 |
+
'''fun1 description
|
| 24 |
+
line2
|
| 25 |
+
line3
|
| 26 |
+
line4'''
|
| 27 |
+
print(aaa)
|
| 28 |
+
def fun2(self):
|
| 29 |
+
'''fun2 description'''
|
| 30 |
+
print('function2')
|
| 31 |
+
def doc(self, name):
|
| 32 |
+
return pydoc.help(name)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
obj = testclass()
|
| 36 |
+
aaa =obj.doc(obj.fun1)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
members = dir(obj)
|
| 41 |
+
print('#'*16)
|
| 42 |
+
pydoc.Doc()
|
| 43 |
+
des =pydoc.describe(obj)
|
| 44 |
+
print(des)
|
| 45 |
+
print('#'*16)
|
| 46 |
+
for m in sorted(members):
|
| 47 |
+
if m.startswith('__'):
|
| 48 |
+
pass
|
| 49 |
+
else:
|
| 50 |
+
print(m+'\n\t')
|
| 51 |
+
fundef = inspect.getsource(eval('obj.%s'%m))
|
| 52 |
+
fundefstr = fundef[:fundef.find(':')]
|
| 53 |
+
listoffun =fundef.split('\n')
|
| 54 |
+
print(fundefstr)
|
| 55 |
+
ret = eval('obj.%s.__doc__'%m)
|
| 56 |
+
if ret:
|
| 57 |
+
print('\t'+'\n\t'.join(ret.split('\n')))
|
pool/shard002/Python/0025303_test_del_windows_host.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python2.6
|
| 2 |
+
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
|
| 3 |
+
# ex: set expandtab softtabstop=4 shiftwidth=4:
|
| 4 |
+
#
|
| 5 |
+
# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor
|
| 6 |
+
#
|
| 7 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 8 |
+
# you may not use this file except in compliance with the License.
|
| 9 |
+
# You may obtain a copy of the License at
|
| 10 |
+
#
|
| 11 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 12 |
+
#
|
| 13 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 14 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 15 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 16 |
+
# See the License for the specific language governing permissions and
|
| 17 |
+
# limitations under the License.
|
| 18 |
+
"""Module for testing the del windows host command."""
|
| 19 |
+
|
| 20 |
+
import unittest
|
| 21 |
+
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
import utils
|
| 24 |
+
utils.import_depends()
|
| 25 |
+
|
| 26 |
+
from brokertest import TestBrokerCommand
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TestDelWindowsHost(TestBrokerCommand):
|
| 30 |
+
|
| 31 |
+
def testfailnonwindows(self):
|
| 32 |
+
command = "del windows host --hostname unittest00.one-nyp.ms.com"
|
| 33 |
+
err = self.badrequesttest(command.split(" "))
|
| 34 |
+
self.matchoutput(err,
|
| 35 |
+
"Host unittest00.one-nyp.ms.com "
|
| 36 |
+
"has archetype aquilon, expected windows.",
|
| 37 |
+
command)
|
| 38 |
+
|
| 39 |
+
def testdelunittest01(self):
|
| 40 |
+
self.dsdb_expect_delete(self.net.unknown[0].usable[10])
|
| 41 |
+
command = "del windows host --hostname unittest01.one-nyp.ms.com"
|
| 42 |
+
(out, err) = self.successtest(command.split(" "))
|
| 43 |
+
self.assertEmptyOut(out, command)
|
| 44 |
+
self.dsdb_verify()
|
| 45 |
+
|
| 46 |
+
def testverifydelunittest01(self):
|
| 47 |
+
command = "show host --hostname unittest01.one-nyp.ms.com"
|
| 48 |
+
self.notfoundtest(command.split(" "))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == '__main__':
|
| 52 |
+
suite = unittest.TestLoader().loadTestsFromTestCase(TestDelWindowsHost)
|
| 53 |
+
unittest.TextTestRunner(verbosity=2).run(suite)
|
pool/shard002/Python/0025305_para_handler.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2021 OpenMotics BV
|
| 2 |
+
#
|
| 3 |
+
# This program is free software: you can redistribute it and/or modify
|
| 4 |
+
# it under the terms of the GNU Affero General Public License as
|
| 5 |
+
# published by the Free Software Foundation, either version 3 of the
|
| 6 |
+
# License, or (at your option) any later version.
|
| 7 |
+
#
|
| 8 |
+
# This program is distributed in the hope that it will be useful,
|
| 9 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 10 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 11 |
+
# GNU Affero General Public License for more details.
|
| 12 |
+
#
|
| 13 |
+
# You should have received a copy of the GNU Affero General Public License
|
| 14 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 15 |
+
"""
|
| 16 |
+
Para packet handler
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from esafe.rfid.idtronic_M890.para.para_packet import ParaPacketType, ParaPacket, CardType
|
| 20 |
+
from esafe.rfid.idtronic_M890.para.para_exception import ParaException
|
| 21 |
+
|
| 22 |
+
import logging
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
if False: # MyPy
|
| 26 |
+
from typing import Any, Dict, Callable
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# @Injectable.named('para_packet_handler')
|
| 30 |
+
class ParaPacketHandler(object):
|
| 31 |
+
""" Packet handler for the ParaPackets, this can be extended in the future for multiple requests, and for keeping state of the reader"""
|
| 32 |
+
# At this point only one kind of packet is implemented, but can be extended in the future
|
| 33 |
+
|
| 34 |
+
def __init__(self, new_scan_callback):
|
| 35 |
+
self.handlers = {
|
| 36 |
+
ParaPacketType.AutoListCard.value: self.handle_auto_list
|
| 37 |
+
} # type: Dict[ParaPacketType.value, Callable[[ParaPacket], Any]]
|
| 38 |
+
self.new_scan_callback = new_scan_callback
|
| 39 |
+
|
| 40 |
+
def handle_packet(self, para_packet):
|
| 41 |
+
# type: (ParaPacket) -> Any
|
| 42 |
+
packet_type = para_packet.header.command_type
|
| 43 |
+
if packet_type in self.handlers:
|
| 44 |
+
handler = self.handlers[packet_type]
|
| 45 |
+
return handler(para_packet)
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
def handle_auto_list(self, para_packet):
|
| 49 |
+
# type: (ParaPacket) -> Any
|
| 50 |
+
_ = self
|
| 51 |
+
# Ignore the empty list packets
|
| 52 |
+
if not para_packet.data:
|
| 53 |
+
return
|
| 54 |
+
# General scan parameters
|
| 55 |
+
card_type = para_packet.data[0]
|
| 56 |
+
# scan_period = para_packet.data[1]
|
| 57 |
+
# scanned_antenna = para_packet.data[2]
|
| 58 |
+
# notice_type = para_packet.data[3]
|
| 59 |
+
# reserved_future_use = para_packet.data[4]
|
| 60 |
+
|
| 61 |
+
if card_type in [CardType.ISO14443A.value, CardType.ISO14443B.value]:
|
| 62 |
+
# auto reporting format for ISO14443 cards
|
| 63 |
+
# ATQL = para_packet.data[5]
|
| 64 |
+
# ATQH = para_packet.data[6]
|
| 65 |
+
# SAK = para_packet.data[7]
|
| 66 |
+
uuid_length = para_packet.data[8]
|
| 67 |
+
logger.debug('Detected new ISO14443 card scan: Card type: {}, uuid_length: {}'.format(card_type, uuid_length))
|
| 68 |
+
scanned_uuid = para_packet.data[-uuid_length:]
|
| 69 |
+
elif card_type == CardType.ISO15693.value:
|
| 70 |
+
scanned_uuid = para_packet.data[5:]
|
| 71 |
+
else:
|
| 72 |
+
raise ParaException('Cannot handle auto list packet: Cannot detect card type')
|
| 73 |
+
scanned_uuid_str = ''.join('{:02X}'.format(x) for x in scanned_uuid)
|
| 74 |
+
self.new_scan_callback(scanned_uuid_str)
|
pool/shard002/Python/0025311_basepathstestcase.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: UTF-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Basepaths test cases
|
| 4 |
+
@author: Aurélien Gâteau <mail@agateau.com>
|
| 5 |
+
@license: GPL v3 or later
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from yokadi.core import basepaths
|
| 14 |
+
from yokadi.tests.yokaditestcase import YokadiTestCase
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class BasePathsUnixTestCase(YokadiTestCase):
|
| 18 |
+
def setUp(self):
|
| 19 |
+
YokadiTestCase.setUp(self)
|
| 20 |
+
self._oldWindows = basepaths._WINDOWS
|
| 21 |
+
basepaths._WINDOWS = False
|
| 22 |
+
|
| 23 |
+
def tearDown(self):
|
| 24 |
+
basepaths._WINDOWS = self._oldWindows
|
| 25 |
+
YokadiTestCase.tearDown(self)
|
| 26 |
+
|
| 27 |
+
def testMigrateOldDb(self):
|
| 28 |
+
oldDb = Path(self.testHomeDir) / '.yokadi.db'
|
| 29 |
+
newDb = Path(basepaths.getDbPath(basepaths.getDataDir()))
|
| 30 |
+
|
| 31 |
+
oldDb.touch()
|
| 32 |
+
|
| 33 |
+
basepaths.migrateOldDb(str(newDb))
|
| 34 |
+
self.assertFalse(oldDb.exists())
|
| 35 |
+
self.assertTrue(newDb.exists())
|
| 36 |
+
|
| 37 |
+
def testMigrateNothingToDo(self):
|
| 38 |
+
newDb = Path(basepaths.getDbPath(basepaths.getDataDir()))
|
| 39 |
+
basepaths.migrateOldDb(str(newDb))
|
| 40 |
+
basepaths.migrateOldHistory()
|
| 41 |
+
self.assertFalse(newDb.exists())
|
| 42 |
+
|
| 43 |
+
def testMigrateOldDbFails(self):
|
| 44 |
+
oldDb = Path(self.testHomeDir) / '.yokadi.db'
|
| 45 |
+
newDb = Path(basepaths.getDbPath(basepaths.getDataDir()))
|
| 46 |
+
|
| 47 |
+
oldDb.touch()
|
| 48 |
+
newDb.parent.mkdir(parents=True)
|
| 49 |
+
newDb.touch()
|
| 50 |
+
|
| 51 |
+
self.assertRaises(basepaths.MigrationException, basepaths.migrateOldDb, str(newDb))
|
| 52 |
+
|
| 53 |
+
def testMigrateOldHistory(self):
|
| 54 |
+
old = Path(self.testHomeDir) / '.yokadi_history'
|
| 55 |
+
new = Path(basepaths.getHistoryPath())
|
| 56 |
+
|
| 57 |
+
old.touch()
|
| 58 |
+
|
| 59 |
+
basepaths.migrateOldHistory()
|
| 60 |
+
self.assertFalse(old.exists())
|
| 61 |
+
self.assertTrue(new.exists())
|
| 62 |
+
|
| 63 |
+
def testMigrateOldHistoryOverwriteNew(self):
|
| 64 |
+
old = Path(self.testHomeDir) / '.yokadi_history'
|
| 65 |
+
new = Path(basepaths.getHistoryPath())
|
| 66 |
+
|
| 67 |
+
with old.open('w') as f:
|
| 68 |
+
f.write('old')
|
| 69 |
+
new.parent.mkdir(parents=True)
|
| 70 |
+
with new.open('w') as f:
|
| 71 |
+
f.write('new')
|
| 72 |
+
|
| 73 |
+
basepaths.migrateOldHistory()
|
| 74 |
+
self.assertFalse(old.exists())
|
| 75 |
+
with new.open() as f:
|
| 76 |
+
newData = f.read()
|
| 77 |
+
self.assertEqual(newData, 'old')
|
| 78 |
+
|
| 79 |
+
def testHistoryEnvVar(self):
|
| 80 |
+
path = "foo"
|
| 81 |
+
os.environ["YOKADI_HISTORY"] = path
|
| 82 |
+
self.assertEqual(basepaths.getHistoryPath(), path)
|
| 83 |
+
|
| 84 |
+
def testDbEnvVar(self):
|
| 85 |
+
path = "foo"
|
| 86 |
+
os.environ["YOKADI_DB"] = path
|
| 87 |
+
self.assertEqual(basepaths.getDbPath(basepaths.getDataDir()), path)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class BasePathsWindowsTestCase(YokadiTestCase):
|
| 91 |
+
def setUp(self):
|
| 92 |
+
YokadiTestCase.setUp(self)
|
| 93 |
+
self._oldWindows = basepaths._WINDOWS
|
| 94 |
+
basepaths._WINDOWS = True
|
| 95 |
+
self.testAppDataDir = tempfile.mkdtemp(prefix="yokadi-basepaths-testcase")
|
| 96 |
+
os.environ["APPDATA"] = self.testAppDataDir
|
| 97 |
+
|
| 98 |
+
def tearDown(self):
|
| 99 |
+
shutil.rmtree(self.testAppDataDir)
|
| 100 |
+
basepaths._WINDOWS = self._oldWindows
|
| 101 |
+
YokadiTestCase.tearDown(self)
|
| 102 |
+
|
| 103 |
+
def testGetCacheDir(self):
|
| 104 |
+
expected = os.path.join(self.testAppDataDir, "yokadi", "cache")
|
| 105 |
+
self.assertEqual(basepaths.getCacheDir(), expected)
|
| 106 |
+
|
| 107 |
+
def testGetDataDir(self):
|
| 108 |
+
expected = os.path.join(self.testAppDataDir, "yokadi", "data")
|
| 109 |
+
self.assertEqual(basepaths.getDataDir(), expected)
|
| 110 |
+
|
| 111 |
+
def testOldHistoryPath(self):
|
| 112 |
+
expected = os.path.join(self.testAppDataDir, ".yokadi_history")
|
| 113 |
+
self.assertEqual(basepaths._getOldHistoryPath(), expected)
|
pool/shard002/Python/0025315_init__.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Part of bubble. See LICENSE file for full copyright and licensing details.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
"""store: for getting and putting files
|
| 6 |
+
currently only json
|
| 7 |
+
and the highly experimental ".bubble" format for testing and comparing purposes"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
from ... import Bubble
|
| 12 |
+
from ..counter import Counter
|
| 13 |
+
from ..zipit import zipit
|
| 14 |
+
from ..inside_try import inside_try
|
| 15 |
+
from ..generators import make_gen, make_stamping_gen
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def load_storage_type_class(ctx, storage_type):
|
| 19 |
+
ctx.gbc.say('loading module for storage type:' +
|
| 20 |
+
storage_type, verbosity=10)
|
| 21 |
+
if storage_type == '.json':
|
| 22 |
+
return load_storage_type_class_json(ctx)
|
| 23 |
+
if storage_type == '.jsonl':
|
| 24 |
+
return load_storage_type_class_jsonl(ctx)
|
| 25 |
+
|
| 26 |
+
def load_storage_type_class_json(ctx):
|
| 27 |
+
from .storage_type_json import JsonKV as STOREM
|
| 28 |
+
ctx.gbc.say('storage module loaded', stuff=STOREM, verbosity=10)
|
| 29 |
+
return STOREM
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_storage_type_class_jsonl(ctx):
|
| 33 |
+
from .storage_type_jsonl import JsonLinesKV as STOREM
|
| 34 |
+
ctx.gbc.say('storage module loaded', stuff=STOREM, verbosity=10)
|
| 35 |
+
return STOREM
|
| 36 |
+
|
| 37 |
+
def get_file_name(ctx, path, step, stage, stype):
|
| 38 |
+
ctx.gbc.say('get_file_name:', stuff=(path, step, stage, stype))
|
| 39 |
+
|
| 40 |
+
storage_file = path + 'remember/' + step + '_' + stage
|
| 41 |
+
storage_file += '.' + stype
|
| 42 |
+
ctx.gbc.say('get_file_name:res:' + storage_file)
|
| 43 |
+
return storage_file
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_file_info(ctx, storage_file_name):
|
| 47 |
+
file_name, file_extension = os.path.splitext(storage_file_name)
|
| 48 |
+
ret = {'file_name': file_name,
|
| 49 |
+
'file_extension': file_extension}
|
| 50 |
+
|
| 51 |
+
ctx.gbc.say('file_info:', stuff=ret)
|
| 52 |
+
return ret
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@inside_try
|
| 56 |
+
def get_bubble(ctx, bubble_file_name):
|
| 57 |
+
# this is the proof of existence for a bubble content directory
|
| 58 |
+
# TODO:
|
| 59 |
+
# its not in the bubble format yet, when converted to bubble format,
|
| 60 |
+
# we can use something like get_file(...,home+"/.bubble")
|
| 61 |
+
|
| 62 |
+
ctx.gbc.say('get_bubble:' + bubble_file_name, verbosity=10)
|
| 63 |
+
if bubble_file_name.endswith('.bubble'):
|
| 64 |
+
with open(bubble_file_name) as bubble_file:
|
| 65 |
+
content = bubble_file.read()
|
| 66 |
+
ctx.say('get_bubble:content:' + str(content), verbosity=200)
|
| 67 |
+
return content
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_file(ctx, storage_file_name, first_only=False):
|
| 71 |
+
ctx.gbc.say('get_file:' + storage_file_name, verbosity=10)
|
| 72 |
+
file_info = get_file_info(ctx, storage_file_name)
|
| 73 |
+
storem = load_storage_type_class(ctx, file_info['file_extension'])
|
| 74 |
+
|
| 75 |
+
data = None
|
| 76 |
+
|
| 77 |
+
if not os.path.exists(storage_file_name):
|
| 78 |
+
if first_only:
|
| 79 |
+
ctx.gbc.say('first only: returning empty dict, no such file:' +
|
| 80 |
+
storage_file_name, verbosity=10)
|
| 81 |
+
return {}
|
| 82 |
+
else:
|
| 83 |
+
ctx.gbc.say('returning empty list, no such file:' +
|
| 84 |
+
storage_file_name, verbosity=10)
|
| 85 |
+
return {'lod_gen': make_gen(ctx),
|
| 86 |
+
'total': 0,
|
| 87 |
+
'status': 'no such file:' + storage_file_name}
|
| 88 |
+
|
| 89 |
+
bkv = storem(storage_file_name)
|
| 90 |
+
bkv.set_parent(ctx.gbc)
|
| 91 |
+
data = bkv.load()
|
| 92 |
+
count = Counter()
|
| 93 |
+
count.set_parent(ctx.gbc)
|
| 94 |
+
|
| 95 |
+
ctx.gbc.say('get file:data', stuff=data, verbosity=1000)
|
| 96 |
+
ctx.gbc.say('get file:data:type:' + str(type(data)), verbosity=100)
|
| 97 |
+
|
| 98 |
+
if data:
|
| 99 |
+
ctx.gbc.say('get file:data', stuff=data, verbosity=2000)
|
| 100 |
+
else:
|
| 101 |
+
ctx.gbc.cry('get file:there is no data', verbosity=10)
|
| 102 |
+
|
| 103 |
+
gen_types_23 = ["<type 'generator'>", # py2
|
| 104 |
+
"<class 'generator'>"] # py3
|
| 105 |
+
|
| 106 |
+
if str(type(data)) in gen_types_23:
|
| 107 |
+
return {'lod_gen': data,
|
| 108 |
+
'total': 'unknown from generator'}
|
| 109 |
+
if 'data' in data and str(type(data['data'])) in gen_types_23:
|
| 110 |
+
return {'lod_gen': data['data'],
|
| 111 |
+
'total': 'unknown from generator'}
|
| 112 |
+
|
| 113 |
+
if isinstance(data, dict) and 'data' in data and isinstance(data['data'], list):
|
| 114 |
+
if first_only:
|
| 115 |
+
if len(data['data']) >= 1:
|
| 116 |
+
return data['data'][0]
|
| 117 |
+
else:
|
| 118 |
+
return {}
|
| 119 |
+
return {'lod_gen': make_gen(ctx, data['data'], count),
|
| 120 |
+
'total': count.get_total()}
|
| 121 |
+
elif isinstance(data, list):
|
| 122 |
+
# inspect.isgeneratorfunction(data):
|
| 123 |
+
return {'lod_gen': make_gen(ctx, data, count),
|
| 124 |
+
'total': 'unknown from generator'}
|
| 125 |
+
else:
|
| 126 |
+
ctx.gbc.cry('data is not dict with a data list, or list',
|
| 127 |
+
stuff=data, verbosity=10)
|
| 128 |
+
ctx.gbc.say('make gen and return', verbosity=10)
|
| 129 |
+
return {'lod_gen': make_gen(ctx, data, count),
|
| 130 |
+
'total': 'unknown from generator',
|
| 131 |
+
'last_resort': True}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@inside_try
|
| 135 |
+
def put_file(ctx, storage_file_name, data=[], remove_first=False, archive=True, add_timestamp=True, full_data=True):
|
| 136 |
+
|
| 137 |
+
# TODO: ensure no data ->no file
|
| 138 |
+
ret = {}
|
| 139 |
+
ret['total'] = 'unknown total'
|
| 140 |
+
count = Counter()
|
| 141 |
+
count.set_parent(ctx.gbc)
|
| 142 |
+
data = make_stamping_gen(ctx.gbc, data, full_data, count)
|
| 143 |
+
# generator calling should happen in STOREC
|
| 144 |
+
|
| 145 |
+
ctx.gbc.say('count', stuff=count, verbosity=100)
|
| 146 |
+
ctx.say('count.get_total:', stuff=count.get_total(), verbosity=10)
|
| 147 |
+
|
| 148 |
+
file_info = get_file_info(ctx, storage_file_name)
|
| 149 |
+
|
| 150 |
+
storec = load_storage_type_class(ctx, file_info['file_extension'])
|
| 151 |
+
|
| 152 |
+
if not storec:
|
| 153 |
+
ctx.gbc.cry("cannot load storage module for file", verbosity=10)
|
| 154 |
+
return False
|
| 155 |
+
else:
|
| 156 |
+
ctx.gbc.say("will use loaded storage module for file",
|
| 157 |
+
stuff=storec, verbosity=10)
|
| 158 |
+
|
| 159 |
+
ctx.gbc.say('put_file:' + storage_file_name, verbosity=10)
|
| 160 |
+
ctx.gbc.say('put_file:.bubble', verbosity=999)
|
| 161 |
+
bkv = storec(storage_file_name, reset=remove_first)
|
| 162 |
+
bkv.set_parent(ctx.gbc)
|
| 163 |
+
ctx.gbc.say('bubble data type:' + str(type(data)), verbosity=1000)
|
| 164 |
+
ret['res'] = bkv.dump(data, full_data)
|
| 165 |
+
ctx.gbc.say('counter', stuff=count.get_total(), verbosity=1)
|
| 166 |
+
|
| 167 |
+
bkv.close()
|
| 168 |
+
zipped = False
|
| 169 |
+
if archive:
|
| 170 |
+
zipped = zipit(ctx, storage_file_name)
|
| 171 |
+
ret['zipped'] = zipped
|
| 172 |
+
ret['total'] = count.get_total()
|
| 173 |
+
ctx.gbc.say('put_file:return', stuff=ret, verbosity=100)
|
| 174 |
+
return ret
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class BubbleKV(Bubble):
|
| 178 |
+
|
| 179 |
+
"""store and retrieve a List of dictionaries in any file based type.
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
def __init__(self,
|
| 183 |
+
file_name='__bubble_kvdb_data_tmp.unknown_type',
|
| 184 |
+
name='BubbleKV',
|
| 185 |
+
reset=False):
|
| 186 |
+
Bubble.__init__(self, name=name)
|
| 187 |
+
|
| 188 |
+
self.say(file_name, verbosity=999)
|
| 189 |
+
self._file_name = file_name
|
| 190 |
+
|
| 191 |
+
self._count = 0
|
| 192 |
+
self._kcount = 0
|
| 193 |
+
self._vcount = 0
|
| 194 |
+
self._kvcount = 0
|
| 195 |
+
self._can_dump_generator = False
|
| 196 |
+
self._reset = reset
|
| 197 |
+
self.reset()
|
| 198 |
+
|
| 199 |
+
def dump(self, lod=[], full_data=True):
|
| 200 |
+
self.say('dumping:' + self._file_name, verbosity=1)
|
| 201 |
+
ret = {}
|
| 202 |
+
|
| 203 |
+
if self._can_dump_generator:
|
| 204 |
+
try:
|
| 205 |
+
ret = self._dump(lod)
|
| 206 |
+
return ret
|
| 207 |
+
except Exception as e:
|
| 208 |
+
ret['error'] = 'cannot dump data to file %s' % self._file_name
|
| 209 |
+
ret['exception'] = e
|
| 210 |
+
return ret
|
| 211 |
+
|
| 212 |
+
ndata = []
|
| 213 |
+
for item in lod:
|
| 214 |
+
try:
|
| 215 |
+
self._encode_for_try({'test_enc': item})
|
| 216 |
+
ndata.append(item)
|
| 217 |
+
except Exception as encexpt:
|
| 218 |
+
self.cry('skipped: cannot encode item: ' +
|
| 219 |
+
str(encexpt), stuff=item)
|
| 220 |
+
data_to_dump = {'data': ndata}
|
| 221 |
+
|
| 222 |
+
ret['notdumped'] = True
|
| 223 |
+
if not self._dump:
|
| 224 |
+
self.cry('dumping, there is no _dump method', verbosity=1)
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
ret = self._dump(data_to_dump)
|
| 228 |
+
return ret
|
| 229 |
+
except Exception as e:
|
| 230 |
+
ret['error'] = 'cannot dump data to file %s' % self._file_name
|
| 231 |
+
ret['exception'] = e
|
| 232 |
+
return ret
|
| 233 |
+
|
| 234 |
+
def load(self):
|
| 235 |
+
self.say('loading:' + self._file_name, verbosity=1)
|
| 236 |
+
if os.path.exists(self._file_name):
|
| 237 |
+
if not self._load:
|
| 238 |
+
self.cry('loading, there is no _load method', verbosity=1)
|
| 239 |
+
res = self._load()
|
| 240 |
+
else:
|
| 241 |
+
res = []
|
| 242 |
+
self.say(
|
| 243 |
+
'loading:file does not exist, returning empty list', verbosity=1)
|
| 244 |
+
|
| 245 |
+
self.say('loading:res type=' + str(type(res)), verbosity=1)
|
| 246 |
+
self.say('loading:res:', stuff=res, verbosity=10001)
|
| 247 |
+
|
| 248 |
+
return res
|
| 249 |
+
|
| 250 |
+
def close(self):
|
| 251 |
+
pass
|
| 252 |
+
|
| 253 |
+
def reset(self):
|
| 254 |
+
if self._reset:
|
| 255 |
+
if os.path.exists(self._file_name):
|
| 256 |
+
self.say('reset, removing:' + self._file_name)
|
| 257 |
+
os.remove(self._file_name)
|
| 258 |
+
else:
|
| 259 |
+
self.say('reset, there is no file yet:' + self._file_name)
|
| 260 |
+
else:
|
| 261 |
+
self.say('no reset:' + self._file_name)
|
pool/shard002/Python/0025319_synth.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""This script is used to synthesize generated parts of this library."""
|
| 16 |
+
|
| 17 |
+
import synthtool as s
|
| 18 |
+
from synthtool import gcp
|
| 19 |
+
|
| 20 |
+
gapic = gcp.GAPICGenerator()
|
| 21 |
+
common = gcp.CommonTemplates()
|
| 22 |
+
version = 'v1'
|
| 23 |
+
|
| 24 |
+
# ----------------------------------------------------------------------------
|
| 25 |
+
# Generate cloudbuild GAPIC layer
|
| 26 |
+
# ----------------------------------------------------------------------------
|
| 27 |
+
library = gapic.py_library(
|
| 28 |
+
'cloudbuild',
|
| 29 |
+
version,
|
| 30 |
+
config_path='/google/devtools/cloudbuild/artman_cloudbuild.yaml',
|
| 31 |
+
generator_args=["--dev_samples"],
|
| 32 |
+
include_protos=True
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
s.move(
|
| 36 |
+
library,
|
| 37 |
+
excludes=[
|
| 38 |
+
'docs/index.rst',
|
| 39 |
+
'nox*.py',
|
| 40 |
+
'setup.py',
|
| 41 |
+
'setup.cfg',
|
| 42 |
+
'README.rst'
|
| 43 |
+
'**/*.proto'
|
| 44 |
+
'google/cloud/devtools/__init__.py' # declare this as a namespace package
|
| 45 |
+
],
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Move protos to the right directory
|
| 49 |
+
s.move(library / "google/cloud/cloudbuild_v1/proto/*.proto", "google/cloud/devtools/cloudbuild_v1/proto")
|
| 50 |
+
|
| 51 |
+
# Fix up imports
|
| 52 |
+
s.replace(
|
| 53 |
+
["google/**/*.py", "tests/unit/**/*.py"],
|
| 54 |
+
r"from google.devtools.cloudbuild_v1.proto import ",
|
| 55 |
+
r"from google.cloud.devtools.cloudbuild_v1.proto import ",
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Rename package to `google-cloud-build`
|
| 60 |
+
s.replace(
|
| 61 |
+
["**/*.rst", "*/**/*.py", "**/*.md"],
|
| 62 |
+
"google-cloud-cloudbuild",
|
| 63 |
+
"google-cloud-build"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
# ----------------------------------------------------------------------------
|
| 67 |
+
# Add templated files
|
| 68 |
+
# ----------------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
# coverage level is low because of missing coverage for __init__.py files
|
| 71 |
+
templated_files = common.py_library(unit_cov_level=65, cov_level=65)
|
| 72 |
+
s.move(templated_files)
|
| 73 |
+
|
| 74 |
+
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
|
pool/shard002/Python/0025326_NLP11.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
def expand():
|
| 6 |
+
in_file = 'hightemp.txt'
|
| 7 |
+
with open(in_file, 'r') as f:
|
| 8 |
+
for line in f.readlines():
|
| 9 |
+
print(re.sub('\t+', ' ', line.rstrip()))
|
| 10 |
+
f.close()
|
| 11 |
+
|
| 12 |
+
if __name__ == '__main__':
|
| 13 |
+
expand()
|
pool/shard002/Python/0025327_bot.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tweepy
|
| 2 |
+
from variable_stuff import *
|
| 3 |
+
import requests, bs4
|
| 4 |
+
from PIL import ImageFont
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from PIL import ImageDraw
|
| 7 |
+
|
| 8 |
+
#
|
| 9 |
+
# abstract --> image; adapted from https://gist.github.com/destan/5540702
|
| 10 |
+
#
|
| 11 |
+
|
| 12 |
+
def text2png(text, fullpath, leftpadding = 6, upperpadding=6, rightpadding = 3, width = 500):
|
| 13 |
+
|
| 14 |
+
font = ImageFont.truetype("font.ttf", 20)
|
| 15 |
+
text = text.replace('\r\n', '')#.replace('\n', ' ' + '\uFFFD' + ' ')
|
| 16 |
+
|
| 17 |
+
lines = []
|
| 18 |
+
line = ""
|
| 19 |
+
|
| 20 |
+
for word in text.split():
|
| 21 |
+
if font.getsize( line + ' ' + word )[0] <= (width - rightpadding - leftpadding):
|
| 22 |
+
line += ' ' + word
|
| 23 |
+
else: #start a new line
|
| 24 |
+
lines.append( line[1:] ) #slice the white space in the begining of the line
|
| 25 |
+
line = ' ' + word
|
| 26 |
+
|
| 27 |
+
if len(line) != 0:
|
| 28 |
+
lines.append( line[1:] ) #add the last line
|
| 29 |
+
|
| 30 |
+
line_height = font.getsize(text)[1]
|
| 31 |
+
img_height = line_height * len(lines) + 12
|
| 32 |
+
|
| 33 |
+
img = Image.new("RGB", (width, img_height), "#FFF")
|
| 34 |
+
draw = ImageDraw.Draw(img)
|
| 35 |
+
|
| 36 |
+
for line in lines:
|
| 37 |
+
draw.text( (leftpadding, upperpadding), line, "#000", font=font)
|
| 38 |
+
upperpadding += line_height
|
| 39 |
+
|
| 40 |
+
img.save(fullpath)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
|
| 45 |
+
# twitter auth info
|
| 46 |
+
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
|
| 47 |
+
auth.set_access_token(access_token, access_token_secret)
|
| 48 |
+
api = tweepy.API(auth)
|
| 49 |
+
|
| 50 |
+
# repec page with last papers; jel=d82 is mechanism design code
|
| 51 |
+
web_page = requests.get('https://econpapers.repec.org/scripts/search.pf?sort=date;jel=' + jel_codes + '&iframes=no')
|
| 52 |
+
web_page_text = bs4.BeautifulSoup(web_page.text, "html.parser")
|
| 53 |
+
|
| 54 |
+
# get tweets to be able to check if paper was tweeted already
|
| 55 |
+
tweets = api.user_timeline(id=user_id, count=1)
|
| 56 |
+
|
| 57 |
+
# get parts of web_page with each paper (they're in a list)
|
| 58 |
+
parsed_lists = web_page_text.find_all('li')
|
| 59 |
+
|
| 60 |
+
# check each paper if it was tweeted already till reach the last one that was tweeted
|
| 61 |
+
papers_titles = [None] * 20
|
| 62 |
+
papers_links = [None] * 20
|
| 63 |
+
|
| 64 |
+
for paper in range(0, 20):
|
| 65 |
+
# extract title from webpage (they're in bold)
|
| 66 |
+
papers_titles[paper] = parsed_lists[paper].find_next('a').getText()
|
| 67 |
+
# cut long titles to fit in a tweet
|
| 68 |
+
if len(papers_titles[paper]) > 116:
|
| 69 |
+
papers_titles[paper] = papers_titles[paper][0:115] + "…"
|
| 70 |
+
papers_links[paper] = "https://econpapers.repec.org" + parsed_lists[paper].find_next('a')['href']
|
| 71 |
+
|
| 72 |
+
if tweets:
|
| 73 |
+
# if length of paper's title is less than length of tweet,
|
| 74 |
+
# then could be the right tweet, since link adds to length
|
| 75 |
+
# can't compare directly because then could get out of range for tweet
|
| 76 |
+
# + only check last tweet
|
| 77 |
+
# -2 appears because twitter adds "…" symbol sometimes and we need to cut it off to make comparison ok
|
| 78 |
+
if len(papers_titles[paper]) < len(tweets[0].text):
|
| 79 |
+
if papers_titles[paper][0:-2] == tweets[0].text[0:int(len(papers_titles[paper])) - 2]:
|
| 80 |
+
# get the number of last paper tweeted
|
| 81 |
+
last_tweeted_paper = paper
|
| 82 |
+
break
|
| 83 |
+
else:
|
| 84 |
+
last_tweeted_paper = 19
|
| 85 |
+
|
| 86 |
+
for paper in reversed(range(0,last_tweeted_paper)):
|
| 87 |
+
|
| 88 |
+
paper_page = requests.get(papers_links[paper])
|
| 89 |
+
paper_page.encoding = paper_page.apparent_encoding
|
| 90 |
+
paper_page_text = bs4.BeautifulSoup(paper_page.text, "html.parser")
|
| 91 |
+
if paper_page_text.find(text="Abstract:"):
|
| 92 |
+
abstract = paper_page_text.find(text="Abstract:").next_element
|
| 93 |
+
text2png(abstract, 'abstract.png')
|
| 94 |
+
api.update_with_media("abstract.png", papers_titles[paper] + " " + papers_links[paper])
|
| 95 |
+
else:
|
| 96 |
+
api.update_status(papers_titles[paper] + " " + papers_links[paper])
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
pool/shard002/Python/0025328_simple_model.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__author__ = 'Federico Vaggi'
|
| 2 |
+
|
| 3 |
+
n_vars = 1
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def simple_model(y, t, *args):
|
| 7 |
+
p = args[0]
|
| 8 |
+
|
| 9 |
+
#*! Parameters Start
|
| 10 |
+
k_deg = p[0]
|
| 11 |
+
k_synt = p[1]
|
| 12 |
+
#*! Parameters End
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
#*! Variables Start
|
| 16 |
+
_y = y[0]
|
| 17 |
+
#*! Variables End
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#*! Differential Equations Start
|
| 21 |
+
d_y = k_synt - k_deg * _y
|
| 22 |
+
#*! Differential Equations End
|
| 23 |
+
return d_y
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__ == '__main__':
|
| 27 |
+
from scipy.integrate import odeint
|
| 28 |
+
import numpy as np
|
| 29 |
+
import matplotlib.pyplot as plt
|
| 30 |
+
init_conditions = [0]
|
| 31 |
+
param_idx = {'k_deg': 0, 'k_synt': 1}
|
| 32 |
+
param_vector = np.array([0.001, 0.01])
|
| 33 |
+
t_sim = np.linspace(0, 100, 100)
|
| 34 |
+
low_deg = odeint(simple_model, init_conditions, t_sim, args=(param_idx, None, param_vector))
|
| 35 |
+
t_exp = np.array([0. , 11.11111111, 22.22222222, 33.33333333,
|
| 36 |
+
44.44444444, 55.55555556, 66.66666667, 77.77777778,
|
| 37 |
+
88.88888889, 100.])
|
| 38 |
+
t_idx = np.searchsorted(t_sim, t_exp)
|
| 39 |
+
print t_sim[t_idx]
|
| 40 |
+
print low_deg[t_idx].flatten()
|
| 41 |
+
|
| 42 |
+
print '_____________________________________________________________________________________'
|
| 43 |
+
|
| 44 |
+
param_vector = np.array([0.01, 0.01])
|
| 45 |
+
high_deg = odeint(simple_model, init_conditions, t_sim, args=(param_idx, None, param_vector))
|
| 46 |
+
plt.plot(t_sim, high_deg, 'r-')
|
| 47 |
+
plt.plot(t_sim, low_deg, 'b-')
|
| 48 |
+
|
| 49 |
+
t_idx = np.searchsorted(t_sim, np.arange(5, 95, 3.5))
|
| 50 |
+
print t_sim[t_idx]
|
| 51 |
+
print high_deg[t_idx].flatten()
|
| 52 |
+
|
pool/shard002/Python/0025330_main.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
Copyright 2010-2012 Asidev s.r.l.
|
| 5 |
+
|
| 6 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
you may not use this file except in compliance with the License.
|
| 8 |
+
You may obtain a copy of the License at
|
| 9 |
+
|
| 10 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
|
| 12 |
+
Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
See the License for the specific language governing permissions and
|
| 16 |
+
limitations under the License.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import plac
|
| 22 |
+
import sys
|
| 23 |
+
import requests
|
| 24 |
+
|
| 25 |
+
from . instance import InstanceInterface
|
| 26 |
+
from . task import TaskInterface
|
| 27 |
+
from . environment import EnvironmentInterface
|
| 28 |
+
from . theme import ThemeInterface
|
| 29 |
+
from . group import GroupInterface
|
| 30 |
+
from . user import UserInterface
|
| 31 |
+
from . redirect import RedirectInterface
|
| 32 |
+
from . archive import ArchiveInterface
|
| 33 |
+
from . alias import AliasInterface
|
| 34 |
+
from . client import AybuManagerClient
|
| 35 |
+
from . autocomplete import AybuManagerCliReadline
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def string_to_level(level):
|
| 39 |
+
try:
|
| 40 |
+
level = level.upper()
|
| 41 |
+
return getattr(logging, level)
|
| 42 |
+
|
| 43 |
+
except AttributeError:
|
| 44 |
+
sys.stderr.write('Cannot find logging level {}'.format(level))
|
| 45 |
+
sys.stderr.flush()
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AybuManagerCliInterface(object):
|
| 50 |
+
|
| 51 |
+
interfaces = (InstanceInterface, TaskInterface, EnvironmentInterface,
|
| 52 |
+
ThemeInterface, GroupInterface, UserInterface,
|
| 53 |
+
RedirectInterface, ArchiveInterface, AliasInterface)
|
| 54 |
+
interface_instances = {}
|
| 55 |
+
commands = set(('exit', 'quit', 'help_commands', 'set_log_level',
|
| 56 |
+
'connect', 'show_remote'))
|
| 57 |
+
|
| 58 |
+
def create_commands_for_interface(self, intf_cls):
|
| 59 |
+
interface = intf_cls(self.api_client, self)
|
| 60 |
+
self.__class__.interface_instances[intf_cls.name] = interface
|
| 61 |
+
for command in interface.commands:
|
| 62 |
+
command_name = "{}_{}".format(intf_cls.name, command)
|
| 63 |
+
setattr(self, command_name, getattr(interface, command))
|
| 64 |
+
self.__class__.commands.add(command_name)
|
| 65 |
+
|
| 66 |
+
@plac.annotations(
|
| 67 |
+
level=('logging level to set', 'positional', None, string_to_level)
|
| 68 |
+
)
|
| 69 |
+
def set_log_level(self, level):
|
| 70 |
+
if level is None:
|
| 71 |
+
return
|
| 72 |
+
try:
|
| 73 |
+
if level == self.loglevel:
|
| 74 |
+
return
|
| 75 |
+
self.log
|
| 76 |
+
|
| 77 |
+
except AttributeError:
|
| 78 |
+
self.log = logging.getLogger('aybu')
|
| 79 |
+
self.log.addHandler(logging.StreamHandler())
|
| 80 |
+
|
| 81 |
+
self.loglevel = level
|
| 82 |
+
self.log.setLevel(self.loglevel)
|
| 83 |
+
if level == logging.DEBUG:
|
| 84 |
+
requests.defaults.defaults['verbose'] = sys.stderr
|
| 85 |
+
else:
|
| 86 |
+
requests.defaults.defaults['verbose'] = None
|
| 87 |
+
|
| 88 |
+
@plac.annotations(
|
| 89 |
+
remote=('remote configuration section name', 'positional')
|
| 90 |
+
)
|
| 91 |
+
def connect(self, remote):
|
| 92 |
+
""" Connect to a new remote """
|
| 93 |
+
try:
|
| 94 |
+
api_client = AybuManagerClient.create_from_config(
|
| 95 |
+
self.configfile,
|
| 96 |
+
remote=remote,
|
| 97 |
+
debug=self.verbose)
|
| 98 |
+
|
| 99 |
+
except Exception as e:
|
| 100 |
+
self.log.error('Cannot connect to %s: %s', remote, e)
|
| 101 |
+
|
| 102 |
+
else:
|
| 103 |
+
self.api_client = api_client
|
| 104 |
+
self.log.info("Using remote %s: %s", remote, self.api_client)
|
| 105 |
+
for intf in self.__class__.interface_instances.values():
|
| 106 |
+
intf.api = api_client
|
| 107 |
+
self.remote_name = remote
|
| 108 |
+
|
| 109 |
+
@plac.annotations(
|
| 110 |
+
configfile=('Path to the config file', 'option', "F"),
|
| 111 |
+
remote=('Remote server to connect to', 'option', "R"),
|
| 112 |
+
verbose=('Be verbose', 'flag', 'V')
|
| 113 |
+
)
|
| 114 |
+
def __init__(self, configfile, verbose, remote):
|
| 115 |
+
|
| 116 |
+
self.__doc__ = "\nUse help to see subcommands"
|
| 117 |
+
self.remote_name = remote or "default"
|
| 118 |
+
self.configfile = configfile or '~/.aybu_manager_cli.conf'
|
| 119 |
+
self.configfile = os.path.expanduser(self.configfile)
|
| 120 |
+
llevel = logging.INFO if not verbose else logging.DEBUG
|
| 121 |
+
self.set_log_level(llevel)
|
| 122 |
+
self.verbose = verbose
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
self.api_client = AybuManagerClient.create_from_config(
|
| 126 |
+
self.configfile,
|
| 127 |
+
remote=self.remote_name,
|
| 128 |
+
debug=verbose)
|
| 129 |
+
self.log.info("Using remote %s: %s", self.remote_name,
|
| 130 |
+
self.api_client)
|
| 131 |
+
except:
|
| 132 |
+
self.log.exception('Error creating API client')
|
| 133 |
+
sys.exit()
|
| 134 |
+
|
| 135 |
+
for intf in self.interfaces:
|
| 136 |
+
self.create_commands_for_interface(intf)
|
| 137 |
+
|
| 138 |
+
def show_remote(self):
|
| 139 |
+
""" Show current remote """
|
| 140 |
+
self.log.info("Connected to %s: %s", self.remote_name, self.api_client)
|
| 141 |
+
|
| 142 |
+
def __enter__(self):
|
| 143 |
+
return self
|
| 144 |
+
|
| 145 |
+
def __exit__(self, etype, exc, tb):
|
| 146 |
+
"Will be called automatically at the end of the intepreter loop"
|
| 147 |
+
if etype in (None, GeneratorExit): # success
|
| 148 |
+
if self._interact_:
|
| 149 |
+
self.log.info("exiting...")
|
| 150 |
+
|
| 151 |
+
def exit(self):
|
| 152 |
+
raise plac.Interpreter.Exit
|
| 153 |
+
|
| 154 |
+
def quit(self):
|
| 155 |
+
self.exit()
|
| 156 |
+
|
| 157 |
+
def help_commands(self):
|
| 158 |
+
self.log.info(" ".join([c for c in self.commands if c not in ("help",
|
| 159 |
+
"help_commands",
|
| 160 |
+
"exit",
|
| 161 |
+
".last_tb",
|
| 162 |
+
"quit")]))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def main():
|
| 166 |
+
try:
|
| 167 |
+
histfile = os.path.expanduser('~/.{}.history'.format(__name__))
|
| 168 |
+
completer = AybuManagerCliReadline(histfile=histfile,
|
| 169 |
+
factory=AybuManagerCliInterface)
|
| 170 |
+
plac.Interpreter.call(AybuManagerCliInterface,
|
| 171 |
+
stdin=completer, verbose=True, prompt='aybu> ')
|
| 172 |
+
except KeyboardInterrupt:
|
| 173 |
+
print "interrupted"
|
pool/shard002/Python/0025331_American.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from math import *
|
| 3 |
+
|
| 4 |
+
# Initialize parameters
|
| 5 |
+
S = 150
|
| 6 |
+
r = 0.06
|
| 7 |
+
sigma = 0.3
|
| 8 |
+
T = 1
|
| 9 |
+
K = 150
|
| 10 |
+
N = 100
|
| 11 |
+
option = 'Put'
|
| 12 |
+
|
| 13 |
+
def american(S,r,sigma,T,K,N,option):
|
| 14 |
+
dt = T/N
|
| 15 |
+
u = exp(sigma * sqrt(dt))
|
| 16 |
+
d = 1/u
|
| 17 |
+
p = (exp(r*dt)-d)/(u-d)
|
| 18 |
+
disc = exp(-r*dt)
|
| 19 |
+
|
| 20 |
+
St = [0]*(N+1)
|
| 21 |
+
C = [0]*(N+1)
|
| 22 |
+
|
| 23 |
+
St[0] = S*d**N
|
| 24 |
+
for j in range(1, N):
|
| 25 |
+
St[j] = St[j-1]*(u/d)
|
| 26 |
+
|
| 27 |
+
for j in range(0, N):
|
| 28 |
+
if option == 'Put':
|
| 29 |
+
C[j] = max(0.0, K - St[j])
|
| 30 |
+
elif option == 'Call':
|
| 31 |
+
C[j] = max(0.0, St[j] - K)
|
| 32 |
+
else:
|
| 33 |
+
break
|
| 34 |
+
|
| 35 |
+
for i in range(N-1, 0):
|
| 36 |
+
for j in range(0, i):
|
| 37 |
+
C[j] = disc*(p*C[j+1]+(1-p)*C[j])
|
| 38 |
+
St[j] = (St[j])/d
|
| 39 |
+
if option == 'Put':
|
| 40 |
+
C[j] = max(C[j], K - St[j])
|
| 41 |
+
elif option == 'Call':
|
| 42 |
+
C[j] = max(C[j], St[j] - K)
|
| 43 |
+
next(j)
|
| 44 |
+
next(i)
|
| 45 |
+
if option =='Call':
|
| 46 |
+
return C[52]
|
| 47 |
+
elif option =='Put':
|
| 48 |
+
return C[0]
|
| 49 |
+
|
| 50 |
+
print(american(S,r,sigma,T,K,N,option))
|
pool/shard002/Python/0025335_admin.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Administration interface options for ``critica.apps.videos`` models.
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
from django.contrib import admin
|
| 7 |
+
from django.utils.translation import ugettext_lazy as _
|
| 8 |
+
from critica.apps.custom_admin.sites import custom_site
|
| 9 |
+
from critica.apps.videos.models import Video
|
| 10 |
+
from critica.apps.issues.models import Issue
|
| 11 |
+
from critica.apps.videos.forms import VideoAdminModelForm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class VideoAdmin(admin.ModelAdmin):
|
| 15 |
+
"""
|
| 16 |
+
Administration interface for ``Video`` model.
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
fieldsets = (
|
| 20 |
+
(_('Video'), {'fields': ('name', 'widget')}),
|
| 21 |
+
(_('Filling'), {'fields': ('issues', 'tags')}),
|
| 22 |
+
(_('Publication'), {'fields': ('is_reserved', 'is_ready_to_publish')}),
|
| 23 |
+
)
|
| 24 |
+
list_display = ('name', 'ald_issues', 'creation_date', 'modification_date', 'is_reserved', 'is_ready_to_publish', 'ald_submitter')
|
| 25 |
+
list_filter = ('issues',)
|
| 26 |
+
filter_horizontal = ('issues',)
|
| 27 |
+
search_fields = ('name',)
|
| 28 |
+
ordering = ('-creation_date',)
|
| 29 |
+
date_hierarchy = 'creation_date'
|
| 30 |
+
exclude = ['author']
|
| 31 |
+
form = VideoAdminModelForm
|
| 32 |
+
_object = None
|
| 33 |
+
|
| 34 |
+
def __call__(self, request, url):
|
| 35 |
+
"""
|
| 36 |
+
Adds current request object and current URL to this class.
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
self.request = request
|
| 40 |
+
return super(VideoAdmin, self).__call__(request, url)
|
| 41 |
+
|
| 42 |
+
def change_view(self, request, object_id):
|
| 43 |
+
"""
|
| 44 |
+
Custom change view.
|
| 45 |
+
|
| 46 |
+
"""
|
| 47 |
+
self._request = request
|
| 48 |
+
self._object = None
|
| 49 |
+
try:
|
| 50 |
+
self._object = self.model._default_manager.get(pk=object_id)
|
| 51 |
+
except model.DoesNotExist:
|
| 52 |
+
self._object = None
|
| 53 |
+
self._action = "change"
|
| 54 |
+
return super(VideoAdmin, self).change_view(request, object_id)
|
| 55 |
+
|
| 56 |
+
def formfield_for_dbfield(self, db_field, **kwargs):
|
| 57 |
+
"""
|
| 58 |
+
Hook for specifying the form Field instance for a given database Field
|
| 59 |
+
instance. If kwargs are given, they're passed to the form Field's constructor.
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
field = super(VideoAdmin, self).formfield_for_dbfield(db_field, **kwargs)
|
| 63 |
+
if db_field.name == 'issues':
|
| 64 |
+
my_choices = [('', '---------')]
|
| 65 |
+
my_choices.extend(Issue.objects.order_by('-number').values_list('id','number'))
|
| 66 |
+
print my_choices
|
| 67 |
+
field.choices = my_choices
|
| 68 |
+
return field
|
| 69 |
+
|
| 70 |
+
def save_model(self, request, obj, form, change):
|
| 71 |
+
"""
|
| 72 |
+
Given a model instance save it to the database.
|
| 73 |
+
Auto-save submitter.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
if change == False:
|
| 77 |
+
obj.submitter = request.user
|
| 78 |
+
obj.save()
|
| 79 |
+
|
| 80 |
+
def ald_submitter(self, obj):
|
| 81 |
+
"""
|
| 82 |
+
Formatted submitter for admin list_display option.
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
if obj.submitter.get_full_name():
|
| 86 |
+
return obj.submitter.get_full_name()
|
| 87 |
+
else:
|
| 88 |
+
return obj.submitter
|
| 89 |
+
ald_submitter.short_description = _('submitter')
|
| 90 |
+
|
| 91 |
+
def ald_issues(self, obj):
|
| 92 |
+
"""
|
| 93 |
+
Formatted issue list for admin list_display option."
|
| 94 |
+
|
| 95 |
+
"""
|
| 96 |
+
issues = [issue.number for issue in obj.issues.all()]
|
| 97 |
+
return ', '.join(['%s' % issue for issue in issues])
|
| 98 |
+
ald_issues.short_description = _('issues')
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# Registers
|
| 102 |
+
# ------------------------------------------------------------------------------
|
| 103 |
+
admin.site.register(Video, VideoAdmin)
|
| 104 |
+
custom_site.register(Video, VideoAdmin)
|
| 105 |
+
|
pool/shard002/Python/0025344_import_codex.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Read from dbf's with codepage unsupported by modules dbf and codecs (like 895 cz Kamenicky)
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
from books import isxn_to_ean, parse_pubyear
|
| 11 |
+
|
| 12 |
+
from c_utils import REPEATJOINER, DEFAULT_SUBTITLE_JOINER, parse_year_from_text, normalize_authors, publ_fastinfo_and_hash
|
| 13 |
+
from dal_import import (place_to_place_id, update_or_insert_answer, update_or_insert_owned_book, update_or_insert_impressions,
|
| 14 |
+
counter_and_commit_if_100, finished, init_param, init_import, set_proc)
|
| 15 |
+
|
| 16 |
+
from gluon.tools import Storage # or other class used to create empty object
|
| 17 |
+
|
| 18 |
+
import dbf
|
| 19 |
+
from dbf_read_iffy import fix_init, fix_895
|
| 20 |
+
fix_init(dbf)
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
import dbf
|
| 24 |
+
from dbf_read_iffy import fix_init, fix_895
|
| 25 |
+
fix_init(dbf)
|
| 26 |
+
t = dbf.Table('autori.dbf')
|
| 27 |
+
t.open('read-only')
|
| 28 |
+
for record in t:
|
| 29 |
+
print fix_895(record.autor)
|
| 30 |
+
t.close()
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def imp_codex(db, library_id, src_folder):
|
| 35 |
+
"""
|
| 36 |
+
This is the main (entry) function.
|
| 37 |
+
"""
|
| 38 |
+
param = init_param()
|
| 39 |
+
set_proc(library_id, 0.1)
|
| 40 |
+
param['autori'] = read_xbase_as_dict(os.path.join(src_folder, 'autori.dbf'), key='id_autora') # AUTOR , need ","->", "
|
| 41 |
+
set_proc(library_id, 0.2)
|
| 42 |
+
param['k_autori'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_autori.dbf'), key='id_publ') # VZTAH, ID_AUTORA
|
| 43 |
+
set_proc(library_id, 0.4)
|
| 44 |
+
param['klsl'] = read_xbase_as_dict(os.path.join(src_folder, 'klsl.dbf'), key='id_klsl') # KLSL
|
| 45 |
+
set_proc(library_id, 0.5)
|
| 46 |
+
param['k_klsl'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_klsl.dbf'), key='id_publ') # ID_KLSL
|
| 47 |
+
set_proc(library_id, 0.9)
|
| 48 |
+
#param['dt'] = read_xbase_as_dict(os.path.join(src_folder, 'dt.dbf'), key='dt') # DT, DT_TXT
|
| 49 |
+
param['k_dt'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_dt.dbf'), key='id_publ') # POM_ZNAK, DT
|
| 50 |
+
set_proc(library_id, 1.2)
|
| 51 |
+
param['nakl'] = read_xbase_as_dict(os.path.join(src_folder, 'dodavat.dbf'), key='id_dodav') # ICO, NAZEV1, NAZEV2, NAZEV_ZKR, MISTO
|
| 52 |
+
set_proc(library_id, 1.5)
|
| 53 |
+
param['vytisky'] = read_xbase_as_list_dict(os.path.join(src_folder, 'vytisk.dbf'), key='id_publ', left=4)
|
| 54 |
+
# value: (tail<id>, record) # PC, SIGNATURA, UC, ZARAZENO, VYRAZENO, CENA, ID_DODAV, UMISTENI, BARCODE, REVIZE, POZNAMKA
|
| 55 |
+
set_proc(library_id, 1.9) # < 2.0 !
|
| 56 |
+
# TODO: VYPUJCKY?
|
| 57 |
+
|
| 58 |
+
param['_library_id'] = library_id
|
| 59 |
+
read_xbase(os.path.join(src_folder, 'knihy.dbf'), import_publ, param, do_init=True)
|
| 60 |
+
finished(param) # commit tail records after nnn % 100 and set imp_proc=100.0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def import_publ(record, param):
|
| 64 |
+
# KNIHY: ID_PUBL, RADA_PC, RADA_KNIHY, SIGNATURA, TEMATIKA, EAN, AUTORI, NAZEV, PODNAZEV, PUVOD, KNPOZNAMKA,
|
| 65 |
+
# JAZYK, VYDANI, IMPRESUM, ANOTACE, ISBN, KS_CELK, KS, KS_JE, POZNAMKA, STUDOVNA, ID_NAKL
|
| 66 |
+
def impression_iter(impressions):
|
| 67 |
+
for record in impressions:
|
| 68 |
+
impression = {}
|
| 69 |
+
impression['iid'] = record['pc']
|
| 70 |
+
impression['sgn'] = record['signatura']
|
| 71 |
+
impression['barcode'] = record['barcode']
|
| 72 |
+
impression['place_id'] = place_to_place_id(param['places'], record['umisteni'].strip())
|
| 73 |
+
yield impression
|
| 74 |
+
|
| 75 |
+
id_publ = record['id_publ']
|
| 76 |
+
nazev = fix_895(record['nazev'].strip())
|
| 77 |
+
podnazev = fix_895(record['podnazev'].strip())
|
| 78 |
+
pubplace = publisher = ''
|
| 79 |
+
nakl_id = record['id_nakl']
|
| 80 |
+
nakladatel = param['nakl'].get(nakl_id)
|
| 81 |
+
if nakladatel:
|
| 82 |
+
pubplace = fix_895(nakladatel['misto'].strip())
|
| 83 |
+
publisher = fix_895(nakladatel['nazev1'].strip() or nakladatel['nazev_zkr'].strip()) # prefer Nazev1 ?
|
| 84 |
+
pubyear = parse_year_from_text(record['impresum'], as_string=True)
|
| 85 |
+
|
| 86 |
+
klsl = []
|
| 87 |
+
for klic in param['k_klsl'].get(id_publ, ()):
|
| 88 |
+
klsl.append(fix_895(param['klsl'][klic['id_klsl']]['klsl'].strip()))
|
| 89 |
+
for klic in param['k_dt'].get(id_publ, ()):
|
| 90 |
+
klsl.append(fix_895(klic['dt'].strip())) # zatím neukládám k_dt.pom_znak a dt.dt_txt
|
| 91 |
+
surnamed = []
|
| 92 |
+
full = []
|
| 93 |
+
for osoba in param['k_autori'].get(id_publ, ()):
|
| 94 |
+
osoba_tuple = (fix_895(param['autori'][osoba['id_autora']]['autor']),)
|
| 95 |
+
surnamed1, full1 = normalize_authors(osoba_tuple, string_surnamed=True, string_full=True)
|
| 96 |
+
if osoba['vztah'] == 'A': # aut
|
| 97 |
+
surnamed.append(surnamed1)
|
| 98 |
+
full.append(full1)
|
| 99 |
+
else: # ostatní osoby
|
| 100 |
+
klsl.append(full1) # zatím neukládám k_autori.vztah
|
| 101 |
+
auth_surnamed = REPEATJOINER.join(surnamed)
|
| 102 |
+
auth_full = REPEATJOINER.join(full)
|
| 103 |
+
|
| 104 |
+
origin = fix_895(record['puvod'].strip())
|
| 105 |
+
knpoznamka = fix_895(record['knpoznamka'].strip())
|
| 106 |
+
impresum = fix_895(record['impresum'].strip())
|
| 107 |
+
anotace = fix_895(record['anotace'].strip())
|
| 108 |
+
# TODO: promyslet, jak spojit a kam uložit <<<<<<<<<<<<<<<<<<<<<<
|
| 109 |
+
|
| 110 |
+
answer_rec = Storage() # get an empty object
|
| 111 |
+
answer_rec.pubyears = parse_pubyear(impresum)
|
| 112 |
+
answer_rec.country = 'cze' # ???
|
| 113 |
+
# zatim ignorujeme JAZYK (Manetin: jazyk originalu nebo ORI pro knihy v originale)
|
| 114 |
+
|
| 115 |
+
isbn = ''
|
| 116 |
+
if record['isbn']:
|
| 117 |
+
isbn_candidates = re.findall(r'\b[0-9X\-]\b', record['isbn'])
|
| 118 |
+
isbn_candidates = [candidate for candidate in isbn_candidates if len(candidate.replace('-', '')) in (8, 10, 13)]
|
| 119 |
+
if isbn_candidates:
|
| 120 |
+
isbn = isbn_candidates[0]
|
| 121 |
+
ean = record['ean'].strip()
|
| 122 |
+
if not ean:
|
| 123 |
+
ean = isxn_to_ean(isbn)
|
| 124 |
+
|
| 125 |
+
# always, because in case of other system import fastinfo can change together with same ean & md5publ
|
| 126 |
+
fastinfo, md5publ = publ_fastinfo_and_hash(nazev, auth_surnamed, auth_full, pubplace, publisher, pubyear,
|
| 127 |
+
subtitles=((DEFAULT_SUBTITLE_JOINER, podnazev),) if podnazev else None, origin=origin, keys=klsl)
|
| 128 |
+
|
| 129 |
+
impressions = param['vytisky'].get(id_publ, ())
|
| 130 |
+
added, answer_id = update_or_insert_answer(ean, md5publ, fastinfo, md5redirects=param['redirects'], marcrec=answer_rec)
|
| 131 |
+
owned_book_id = update_or_insert_owned_book(answer_id, fastinfo, len(impressions))
|
| 132 |
+
# impression_gen je generátor podle impression/impressions
|
| 133 |
+
impression_gen = impression_iter(impressions)
|
| 134 |
+
update_or_insert_impressions(answer_id, owned_book_id, impression_gen)
|
| 135 |
+
|
| 136 |
+
counter_and_commit_if_100(param, added)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
#TODO: rest should be moved into modules/c_import with next xBase import (import dbf + fix_init(dbf) can be used in c_import too)
|
| 140 |
+
def read_xbase(filename, callback, *args, **kwargs):
|
| 141 |
+
"""
|
| 142 |
+
run the callback function for each row in the table (similar to xBase SCAN)
|
| 143 |
+
"""
|
| 144 |
+
flds = dbf.get_fields(filename)
|
| 145 |
+
t = dbf.Table(filename)
|
| 146 |
+
t.open('read-only')
|
| 147 |
+
if kwargs.get('do_init'):
|
| 148 |
+
del kwargs['do_init'] # to avoid error in the callback function
|
| 149 |
+
init_import(args[0], cnt_total=len(t)) # args[0] ~ param
|
| 150 |
+
for record in t:
|
| 151 |
+
# callback(record, *args, **kwargs) # this run extremely slow !!!
|
| 152 |
+
callback({fld: record[fld] for fld in flds}, *args, **kwargs) # with real python dict it run well
|
| 153 |
+
t.close()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def read_xbase_as_dict(filename, key='id'):
|
| 157 |
+
"""
|
| 158 |
+
get rows as dict where keys are primary keys, values are records (without primary key)
|
| 159 |
+
"""
|
| 160 |
+
def rec_to_dict(record, key, rows):
|
| 161 |
+
current_id = record[key]
|
| 162 |
+
rows[current_id] = record
|
| 163 |
+
|
| 164 |
+
rows = {}
|
| 165 |
+
read_xbase(filename, rec_to_dict, key, rows)
|
| 166 |
+
return rows
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def read_xbase_as_list_dict(filename, key, left=None):
|
| 170 |
+
"""
|
| 171 |
+
get rows as dict where keys are given keys (can be non-unique), values are list records (without given key)
|
| 172 |
+
"""
|
| 173 |
+
def rec_to_list_dict(record, key, rows, left):
|
| 174 |
+
current_id = record[key]
|
| 175 |
+
if left:
|
| 176 |
+
current_id = current_id[:left]
|
| 177 |
+
if current_id in rows:
|
| 178 |
+
rows[current_id].append(record)
|
| 179 |
+
else:
|
| 180 |
+
rows[current_id] = [record]
|
| 181 |
+
|
| 182 |
+
rows = {}
|
| 183 |
+
read_xbase(filename, rec_to_list_dict, key, rows, left)
|
| 184 |
+
return rows
|
| 185 |
+
#TODO: end
|
pool/shard002/Python/0025345_check.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from optparse import Values
|
| 3 |
+
from typing import Any, List
|
| 4 |
+
|
| 5 |
+
from pip._internal.cli.base_command import Command
|
| 6 |
+
from pip._internal.cli.status_codes import ERROR, SUCCESS
|
| 7 |
+
from pip._internal.operations.check import (
|
| 8 |
+
check_package_set,
|
| 9 |
+
create_package_set_from_installed,
|
| 10 |
+
)
|
| 11 |
+
from pip._internal.utils.misc import write_output
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CheckCommand(Command):
|
| 17 |
+
"""Verify installed packages have compatible dependencies."""
|
| 18 |
+
|
| 19 |
+
usage = """
|
| 20 |
+
%prog [options]"""
|
| 21 |
+
|
| 22 |
+
def run(self, options, args):
|
| 23 |
+
# type: (Values, List[Any]) -> int
|
| 24 |
+
|
| 25 |
+
package_set, parsing_probs = create_package_set_from_installed()
|
| 26 |
+
missing, conflicting = check_package_set(package_set)
|
| 27 |
+
|
| 28 |
+
for project_name in missing:
|
| 29 |
+
version = package_set[project_name].version
|
| 30 |
+
for dependency in missing[project_name]:
|
| 31 |
+
write_output(
|
| 32 |
+
"%s %s requires %s, which is not installed.",
|
| 33 |
+
project_name, version, dependency[0],
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
for project_name in conflicting:
|
| 37 |
+
version = package_set[project_name].version
|
| 38 |
+
for dep_name, dep_version, req in conflicting[project_name]:
|
| 39 |
+
write_output(
|
| 40 |
+
"%s %s has requirement %s, but you have %s %s.",
|
| 41 |
+
project_name, version, req, dep_name, dep_version,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if missing or conflicting or parsing_probs:
|
| 45 |
+
return ERROR
|
| 46 |
+
else:
|
| 47 |
+
write_output("No broken requirements found.")
|
| 48 |
+
return SUCCESS
|
pool/shard002/Python/0025356_flip.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Pyctools - a picture processing algorithm development kit.
|
| 3 |
+
# http://github.com/jim-easterbrook/pyctools
|
| 4 |
+
# Copyright (C) 2014-18 Pyctools contributors
|
| 5 |
+
#
|
| 6 |
+
# This program is free software: you can redistribute it and/or
|
| 7 |
+
# modify it under the terms of the GNU General Public License as
|
| 8 |
+
# published by the Free Software Foundation, either version 3 of the
|
| 9 |
+
# License, or (at your option) any later version.
|
| 10 |
+
#
|
| 11 |
+
# This program is distributed in the hope that it will be useful,
|
| 12 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
| 14 |
+
# General Public License for more details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU General Public License
|
| 17 |
+
# along with this program. If not, see
|
| 18 |
+
# <http://www.gnu.org/licenses/>.
|
| 19 |
+
|
| 20 |
+
"""Turn a picture upside down or reflect it left to right.
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
__all__ = ['Flip']
|
| 25 |
+
__docformat__ = 'restructuredtext en'
|
| 26 |
+
|
| 27 |
+
import PIL.Image
|
| 28 |
+
|
| 29 |
+
from pyctools.core.base import Transformer
|
| 30 |
+
from pyctools.core.config import ConfigEnum
|
| 31 |
+
|
| 32 |
+
class Flip(Transformer):
|
| 33 |
+
def initialise(self):
|
| 34 |
+
self.config['direction'] = ConfigEnum(choices=('vertical', 'horizontal'))
|
| 35 |
+
|
| 36 |
+
def transform(self, in_frame, out_frame):
|
| 37 |
+
self.update_config()
|
| 38 |
+
direction = self.config['direction']
|
| 39 |
+
if direction == 'vertical':
|
| 40 |
+
flip = PIL.Image.FLIP_TOP_BOTTOM
|
| 41 |
+
else:
|
| 42 |
+
flip = PIL.Image.FLIP_LEFT_RIGHT
|
| 43 |
+
in_data = in_frame.as_PIL()
|
| 44 |
+
out_frame.data = in_data.transpose(flip)
|
| 45 |
+
audit = out_frame.metadata.get('audit')
|
| 46 |
+
audit += 'data = Flip(data)\n'
|
| 47 |
+
audit += ' direction: %s\n' % direction
|
| 48 |
+
out_frame.metadata.set('audit', audit)
|
| 49 |
+
return True
|
pool/shard002/Python/0025357_setup.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
import imp
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import subprocess
|
| 7 |
+
|
| 8 |
+
import setuptools
|
| 9 |
+
|
| 10 |
+
NAME = 'Orange'
|
| 11 |
+
|
| 12 |
+
VERSION = '3.2'
|
| 13 |
+
ISRELEASED = False
|
| 14 |
+
|
| 15 |
+
DESCRIPTION = 'Orange, a component-based data mining framework.'
|
| 16 |
+
README_FILE = os.path.join(os.path.dirname(__file__), 'README.md')
|
| 17 |
+
LONG_DESCRIPTION = open(README_FILE).read()
|
| 18 |
+
AUTHOR = 'Bioinformatics Laboratory, FRI UL'
|
| 19 |
+
AUTHOR_EMAIL = 'contact@orange.biolab.si'
|
| 20 |
+
URL = 'http://orange.biolab.si/'
|
| 21 |
+
DOWNLOAD_URL = 'https://bitbucket.org/biolab/orange/downloads'
|
| 22 |
+
LICENSE = 'GPLv3'
|
| 23 |
+
|
| 24 |
+
KEYWORDS = (
|
| 25 |
+
'data mining',
|
| 26 |
+
'machine learning',
|
| 27 |
+
'artificial intelligence',
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
CLASSIFIERS = (
|
| 31 |
+
'Development Status :: 4 - Beta',
|
| 32 |
+
'Environment :: X11 Applications :: Qt',
|
| 33 |
+
'Environment :: Console',
|
| 34 |
+
'Environment :: Plugins',
|
| 35 |
+
'Programming Language :: Python',
|
| 36 |
+
'Framework :: Orange',
|
| 37 |
+
'License :: OSI Approved :: '
|
| 38 |
+
'GNU General Public License v3 or later (GPLv3+)',
|
| 39 |
+
'Operating System :: POSIX',
|
| 40 |
+
'Operating System :: Microsoft :: Windows',
|
| 41 |
+
'Topic :: Scientific/Engineering :: Artificial Intelligence',
|
| 42 |
+
'Topic :: Scientific/Engineering :: Visualization',
|
| 43 |
+
'Topic :: Software Development :: Libraries :: Python Modules',
|
| 44 |
+
'Intended Audience :: Education',
|
| 45 |
+
'Intended Audience :: Science/Research',
|
| 46 |
+
'Intended Audience :: Developers',
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
INSTALL_REQUIRES = (
|
| 51 |
+
'setuptools',
|
| 52 |
+
'numpy>=1.9.0',
|
| 53 |
+
'scipy',
|
| 54 |
+
'scikit-learn>=0.16',
|
| 55 |
+
'bottlechest',
|
| 56 |
+
'openpyxl>=2.1.2',
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if sys.version_info < (3, 4):
|
| 60 |
+
INSTALL_REQUIRES = INSTALL_REQUIRES + ("singledispatch",)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
ENTRY_POINTS = {
|
| 64 |
+
"orange.canvas.help": (
|
| 65 |
+
"html-index = Orange.widgets:WIDGET_HELP_PATH",)
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Return the git revision as a string
|
| 70 |
+
def git_version():
|
| 71 |
+
"""Return the git revision as a string.
|
| 72 |
+
|
| 73 |
+
Copied from numpy setup.py
|
| 74 |
+
"""
|
| 75 |
+
def _minimal_ext_cmd(cmd):
|
| 76 |
+
# construct minimal environment
|
| 77 |
+
env = {}
|
| 78 |
+
for k in ['SYSTEMROOT', 'PATH']:
|
| 79 |
+
v = os.environ.get(k)
|
| 80 |
+
if v is not None:
|
| 81 |
+
env[k] = v
|
| 82 |
+
# LANGUAGE is used on win32
|
| 83 |
+
env['LANGUAGE'] = 'C'
|
| 84 |
+
env['LANG'] = 'C'
|
| 85 |
+
env['LC_ALL'] = 'C'
|
| 86 |
+
out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
|
| 87 |
+
return out
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
|
| 91 |
+
GIT_REVISION = out.strip().decode('ascii')
|
| 92 |
+
except OSError:
|
| 93 |
+
GIT_REVISION = "Unknown"
|
| 94 |
+
return GIT_REVISION
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def write_version_py(filename='Orange/version.py'):
|
| 98 |
+
# Copied from numpy setup.py
|
| 99 |
+
cnt = """
|
| 100 |
+
# THIS FILE IS GENERATED FROM ORANGE SETUP.PY
|
| 101 |
+
short_version = '%(version)s'
|
| 102 |
+
version = '%(version)s'
|
| 103 |
+
full_version = '%(full_version)s'
|
| 104 |
+
git_revision = '%(git_revision)s'
|
| 105 |
+
release = %(isrelease)s
|
| 106 |
+
|
| 107 |
+
if not release:
|
| 108 |
+
version = full_version
|
| 109 |
+
short_version += ".dev"
|
| 110 |
+
"""
|
| 111 |
+
FULLVERSION = VERSION
|
| 112 |
+
if os.path.exists('.git'):
|
| 113 |
+
GIT_REVISION = git_version()
|
| 114 |
+
elif os.path.exists('Orange/version.py'):
|
| 115 |
+
# must be a source distribution, use existing version file
|
| 116 |
+
version = imp.load_source("Orange.version", "Orange/version.py")
|
| 117 |
+
GIT_REVISION = version.git_revision
|
| 118 |
+
else:
|
| 119 |
+
GIT_REVISION = "Unknown"
|
| 120 |
+
|
| 121 |
+
if not ISRELEASED:
|
| 122 |
+
FULLVERSION += '.dev0+' + GIT_REVISION[:7]
|
| 123 |
+
|
| 124 |
+
a = open(filename, 'w')
|
| 125 |
+
try:
|
| 126 |
+
a.write(cnt % {'version': VERSION,
|
| 127 |
+
'full_version': FULLVERSION,
|
| 128 |
+
'git_revision': GIT_REVISION,
|
| 129 |
+
'isrelease': str(ISRELEASED)})
|
| 130 |
+
finally:
|
| 131 |
+
a.close()
|
| 132 |
+
|
| 133 |
+
from numpy.distutils.core import setup
|
| 134 |
+
|
| 135 |
+
def configuration(parent_package='', top_path=None):
|
| 136 |
+
if os.path.exists('MANIFEST'):
|
| 137 |
+
os.remove('MANIFEST')
|
| 138 |
+
|
| 139 |
+
from numpy.distutils.misc_util import Configuration
|
| 140 |
+
config = Configuration(None, parent_package, top_path)
|
| 141 |
+
|
| 142 |
+
# Avoid non-useful msg:
|
| 143 |
+
# "Ignoring attempt to set 'name' (from ... "
|
| 144 |
+
config.set_options(ignore_setup_xxx_py=True,
|
| 145 |
+
assume_default_configuration=True,
|
| 146 |
+
delegate_options_to_subpackages=True,
|
| 147 |
+
quiet=True)
|
| 148 |
+
|
| 149 |
+
config.add_subpackage('Orange')
|
| 150 |
+
|
| 151 |
+
config.get_version('Orange/version.py') # sets config.version
|
| 152 |
+
|
| 153 |
+
return config
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
PACKAGES = [
|
| 157 |
+
"Orange",
|
| 158 |
+
"Orange.canvas",
|
| 159 |
+
"Orange.canvas.application",
|
| 160 |
+
"Orange.canvas.application.tutorials",
|
| 161 |
+
"Orange.canvas.canvas",
|
| 162 |
+
"Orange.canvas.canvas.items",
|
| 163 |
+
"Orange.canvas.document",
|
| 164 |
+
"Orange.canvas.gui",
|
| 165 |
+
"Orange.canvas.help",
|
| 166 |
+
"Orange.canvas.preview",
|
| 167 |
+
"Orange.canvas.registry",
|
| 168 |
+
"Orange.canvas.scheme",
|
| 169 |
+
"Orange.canvas.styles",
|
| 170 |
+
"Orange.canvas.utils",
|
| 171 |
+
"Orange.classification",
|
| 172 |
+
"Orange.clustering",
|
| 173 |
+
"Orange.data",
|
| 174 |
+
"Orange.data.sql",
|
| 175 |
+
"Orange.distance",
|
| 176 |
+
"Orange.evaluation",
|
| 177 |
+
"Orange.misc",
|
| 178 |
+
"Orange.preprocess",
|
| 179 |
+
"Orange.projection",
|
| 180 |
+
"Orange.regression",
|
| 181 |
+
"Orange.statistics",
|
| 182 |
+
"Orange.testing",
|
| 183 |
+
"Orange.widgets",
|
| 184 |
+
"Orange.widgets.data",
|
| 185 |
+
"Orange.widgets.visualize",
|
| 186 |
+
"Orange.widgets.classify",
|
| 187 |
+
"Orange.widgets.regression",
|
| 188 |
+
"Orange.widgets.evaluate",
|
| 189 |
+
"Orange.widgets.unsupervised",
|
| 190 |
+
"Orange.widgets.utils",
|
| 191 |
+
"Orange.widgets.utils.plot",
|
| 192 |
+
"Orange.widgets.utils.plot.primitives"
|
| 193 |
+
]
|
| 194 |
+
|
| 195 |
+
PACKAGE_DATA = {
|
| 196 |
+
"Orange": ["datasets/*.{}".format(ext)
|
| 197 |
+
for ext in ["tab", "csv", "basket", "info"]],
|
| 198 |
+
"Orange.canvas": ["icons/*.png", "icons/*.svg"],
|
| 199 |
+
"Orange.canvas.styles": ["*.qss", "orange/*.svg"],
|
| 200 |
+
"Orange.canvas.application.tutorials": ["*.ows"],
|
| 201 |
+
"Orange.widgets": ["icons/*.png", "icons/*.svg"],
|
| 202 |
+
"Orange.widgets.data": ["icons/*.svg", "icons/paintdata/*.png", "icons/paintdata/*.svg"],
|
| 203 |
+
"Orange.widgets.visualize": ["icons/*.svg"],
|
| 204 |
+
"Orange.widgets.classify": ["icons/*.svg"],
|
| 205 |
+
"Orange.widgets.regression": ["icons/*.svg"],
|
| 206 |
+
"Orange.widgets.evaluate": ["icons/*.svg"],
|
| 207 |
+
"Orange.widgets.unsupervised": ["icons/*.svg"],
|
| 208 |
+
"Orange.widgets.plot": ["*.fs", "*.gs", "*.vs"],
|
| 209 |
+
"Orange.widgets.plot.primitives": ["*.obj"],
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def setup_package():
|
| 214 |
+
write_version_py()
|
| 215 |
+
setup(
|
| 216 |
+
configuration=configuration,
|
| 217 |
+
name=NAME,
|
| 218 |
+
description=DESCRIPTION,
|
| 219 |
+
long_description=LONG_DESCRIPTION,
|
| 220 |
+
author=AUTHOR,
|
| 221 |
+
author_email=AUTHOR_EMAIL,
|
| 222 |
+
url=URL,
|
| 223 |
+
download_url=DOWNLOAD_URL,
|
| 224 |
+
license=LICENSE,
|
| 225 |
+
keywords=KEYWORDS,
|
| 226 |
+
classifiers=CLASSIFIERS,
|
| 227 |
+
packages=PACKAGES,
|
| 228 |
+
package_data=PACKAGE_DATA,
|
| 229 |
+
install_requires=INSTALL_REQUIRES,
|
| 230 |
+
entry_points=ENTRY_POINTS,
|
| 231 |
+
zip_safe=False,
|
| 232 |
+
include_package_data=True,
|
| 233 |
+
test_suite='Orange.tests.test_suite',
|
| 234 |
+
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
if __name__ == '__main__':
|
| 238 |
+
setup_package()
|
pool/shard002/Python/0025359_transfer.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
from flask import request, jsonify, g
|
| 3 |
+
from flask_sqlalchemy import SQLAlchemy
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
tasks = []
|
| 7 |
+
done = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def register_front(app):
|
| 11 |
+
|
| 12 |
+
db = SQLAlchemy(app)
|
| 13 |
+
# users = cur = g.Post.query.all()
|
| 14 |
+
|
| 15 |
+
@app.route('/api/user/add/', methods=['GET', 'POST'])
|
| 16 |
+
def signup():
|
| 17 |
+
username = request.values.get('username', '')
|
| 18 |
+
password = request.values.get('password', '')
|
| 19 |
+
email = request.values.get('email', '')
|
| 20 |
+
|
| 21 |
+
# cur = g.User.query.filter_by(username='admin').filter_by(password='123')
|
| 22 |
+
ex = g.User.query.filter_by(del_status=False)
|
| 23 |
+
user = ex.filter_by(username=username).first() or ex.filter_by(email=email).first()
|
| 24 |
+
if user:
|
| 25 |
+
return jsonify({ 'code': -2 })
|
| 26 |
+
|
| 27 |
+
user = db.User(username=username, email=email, psw=password)
|
| 28 |
+
db.session.add(user)
|
| 29 |
+
db.session.commit()
|
| 30 |
+
|
| 31 |
+
return jsonify({ 'code': 1 })
|
| 32 |
+
# return jsonify({'code':[ dict(un=row.username, ps=row.password) for row in cur] })
|
| 33 |
+
|
| 34 |
+
@app.route('/api/user/query/', methods=['GET', 'POST'])
|
| 35 |
+
def signin():
|
| 36 |
+
# cur = g.User.query.all()
|
| 37 |
+
username = request.values.get('username', '')
|
| 38 |
+
password = request.values.get('password', '')
|
| 39 |
+
user = g.User.query.filter_by(del_status=False, username=username).first()
|
| 40 |
+
if not user:
|
| 41 |
+
return jsonify({ 'code': -1 })
|
| 42 |
+
|
| 43 |
+
fw = [i.to_user.username for i in g.FollowUser.query.filter_by(del_status=False, from_user_id=user.id).all()]
|
| 44 |
+
fd = [i.from_user.username for i in g.FollowUser.query.filter_by(del_status=False, to_user_id=user.id).all()]
|
| 45 |
+
|
| 46 |
+
res = {
|
| 47 |
+
'code': 1,
|
| 48 |
+
'username': user.username,
|
| 49 |
+
'email': user.email,
|
| 50 |
+
'login': False,
|
| 51 |
+
'follow_user': fw,
|
| 52 |
+
'followed_user': fd,
|
| 53 |
+
}
|
| 54 |
+
res_secret = {
|
| 55 |
+
'login': True,
|
| 56 |
+
'id': user.id,
|
| 57 |
+
}
|
| 58 |
+
if user and user.password == password:
|
| 59 |
+
res.update(res_secret)
|
| 60 |
+
|
| 61 |
+
return jsonify(res)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# return jsonify({'code':[ dict(un=row.username, ps=row.password) for row in cur] })
|
| 65 |
+
|
| 66 |
+
@app.route('/api/user/follow/', methods=['GET', 'POST'])
|
| 67 |
+
def follow_user():
|
| 68 |
+
from_user_name = request.values.get('from_user_name', '')
|
| 69 |
+
to_user_name = request.values.get('to_user_name', '')
|
| 70 |
+
follow_bool = request.values.get('follow_bool', '1') # 1 or 0
|
| 71 |
+
|
| 72 |
+
from_user = g.User.query.filter_by(username=from_user_name).first()
|
| 73 |
+
to_user = g.User.query.filter_by(username=to_user_name).first()
|
| 74 |
+
if not (from_user and to_user):
|
| 75 |
+
return jsonify({ 'code': -1 })
|
| 76 |
+
|
| 77 |
+
args = {
|
| 78 |
+
'from_user_id': from_user.id,
|
| 79 |
+
'to_user_id': to_user.id,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
follow = g.FollowUser.query.filter_by(**args).first()
|
| 83 |
+
want_to_follow = bool(int(follow_bool))
|
| 84 |
+
if follow:
|
| 85 |
+
follow.del_status = not want_to_follow
|
| 86 |
+
elif want_to_follow:
|
| 87 |
+
follow = g.FollowUser(**args)
|
| 88 |
+
db.session.add(follow)
|
| 89 |
+
db.session.commit()
|
| 90 |
+
|
| 91 |
+
return jsonify({ 'code': 1 })
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@app.route('/api/image/addinfo/', methods=['GET', 'POST'])
|
| 95 |
+
def image_info():
|
| 96 |
+
kwargs = {
|
| 97 |
+
'url': request.values.get('url', ''),
|
| 98 |
+
'filename': request.values.get('filename', ''),
|
| 99 |
+
'param': request.values.get('param', '')
|
| 100 |
+
}
|
| 101 |
+
user_id = request.values.get('user_id', '')
|
| 102 |
+
if user_id:
|
| 103 |
+
kwargs.update({ 'user_id': user_id })
|
| 104 |
+
|
| 105 |
+
item = g.Item.query.filter_by(name=filename).first()
|
| 106 |
+
if item:
|
| 107 |
+
return jsonify({'code': '-2'})
|
| 108 |
+
|
| 109 |
+
item = g.Item(**kwargs)
|
| 110 |
+
g.db.session.add(item)
|
| 111 |
+
g.db.session.commit()
|
| 112 |
+
|
| 113 |
+
return jsonify({ 'code': 1 })
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@app.route('/api/tasks/add/', methods=['GET', 'POST'])
|
| 117 |
+
def add_image_task():
|
| 118 |
+
"""add task to a queue"""
|
| 119 |
+
task = {
|
| 120 |
+
'url': request.values.get('url', ''),
|
| 121 |
+
'type': request.values.get('type', 'model'),
|
| 122 |
+
'model': request.values.get('model', 'mosaic'),
|
| 123 |
+
}
|
| 124 |
+
tasks.append(task)
|
| 125 |
+
return jsonify({ 'code': 1, 'task':task })
|
| 126 |
+
|
| 127 |
+
# @app.route('/defaultstyles/')
|
| 128 |
+
# def defaultstyles():
|
| 129 |
+
# """获取系统所有风格信息"""
|
| 130 |
+
# styles = []
|
| 131 |
+
# styles.append({
|
| 132 |
+
# 'styleName':'123',
|
| 133 |
+
# 'styleId':123,
|
| 134 |
+
# 'styleImgUrl':'iii'
|
| 135 |
+
# })
|
| 136 |
+
# return jsonify(styles)
|
| 137 |
+
#
|
| 138 |
+
#
|
| 139 |
+
# @app.route('/process/human-mask-picture/')
|
| 140 |
+
# def human_mask_picture():
|
| 141 |
+
# """风格转化结果图处理-获取人像遮罩图"""
|
| 142 |
+
# originImgUrl = request.values.get('originImgUrl', '')
|
| 143 |
+
#
|
| 144 |
+
# return jsonify({
|
| 145 |
+
# 'maskImgUrl':'iii'
|
| 146 |
+
# })
|
| 147 |
+
#
|
| 148 |
+
# @app.route('/users/<userId>/styletransfer', methods=['POST'])
|
| 149 |
+
# def users_styletransfer(userId):
|
| 150 |
+
# """
|
| 151 |
+
# 风格转化—系统风格
|
| 152 |
+
# 风格转化—自定义���格
|
| 153 |
+
# """
|
| 154 |
+
# styleId = request.values.get('styleId ', '')
|
| 155 |
+
# originImgUrl = request.values.get('originImgUrl', '')
|
| 156 |
+
#
|
| 157 |
+
# return jsonify({
|
| 158 |
+
# 'processImgUrl':'iii'
|
| 159 |
+
# })
|
| 160 |
+
#
|
| 161 |
+
# @app.route('/process/mask/', methods=['POST'])
|
| 162 |
+
# def process_mask():
|
| 163 |
+
# """风格转化结果图处理-遮罩"""
|
| 164 |
+
# originImgUrl = request.values.get('originImgUrl', '')
|
| 165 |
+
# resultImgUrl = request.values.get('resultImgUrl', '')
|
| 166 |
+
# maskImgUrl = request.values.get('maskImgUrl', '')
|
| 167 |
+
#
|
| 168 |
+
# return jsonify({
|
| 169 |
+
# 'processImgUrl': 'iii'
|
| 170 |
+
# })
|
| 171 |
+
#
|
| 172 |
+
# @app.route('/process/colorpreserve/', methods=['POST'])
|
| 173 |
+
# def process_colorpreserve():
|
| 174 |
+
# originImgUrl = request.values.get('originImgUrl', '')
|
| 175 |
+
# resultImgUrl = request.values.get('resultImgUrl', '')
|
| 176 |
+
# colorMaskImgUrl = request.values.get('colorMaskImgUrl', '')
|
| 177 |
+
#
|
| 178 |
+
# return jsonify({
|
| 179 |
+
# 'processImgUrl': 'iii'
|
| 180 |
+
# })
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def register_calculate(app):
|
| 185 |
+
|
| 186 |
+
@app.route('/tasks/add/model/')
|
| 187 |
+
def add_model():
|
| 188 |
+
task = {
|
| 189 |
+
'url':'https://oi3qt7c8d.qnssl.com/res.jpg',
|
| 190 |
+
'type':'model',
|
| 191 |
+
'model':'mosaic',
|
| 192 |
+
}
|
| 193 |
+
tasks.append(task)
|
| 194 |
+
return jsonify(task)
|
| 195 |
+
|
| 196 |
+
@app.route('/tasks/add/')
|
| 197 |
+
def add_task():
|
| 198 |
+
ID = random.randint(10001, 99999)
|
| 199 |
+
tasks.append({'id':ID})
|
| 200 |
+
return jsonify({
|
| 201 |
+
'code':1,
|
| 202 |
+
'id':ID
|
| 203 |
+
})
|
| 204 |
+
|
| 205 |
+
@app.route('/tasks/query/')
|
| 206 |
+
def task_query():
|
| 207 |
+
return jsonify({
|
| 208 |
+
'tasks':tasks,
|
| 209 |
+
'done':done,
|
| 210 |
+
})
|
| 211 |
+
|
| 212 |
+
@app.route('/tasks/pop/')
|
| 213 |
+
def task_pop():
|
| 214 |
+
if tasks:
|
| 215 |
+
return jsonify(tasks.pop(0))
|
| 216 |
+
return jsonify('Empty')
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
@app.route('/tasks/callback/', methods=['POST'])
|
| 220 |
+
def task_cb():
|
| 221 |
+
"""callback from qiniu"""
|
| 222 |
+
qiniu_setting = {
|
| 223 |
+
'access_key' : 'iQ3ndG5uRpwdeln_gcrH3iiZ7E3KbMdJVkdYV9Im',
|
| 224 |
+
'secret_key' : 'AGsp6K7fu1NsH2DnsPi7hW3qa3JXb4dtfeGvkm-A',
|
| 225 |
+
'bucket_name' : 'image',
|
| 226 |
+
'bucket_domain' : 'https://oi3qt7c8d.qnssl.com/',
|
| 227 |
+
'callbakUrl' : 'http://139.129.24.151/tasks/callback/',
|
| 228 |
+
'callbackBody' : 'filename:$(fname)'
|
| 229 |
+
}
|
| 230 |
+
filename = request.values.get('filename', '')
|
| 231 |
+
imageInfo = request.values.get('imageInfo', '')
|
| 232 |
+
url = qiniu_setting['bucket_domain'] + filename
|
| 233 |
+
print(filename, url, imageInfo)
|
| 234 |
+
done.append({
|
| 235 |
+
'url':url,
|
| 236 |
+
})
|
| 237 |
+
|
| 238 |
+
return url
|
pool/shard002/Python/0025361_load_as_driver.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import print_function
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
|
| 5 |
+
from stevedore import driver
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
if __name__ == '__main__':
|
| 9 |
+
parser = argparse.ArgumentParser()
|
| 10 |
+
parser.add_argument(
|
| 11 |
+
'format',
|
| 12 |
+
nargs='?',
|
| 13 |
+
default='simple',
|
| 14 |
+
help='the output format',
|
| 15 |
+
)
|
| 16 |
+
parser.add_argument(
|
| 17 |
+
'--width',
|
| 18 |
+
default=60,
|
| 19 |
+
type=int,
|
| 20 |
+
help='maximum output width for text',
|
| 21 |
+
)
|
| 22 |
+
parsed_args = parser.parse_args()
|
| 23 |
+
|
| 24 |
+
data = {
|
| 25 |
+
'a': 'A',
|
| 26 |
+
'b': 'B',
|
| 27 |
+
'long': 'word ' * 80,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
mgr = driver.DriverManager(
|
| 31 |
+
namespace='stevedore.example.formatter',
|
| 32 |
+
name=parsed_args.format,
|
| 33 |
+
invoke_on_load=True,
|
| 34 |
+
invoke_args=(parsed_args.width,),
|
| 35 |
+
)
|
| 36 |
+
for chunk in mgr.driver.format(data):
|
| 37 |
+
print(chunk, end='')
|
pool/shard002/Python/0025362_ptest.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.core.management.base import BaseCommand
|
| 2 |
+
import pytest
|
| 3 |
+
import optparse
|
| 4 |
+
|
| 5 |
+
from django.conf import settings
|
| 6 |
+
|
| 7 |
+
class Command(BaseCommand):
|
| 8 |
+
option_list = BaseCommand.option_list + (
|
| 9 |
+
optparse.make_option('-s',
|
| 10 |
+
action='store_false',
|
| 11 |
+
dest='capture',
|
| 12 |
+
default=True,
|
| 13 |
+
help='Capture output'),
|
| 14 |
+
optparse.make_option('-k',
|
| 15 |
+
dest='keyword',
|
| 16 |
+
default='',
|
| 17 |
+
help='Limit by keyword'),
|
| 18 |
+
optparse.make_option('-p',
|
| 19 |
+
action='store_false',
|
| 20 |
+
dest='paste',
|
| 21 |
+
default=True,
|
| 22 |
+
help='Paste result to pastebin'),
|
| 23 |
+
optparse.make_option('-f',
|
| 24 |
+
action='store_true',
|
| 25 |
+
dest='functional',
|
| 26 |
+
default=False,
|
| 27 |
+
help='Include functional tests'),
|
| 28 |
+
optparse.make_option('-c',
|
| 29 |
+
dest='coverage',
|
| 30 |
+
default="",
|
| 31 |
+
help='Perform coverage analysis, restrict to modules'),
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def handle(self, *a, **b):
|
| 35 |
+
## http://pytest.org/latest/usage.html
|
| 36 |
+
## --tb=native is also usable
|
| 37 |
+
coverage = False
|
| 38 |
+
opts = ["--tb=short"]
|
| 39 |
+
|
| 40 |
+
keyword_specified = False
|
| 41 |
+
|
| 42 |
+
settings.DATABASES = dict(default=settings.TEST_DB)
|
| 43 |
+
if not b.get('capture'):
|
| 44 |
+
opts.append("-s")
|
| 45 |
+
if b.get('keyword') and b['keyword']:
|
| 46 |
+
opts.append("-k")
|
| 47 |
+
opts.append(b['keyword'])
|
| 48 |
+
keyword_specified = True
|
| 49 |
+
|
| 50 |
+
if not b.get('paste'):
|
| 51 |
+
opts.append("--pastebin=all")
|
| 52 |
+
if not b.get('functional') and not keyword_specified:
|
| 53 |
+
opts.append("-k")
|
| 54 |
+
opts.append("not functional_")
|
| 55 |
+
|
| 56 |
+
if b.get('coverage'):
|
| 57 |
+
coverage = True
|
| 58 |
+
coverage_modules = b.get('coverage', '').split(",")
|
| 59 |
+
|
| 60 |
+
if coverage:
|
| 61 |
+
import coverage
|
| 62 |
+
conf = getattr(settings, 'COVERAGE_CONF', '')
|
| 63 |
+
cov = coverage.coverage(source=coverage_modules, config_file=conf)
|
| 64 |
+
cov.start()
|
| 65 |
+
pytest.main(opts + list(a))
|
| 66 |
+
if coverage:
|
| 67 |
+
cov.stop()
|
| 68 |
+
cov.report()
|
| 69 |
+
|
| 70 |
+
|
pool/shard002/Python/0025370_orderedset.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ==================================================================================================
|
| 2 |
+
# Copyright 2011 Twitter, Inc.
|
| 3 |
+
# --------------------------------------------------------------------------------------------------
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this work except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License in the LICENSE file, or at:
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
# ==================================================================================================
|
| 16 |
+
# OrderedSet recipe referenced in the Python standard library docs (bottom):
|
| 17 |
+
# http://docs.python.org/library/collections.html
|
| 18 |
+
#
|
| 19 |
+
# Copied from recipe code found here: http://code.activestate.com/recipes/576694/ with small
|
| 20 |
+
# modifications
|
| 21 |
+
#
|
| 22 |
+
|
| 23 |
+
import collections
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class OrderedSet(collections.MutableSet):
|
| 27 |
+
KEY, PREV, NEXT = range(3)
|
| 28 |
+
|
| 29 |
+
def __init__(self, iterable=None):
|
| 30 |
+
self.end = end = []
|
| 31 |
+
end += [None, end, end] # sentinel node for doubly linked list
|
| 32 |
+
self.map = {} # key --> [key, prev, next]
|
| 33 |
+
if iterable is not None:
|
| 34 |
+
self |= iterable
|
| 35 |
+
|
| 36 |
+
def __len__(self):
|
| 37 |
+
return len(self.map)
|
| 38 |
+
|
| 39 |
+
def __contains__(self, key):
|
| 40 |
+
return key in self.map
|
| 41 |
+
|
| 42 |
+
def add(self, key):
|
| 43 |
+
if key not in self.map:
|
| 44 |
+
end = self.end
|
| 45 |
+
curr = end[self.PREV]
|
| 46 |
+
curr[self.NEXT] = end[self.PREV] = self.map[key] = [key, curr, end]
|
| 47 |
+
|
| 48 |
+
def update(self, iterable):
|
| 49 |
+
for key in iterable:
|
| 50 |
+
self.add(key)
|
| 51 |
+
|
| 52 |
+
def discard(self, key):
|
| 53 |
+
if key in self.map:
|
| 54 |
+
key, prev, next = self.map.pop(key)
|
| 55 |
+
prev[self.NEXT] = next
|
| 56 |
+
next[self.PREV] = prev
|
| 57 |
+
|
| 58 |
+
def __iter__(self):
|
| 59 |
+
end = self.end
|
| 60 |
+
curr = end[self.NEXT]
|
| 61 |
+
while curr is not end:
|
| 62 |
+
yield curr[self.KEY]
|
| 63 |
+
curr = curr[self.NEXT]
|
| 64 |
+
|
| 65 |
+
def __reversed__(self):
|
| 66 |
+
end = self.end
|
| 67 |
+
curr = end[self.PREV]
|
| 68 |
+
while curr is not end:
|
| 69 |
+
yield curr[self.KEY]
|
| 70 |
+
curr = curr[self.PREV]
|
| 71 |
+
|
| 72 |
+
def pop(self, last=True):
|
| 73 |
+
if not self:
|
| 74 |
+
raise KeyError('set is empty')
|
| 75 |
+
key = next(reversed(self)) if last else next(iter(self))
|
| 76 |
+
self.discard(key)
|
| 77 |
+
return key
|
| 78 |
+
|
| 79 |
+
def __repr__(self):
|
| 80 |
+
if not self:
|
| 81 |
+
return '%s()' % (self.__class__.__name__,)
|
| 82 |
+
return '%s(%r)' % (self.__class__.__name__, list(self))
|
| 83 |
+
|
| 84 |
+
def __eq__(self, other):
|
| 85 |
+
if other is None:
|
| 86 |
+
return False
|
| 87 |
+
if isinstance(other, OrderedSet):
|
| 88 |
+
return len(self) == len(other) and list(self) == list(other)
|
| 89 |
+
return set(self) == set(other)
|
| 90 |
+
|
| 91 |
+
def __del__(self):
|
| 92 |
+
self.clear() # remove circular references
|
pool/shard002/Python/0025372_custom_freeze_graph.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
import tensorflow.compat.v1 as tf
|
| 5 |
+
|
| 6 |
+
# from: https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc
|
| 7 |
+
|
| 8 |
+
# The original freeze_graph function
|
| 9 |
+
# from tensorflow.python.tools.freeze_graph import freeze_graph
|
| 10 |
+
|
| 11 |
+
dir = os.path.dirname(os.path.realpath(__file__))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def freeze_graph(model_dir, output_node_names):
|
| 15 |
+
"""Extract the sub graph defined by the output nodes and convert
|
| 16 |
+
all its variables into constant
|
| 17 |
+
Args:
|
| 18 |
+
model_dir: the root folder containing the checkpoint state file
|
| 19 |
+
output_node_names: a string, containing all the output node's names,
|
| 20 |
+
comma separated
|
| 21 |
+
"""
|
| 22 |
+
if not tf.gfile.Exists(model_dir):
|
| 23 |
+
raise AssertionError(
|
| 24 |
+
"Export directory doesn't exists. Please specify an export "
|
| 25 |
+
"directory: %s" % model_dir)
|
| 26 |
+
|
| 27 |
+
if not output_node_names:
|
| 28 |
+
print("You need to supply the name of a node to --output_node_names.")
|
| 29 |
+
return -1
|
| 30 |
+
|
| 31 |
+
# We retrieve our checkpoint fullpath
|
| 32 |
+
checkpoint = tf.train.get_checkpoint_state(model_dir)
|
| 33 |
+
print(model_dir)
|
| 34 |
+
input_checkpoint = checkpoint.model_checkpoint_path
|
| 35 |
+
|
| 36 |
+
# We precise the file fullname of our freezed graph
|
| 37 |
+
absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1])
|
| 38 |
+
output_graph = absolute_model_dir + "/frozen_model.pb"
|
| 39 |
+
|
| 40 |
+
# We clear devices to allow TensorFlow to control on which device it will load operations
|
| 41 |
+
clear_devices = True
|
| 42 |
+
|
| 43 |
+
# We start a session using a temporary fresh Graph
|
| 44 |
+
with tf.Session(graph=tf.Graph()) as sess:
|
| 45 |
+
# We import the meta graph in the current default Graph
|
| 46 |
+
saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)
|
| 47 |
+
|
| 48 |
+
# We restore the weights
|
| 49 |
+
saver.restore(sess, input_checkpoint)
|
| 50 |
+
|
| 51 |
+
# We use a built-in TF helper to export variables to constants
|
| 52 |
+
output_graph_def = tf.graph_util.convert_variables_to_constants(
|
| 53 |
+
sess, # The session is used to retrieve the weights
|
| 54 |
+
tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes
|
| 55 |
+
output_node_names.split(",") # The output node names are used to select the usefull nodes
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# # Finally we serialize and dump the output graph to the filesystem
|
| 59 |
+
with tf.gfile.GFile(output_graph, "wb") as f:
|
| 60 |
+
f.write(output_graph_def.SerializeToString())
|
| 61 |
+
print("%d ops in the final graph." % len(output_graph_def.node))
|
| 62 |
+
|
| 63 |
+
if __name__ == '__main__':
|
| 64 |
+
parser = argparse.ArgumentParser()
|
| 65 |
+
parser.add_argument("--model_dir", type=str, default="", help="Model folder to export")
|
| 66 |
+
parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.")
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
|
| 69 |
+
freeze_graph(args.model_dir, args.output_node_names)
|
pool/shard002/Python/0025379_routes.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import tempfile
|
| 4 |
+
import shutil
|
| 5 |
+
|
| 6 |
+
from flask import request, redirect, url_for
|
| 7 |
+
from werkzeug.utils import secure_filename
|
| 8 |
+
|
| 9 |
+
from findex_gui.web import app, themes, db
|
| 10 |
+
from findex_gui.bin.misc import version
|
| 11 |
+
from findex_gui.controllers.admin.status.status import AdminStatusController
|
| 12 |
+
from findex_gui.controllers.amqp.forms import FormAmqpAdd
|
| 13 |
+
from findex_gui.controllers.options.options import OptionsController
|
| 14 |
+
from findex_gui.controllers.user.decorators import admin_required
|
| 15 |
+
from findex_gui.controllers.news.news import NewsController
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
#
|
| 19 |
+
# general
|
| 20 |
+
#
|
| 21 |
+
|
| 22 |
+
@app.route("/admin")
|
| 23 |
+
@admin_required
|
| 24 |
+
def admin_home():
|
| 25 |
+
return themes.render("main/home", theme="_admin", version=version)
|
| 26 |
+
|
| 27 |
+
@admin_required
|
| 28 |
+
def admin_appearance():
|
| 29 |
+
return themes.render("main/appearance", theme="_admin")
|
| 30 |
+
|
| 31 |
+
@app.route("/admin/metadata", methods=["POST", "GET"])
|
| 32 |
+
@admin_required
|
| 33 |
+
def admin_metadata():
|
| 34 |
+
if request.method == 'POST':
|
| 35 |
+
from findex_gui.bin.utils import log_msg
|
| 36 |
+
from findex_gui.controllers.meta.controller import MetaController
|
| 37 |
+
try:
|
| 38 |
+
MetaController.load_new_db()
|
| 39 |
+
except Exception as ex:
|
| 40 |
+
log_msg(str(ex), category="meta_import", level=3)
|
| 41 |
+
|
| 42 |
+
return redirect(request.url)
|
| 43 |
+
|
| 44 |
+
meta_movies_count = db.session.execute("SELECT COUNT(*) FROM meta_movies;").fetchone()
|
| 45 |
+
if meta_movies_count:
|
| 46 |
+
meta_movies_count = meta_movies_count[0]
|
| 47 |
+
|
| 48 |
+
meta_version = OptionsController.get("meta")
|
| 49 |
+
if meta_version:
|
| 50 |
+
meta_version = meta_version.val
|
| 51 |
+
|
| 52 |
+
return themes.render("main/metadata", theme="_admin",
|
| 53 |
+
meta_movies_count=meta_movies_count,
|
| 54 |
+
meta_version=meta_version)
|
| 55 |
+
|
| 56 |
+
#
|
| 57 |
+
# News
|
| 58 |
+
#
|
| 59 |
+
|
| 60 |
+
@app.route("/admin/news/overview")
|
| 61 |
+
@admin_required
|
| 62 |
+
def admin_news():
|
| 63 |
+
posts = NewsController.get(limit=10)
|
| 64 |
+
return themes.render("main/news/overview", theme="_admin", posts=posts)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@app.route("/admin/news/add")
|
| 68 |
+
@admin_required
|
| 69 |
+
def admin_news_add():
|
| 70 |
+
return themes.render("main/news/edit_add", theme="_admin")
|
| 71 |
+
|
| 72 |
+
@app.route("/admin/news/edit/<path:uid>")
|
| 73 |
+
@admin_required
|
| 74 |
+
def admin_news_edit(uid):
|
| 75 |
+
if not uid.isdigit():
|
| 76 |
+
raise Exception("uid must be an integer")
|
| 77 |
+
post = NewsController.get(uid=int(uid))
|
| 78 |
+
return themes.render("main/news/edit_add", theme="_admin", post=post)
|
| 79 |
+
|
| 80 |
+
@app.route("/admin/news/remove/<path:uid>")
|
| 81 |
+
@admin_required
|
| 82 |
+
def admin_news_remove(uid):
|
| 83 |
+
if not uid.isdigit():
|
| 84 |
+
raise Exception("uid must be an integer")
|
| 85 |
+
NewsController.remove(uid=int(uid))
|
| 86 |
+
return redirect(url_for("admin_news"))
|
| 87 |
+
|
| 88 |
+
#
|
| 89 |
+
# AMQP
|
| 90 |
+
#
|
| 91 |
+
|
| 92 |
+
@app.route("/admin/amqp/overview")
|
| 93 |
+
@admin_required
|
| 94 |
+
def admin_amqp_list():
|
| 95 |
+
return themes.render("main/amqp", theme="_admin")
|
| 96 |
+
|
| 97 |
+
@app.route("/admin/amqp/add")
|
| 98 |
+
@admin_required
|
| 99 |
+
def admin_amqp_add():
|
| 100 |
+
amqp_add = FormAmqpAdd(request.form)
|
| 101 |
+
return themes.render("main/amqp_add", theme="_admin", form_add=amqp_add)
|
pool/shard002/Python/0025385_data_to_text_file.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
|
| 3 |
+
Write a list of numbers to a text file
|
| 4 |
+
|
| 5 |
+
-----------------------------------------------------------
|
| 6 |
+
(c) 2013 Allegra Via and Kristian Rother
|
| 7 |
+
Licensed under the conditions of the Python License
|
| 8 |
+
|
| 9 |
+
This code appears in section 3.3.6 of the book
|
| 10 |
+
"Managing Biological Data with Python".
|
| 11 |
+
-----------------------------------------------------------
|
| 12 |
+
'''
|
| 13 |
+
|
| 14 |
+
data = [16.38, 139.90, 441.46, 29.03, 40.93, 202.07, 142.30, 346.00, 300.00]
|
| 15 |
+
|
| 16 |
+
out = []
|
| 17 |
+
for value in data:
|
| 18 |
+
out.append(str(value) + '\n')
|
| 19 |
+
open('results.txt', 'w').writelines(out)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Test
|
| 23 |
+
outP = []
|
| 24 |
+
num = 0
|
| 25 |
+
for valueP in data:
|
| 26 |
+
outP.append(str(num) + ':' + str(valueP) + '\n')
|
| 27 |
+
num = num + 1
|
| 28 |
+
open('resultsP.txt', 'w').writelines(outP)
|
pool/shard002/Python/0025387_stats.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licensed to the Apache Software Foundation (ASF) under one
|
| 2 |
+
# or more contributor license agreements. See the NOTICE file
|
| 3 |
+
# distributed with this work for additional information
|
| 4 |
+
# regarding copyright ownership. The ASF licenses this file
|
| 5 |
+
# to you under the Apache License, Version 2.0 (the
|
| 6 |
+
# "License"); you may not use this file except in compliance
|
| 7 |
+
# with the License. You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing,
|
| 12 |
+
# software distributed under the License is distributed on an
|
| 13 |
+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
| 14 |
+
# KIND, either express or implied. See the License for the
|
| 15 |
+
# specific language governing permissions and limitations
|
| 16 |
+
# under the License.
|
| 17 |
+
|
| 18 |
+
from blog.models import Post
|
| 19 |
+
import datetime
|
| 20 |
+
from bs4 import BeautifulSoup
|
| 21 |
+
import urllib2
|
| 22 |
+
|
| 23 |
+
def getWordCount():
|
| 24 |
+
posts = Post.objects.all()
|
| 25 |
+
|
| 26 |
+
wordcount = 0
|
| 27 |
+
|
| 28 |
+
for i in posts:
|
| 29 |
+
|
| 30 |
+
wordcount += len(i.content.split(' '))
|
| 31 |
+
|
| 32 |
+
wordcountInt = wordcount
|
| 33 |
+
|
| 34 |
+
wordcountString = format(wordcount, ",d")
|
| 35 |
+
|
| 36 |
+
return wordcountInt, wordcountString
|
| 37 |
+
|
| 38 |
+
def getPostCount():
|
| 39 |
+
posts = Post.objects.all()
|
| 40 |
+
|
| 41 |
+
postcount = len(posts)
|
| 42 |
+
|
| 43 |
+
return postcount
|
| 44 |
+
|
| 45 |
+
def daysSince():
|
| 46 |
+
last = Post.objects.all().order_by('-published')[0].published.replace(tzinfo=None)
|
| 47 |
+
now = datetime.datetime.now()
|
| 48 |
+
delta = now - last
|
| 49 |
+
return delta.days + 1
|
| 50 |
+
|
| 51 |
+
def suggestion():
|
| 52 |
+
page = urllib2.urlopen('http://techmeme.com').read()
|
| 53 |
+
soup = BeautifulSoup(page)
|
| 54 |
+
|
| 55 |
+
topItem = soup.find('strong').contents
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
firstLinkChar = str(topItem).find('href="') + 6
|
| 59 |
+
|
| 60 |
+
newlink = str(topItem)[firstLinkChar:]
|
| 61 |
+
|
| 62 |
+
lastLinkChar = newlink.find('"')
|
| 63 |
+
|
| 64 |
+
link = newlink[:lastLinkChar]
|
| 65 |
+
|
| 66 |
+
title = topItem[0].contents[0]
|
| 67 |
+
|
| 68 |
+
newtitle = ""
|
| 69 |
+
|
| 70 |
+
for char in title:
|
| 71 |
+
try:
|
| 72 |
+
newtitle += str(char)
|
| 73 |
+
except UnicodeEncodeError:
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
return newtitle, link
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
pool/shard002/Python/0025391_urls.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import core
|
| 2 |
+
from core.urls import urls_base
|
| 3 |
+
from django.contrib import admin
|
| 4 |
+
from django.urls import include, path
|
| 5 |
+
from django.conf.urls.i18n import i18n_patterns
|
| 6 |
+
from django.contrib.sitemaps.views import sitemap
|
| 7 |
+
from .sitemaps import RootSitemap
|
| 8 |
+
from .api.urls import urlpatterns as api_urls
|
| 9 |
+
from .views import (
|
| 10 |
+
Index,
|
| 11 |
+
FAQ,
|
| 12 |
+
Contacts,
|
| 13 |
+
Students,
|
| 14 |
+
CourseView,
|
| 15 |
+
PayView,
|
| 16 |
+
Agreement,
|
| 17 |
+
TestCallback,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
courses_urls = ([
|
| 22 |
+
path('<slug>', CourseView.as_view(), name="course"),
|
| 23 |
+
# path(r'^$', include('core.urls', namespace='core')),
|
| 24 |
+
# path(r'^articles/', include('articles.urls', namespace='articles')),
|
| 25 |
+
], 'courses')
|
| 26 |
+
|
| 27 |
+
# Error handlers
|
| 28 |
+
#
|
| 29 |
+
# https://docs.djangoproject.com/en/dev/ref/urls/#django.conf.urls.handler400
|
| 30 |
+
#
|
| 31 |
+
# def err404(request):
|
| 32 |
+
# if request.method == 'GET':
|
| 33 |
+
# return HttpResponseNotFound(render_to_string('404.html', locals()))
|
| 34 |
+
# else:
|
| 35 |
+
# return HttpResponseNotFound('404')
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# def err500(request):
|
| 39 |
+
# if request.method == 'GET':
|
| 40 |
+
# return HttpResponseNotFound(render_to_string('500.html', locals()))
|
| 41 |
+
# else:
|
| 42 |
+
# return HttpResponseNotFound('500')
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# handler404 = 'proj.urls.err404'
|
| 46 |
+
# handler500 = 'pashinin.urls.err500'
|
| 47 |
+
# handler404 = IndexView.as_view()
|
| 48 |
+
|
| 49 |
+
sitemaps = {
|
| 50 |
+
'static': RootSitemap,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
urlpatterns = [
|
| 54 |
+
*core.urls.urlpatterns,
|
| 55 |
+
path('accounts/', include('allauth.urls')),
|
| 56 |
+
# path('accounts/vk/login/callback/', TestCallback.as_view(), name='cb'),
|
| 57 |
+
path(
|
| 58 |
+
'sitemap.xml',
|
| 59 |
+
sitemap,
|
| 60 |
+
{'sitemaps': sitemaps},
|
| 61 |
+
name='django.contrib.sitemaps.views.sitemap'
|
| 62 |
+
),
|
| 63 |
+
path('articles/', include('articles.urls', namespace='articles')),
|
| 64 |
+
path('api/', include(api_urls, namespace='api')),
|
| 65 |
+
path('courses/', include(courses_urls, namespace='courses')),
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
urlpatterns += i18n_patterns(
|
| 69 |
+
path('', Index.as_view(), name="index"),
|
| 70 |
+
# path(r'^$', Index.as_view(), name="lazysignup_convert"),
|
| 71 |
+
path('pay', PayView.as_view(), name='pay'),
|
| 72 |
+
path('contacts', Contacts.as_view(), name='contacts'),
|
| 73 |
+
path('students', Students.as_view(), name='students'),
|
| 74 |
+
path('faq', FAQ.as_view(), name="faq"),
|
| 75 |
+
path('agreement', Agreement.as_view(), name="agreement"),
|
| 76 |
+
# path('login', Login.as_view(), name='login'),
|
| 77 |
+
|
| 78 |
+
# This really needs to be here, not just in 'core' urls.py.
|
| 79 |
+
# Because admin templates are getting reverse urls with "admin:..."
|
| 80 |
+
# So if you wrap admin inside some app - reverse will throw an error
|
| 81 |
+
# path('_/django/', admin.site.urls),
|
| 82 |
+
|
| 83 |
+
prefix_default_language=False
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# urlpatterns += [
|
| 87 |
+
# path(r'^cas/', include('mama_cas.urls'))
|
| 88 |
+
# ]
|
pool/shard002/Python/0025397_sitemap.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
# <markment - markdown-based documentation generator for python>
|
| 4 |
+
# Copyright (C) <2013> Gabriel Falc達o <gabriel@nacaolivre.org>
|
| 5 |
+
#
|
| 6 |
+
# This program is free software: you can redistribute it and/or modify
|
| 7 |
+
# it under the terms of the GNU General Public License as published by
|
| 8 |
+
# the Free Software Foundation, either version 3 of the License, or
|
| 9 |
+
# (at your option) any later version.
|
| 10 |
+
#
|
| 11 |
+
# This program is distributed in the hope that it will be useful,
|
| 12 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 13 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 14 |
+
# GNU General Public License for more details.
|
| 15 |
+
#
|
| 16 |
+
# You should have received a copy of the GNU General Public License
|
| 17 |
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 18 |
+
|
| 19 |
+
from __future__ import unicode_literals
|
| 20 |
+
from markment.events import after
|
| 21 |
+
from markment.fs import Node
|
| 22 |
+
from lxml import etree
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@after.all
|
| 26 |
+
def save_sitemap(event, args, project, theme, generated):
|
| 27 |
+
if not args.SITEMAP_PREFIX:
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
urlset = etree.Element("urlset")
|
| 31 |
+
destination = Node(args.OUTPUT)
|
| 32 |
+
|
| 33 |
+
NAME = 'sitemap.xml'
|
| 34 |
+
|
| 35 |
+
for item in filter(lambda x: x.endswith('html'), generated):
|
| 36 |
+
relative = destination.relative(item)
|
| 37 |
+
url = etree.SubElement(urlset, "url")
|
| 38 |
+
loc = etree.SubElement(url, "loc")
|
| 39 |
+
loc.text = "{0}/{1}".format(
|
| 40 |
+
args.SITEMAP_PREFIX.rstrip('/'),
|
| 41 |
+
relative,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
with destination.open(NAME, 'w') as f:
|
| 45 |
+
f.write(etree.tostring(urlset, pretty_print=True).decode('utf-8'))
|
pool/shard002/Python/0025398_test_parse_omim.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scout.parse.omim import (
|
| 2 |
+
get_mim_phenotypes,
|
| 3 |
+
parse_genemap2,
|
| 4 |
+
parse_genemap2_phenotypes,
|
| 5 |
+
parse_mim2gene,
|
| 6 |
+
parse_mim_titles,
|
| 7 |
+
parse_omim_line,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_parse_omim_line():
|
| 12 |
+
## GIVEN a header and a line
|
| 13 |
+
header = ["a", "b", "c"]
|
| 14 |
+
line = "1\t2\t3"
|
| 15 |
+
## WHEN parsing the omim line
|
| 16 |
+
res = parse_omim_line(line, header)
|
| 17 |
+
|
| 18 |
+
## THEN assert a dict was built by the header and the line
|
| 19 |
+
assert res["a"] == "1"
|
| 20 |
+
assert res["b"] == "2"
|
| 21 |
+
assert res["c"] == "3"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_parse_genemap2_phenotype_entry_single():
|
| 25 |
+
# GIVEN a phenotype description with one entry
|
| 26 |
+
entry = "Ehlers-Danlos syndrome, progeroid type," " 2, 615349 (3), Autosomal recessive"
|
| 27 |
+
# WHEN parsing the entry
|
| 28 |
+
parsed_entries = parse_genemap2_phenotypes(entry)
|
| 29 |
+
parsed_entry = parsed_entries[0]
|
| 30 |
+
# THEN assert that the information was parsed correct
|
| 31 |
+
|
| 32 |
+
assert parsed_entry["mim_number"] == 615349
|
| 33 |
+
assert parsed_entry["inheritance"] == {"AR"}
|
| 34 |
+
assert parsed_entry["status"] == "established"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_parse_genemap(genemap_lines):
|
| 38 |
+
|
| 39 |
+
for res in parse_genemap2(genemap_lines):
|
| 40 |
+
assert res["Chromosome"] == "chr1"
|
| 41 |
+
assert res["mim_number"] == 615291
|
| 42 |
+
assert res["hgnc_symbol"] == "B3GALT6"
|
| 43 |
+
assert res["inheritance"] == set(["AR"])
|
| 44 |
+
for phenotype in res["phenotypes"]:
|
| 45 |
+
assert phenotype["mim_number"]
|
| 46 |
+
assert phenotype["inheritance"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_parse_genemap_file(genemap_handle):
|
| 50 |
+
# WHEN parsing a valid genemap handle
|
| 51 |
+
i = 0
|
| 52 |
+
for i, res in enumerate(parse_genemap2(genemap_handle)):
|
| 53 |
+
assert "mim_number" in res
|
| 54 |
+
# THEN items are returned
|
| 55 |
+
assert i > 0
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_parse_mim2gene(mim2gene_lines):
|
| 59 |
+
## GIVEN some lines from a mim2gene file
|
| 60 |
+
mim2gene_info = parse_mim2gene(mim2gene_lines)
|
| 61 |
+
|
| 62 |
+
## WHEN parsing the lines
|
| 63 |
+
first_entry = next(mim2gene_info)
|
| 64 |
+
|
| 65 |
+
## ASSERT that they are correctly parsed
|
| 66 |
+
|
| 67 |
+
# First entry is a gene so it should have a hgnc symbol
|
| 68 |
+
assert first_entry["mim_number"] == 615291
|
| 69 |
+
assert first_entry["entry_type"] == "gene"
|
| 70 |
+
assert first_entry["hgnc_symbol"] == "B3GALT6"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_parse_mim2gene_file(mim2gene_handle):
|
| 74 |
+
i = 0
|
| 75 |
+
# Just check that the file exists and that some result is given
|
| 76 |
+
for i, res in enumerate(parse_mim2gene(mim2gene_handle)):
|
| 77 |
+
assert "mim_number" in res
|
| 78 |
+
assert i > 0
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_get_mim_phenotypes(genemap_lines):
|
| 82 |
+
## GIVEN a small testdata set
|
| 83 |
+
|
| 84 |
+
# This will return a dictionary with mim number as keys and
|
| 85 |
+
# phenotypes as values
|
| 86 |
+
|
| 87 |
+
## WHEN parsing the phenotypes
|
| 88 |
+
phenotypes = get_mim_phenotypes(genemap_lines=genemap_lines)
|
| 89 |
+
|
| 90 |
+
## THEN assert they where parsed in a correct way
|
| 91 |
+
|
| 92 |
+
# There was only one line in genemap_lines that have two phenotypes
|
| 93 |
+
# so we expect that there should be two phenotypes
|
| 94 |
+
|
| 95 |
+
assert len(phenotypes) == 2
|
| 96 |
+
|
| 97 |
+
term = phenotypes[615349]
|
| 98 |
+
|
| 99 |
+
assert term["inheritance"] == set(["AR"])
|
| 100 |
+
assert term["hgnc_symbols"] == set(["B3GALT6"])
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_get_mim_phenotypes_file(genemap_handle):
|
| 104 |
+
phenotypes = get_mim_phenotypes(genemap_lines=genemap_handle)
|
| 105 |
+
i = 0
|
| 106 |
+
for i, mim_nr in enumerate(phenotypes):
|
| 107 |
+
assert phenotypes[mim_nr]["mim_number"]
|
| 108 |
+
|
| 109 |
+
assert i > 0
|
pool/shard002/Python/0025400_sparql.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Utilities for SPARQL language
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from __future__ import unicode_literals
|
| 6 |
+
from common.settings import ONLINE_ENABLED
|
| 7 |
+
from knowledge.namespaces import NAMESPACES_DICT, RDF, RDFS, FOAF, ONTOLOGY, DCTERMS
|
| 8 |
+
from rdflib.plugins.sparql import prepareQuery
|
| 9 |
+
from rdflib import Graph, Literal, URIRef
|
| 10 |
+
from SPARQLWrapper import SPARQLWrapper, JSON
|
| 11 |
+
from urllib import quote_plus
|
| 12 |
+
from urllib2 import HTTPError
|
| 13 |
+
|
| 14 |
+
import cjson
|
| 15 |
+
import logging
|
| 16 |
+
#import traceback
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def prepared_query(query_string):
|
| 23 |
+
"""
|
| 24 |
+
Returns prepared query with initialized standard namespaces bindings.
|
| 25 |
+
"""
|
| 26 |
+
return prepareQuery(query_string, initNs=NAMESPACES_DICT)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def retrieve_graph_from_dbpedia(term):
|
| 30 |
+
assert ONLINE_ENABLED
|
| 31 |
+
logger.info('online access - DBpedia: {term}'.format(term=unicode(term)))
|
| 32 |
+
term_utf = term.encode('utf-8')
|
| 33 |
+
term_url = quote_plus(term_utf, safe=str("/:#,()'"))
|
| 34 |
+
#print '---'
|
| 35 |
+
#print 'term_url', term_url
|
| 36 |
+
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
|
| 37 |
+
#query = """
|
| 38 |
+
# SELECT ?p ?o
|
| 39 |
+
# WHERE {{ <{term_url}> ?p ?o }}
|
| 40 |
+
#""".format(term_url=term_url)
|
| 41 |
+
query = """
|
| 42 |
+
SELECT ?p ?o
|
| 43 |
+
WHERE {{
|
| 44 |
+
<{term_url}> ?p ?o
|
| 45 |
+
FILTER( STRSTARTS(STR(?p), "{foaf}")
|
| 46 |
+
|| STRSTARTS(STR(?p), "{rdf}")
|
| 47 |
+
|| STRSTARTS(STR(?p), "{rdfs}")
|
| 48 |
+
|| STRSTARTS(STR(?p), "{dcterms}")
|
| 49 |
+
|| STRSTARTS(STR(?p), "{ontology}"))
|
| 50 |
+
FILTER (isURI(?o) || langMatches(lang(?o), "EN"))
|
| 51 |
+
}}
|
| 52 |
+
""".format(term_url=term_url,
|
| 53 |
+
foaf=unicode(FOAF),
|
| 54 |
+
rdf=unicode(RDF),
|
| 55 |
+
rdfs=unicode(RDFS),
|
| 56 |
+
dcterms=unicode(DCTERMS),
|
| 57 |
+
ontology=unicode(ONTOLOGY))
|
| 58 |
+
|
| 59 |
+
sparql.setQuery(query.encode('utf-8'))
|
| 60 |
+
sparql.setReturnFormat(JSON)
|
| 61 |
+
try:
|
| 62 |
+
results = sparql.query()
|
| 63 |
+
# workaround for "Invalid \escape" error which can be raised by
|
| 64 |
+
# convert()
|
| 65 |
+
body = results.response.read()
|
| 66 |
+
results = cjson.decode(body)
|
| 67 |
+
except HTTPError as exc:
|
| 68 |
+
# can occur if DBpedia is under maintenance (quite often)
|
| 69 |
+
logger.error('Getting graph for {term} failed; {message}; {excType}'
|
| 70 |
+
.format(term=term, message=exc.message, excType=unicode(type(exc))))
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
# create graph and bind relevant namespaces
|
| 74 |
+
graph = Graph()
|
| 75 |
+
for prefix, namespace in NAMESPACES_DICT.items():
|
| 76 |
+
graph.bind(prefix, namespace)
|
| 77 |
+
|
| 78 |
+
LITERAL_MAX_LENGTH = 600
|
| 79 |
+
for result in results["results"]["bindings"]:
|
| 80 |
+
try:
|
| 81 |
+
p = URIRef(result['p']['value'])
|
| 82 |
+
# filter wikiPageRevisionID, wikiPageExternalLike etc.
|
| 83 |
+
if p.startswith(ONTOLOGY['wiki']):
|
| 84 |
+
continue
|
| 85 |
+
if result['o']['type'] == 'uri':
|
| 86 |
+
o = URIRef(result['o']['value'])
|
| 87 |
+
else:
|
| 88 |
+
o = Literal(result['o']['value'])
|
| 89 |
+
# if object is too long (e.g. abstract, ignore it)
|
| 90 |
+
if len(o) > LITERAL_MAX_LENGTH:
|
| 91 |
+
continue
|
| 92 |
+
graph.add((term, p, o))
|
| 93 |
+
#print type(p), p
|
| 94 |
+
#print type(o), o
|
| 95 |
+
#print '*'
|
| 96 |
+
except KeyError:
|
| 97 |
+
continue
|
| 98 |
+
|
| 99 |
+
# check if the graph is not empty
|
| 100 |
+
if not graph:
|
| 101 |
+
logger.warning('Retrieved empty graph for ' + unicode(term))
|
| 102 |
+
|
| 103 |
+
return graph
|
pool/shard002/Python/0025403_handshake.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The :mod:`websockets.handshake` module deals with the WebSocket opening
|
| 3 |
+
handshake according to `section 4 of RFC 6455`_.
|
| 4 |
+
|
| 5 |
+
.. _section 4 of RFC 6455: http://tools.ietf.org/html/rfc6455#section-4
|
| 6 |
+
|
| 7 |
+
It provides functions to implement the handshake with any existing HTTP
|
| 8 |
+
library. You must pass to these functions:
|
| 9 |
+
|
| 10 |
+
- A ``set_header`` function accepting a header name and a header value,
|
| 11 |
+
- A ``get_header`` function accepting a header name and returning the header
|
| 12 |
+
value.
|
| 13 |
+
|
| 14 |
+
The inputs and outputs of ``get_header`` and ``set_header`` are :class:`str`
|
| 15 |
+
objects containing only ASCII characters.
|
| 16 |
+
|
| 17 |
+
Some checks cannot be performed because they depend too much on the
|
| 18 |
+
context; instead, they're documented below.
|
| 19 |
+
|
| 20 |
+
To accept a connection, a server must:
|
| 21 |
+
|
| 22 |
+
- Read the request, check that the method is GET, and check the headers with
|
| 23 |
+
:func:`check_request`,
|
| 24 |
+
- Send a 101 response to the client with the headers created by
|
| 25 |
+
:func:`build_response` if the request is valid; otherwise, send an
|
| 26 |
+
appropriate HTTP error code.
|
| 27 |
+
|
| 28 |
+
To open a connection, a client must:
|
| 29 |
+
|
| 30 |
+
- Send a GET request to the server with the headers created by
|
| 31 |
+
:func:`build_request`,
|
| 32 |
+
- Read the response, check that the status code is 101, and check the headers
|
| 33 |
+
with :func:`check_response`.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
'build_request', 'check_request',
|
| 38 |
+
'build_response', 'check_response',
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
import base64
|
| 42 |
+
import hashlib
|
| 43 |
+
import random
|
| 44 |
+
|
| 45 |
+
from .exceptions import InvalidHandshake
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def build_request(set_header):
|
| 52 |
+
"""
|
| 53 |
+
Build a handshake request to send to the server.
|
| 54 |
+
|
| 55 |
+
Return the ``key`` which must be passed to :func:`check_response`.
|
| 56 |
+
"""
|
| 57 |
+
rand = bytes(random.getrandbits(8) for _ in range(16))
|
| 58 |
+
key = base64.b64encode(rand).decode()
|
| 59 |
+
set_header('Upgrade', 'WebSocket')
|
| 60 |
+
set_header('Connection', 'Upgrade')
|
| 61 |
+
set_header('Sec-WebSocket-Key', key)
|
| 62 |
+
set_header('Sec-WebSocket-Version', '13')
|
| 63 |
+
return key
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def check_request(get_header):
|
| 67 |
+
"""
|
| 68 |
+
Check a handshake request received from the client.
|
| 69 |
+
|
| 70 |
+
If the handshake is valid, this function returns the ``key`` which must be
|
| 71 |
+
passed to :func:`build_response`.
|
| 72 |
+
|
| 73 |
+
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
|
| 74 |
+
exception and the server must return an error like 400 Bad Request.
|
| 75 |
+
|
| 76 |
+
This function doesn't verify that the request is an HTTP/1.1 or higher GET
|
| 77 |
+
request and doesn't perform Host and Origin checks. These controls are
|
| 78 |
+
usually performed earlier in the HTTP request handling code. They're the
|
| 79 |
+
responsibility of the caller.
|
| 80 |
+
"""
|
| 81 |
+
try:
|
| 82 |
+
assert get_header('Upgrade').lower() == 'websocket'
|
| 83 |
+
assert any(
|
| 84 |
+
token.strip() == 'upgrade'
|
| 85 |
+
for token in get_header('Connection').lower().split(','))
|
| 86 |
+
key = get_header('Sec-WebSocket-Key')
|
| 87 |
+
assert len(base64.b64decode(key.encode(), validate=True)) == 16
|
| 88 |
+
assert get_header('Sec-WebSocket-Version') == '13'
|
| 89 |
+
except Exception as exc:
|
| 90 |
+
raise InvalidHandshake("Invalid request") from exc
|
| 91 |
+
else:
|
| 92 |
+
return key
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def build_response(set_header, key):
|
| 96 |
+
"""
|
| 97 |
+
Build a handshake response to send to the client.
|
| 98 |
+
|
| 99 |
+
``key`` comes from :func:`check_request`.
|
| 100 |
+
"""
|
| 101 |
+
set_header('Upgrade', 'WebSocket')
|
| 102 |
+
set_header('Connection', 'Upgrade')
|
| 103 |
+
set_header('Sec-WebSocket-Accept', accept(key))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def check_response(get_header, key):
|
| 107 |
+
"""
|
| 108 |
+
Check a handshake response received from the server.
|
| 109 |
+
|
| 110 |
+
``key`` comes from :func:`build_request`.
|
| 111 |
+
|
| 112 |
+
If the handshake is valid, this function returns ``None``.
|
| 113 |
+
|
| 114 |
+
Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake`
|
| 115 |
+
exception.
|
| 116 |
+
|
| 117 |
+
This function doesn't verify that the response is an HTTP/1.1 or higher
|
| 118 |
+
response with a 101 status code. These controls are the responsibility of
|
| 119 |
+
the caller.
|
| 120 |
+
"""
|
| 121 |
+
try:
|
| 122 |
+
assert get_header('Upgrade').lower() == 'websocket'
|
| 123 |
+
assert any(
|
| 124 |
+
token.strip() == 'upgrade'
|
| 125 |
+
for token in get_header('Connection').lower().split(','))
|
| 126 |
+
assert get_header('Sec-WebSocket-Accept') == accept(key)
|
| 127 |
+
except Exception as exc:
|
| 128 |
+
raise InvalidHandshake("Invalid response") from exc
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def accept(key):
|
| 132 |
+
sha1 = hashlib.sha1((key + GUID).encode()).digest()
|
| 133 |
+
return base64.b64encode(sha1).decode()
|
pool/shard002/Python/0025409_vcftobedpeconverter_tests.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from unittest import TestCase
|
| 2 |
+
from svtools.vcftobedpeconverter import VcfToBedpeConverter
|
| 3 |
+
from svtools.vcf.file import Vcf
|
| 4 |
+
from svtools.vcf.variant import Variant
|
| 5 |
+
from svtools.bedpe import Bedpe
|
| 6 |
+
|
| 7 |
+
class TestVcfToBedpeConverter(TestCase):
|
| 8 |
+
def setUp(self):
|
| 9 |
+
self.converter = VcfToBedpeConverter()
|
| 10 |
+
header_lines = [
|
| 11 |
+
'##fileformat=VCFv4.2',
|
| 12 |
+
'##fileDate=20090805',
|
| 13 |
+
'##reference=file:///seq/references/1000GenomesPilot-NCBI36.fasta',
|
| 14 |
+
'##INFO=<ID=DP,Number=1,Type=Integer,Description="Total Depth">',
|
| 15 |
+
'##INFO=<ID=AF,Number=A,Type=Float,Description="Allele Frequency">',
|
| 16 |
+
'##INFO=<ID=END,Number=1,Type=Integer,Description="End position of the variant">',
|
| 17 |
+
'##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">',
|
| 18 |
+
'#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001']
|
| 19 |
+
self.vcf = Vcf()
|
| 20 |
+
self.vcf.add_header(header_lines)
|
| 21 |
+
|
| 22 |
+
def test_bnd_breakpoints(self):
|
| 23 |
+
vcf_array1 = ['1', '20000', '235', 'T', 'A[1:6[', '0.00', '.', '.', 'GT', '0/0']
|
| 24 |
+
v1 = Variant(vcf_array1, self.vcf)
|
| 25 |
+
self.assertEqual(
|
| 26 |
+
self.converter.bnd_breakpoints(v1),
|
| 27 |
+
('1', 20000, 20000, '1', 5, 5, '+', '-'))
|
| 28 |
+
vcf_array2 = ['1', '20000', '235', 'T', ']1:6]N', '0.00', '.', '.', 'GT', '0/0']
|
| 29 |
+
v2 = Variant(vcf_array2, self.vcf)
|
| 30 |
+
self.assertEqual(
|
| 31 |
+
self.converter.bnd_breakpoints(v2),
|
| 32 |
+
('1', 19999, 19999, '1', 6, 6, '-', '+'))
|
| 33 |
+
|
| 34 |
+
def test_simple_breakpoints(self):
|
| 35 |
+
vcf_array1 = ['1', '20000', '235', 'T', '<DEL>', '0.00', '.', 'END=20500', 'GT', '0/0']
|
| 36 |
+
v1 = Variant(vcf_array1, self.vcf)
|
| 37 |
+
self.assertEqual(
|
| 38 |
+
self.converter.simple_breakpoints(v1),
|
| 39 |
+
('1', 20000, 20000, '1', 20500, 20500, '+', '-'))
|
| 40 |
+
vcf_array2 = ['1', '20000', '235', 'T', '<DEL>', '0.00', '.', 'END=20500;STRANDS=-+:2', 'GT', '0/0']
|
| 41 |
+
v2 = Variant(vcf_array2, self.vcf)
|
| 42 |
+
self.assertEqual(
|
| 43 |
+
self.converter.simple_breakpoints(v2),
|
| 44 |
+
('1', 20000, 20000, '1', 20500, 20500, '-', '+'))
|
| 45 |
+
vcf_array3 = ['1', '20000', '235', 'T', '<DEL>', '0.00', '.', 'STRANDS=--:2', 'GT', '0/0']
|
| 46 |
+
v3 = Variant(vcf_array3, self.vcf)
|
| 47 |
+
with self.assertRaises(ValueError):
|
| 48 |
+
self.converter.simple_breakpoints(v3)
|
| 49 |
+
|
| 50 |
+
def test_adjust_coordinate(self):
|
| 51 |
+
vcf_array1 = ['1', '20000', '235', 'T', '<DEL>', '0.00', '.', 'CIEND=-50,50', 'GT', '0/0']
|
| 52 |
+
v1 = Variant(vcf_array1, self.vcf)
|
| 53 |
+
self.assertEqual(
|
| 54 |
+
self.converter.adjust_coordinate(v1, 'CIEND', 500, 1000),
|
| 55 |
+
(450, 1050))
|
| 56 |
+
self.assertEqual(
|
| 57 |
+
self.converter.adjust_coordinate(v1, 'CIPOS', 500, 1000),
|
| 58 |
+
(500, 1000))
|
| 59 |
+
vcf_array2 = ['1', '20000', '235', 'T', '<DEL>', '0.00', '.', 'CIEND=50', 'GT', '0/0']
|
| 60 |
+
v2 = Variant(vcf_array2, self.vcf)
|
| 61 |
+
with self.assertRaises(ValueError):
|
| 62 |
+
self.converter.adjust_coordinate(v2, 'CIEND', 500, 1000)
|
pool/shard002/Python/0025418_feedback_tags.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django import template
|
| 2 |
+
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
from feedback.models import Feedback, Favorite, Event
|
| 6 |
+
|
| 7 |
+
register = template.Library()
|
| 8 |
+
|
| 9 |
+
@register.filter
|
| 10 |
+
def rating_average(feedback, num=False):
|
| 11 |
+
ratings = [f.rating for f in feedback if f.rating]
|
| 12 |
+
if not ratings:
|
| 13 |
+
return ''
|
| 14 |
+
avg = sum(ratings) / float(len(ratings))
|
| 15 |
+
if num:
|
| 16 |
+
return avg
|
| 17 |
+
return '%.2f' % avg
|
| 18 |
+
|
| 19 |
+
@register.filter
|
| 20 |
+
def interest_average(feedback, num=False):
|
| 21 |
+
ratings = [f.interest for f in feedback if f.interest]
|
| 22 |
+
if not ratings:
|
| 23 |
+
return ''
|
| 24 |
+
avg = sum(ratings) / float(len(ratings))
|
| 25 |
+
if num:
|
| 26 |
+
return avg
|
| 27 |
+
return '%.2f' % avg
|
| 28 |
+
|
| 29 |
+
@register.filter
|
| 30 |
+
def feedback_count(feedback):
|
| 31 |
+
non_empty = [f for f in feedback if (f.interest or f.rating or f.comments)]
|
| 32 |
+
return str(len(non_empty))
|
| 33 |
+
|
| 34 |
+
@register.filter
|
| 35 |
+
def all_feedback(applicant):
|
| 36 |
+
feedback = Feedback.objects.filter(applicant=applicant)
|
| 37 |
+
return [f for f in feedback]
|
| 38 |
+
|
| 39 |
+
@register.filter
|
| 40 |
+
def alumni_filter(feedback):
|
| 41 |
+
return [f for f in feedback if (f.scholar.class_year < 2013 or f.scholar.class_year is None)]
|
| 42 |
+
|
| 43 |
+
@register.filter
|
| 44 |
+
def senior_filter(feedback):
|
| 45 |
+
return [f for f in feedback if f.scholar.class_year == 2013]
|
| 46 |
+
|
| 47 |
+
@register.filter
|
| 48 |
+
def other_filter(feedback):
|
| 49 |
+
return [f for f in feedback if f.scholar.class_year > 2013]
|
| 50 |
+
|
| 51 |
+
@register.filter
|
| 52 |
+
def favorite_filter(applicant):
|
| 53 |
+
favs = Favorite.objects.filter(applicant=applicant)
|
| 54 |
+
return [f for f in favs]
|
| 55 |
+
|
| 56 |
+
@register.inclusion_tag('macro/feedback_header.html')
|
| 57 |
+
def feedback_header(active, user, event_name):
|
| 58 |
+
return {'active': active, 'user': user, 'event_name': event_name}
|
| 59 |
+
|
| 60 |
+
@register.inclusion_tag('macro/form_element.html')
|
| 61 |
+
def form_element(element, label, style, add_form_control=True):
|
| 62 |
+
return {'element': element, 'style': style, 'label': label, 'add_form_control': add_form_control}
|
| 63 |
+
|
| 64 |
+
@register.filter
|
| 65 |
+
def convert_attended(attended):
|
| 66 |
+
return 'Yes' if attended else 'No'
|
| 67 |
+
|
| 68 |
+
# works on the Django user, not McUser
|
| 69 |
+
@register.filter
|
| 70 |
+
def is_staff_for(user, event_name):
|
| 71 |
+
try:
|
| 72 |
+
event = Event.objects.get(name=event_name)
|
| 73 |
+
except Event.DoesNotExist:
|
| 74 |
+
return False
|
| 75 |
+
return user.mcuser in event.staff.all()
|
| 76 |
+
|
| 77 |
+
@register.filter
|
| 78 |
+
def can_read_data_for(user, event_name):
|
| 79 |
+
try:
|
| 80 |
+
event = Event.objects.get(name=event_name)
|
| 81 |
+
except Event.DoesNotExist:
|
| 82 |
+
return False
|
| 83 |
+
return user.mcuser in event.staff.all() or user.mcuser in event.selection.all()
|
pool/shard002/Python/0025419_disk_filter.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2012 OpenStack Foundation
|
| 2 |
+
# All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
| 5 |
+
# not use this file except in compliance with the License. You may obtain
|
| 6 |
+
# a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
| 12 |
+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
| 13 |
+
# License for the specific language governing permissions and limitations
|
| 14 |
+
# under the License.
|
| 15 |
+
|
| 16 |
+
from oslo_log import log as logging
|
| 17 |
+
|
| 18 |
+
import nova.conf
|
| 19 |
+
from nova.i18n import _LW
|
| 20 |
+
from nova.scheduler import filters
|
| 21 |
+
from nova.scheduler.filters import utils
|
| 22 |
+
|
| 23 |
+
LOG = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
CONF = nova.conf.CONF
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DiskFilter(filters.BaseHostFilter):
|
| 29 |
+
"""Disk Filter with over subscription flag."""
|
| 30 |
+
|
| 31 |
+
def _get_disk_allocation_ratio(self, host_state, spec_obj):
|
| 32 |
+
return CONF.disk_allocation_ratio
|
| 33 |
+
|
| 34 |
+
def host_passes(self, host_state, spec_obj):
|
| 35 |
+
"""Filter based on disk usage."""
|
| 36 |
+
requested_disk = (1024 * (spec_obj.root_gb +
|
| 37 |
+
spec_obj.ephemeral_gb) +
|
| 38 |
+
spec_obj.swap)
|
| 39 |
+
|
| 40 |
+
free_disk_mb = host_state.free_disk_mb
|
| 41 |
+
total_usable_disk_mb = host_state.total_usable_disk_gb * 1024
|
| 42 |
+
|
| 43 |
+
disk_allocation_ratio = self._get_disk_allocation_ratio(
|
| 44 |
+
host_state, spec_obj)
|
| 45 |
+
|
| 46 |
+
disk_mb_limit = total_usable_disk_mb * disk_allocation_ratio
|
| 47 |
+
used_disk_mb = total_usable_disk_mb - free_disk_mb
|
| 48 |
+
usable_disk_mb = disk_mb_limit - used_disk_mb
|
| 49 |
+
|
| 50 |
+
if not usable_disk_mb >= requested_disk:
|
| 51 |
+
LOG.debug("%(host_state)s does not have %(requested_disk)s MB "
|
| 52 |
+
"usable disk, it only has %(usable_disk_mb)s MB usable "
|
| 53 |
+
"disk.", {'host_state': host_state,
|
| 54 |
+
'requested_disk': requested_disk,
|
| 55 |
+
'usable_disk_mb': usable_disk_mb})
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
disk_gb_limit = disk_mb_limit / 1024
|
| 59 |
+
host_state.limits['disk_gb'] = disk_gb_limit
|
| 60 |
+
return True
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class AggregateDiskFilter(DiskFilter):
|
| 64 |
+
"""AggregateDiskFilter with per-aggregate disk allocation ratio flag.
|
| 65 |
+
|
| 66 |
+
Fall back to global disk_allocation_ratio if no per-aggregate setting
|
| 67 |
+
found.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
def _get_disk_allocation_ratio(self, host_state, spec_obj):
|
| 71 |
+
aggregate_vals = utils.aggregate_values_from_key(
|
| 72 |
+
host_state,
|
| 73 |
+
'disk_allocation_ratio')
|
| 74 |
+
try:
|
| 75 |
+
ratio = utils.validate_num_values(
|
| 76 |
+
aggregate_vals, CONF.disk_allocation_ratio, cast_to=float)
|
| 77 |
+
except ValueError as e:
|
| 78 |
+
LOG.warning(_LW("Could not decode disk_allocation_ratio: '%s'"), e)
|
| 79 |
+
ratio = CONF.disk_allocation_ratio
|
| 80 |
+
|
| 81 |
+
return ratio
|
pool/shard002/Python/0025420_committees.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import lxml.html
|
| 2 |
+
from openstates.scrape import Scraper, Organization
|
| 3 |
+
|
| 4 |
+
from .common import SESSION_TERMS
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class WICommitteeScraper(Scraper):
|
| 8 |
+
def scrape_committee(self, name, url, chamber):
|
| 9 |
+
org = Organization(name=name, chamber=chamber, classification="committee")
|
| 10 |
+
org.add_source(url)
|
| 11 |
+
data = self.get(url).text
|
| 12 |
+
doc = lxml.html.fromstring(data)
|
| 13 |
+
|
| 14 |
+
for leg in doc.xpath('//div[@id="members"]/div[@id="members"]/p/a/text()'):
|
| 15 |
+
leg = leg.replace("Representative ", "")
|
| 16 |
+
leg = leg.replace("Senator ", "")
|
| 17 |
+
leg = leg.strip()
|
| 18 |
+
if " (" in leg:
|
| 19 |
+
leg, role = leg.split(" (")
|
| 20 |
+
if "Vice-Chair" in role:
|
| 21 |
+
role = "vice-chair"
|
| 22 |
+
elif "Co-Chair" in role:
|
| 23 |
+
role = "co-chair"
|
| 24 |
+
elif "Chair" in role:
|
| 25 |
+
role = "chair"
|
| 26 |
+
else:
|
| 27 |
+
raise Exception("unknown role: %s" % role)
|
| 28 |
+
else:
|
| 29 |
+
role = "member"
|
| 30 |
+
org.add_member(leg, role)
|
| 31 |
+
|
| 32 |
+
return org
|
| 33 |
+
|
| 34 |
+
def scrape(self, chamber=None, session=None):
|
| 35 |
+
if session is None:
|
| 36 |
+
session = self.latest_session()
|
| 37 |
+
self.info("no session specified, using %s", session)
|
| 38 |
+
term = SESSION_TERMS[session]
|
| 39 |
+
|
| 40 |
+
chambers = [chamber] if chamber is not None else ["upper", "lower"]
|
| 41 |
+
|
| 42 |
+
for chamber in chambers + ["legislature"]:
|
| 43 |
+
url = "http://docs.legis.wisconsin.gov/{}/committees/".format(
|
| 44 |
+
term.split("-")[0]
|
| 45 |
+
)
|
| 46 |
+
if chamber == "legislature":
|
| 47 |
+
url += "joint"
|
| 48 |
+
elif chamber == "upper":
|
| 49 |
+
url += "senate"
|
| 50 |
+
else:
|
| 51 |
+
url += "assembly"
|
| 52 |
+
data = self.get(url).text
|
| 53 |
+
doc = lxml.html.fromstring(data)
|
| 54 |
+
doc.make_links_absolute(url)
|
| 55 |
+
|
| 56 |
+
for a in doc.xpath('//ul[@class="docLinks"]/li/p/a'):
|
| 57 |
+
if "(Disbanded" not in a.text:
|
| 58 |
+
comm_name = a.text
|
| 59 |
+
comm_name = comm_name.replace("Committee on", "")
|
| 60 |
+
comm_name = comm_name.replace("Assembly", "")
|
| 61 |
+
comm_name = comm_name.replace("Joint Survey", "")
|
| 62 |
+
comm_name = comm_name.replace("Joint Review", "")
|
| 63 |
+
comm_name = comm_name.replace("Joint", "")
|
| 64 |
+
comm_name = comm_name.replace("Senate", "")
|
| 65 |
+
comm_name = comm_name.replace("Committee for", "")
|
| 66 |
+
comm_name = comm_name.replace("Committee", "")
|
| 67 |
+
comm_name = comm_name.strip()
|
| 68 |
+
yield self.scrape_committee(comm_name, a.get("href"), chamber)
|
pool/shard002/Python/0025434_kernel.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""IPython kernel for parallel computing"""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
from ipython_genutils.py3compat import cast_bytes, cast_unicode_py2
|
| 7 |
+
from traitlets import Integer, Type
|
| 8 |
+
|
| 9 |
+
from ipykernel.ipkernel import IPythonKernel
|
| 10 |
+
from ipykernel.jsonutil import json_clean
|
| 11 |
+
from ipyparallel.serialize import serialize_object, unpack_apply_message
|
| 12 |
+
from .datapub import ZMQDataPublisher
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class IPythonParallelKernel(IPythonKernel):
|
| 16 |
+
"""Extend IPython kernel for parallel computing"""
|
| 17 |
+
engine_id = Integer(-1)
|
| 18 |
+
msg_types = getattr(IPythonKernel, 'msg_types', []) + ['apply_request']
|
| 19 |
+
_execute_sleep = 0
|
| 20 |
+
data_pub_class = Type(ZMQDataPublisher)
|
| 21 |
+
|
| 22 |
+
def _topic(self, topic):
|
| 23 |
+
"""prefixed topic for IOPub messages"""
|
| 24 |
+
base = "engine.%s" % self.engine_id
|
| 25 |
+
|
| 26 |
+
return cast_bytes("%s.%s" % (base, topic))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def __init__(self, **kwargs):
|
| 30 |
+
super(IPythonParallelKernel, self).__init__(**kwargs)
|
| 31 |
+
# add apply_request, in anticipation of upstream deprecation
|
| 32 |
+
self.shell_handlers['apply_request'] = self.apply_request
|
| 33 |
+
# set up data pub
|
| 34 |
+
data_pub = self.shell.data_pub = self.data_pub_class(parent=self)
|
| 35 |
+
self.shell.configurables.append(data_pub)
|
| 36 |
+
data_pub.session = self.session
|
| 37 |
+
data_pub.pub_socket = self.iopub_socket
|
| 38 |
+
|
| 39 |
+
def init_metadata(self, parent):
|
| 40 |
+
"""init metadata dict, for execute/apply_reply"""
|
| 41 |
+
return {
|
| 42 |
+
'started': datetime.now(),
|
| 43 |
+
'dependencies_met' : True,
|
| 44 |
+
'engine' : self.ident,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
def finish_metadata(self, parent, metadata, reply_content):
|
| 48 |
+
"""Finish populating metadata.
|
| 49 |
+
|
| 50 |
+
Run after completing a request handler.
|
| 51 |
+
"""
|
| 52 |
+
# FIXME: remove ipyparallel-specific code
|
| 53 |
+
metadata['status'] = reply_content['status']
|
| 54 |
+
if reply_content['status'] == 'error':
|
| 55 |
+
if reply_content['ename'] == 'UnmetDependency':
|
| 56 |
+
metadata['dependencies_met'] = False
|
| 57 |
+
metadata['engine_info'] = dict(
|
| 58 |
+
engine_uuid=self.ident,
|
| 59 |
+
engine_id=self.engine_id,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
return metadata
|
| 63 |
+
|
| 64 |
+
def execute_request(self, stream, ident, parent):
|
| 65 |
+
"""handle an execute_request - overridden for ipyparallel metadata
|
| 66 |
+
|
| 67 |
+
Once ipykernel has init/finish_metadata, this should be removed.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
content = parent[u'content']
|
| 72 |
+
code = cast_unicode_py2(content[u'code'])
|
| 73 |
+
silent = content[u'silent']
|
| 74 |
+
store_history = content.get(u'store_history', not silent)
|
| 75 |
+
user_expressions = content.get('user_expressions', {})
|
| 76 |
+
allow_stdin = content.get('allow_stdin', False)
|
| 77 |
+
except:
|
| 78 |
+
self.log.error("Got bad msg: ")
|
| 79 |
+
self.log.error("%s", parent)
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
stop_on_error = content.get('stop_on_error', True)
|
| 83 |
+
|
| 84 |
+
md = self.init_metadata(parent)
|
| 85 |
+
|
| 86 |
+
# Re-broadcast our input for the benefit of listening clients, and
|
| 87 |
+
# start computing output
|
| 88 |
+
if not silent:
|
| 89 |
+
self.execution_count += 1
|
| 90 |
+
self._publish_execute_input(code, parent, self.execution_count)
|
| 91 |
+
|
| 92 |
+
reply_content = self.do_execute(code, silent, store_history,
|
| 93 |
+
user_expressions, allow_stdin)
|
| 94 |
+
# finish building metadata
|
| 95 |
+
md = self.finish_metadata(parent, md, reply_content)
|
| 96 |
+
|
| 97 |
+
# Flush output before sending the reply.
|
| 98 |
+
sys.stdout.flush()
|
| 99 |
+
sys.stderr.flush()
|
| 100 |
+
|
| 101 |
+
# Send the reply.
|
| 102 |
+
reply_content = json_clean(reply_content)
|
| 103 |
+
|
| 104 |
+
reply_msg = self.session.send(stream, u'execute_reply',
|
| 105 |
+
reply_content, parent, metadata=md,
|
| 106 |
+
ident=ident)
|
| 107 |
+
|
| 108 |
+
self.log.debug("%s", reply_msg)
|
| 109 |
+
|
| 110 |
+
if not silent and reply_msg['content']['status'] == u'error' and stop_on_error:
|
| 111 |
+
self._abort_queues()
|
| 112 |
+
|
| 113 |
+
def apply_request(self, stream, ident, parent):
|
| 114 |
+
try:
|
| 115 |
+
content = parent[u'content']
|
| 116 |
+
bufs = parent[u'buffers']
|
| 117 |
+
msg_id = parent['header']['msg_id']
|
| 118 |
+
except:
|
| 119 |
+
self.log.error("Got bad msg: %s", parent, exc_info=True)
|
| 120 |
+
return
|
| 121 |
+
|
| 122 |
+
md = self.init_metadata(parent)
|
| 123 |
+
|
| 124 |
+
reply_content, result_buf = self.do_apply(content, bufs, msg_id, md)
|
| 125 |
+
|
| 126 |
+
# put 'ok'/'error' status in header, for scheduler introspection:
|
| 127 |
+
md = self.finish_metadata(parent, md, reply_content)
|
| 128 |
+
|
| 129 |
+
# flush i/o
|
| 130 |
+
sys.stdout.flush()
|
| 131 |
+
sys.stderr.flush()
|
| 132 |
+
|
| 133 |
+
self.session.send(stream, u'apply_reply', reply_content,
|
| 134 |
+
parent=parent, ident=ident, buffers=result_buf, metadata=md)
|
| 135 |
+
|
| 136 |
+
def do_apply(self, content, bufs, msg_id, reply_metadata):
|
| 137 |
+
shell = self.shell
|
| 138 |
+
try:
|
| 139 |
+
working = shell.user_ns
|
| 140 |
+
|
| 141 |
+
prefix = "_"+str(msg_id).replace("-","")+"_"
|
| 142 |
+
|
| 143 |
+
f,args,kwargs = unpack_apply_message(bufs, working, copy=False)
|
| 144 |
+
|
| 145 |
+
fname = getattr(f, '__name__', 'f')
|
| 146 |
+
|
| 147 |
+
fname = prefix+"f"
|
| 148 |
+
argname = prefix+"args"
|
| 149 |
+
kwargname = prefix+"kwargs"
|
| 150 |
+
resultname = prefix+"result"
|
| 151 |
+
|
| 152 |
+
ns = { fname : f, argname : args, kwargname : kwargs , resultname : None }
|
| 153 |
+
# print ns
|
| 154 |
+
working.update(ns)
|
| 155 |
+
code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname)
|
| 156 |
+
try:
|
| 157 |
+
exec(code, shell.user_global_ns, shell.user_ns)
|
| 158 |
+
result = working.get(resultname)
|
| 159 |
+
finally:
|
| 160 |
+
for key in ns:
|
| 161 |
+
working.pop(key)
|
| 162 |
+
|
| 163 |
+
result_buf = serialize_object(result,
|
| 164 |
+
buffer_threshold=self.session.buffer_threshold,
|
| 165 |
+
item_threshold=self.session.item_threshold,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
except:
|
| 169 |
+
# invoke IPython traceback formatting
|
| 170 |
+
shell.showtraceback()
|
| 171 |
+
# FIXME - fish exception info out of shell, possibly left there by
|
| 172 |
+
# run_code. We'll need to clean up this logic later.
|
| 173 |
+
reply_content = {}
|
| 174 |
+
if shell._reply_content is not None:
|
| 175 |
+
reply_content.update(shell._reply_content)
|
| 176 |
+
# reset after use
|
| 177 |
+
shell._reply_content = None
|
| 178 |
+
|
| 179 |
+
self.send_response(self.iopub_socket, u'error', reply_content,
|
| 180 |
+
ident=self._topic('error'))
|
| 181 |
+
self.log.info("Exception in apply request:\n%s", '\n'.join(reply_content['traceback']))
|
| 182 |
+
result_buf = []
|
| 183 |
+
else:
|
| 184 |
+
reply_content = {'status' : 'ok'}
|
| 185 |
+
|
| 186 |
+
return reply_content, result_buf
|
pool/shard002/Python/0025443_get_oss.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#coding=utf8
|
| 2 |
+
# windows环境oss下载程序
|
| 3 |
+
from __future__ import print_function
|
| 4 |
+
import oss2
|
| 5 |
+
import sys,os
|
| 6 |
+
|
| 7 |
+
def percentage(consumed_bytes, total_bytes):
|
| 8 |
+
if total_bytes:
|
| 9 |
+
rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
|
| 10 |
+
print('\r{0}% '.format(rate), end='')
|
| 11 |
+
sys.stdout.flush()
|
| 12 |
+
|
| 13 |
+
def download(filename):
|
| 14 |
+
auth = oss2.Auth('您的AccessKeyId', '您的AccessKeySecret')
|
| 15 |
+
bucket = oss2.Bucket(auth, '您的Endpoint', '您的Bucket名')
|
| 16 |
+
bucket.get_object_to_file(filename,filename, progress_callback=percentage)
|
| 17 |
+
|
| 18 |
+
def start(filename):
|
| 19 |
+
curdir_list = os.listdir('.')
|
| 20 |
+
filename = filename.decode('utf8').encode('gbk')
|
| 21 |
+
print('start downloading [%s]......'%filename)
|
| 22 |
+
if filename in curdir_list:
|
| 23 |
+
raise Exception,'%s already in the current directory,can\'t download.'%filename
|
| 24 |
+
else:
|
| 25 |
+
download(filename.decode('gbk').encode('utf8'))
|
| 26 |
+
print('Download success.')
|
| 27 |
+
|
| 28 |
+
if __name__=='__main__':
|
| 29 |
+
# 获取下载列表
|
| 30 |
+
if len(sys.argv)==1:
|
| 31 |
+
files = raw_input('Please input download filename : ')
|
| 32 |
+
files = files.strip().decode('gbk').encode('utf8').split()
|
| 33 |
+
elif len(sys.argv)>=2:
|
| 34 |
+
files = sys.argv[1:]
|
| 35 |
+
files = map(lambda x:x.decode('gbk').encode('utf8'),files)
|
| 36 |
+
|
| 37 |
+
# 开始下载
|
| 38 |
+
for i,filename in enumerate(files):
|
| 39 |
+
print ("[%d]"%(i+1),end=' ')
|
| 40 |
+
try:
|
| 41 |
+
start(filename)
|
| 42 |
+
except Exception,e:
|
| 43 |
+
print('Download failed.')
|
| 44 |
+
print('[ERROR]:%s'%e)
|
| 45 |
+
# 删除多余创建的文件
|
| 46 |
+
if str(e).find('already')==-1 and os.path.exists(filename):
|
| 47 |
+
os.remove(filename)
|
| 48 |
+
# 下载完成
|
| 49 |
+
os.system('pause')
|
| 50 |
+
|
| 51 |
+
|
pool/shard002/Python/0025448_test1.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/python
|
| 2 |
+
'''Test for an openGL based renderer - testing scene graph features (parenting, dirty propigation, animation)
|
| 3 |
+
|
| 4 |
+
David Dunn
|
| 5 |
+
Feb 2017 - created test suite
|
| 6 |
+
|
| 7 |
+
www.qenops.com
|
| 8 |
+
|
| 9 |
+
'''
|
| 10 |
+
__author__ = ('David Dunn')
|
| 11 |
+
__version__ = '1.0'
|
| 12 |
+
|
| 13 |
+
import OpenGL
|
| 14 |
+
OpenGL.ERROR_CHECKING = False # Uncomment for 2x speed up
|
| 15 |
+
OpenGL.ERROR_LOGGING = False # Uncomment for speed up
|
| 16 |
+
#OpenGL.FULL_LOGGING = True # Uncomment for verbose logging
|
| 17 |
+
#OpenGL.ERROR_ON_COPY = True # Comment for release
|
| 18 |
+
import OpenGL.GL as GL
|
| 19 |
+
import math, os
|
| 20 |
+
import numpy as np
|
| 21 |
+
import dGraph as dg
|
| 22 |
+
import dGraph.ui as dgui
|
| 23 |
+
import dGraph.render as dgr
|
| 24 |
+
import dGraph.cameras as dgc
|
| 25 |
+
import dGraph.shapes as dgs
|
| 26 |
+
import dGraph.materials as dgm
|
| 27 |
+
import dGraph.config as config
|
| 28 |
+
import dGraph.util.imageManip as im
|
| 29 |
+
import time
|
| 30 |
+
|
| 31 |
+
MODELDIR = '%s/data'%os.path.dirname(__file__)
|
| 32 |
+
|
| 33 |
+
def loadScene(renderGraph):
|
| 34 |
+
'''Load or create our sceneGraph'''
|
| 35 |
+
scene = dg.SceneGraph('Test1_SG')
|
| 36 |
+
cam = scene.add(dgc.Camera('cam', scene))
|
| 37 |
+
cam.setResolution((renderGraph.width, renderGraph.height))
|
| 38 |
+
cam.setTranslate(0.,0.,0.)
|
| 39 |
+
cam.setFOV(50.)
|
| 40 |
+
sun = scene.add(dgs.PolySurface.polySphere('sun', scene, radius=.2))
|
| 41 |
+
sun.setTranslate(0.,0.,-2.)
|
| 42 |
+
sun.setRotate(10.,0.,0.)
|
| 43 |
+
sunMaterial = scene.add(dgm.Lambert('sunMaterial',ambient=(1,1,0), amb_coeff=1., diffuse=(0,0,0), diff_coeff=0))
|
| 44 |
+
sun.setMaterial(sunMaterial)
|
| 45 |
+
mercury = scene.add(dgs.PolySurface.polySphere('mercury', sun, radius=.01))
|
| 46 |
+
mercury.setTranslate(0.3,0.,0.)
|
| 47 |
+
mercuryMaterial = scene.add(dgm.Lambert('mercuryMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(1.,.5,.3), diff_coeff=1))
|
| 48 |
+
mercury.setMaterial(mercuryMaterial)
|
| 49 |
+
venus = scene.add(dgs.PolySurface.polySphere('venus', sun, radius=.028))
|
| 50 |
+
venus.setTranslate(0.425,0.,0.)
|
| 51 |
+
venusMaterial = scene.add(dgm.Lambert('venusMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(1.,.6,.6), diff_coeff=1))
|
| 52 |
+
venus.setMaterial(venusMaterial)
|
| 53 |
+
earth = scene.add(dgs.PolySurface.polySphere('earth', sun, radius=.03))
|
| 54 |
+
earth.setTranslate(0.6,0.,0.)
|
| 55 |
+
earth.setRotate(0.,0.,15.)
|
| 56 |
+
earthMaterial = scene.add(dgm.Lambert('earthMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.25,.41,.879), diff_coeff=1))
|
| 57 |
+
earth.setMaterial(earthMaterial)
|
| 58 |
+
moon = scene.add(dgs.PolySurface.polySphere('moon', earth, radius=.005))
|
| 59 |
+
moon.setTranslate(0.075,0.,0.)
|
| 60 |
+
moonMaterial = scene.add(dgm.Lambert('moonMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.7,.7,.7), diff_coeff=1))
|
| 61 |
+
moon.setMaterial(moonMaterial)
|
| 62 |
+
mars = scene.add(dgs.PolySurface.polySphere('mars', sun, radius=.015))
|
| 63 |
+
mars.setTranslate(0.8,0.,0.)
|
| 64 |
+
marsMaterial = scene.add(dgm.Lambert('marsMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.8,.2,.2), diff_coeff=1))
|
| 65 |
+
mars.setMaterial(marsMaterial)
|
| 66 |
+
jupiter = scene.add(dgs.PolySurface.polySphere('jupiter', sun, radius=.1))
|
| 67 |
+
jupiter.setTranslate(1.2,0.,0.)
|
| 68 |
+
jupiterMaterial = scene.add(dgm.Lambert('jupiterMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.867,.71875,.527), diff_coeff=1))
|
| 69 |
+
jupiter.setMaterial(jupiterMaterial)
|
| 70 |
+
renderGraph.frameBuffer.connectInput(cam)
|
| 71 |
+
scene.add(renderGraph)
|
| 72 |
+
return scene # Initialization Successful
|
| 73 |
+
|
| 74 |
+
def animateScene(scene, frame):
|
| 75 |
+
''' Create motion in our scene '''
|
| 76 |
+
# name: (distance, orbit, rotation )
|
| 77 |
+
speeds = {'mercury':(0.3, 87.969, 58.646 ),
|
| 78 |
+
'venus': (0.425, 224.7, 243 ),
|
| 79 |
+
'earth': (0.6, 365.2564, 1 ),
|
| 80 |
+
'moon': (0.075, 28, 28 ),
|
| 81 |
+
'mars': (0.8, 687, 1.03 ),
|
| 82 |
+
'jupiter':(1.2, 4332.59, 0.4135 )}
|
| 83 |
+
for k in scene.shapes:
|
| 84 |
+
if k in speeds:
|
| 85 |
+
dist, orbit, rot = speeds[k]
|
| 86 |
+
# add rot when we have textures - but will mess up children
|
| 87 |
+
x = math.cos(math.pi/2/orbit*frame) * dist
|
| 88 |
+
z = math.sin(math.pi/2/orbit*frame) * dist
|
| 89 |
+
scene[k].translate = np.array((x,0.,z))
|
| 90 |
+
|
| 91 |
+
def addInput(scene):
|
| 92 |
+
dgui.add_key_callback(arrowKey, dgui.KEY_RIGHT, scene=scene, direction=3)
|
| 93 |
+
dgui.add_key_callback(arrowKey, dgui.KEY_LEFT, scene=scene, direction=2)
|
| 94 |
+
dgui.add_key_callback(arrowKey, dgui.KEY_UP, scene=scene, direction=1)
|
| 95 |
+
dgui.add_key_callback(arrowKey, dgui.KEY_DOWN, scene=scene, direction=0)
|
| 96 |
+
|
| 97 |
+
''' In order to do input with mouse and keyboard, we need to setup a state machine with
|
| 98 |
+
states switches from mouse presses and releases and certain key presses
|
| 99 |
+
- maybe enable a glfwSetCursorPosCallback when button is pressed, or
|
| 100 |
+
- more likely just poll cursor position since you can't disable a callback'''
|
| 101 |
+
def arrowKey(window,scene,direction):
|
| 102 |
+
if direction == 3: # print "right"
|
| 103 |
+
pass
|
| 104 |
+
elif direction == 2: # print "left"
|
| 105 |
+
pass
|
| 106 |
+
elif direction == 1: # print 'up'
|
| 107 |
+
scene['sun'].rotate += np.array((5.,0.,0.))
|
| 108 |
+
print(scene['sun'].rotate)
|
| 109 |
+
else: # print "down"
|
| 110 |
+
scene['sun'].rotate -= np.array((5.,0.,0.))
|
| 111 |
+
print(scene['sun'].rotate)
|
| 112 |
+
|
| 113 |
+
def setup():
|
| 114 |
+
renderGraph = dgr.RenderGraph('Test1_RG')
|
| 115 |
+
display = renderGraph.add(dgui.Display('Fake Display',resolution=(1920,1200)))
|
| 116 |
+
dgui.init()
|
| 117 |
+
offset = (0,0)
|
| 118 |
+
mainWindow = renderGraph.add(dgui.open_window('Scene Graph Test', offset[0], offset[1], display.width, display.height))
|
| 119 |
+
if not mainWindow:
|
| 120 |
+
dgui.terminate()
|
| 121 |
+
exit(1)
|
| 122 |
+
x, y = dgui.get_window_pos(mainWindow)
|
| 123 |
+
width, height = dgui.get_window_size(mainWindow)
|
| 124 |
+
dgui.add_key_callback(dgui.close_window, dgui.KEY_ESCAPE)
|
| 125 |
+
dg.initGL()
|
| 126 |
+
scene = loadScene(renderGraph)
|
| 127 |
+
renderGraph.graphicsCardInit()
|
| 128 |
+
return scene, [mainWindow]
|
| 129 |
+
|
| 130 |
+
def runLoop(scene, mainWindow):
|
| 131 |
+
# Print message to console, and kick off the loop to get it rolling.
|
| 132 |
+
print("Hit ESC key to quit.")
|
| 133 |
+
frame = 0
|
| 134 |
+
totalSleep = 0
|
| 135 |
+
start = time.time()
|
| 136 |
+
while not dgui.window_should_close(mainWindow):
|
| 137 |
+
dgui.make_context_current(mainWindow)
|
| 138 |
+
scene.render()
|
| 139 |
+
now = time.time()
|
| 140 |
+
toSleep = max(0,(frame+1)/config.maxFPS+start-now)
|
| 141 |
+
time.sleep(toSleep)
|
| 142 |
+
dgui.swap_buffers(mainWindow)
|
| 143 |
+
dgui.poll_events()
|
| 144 |
+
animateScene(scene, frame)
|
| 145 |
+
totalSleep += toSleep
|
| 146 |
+
frame += 1
|
| 147 |
+
end = time.time()
|
| 148 |
+
dgui.terminate()
|
| 149 |
+
elapsed = end-start
|
| 150 |
+
computePct = (1-totalSleep/elapsed)*100
|
| 151 |
+
renderTime = elapsed-totalSleep
|
| 152 |
+
frameTime = renderTime/frame*1000
|
| 153 |
+
print('Average frame took %.4f ms to render.\nRendered %.4f seconds of a total %.4f seconds.\nRendering %.2f%% of the time.'%(frameTime,renderTime,elapsed,computePct))
|
| 154 |
+
exit(0)
|
| 155 |
+
|
| 156 |
+
if __name__ == '__main__':
|
| 157 |
+
scene, windows = setup()
|
| 158 |
+
addInput(scene)
|
| 159 |
+
runLoop(scene, windows[0])
|