"
+ _id = params[0]
+ self.app.ob_client.delete_nsd(_id)
+ return "INFO: Deleted nsd with id %s" % _id
+
+ def list(self, params=None):
+ return result_to_str(
+ get_result_to_list(self.app.ob_client.list_nsds(), keys=self.keys_to_list, _format=self.app.format),
+ _format=self.app.format)
diff --git a/pool/shard003/Python/0028594_main.py b/pool/shard003/Python/0028594_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee12a53b6f7f6d26876ad16b386fc057dde6df49
--- /dev/null
+++ b/pool/shard003/Python/0028594_main.py
@@ -0,0 +1,84 @@
+__author__ = 'Daniel'
+
+import platform
+from PySide.QtCore import *
+from PySide.QtGui import *
+import GUI.ui_mainwindow
+from GUI.component import *
+from Game import Game
+from GUI.models import MyHistoryTableModel
+from UserData import config
+from utility import is_debug_mode, __version__
+
+
+class MainWindow(QMainWindow, GUI.ui_mainwindow.Ui_MainWindow):
+ def keyPressEvent(self, event):
+ if is_debug_mode():
+ print('key: %s -' % hex(event.key()))
+ print('modifiers:', hex(int(event.modifiers())))
+
+ def checkAns(self, user_input):
+ if is_debug_mode():
+ print(self.game.current_question.answer)
+ try:
+ return float(user_input) == self.game.current_question.answer
+ except:
+ return False
+
+ def start_quick_game(self):
+ g = GameDialog(self)
+ g.start()
+
+ def start_training(self):
+ # TODO: Create a new dialog asking for type
+ self.start_quick_game()
+
+ def display_settings(self):
+ # TODO: Create interface to change settings
+ QMessageBox.information(self, "Settings", "Coming soon")
+
+ def display_history(self):
+ """Create dumb dialog and display table"""
+ data = []
+ for q in self.game.history.values():
+ data.append([q.query.strip(), len(q.correct_times), len(q.wrong_times)])
+ header = ['Query', 'Correct', 'Wrong']
+ model = MyHistoryTableModel(data, header, self)
+
+ h = HistoryDlg(self)
+ h.set_up_history(model)
+ h.show()
+
+ def display_about(self):
+ QMessageBox.about(self, "About Mental Math",
+ """Mental Math v %s
+
+ Made by Daniel Low
+ This application can be used to train your mental calculation.
+
Running on Python %s on %s""" % (
+ __version__, platform.python_version(), platform.system()))
+
+ def __init__(self, game):
+ self.game = game
+ super(MainWindow, self).__init__()
+ self.setupUi(self)
+ self.setWindowTitle("Mental Math trainer")
+ # self.statusBar.showMessage('Ready')
+ self.setCentralWidget(StartWidget(self))
+ self.actionQuit.triggered.connect(self.close)
+ self.actionQuick_Game.triggered.connect(self.start_quick_game)
+ self.actionTraining.triggered.connect(self.start_training)
+ self.actionHistory.triggered.connect(self.display_history)
+ self.actionAbout.triggered.connect(self.display_about)
+
+
+def main():
+ app = QApplication(sys.argv)
+ g = Game()
+ f = MainWindow(g)
+ f.show()
+ sys.exit(app.exec_())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard003/Python/0028597_multi_rnn.py b/pool/shard003/Python/0028597_multi_rnn.py
new file mode 100644
index 0000000000000000000000000000000000000000..75f438ad594358ee39c4af17e189b292132cf65d
--- /dev/null
+++ b/pool/shard003/Python/0028597_multi_rnn.py
@@ -0,0 +1,101 @@
+# Copyright 2019 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""this class is changed so that outputs of all LSTM layers are recorded not just the last one."""
+
+import tensorflow.compat.v1 as tf
+# TODO: verify if we need this class at all
+from tensorflow.python.util import nest
+
+
+class MultiRNNCell(tf.nn.rnn_cell.RNNCell):
+ """RNN cell composed sequentially of multiple simple cells."""
+
+ def __init__(self, cells, state_is_tuple=True):
+ """Create a RNN cell composed sequentially of a number of RNNCells.
+
+ Args:
+ cells: list of RNNCells that will be composed in this order.
+ state_is_tuple: If True, accepted and returned states are n-tuples, where
+ `n = len(cells)`. If False, the states are all
+ concatenated along the column axis. This latter behavior will soon be
+ deprecated.
+
+ Raises:
+ ValueError: if cells is empty (not allowed), or at least one of the cells
+ returns a state tuple but the flag `state_is_tuple` is `False`.
+ """
+ super(MultiRNNCell, self).__init__()
+ if not cells:
+ raise ValueError("Must specify at least one cell for MultiRNNCell.")
+ if not nest.is_sequence(cells):
+ raise TypeError("cells must be a list or tuple, but saw: %s." % cells)
+
+ self._cells = cells
+ self._state_is_tuple = state_is_tuple
+ if not state_is_tuple:
+ if any(nest.is_sequence(c.state_size) for c in self._cells):
+ raise ValueError("Some cells return tuples of states, but the flag "
+ "state_is_tuple is not set. State sizes are: %s" %
+ str([c.state_size for c in self._cells]))
+
+ @property
+ def state_size(self):
+ if self._state_is_tuple:
+ return tuple(cell.state_size for cell in self._cells)
+ else:
+ return sum([cell.state_size for cell in self._cells])
+
+ @property
+ def output_size(self):
+ return self._cells[-1].output_size * len(self._cells)
+
+ def zero_state(self, batch_size, dtype):
+ with tf.name_scope(type(self).__name__ + "ZeroState", values=[batch_size]):
+ if self._state_is_tuple:
+ return tuple(cell.zero_state(batch_size, dtype) for cell in self._cells)
+ else:
+ # We know here that state_size of each cell is not a tuple and
+ # presumably does not contain TensorArrays or anything else fancy
+ return super(MultiRNNCell, self).zero_state(batch_size, dtype)
+
+ def call(self, inputs, state):
+ """Run this multi-layer cell on inputs, starting from state."""
+ cur_state_pos = 0
+ cur_inp = inputs
+ all_output = []
+ new_states = []
+ for i, cell in enumerate(self._cells):
+ with tf.variable_scope("cell_%d" % i):
+ if self._state_is_tuple:
+ if not nest.is_sequence(state):
+ raise ValueError(
+ "Expected state to be a tuple of length %d, but received: %s" %
+ (len(self.state_size), state))
+ cur_state = state[i]
+ else:
+ cur_state = tf.slice(state, [0, cur_state_pos],
+ [-1, cell.state_size])
+ cur_state_pos += cell.state_size
+ cur_inp, new_state = cell(cur_inp, cur_state)
+ all_output.append(cur_inp)
+ new_states.append(new_state)
+
+ new_states = (
+ tuple(new_states)
+ if self._state_is_tuple else tf.concat(new_states, 1))
+ concat = tf.concat(all_output,
+ 1) # batch_size* (unit_size*num_layers)
+ # return cur_inp, new_states
+ return concat, new_states
diff --git a/pool/shard003/Python/0028603_wemo.py b/pool/shard003/Python/0028603_wemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..29c3487bf5313c241faf683748128b5e4ad370e0
--- /dev/null
+++ b/pool/shard003/Python/0028603_wemo.py
@@ -0,0 +1,96 @@
+"""
+Support for WeMo device discovery.
+
+For more details about this component, please refer to the documentation at
+https://home-assistant.io/components/wemo/
+"""
+import logging
+
+from homeassistant.components import discovery
+from homeassistant.const import EVENT_HOMEASSISTANT_STOP
+
+REQUIREMENTS = ['pywemo==0.3.12']
+
+DOMAIN = 'wemo'
+DISCOVER_LIGHTS = 'wemo.light'
+DISCOVER_BINARY_SENSORS = 'wemo.binary_sensor'
+DISCOVER_SWITCHES = 'wemo.switch'
+
+# Mapping from Wemo model_name to service.
+WEMO_MODEL_DISPATCH = {
+ 'Bridge': DISCOVER_LIGHTS,
+ 'Insight': DISCOVER_SWITCHES,
+ 'Maker': DISCOVER_SWITCHES,
+ 'Sensor': DISCOVER_BINARY_SENSORS,
+ 'Socket': DISCOVER_SWITCHES,
+ 'LightSwitch': DISCOVER_SWITCHES
+}
+WEMO_SERVICE_DISPATCH = {
+ DISCOVER_LIGHTS: 'light',
+ DISCOVER_BINARY_SENSORS: 'binary_sensor',
+ DISCOVER_SWITCHES: 'switch',
+}
+
+SUBSCRIPTION_REGISTRY = None
+KNOWN_DEVICES = []
+
+_LOGGER = logging.getLogger(__name__)
+
+
+# pylint: disable=unused-argument, too-many-function-args
+def setup(hass, config):
+ """Common setup for WeMo devices."""
+ import pywemo
+
+ global SUBSCRIPTION_REGISTRY
+ SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
+ SUBSCRIPTION_REGISTRY.start()
+
+ def stop_wemo(event):
+ """Shutdown Wemo subscriptions and subscription thread on exit."""
+ _LOGGER.info("Shutting down subscriptions.")
+ SUBSCRIPTION_REGISTRY.stop()
+
+ hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)
+
+ def discovery_dispatch(service, discovery_info):
+ """Dispatcher for WeMo discovery events."""
+ # name, model, location, mac
+ _, model_name, _, _, serial = discovery_info
+
+ # Only register a device once
+ if serial in KNOWN_DEVICES:
+ return
+ _LOGGER.debug('Discovered unique device %s', serial)
+ KNOWN_DEVICES.append(serial)
+
+ service = WEMO_MODEL_DISPATCH.get(model_name) or DISCOVER_SWITCHES
+ component = WEMO_SERVICE_DISPATCH.get(service)
+
+ discovery.discover(hass, service, discovery_info,
+ component, config)
+
+ discovery.listen(hass, discovery.SERVICE_WEMO, discovery_dispatch)
+
+ _LOGGER.info("Scanning for WeMo devices.")
+ devices = [(device.host, device) for device in pywemo.discover_devices()]
+
+ # Add static devices from the config file.
+ devices.extend((address, None)
+ for address in config.get(DOMAIN, {}).get('static', []))
+
+ for address, device in devices:
+ port = pywemo.ouimeaux_device.probe_wemo(address)
+ if not port:
+ _LOGGER.warning('Unable to probe wemo at %s', address)
+ continue
+ _LOGGER.info('Adding wemo at %s:%i', address, port)
+
+ url = 'http://%s:%i/setup.xml' % (address, port)
+ if device is None:
+ device = pywemo.discovery.device_from_description(url, None)
+
+ discovery_info = (device.name, device.model_name, url, device.mac,
+ device.serialnumber)
+ discovery.discover(hass, discovery.SERVICE_WEMO, discovery_info)
+ return True
diff --git a/pool/shard003/Python/0028604_dictionary.py b/pool/shard003/Python/0028604_dictionary.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d9fdfad1774e647e87de5f29b90f61376cbb4b4
--- /dev/null
+++ b/pool/shard003/Python/0028604_dictionary.py
@@ -0,0 +1,74 @@
+'''
+A few common functions for checking possible solutions
+
+Functionality:
+- Recursively check against a scrabble dictionary and list of one letter words and return a Boolean and the decrypted cipher
+
+Sample Usage:
+
+>>> from cipher import dictionary
+>>> dictionary.filterIgnoreSpace(lambda x, a, b: a*(x - b), , )
+
+
+Depends: cipher.core.shiftLinear, twl
+'''
+try:
+ from src.TWL06 import twl
+ from src.core import shiftLinear
+except ImportError:
+ from TWL06 import twl
+ from core import shiftLinear
+__debug = True
+
+def filterIgnoreSpace(function,cipher,sortedShiftList,utf8=False):
+ '''
+ Runs recursiveCheck against a list of possible inputs with a function and returns a properly spaced string
+ and the correct inputs
+
+ >>> filterIgnoreSpace(lambda x, a, b: a*(x - b), "NGG NPX NGQ NJA", [(5,1),(2,4),(1,13)],utf8=True)
+ ('attack at dawn', (1, 13))
+ >>> filterIgnoreSpace(lambda x, a, b: a*(x - b), bytearray("NGG NPX NGQ NJA","ascii"), [(5,1),(2,4),(1,13)])
+ ('attack at dawn', (1, 13))
+ '''
+ for param in sortedShiftList:
+ input1 = shiftLinear(function,cipher,param[0],param[1],utf8=utf8)
+ if utf8: solution,output = recursiveCheck(input1.replace(" ",""))
+ else: solution,output = recursiveCheck(str(input1,"utf-8").replace(" ",""))
+ if solution:
+ return (output,param)
+def recursiveCheck(cipher,index=0,length=1,partialSolution=''):
+ '''
+ Checks an input recursively against a scrabble dictionary (or 'a','i','o').
+ The input must have no spaces - so string.replace(" ","") should be used on the input.
+ In most cases it is better to use filterIgnoreSpace than recursiveCheck
+
+ >>> solution = "att ack atd awn"
+ >>> recursiveCheck(solution.replace(" ",""))
+ (True, 'attack at dawn')
+ '''
+ ONE_LETTER_WORDS = ['a','i','o']
+ word = cipher[index:index+length]
+ longerWord = cipher[index:index+length+1]
+ nextWord = cipher[index+length:index+length+1]
+ if twl.check(word) or word in ONE_LETTER_WORDS:
+ if index+length > len(cipher) - 1:
+ return True,(partialSolution+word)
+ elif twl.check(longerWord) or len(twl.children(longerWord)) > 0:
+ # TODO: find more elegant way of recursing
+ longer,partL = recursiveCheck(cipher,index,length+1,partialSolution)
+ next,partN = recursiveCheck(cipher,index+length,1,partialSolution+word+" ")
+ if longer: return longer,partL
+ else: return next,partN
+ else:
+ return recursiveCheck(cipher,index+length,1,partialSolution+word+" ")
+ elif twl.check(longerWord) or len(twl.children(longerWord)) > 0:
+ if index+length > len(cipher) - 1:
+ #print(partialSolution)
+ return True,(partialSolution+word)
+ return recursiveCheck(cipher,index,length+1,partialSolution)
+ else:
+ #print(partialSolution)
+ return False,""
+
+def partialCheck(): raise NotImplementedError
+
diff --git a/pool/shard003/Python/0028605_0002_auto_20171207_2305.py b/pool/shard003/Python/0028605_0002_auto_20171207_2305.py
new file mode 100644
index 0000000000000000000000000000000000000000..100084e5dbb3ec7760b2971c8e6ce03b248833c1
--- /dev/null
+++ b/pool/shard003/Python/0028605_0002_auto_20171207_2305.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.7 on 2017-12-07 23:05
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('emailservice', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name='birthdayemailgreetingconfiguration',
+ old_name='send_greeting',
+ new_name='send_emails',
+ ),
+ migrations.RenameField(
+ model_name='birthdayslistconfiguration',
+ old_name='send_list',
+ new_name='send_emails',
+ ),
+ migrations.AddField(
+ model_name='grouprotationconfiguration',
+ name='send_emails',
+ field=models.BooleanField(default=False),
+ ),
+ ]
diff --git a/pool/shard003/Python/0028611_mq9_sensor.py b/pool/shard003/Python/0028611_mq9_sensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..38af64b3da7fd340cb08bf34cbaa0fdc97d5ab60
--- /dev/null
+++ b/pool/shard003/Python/0028611_mq9_sensor.py
@@ -0,0 +1,41 @@
+
+# Copyright (c) 2015 "aldarionsevero Lucas Severo Alves
+# ""
+
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+from sensor import Sensor
+
+import botbook_mcp3002 as mcp
+
+
+class Mq9Sensor(Sensor):
+
+ """docstring for Mq9Sensor"""
+
+ def __init__(self):
+ Sensor.__init__(self)
+ self.sense_pin1 = 0 # pin 7 rasp
+ self.gain = float(1 / 1000)
+ self.gain_plus = 0
+ self.gaslevel = 0
+
+ def read_sensor(self):
+ self.gaslevel = mcp.readAnalog()
+ return self.gaslevel
diff --git a/pool/shard003/Python/0028612_s3_acl.py b/pool/shard003/Python/0028612_s3_acl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bb3764e08921b46b84955c1dd93840c8bb69288
--- /dev/null
+++ b/pool/shard003/Python/0028612_s3_acl.py
@@ -0,0 +1,67 @@
+# Copyright (c) 2014 OpenStack Foundation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from six.moves.urllib.parse import quote
+from swift.common.utils import public
+
+from swift.common.middleware.s3api.controllers.base import Controller
+from swift.common.middleware.s3api.s3response import HTTPOk
+from swift.common.middleware.s3api.etree import tostring
+
+
+class S3AclController(Controller):
+ """
+ Handles the following APIs:
+
+ * GET Bucket acl
+ * PUT Bucket acl
+ * GET Object acl
+ * PUT Object acl
+
+ Those APIs are logged as ACL operations in the S3 server log.
+ """
+ @public
+ def GET(self, req):
+ """
+ Handles GET Bucket acl and GET Object acl.
+ """
+ resp = req.get_response(self.app, method='HEAD')
+
+ acl = resp.object_acl if req.is_object_request else resp.bucket_acl
+
+ resp = HTTPOk()
+ resp.body = tostring(acl.elem())
+
+ return resp
+
+ @public
+ def PUT(self, req):
+ """
+ Handles PUT Bucket acl and PUT Object acl.
+ """
+ if req.is_object_request:
+ headers = {}
+ src_path = '/%s/%s' % (req.container_name, req.object_name)
+
+ # object-sysmeta' can be updated by 'Copy' method,
+ # but can not be by 'POST' method.
+ # So headers['X-Copy-From'] for copy request is added here.
+ headers['X-Copy-From'] = quote(src_path)
+ headers['Content-Length'] = 0
+ req.get_response(self.app, 'PUT', headers=headers)
+ else:
+ req.get_response(self.app, 'POST')
+
+ return HTTPOk()
diff --git a/pool/shard003/Python/0028616_check.py b/pool/shard003/Python/0028616_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..708440b08f1a438195ff771d7ab74b5c840115b9
--- /dev/null
+++ b/pool/shard003/Python/0028616_check.py
@@ -0,0 +1,91 @@
+#!/usr/bin/python
+# converts answer set (only 1 answer must be given, preceded by answer) to flatzinc constraints
+
+import sys
+import subprocess
+import tempfile
+import os
+import signal
+
+
+timelimit =3600
+memlimit =6000
+
+def handler(signum, frame):
+ try:
+ finstance.close()
+ fsolverout.close()
+ fcheck.close()
+ finally:
+ a = 0
+ os.remove(instance)
+ os.remove(watcher)
+ os.remove(solverout)
+ os.remove(check)
+ sys.stdout.flush()
+
+
+
+def flatzincUNSAT(testit):
+ res = subprocess.Popen(["./runsolver", "-w "+watcher, "-M"+str(memlimit), "-W"+str(timelimit), "./flatzinc", testit],stdout=subprocess.PIPE)
+ res = res.communicate()[0]
+ for s in res:
+ if (s.find("UNSATISFIABLE")!=-1):
+ return True
+ return False
+
+
+if len(sys.argv)<2:
+ print 'One file and several parameters for clingcon expected'
+ sys.exit(1)
+
+flatzinc = sys.argv[1]
+print("Currently processing file: " + flatzinc)
+(fd, instance) = tempfile.mkstemp()
+finstance = open(instance, "w")
+subprocess.call(["./fz", sys.argv[1]], stdout=finstance)
+finstance.close()
+(fd, watcher) = tempfile.mkstemp()
+(fd, solverout) = tempfile.mkstemp()
+#print(watcher)
+#print(solverout)
+#cant use -o of runsolver, interferes with python subprocess pipe
+#commandline = ["./runsolver", "-w "+watcher, "-o "+solverout, "-M"+str(memlimit), "-W"+str(timelimit), "./clingcon", instance]
+commandline = ["./runsolver", "-w "+watcher, "-M"+str(memlimit), "-W"+str(timelimit), "./clingcon", "--quiet=1,0,2", instance]
+#print(" ".join(commandline))
+ret = subprocess.Popen(commandline,stdout=subprocess.PIPE)
+ret = ret.communicate()[0]
+fsolverout = open(solverout,"w")
+if ret.find("Models : 0+")!=-1:
+ print("Cant solve anything, sorry")
+ fsolverout.close()
+ os.remove(instance)
+ os.remove(watcher)
+ os.remove(solverout)
+ sys.exit()
+else:
+ fsolverout.write(ret)
+fsolverout.close()
+(fd, check) = tempfile.mkstemp(suffix='.fzn')
+fcheck = open(check,"w")
+subprocess.call(["head","-n","-1", flatzinc],stdout=fcheck)
+fsolverout = open(solverout,"r")
+ret = subprocess.call(["./converter.py"],stdin=fsolverout,stdout=fcheck)
+if ret==0:
+ fsolverout.close()
+ subprocess.call(["tail","-n 1", flatzinc],stdout=fcheck)
+ fcheck.close()
+ x = flatzincUNSAT(check)
+ if x:
+ print("Problem " + flatzinc + " was SAT, but solution was incorrect")
+ else:
+ print("Correct")
+else:
+ x = flatzincUNSAT(flatzinc)
+ if x:
+ print("Correct")
+ else:
+ print("Problem " + flatzinc + " was UNSAT, but it should have been SAT")
+
+handler(0,0)
+
diff --git a/pool/shard003/Python/0028623_test_util.py b/pool/shard003/Python/0028623_test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7ea8eb645a7f327491e32ea2cb2bf1cc419cf03
--- /dev/null
+++ b/pool/shard003/Python/0028623_test_util.py
@@ -0,0 +1,116 @@
+# coding=utf-8
+# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
+# Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
+ unicode_literals, with_statement)
+
+import os
+import unittest
+from contextlib import contextmanager
+
+from mock import Mock, patch
+
+from pants.java.executor import Executor
+from pants.java.jar.manifest import Manifest
+from pants.java.util import execute_java, safe_classpath
+from pants.util.contextutil import open_zip
+from pants.util.dirutil import safe_mkdir, safe_mkdtemp, touch
+
+
+class ExecuteJavaTest(unittest.TestCase):
+ EXECUTOR_ERROR = Executor.Error()
+ TEST_MAIN = 'foo.bar.main'
+ TEST_CLASSPATH = ['A.jar', 'B.jar']
+ SAFE_CLASSPATH = ['C.jar']
+ SYNTHETIC_JAR_DIR = 'somewhere'
+
+ def setUp(self):
+ self.executor = Mock(spec=Executor)
+ self.runner = Mock(spec=Executor.Runner)
+ self.executor.runner = Mock(return_value=self.runner)
+ self.runner.run = Mock(return_value=0)
+
+ @contextmanager
+ def mock_safe_classpath_helper(self, create_synthetic_jar=True):
+ with patch('pants.java.util.safe_classpath') as mock_safe_classpath:
+ mock_safe_classpath.side_effect = fake_safe_classpath
+ yield mock_safe_classpath
+
+ self.runner.run.assert_called_once_with()
+ if create_synthetic_jar:
+ self.executor.runner.assert_called_once_with(self.SAFE_CLASSPATH, self.TEST_MAIN,
+ args=None, jvm_options=None, cwd=None)
+ mock_safe_classpath.assert_called_once_with(self.TEST_CLASSPATH, self.SYNTHETIC_JAR_DIR)
+ else:
+ self.executor.runner.assert_called_once_with(self.TEST_CLASSPATH, self.TEST_MAIN,
+ args=None, jvm_options=None, cwd=None)
+ mock_safe_classpath.assert_not_called()
+
+ def test_execute_java_no_error(self):
+ with self.mock_safe_classpath_helper():
+ self.assertEquals(0, execute_java(self.TEST_CLASSPATH, self.TEST_MAIN,
+ executor=self.executor,
+ synthetic_jar_dir=self.SYNTHETIC_JAR_DIR))
+
+ def test_execute_java_executor_error(self):
+ with self.mock_safe_classpath_helper():
+ self.runner.run.side_effect = self.EXECUTOR_ERROR
+
+ with self.assertRaises(type(self.EXECUTOR_ERROR)):
+ execute_java(self.TEST_CLASSPATH, self.TEST_MAIN, executor=self.executor,
+ synthetic_jar_dir=self.SYNTHETIC_JAR_DIR)
+
+ def test_execute_java_no_synthentic_jar(self):
+ with self.mock_safe_classpath_helper(create_synthetic_jar=False):
+ self.assertEquals(0, execute_java(self.TEST_CLASSPATH, self.TEST_MAIN,
+ executor=self.executor,
+ create_synthetic_jar=False))
+
+
+def fake_safe_classpath(classpath, synthetic_jar_dir):
+ return ExecuteJavaTest.SAFE_CLASSPATH
+
+
+class SafeClasspathTest(unittest.TestCase):
+ def test_safe_classpath(self):
+ """For directory structure like:
+
+ ./
+ ./libs/A.jar
+ ./libs/resources/
+ ./synthetic_jar_dir
+
+ Verify a synthetic jar with the following classpath in manifest is created:
+
+ Class-Path: ../libs/A.jar:../libs/resources/
+ """
+ RESOURCES = 'resources'
+ LIB_DIR = 'libs'
+ JAR_FILE = 'A.jar'
+ SYNTHENTIC_JAR_DIR = 'synthetic_jar_dir'
+
+ basedir = safe_mkdtemp()
+ lib_dir = os.path.join(basedir, LIB_DIR)
+ synthetic_jar_dir = os.path.join(basedir, SYNTHENTIC_JAR_DIR)
+ resource_dir = os.path.join(lib_dir, RESOURCES)
+ jar_file = os.path.join(lib_dir, JAR_FILE)
+
+ for dir in (lib_dir, resource_dir, synthetic_jar_dir):
+ safe_mkdir(dir)
+ touch(jar_file)
+
+ classpath = [jar_file, resource_dir]
+
+ safe_cp = safe_classpath(classpath, synthetic_jar_dir)
+ self.assertEquals(1, len(safe_cp))
+ safe_jar = safe_cp[0]
+ self.assertTrue(os.path.exists(safe_jar))
+ self.assertEquals(synthetic_jar_dir, os.path.dirname(safe_jar))
+
+ with open_zip(safe_jar) as synthetic_jar:
+ self.assertListEqual([Manifest.PATH], synthetic_jar.namelist())
+ # manifest should contain the relative path of both jar and resource directory
+ self.assertEquals('{}: ../{}/{} ../{}/{}/\n'.format(Manifest.CLASS_PATH, LIB_DIR, JAR_FILE,
+ LIB_DIR, RESOURCES),
+ synthetic_jar.read(Manifest.PATH).replace('\n ', ''))
diff --git a/pool/shard003/Python/0028625_main.py b/pool/shard003/Python/0028625_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..a361a203cf159d6ab327fe81b83bcee27fcccf76
--- /dev/null
+++ b/pool/shard003/Python/0028625_main.py
@@ -0,0 +1,194 @@
+import argparse
+import logging
+import multiprocessing
+import os
+import os.path
+import pwd
+import shutil
+import signal
+import sys
+
+import fooster.web
+
+
+import mcp.config
+
+
+parser = argparse.ArgumentParser(description='start a multi-server management framework for Armagetron Advanced')
+parser.add_argument('-a', '--address', dest='address', help='address to bind')
+parser.add_argument('-p', '--port', type=int, dest='port', help='port to bind')
+parser.add_argument('-t', '--template', dest='template', help='template directory to use')
+parser.add_argument('-l', '--log', dest='log', help='log directory to use')
+parser.add_argument('--db', '--database', dest='database', help='database directory to use')
+parser.add_argument('--prefix', dest='prefix', help='prefix directory to use')
+parser.add_argument('--sources', dest='sources', help='sources directory to use')
+parser.add_argument('--config', dest='config', help='config directory to use')
+parser.add_argument('--scripting', dest='scripting', help='scripting directory to use')
+parser.add_argument('--tmp', dest='tmp', help='tmp directory to use')
+parser.add_argument('--sftpkey', dest='sftpkey', help='sftp key to use')
+parser.add_argument('--user', dest='user', help='user to drop to if run as root')
+parser.add_argument('--container', action='store_true', dest='container', help='whether to put servers and scripts in a container')
+
+args = parser.parse_args()
+
+if args.address:
+ mcp.config.addr = (args.address, mcp.config.addr[1])
+
+if args.port:
+ mcp.config.addr = (mcp.config.addr[0], args.port)
+
+if args.template:
+ config.template = args.template
+
+if args.log:
+ if args.log == 'none':
+ mcp.config.log = None
+ mcp.config.cmdlog = None
+ mcp.config.httpdlog = None
+ mcp.config.accesslog = None
+ else:
+ mcp.config.log = os.path.join(args.log, 'manager.log')
+ mcp.config.cmdlog = os.path.join(args.log, 'command.log')
+ mcp.config.httplog = os.path.join(args.log, 'httpd.log')
+ mcp.config.accesslog = os.path.join(args.log, 'access.log')
+
+if args.database:
+ mcp.config.database = os.path.abspath(args.database)
+
+if args.prefix:
+ mcp.config.prefix = os.path.abspath(args.prefix)
+
+if args.sources:
+ mcp.config.sources = os.path.abspath(args.sources)
+
+if args.config:
+ mcp.config.config = os.path.abspath(args.config)
+
+if args.scripting:
+ mcp.config.scripting = os.path.abspath(args.scripting)
+
+if args.tmp:
+ mcp.config.tmp = os.path.abspath(args.tmp)
+
+if args.sftpkey:
+ mcp.config.sftpkey = os.path.abspath(args.sftpkey)
+
+if args.user:
+ mcp.config.user = args.user
+
+if args.container:
+ mcp.config.container = args.container
+
+
+if mcp.config.log:
+ logging.getLogger('mcp').addHandler(logging.StreamHandler())
+ logging.getLogger('mcp').addHandler(logging.FileHandler(mcp.config.log))
+
+
+if mcp.config.cmdlog:
+ logging.getLogger('cmd').addHandler(logging.FileHandler(mcp.config.cmdlog))
+
+
+if mcp.config.httpdlog:
+ logging.getLogger('web').addHandler(logging.FileHandler(mcp.config.httpdlog))
+
+
+if mcp.config.accesslog:
+ logging.getLogger('http').handlers = []
+
+ accesslog_handler = logging.FileHandler(mcp.config.accesslog)
+ accesslog_handler.setFormatter(fooster.web.HTTPLogFormatter())
+
+ logging.getLogger('http').addHandler(accesslog_handler)
+
+
+from mcp import name, version
+
+import mcp.initial
+
+import mcp.common.util
+
+
+if os.geteuid() == 0:
+ pid = os.fork()
+ if pid == 0:
+ mcp.common.util.demote(mcp.config.user)
+ mcp.initial.check()
+ sys.exit(0)
+ else:
+ os.waitpid(pid, 0)
+else:
+ # check for initial files
+ mcp.initial.check()
+
+
+import mcp.service.manager
+
+log = logging.getLogger('mcp')
+
+log.info(name + ' ' + version + ' starting...')
+
+if mcp.config.container and os.geteuid() != 0:
+ log.error('Root privileges required to create containers.\nNote: The root privileges will be dropped by all daemons except the server management daemon.')
+ sys.exit(1)
+
+# fix multiprocessing ctrl+c
+signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+# start server manager
+mcp.service.manager.start()
+# drop root privileges if necessary
+if os.geteuid() == 0:
+ mcp.common.util.demote(mcp.config.user)
+
+
+import mcp.common.daemon
+
+
+# fill in daemon details
+mcp.common.daemon.pid = os.getpid()
+mcp.common.daemon.sync = multiprocessing.Manager()
+
+
+import mcp.service.http
+import mcp.service.rotate
+import mcp.service.update
+if os.path.exists(mcp.config.sftpkey):
+ import mcp.service.sftp
+
+
+# start everything else
+mcp.service.rotate.start()
+mcp.service.update.start()
+
+if os.path.exists(mcp.config.sftpkey):
+ mcp.service.sftp.start()
+
+mcp.service.http.start()
+
+# cleanup function
+def exit(signum, frame):
+ mcp.service.http.stop()
+
+# restart function
+def restart(signum, frame):
+ mcp.service.manager.stop()
+ mcp.service.manager.start()
+
+# use the function for both SIGINT and SIGTERM
+for sig in signal.SIGINT, signal.SIGTERM:
+ signal.signal(sig, exit)
+
+# use SIGUSR1 for restart
+signal.signal(signal.SIGUSR1, restart)
+
+# wait for http to finish
+mcp.service.http.join()
+
+# stop background services
+if os.path.exists(mcp.config.sftpkey):
+ mcp.service.sftp.stop()
+
+mcp.service.update.stop()
+mcp.service.rotate.stop()
+mcp.service.manager.stop()
diff --git a/pool/shard003/Python/0028627_currency.py b/pool/shard003/Python/0028627_currency.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d920d9ff9f0aff385bb91b14c6c9bbf52ae8aca
--- /dev/null
+++ b/pool/shard003/Python/0028627_currency.py
@@ -0,0 +1,61 @@
+# -*- coding: utf-8 -*-
+
+from decimal import Decimal
+from django.db import models
+from django.contrib import admin
+from django.utils.translation import ugettext as _
+
+
+class Currency(models.Model):
+ description = models.CharField(verbose_name=_("Description"),
+ max_length=100)
+ short_name = models.CharField(verbose_name=_("Displayed Name After Prices"),
+ max_length=3)
+ rounding = models.DecimalField(max_digits=5,
+ decimal_places=2,
+ verbose_name=_("Rounding"),
+ blank=True,
+ null=True)
+
+ def get_rounding(self):
+ """Returns either the stored rounding value for a currency or a default rounding value of 0.05
+
+ Args: no arguments
+
+ Returns: Decimal value
+
+ Raises: should not return exceptions"""
+ if self.rounding is None:
+ return Decimal('0.05')
+ else:
+ return self.rounding
+
+ def round(self, value):
+ """Rounds the input value to the rounding resolution which is defined in the variable "rounding"
+
+ Args: Decimal value value
+
+ Returns: Decimal value
+
+ Raises: should not return exceptions"""
+ rounded_value = int(value / self.get_rounding()) * self.get_rounding()
+ return rounded_value
+
+ def __str__(self):
+ return self.short_name
+
+ class Meta:
+ app_label = "crm"
+ verbose_name = _('Currency')
+ verbose_name_plural = _('Currency')
+
+
+class OptionCurrency(admin.ModelAdmin):
+ list_display = ('id',
+ 'description',
+ 'short_name',
+ 'rounding')
+ fieldsets = (('', {'fields': ('description',
+ 'short_name',
+ 'rounding')}),)
+ allow_add = True
diff --git a/pool/shard003/Python/0028629_writer.py b/pool/shard003/Python/0028629_writer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a27e1efd1761f18e55ebb2a0c2469191c097da1
--- /dev/null
+++ b/pool/shard003/Python/0028629_writer.py
@@ -0,0 +1,67 @@
+import time
+from netlib.exceptions import TcpDisconnect
+import netlib.tcp
+
+BLOCKSIZE = 1024
+# It's not clear what the upper limit for time.sleep is. It's lower than the
+# maximum int or float. 1 year should do.
+FOREVER = 60 * 60 * 24 * 365
+
+
+def send_chunk(fp, val, blocksize, start, end):
+ """
+ (start, end): Inclusive lower bound, exclusive upper bound.
+ """
+ for i in range(start, end, blocksize):
+ fp.write(
+ val[i:min(i + blocksize, end)]
+ )
+ return end - start
+
+
+def write_values(fp, vals, actions, sofar=0, blocksize=BLOCKSIZE):
+ """
+ vals: A list of values, which may be strings or Value objects.
+
+ actions: A list of (offset, action, arg) tuples. Action may be "pause"
+ or "disconnect".
+
+ Both vals and actions are in reverse order, with the first items last.
+
+ Return True if connection should disconnect.
+ """
+ sofar = 0
+ try:
+ while vals:
+ v = vals.pop()
+ offset = 0
+ while actions and actions[-1][0] < (sofar + len(v)):
+ a = actions.pop()
+ offset += send_chunk(
+ fp,
+ v,
+ blocksize,
+ offset,
+ a[0] - sofar - offset
+ )
+ if a[1] == "pause":
+ time.sleep(
+ FOREVER if a[2] == "f" else a[2]
+ )
+ elif a[1] == "disconnect":
+ return True
+ elif a[1] == "inject":
+ send_chunk(fp, a[2], blocksize, 0, len(a[2]))
+ send_chunk(fp, v, blocksize, offset, len(v))
+ sofar += len(v)
+ # Remainders
+ while actions:
+ a = actions.pop()
+ if a[1] == "pause":
+ time.sleep(a[2])
+ elif a[1] == "disconnect":
+ return True
+ elif a[1] == "inject":
+ send_chunk(fp, a[2], blocksize, 0, len(a[2]))
+ except TcpDisconnect: # pragma: no cover
+ return True
diff --git a/pool/shard003/Python/0028630_dashboard.py b/pool/shard003/Python/0028630_dashboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbf1d0fbfd2fa73d3cd194fe7dc01235bd286f7d
--- /dev/null
+++ b/pool/shard003/Python/0028630_dashboard.py
@@ -0,0 +1,156 @@
+from __future__ import unicode_literals
+
+from django.apps import apps
+from django.conf import settings
+from django.conf.urls import patterns, url, include
+from django.core.cache import cache
+from django.core.urlresolvers import reverse
+from django.template.loader import render_to_string
+from django.utils import six
+from django.utils.functional import cached_property
+from django.utils.importlib import import_module
+from django.utils.translation import ugettext_lazy as _
+
+
+class Dashboard(object):
+ @cached_property
+ def widgets(self):
+ return [
+ get_object(widget)(**config)
+ for widget, config in settings.MKADMIN_DASHBOARD]
+
+ @cached_property
+ def urls(self):
+ urlpatterns = patterns('')
+ for widget in self.widgets:
+ urlpatterns += patterns(
+ '',
+ url(
+ r'^%s/' % widget.__class__.__name__.lower(),
+ include(widget.get_urls()),
+ ),
+ )
+ return urlpatterns
+
+
+dashboard = Dashboard()
+
+
+class Widget(object):
+ def __init__(self, **kwargs):
+ for key, value in kwargs.items():
+ if not hasattr(self, key):
+ raise TypeError('Invalid attribute %s for %s' % (
+ key, self.__class__.__name__))
+ setattr(self, key, value)
+
+ def get_urls(self):
+ return patterns('')
+
+ def get_context(self):
+ return {}
+
+ def render(self, context):
+ html = render_to_string(
+ 'mkadmin/%s.html' % self.__class__.__name__.lower(),
+ dict(self.get_context(), widget=self),
+ context_instance=context)
+ return html
+
+
+class AtAGlance(Widget):
+ models = []
+ title = _('At a glance')
+
+ def get_context(self):
+ models = [apps.get_model(model) for model in self.models]
+ models = [{
+ 'name': model._meta.verbose_name_plural,
+ 'count': model._default_manager.count(),
+ 'admin_url': reverse('admin:%s_%s_changelist' % (
+ model._meta.app_label, model._meta.model_name)),
+ } for model in models]
+
+ versions = []
+
+ import django
+ versions.append('Django %s' % django.get_version())
+
+ try:
+ import feincms
+ versions.append('FeinCMS %s' % feincms.__version__)
+ except ImportError:
+ pass
+
+ return {
+ 'models': models,
+ 'versions': versions,
+ }
+
+
+class Feed(Widget):
+ title = _('Feed')
+ url = None
+
+ def get_urls(self):
+ return patterns(
+ '',
+ url(r'^mkadmin_feed_feed/$', self.feed, name='mkadmin_feed_feed'),
+ )
+
+ def cache_key(self):
+ import hashlib
+ return 'mkadmin-feed-%s' % hashlib.md5(self.url).hexdigest()
+
+ def feed(self, request):
+ from django.http import HttpResponse
+ html = cache.get(self.cache_key())
+ if html:
+ return HttpResponse(html)
+
+ import feedparser
+ import socket
+
+ socket.setdefaulttimeout(5)
+ try:
+ feed = feedparser.parse(self.url)
+ context = {
+ 'feed': feed,
+ }
+ except:
+ context = {}
+
+ html = render_to_string('mkadmin/feed_feed.html', context)
+ cache.set(self.cache_key(), html, timeout=300)
+ return HttpResponse(html)
+
+
+class RecentActions(Widget):
+ title = _('Recent Actions')
+
+
+class AllApps(Widget):
+ title = _('All apps')
+
+
+class QuickDraft(Widget):
+ title = _('Quick draft')
+
+
+def get_object(path, fail_silently=False):
+ # Return early if path isn't a string (might already be an callable or
+ # a class or whatever)
+ if not isinstance(path, six.string_types): # XXX bytes?
+ return path
+
+ try:
+ return import_module(path)
+ except ImportError:
+ try:
+ dot = path.rindex('.')
+ mod, fn = path[:dot], path[dot + 1:]
+
+ return getattr(import_module(mod), fn)
+ except (AttributeError, ImportError):
+ if not fail_silently:
+ raise
diff --git a/pool/shard003/Python/0028631_test_schema.py b/pool/shard003/Python/0028631_test_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..d92eed3991ffccaf6b177db4c77f309a59b835e9
--- /dev/null
+++ b/pool/shard003/Python/0028631_test_schema.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import os
+import shutil
+
+from migrate import exceptions
+from migrate.versioning.schema import *
+from migrate.versioning import script, schemadiff
+
+from sqlalchemy import *
+
+from migrate.tests import fixture
+
+
+class TestControlledSchema(fixture.Pathed, fixture.DB):
+ # Transactions break postgres in this test; we'll clean up after ourselves
+ level = fixture.DB.CONNECT
+
+ def setUp(self):
+ super(TestControlledSchema, self).setUp()
+ self.path_repos = self.temp_usable_dir + '/repo/'
+ self.repos = Repository.create(self.path_repos, 'repo_name')
+
+ def _setup(self, url):
+ self.setUp()
+ super(TestControlledSchema, self)._setup(url)
+ self.cleanup()
+
+ def _teardown(self):
+ super(TestControlledSchema, self)._teardown()
+ self.cleanup()
+ self.tearDown()
+
+ def cleanup(self):
+ # drop existing version table if necessary
+ try:
+ ControlledSchema(self.engine, self.repos).drop()
+ except:
+ # No table to drop; that's fine, be silent
+ pass
+
+ def tearDown(self):
+ self.cleanup()
+ super(TestControlledSchema, self).tearDown()
+
+ @fixture.usedb()
+ def test_version_control(self):
+ """Establish version control on a particular database"""
+ # Establish version control on this database
+ dbcontrol = ControlledSchema.create(self.engine, self.repos)
+
+ # Trying to create another DB this way fails: table exists
+ self.assertRaises(exceptions.DatabaseAlreadyControlledError,
+ ControlledSchema.create, self.engine, self.repos)
+
+ # We can load a controlled DB this way, too
+ dbcontrol0 = ControlledSchema(self.engine, self.repos)
+ self.assertEqual(dbcontrol, dbcontrol0)
+
+ # We can also use a repository path, instead of a repository
+ dbcontrol0 = ControlledSchema(self.engine, self.repos.path)
+ self.assertEqual(dbcontrol, dbcontrol0)
+
+ # We don't have to use the same connection
+ engine = create_engine(self.url)
+ dbcontrol0 = ControlledSchema(engine, self.repos.path)
+ self.assertEqual(dbcontrol, dbcontrol0)
+
+ # Clean up:
+ dbcontrol.drop()
+
+ # Attempting to drop vc from a db without it should fail
+ self.assertRaises(exceptions.DatabaseNotControlledError, dbcontrol.drop)
+
+ # No table defined should raise error
+ self.assertRaises(exceptions.DatabaseNotControlledError,
+ ControlledSchema, self.engine, self.repos)
+
+ @fixture.usedb()
+ def test_version_control_specified(self):
+ """Establish version control with a specified version"""
+ # Establish version control on this database
+ version = 0
+ dbcontrol = ControlledSchema.create(self.engine, self.repos, version)
+ self.assertEqual(dbcontrol.version, version)
+
+ # Correct when we load it, too
+ dbcontrol = ControlledSchema(self.engine, self.repos)
+ self.assertEqual(dbcontrol.version, version)
+
+ dbcontrol.drop()
+
+ # Now try it with a nonzero value
+ version = 10
+ for i in range(version):
+ self.repos.create_script('')
+ self.assertEqual(self.repos.latest, version)
+
+ # Test with some mid-range value
+ dbcontrol = ControlledSchema.create(self.engine,self.repos, 5)
+ self.assertEqual(dbcontrol.version, 5)
+ dbcontrol.drop()
+
+ # Test with max value
+ dbcontrol = ControlledSchema.create(self.engine, self.repos, version)
+ self.assertEqual(dbcontrol.version, version)
+ dbcontrol.drop()
+
+ @fixture.usedb()
+ def test_version_control_invalid(self):
+ """Try to establish version control with an invalid version"""
+ versions = ('Thirteen', '-1', -1, '' , 13)
+ # A fresh repository doesn't go up to version 13 yet
+ for version in versions:
+ #self.assertRaises(ControlledSchema.InvalidVersionError,
+ # Can't have custom errors with assertRaises...
+ try:
+ ControlledSchema.create(self.engine, self.repos, version)
+ self.assertTrue(False, repr(version))
+ except exceptions.InvalidVersionError:
+ pass
+
+ @fixture.usedb()
+ def test_changeset(self):
+ """Create changeset from controlled schema"""
+ dbschema = ControlledSchema.create(self.engine, self.repos)
+
+ # empty schema doesn't have changesets
+ cs = dbschema.changeset()
+ self.assertEqual(cs, {})
+
+ for i in range(5):
+ self.repos.create_script('')
+ self.assertEqual(self.repos.latest, 5)
+
+ cs = dbschema.changeset(5)
+ self.assertEqual(len(cs), 5)
+
+ # cleanup
+ dbschema.drop()
+
+ @fixture.usedb()
+ def test_upgrade_runchange(self):
+ dbschema = ControlledSchema.create(self.engine, self.repos)
+
+ for i in range(10):
+ self.repos.create_script('')
+
+ self.assertEqual(self.repos.latest, 10)
+
+ dbschema.upgrade(10)
+
+ self.assertRaises(ValueError, dbschema.upgrade, 'a')
+ self.assertRaises(exceptions.InvalidVersionError, dbschema.runchange, 20, '', 1)
+
+ # TODO: test for table version in db
+
+ # cleanup
+ dbschema.drop()
+
+ @fixture.usedb()
+ def test_create_model(self):
+ """Test workflow to generate create_model"""
+ model = ControlledSchema.create_model(self.engine, self.repos, declarative=False)
+ self.assertTrue(isinstance(model, basestring))
+
+ model = ControlledSchema.create_model(self.engine, self.repos.path, declarative=True)
+ self.assertTrue(isinstance(model, basestring))
+
+ @fixture.usedb()
+ def test_compare_model_to_db(self):
+ meta = self.construct_model()
+
+ diff = ControlledSchema.compare_model_to_db(self.engine, meta, self.repos)
+ self.assertTrue(isinstance(diff, schemadiff.SchemaDiff))
+
+ diff = ControlledSchema.compare_model_to_db(self.engine, meta, self.repos.path)
+ self.assertTrue(isinstance(diff, schemadiff.SchemaDiff))
+ meta.drop_all(self.engine)
+
+ @fixture.usedb()
+ def test_update_db_from_model(self):
+ dbschema = ControlledSchema.create(self.engine, self.repos)
+
+ meta = self.construct_model()
+
+ dbschema.update_db_from_model(meta)
+
+ # TODO: test for table version in db
+
+ # cleanup
+ dbschema.drop()
+ meta.drop_all(self.engine)
+
+ def construct_model(self):
+ meta = MetaData()
+
+ user = Table('temp_model_schema', meta, Column('id', Integer), Column('user', String(245)))
+
+ return meta
+
+ # TODO: test how are tables populated in db
diff --git a/pool/shard003/Python/0028634_east_multi_inference.py b/pool/shard003/Python/0028634_east_multi_inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..dea85f379dba1db3bf041c59ab1cdcad089a6bee
--- /dev/null
+++ b/pool/shard003/Python/0028634_east_multi_inference.py
@@ -0,0 +1,63 @@
+# Copyright 2017 The UAI-SDK Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+
+"""A east text detector inferencer.
+
+"""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import sys
+from PIL import Image
+import tensorflow as tf
+import numpy as np
+import sys
+import os
+import copy
+import argparse
+import cv2
+import lanms
+import model
+from icdar import restore_rectangle
+
+import east_multi_infer
+from uai.arch.tf_model import TFAiUcloudModel
+
+class EASTTextDetectModel(TFAiUcloudModel):
+ """ EASTTextDetectModel example model
+ """
+
+ def __init__(self, conf):
+ super(EASTTextDetectModel, self).__init__(conf)
+
+ def load_model(self):
+ predictor = east_multi_infer.EastPredictor('./checkpoint_dir')
+ predictor.load_serve_model()
+ self._predictor = predictor
+
+ def execute(self, data, batch_size):
+ predictor = self._predictor
+ ret = []
+
+ images = []
+ for i in range(batch_size):
+ image = Image.open(data[i])
+ images.append(image)
+
+ results = predictor.do_serve_predict(images)
+
+ return results
+
diff --git a/pool/shard003/Python/0028636_convolution_2d.py b/pool/shard003/Python/0028636_convolution_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d880398cb039bec2db94094c6e8d9b6f24b0d60
--- /dev/null
+++ b/pool/shard003/Python/0028636_convolution_2d.py
@@ -0,0 +1,172 @@
+from chainer.functions.connection import convolution_2d
+from chainer import initializers
+from chainer import link
+from chainer.utils import argument
+from chainer import variable
+
+
+class Convolution2D(link.Link):
+
+ """__init__(self, in_channels, out_channels, ksize=None, stride=1, pad=0, nobias=False, initialW=None, initial_bias=None, *, dilate=1, groups=1)
+
+ Two-dimensional convolutional layer.
+
+ This link wraps the :func:`~chainer.functions.convolution_2d` function and
+ holds the filter weight and bias vector as parameters.
+
+ The output of this function can be non-deterministic when it uses cuDNN.
+ If ``chainer.configuration.config.deterministic`` is ``True`` and
+ cuDNN version is >= v3, it forces cuDNN to use a deterministic algorithm.
+
+ Convolution links can use a feature of cuDNN called autotuning, which
+ selects the most efficient CNN algorithm for images of fixed-size,
+ can provide a significant performance boost for fixed neural nets.
+ To enable, set `chainer.using_config('autotune', True)`
+
+ Args:
+ in_channels (int or None): Number of channels of input arrays.
+ If ``None``, parameter initialization will be deferred until the
+ first forward data pass at which time the size will be determined.
+ out_channels (int): Number of channels of output arrays.
+ ksize (int or pair of ints): Size of filters (a.k.a. kernels).
+ ``ksize=k`` and ``ksize=(k, k)`` are equivalent.
+ stride (int or pair of ints): Stride of filter applications.
+ ``stride=s`` and ``stride=(s, s)`` are equivalent.
+ pad (int or pair of ints): Spatial padding width for input arrays.
+ ``pad=p`` and ``pad=(p, p)`` are equivalent.
+ nobias (bool): If ``True``, then this link does not use the bias term.
+ initialW (:ref:`initializer `): Initializer to
+ initialize the weight. When it is :class:`numpy.ndarray`,
+ its ``ndim`` should be 4.
+ initial_bias (:ref:`initializer `): Initializer to
+ initialize the bias. If ``None``, the bias will be initialized to
+ zero. When it is :class:`numpy.ndarray`, its ``ndim`` should be 1.
+ dilate (int or pair of ints):
+ Dilation factor of filter applications.
+ ``dilate=d`` and ``dilate=(d, d)`` are equivalent.
+ groups (:class:`int`): Number of groups of channels. If the number
+ is greater than 1, input tensor :math:`W` is divided into some
+ blocks by this value channel-wise. For each tensor blocks,
+ convolution operation will be executed independently. Input channel
+ size ``in_channels`` and output channel size ``out_channels`` must
+ be exactly divisible by this value.
+
+ .. seealso::
+ See :func:`chainer.functions.convolution_2d` for the definition of
+ two-dimensional convolution.
+
+ Attributes:
+ W (~chainer.Variable): Weight parameter.
+ b (~chainer.Variable): Bias parameter.
+
+ .. admonition:: Example
+
+ There are several ways to make a Convolution2D link.
+
+ Let an input vector ``x`` be:
+
+ >>> x = np.arange(1 * 3 * 10 * 10, dtype=np.float32).reshape(1, 3, 10, 10)
+
+ 1. Give the first three arguments explicitly:
+
+ >>> l = L.Convolution2D(3, 7, 5)
+ >>> y = l(x)
+ >>> y.shape
+ (1, 7, 6, 6)
+
+ 2. Omit ``in_channels`` or fill it with ``None``:
+
+ The below two cases are the same.
+
+ >>> l = L.Convolution2D(7, 5)
+ >>> y = l(x)
+ >>> y.shape
+ (1, 7, 6, 6)
+
+ >>> l = L.Convolution2D(None, 7, 5)
+ >>> y = l(x)
+ >>> y.shape
+ (1, 7, 6, 6)
+
+ When you omit the first argument, you need to specify the other
+ subsequent arguments from ``stride`` as keyword auguments. So the
+ below two cases are the same.
+
+ >>> l = L.Convolution2D(7, 5, stride=1, pad=0)
+ >>> y = l(x)
+ >>> y.shape
+ (1, 7, 6, 6)
+
+ >>> l = L.Convolution2D(None, 7, 5, 1, 0)
+ >>> y = l(x)
+ >>> y.shape
+ (1, 7, 6, 6)
+
+ """ # NOQA
+
+ def __init__(self, in_channels, out_channels, ksize=None, stride=1, pad=0,
+ nobias=False, initialW=None, initial_bias=None, **kwargs):
+ super(Convolution2D, self).__init__()
+
+ dilate, groups = argument.parse_kwargs(
+ kwargs, ('dilate', 1), ('groups', 1),
+ deterministic="deterministic argument is not supported anymore. "
+ "Use chainer.using_config('cudnn_deterministic', value) "
+ "context where value is either `True` or `False`.")
+
+ if ksize is None:
+ out_channels, ksize, in_channels = in_channels, out_channels, None
+
+ self.ksize = ksize
+ self.stride = _pair(stride)
+ self.pad = _pair(pad)
+ self.dilate = _pair(dilate)
+ self.out_channels = out_channels
+ self.groups = int(groups)
+
+ with self.init_scope():
+ W_initializer = initializers._get_initializer(initialW)
+ self.W = variable.Parameter(W_initializer)
+ if in_channels is not None:
+ self._initialize_params(in_channels)
+
+ if nobias:
+ self.b = None
+ else:
+ if initial_bias is None:
+ initial_bias = 0
+ bias_initializer = initializers._get_initializer(initial_bias)
+ self.b = variable.Parameter(bias_initializer, out_channels)
+
+ def _initialize_params(self, in_channels):
+ kh, kw = _pair(self.ksize)
+ if self.out_channels % self.groups != 0:
+ raise ValueError('the number of output channels must be'
+ ' divisible by the number of groups')
+ if in_channels % self.groups != 0:
+ raise ValueError('the number of input channels must be'
+ ' divisible by the number of groups')
+ W_shape = (self.out_channels, int(in_channels / self.groups), kh, kw)
+ self.W.initialize(W_shape)
+
+ def forward(self, x):
+ """Applies the convolution layer.
+
+ Args:
+ x (~chainer.Variable): Input image.
+
+ Returns:
+ ~chainer.Variable: Output of the convolution.
+
+ """
+ if self.W.array is None:
+ self._initialize_params(x.shape[1])
+ return convolution_2d.convolution_2d(
+ x, self.W, self.b, self.stride, self.pad, dilate=self.dilate,
+ groups=self.groups)
+
+
+def _pair(x):
+ if hasattr(x, '__getitem__'):
+ return x
+ return x, x
diff --git a/pool/shard003/Python/0028640_leave_open.py b/pool/shard003/Python/0028640_leave_open.py
new file mode 100644
index 0000000000000000000000000000000000000000..366e62aa6a320c46c268092ad6092638e16fb5a9
--- /dev/null
+++ b/pool/shard003/Python/0028640_leave_open.py
@@ -0,0 +1,37 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this file,
+# You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from auto_nag.bzcleaner import BzCleaner
+
+
+class LeaveOpen(BzCleaner):
+ def __init__(self):
+ super(LeaveOpen, self).__init__()
+
+ def description(self):
+ return "Closed bugs with leave-open keyword"
+
+ def get_bz_params(self, date):
+ start_date, end_date = self.get_dates(date)
+ params = {
+ "bug_status": ["RESOLVED", "VERIFIED", "CLOSED"],
+ "f1": "keywords",
+ "o1": "casesubstring",
+ "v1": "leave-open",
+ "f2": "resolution",
+ "o2": "changedafter",
+ "v2": start_date,
+ "f3": "resolution",
+ "o3": "changedbefore",
+ "v3": end_date,
+ }
+
+ return params
+
+ def get_autofix_change(self):
+ return {"keywords": {"remove": ["leave-open"]}}
+
+
+if __name__ == "__main__":
+ LeaveOpen().run()
diff --git a/pool/shard003/Python/0028647_get_north_index_all_jan2017.py b/pool/shard003/Python/0028647_get_north_index_all_jan2017.py
new file mode 100644
index 0000000000000000000000000000000000000000..db98c007cf804f33de908bfaf158eeb85b2eecd7
--- /dev/null
+++ b/pool/shard003/Python/0028647_get_north_index_all_jan2017.py
@@ -0,0 +1,131 @@
+# Copyright (c) Case Western Reserve University 2015
+# This software is distributed under Apache License 2.0
+# Consult the file LICENSE.txt
+# Author: Sean Quinn spq@case.edu
+# Dec 14 2016
+
+# PYTHON 2
+import os
+import numpy as np
+import subprocess as sp
+import sys
+import time
+import datetime as dt
+
+fdate = sp.check_output(['date','--date','-1 day','+%Y%m%d'])
+fdate = fdate.replace('\n','')
+yr = int(fdate[:4])
+mo = int(fdate[4:6])
+dy = int(fdate[6:])
+
+os.chdir('/home/augta/web_monitor/tmpevt')
+# Expected layout in cwd
+# tmpevt/
+# t2/
+
+# Ensure t2/ is clean before proceeding
+files_in_t2 = os.listdir('t2/')
+if len(files_in_t2) > 0:
+ for y in files_in_t2:
+ sp.call(['rm','t2/'+y])
+else:
+ print "Directory empty, no files to remove."
+
+sp.call(['cp','/home/augta/data/north/Events/%s/evt_list.txt' %fdate,'.'])
+evt_dat_list = np.loadtxt('evt_list.txt',dtype='S100')
+os.chdir('t2')
+dirlist = os.listdir('/home/augta/data/north/Events/%s' %fdate,)
+tsp_list = [j for j in dirlist if '.tsp' in j]
+tsp_list.sort()
+for m in tsp_list:
+ sp.call(['cp','/home/augta/data/north/Events/%s/%s' %(fdate,m),'.'])
+# Rename .tsp file to match .dat file so the correct
+#file name is given for the event retrieval script
+tsp_k = 0
+for k in tsp_list:
+ tsp_time = k.split('.')[0]
+ tsp_time = dt.datetime.strptime(tsp_time,'%Y%m%d_%H%M%S')
+ for j in evt_dat_list:
+ evt_time = j.split('.')[0]
+ evt_time = dt.datetime.strptime(evt_time,'%Y%m%d_%H%M%S')
+ tdiff = evt_time - tsp_time
+ if abs(tdiff.total_seconds()) < 5:
+ new_tsp = j.replace('.dat','.tsp')
+ tsp_list[tsp_k] = new_tsp
+ tsp_k += 1
+ break
+today = fdate
+sp.call(['cp','../make_t2.sh','.'])
+sp.call(['cp','../testtsp','.'])
+
+sp.call(['./make_t2.sh','%s' %today])
+big_t2_sec = np.loadtxt('%s.T2' %today,delimiter='.',dtype=int,usecols=(0,))
+big_t2_micro = np.loadtxt('%s.T2' %today,delimiter='.',dtype=float,usecols=(1,))
+big_t2_micro = big_t2_micro / 1e8
+
+sp.call(['cp','/home/augta/data/coincidence/%i_%02d_%02d.CTAL.gz' %(yr,mo,dy),'.'])
+sp.call(['gunzip','%i_%02d_%02d.CTAL.gz' %(yr,mo,dy)])
+tal_list = np.loadtxt('%i_%02d_%02d.CTAL'%(yr,mo,dy),usecols=(1,),dtype=str)
+evt_counter = 0
+denom = 20001
+with open('get_events_local.sh','w') as F1:
+ F1.write('#!/bin/bash\n\n')
+ if tal_list.size > 0:
+ if tal_list.size == 1:
+ new_tal = np.zeros(1,dtype='S500')
+ new_tal[0] = tal_list
+ tal_list = new_tal
+ for x in tal_list:
+ lsec = int(x.split('.')[0])
+ micro = float(x.split('.')[1])
+ micro = micro / 1e6
+ roi = np.where(big_t2_sec == lsec)[0]
+ if len(roi) > 0:
+ roi_micro = abs(big_t2_micro[roi] - micro)
+ ind = roi[roi_micro.argmin()]
+ fileind = ind / denom
+ ind_final = ind - fileind * denom
+ # If new data file, must transfer from the LSC
+ evt_dat_str = tsp_list[fileind][:-3]+'dat'
+ F1.write('./getevt -i %i -o %02d_local.evt %s\n' %(ind_final,evt_counter,evt_dat_str))
+ evt_counter += 1
+ else:
+ print "**** MISSING T2 DATA FOR GPS SECOND %i" %lsec
+ evt_counter += 1
+
+sp.call(['cp','/home/augta/data/coincidence/%i_%02d_%02d.CTAG.gz' %(yr,mo,dy),'.'])
+sp.call(['gunzip','%i_%02d_%02d.CTAG.gz' %(yr,mo,dy)])
+tag_list = np.loadtxt('%i_%02d_%02d.CTAG'%(yr,mo,dy),usecols=(6,),dtype='S500',
+ comments=None)
+evt_counter = 0
+denom = 20001
+with open('get_events_global.sh','w') as F1:
+ F1.write('#!/bin/bash\n\n')
+ if tag_list.size > 0:
+ if tag_list.size == 1:
+ new_tag = np.zeros(1,dtype='S500')
+ new_tag[0] = tag_list
+ tag_list = new_tag
+ for x in tag_list:
+ lsec = int(x.split('.')[0])
+ micro = float(x.split('.')[1])
+ micro = micro / 1e6
+ roi = np.where(big_t2_sec == lsec)[0]
+ if len(roi) > 0:
+ roi_micro = abs(big_t2_micro[roi] - micro)
+ ind = roi[roi_micro.argmin()]
+ fileind = ind / denom
+ ind_final = ind - fileind * denom
+ evt_dat_str = tsp_list[fileind][:-3]+'dat'
+ F1.write('./getevt -i %i -o %02d_global.evt %s\n' %(ind_final,evt_counter,evt_dat_str))
+ evt_counter += 1
+ else:
+ print "**** MISSING T2 DATA FOR GPS SECOND %i" %lsec
+ evt_counter += 1
+
+sp.call(['cp','get_events_global.sh','/home/augta/data/north'])
+sp.call(['cp','get_events_local.sh','/home/augta/data/north'])
+# Temp folder cleanup
+newlist = os.listdir('/home/augta/web_monitor/tmpevt/t2/')
+for x in newlist:
+ sp.call(['rm','/home/augta/web_monitor/tmpevt/t2/'+x])
diff --git a/pool/shard003/Python/0028652_compiler_options_test.py b/pool/shard003/Python/0028652_compiler_options_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..945db55b2b405416f4074afba87222c473bba3b6
--- /dev/null
+++ b/pool/shard003/Python/0028652_compiler_options_test.py
@@ -0,0 +1,50 @@
+# Copyright 2022 The IREE Authors
+#
+# Licensed under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+
+import logging
+import unittest
+
+from iree.compiler.transforms import ireec
+
+
+class CompilerTest(unittest.TestCase):
+
+ def testDefaultOptions(self):
+ options = ireec.CompilerOptions()
+ self.assertEqual(repr(options), "")
+
+ def testOptionsBadArg(self):
+ with self.assertRaisesRegex(ValueError, "option not found: foobar"):
+ options = ireec.CompilerOptions("--foobar")
+
+ def testOptionsBoolArgImplicit(self):
+ options = ireec.CompilerOptions("--iree-tflite-bindings-support")
+ self.assertEqual(
+ repr(options),
+ "")
+
+ def testOptionsBoolArgExplicit(self):
+ options = ireec.CompilerOptions("--iree-tflite-bindings-support=true")
+ self.assertEqual(
+ repr(options),
+ "")
+
+ def testOptionsEnumArg(self):
+ options = ireec.CompilerOptions("--iree-input-type=mhlo")
+ self.assertEqual(repr(options),
+ "")
+
+ def testListOption(self):
+ options = ireec.CompilerOptions("--iree-hal-target-backends=cpu,vmvx")
+ self.assertEqual(
+ repr(options),
+ "")
+ print(options)
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.DEBUG)
+ unittest.main()
diff --git a/pool/shard003/Python/0028659_gene_queries.py b/pool/shard003/Python/0028659_gene_queries.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1aa3b12cf0f350b4a7c8b7b6c6e8f57d098f6e4
--- /dev/null
+++ b/pool/shard003/Python/0028659_gene_queries.py
@@ -0,0 +1,34 @@
+import logging
+import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger
+
+__authors__ = "David L. Lahr"
+__email__ = "dlahr@broadinstitute.org"
+
+
+logger = logging.getLogger(setup_logger.LOGGER_NAME)
+
+resource_name = "genes"
+
+
+def are_genes_in_api(my_clue_api_client, gene_symbols):
+ """determine if genes are present in the API
+
+ Args:
+ my_clue_api_client:
+ gene_symbols: collection of gene symbols to query the API with
+
+ Returns: set of the found gene symbols
+
+ """
+ if len(gene_symbols) > 0:
+ query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols)
+
+ query_result = my_clue_api_client.run_filter_query(resource_name,
+ {"where":{"gene_symbol":{"inq":query_gene_symbols}}, "fields":{"gene_symbol":True}})
+ logger.debug("query_result: {}".format(query_result))
+
+ r = set([x["gene_symbol"] for x in query_result])
+ return r
+ else:
+ logger.warning("provided gene_symbols was empty, cannot run query")
+ return set()
diff --git a/pool/shard003/Python/0028670_test_pyopenssl.py b/pool/shard003/Python/0028670_test_pyopenssl.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fc296f31b43b2a061f963b3a0bdca51c9768c6c
--- /dev/null
+++ b/pool/shard003/Python/0028670_test_pyopenssl.py
@@ -0,0 +1,86 @@
+# -*- coding: utf-8 -*-
+import os
+import unittest
+
+import mock
+import pytest
+
+try:
+ from urllib3.contrib.pyopenssl import (
+ _dnsname_to_stdlib, get_subj_alt_name
+ )
+ from cryptography import x509
+ from OpenSSL.crypto import FILETYPE_PEM, load_certificate
+except ImportError:
+ pass
+
+
+def setup_module():
+ try:
+ from urllib3.contrib.pyopenssl import inject_into_urllib3
+ inject_into_urllib3()
+ except ImportError as e:
+ pytest.skip('Could not import PyOpenSSL: %r' % e)
+
+
+def teardown_module():
+ try:
+ from urllib3.contrib.securetransport import extract_from_urllib3
+ extract_from_urllib3()
+ except ImportError:
+ pass
+
+
+from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401
+from ..with_dummyserver.test_socketlevel import ( # noqa: F401
+ TestSNI, TestSocketClosing, TestClientCerts
+)
+
+
+class TestPyOpenSSLHelpers(unittest.TestCase):
+ """
+ Tests for PyOpenSSL helper functions.
+ """
+ def test_dnsname_to_stdlib_simple(self):
+ """
+ We can convert a dnsname to a native string when the domain is simple.
+ """
+ name = u"उदाहरण.परीक"
+ expected_result = 'xn--p1b6ci4b4b3a.xn--11b5bs8d'
+
+ self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+
+ def test_dnsname_to_stdlib_leading_period(self):
+ """
+ If there is a . in front of the domain name we correctly encode it.
+ """
+ name = u".उदाहरण.परीक"
+ expected_result = '.xn--p1b6ci4b4b3a.xn--11b5bs8d'
+
+ self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+
+ def test_dnsname_to_stdlib_leading_splat(self):
+ """
+ If there's a wildcard character in the front of the string we handle it
+ appropriately.
+ """
+ name = u"*.उदाहरण.परीक"
+ expected_result = '*.xn--p1b6ci4b4b3a.xn--11b5bs8d'
+
+ self.assertEqual(_dnsname_to_stdlib(name), expected_result)
+
+ @mock.patch('urllib3.contrib.pyopenssl.log.warning')
+ def test_get_subj_alt_name(self, mock_warning):
+ """
+ If a certificate has two subject alternative names, cryptography raises
+ an x509.DuplicateExtension exception.
+ """
+ path = os.path.join(os.path.dirname(__file__), 'duplicate_san.pem')
+ with open(path, 'r') as fp:
+ cert = load_certificate(FILETYPE_PEM, fp.read())
+
+ self.assertEqual(get_subj_alt_name(cert), [])
+
+ self.assertEqual(mock_warning.call_count, 1)
+ self.assertIsInstance(mock_warning.call_args[0][1],
+ x509.DuplicateExtension)
diff --git a/pool/shard003/Python/0028671_init__.py b/pool/shard003/Python/0028671_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0d31b699d3acd62be89b991a005f115a8b26b9f
--- /dev/null
+++ b/pool/shard003/Python/0028671_init__.py
@@ -0,0 +1,55 @@
+#Used for the wesberver
+from flask import Flask
+
+#Used to create the process in which our server will reside
+from multiprocessing import Process
+
+#Used to load a browser window at localhost:port upon starting the server
+import webbrowser
+
+class FunkyServer(object):
+ app = None
+ process = None
+ host = 'localhost'
+ port = 5000
+
+ #Constructor
+ def __init__(self):
+ self.app = Flask('app')
+
+ #Add an endpoint for the server, so that the server can return data via the handler function
+ def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None):
+ self.app.add_url_rule(endpoint, endpoint_name, handler)
+
+ #This is the process that will run the server in the background
+ def create_process(self):
+ self.app.run(host=self.host, port=self.port)
+
+ #Start the process
+ #If open_new_window is True, open localhost:port in a new window
+ def start(self, open_new_window=True):
+ self.process = Process(target=self.create_process)
+ self.process.daemon = True
+ self.process.start()
+
+ if open_new_window:
+ webbrowser.open("%s:%s" % (self.host, self.port))
+
+ #Stop the process
+ def stop(self):
+ self.process.terminate()
+ self.process.join()
+
+ #Getters
+ def get_port(self):
+ return self.port
+
+ def get_host(self):
+ return self.host
+
+ #Setters
+ def set_port(self, port):
+ self.port = port
+
+ def set_host(self, host):
+ self.host = host
diff --git a/pool/shard003/Python/0028672_func_typecheck_getattr.py b/pool/shard003/Python/0028672_func_typecheck_getattr.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b7c075dc64e8190396087228133f0c026a312d
--- /dev/null
+++ b/pool/shard003/Python/0028672_func_typecheck_getattr.py
@@ -0,0 +1,69 @@
+# pylint: disable=
+"""check getattr if inference succeed"""
+
+__revision__ = None
+
+class Provider:
+ """provide some attributes and method"""
+ cattr = 4
+ def __init__(self):
+ self.attr = 4
+ def method(self, val):
+ """impressive method"""
+ return self.attr * val
+ def hophop(self):
+ """hop method"""
+ print 'hop hop hop', self
+
+
+class Client:
+ """use provider class"""
+
+ def __init__(self):
+ self._prov = Provider()
+ self._prov_attr = Provider.cattr
+ self._prov_attr2 = Provider.cattribute
+ self.set_later = 0
+
+ def set_set_later(self, value):
+ """set set_later attribute (introduce an inference ambiguity)"""
+ self.set_later = value
+
+ def use_method(self):
+ """use provider's method"""
+ self._prov.hophop()
+ self._prov.hophophop()
+
+ def use_attr(self):
+ """use provider's attr"""
+ print self._prov.attr
+ print self._prov.attribute
+
+ def debug(self):
+ """print debug information"""
+ print self.__class__.__name__
+ print self.__doc__
+ print self.__dict__
+ print self.__module__
+
+ def test_bt_types(self):
+ """test access to unexistant member of builtin types"""
+ lis = []
+ lis.apppend(self)
+ dic = {}
+ dic.set(self)
+ tup = ()
+ tup.append(self)
+ string = 'toto'
+ print string.loower()
+ # unicode : moved to func_3k_removed_stuff_py_30.py
+ #
+ integer = 1
+ print integer.whatever
+
+print object.__init__
+print property.__init__
+print Client().set_later.lower()
+
+# should detect mixing new style / old style classes
+Client.__bases__ += (object,)
diff --git a/pool/shard003/Python/0028675_0004_auto_20150919_2339.py b/pool/shard003/Python/0028675_0004_auto_20150919_2339.py
new file mode 100644
index 0000000000000000000000000000000000000000..66054a0a7b4e7db33f750e4b0f8e0fd25181d99c
--- /dev/null
+++ b/pool/shard003/Python/0028675_0004_auto_20150919_2339.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('lyrics', '0003_remove_song_top_five_words'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='song',
+ name='avg_syllables',
+ field=models.FloatField(default=0),
+ preserve_default=False,
+ ),
+ migrations.AddField(
+ model_name='song',
+ name='thug_rating',
+ field=models.FloatField(default=0),
+ preserve_default=False,
+ ),
+ ]
diff --git a/pool/shard003/Python/0028678_colbyPDL10A.py b/pool/shard003/Python/0028678_colbyPDL10A.py
new file mode 100644
index 0000000000000000000000000000000000000000..1760ebfdd6c0139ae7ccd0cccbd46879debc6703
--- /dev/null
+++ b/pool/shard003/Python/0028678_colbyPDL10A.py
@@ -0,0 +1,143 @@
+"""
+
+Python Interchangeable Virtual Instrument Library
+
+Copyright (c) 2012-2014 Alex Forencich
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+"""
+
+from .. import ivi
+from .. import scpi
+
+Mode = set(['312.5ps', '625ps'])
+
+class colbyPDL10A(scpi.common.IdnCommand, scpi.common.Reset,
+ scpi.common.SelfTest,
+ ivi.Driver):
+ "Colby Instruments PDL10A Programmable Delay Line driver"
+
+ def __init__(self, *args, **kwargs):
+ self.__dict__.setdefault('_instrument_id', 'PDL 10A')
+
+ super(colbyPDL10A, self).__init__(*args, **kwargs)
+
+ self._identity_description = "Colby Instruments PDL10A Programmable Delay Line driver"
+ self._identity_identifier = ""
+ self._identity_revision = ""
+ self._identity_vendor = ""
+ self._identity_instrument_manufacturer = "Colby Instruments"
+ self._identity_instrument_model = ""
+ self._identity_instrument_firmware_revision = ""
+ self._identity_specification_major_version = 0
+ self._identity_specification_minor_version = 0
+ self._identity_supported_instrument_models = ['PDL10A']
+
+ self._delay = 0
+ self._mode = ''
+
+ self._add_property('delay',
+ self._get_delay,
+ self._set_delay,
+ None,
+ ivi.Doc("""
+ Specifies the delay of the delay line. The units are seconds.
+ """))
+ self._add_property('mode',
+ self._get_mode,
+ self._set_mode,
+ None,
+ ivi.Doc("""
+ Specifies the mode of the delay line. If the segments are cascaded, then
+ the mode should be set to '625ps'. If the segments are not cascaded, then
+ the mode should be set to '312.5ps'.
+ """))
+
+ def _initialize(self, resource = None, id_query = False, reset = False, **keywargs):
+ "Opens an I/O session to the instrument."
+
+ super(colbyPDL10A, self)._initialize(resource, id_query, reset, **keywargs)
+
+ # interface clear
+ if not self._driver_operation_simulate:
+ self._clear()
+
+ # check ID
+ if id_query and not self._driver_operation_simulate:
+ id = self.identity.instrument_model
+ id_check = self._instrument_id
+ id_short = id[:len(id_check)]
+ if id_short != id_check:
+ raise Exception("Instrument ID mismatch, expecting %s, got %s", id_check, id_short)
+
+ # reset
+ if reset:
+ self.utility_reset()
+
+
+ def _utility_disable(self):
+ pass
+
+ def _utility_error_query(self):
+ error_code = 0
+ error_message = "No error"
+ if not self._driver_operation_simulate:
+ error_message = self._ask("err?").strip('"')
+ error_code = 1
+ if error_message == '0':
+ error_code = 0
+ return (error_code, error_message)
+
+ def _utility_lock_object(self):
+ pass
+
+ def _utility_unlock_object(self):
+ pass
+
+ def _get_delay(self):
+ if not self._driver_operation_simulate and not self._get_cache_valid():
+ resp = self._ask("del?")
+ self._delay = float(resp)
+ self._set_cache_valid()
+ return self._delay
+
+ def _set_delay(self, value):
+ value = float(value)
+ if not self._driver_operation_simulate:
+ self._write("del %e" % (value))
+ self._delay = value
+ self._set_cache_valid()
+
+ def _get_mode(self):
+ if not self._driver_operation_simulate and not self._get_cache_valid():
+ resp = self._ask("mode?")
+ self._mode = resp.strip('"')
+ self._set_cache_valid()
+ return self._mode
+
+ def _set_mode(self, value):
+ if value not in Mode:
+ raise ivi.ValueNotSupportedException()
+ if not self._driver_operation_simulate:
+ self._write("mode %s" % (value))
+ self._mode = value
+ self._set_cache_valid()
+ self._set_cache_valid(False, 'delay')
+
diff --git a/pool/shard003/Python/0028681_histogram_demo_cumulative.py b/pool/shard003/Python/0028681_histogram_demo_cumulative.py
new file mode 100644
index 0000000000000000000000000000000000000000..b555f0060eca6accb34b4d4343805adc77a5c6d2
--- /dev/null
+++ b/pool/shard003/Python/0028681_histogram_demo_cumulative.py
@@ -0,0 +1,30 @@
+"""
+Demo of the histogram (hist) function used to plot a cumulative distribution.
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib import mlab
+
+
+mu = 200
+sigma = 25
+n_bins = 50
+x = mu + sigma*np.random.randn(10000)
+
+n, bins, patches = plt.hist(x, n_bins, normed=1,
+ histtype='step', cumulative=True)
+
+# Add a line showing the expected distribution.
+y = mlab.normpdf(bins, mu, sigma).cumsum()
+y /= y[-1]
+plt.plot(bins, y, 'k--', linewidth=1.5)
+
+# Overlay a reversed cumulative histogram.
+plt.hist(x, bins=bins, normed=1, histtype='step', cumulative=-1)
+
+plt.grid(True)
+plt.ylim(0, 1.05)
+plt.title('cumulative step')
+
+plt.show()
diff --git a/pool/shard003/Python/0028688_telnet.py b/pool/shard003/Python/0028688_telnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f703ea34e6af08cc5a2b6dfce101278988da6f3
--- /dev/null
+++ b/pool/shard003/Python/0028688_telnet.py
@@ -0,0 +1,86 @@
+import telnetlib
+
+from v0ltlib.utils.v0lt_utils import fail, green, yellow, bytes_to_str
+
+
+# WIP - SOME FEATURES NEED SOME REWORK
+
+
+class Telnet:
+ """
+ Quick Telnet implementation
+ """
+
+ def __init__(self, hostname, port):
+ """
+ Initialize a netcat client
+
+ :param hostname: Hostname to connect to
+ :param port: Port to connect to
+ """
+
+ try:
+ self.tn = telnetlib.Telnet(hostname, port)
+ except Exception as err:
+ fail("Could not connect Telnet to {0}:{1} (error: {2})".format(hostname, port, err))
+ raise err
+ print("Connected to port {0}".format(green(port)))
+
+ def write(self, command):
+ """
+ Send a message
+ """
+
+ self.tn.write(bytes(command, "UTF-8"))
+
+ def writeln(self, command):
+ """
+ Send a message followed by a \n
+ """
+
+ self.write(command + "\n")
+
+ def shellnet(self, shellcode):
+ """
+ Send a shellcode from the ShellCrafter
+ """
+
+ shellcode = shellcode.replace("\\x", "")
+ self.tn.write(bytearray.fromhex(shellcode))
+
+ def read(self, nb_of_recv=1):
+ """
+ Read from the server
+ :param nb_of_recv: Number of message to try to receive
+ :returns: The received data
+ """
+
+ data = "\n"
+ for x in range(0, nb_of_recv):
+ data += bytes_to_str(self.tn.read_some())
+ return data
+
+
+def read_until(self, substring):
+ """
+ Read until 'substring' is found
+
+ :param substring: The string to look for
+ :returns: The received data
+ """
+
+ return bytes.decode(self.tn.read_until(bytes(substring, "UTF-8")), "UTF-8")
+
+
+def dialogue(self, command, nb_of_recv=1):
+ """
+ Exchange with the server
+ Sends 'commands' and waits for 'nb_of_recv' messages back
+
+ :param command: message to send
+ :param nb_of_recv: Number of messages to try to read
+ :returns: The received data
+ """
+
+ self.writeln(command)
+ return "{0}: {1}".format(yellow("Answer"), self.read(nb_of_recv))
diff --git a/pool/shard003/Python/0028694_install.py b/pool/shard003/Python/0028694_install.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7a3659a3f9fbcfa9b55171d98ad7e6a1bdb7f33
--- /dev/null
+++ b/pool/shard003/Python/0028694_install.py
@@ -0,0 +1,52 @@
+import os, os.path
+import zipfile
+
+try:
+ from urllib2 import urlopen
+except ImportError:
+ from urllib.request import urlopen
+
+
+def downlad_file(url, fname):
+ """Download file from url and save as fname."""
+ print("Downloading {} as {}".format(url, fname))
+ response = urlopen(url)
+ download = response.read()
+ with open(fname, 'wb') as fh:
+ fh.write(download)
+
+
+def unzip_file(zip_fname):
+ """Unzip the zip_fname in the current directory."""
+ print("Unzipping {}".format(zip_fname))
+ with zipfile.ZipFile(zip_fname) as zf:
+ zf.extractall()
+
+def install_from_zip(url):
+ """Download and unzip from url."""
+ fname = 'tmp.zip'
+ downlad_file(url, fname)
+ unzip_file(fname)
+ print("Removing {}".format(fname))
+ os.unlink(fname)
+
+def install_bftools():
+ print("Installing bftools.")
+# url = 'http://downloads.openmicroscopy.org/latest/bio-formats5.1/artifacts/bftools.zip'
+# Using older version of bftools as 5.1 appears to depend on SlideBook6Reader.dll
+ url = 'http://downloads.openmicroscopy.org/bio-formats/5.0.8/artifacts/bftools.zip'
+ install_from_zip(url)
+
+def install_freeimage():
+ print("Installing freeimage.")
+ url = 'http://downloads.sourceforge.net/freeimage/FreeImage3170Win32Win64.zip'
+ install_from_zip(url)
+
+def main():
+ print("Running {}.{}".format(__file__, __name__))
+ os.chdir("/")
+ print("Working directory: {}".format(os.getcwd()))
+ install_bftools()
+ install_freeimage()
+
+main()
diff --git a/pool/shard003/Python/0028696_validate_ebird_scraper.py b/pool/shard003/Python/0028696_validate_ebird_scraper.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e18905bc87b2edf7e48a97446a835f28b47e264
--- /dev/null
+++ b/pool/shard003/Python/0028696_validate_ebird_scraper.py
@@ -0,0 +1,50 @@
+"""
+validate_ebird_scraper.py
+
+This script is used to validate the scraper used to download checklists from
+the eBird API and checklist web pages. Once the scraper has finished the suite
+of tests in the module checklists_scrapers.tests.sites is executed to verify
+that all the information is extracted correctly.
+
+To run the tests on the checklists downloaded by the WorldBirds scraper run
+the script as follows:
+
+ python validate_ebird_scraper.py
+
+where,
+
+ is eBird region code for a given area, e.g. PT-11
+
+"""
+
+import json
+import nose
+import shutil
+import sys
+import tempfile
+
+from scrapy.settings import CrawlerSettings
+
+from checklists_scrapers import settings
+from checklists_scrapers.spiders.ebird_spider import EBirdSpider
+from checklists_scrapers.tests.utils import RunCrawler
+from checklists_scrapers.utils import list_files
+
+from checklists_scrapers.tests.validation import checklists
+
+
+settings.DOWNLOAD_DIR = tempfile.mkdtemp()
+settings.REPORT_RECIPIENTS = ''
+
+region = sys.argv[1]
+
+spider = EBirdSpider(region=region)
+RunCrawler(CrawlerSettings(settings)).crawl(spider)
+
+for path in list_files(settings.DOWNLOAD_DIR, 'json'):
+ with open(path, 'rb') as fp:
+ checklists.append(json.load(fp))
+
+nose.run(argv=['checklists_scrapers.tests.validation'])
+
+shutil.rmtree(settings.DOWNLOAD_DIR)
diff --git a/pool/shard003/Python/0028701_rv.py b/pool/shard003/Python/0028701_rv.py
new file mode 100644
index 0000000000000000000000000000000000000000..98c8a6842adc7211602a88e37d8f0f2123de3628
--- /dev/null
+++ b/pool/shard003/Python/0028701_rv.py
@@ -0,0 +1,46 @@
+
+from numpy import vectorize
+from numpy.random import random_sample
+
+__all__ = ['randwppf', 'randwcdf']
+
+# XXX: Are these needed anymore?
+
+#####################################
+# General purpose continuous
+######################################
+
+def randwppf(ppf, args=(), size=None):
+ """
+ returns an array of randomly distributed integers of a distribution
+ whose percent point function (inverse of the CDF or quantile function)
+ is given.
+
+ args is a tuple of extra arguments to the ppf function (i.e. shape,
+ location, scale), and size is the size of the output. Note the ppf
+ function must accept an array of q values to compute over.
+
+ """
+ U = random_sample(size=size)
+ return apply(ppf, (U,)+args)
+
+def randwcdf(cdf, mean=1.0, args=(), size=None):
+ """returns an array of randomly distributed integers of a distribution
+ whose cumulative distribution function (CDF) is given.
+
+ mean is the mean of the distribution (helps the solver).
+ args is a tuple of extra arguments to the cdf function (i.e. shape,
+ location, scale), and size is the size of the output. Note the
+ cdf function needs to accept a single value to compute over.
+ """
+ import scipy.optimize as optimize
+ def _ppfopt(x, q, *nargs):
+ newargs = (x,)+nargs
+ return cdf(*newargs) - q
+
+ def _ppf(q, *nargs):
+ return optimize.fsolve(_ppfopt, mean, args=(q,)+nargs)
+
+ _vppf = vectorize(_ppf)
+ U = random_sample(size=size)
+ return apply(_vppf,(U,)+args)
diff --git a/pool/shard003/Python/0028702_api2_test.py b/pool/shard003/Python/0028702_api2_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad46567bc03a90952f6c9e49f6c97a3f9baa52c3
--- /dev/null
+++ b/pool/shard003/Python/0028702_api2_test.py
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-
+
+#############################################################################
+##
+## Copyright (C) 2016 The Qt Company Ltd.
+## Contact: https://www.qt.io/licensing/
+##
+## This file is part of the test suite of PySide2.
+##
+## $QT_BEGIN_LICENSE:GPL-EXCEPT$
+## Commercial License Usage
+## Licensees holding valid commercial Qt licenses may use this file in
+## accordance with the commercial license agreement provided with the
+## Software or, alternatively, in accordance with the terms contained in
+## a written agreement between you and The Qt Company. For licensing terms
+## and conditions see https://www.qt.io/terms-conditions. For further
+## information use the contact form at https://www.qt.io/contact-us.
+##
+## GNU General Public License Usage
+## Alternatively, this file may be used under the terms of the GNU
+## General Public License version 3 as published by the Free Software
+## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
+## included in the packaging of this file. Please review the following
+## information to ensure the GNU General Public License requirements will
+## be met: https://www.gnu.org/licenses/gpl-3.0.html.
+##
+## $QT_END_LICENSE$
+##
+#############################################################################
+
+'''Test cases for PySide API2 support'''
+
+
+import unittest
+import sys
+
+from PySide2.QtGui import QIntValidator, QValidator
+from PySide2.QtWidgets import QWidget, QSpinBox, QApplication
+
+from helper import UsesQApplication
+
+class WidgetValidatorQInt(QWidget, QIntValidator):
+ def __init__(self, parent=None):
+ QWidget.__init__(self, parent)
+ QIntValidator.__init__(self, parent)
+
+class WidgetValidatorQSpinBox(QSpinBox):
+ def __init__(self, parent=None):
+ QSpinBox.__init__(self, parent)
+
+ def fixup(self, text):
+ print("It was called!")
+
+class DoubleQObjectInheritanceTest(UsesQApplication):
+
+ def testDouble(self):
+ '''Double inheritance from QObject classes'''
+
+ obj = WidgetValidatorQInt()
+
+ #QIntValidator methods
+ state, string, number = obj.validate('Test', 0)
+ self.assertEqual(state, QValidator.Invalid)
+ state, string, number = obj.validate('33', 0)
+ self.assertEqual(state, QValidator.Acceptable)
+
+ def testQSpinBox(self):
+ obj = WidgetValidatorQSpinBox()
+
+ obj.setRange(1, 10)
+ obj.setValue(0)
+ self.assertEqual(obj.value(), 1)
+
+class QClipboardTest(UsesQApplication):
+
+ def testQClipboard(self):
+ #skip this test on MacOS because the clipboard is not available during the ssh session
+ #this cause problems in the buildbot
+ if sys.platform == 'darwin':
+ return
+ clip = QApplication.clipboard()
+ clip.setText("Testing this thing!")
+
+ text, subtype = clip.text("")
+ self.assertEqual(subtype, "plain")
+ self.assertEqual(text, "Testing this thing!")
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard003/Python/0028712_32b34a664b5a_add_db_settings_table.py b/pool/shard003/Python/0028712_32b34a664b5a_add_db_settings_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ce3e75cb91b541ff8421ae66145633d39dfc9b
--- /dev/null
+++ b/pool/shard003/Python/0028712_32b34a664b5a_add_db_settings_table.py
@@ -0,0 +1,33 @@
+"""
+add DB settings table
+
+Revision ID: 32b34a664b5a
+Revises: 9dc8545963be
+Create Date: 2017-08-12 21:44:45.860272
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '32b34a664b5a'
+down_revision = '9dc8545963be'
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ 'settings',
+ sa.Column('name', sa.String(length=80), nullable=False),
+ sa.Column('value', sa.Text(), nullable=True),
+ sa.Column('default_value', sa.Text(), nullable=True),
+ sa.Column('is_json', sa.Boolean(), nullable=True),
+ sa.PrimaryKeyConstraint('name', name=op.f('pk_settings')),
+ mysql_engine='InnoDB'
+ )
+
+
+def downgrade():
+ op.drop_table('settings')
diff --git a/pool/shard003/Python/0028716_ethernet_chips.py b/pool/shard003/Python/0028716_ethernet_chips.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b940c0a33ff1ebe6b2a05b12c2dbc5427a118f
--- /dev/null
+++ b/pool/shard003/Python/0028716_ethernet_chips.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+
+"""Produce CSV listings of Ethernet connected chip positions."""
+
+import argparse
+
+from spinner.diagrams.machine_map import draw_machine_map, \
+ get_machine_map_aspect_ratio
+
+from spinner.utils import folded_torus
+
+from spinner import transforms
+from spinner import topology
+
+from spinner.scripts import arguments
+from spinner.scripts.contexts import PDFContextManager, PNGContextManager
+
+
+def main(args=None):
+ parser = argparse.ArgumentParser(
+ description="Produce CSV listings of Ethernet connected chip physical and "
+ "network positions.")
+ arguments.add_version_args(parser)
+ arguments.add_topology_args(parser)
+ arguments.add_cabinet_args(parser)
+
+ # Process command-line arguments
+ args = parser.parse_args(args)
+ (w, h), transformation, uncrinkle_direction, folds =\
+ arguments.get_topology_from_args(parser, args)
+
+ cabinet, num_frames = arguments.get_cabinets_from_args(parser, args)
+
+ # Generate folded system
+ hex_boards, folded_boards = folded_torus(w, h,
+ transformation,
+ uncrinkle_direction,
+ folds)
+
+ # Divide into cabinets
+ cabinetised_boards = transforms.cabinetise(folded_boards,
+ cabinet.num_cabinets,
+ num_frames,
+ cabinet.boards_per_frame)
+ cabinetised_boards = transforms.remove_gaps(cabinetised_boards)
+
+ # Generate the output
+ print("cabinet,frame,board,x,y")
+ b2c = dict(cabinetised_boards)
+ for board, hex_coord in sorted(hex_boards, key=(lambda v: topology.to_xy(v[1]))):
+ x, y = topology.to_xy(topology.board_to_chip(hex_coord))
+ c, f, b = b2c[board]
+ print(",".join(map(str, [c,f,b, x,y])))
+
+
+ return 0
+
+
+if __name__=="__main__": # pragma: no cover
+ import sys
+ sys.exit(main())
+
+
diff --git a/pool/shard003/Python/0028718_trie_tree.py b/pool/shard003/Python/0028718_trie_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e36eb2ee09f182722026a06cbc70aabf8b73794
--- /dev/null
+++ b/pool/shard003/Python/0028718_trie_tree.py
@@ -0,0 +1,35 @@
+class Node:
+ def __init__(self, val):
+ self.val = val
+ self.next = {}
+
+def insert(root, word):
+ cur = root
+ for i in xrange(len(word)):
+ if word[i] not in cur.next:
+ node = Node(word[i])
+ cur.next[word[i]] = node
+ cur = cur.next[word[i]]
+
+def find(root, word):
+ cur = root
+
+if __name__ == "__main__":
+ root = Node("")
+ insert(root, "lileeyao")
+ insert(root, "woshisha")
+ insert(root, "lilkk")
+ insert(root, "lilka")
+
+ queue = [root]
+ while queue != []:
+ tmp = []
+ while queue != []:
+ node = queue.pop(0)
+ for i in node.next.keys():
+ tmp.append(node.next[i])
+ if tmp != []:
+ for i in tmp:
+ print i.val,
+ queue += tmp
+ print
diff --git a/pool/shard003/Python/0028720_test_receiver.py b/pool/shard003/Python/0028720_test_receiver.py
new file mode 100644
index 0000000000000000000000000000000000000000..197cfb01e7b71a9b5524331cec4e5eb3e6fa2dcf
--- /dev/null
+++ b/pool/shard003/Python/0028720_test_receiver.py
@@ -0,0 +1,72 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from openstack.tests.unit import base
+
+from openstack.clustering.v1 import receiver
+
+
+FAKE_ID = 'ae63a10b-4a90-452c-aef1-113a0b255ee3'
+FAKE_NAME = 'test_receiver'
+
+FAKE = {
+ 'id': FAKE_ID,
+ 'name': FAKE_NAME,
+ 'type': 'webhook',
+ 'cluster_id': 'FAKE_CLUSTER',
+ 'action': 'CLUSTER_RESIZE',
+ 'created_at': '2015-10-10T12:46:36.000000',
+ 'updated_at': '2016-10-10T12:46:36.000000',
+ 'actor': {},
+ 'params': {
+ 'adjustment_type': 'CHANGE_IN_CAPACITY',
+ 'adjustment': 2
+ },
+ 'channel': {
+ 'alarm_url': 'http://host:port/webhooks/AN_ID/trigger?V=1',
+ },
+ 'user': 'FAKE_USER',
+ 'project': 'FAKE_PROJECT',
+ 'domain': '',
+}
+
+
+class TestReceiver(base.TestCase):
+
+ def setUp(self):
+ super(TestReceiver, self).setUp()
+
+ def test_basic(self):
+ sot = receiver.Receiver()
+ self.assertEqual('receiver', sot.resource_key)
+ self.assertEqual('receivers', sot.resources_key)
+ self.assertEqual('/receivers', sot.base_path)
+ self.assertTrue(sot.allow_create)
+ self.assertTrue(sot.allow_fetch)
+ self.assertTrue(sot.allow_commit)
+ self.assertTrue(sot.allow_delete)
+ self.assertTrue(sot.allow_list)
+
+ def test_instantiate(self):
+ sot = receiver.Receiver(**FAKE)
+ self.assertEqual(FAKE['id'], sot.id)
+ self.assertEqual(FAKE['name'], sot.name)
+ self.assertEqual(FAKE['type'], sot.type)
+ self.assertEqual(FAKE['cluster_id'], sot.cluster_id)
+ self.assertEqual(FAKE['action'], sot.action)
+ self.assertEqual(FAKE['params'], sot.params)
+ self.assertEqual(FAKE['created_at'], sot.created_at)
+ self.assertEqual(FAKE['updated_at'], sot.updated_at)
+ self.assertEqual(FAKE['user'], sot.user_id)
+ self.assertEqual(FAKE['project'], sot.project_id)
+ self.assertEqual(FAKE['domain'], sot.domain_id)
+ self.assertEqual(FAKE['channel'], sot.channel)
diff --git a/pool/shard003/Python/0028725_main.py b/pool/shard003/Python/0028725_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..90d28d07b0eea2e4e65903a0b67191d9119f500f
--- /dev/null
+++ b/pool/shard003/Python/0028725_main.py
@@ -0,0 +1,14 @@
+def main():
+ for _ in range(int(input())):
+ menu_items = int(input())
+ name = input()
+ s = {'pancakes','pea soup'}
+ for _ in range(menu_items):
+ s.discard(input())
+ if not s:
+ print(name)
+ return
+ print('Anywhere is fine I guess')
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/pool/shard003/Python/0028726_views.py b/pool/shard003/Python/0028726_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fe14fddd2790e7b35198d209f3b820a4aa2df78
--- /dev/null
+++ b/pool/shard003/Python/0028726_views.py
@@ -0,0 +1,169 @@
+# Copyright 2012 Nebula, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from django.urls import reverse
+from django.urls import reverse_lazy
+from django.utils.translation import ugettext_lazy as _
+from horizon import exceptions
+from horizon import forms
+from horizon import tables
+from horizon import tabs
+from horizon.utils import memoized
+
+from manila_ui.api import manila
+from manila_ui.dashboards.project.security_services import forms as ss_forms
+from manila_ui.dashboards.project.security_services import tables as ss_tables
+from manila_ui.dashboards.project.security_services import tabs as ss_tabs
+from manila_ui.dashboards.project.share_networks import forms as sn_forms
+from manila_ui.dashboards import utils
+
+
+class SecurityServicesView(tables.MultiTableView):
+ table_classes = (
+ ss_tables.SecurityServicesTable,
+ )
+ template_name = "project/security_services/index.html"
+ page_title = _("Security Services")
+
+ @memoized.memoized_method
+ def get_security_services_data(self):
+ try:
+ security_services = manila.security_service_list(self.request)
+ except Exception:
+ security_services = []
+ exceptions.handle(
+ self.request, _("Unable to retrieve security services"))
+
+ return security_services
+
+
+class UpdateView(forms.ModalFormView):
+ template_name = "project/security_services/update.html"
+ form_class = ss_forms.Update
+ form_id = "update_security_service"
+ modal_header = _("Edit Security Service")
+ modal_id = "update_security_service_modal"
+ submit_label = _("Edit")
+ submit_url = "horizon:project:security_services:security_service_update"
+ success_url = reverse_lazy("horizon:project:security_services:index")
+ page_title = _('Edit Security Service')
+
+ def get_object(self):
+ if not hasattr(self, "_object"):
+ sec_service_id = self.kwargs['sec_service_id']
+ try:
+ self._object = manila.security_service_get(
+ self.request, sec_service_id)
+ except Exception:
+ msg = _('Unable to retrieve security_service.')
+ url = reverse('horizon:project:security_services:index')
+ exceptions.handle(self.request, msg, redirect=url)
+ return self._object
+
+ def get_context_data(self, **kwargs):
+ context = super(UpdateView, self).get_context_data(**kwargs)
+ args = (self.kwargs['sec_service_id'],)
+ context['submit_url'] = reverse(self.submit_url, args=args)
+ return context
+
+ def get_initial(self):
+ sec_service = self.get_object()
+ return {'sec_service_id': self.kwargs["sec_service_id"],
+ 'dns_ip': sec_service.dns_ip,
+ 'ou': sec_service.ou,
+ 'server': sec_service.server,
+ 'domain': sec_service.domain,
+ 'user': sec_service.user,
+ 'name': sec_service.name,
+ 'description': sec_service.description,
+ }
+
+
+class CreateView(forms.ModalFormView):
+ form_class = ss_forms.Create
+ form_id = "create_security_service"
+ template_name = 'project/security_services/create.html'
+ modal_header = _("Create Security Service")
+ modal_id = "create_security_service_modal"
+ submit_label = _("Create")
+ submit_url = reverse_lazy(
+ "horizon:project:security_services:security_service_create")
+ success_url = reverse_lazy("horizon:project:security_services:index")
+ page_title = _('Create Security Service')
+
+
+class AddSecurityServiceView(forms.ModalFormView):
+ form_class = sn_forms.AddSecurityServiceForm
+ template_name = 'project/security_services/add.html'
+ success_url = 'horizon:project:security_services:index'
+ page_title = _('Add Security Service')
+
+ def get_object(self):
+ if not hasattr(self, "_object"):
+ share_id = self.kwargs['share_network_id']
+ try:
+ self._object = manila.share_network_get(self.request, share_id)
+ except Exception:
+ msg = _('Unable to retrieve share network.')
+ url = reverse('horizon:project:security_services:index')
+ exceptions.handle(self.request, msg, redirect=url)
+ return self._object
+
+ def get_context_data(self, **kwargs):
+ context = super(AddSecurityServiceView,
+ self).get_context_data(**kwargs)
+ context['share_network'] = self.get_object()
+ return context
+
+ def get_initial(self):
+ share_net = self.get_object()
+ return {'share_net_id': self.kwargs["share_network_id"],
+ 'name': share_net.name,
+ 'description': share_net.description}
+
+
+class Detail(tabs.TabView):
+ tab_group_class = ss_tabs.SecurityServiceDetailTabs
+ template_name = 'project/security_services/detail.html'
+ redirect_url = reverse_lazy('horizon:project:security_services:index')
+
+ def get_context_data(self, **kwargs):
+ context = super(Detail, self).get_context_data(**kwargs)
+ sec_service = self.get_data()
+ context["sec_service"] = sec_service
+ sec_service_display_name = sec_service.name or sec_service.id
+ context["sec_service_display_name"] = sec_service_display_name
+ context["page_title"] = _("Security Service Details: "
+ "%(service_display_name)s") % \
+ {'service_display_name': sec_service_display_name}
+ return context
+
+ @memoized.memoized_method
+ def get_data(self):
+ try:
+ sec_service_id = self.kwargs['sec_service_id']
+ sec_service = manila.security_service_get(
+ self.request, sec_service_id)
+ sec_service.type = utils.get_nice_security_service_type(
+ sec_service)
+ except Exception:
+ message = _("Unable to retrieve security service "
+ "'%s' details.") % sec_service_id
+ exceptions.handle(
+ self.request, message, redirect=self.redirect_url)
+ return sec_service
+
+ def get_tabs(self, request, *args, **kwargs):
+ sec_service = self.get_data()
+ return self.tab_group_class(request, sec_service=sec_service, **kwargs)
diff --git a/pool/shard003/Python/0028730_word_accuracy_metrics.py b/pool/shard003/Python/0028730_word_accuracy_metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..aab33803d93076210e2fc2beb5d7550a1c5a9233
--- /dev/null
+++ b/pool/shard003/Python/0028730_word_accuracy_metrics.py
@@ -0,0 +1,226 @@
+# -*- coding: utf-8 -*-
+"""
+Test accuracy of different word-level lookup schemes.
+Uses annotated data from the Digital Corpus of Sanskrit
+database to evaluate how many words are recognized by
+each of the lexical lookup schemes. Also checks if the
+annotated root of the word in the DCS matches the stems
+returned by the lexical lookup schemes.
+
+Saves a log of which words are not correctly recognized for
+further analysis.
+
+Current output should look similar to:
+```
+--------------------------------------------------
+Metrics for inria
+--------------------------------------------------
+Recognized 1438669 / 1932518 words, accuracy = 74.45%
+Correct root for 1181208 / 1438669 recognized words, accuracy = 82.10%
+==================================================
+--------------------------------------------------
+Metrics for sanskrit_data
+--------------------------------------------------
+Recognized 1670698 / 1932518 words, accuracy = 86.45%
+Correct root for 1375194 / 1670698 recognized words, accuracy = 82.31%
+==================================================
+--------------------------------------------------
+Metrics for combined
+--------------------------------------------------
+Recognized 1692948 / 1932518 words, accuracy = 87.60%
+Correct root for 1429996 / 1692948 recognized words, accuracy = 84.47%
+==================================================
+```
+
+### Dependencies
+
+Depends on dcs_wrapper python package for the data and openpyxl
+for logging some results. All dependencies can be installed using
+```pip install dcs_wrapper openpyxl progressbar2```
+
+### TODO:
+- Compute precision metrics as well
+
+@author: alvarna
+"""
+
+from __future__ import print_function, division
+import os
+import time
+import logging
+import itertools
+import argparse
+import progressbar
+from openpyxl import Workbook
+from dcs_wrapper import DCS
+from dcs_wrapper import DCSTagMapper
+from sanskrit_parser.util.lexical_lookup_factory import LexicalLookupFactory
+from sanskrit_parser.base.sanskrit_base import SanskritObject, IAST
+from joblib import Parallel, delayed
+
+
+logger = logging.getLogger(__name__)
+
+
+class WordLevelMetrics(object):
+ ''' Compute word level metrics for a lexical lookup'''
+
+ def __init__(self, lookup):
+ self.name = lookup
+ self.lookup = LexicalLookupFactory.create(lookup)
+ self.count = 0
+ self.recognized = 0
+ self.correct_root = 0
+
+ def update(self, word, ref_root, ref_tags):
+ '''Update the metrics using the given word and tag.
+ The input word is expected to be in SLP1'''
+ valid = self.lookup.valid(word)
+ if valid:
+ self.recognized += 1
+ tag_list = self.lookup.get_tags(word)
+ correct_root = False
+ for (stem, tag_set) in tag_list:
+ if(stem.split("#")[0]) == ref_root:
+ correct_root = True
+ break
+ if correct_root:
+ self.correct_root += 1
+ else:
+ logger.info("%s: Incorrect root for %s (ref = %s). Got %s",
+ self.name, word, ref_root, tag_list)
+ self.count += 1
+ return valid
+
+ def metrics(self):
+ return self.count, self.recognized, self.correct_root
+
+
+def print_stats(lookup_scheme, stats):
+ print("-"*50)
+ print("Metrics for", lookup_scheme)
+ print("-"*50)
+ print("Recognized %d / %d words, accuracy = %.2f%%" %
+ (stats['recognized'], stats['count'],
+ percentage(stats['recognized'], stats['count']))
+ )
+ print("Correct root for %d / %d recognized words, accuracy = %.2f%%" %
+ (stats['correct_root'], stats['recognized'],
+ percentage(stats['correct_root'], stats['recognized']))
+ )
+ print("="*50)
+
+
+def percentage(a, b):
+ return (a * 100.0 / b)
+
+
+def process(sentences, tag_mapper, ws):
+ inria_metrics = WordLevelMetrics("inria")
+ sdata_metrics = WordLevelMetrics("sanskrit_data")
+ comb_metrics = WordLevelMetrics("combined")
+
+ stats = {'inria': (0, 0, 0), 'sdata': (0, 0, 0), 'combo': (0, 0, 0)}
+ missing = []
+ for sent in sentences:
+ if sent is None:
+ continue
+ text_obj = SanskritObject(sent.text, encoding=IAST,
+ strict_io=False)
+ words = text_obj.canonical().strip().split(" ")
+ if len(words) != len(sent.dcsAnalysisDecomposition):
+ continue
+ for w, analysis in zip(words, sent.dcsAnalysisDecomposition):
+ if len(analysis) != 1:
+ continue
+ word_analysis = analysis[0]
+ if word_analysis.dcsGrammarHint == []:
+ continue
+ word_slp = SanskritObject(w, encoding=IAST,
+ strict_io=False).canonical()
+ tags = tag_mapper(word_analysis.dcsGrammarHint)
+ root = SanskritObject(word_analysis.root,
+ encoding=IAST,
+ strict_io=False).canonical()
+ i_valid = inria_metrics.update(word_slp, root, tags)
+ s_valid = sdata_metrics.update(word_slp, root, tags)
+ comb_metrics.update(word_slp, root, tags)
+ if not i_valid or not s_valid:
+ missing.append([word_slp, word_analysis.root,
+ word_analysis.dcsGrammarHint,
+ i_valid, s_valid,
+ not i_valid and not s_valid,
+ i_valid and not s_valid,
+ not i_valid and s_valid
+ ])
+
+ stats['inria'] = inria_metrics.metrics()
+ stats['sdata'] = sdata_metrics.metrics()
+ stats['combo'] = comb_metrics.metrics()
+ stats['missing'] = missing
+ return stats
+
+
+def main(count=None, jobs=None):
+ tag_mapper = DCSTagMapper().map_tag
+
+ wb = Workbook()
+ ws = wb.active
+ ws.append(["Word", "Root", "DCS Tag", "Inria", "Sanskrit Data",
+ "Both missed", "Inria only", "Sanskrit only"])
+
+ with DCS() as dcs:
+ sentences = itertools.islice(dcs.iter_sentences(), count)
+
+ def chunk(n, iterable, fill=None):
+ return itertools.zip_longest(*[iter(iterable)]*n, fillvalue=fill)
+
+ # Number of parallel jobs, default to use all processors
+ job_count = -1 if jobs is None else jobs
+ chunk_size = 10000 if count is None else int(count/os.cpu_count())
+ bar = progressbar.ProgressBar(max_value=jobs)
+ backend = 'sequential' if job_count == 1 else 'multiprocessing'
+
+ r = Parallel(n_jobs=job_count, backend=backend)(
+ delayed(process)(sent, tag_mapper, ws)
+ for sent in bar(chunk(chunk_size, sentences)))
+ inria = {'count': 0, 'recognized': 0, 'correct_root': 0, 'missing': []}
+ sdata = {'count': 0, 'recognized': 0, 'correct_root': 0, 'missing': []}
+ combo = {'count': 0, 'recognized': 0, 'correct_root': 0, 'missing': []}
+
+ def total(result, key, stat):
+ stat['count'] += result[key][0]
+ stat['recognized'] += result[key][1]
+ stat['correct_root'] += result[key][2]
+
+ for v in r:
+ total(v, 'inria', inria)
+ total(v, 'sdata', sdata)
+ total(v, 'combo', combo)
+ for x in v['missing']:
+ ws.append(x)
+
+ wb.save("lookup_results.xlsx")
+ print_stats('inria', inria)
+ print_stats('sanskrit_data', sdata)
+ print_stats('combined', combo)
+
+
+if __name__ == "__main__":
+ logging.basicConfig(filename="accuracy_metrics.log", filemode="w",
+ level=logging.INFO)
+ start = time.time()
+
+ parser = argparse.ArgumentParser("Collect word level accuracy metrics")
+ parser.add_argument('--count', type=int, default=None,
+ help="Limit to no. of sentences from DCS")
+ parser.add_argument('--jobs', type=int, default=None,
+ help="Number of parallel jobs")
+
+ args = parser.parse_args()
+
+ main(args.count, args.jobs)
+
+ logging.shutdown()
+ end = time.time()
+ print("Took %0.2fs" % (end - start))
diff --git a/pool/shard003/Python/0028733_tags.py b/pool/shard003/Python/0028733_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a62261d5013b5f811882571eeb3bb10ec6432ce
--- /dev/null
+++ b/pool/shard003/Python/0028733_tags.py
@@ -0,0 +1,54 @@
+from __future__ import unicode_literals
+
+from moto.core.responses import BaseResponse
+from moto.ec2.models import validate_resource_ids
+from moto.ec2.utils import sequence_from_querystring, tags_from_query_string, filters_from_querystring
+
+
+class TagResponse(BaseResponse):
+
+ def create_tags(self):
+ resource_ids = sequence_from_querystring('ResourceId', self.querystring)
+ validate_resource_ids(resource_ids)
+ self.ec2_backend.do_resources_exist(resource_ids)
+ tags = tags_from_query_string(self.querystring)
+ self.ec2_backend.create_tags(resource_ids, tags)
+ return CREATE_RESPONSE
+
+ def delete_tags(self):
+ resource_ids = sequence_from_querystring('ResourceId', self.querystring)
+ validate_resource_ids(resource_ids)
+ tags = tags_from_query_string(self.querystring)
+ self.ec2_backend.delete_tags(resource_ids, tags)
+ return DELETE_RESPONSE
+
+ def describe_tags(self):
+ filters = filters_from_querystring(querystring_dict=self.querystring)
+ tags = self.ec2_backend.describe_tags(filters=filters)
+ template = self.response_template(DESCRIBE_RESPONSE)
+ return template.render(tags=tags)
+
+
+CREATE_RESPONSE = """
+ 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
+ true
+"""
+
+DELETE_RESPONSE = """
+ 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
+ true
+"""
+
+DESCRIBE_RESPONSE = """
+ 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE
+
+ {% for tag in tags %}
+ -
+ {{ tag.resource_id }}
+ {{ tag.resource_type }}
+ {{ tag.key }}
+ {{ tag.value }}
+
+ {% endfor %}
+
+"""
diff --git a/pool/shard003/Python/0028735_searchable_titles.py b/pool/shard003/Python/0028735_searchable_titles.py
new file mode 100644
index 0000000000000000000000000000000000000000..a10ab3f225a7ae5a59bdb3026394a8bc150e754f
--- /dev/null
+++ b/pool/shard003/Python/0028735_searchable_titles.py
@@ -0,0 +1,52 @@
+# This file is part of Indico.
+# Copyright (C) 2002 - 2021 CERN
+#
+# Indico is free software; you can redistribute it and/or
+# modify it under the terms of the MIT License; see the
+# LICENSE file for more details.
+
+from sqlalchemy.ext.declarative import declared_attr
+
+from indico.core.db import db
+from indico.core.db.sqlalchemy.util.queries import escape_like, preprocess_ts_string
+from indico.util.decorators import strict_classproperty
+
+
+class SearchableTitleMixin:
+ """Mixin to add a fulltext-searchable title column."""
+
+ #: Whether the title column may not be empty
+ title_required = True
+
+ @strict_classproperty
+ @classmethod
+ def __auto_table_args(cls):
+ args = [
+ db.Index(f'ix_{cls.__tablename__}_title_fts', db.func.to_tsvector('simple', cls.title),
+ postgresql_using='gin')
+ ]
+ if cls.title_required:
+ args.append(db.CheckConstraint("title != ''", 'valid_title'))
+ return tuple(args)
+
+ @declared_attr
+ def title(cls):
+ return db.Column(
+ db.String,
+ nullable=False
+ )
+
+ @classmethod
+ def title_matches(cls, search_string, exact=False):
+ """Check whether the title matches a search string.
+
+ To be used in a SQLAlchemy `filter` call.
+
+ :param search_string: A string to search for
+ :param exact: Whether to search for the exact string
+ """
+ crit = db.func.to_tsvector('simple', cls.title).match(preprocess_ts_string(search_string),
+ postgresql_regconfig='simple')
+ if exact:
+ crit = crit & cls.title.ilike(f'%{escape_like(search_string)}%')
+ return crit
diff --git a/pool/shard003/Python/0028739_test_simulate_data.py b/pool/shard003/Python/0028739_test_simulate_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c238910ea6f28b6ac62291cfa86bf99c95777c21
--- /dev/null
+++ b/pool/shard003/Python/0028739_test_simulate_data.py
@@ -0,0 +1,21 @@
+import numpy as np
+from click.testing import CliRunner
+
+from fastimgproto.scripts.simulate_data import cli as sim_cli
+
+
+def test_simulate_data():
+ runner = CliRunner()
+ with runner.isolated_filesystem():
+ output_filename = 'simdata.npz'
+
+ result = runner.invoke(sim_cli,
+ [output_filename,
+ '--nstep','5'
+ ])
+ assert result.exit_code == 0
+ with open(output_filename, 'rb') as f:
+ output_data = np.load(f)
+ expected_keys = ('uvw_lambda', 'skymodel', 'vis')
+ for k in expected_keys:
+ assert k in output_data
diff --git a/pool/shard003/Python/0028741_question.py b/pool/shard003/Python/0028741_question.py
new file mode 100644
index 0000000000000000000000000000000000000000..3405f3f547d5d5433b05d18f7308c4abe8efa9a0
--- /dev/null
+++ b/pool/shard003/Python/0028741_question.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+"""
+__author__ = 'Zhipeng Du'
+__mtime__ = '16/9/1' '18:27'
+"""
+from . import front
+from flask import render_template, redirect, url_for
+from ..forms import QuestionForm
+from app import ding
+from flask_login import login_required, current_user
+from ..models import db, Category, Config, Issue
+
+
+@front.route('/question/add', methods=['GET', 'POST'])
+@login_required
+def add_question():
+ old_title = Config.query.filter_by(key='title').first()
+ old_subtitle = Config.query.filter_by(key='subtitle').first()
+ web_title = old_title.value if old_title else ''
+ web_subtitle = old_subtitle.value if old_subtitle else ''
+ form = QuestionForm()
+ categories = Category.query.filter_by(parents_id=3).all()
+ form.category.choices = [(category.id, category.name) for category in categories]
+ form.category.choices.insert(0, (0, '请选择产品线'))
+ if form.validate_on_submit():
+ new_issue = Issue(title=form.title.data, details=form.details.data, creator_id=current_user.id,
+ extend=str({'class_id': 1, 'category_id': form.category.data}))
+ db.session.add(new_issue)
+ db.session.commit()
+ url = 'http://chanpin.xinlonghang.cn/back/question/edit?id=' + str(new_issue.id) + '&type=html5'
+ print(url)
+ this_category = Category.query.get(form.category.data)
+ data = {'create_customer': new_issue.creator.name, 'category': this_category.name,
+ 'num': new_issue.id}
+ ding.msg(category=1, url=url, data=data)
+ return redirect(url_for('.commit_success'))
+ return render_template('front/questionNew.html', form=form, web_title=web_title, web_subtitle=web_subtitle)
+
+
+
diff --git a/pool/shard003/Python/0028744_models.py b/pool/shard003/Python/0028744_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..64b6cd7ff54c27a60ef52c1036b75f41a813798a
--- /dev/null
+++ b/pool/shard003/Python/0028744_models.py
@@ -0,0 +1,126 @@
+# coding: utf-8
+
+# Importaciones Django
+from django.contrib.auth.models import Group, Permission
+from django.db.models.signals import post_save
+from django.core.urlresolvers import reverse
+from django.dispatch import receiver
+from django.db import models
+
+# Importaciones Propias
+from finance.models import CustomUser
+
+
+
+class AlumnoColegio(CustomUser):
+ division = models.ForeignKey('Division', related_name="alumnos")
+
+ def get_absolute_url(self):
+ return reverse('alumnos')
+
+
+class Profesor(CustomUser):
+ materias = models.ManyToManyField('MateriaDivision')
+
+ def get_absolute_url(self):
+ return reverse('profesores')
+
+ def get_divisiones(self):
+ divisiones = []
+ for materia in self.materias.all():
+ divisiones.append(materia.division)
+ return divisiones
+
+ def get_alumnos(self):
+ div_prof = self.profesor.get_divisiones()
+ return AlumnoColegio.objects.filter(division__in=div_prof)
+
+ def get_nombre_materias(self):
+ return [materia.materia.nombre for materia in self.materias.all()]
+
+
+class Materia(models.Model):
+ nombre = models.CharField(max_length=50)
+
+ def __unicode__(self):
+ return unicode(self.nombre)
+
+ def get_absolute_url(self):
+ return reverse('materias')
+
+
+class MateriaDivision(models.Model):
+ materia = models.ForeignKey('Materia')
+ division = models.ForeignKey('Division')
+ horario = models.TimeField()
+
+ def __unicode__(self):
+ return u'%s - %s - %s' % (self.materia, self.division, self.horario)
+
+ def get_absolute_url(self):
+ return reverse('materiasdivisiones')
+
+
+class Division(models.Model):
+ nivel = models.CharField(max_length=5)
+ materias = models.ManyToManyField('Materia', through='MateriaDivision')
+
+ def __unicode__(self):
+ return unicode(self.nivel)
+
+ def get_absolute_url(self):
+ return reverse('divisiones')
+
+
+class Asistencia(models.Model):
+ alumno = models.ForeignKey('AlumnoColegio')
+ fecha = models.DateField()
+ estado = models.ForeignKey('EstadoAsistencia')
+
+ def __unicode__(self):
+ return unicode(self.alumno) + " " + unicode(self.fecha) + " " + unicode(self.estado)
+
+
+class EstadoAsistencia(models.Model):
+ nombre = models.CharField(max_length=50, unique=True)
+ codigo = models.CharField(max_length=5, unique=True)
+
+ def __unicode__(self):
+ return unicode(self.nombre)
+
+
+class Calificacion(models.Model):
+ alumno = models.ForeignKey('AlumnoColegio', related_name='calificaciones')
+ materia = models.ForeignKey('Materia')
+ nota = models.DecimalField(max_digits=4,decimal_places=2,default='01.00')
+ nota2 = models.CharField(max_length=10, null=True, blank=True)
+ observacion = models.CharField(max_length=50, null=True, blank=True)
+ fecha = models.DateTimeField(auto_now_add=True)
+
+ def __unicode__(self):
+ return u'%s - %s - %s' % (self.alumno, self.materia, self.nota)
+
+ def get_absolute_url(self):
+ return reverse('calificaciones')
+
+
+
+
+
+
+
+
+
+
+
+
+@receiver(post_save, sender=Profesor)
+def permisos_profesores(sender, **kwargs):
+ try:
+ if kwargs.get('created'):
+ grupo = Group.objects.get(name='Profesores')
+ profesor = kwargs.get('instance')
+ profesor.groups.add(grupo)
+ except Exception, e:
+ print e
+
diff --git a/pool/shard003/Python/0028748_RecordLevelTest.py b/pool/shard003/Python/0028748_RecordLevelTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..44bbf461795fc0b0f56e5fbc18381dc35050b6fb
--- /dev/null
+++ b/pool/shard003/Python/0028748_RecordLevelTest.py
@@ -0,0 +1,19 @@
+import alsaaudio
+import numpy
+import analyse
+
+card = 'sysdefault:CARD=AK5370'
+f = open('out.wav', 'wb')
+inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, card)
+
+inp.setchannels(1)
+inp.setrate(8000)
+inp.setperiodsize(160)
+inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
+
+while True:
+ length, data = inp.read()
+
+ samps = numpy.fromstring(data, dtype=numpy.int16, count=length)
+ # Show the volume and pitch
+ print analyse.loudness(samps)
diff --git a/pool/shard003/Python/0028761_test_captcha.py b/pool/shard003/Python/0028761_test_captcha.py
new file mode 100644
index 0000000000000000000000000000000000000000..dde01923cfd779cb1b8256b39067b113576e836f
--- /dev/null
+++ b/pool/shard003/Python/0028761_test_captcha.py
@@ -0,0 +1,15 @@
+import pytest
+import sys
+import os
+sys.path.insert(0, os.path.dirname(__file__)+"/../krobot/")
+
+from captcha import CaptchaReader
+
+class TestcaptchaReader:
+
+ def test_read(self):
+
+ capReader = CaptchaReader(os.path.dirname(__file__) + "/../krobot/Dico")
+ captcha_str = capReader.read("tests/material/capt-test.png")
+
+ assert captcha_str == "7Ks6W"
diff --git a/pool/shard003/Python/0028762_0010_auto_20170127_1521.py b/pool/shard003/Python/0028762_0010_auto_20170127_1521.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd20c5fb66634aacdf205d8a0418edb713e375fb
--- /dev/null
+++ b/pool/shard003/Python/0028762_0010_auto_20170127_1521.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10 on 2017-01-27 15:21
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('projects', '0009_remove_project_manager_detail'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name='interventiontype',
+ name='intervention',
+ ),
+ migrations.RemoveField(
+ model_name='interventiontype',
+ name='project',
+ ),
+ migrations.RemoveField(
+ model_name='project',
+ name='interventions',
+ ),
+ migrations.DeleteModel(
+ name='InterventionType',
+ ),
+ ]
diff --git a/pool/shard003/Python/0028763_test_missing_object_value.py b/pool/shard003/Python/0028763_test_missing_object_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..b289e990aa14eb210a2666d27338a023c21c7217
--- /dev/null
+++ b/pool/shard003/Python/0028763_test_missing_object_value.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
+#
+# This file is part of Alignak.
+#
+# Alignak is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Alignak is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Alignak. If not, see .
+#
+#
+# This file incorporates work covered by the following copyright and
+# permission notice:
+#
+# Copyright (C) 2009-2014:
+# Jean Gabes, naparuba@gmail.com
+# Hartmut Goebel, h.goebel@goebel-consult.de
+# Grégory Starck, g.starck@gmail.com
+# Sebastien Coavoux, s.coavoux@free.fr
+
+# This file is part of Shinken.
+#
+# Shinken is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Shinken is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Shinken. If not, see .
+
+#
+# This file is used to test reading and processing of config files
+#
+
+from alignak_test import *
+
+
+class TestMissingObjectValue(AlignakTest):
+
+ def setUp(self):
+ self.setup_with_file(['etc/alignak_missing_object_value.cfg'])
+
+ def test_missing_object_value(self):
+ #
+ # Config is not correct because of a wrong relative path
+ # in the main config file
+ #
+
+ print "Get the hosts and services"
+ now = time.time()
+ host = self.conf.hosts.find_by_name("test_host_0")
+ host.checks_in_progress = []
+ host.act_depend_of = [] # ignore the router
+ router = self.conf.hosts.find_by_name("test_router_0")
+ router.checks_in_progress = []
+ router.act_depend_of = [] # ignore the router
+ svc = self.conf.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_00")
+ svc.checks_in_progress = []
+ svc.act_depend_of = [] # no hostchecks on critical checkresults
+ # The service is mising a value for active_check_enabled, it's an error.
+ self.assertEqual(False, svc.is_correct())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard003/Python/0028777_column_flip.py b/pool/shard003/Python/0028777_column_flip.py
new file mode 100644
index 0000000000000000000000000000000000000000..36467f8efaf89d7845764a63d818e7973735f2f2
--- /dev/null
+++ b/pool/shard003/Python/0028777_column_flip.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python
+
+# Gimp-Python - allows the writing of Gimp plugins in Python.
+# Copyright (C) 2015 William Bell
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+from gimpfu import *
+import time
+from array import array
+
+gettext.install("gimp20-python", gimp.locale_directory, unicode=True)
+
+def column_flip(img, layer, col_number):
+ gimp.progress_init("Processing" + layer.name + "...")
+ pdb.gimp_undo_push_group_start(img)
+
+ layername = "flipped " + layer.name
+
+ # Create the new layer:
+ srcWidth, srcHeight = layer.width, layer.height
+ col_width = int(srcWidth / col_number)
+ col_mid = int(col_width / 2)
+
+ destDrawable = gimp.Layer(img, layername, srcWidth, srcHeight,
+ layer.type, layer.opacity, layer.mode)
+ img.add_layer(destDrawable, 0)
+ xoff, yoff = layer.offsets
+
+ destDrawable.translate(xoff, yoff)
+
+ srcRgn = layer.get_pixel_rgn(0, 0, srcWidth, srcHeight, False, False)
+ src_pixels = array("B", srcRgn[0:srcWidth, 0:srcHeight])
+
+ dstRgn = destDrawable.get_pixel_rgn(0, 0, srcWidth, srcHeight, True, True)
+ p_size = len(srcRgn[0,0])
+ dest_pixels = array("B", [0] * (srcWidth * srcHeight * p_size))
+
+ # Finally, loop over the region:
+ for c in xrange(0, int(col_number)) :
+ for x in xrange(0, col_mid) :
+ for y in xrange(0, srcHeight) :
+ val1_pos = (c * col_width + x + srcWidth * y) * p_size
+ val2_pos = (c * col_width + col_width - x - 1 + srcWidth * y) * p_size
+
+ val1 = src_pixels[val1_pos: val1_pos + p_size]
+ val2 = src_pixels[val2_pos: val2_pos + p_size]
+
+ dest_pixels[val1_pos : val1_pos + p_size] = val2
+ dest_pixels[val2_pos : val2_pos + p_size] = val1
+
+ progress = float(x)/layer.width
+ if (int(progress * 100) % 200 == 0) :
+ gimp.progress_update(progress)
+
+ # Copy the whole array back to the pixel region:
+ dstRgn[0:srcWidth, 0:srcHeight] = dest_pixels.tostring()
+
+ destDrawable.flush()
+ destDrawable.merge_shadow(True)
+ destDrawable.update(0, 0, srcWidth,srcHeight)
+
+ # Remove the old layer
+ #img.remove_layer(layer)
+ layer.visible = False
+
+ pdb.gimp_selection_none(img)
+ pdb.gimp_image_undo_group_end(img)
+
+
+register(
+ "python-fu-column_flip",
+ N_("Divides an image into columns and flips them."),
+ "Adds a new layer to the image",
+ "William Bell",
+ "William Bell",
+ "2015",
+ N_("Flip _Columns..."),
+ "RGB*",
+ [
+ (PF_IMAGE, "image", "Input image", None),
+ (PF_DRAWABLE, "drawable", "Input drawable", None),
+ (PF_SPINNER, "col_number", _("Number of Columns:"), 5, (1, 256, 1)),
+ ],
+ [],
+ column_flip,
+ menu="/Image/Transform",
+ domain=("gimp20-python", gimp.locale_directory)
+ )
+
+main()
diff --git a/pool/shard003/Python/0028780_test_blas2_real.py b/pool/shard003/Python/0028780_test_blas2_real.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bb6a521687ca67a7bb57e914643ecc35a10e497
--- /dev/null
+++ b/pool/shard003/Python/0028780_test_blas2_real.py
@@ -0,0 +1,134 @@
+from itertools import product
+
+import numpy as np
+from numpy.random import randn
+from numpy.testing import (
+ assert_equal, assert_array_equal, assert_array_almost_equal_nulp,
+ assert_almost_equal, assert_allclose)
+
+from snackpack import blas
+from snackpack.util import (
+ FloatArray, matrix_generator, square_matrix_generator, indexed_vector,
+ assert_nonindexed_unchanged)
+from snackpack.blas import SP_TRANS
+
+
+vec_inc = (-3, -1, 1, 3)
+
+
+def test_sgemv_no_trans():
+ """Test sp_blas_sgemv with no transpose"""
+ alpha = randn(3)
+ alpha[0] = 0
+ beta = randn(3)
+ beta[0] = 0
+ for a, b in product(alpha, beta):
+ for lda, rows, cols, A in matrix_generator():
+ x = FloatArray(randn(cols))
+ y = FloatArray(randn(rows))
+
+ A_slice = np.reshape(A, (lda, cols), 'F')[:rows, :]
+ x0 = x.copy()
+ y0 = y.copy()
+
+ expected = a * A_slice.dot(x) + b * y
+ blas.sgemv(False, rows, cols, a, A, lda, x, 1, b, y, 1)
+
+ assert_array_equal(x0, x)
+ assert_allclose(expected, expected, 1e-5, 5e-5)
+
+ for lda, rows, cols, A in matrix_generator():
+ for inc_x, inc_y in product(vec_inc, vec_inc):
+ a = randn()
+ b = randn()
+
+ len_x = cols * abs(inc_x)
+ len_y = rows * abs(inc_y)
+
+ x = FloatArray(randn(len_x))
+ y = FloatArray(randn(len_y))
+
+ x_idx = indexed_vector(x, cols, inc_x)
+ y_idx = indexed_vector(y, rows, inc_y)
+
+ A_slice = np.reshape(A, (lda, cols), 'F')[:rows, :]
+ x0 = x.copy()
+ y0 = y.copy()
+
+ expected = a * A_slice.dot(x_idx) + b * y_idx
+ blas.sgemv(False, rows, cols, a, A, lda, x, inc_x, b, y, inc_y)
+
+ assert_array_equal(x0, x)
+ assert_allclose(expected, y_idx, 1e-5, 5e-5)
+ assert_nonindexed_unchanged(y0, y, rows, inc_y)
+
+
+def test_sgemv_with_trans():
+ """Test sp_blas_sgemv with transpose"""
+ alpha = randn(4)
+ alpha[0] = 0
+ beta = randn(4)
+ beta[0] = 0
+ for a, b in product(alpha, beta):
+ for lda, rows, cols, A in matrix_generator():
+ x = FloatArray(randn(rows))
+ y = FloatArray(randn(cols))
+
+ A_sliceT = np.reshape(A, (lda, cols), 'F')[:rows, :].T
+ x0 = x.copy()
+ y0 = y.copy()
+
+ expected = a * A_sliceT.dot(x) + b * y
+ blas.sgemv(True, rows, cols, a, A, lda, x, 1, b, y, 1)
+
+ assert_array_equal(x0, x)
+ assert_allclose(expected, y, 1e-5, 5e-5)
+
+ for lda, rows, cols, A in matrix_generator():
+ for inc_x, inc_y in product(vec_inc, vec_inc):
+ a = randn()
+ b = randn()
+
+ x = FloatArray(randn(rows * abs(inc_x)))
+ y = FloatArray(randn(cols * abs(inc_y)))
+
+ x_idx = indexed_vector(x, rows, inc_x)
+ y_idx = indexed_vector(y, cols, inc_y)
+
+ A_slice = np.reshape(A, (lda, cols), 'F')[:rows, :].T
+ x0 = x.copy()
+ y0 = y.copy()
+
+ expected = a * A_slice.dot(x_idx) + b * y_idx
+ blas.sgemv(True, rows, cols, a, A, lda, x, inc_x, b, y, inc_y)
+
+ assert_array_equal(x0, x)
+ assert_allclose(expected, y_idx, 1e-5, 5e-5)
+ assert_nonindexed_unchanged(y0, y, cols, inc_y)
+
+
+def test_strmv_no_trans():
+ """Test sp_blas_strmv with no transpose"""
+ for lda, n, A0 in square_matrix_generator():
+ for inc_x in vec_inc:
+ A0_slice = np.reshape(A0, (lda, n), 'F')
+ x = FloatArray(randn(n * abs(inc_x)))
+ x0 = x.copy()
+ x_idx = indexed_vector(x, n, inc_x)
+
+ # Upper triangular, no unit diagonal
+ A = np.triu(A0_slice)
+ A_f = A.T.flatten()
+ expected = A.dot(x_idx)[:n]
+ blas.strmv(True, False, False, n, A_f, lda, x, inc_x)
+ assert_allclose(expected, x_idx, 1e-5, 5e-5)
+
+ # Upper triangular, unit diagonal
+ A = np.triu(A0_slice)
+ np.fill_diagonal(A, 1.0)
+ A_f = A.T.flatten()
+ x = x0.copy()
+ x_idx = indexed_vector(x, n, inc_x)
+ expected = A.dot(x_idx)[:n]
+ blas.strmv(True, False, True, n, A_f, lda, x, inc_x)
+ assert_allclose(expected, x_idx, 1e-5, 5e-5)
diff --git a/pool/shard003/Python/0028784_views.py b/pool/shard003/Python/0028784_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8c229139a50a893fd04f983d87a59ba485a1d24
--- /dev/null
+++ b/pool/shard003/Python/0028784_views.py
@@ -0,0 +1,26 @@
+from django.http import HttpResponse,HttpResponseRedirect
+from django.shortcuts import render, get_object_or_404
+from accounts.models import Employee, PhoneNo, Skill, HasSkill
+from django.core.urlresolvers import reverse
+from django.contrib.auth.hashers import make_password, check_password
+from accounts.utils import *
+from project.models import *
+from django.http import Http404
+import json as simplejson
+from notification.utils import *
+
+@login_required
+def main(request):
+ """Main listing, years and months; three years per page."""
+ # prev / next years
+ username = request.session.get('username')
+ emp = Employee.objects.get(username=username)
+ notifs =Notification.objects.filter(destEmp = emp).order_by('-notdate')
+ context ={}
+ print notifs
+ context['notifs'] = notifs
+ context['user'] = emp
+ return render(request,"notification/main.html", context)
+
+
+
diff --git a/pool/shard003/Python/0028785_test_inlinequeryresultphoto.py b/pool/shard003/Python/0028785_test_inlinequeryresultphoto.py
new file mode 100644
index 0000000000000000000000000000000000000000..14a7d8d6e8b50cec936337beb64be7353cd3c61f
--- /dev/null
+++ b/pool/shard003/Python/0028785_test_inlinequeryresultphoto.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python
+#
+# A library that provides a Python interface to the Telegram Bot API
+# Copyright (C) 2015-2017
+# Leandro Toledo de Souza
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see [http://www.gnu.org/licenses/].
+"""This module contains an object that represents Tests for Telegram
+InlineQueryResultPhoto"""
+
+import sys
+import unittest
+
+sys.path.append('.')
+
+import telegram
+from tests.base import BaseTest
+
+
+class InlineQueryResultPhotoTest(BaseTest, unittest.TestCase):
+ """This object represents Tests for Telegram InlineQueryResultPhoto."""
+
+ def setUp(self):
+ self._id = 'id'
+ self.type = 'photo'
+ self.photo_url = 'photo url'
+ self.photo_width = 10
+ self.photo_height = 15
+ self.thumb_url = 'thumb url'
+ self.title = 'title'
+ self.description = 'description'
+ self.caption = 'caption'
+ self.input_message_content = telegram.InputTextMessageContent('input_message_content')
+ self.reply_markup = telegram.InlineKeyboardMarkup(
+ [[telegram.InlineKeyboardButton('reply_markup')]])
+
+ self.json_dict = {
+ 'type': self.type,
+ 'id': self._id,
+ 'photo_url': self.photo_url,
+ 'photo_width': self.photo_width,
+ 'photo_height': self.photo_height,
+ 'thumb_url': self.thumb_url,
+ 'title': self.title,
+ 'description': self.description,
+ 'caption': self.caption,
+ 'input_message_content': self.input_message_content.to_dict(),
+ 'reply_markup': self.reply_markup.to_dict(),
+ }
+
+ def test_photo_de_json(self):
+ photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot)
+
+ self.assertEqual(photo.type, self.type)
+ self.assertEqual(photo.id, self._id)
+ self.assertEqual(photo.photo_url, self.photo_url)
+ self.assertEqual(photo.photo_width, self.photo_width)
+ self.assertEqual(photo.photo_height, self.photo_height)
+ self.assertEqual(photo.thumb_url, self.thumb_url)
+ self.assertEqual(photo.title, self.title)
+ self.assertEqual(photo.description, self.description)
+ self.assertEqual(photo.caption, self.caption)
+ self.assertDictEqual(photo.input_message_content.to_dict(),
+ self.input_message_content.to_dict())
+ self.assertDictEqual(photo.reply_markup.to_dict(), self.reply_markup.to_dict())
+
+ def test_photo_to_json(self):
+ photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot)
+
+ self.assertTrue(self.is_json(photo.to_json()))
+
+ def test_photo_to_dict(self):
+ photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot).to_dict()
+
+ self.assertTrue(self.is_dict(photo))
+ self.assertDictEqual(self.json_dict, photo)
+
+ def test_equality(self):
+ a = telegram.InlineQueryResultPhoto(self._id, self.photo_url, self.thumb_url)
+ b = telegram.InlineQueryResultPhoto(self._id, self.photo_url, self.thumb_url)
+ c = telegram.InlineQueryResultPhoto(self._id, "", self.thumb_url)
+ d = telegram.InlineQueryResultPhoto("", self.photo_url, self.thumb_url)
+ e = telegram.InlineQueryResultArticle(self._id, "", "")
+
+ self.assertEqual(a, b)
+ self.assertEqual(hash(a), hash(b))
+ self.assertIsNot(a, b)
+
+ self.assertEqual(a, c)
+ self.assertEqual(hash(a), hash(c))
+
+ self.assertNotEqual(a, d)
+ self.assertNotEqual(hash(a), hash(d))
+
+ self.assertNotEqual(a, e)
+ self.assertNotEqual(hash(a), hash(e))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard003/Python/0028790_check_format_precommit.py b/pool/shard003/Python/0028790_check_format_precommit.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d9108ff5443d4383b8c3f4f4f83584cffc1cf2
--- /dev/null
+++ b/pool/shard003/Python/0028790_check_format_precommit.py
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+
+import sys
+import subprocess
+
+code_prefixes = (".cpp", ".h", ".hpp", ".ipp")
+git = "git"
+clang_format = "clang-format"
+diff = "diff"
+
+#Check program exists
+def check_program(name):
+ try:
+ subprocess.check_output([name, "--version"])
+ except:
+ print("command {} not found\nExiting...".format(name))
+ sys.exit()
+
+#clang-format file and compare against existing
+def check_file(filename):
+ code = 0
+ try:
+ ps = subprocess.Popen((clang_format, "-style=file", file), stdout=subprocess.PIPE)
+ subprocess.check_output(("diff", "-u", file, "-"), stdin=ps.stdout)
+ ps.wait()
+ except subprocess.CalledProcessError as e:
+ print("File {} not formatted!".format(file))
+ print(e.output.decode(sys.stdout.encoding).strip())
+ print("-------------")
+ code = e.returncode
+ return code
+
+print("Performing pre-commit checks...")
+
+#check git and clang format exist
+check_program(git)
+check_program(clang_format)
+check_program(diff)
+
+#Check modified files matching the required prefix
+#ACMRTU filters Added (A), Copied (C), Modified (M), Renamed (R), Changed Extension (T), Unmerged (U)
+changed = subprocess.check_output("{} diff --name-only --diff-filter=ACMRTU --cached".format(git)).decode(sys.stdout.encoding).strip().split("\n")
+exit_code = 0
+for file in changed:
+ if file.endswith(code_prefixes):
+ exit_code = check_file(file)
+
+if exit_code:
+ print("-------------\nCommit failed. Please run clang-format on your code\n-------------")
+else:
+ print("Pre-commit checks passed")
+sys.exit(exit_code)
\ No newline at end of file
diff --git a/pool/shard003/Python/0028792_test_gaussfitter.py b/pool/shard003/Python/0028792_test_gaussfitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..953920105e3955383ef0361c96d8f34a2429fa14
--- /dev/null
+++ b/pool/shard003/Python/0028792_test_gaussfitter.py
@@ -0,0 +1,32 @@
+from __future__ import division,absolute_import
+import unittest
+import numpy as np
+import gaussfitter as gf
+
+class GaussfitCase(unittest.TestCase):
+ def test_simple_fit(self):
+ # fit a 2D gaussian function centered at (64, 64) with width 8
+ # inpars = [height,amplitude,center_x,center_y,width_x,width_y,rota]
+ inpars = [0, 1, 64, 64, 8, 8, 0]
+ in_data = gf.twodgaussian(inpars, shape=(128, 128))
+ fit = gf.gaussfit(in_data)
+ for inval, outval in zip(inpars, fit):
+ self.assertAlmostEqual(inval, outval)
+
+ def test_masked_fit(self):
+ inpars = [0, 1, 64, 64, 8, 8, 0]
+ in_data = gf.twodgaussian(inpars, shape=(128,128))
+ masked_data = np.ma.array(in_data)
+
+ # fit should be independent of masked data value
+ masked_data[64,64] = 1e6
+ masked_data[64,64] = np.ma.masked
+ fit1 = gf.gaussfit(masked_data)
+
+ masked_data[64,64] = 0
+ masked_data[64,64] = np.ma.masked
+ fit2 = gf.gaussfit(masked_data)
+
+ for v1, v2 in zip(fit1, fit2):
+ self.assertAlmostEqual(v1, v2)
+
diff --git a/pool/shard003/Python/0028800_non_player_castle.py b/pool/shard003/Python/0028800_non_player_castle.py
new file mode 100644
index 0000000000000000000000000000000000000000..55e332a9eba265399c82a2f4e17bb339b8ae1cf4
--- /dev/null
+++ b/pool/shard003/Python/0028800_non_player_castle.py
@@ -0,0 +1,84 @@
+from django.views.generic import View
+from django.shortcuts import render_to_response, RequestContext, HttpResponseRedirect
+from npc.forms import NonPlayerCastleForm
+from gge_proxy_manager.models import NonPlayerCastle
+from .mixins import NonPlayerCastleMixin
+
+
+class EditView(View, NonPlayerCastleMixin):
+ template_name = "npc/form.html"
+ form_class = NonPlayerCastleForm
+
+ def get_form(self, pk):
+ if pk:
+ npc = self.npc_or_404(pk=pk)
+ print npc
+ form = self.form_class(self.request.POST, instance=npc) \
+ if self.request.POST else self.form_class(instance=npc)
+ else:
+ form = self.form_class(self.request.POST) \
+ if self.request.POST else self.form_class()
+
+ return form
+
+ def get(self, request, pk=None):
+
+ form = self.get_form(pk)
+
+ return render_to_response(
+ self.template_name,
+ {
+ "form": form
+ },
+ context_instance=RequestContext(request)
+ )
+
+ def post(self, request, pk=None):
+
+ form = self.get_form(pk)
+
+ if form.is_valid():
+ form.save()
+
+ return HttpResponseRedirect(request.get_full_path())
+
+ return render_to_response(
+ self.template_name,
+ {
+ "form": form
+ },
+ context_instance=RequestContext(request)
+ )
+
+
+class DetailView(View, NonPlayerCastleMixin):
+ template_name = "npc/detail.html"
+
+ def get(self, request, type_slug, npc_slug):
+
+ npc = self.npc_or_404(slug=npc_slug, type__slug=type_slug)
+
+ return render_to_response(
+ self.template_name,
+ {
+ "npc": npc
+ },
+ context_instance=RequestContext(request)
+ )
+
+
+class FormationEditView(View):
+ template_name = "npc/formation/form.html"
+
+ def get(self, request, type_slug, npc_slug):
+
+ npc = self.npc_or_404(type__slug=type_slug, slug=npc_slug)
+ # npc = NonPlayerCastle.objects.get(slug=npc_slug, type__slug=type_slug)
+
+ return render_to_response(
+ self.template_name,
+ {
+ "npc": npc
+ },
+ context_instance=RequestContext(request)
+ )
diff --git a/pool/shard003/Python/0028805_test_core_fields.py b/pool/shard003/Python/0028805_test_core_fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..179a80f1e715987de37268fb56b944d1ccfcbd5b
--- /dev/null
+++ b/pool/shard003/Python/0028805_test_core_fields.py
@@ -0,0 +1,70 @@
+from . import *
+
+class TestEntities(ApiTestCase):
+
+ wants_scanner = wants_events = False
+
+ def setUp(self):
+ super(TestEntities, self).setUp()
+ sg = self.cached
+ self.SHOT = sg.create('Shot', {'code': 'entity_filter_test'})
+ #self.USER = sg.create('HumanUser', {'first_name': 'theuser'})
+ #self.SCRIPT = sg.create('ApiUser', {'code': 'thescript'})
+ #sg.create('Version', {'entity': self.SHOT, 'code': 'none', 'user': None})
+ #sg.create('Version', {'entity': self.SHOT, 'code': 'user', 'user': self.USER})
+ #sg.create('Version', {'entity': self.SHOT, 'code': 'script', 'user': self.SCRIPT})
+
+ def create_version(self, code, **kwargs):
+ kwargs.setdefault('entity', self.SHOT)
+ kwargs['code'] = code
+ return self.cached.create('Version', kwargs)
+
+ def assertFilter(self, filters, expected, *args):
+ filters = list(filters)
+ filters.append(('entity', 'is', self.SHOT))
+ SHOTs = self.cached.find('Version', filters, ['code'])
+ found = sorted(t['code'] for t in SHOTs)
+ expected = sorted(expected)
+ self.assertEqual(found, expected, *args)
+
+ def test_text_filters(self):
+
+ abc = self.create_version('abc')
+ apple = self.create_version('apple')
+ xyz = self.create_version('xyz')
+
+ self.assertFilter([
+ ('code', 'starts_with', 'a')
+ ], ['abc', 'apple'])
+ self.assertFilter([
+ ('code', 'ends_with', 'z')
+ ], ['xyz'])
+ self.assertFilter([
+ ('code', 'contains', 'b')
+ ], ['abc'])
+ self.assertFilter([
+ ('code', 'not_contains', 'a')
+ ], ['xyz'])
+ self.assertFilter([
+ ('code', 'not_contains', 'b')
+ ], ['apple', 'xyz'])
+
+ def test_between_filters(self):
+
+ X = [self.create_version(str(i)) for i in range(5)]
+
+ self.assertFilter([
+ ('id', 'between', X[0]['id'], X[4]['id'])
+ ], ['0', '1', '2', '3', '4'])
+
+ self.assertFilter([
+ ('id', 'not_between', X[0]['id'], X[4]['id'])
+ ], [])
+
+ self.assertFilter([
+ ('id', 'between', X[1]['id'], X[3]['id'])
+ ], ['1', '2', '3'])
+
+ self.assertFilter([
+ ('id', 'not_between', X[1]['id'], X[3]['id'])
+ ], ['0', '4'])
diff --git a/pool/shard003/Python/0028808_plot_tuning_data.py b/pool/shard003/Python/0028808_plot_tuning_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3d95d5f0e8bf4a67b5b9846c43e61944768fbc0
--- /dev/null
+++ b/pool/shard003/Python/0028808_plot_tuning_data.py
@@ -0,0 +1,67 @@
+#!/bin/python
+
+import matplotlib.pyplot as plt
+import sys
+import numpy as np
+import argparse
+
+repetitions = 100
+convert_to_megs = 1.0/1048576
+
+
+def parsecli():
+ parser = argparse.ArgumentParser(description="Visualize opencl_ciphers_improved_test tuning data")
+ parser.add_argument('-s','--save', help='Save the graph as an image', action="store_true")
+ parser.add_argument('-q','--quiet', help='Don\'t display/print anything (use with -s)', action="store_true")
+ parser.add_argument('file', metavar='filename', help='Text file with the tuning data', type=str, default="autotune.txt")
+ return parser.parse_args()
+
+
+def main(cli):
+ with open(cli.file, "r") as fp:
+ all_data = np.loadtxt(fp, delimiter="\t", skiprows=1)
+
+ block_sizes = all_data[:,0]
+ run_times = all_data[:,1]
+
+ throughput = (block_sizes * repetitions * convert_to_megs) / run_times
+ best_throughput = max(throughput)
+ best_blocksize = block_sizes[np.where(throughput == best_throughput)[0]]
+
+ if not cli.quiet:
+ print("Best throughput: %.3f MBs at blocksize: %uMB" % (best_throughput,int(best_blocksize * convert_to_megs)))
+
+ fig, ax = plt.subplots()
+ plt.plot(block_sizes * convert_to_megs, throughput)
+ plt.margins(y=0.2)
+ stride = 4
+ if max(block_sizes * convert_to_megs) > 100: stride = 40
+ elif max(block_sizes * convert_to_megs) > 1000: stride = 80
+ ax.set_xticks(np.arange(0, max(block_sizes * convert_to_megs), stride))
+ plt.xlabel('block size (MB)')
+ plt.ylabel('throughput (MB/s)')
+ plt.title('Throughput tuning')
+ plt.grid(True)
+
+ labelpos = "left"
+ if best_blocksize > max(block_sizes)/2:
+ labelpos = "right"
+
+ plt.annotate(
+ "Best: %.3fMB/s @ bs=%uMB" % (best_throughput, int(best_blocksize * convert_to_megs)),
+ xy=(best_blocksize * convert_to_megs, best_throughput), xytext=(-20, 20),
+ textcoords='offset points', ha=labelpos, va='bottom',
+ bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
+ arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
+
+ figure = plt.gcf()
+ if not cli.quiet:
+ plt.show()
+ if cli.save:
+ plt.draw()
+ figure.savefig(cli.file + ".png", dpi=150)
+
+
+if __name__ == "__main__":
+ cli = parsecli()
+ main(cli)
diff --git a/pool/shard003/Python/0028811_3cfce646762_init_revision.py b/pool/shard003/Python/0028811_3cfce646762_init_revision.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7d54aaf0b837e469f0e88db9078f65acb747155
--- /dev/null
+++ b/pool/shard003/Python/0028811_3cfce646762_init_revision.py
@@ -0,0 +1,66 @@
+"""init revision
+
+Revision ID: 3cfce646762
+Revises:
+Create Date: 2015-05-28 01:27:05.407436
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '3cfce646762'
+down_revision = None
+branch_labels = None
+depends_on = None
+
+from alembic import op
+import sqlalchemy as sa
+import geoalchemy2
+
+
+def upgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('organization',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('name', sa.String(length=120), nullable=True),
+ sa.Column('address', geoalchemy2.types.Geography(), nullable=True),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('user',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('fb_first_name', sa.String(length=120), nullable=True),
+ sa.Column('fb_last_name', sa.String(length=120), nullable=True),
+ sa.Column('fb_id', sa.String(length=40), nullable=True),
+ sa.Column('email', sa.String(length=120), nullable=True),
+ sa.Column('about_me', sa.String(length=120), nullable=True),
+ sa.Column('is_superuser', sa.Boolean(), nullable=True),
+ sa.PrimaryKeyConstraint('id'),
+ sa.UniqueConstraint('email'),
+ sa.UniqueConstraint('fb_id')
+ )
+ op.create_table('issue',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('reporter', sa.Integer(), nullable=True),
+ sa.Column('description', sa.String(length=120), nullable=True),
+ sa.Column('coordinates', geoalchemy2.types.Geography(), nullable=True),
+ sa.ForeignKeyConstraint(['reporter'], ['user.id'], ),
+ sa.PrimaryKeyConstraint('id')
+ )
+ op.create_table('comment',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('author_id', sa.Integer(), nullable=True),
+ sa.Column('issue_id', sa.Integer(), nullable=True),
+ sa.Column('message', sa.String(length=400), nullable=True),
+ sa.ForeignKeyConstraint(['author_id'], ['user.id'], ),
+ sa.ForeignKeyConstraint(['issue_id'], ['issue.id'], ),
+ sa.PrimaryKeyConstraint('id')
+ )
+ ### end Alembic commands ###
+
+
+def downgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.drop_table('comment')
+ op.drop_table('issue')
+ op.drop_table('user')
+ op.drop_table('organization')
+ ### end Alembic commands ###
diff --git a/pool/shard003/Python/0028812_customerRegister.py b/pool/shard003/Python/0028812_customerRegister.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1657d49652d653233aa4e87b01370d0a2949a58
--- /dev/null
+++ b/pool/shard003/Python/0028812_customerRegister.py
@@ -0,0 +1,39 @@
+from django.shortcuts import render, redirect
+from django.http import HttpResponseRedirect
+from django.contrib.auth import login, authenticate, logout
+from django.contrib.auth.models import User, Group
+from django.contrib.auth.decorators import login_required, user_passes_test, permission_required
+from django.contrib.auth.forms import UserCreationForm
+from customermanage.models import Coupon, Wallet
+from storemanage.models import Ticket
+# Create your views here.
+from usermanage import models
+from .validateForm import validateCustomerForm
+from .redirect_after_login import redirect_after_login
+
+def customerRegister(request):
+ if request.user.is_authenticated:
+ return redirect('index:index')
+ if request.method == 'GET':
+ return render(request,'usermanage/register-customer.html')
+
+ data = request.POST
+
+ error = validateCustomerForm(data)
+
+ if error:
+ return render(request,'usermanage/register-customer.html', {
+ 'error' : error
+ })
+
+ user = User.objects.create_user(username = data['username'], password = data['password'], email = data['email'])
+ g = Group.objects.get(name='customer')
+ g.user_set.add(user)
+ user.save()
+ g.save()
+ customerprofile = models.Customer(user = user, first_name = data['first_name'], last_name = data['last_name'])
+ customerprofile.save()
+ user = authenticate(request,username = data['username'], password=data['password'])
+ login(request, user)
+
+ return redirect_after_login(user)
diff --git a/pool/shard003/Python/0028814_create_sedml_axis_minmax_smaller.py b/pool/shard003/Python/0028814_create_sedml_axis_minmax_smaller.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8494241d2a5b44c2397f5594854d0e2c32fc7e
--- /dev/null
+++ b/pool/shard003/Python/0028814_create_sedml_axis_minmax_smaller.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Wed Mar 10 14:58:01 2021
+
+@author: Lucian
+"""
+
+import tellurium as te
+import phrasedml
+import libsedml
+import sys
+
+r = te.loada("""
+ model case_01
+ species S1=10, S2=5
+ S1 -> S2; S1*k
+ k = 0.3
+ end
+ """)
+
+SBML = r.getSBML()
+
+p_str = """
+ model0 = model "case_01.xml"
+ sim0 = simulate uniform(0, 10, 10)
+ task0 = run sim0 on model0
+ plot "UniformTimecourse" time vs S1, S2
+ report task0.time vs task0.S1
+"""
+te.saveToFile("case_01.xml", SBML)
+
+# phrasedml.setReferencedSBML("case_01.xml", SBML)
+sed = phrasedml.convertString(p_str)
+if sed is None:
+ print(phrasedml.getLastError())
+ sys.exit()
+
+sedml = libsedml.readSedMLFromString(sed)
+sedml.setVersion(4)
+
+plot = sedml.getOutput(0)
+
+xaxis=plot.createXAxis()
+xaxis.setType(libsedml.SEDML_AXISTYPE_LINEAR)
+xaxis.setName("Time")
+xaxis.setMin(2.5)
+xaxis.setMax(8)
+
+yaxis=plot.createYAxis()
+yaxis.setType(libsedml.SEDML_AXISTYPE_LINEAR)
+yaxis.setName("Concentration")
+yaxis.setMin(1)
+yaxis.setMax(12)
+
+
+
+sedstr = libsedml.writeSedMLToString(sedml)
+print(sedstr)
+
+te.executeSEDML(sedstr)
+
+import os
+sedfile = os.path.basename(__file__)
+sedfile = sedfile.replace(".py", ".sedml")
+sedfile = sedfile.replace("create_sedml_", "")
+
+te.saveToFile(sedfile, sedstr)
diff --git a/pool/shard003/Python/0028815_setup.py b/pool/shard003/Python/0028815_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..394cb19495db6b8a6fcbcf9b48bd45ce30c43ba8
--- /dev/null
+++ b/pool/shard003/Python/0028815_setup.py
@@ -0,0 +1,25 @@
+from setuptools import setup
+
+
+def getVersion():
+ import re, os
+ r_version = re.compile(r'version\s=\s"(.*?)"')
+ version_py = os.path.abspath(os.path.join(__file__,
+ '../crudset/version.py'))
+ return r_version.search(open(version_py, 'r').read()).groups()[0]
+
+
+setup(
+ url='none',
+ author='Matt Haggard',
+ author_email='haggardii@gmail.com',
+ name='crudset',
+ version=getVersion(),
+ packages=[
+ 'crudset', 'crudset.test'
+ ],
+ install_requires=[
+ 'alchimia',
+ 'SQLAlchemy==0.8.3',
+ ]
+)
diff --git a/pool/shard003/Python/0028817_leetcode.189.rotate-array.py b/pool/shard003/Python/0028817_leetcode.189.rotate-array.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a888e4dca3544911f0425d14e1e89948d6323b
--- /dev/null
+++ b/pool/shard003/Python/0028817_leetcode.189.rotate-array.py
@@ -0,0 +1,26 @@
+class Solution(object):
+ def rotate(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: void Do not return anything, modify nums in-place instead.
+ """
+ l = len(nums)
+ k %= l
+ gcd = self.GCD(l,k)
+ for i in range(gcd):
+ cur = i
+ temp = nums[i]
+ while 1:
+ next = (cur+k) % l
+ if next == i: break
+ temp1 = nums[next]
+ nums[next] = temp
+ cur = next
+ temp = temp1
+ nums[i] = temp
+
+
+ def GCD(self,a,b):
+ if a == 0: return b
+ return self.GCD(b%a,a)
\ No newline at end of file
diff --git a/pool/shard003/Python/0028821_attrtype.py b/pool/shard003/Python/0028821_attrtype.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbd4b81ab25cee045a03e33054f55f157edbbe3e
--- /dev/null
+++ b/pool/shard003/Python/0028821_attrtype.py
@@ -0,0 +1,82 @@
+#
+# Gramps - a GTK+/GNOME based genealogy program
+#
+# Copyright (C) 2000-2007 Donald N. Allingham
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+# $Id$
+
+"""
+Provide the different Attribute Types for GRAMPS.
+"""
+
+#-------------------------------------------------------------------------
+#
+# Standard Python modules
+#
+#-------------------------------------------------------------------------
+from ..ggettext import gettext as _
+#-------------------------------------------------------------------------
+#
+# GRAMPS modules
+#
+#-------------------------------------------------------------------------
+from grampstype import GrampsType
+
+class AttributeType(GrampsType):
+
+ UNKNOWN = -1
+ CUSTOM = 0
+ CASTE = 1
+ DESCRIPTION = 2
+ ID = 3
+ NATIONAL = 4
+ NUM_CHILD = 5
+ SSN = 6
+ NICKNAME = 7
+ CAUSE = 8
+ AGENCY = 9
+ AGE = 10
+ FATHER_AGE = 11
+ MOTHER_AGE = 12
+ WITNESS = 13
+ TIME = 14
+
+ _CUSTOM = CUSTOM
+ _DEFAULT = ID
+
+ _DATAMAP = [
+ (UNKNOWN , _("Unknown"), "Unknown"),
+ (CUSTOM , _("Custom"), "Custom"),
+ (CASTE , _("Caste"), "Caste"),
+ (DESCRIPTION , _("Description"), "Description"),
+ (ID , _("Identification Number"), "Identification Number"),
+ (NATIONAL , _("National Origin"), "National Origin"),
+ (NUM_CHILD , _("Number of Children"), "Number of Children"),
+ (SSN , _("Social Security Number"), "Social Security Number"),
+ (NICKNAME , _("Nickname"), "Nickname"),
+ (CAUSE , _("Cause"), "Cause"),
+ (AGENCY , _("Agency"), "Agency"),
+ (AGE , _("Age"), "Age"),
+ (FATHER_AGE , _("Father's Age"), "Father Age"),
+ (MOTHER_AGE , _("Mother's Age"), "Mother Age"),
+ (WITNESS , _("Witness"), "Witness"),
+ (TIME , _("Time"), "Time"),
+ ]
+
+ def __init__(self, value=None):
+ GrampsType.__init__(self, value)
diff --git a/pool/shard003/Python/0028822_combos.py b/pool/shard003/Python/0028822_combos.py
new file mode 100644
index 0000000000000000000000000000000000000000..f31ec50db1a58ffeeef9139338a7a128979bf6b2
--- /dev/null
+++ b/pool/shard003/Python/0028822_combos.py
@@ -0,0 +1,68 @@
+"""Powerset generators based on combining integers or sets."""
+
+import collections
+
+__all__ = ['shortlex', 'reverse_shortlex']
+
+
+def shortlex(start, other, excludestart=False):
+ """Yield all unions of start with other in shortlex order.
+
+ >>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])]
+ ['000', '100', '010', '001', '110', '101', '011', '111']
+
+ >>> ', '.join(''.join(sorted(s))
+ ... for s in shortlex(set(), [{'a'}, {'b'}, {'c'}, {'d'}]))
+ ', a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd'
+
+ >>> assert list(shortlex(set(), [{1}, {2}], excludestart=True)) == \
+ [{1}, {2}, {1, 2}]
+ """
+ if not excludestart:
+ yield start
+
+ queue = collections.deque([(start, other)])
+
+ while queue:
+ current, other = queue.popleft()
+
+ while other:
+ first, other = other[0], other[1:]
+ result = current | first
+
+ yield result
+
+ if other:
+ queue.append((result, other))
+
+
+def reverse_shortlex(end, other, excludeend=False):
+ """Yield all intersections of end with other in reverse shortlex order.
+
+ >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])]
+ ['111', '011', '101', '110', '001', '010', '100', '000']
+
+ >>> ', '.join(''.join(sorted(s))
+ ... for s in reverse_shortlex({'a', 'b', 'c', 'd'},
+ ... [{'b', 'c', 'd'}, {'a', 'c', 'd'}, {'a', 'b', 'd'}, {'a', 'b', 'c'}]))
+ 'abcd, bcd, acd, abd, abc, cd, bd, bc, ad, ac, ab, d, c, b, a, '
+
+ >>> assert list(reverse_shortlex({1, 2}, [{1}, {2}], excludeend=True)) == \
+ [{1}, {2}, set()]
+ """
+ if not excludeend:
+ yield end
+
+ queue = collections.deque([(end, other)])
+
+ while queue:
+ current, other = queue.popleft()
+
+ while other:
+ first, other = other[0], other[1:]
+ result = current & first
+
+ yield result
+
+ if other:
+ queue.append((result, other))
diff --git a/pool/shard003/Python/0028824_data_utils.py b/pool/shard003/Python/0028824_data_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..94c25c647364c8fec88c7eb901540fd69d866cfd
--- /dev/null
+++ b/pool/shard003/Python/0028824_data_utils.py
@@ -0,0 +1,82 @@
+# Copyright 2020 The AutoKeras Authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import numpy as np
+import tensorflow as tf
+from tensorflow import nest
+
+
+def batched(dataset):
+ shape = nest.flatten(dataset_shape(dataset))[0]
+ return len(shape) > 0 and shape[0] is None
+
+
+def batch_dataset(dataset, batch_size):
+ if batched(dataset):
+ return dataset
+ return dataset.batch(batch_size)
+
+
+def split_dataset(dataset, validation_split):
+ """Split dataset into training and validation.
+
+ # Arguments
+ dataset: tf.data.Dataset. The entire dataset to be split.
+ validation_split: Float. The split ratio for the validation set.
+
+ # Raises
+ ValueError: If the dataset provided is too small to be split.
+
+ # Returns
+ A tuple of two tf.data.Dataset. The training set and the validation set.
+ """
+ num_instances = dataset.reduce(np.int64(0), lambda x, _: x + 1).numpy()
+ if num_instances < 2:
+ raise ValueError(
+ "The dataset should at least contain 2 batches to be split."
+ )
+ validation_set_size = min(
+ max(int(num_instances * validation_split), 1), num_instances - 1
+ )
+ train_set_size = num_instances - validation_set_size
+ train_dataset = dataset.take(train_set_size)
+ validation_dataset = dataset.skip(train_set_size)
+ return train_dataset, validation_dataset
+
+
+def dataset_shape(dataset):
+ return tf.compat.v1.data.get_output_shapes(dataset)
+
+
+def unzip_dataset(dataset):
+ return nest.flatten(
+ [
+ dataset.map(lambda *a: nest.flatten(a)[index])
+ for index in range(len(nest.flatten(dataset_shape(dataset))))
+ ]
+ )
+
+
+def cast_to_string(tensor):
+ if tensor.dtype == tf.string:
+ return tensor
+ return tf.strings.as_string(tensor)
+
+
+def cast_to_float32(tensor):
+ if tensor.dtype == tf.float32:
+ return tensor
+ if tensor.dtype == tf.string:
+ return tf.strings.to_number(tensor, tf.float32)
+ return tf.cast(tensor, tf.float32)
diff --git a/pool/shard003/Python/0028828_utils.py b/pool/shard003/Python/0028828_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f3688d1917aa8273912821a74a3b3927ba669ab
--- /dev/null
+++ b/pool/shard003/Python/0028828_utils.py
@@ -0,0 +1,280 @@
+# -*- coding: utf-8 -*-
+# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
+#
+# This file is part of FI-WARE project.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+#
+# You may obtain a copy of the License at:
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# For those usages not covered by the Apache version 2.0 License please
+# contact with opensource@tid.es
+
+__author__ = 'arobres, jfernandez'
+
+import xmldict
+import xmltodict
+import string
+import random
+import time
+from commons.rest_utils import RestUtils
+from constants import *
+from lxml import etree
+from commons.fabric_utils import execute_file_exist
+from configuration import WAIT_FOR_OPERATION, WAIT_FOR_INSTALLATION
+
+
+def __set_none_as_empty_value__(python_dict_element):
+ """ Replace all None values of a dict by an empty value ""
+ :param python_dict_element: Dict to be analyzed. Will be replaced itself.
+ :return: None
+ """
+ for element in python_dict_element:
+ if python_dict_element[element] is None:
+ python_dict_element.update({element: ''})
+ elif isinstance(element, dict):
+ __set_none_as_empty_value__(element)
+
+
+def dict_to_xml(dict_to_convert):
+
+ return xmldict.dict_to_xml(dict_to_convert)
+
+
+def xml_to_dict(xml_to_convert):
+
+ return xmldict.xml_to_dict(xml_to_convert)
+
+
+def xml_to_dict_attr(xml_to_convert):
+
+ return xmltodict.parse(xml_to_convert, attr_prefix='')
+
+
+def response_body_to_dict(http_response, accept_content_type, with_attributes=False, xml_root_element_name=None,
+ is_list=False):
+ """
+ Method to convert a XML o JSON response in a Python dict
+ :param http_response: 'Requests (lib)' response
+ :param accept_content_type: Accept header value
+ :param with_attributes: For XML requests. If True, XML attributes will be processed
+ :param xml_root_element_name: For XML requests. XML root element in response.
+ :param is_list: For XML requests. If response is a list, a True value will delete list node name
+ :return: Python dict with response.
+ """
+ if ACCEPT_HEADER_JSON in accept_content_type:
+ try:
+ return http_response.json()
+ except Exception, e:
+ print str(e)
+ else:
+ if with_attributes is True:
+ return xml_to_dict_attr(http_response.content)[xml_root_element_name]
+ else:
+ assert xml_root_element_name is not None,\
+ "xml_root_element_name is a mandatory param when body is in XML and attributes are not considered"
+ response_body = xml_to_dict(http_response.content)[xml_root_element_name]
+ if response_body is not None:
+ __set_none_as_empty_value__(response_body)
+
+ if is_list and response_body is not None:
+ response_body = response_body.popitem()[1]
+
+ return response_body
+
+
+def body_model_to_body_request(body_model, content_type, body_model_root_element=None):
+ if CONTENT_TYPE_XML in content_type:
+ return dict_to_xml(body_model)
+ else:
+ return body_model[body_model_root_element]
+
+
+def set_default_headers(token_id, tenant_id):
+
+ headers = dict()
+ headers[AUTH_TOKEN_HEADER] = token_id
+ headers[TENANT_ID_HEADER] = tenant_id
+ headers[CONTENT_TYPE] = CONTENT_TYPE_XML
+ headers[ACCEPT_HEADER] = CONTENT_TYPE_JSON
+
+ return headers
+
+
+def id_generator(size=10, chars=string.ascii_letters + string.digits):
+
+ """Method to create random ids
+ :param size: define the string size
+ :param chars: the characters to be use to create the string
+ return ''.join(random.choice(chars) for x in range(size))
+ """
+
+ return ''.join(random.choice(chars) for x in range(size))
+
+
+def delete_keys_from_dict(dict_del, key):
+
+ """
+ Method to delete keys from python dict
+ :param dict_del: Python dictionary with all keys
+ :param key: key to be deleted in the Python dictionary
+ :returns a new Python dictionary without the rules deleted
+ """
+
+ if key in dict_del.keys():
+
+ del dict_del[key]
+ for v in dict_del.values():
+ if isinstance(v, dict):
+ delete_keys_from_dict(v, key)
+
+ return dict_del
+
+
+def delete_keys_when_value_is_none(dict_del):
+
+ default_dict = dict_del.copy()
+ for v in default_dict.keys():
+ if default_dict[v] is None:
+ del dict_del[v]
+ return dict_del
+
+
+def replace_none_value_metadata_to_empty_string(list_of_metadatas):
+ """
+ In a metadata list, replace None value by empty string
+ :param list_of_metadatas:
+ :return:
+ """
+ for metadata in list_of_metadatas:
+ if metadata['value'] is None:
+ metadata['value'] = ''
+
+
+def wait_for_task_finished(vdc_id, task_id, seconds=WAIT_FOR_OPERATION, status_to_be_finished=None, headers=None):
+
+ rest_utils = RestUtils()
+
+ correct_status = False
+ for count in range(seconds):
+ response = rest_utils.retrieve_task(headers=headers, vdc_id=vdc_id, task_id=task_id)
+ response_body = response_body_to_dict(response, headers[ACCEPT_HEADER], with_attributes=True,
+ xml_root_element_name=TASK)
+ status = response_body[TASK_STATUS]
+ print '[TASK] Waiting for task status. CHECK: {} - STATUS: {}'.format(count, status)
+
+ if status == status_to_be_finished:
+ correct_status = True
+ break
+ elif status != TASK_STATUS_VALUE_RUNNING:
+ break
+ time.sleep(5)
+
+ if correct_status is False:
+ print "[TASK] Response body:", response_body
+
+ return correct_status
+
+
+def wait_for_software_installed(seconds=WAIT_FOR_INSTALLATION, status_to_be_finished=True, file_name=None):
+
+ for count in range(seconds/3):
+
+ response = execute_file_exist(test_file_name=file_name)
+ print "Waiting for file status. FILE EXISTS: {}".format(response)
+ if status_to_be_finished == response:
+ return True
+
+ time.sleep(3)
+ return False
+
+
+#@deprecated [utils.response_body_to_dict]
+def convert_response_to_json(response):
+
+ response_headers = response.headers
+ if response_headers[CONTENT_TYPE] == CONTENT_TYPE_JSON:
+ try:
+ response_body = response.json()
+ except Exception, e:
+ print str(e)
+
+ else:
+ response_body = xml_to_dict(response.content)
+
+ return response_body
+
+
+def get_installation_response(response):
+
+ response_headers = response.headers
+ if response_headers[CONTENT_TYPE] == CONTENT_TYPE_JSON:
+ try:
+ response_body = response.json()
+ status = response_body[STATUS_XML]
+ href = response_body[TASK_URL]
+ vdc = response_body[VDC]
+ except Exception, e:
+ print str(e)
+
+ else:
+ try:
+ response_xml = etree.XML(response.content)
+ href = response_xml.xpath("//task/@href")[0]
+ status = response_xml.xpath("//task/@status")[0]
+ vdc = response_xml.xpath("//task/vdc")[0].text
+
+ except Exception, e:
+ print str(e)
+
+ return href, status, vdc
+
+
+def generate_product_instance_id(vm_fqn, product_name, product_version):
+ """
+ Method to generate instance id for installed products (product instances)
+ :param vm_fqn: FQN (where product has been installed)
+ :param product_name: Product name (instance)
+ :param product_version: Product release (instance)
+ :return: Product instance ID
+ """
+ return "{}_{}_{}".format(vm_fqn, product_name, product_version)
+
+
+def _replace_ipall_att_value(attribute, installator):
+ """
+ If installator is Puppet, list of values (IPALL type) is installed by our testing manifest without ",".
+ This method return the list without that character to validate a successful installation
+ :param attribute: Instance attribute to be processed
+ :return: If installator is Puppet, list of values when attribute type is IPALL will be processed
+ to delete the "," character
+ """
+ if installator == 'puppet' and ATTRIBUTE_TYPE in attribute and attribute[ATTRIBUTE_TYPE] == ATTRIBUTE_TYPE_IPALL:
+ return attribute[VALUE].replace(",", "")
+ else:
+ return attribute[VALUE]
+
+
+def generate_content_installed_by_product(product_name, product_version, instance_attributes, installator='chef'):
+
+ att_01 = PRODUCT_INSTALLATION_ATT1_DEFAULT
+ att_02 = PRODUCT_INSTALLATION_ATT2_DEFAULT
+
+ if instance_attributes is not None or len(instance_attributes) != 0:
+ if len(instance_attributes) >= 1:
+ att_01 = _replace_ipall_att_value(instance_attributes[0], installator)
+
+ if len(instance_attributes) >= 2:
+ att_02 = _replace_ipall_att_value(instance_attributes[1], installator)
+ return PRODUCT_INSTALLATION_FILE_CONTENT.format(product_name=product_name, product_version=product_version,
+ att_01=att_01, att_02=att_02)
diff --git a/pool/shard003/Python/0028838_test_daemon_thread.py b/pool/shard003/Python/0028838_test_daemon_thread.py
new file mode 100644
index 0000000000000000000000000000000000000000..4da3ec4677650948d5c8c8a5cbc958e6215b3683
--- /dev/null
+++ b/pool/shard003/Python/0028838_test_daemon_thread.py
@@ -0,0 +1,48 @@
+#!/bin/env python
+#-*- coding=utf-8 -*-
+# Author: John Hu
+# Email: huzichunjohn@126.com
+# Date: 2014-2-28
+# Version: 1.0
+
+import time
+import threading
+import logging
+
+class MyDaemonThread(threading.Thread):
+ id = 1
+ data = []
+
+ def __init__(self, interval=1):
+ threading.Thread.__init__(self)
+ self.__interval = interval
+ self.id = MyDaemonThread.getID()
+ self.__stop = False
+
+ def run(self):
+ count = 0
+ while count < 10 and not self.__stop:
+ logging.debug("ID: %d, sleep %d, current time is: %s", self.id, self.__interval, time.ctime())
+ time.sleep(self.__interval)
+ count += 1
+ self.data.append(count)
+ else:
+ logging.debug("ID %d is over.", self.id)
+
+ @staticmethod
+ def getID():
+ MyDaemonThread.id += 1
+ return MyDaemonThread.id
+
+ def stop(self):
+ self.__stop = True
+
+if __name__ == "__main__":
+ logging.basicConfig(filename='daemon.log', format='[%(asctime)s] (%(threadName)10s) %(message)s', datefmt='%Y-%m-%d %I:%M:%S %p', level=logging.DEBUG)
+ logging.debug("Start main thread ......")
+ mydaemon = MyDaemonThread(3)
+ mydaemon.setDaemon(True)
+ mydaemon.start()
+ logging.debug("Stop main thread ......")
+ time.sleep(15)
+ mydaemon.stop()
diff --git a/pool/shard003/Python/0028839_unblockIP.py b/pool/shard003/Python/0028839_unblockIP.py
new file mode 100644
index 0000000000000000000000000000000000000000..586f952c720270891185c0773a2ff17fcbca7e90
--- /dev/null
+++ b/pool/shard003/Python/0028839_unblockIP.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+#import sys, os
+from logEmail import EmailLogger
+import cgi, cgitb
+import os
+
+cgitb.enable()
+
+if __name__=="__main__":
+ print "Content-type: text/html\n\n"
+ f = cgi.FieldStorage()
+ ip=None
+ #try:
+ ip = f["ip"].value
+ loggerPath = f["loggerPath"].value
+ logger = EmailLogger( os.path.normpath(loggerPath) ) # Cannot change the path through CGI parameter
+ unBlocked = logger.unblock(ip)
+ if unBlocked==True:
+ print "IP %s successfully unblocked!" %(ip)
+ else:
+ print "IP %s was not blocked." %(ip)
+
diff --git a/pool/shard003/Python/0028841_Configuration.py b/pool/shard003/Python/0028841_Configuration.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1076e53264aba0ef34be877a3db4e8ef91d4c31
--- /dev/null
+++ b/pool/shard003/Python/0028841_Configuration.py
@@ -0,0 +1,115 @@
+import os
+
+CONFIGURATION_NAME = 'ResourcesManager.conf'
+SEPARATOR = ' = '
+NEW_LINE = '\n'
+TRUE = 'true'
+FALSE = 'false'
+FOLDER_NAME = 'ResourcesManager'
+PROCESSED_FILES_FILE_NAME = 'processed.list'
+PENDING_FILES_FILE_NAME = 'pending.list'
+DEFAULT_EVENT_BUS_NAME = 'EventBus'
+DEFAULT_KEYS = 'CFBundleURLTypes, UIAppFonts'
+
+TURN_TO_CAMEL_KEY = 'turn_to_camel'
+TURN_TO_CAMEL_CHARACTERS_KEY = 'turn_to_camel_characters'
+REPLACEMENTS_KEY = 'characters_to_replace'
+CHANGE_R_SWIFT_STRING_KEY = 'change_r_swift_strings'
+STRINGS_CONTAINER_TYPE_KEY = 'parsed_strings_container_type'
+LOCALIZATIONS_PATH_KEY = 'localizations_files_path'
+LOCALIZATIONS_TABLE_NAME_KEY = 'localizations_table_name'
+GENERATED_FOLDER_NAME_KEY = 'generated_folder_name'
+PROCESSED_FILES_NAME_KEY = 'processed_list_file_name'
+NEEDS_PROCESSING_FILES_NAME_KEY = 'pending_files_list_file_name'
+PROCESS_FILES_KEY = 'process_files'
+PARSE_STRINGS_KEY = 'parse_strings'
+EVENT_BUS_NAME_KEY = 'event_bus_class_name'
+INFO_PLIST_PATH_KEY = 'info_plist_path'
+GENERATE_INFO_PLIST_PARSER_KEY = 'generate_info_plist_parser'
+NEEDED_KEYS_KEY = 'parser_for_following_keys'
+GENERATE_IMAGES_RESOURCE_KEY = 'generate_images_resource'
+IMAGES_CONTAINER_KEY = 'images_container'
+IS_DEFAULT_TEMPLATE_IMAGE_KEY = 'should_use_always_template_by_default'
+GENERATE_FONTS_RESOURCE_KEY = 'generate_fonts_resource'
+FONTS_CONTAINER_TYPE_KEY = 'fonts_container_type'
+GENERATE_IB_RESOURCES = 'generate_interface_builder_resources'
+GENERATE_MAPPING_KEY = 'generate_mapping'
+MAPPING_PATH_KEY = "mapping_path"
+
+class ContainerType:
+ def __init__(self):
+ raise NotImplementedError
+
+ EXTENSION = 'extension'
+ CLASS = 'class'
+
+
+def get_full_path_to_conf(path):
+ if path[-1] == '/' or path[-1] == '\\':
+ return path + CONFIGURATION_NAME
+ else:
+ return path + "/" + CONFIGURATION_NAME
+
+
+def generate_default_configuration(path):
+ conf = open(get_full_path_to_conf(path), 'w+')
+
+ _put_value_in_configuration(conf, TURN_TO_CAMEL_KEY, TRUE)
+ _put_value_in_configuration(conf, TURN_TO_CAMEL_CHARACTERS_KEY, '_-')
+ _put_value_in_configuration(conf, REPLACEMENTS_KEY, '._')
+ _put_value_in_configuration(conf, CHANGE_R_SWIFT_STRING_KEY, FALSE)
+ _put_value_in_configuration(conf, STRINGS_CONTAINER_TYPE_KEY, ContainerType.EXTENSION)
+ _put_value_in_configuration(conf, LOCALIZATIONS_TABLE_NAME_KEY, 'Localizable')
+ _put_value_in_configuration(conf, GENERATED_FOLDER_NAME_KEY, FOLDER_NAME)
+ _put_value_in_configuration(conf, PROCESSED_FILES_NAME_KEY, PROCESSED_FILES_FILE_NAME)
+ _put_value_in_configuration(conf, NEEDS_PROCESSING_FILES_NAME_KEY, PENDING_FILES_FILE_NAME)
+ _put_value_in_configuration(conf, PROCESS_FILES_KEY, TRUE)
+ _put_value_in_configuration(conf, PARSE_STRINGS_KEY, TRUE)
+ _put_value_in_configuration(conf, EVENT_BUS_NAME_KEY, DEFAULT_EVENT_BUS_NAME)
+ _put_value_in_configuration(conf, GENERATE_INFO_PLIST_PARSER_KEY, TRUE)
+ _put_value_in_configuration(conf, NEEDED_KEYS_KEY, DEFAULT_KEYS)
+ _put_value_in_configuration(conf, GENERATE_IMAGES_RESOURCE_KEY, TRUE)
+ _put_value_in_configuration(conf, IS_DEFAULT_TEMPLATE_IMAGE_KEY, TRUE)
+ _put_value_in_configuration(conf, IMAGES_CONTAINER_KEY, ContainerType.EXTENSION)
+ _put_value_in_configuration(conf, GENERATE_FONTS_RESOURCE_KEY, TRUE)
+ _put_value_in_configuration(conf, FONTS_CONTAINER_TYPE_KEY, ContainerType.EXTENSION)
+ _put_value_in_configuration(conf, GENERATE_IB_RESOURCES, TRUE)
+ _put_value_in_configuration(conf, GENERATE_MAPPING_KEY, FALSE)
+
+ conf.close()
+
+
+def _put_value_in_configuration(conf, key, value):
+ conf.write(key + SEPARATOR + value + NEW_LINE)
+
+
+def read_configuration(path):
+ file_path = get_full_path_to_conf(path)
+ if not os.path.isfile(file_path):
+ generate_default_configuration(path)
+
+ configuration = {}
+
+ conf = open(file_path, 'r')
+
+ for line in conf.readlines():
+ splitted = line.split(SEPARATOR)
+ if len(splitted) == 2:
+ configuration[splitted[0].strip()] = splitted[1].strip()
+
+ if NEEDED_KEYS_KEY in configuration:
+ configuration[NEEDED_KEYS_KEY] = [x.strip() for x in configuration[NEEDED_KEYS_KEY].split(',')]
+
+ conf.close()
+
+ return configuration
+
+
+def synchronize_configuration(path, conf):
+ conf_file = open(get_full_path_to_conf(path), 'w+')
+
+ for key in conf:
+ if key != NEEDED_KEYS_KEY:
+ _put_value_in_configuration(conf_file, key, str(conf[key]))
+
+ conf_file.close()
diff --git a/pool/shard003/Python/0028843_test_non_empty_stack.py b/pool/shard003/Python/0028843_test_non_empty_stack.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f96de327df97e55718beead8ec84722d4bf8908
--- /dev/null
+++ b/pool/shard003/Python/0028843_test_non_empty_stack.py
@@ -0,0 +1,164 @@
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+
+from tempest_lib.common.utils import data_utils
+
+from tempest.api.orchestration import base
+from tempest import config
+from tempest import test
+
+CONF = config.CONF
+
+LOG = logging.getLogger(__name__)
+
+
+class StacksTestJSON(base.BaseOrchestrationTest):
+
+ @classmethod
+ def resource_setup(cls):
+ super(StacksTestJSON, cls).resource_setup()
+ cls.stack_name = data_utils.rand_name('heat')
+ template = cls.read_template('non_empty_stack')
+ image_id = (CONF.compute.image_ref or
+ cls._create_image()['id'])
+ flavor = CONF.orchestration.instance_type
+ # create the stack
+ cls.stack_identifier = cls.create_stack(
+ cls.stack_name,
+ template,
+ parameters={
+ 'trigger': 'start',
+ 'image': image_id,
+ 'flavor': flavor
+ })
+ cls.stack_id = cls.stack_identifier.split('/')[1]
+ cls.resource_name = 'fluffy'
+ cls.resource_type = 'AWS::AutoScaling::LaunchConfiguration'
+ cls.client.wait_for_stack_status(cls.stack_id, 'CREATE_COMPLETE')
+
+ def _list_stacks(self, expected_num=None, **filter_kwargs):
+ stacks = self.client.list_stacks(params=filter_kwargs)
+ self.assertIsInstance(stacks, list)
+ if expected_num is not None:
+ self.assertEqual(expected_num, len(stacks))
+ return stacks
+
+ @test.attr(type='gate')
+ @test.idempotent_id('065c652a-720d-4760-9132-06aedeb8e3ab')
+ def test_stack_list(self):
+ """Created stack should be in the list of existing stacks."""
+ stacks = self._list_stacks()
+ stacks_names = map(lambda stack: stack['stack_name'], stacks)
+ self.assertIn(self.stack_name, stacks_names)
+
+ @test.attr(type='gate')
+ @test.idempotent_id('992f96e3-41ee-4ff6-91c7-bcfb670c0919')
+ def test_stack_show(self):
+ """Getting details about created stack should be possible."""
+ stack = self.client.show_stack(self.stack_name)
+ self.assertIsInstance(stack, dict)
+ self.assert_fields_in_dict(stack, 'stack_name', 'id', 'links',
+ 'parameters', 'outputs', 'disable_rollback',
+ 'stack_status_reason', 'stack_status',
+ 'creation_time', 'updated_time',
+ 'capabilities', 'notification_topics',
+ 'timeout_mins', 'template_description')
+ self.assert_fields_in_dict(stack['parameters'], 'AWS::StackId',
+ 'trigger', 'AWS::Region', 'AWS::StackName')
+ self.assertEqual(True, stack['disable_rollback'],
+ 'disable_rollback should default to True')
+ self.assertEqual(self.stack_name, stack['stack_name'])
+ self.assertEqual(self.stack_id, stack['id'])
+ self.assertEqual('fluffy', stack['outputs'][0]['output_key'])
+
+ @test.attr(type='gate')
+ @test.idempotent_id('fe719f7a-305a-44d8-bbb5-c91e93d9da17')
+ def test_suspend_resume_stack(self):
+ """Suspend and resume a stack."""
+ self.client.suspend_stack(self.stack_identifier)
+ self.client.wait_for_stack_status(self.stack_identifier,
+ 'SUSPEND_COMPLETE')
+ self.client.resume_stack(self.stack_identifier)
+ self.client.wait_for_stack_status(self.stack_identifier,
+ 'RESUME_COMPLETE')
+
+ @test.attr(type='gate')
+ @test.idempotent_id('c951d55e-7cce-4c1f-83a0-bad735437fa6')
+ def test_list_resources(self):
+ """Getting list of created resources for the stack should be possible.
+ """
+ resources = self.list_resources(self.stack_identifier)
+ self.assertEqual({self.resource_name: self.resource_type}, resources)
+
+ @test.attr(type='gate')
+ @test.idempotent_id('2aba03b3-392f-4237-900b-1f5a5e9bd962')
+ def test_show_resource(self):
+ """Getting details about created resource should be possible."""
+ resource = self.client.show_resource(self.stack_identifier,
+ self.resource_name)
+ self.assertIsInstance(resource, dict)
+ self.assert_fields_in_dict(resource, 'resource_name', 'description',
+ 'links', 'logical_resource_id',
+ 'resource_status', 'updated_time',
+ 'required_by', 'resource_status_reason',
+ 'physical_resource_id', 'resource_type')
+ self.assertEqual(self.resource_name, resource['logical_resource_id'])
+ self.assertEqual(self.resource_type, resource['resource_type'])
+
+ @test.attr(type='gate')
+ @test.idempotent_id('898070a9-eba5-4fae-b7d6-cf3ffa03090f')
+ def test_resource_metadata(self):
+ """Getting metadata for created resources should be possible."""
+ metadata = self.client.show_resource_metadata(
+ self.stack_identifier,
+ self.resource_name)
+ self.assertIsInstance(metadata, dict)
+ self.assertEqual(['Tom', 'Stinky'], metadata.get('kittens', None))
+
+ @test.attr(type='gate')
+ @test.idempotent_id('46567533-0a7f-483b-8942-fa19e0f17839')
+ def test_list_events(self):
+ """Getting list of created events for the stack should be possible."""
+ events = self.client.list_events(self.stack_identifier)
+ self.assertIsInstance(events, list)
+
+ for event in events:
+ self.assert_fields_in_dict(event, 'logical_resource_id', 'id',
+ 'resource_status_reason',
+ 'resource_status', 'event_time')
+
+ resource_statuses = map(lambda event: event['resource_status'], events)
+ self.assertIn('CREATE_IN_PROGRESS', resource_statuses)
+ self.assertIn('CREATE_COMPLETE', resource_statuses)
+
+ @test.attr(type='gate')
+ @test.idempotent_id('92465723-1673-400a-909d-4773757a3f21')
+ def test_show_event(self):
+ """Getting details about an event should be possible."""
+ events = self.client.list_resource_events(self.stack_identifier,
+ self.resource_name)
+ self.assertNotEqual([], events)
+ events.sort(key=lambda event: event['event_time'])
+ event_id = events[0]['id']
+ event = self.client.show_event(self.stack_identifier,
+ self.resource_name, event_id)
+ self.assertIsInstance(event, dict)
+ self.assert_fields_in_dict(event, 'resource_name', 'event_time',
+ 'links', 'logical_resource_id',
+ 'resource_status', 'resource_status_reason',
+ 'physical_resource_id', 'id',
+ 'resource_properties', 'resource_type')
+ self.assertEqual(self.resource_name, event['resource_name'])
+ self.assertEqual('state changed', event['resource_status_reason'])
+ self.assertEqual(self.resource_name, event['logical_resource_id'])
diff --git a/pool/shard003/Python/0028853_webapi.py b/pool/shard003/Python/0028853_webapi.py
new file mode 100644
index 0000000000000000000000000000000000000000..47da27c26e9060c457dcf3fa957579ce4cc21577
--- /dev/null
+++ b/pool/shard003/Python/0028853_webapi.py
@@ -0,0 +1,98 @@
+"""
+Web interface exposing crawled items
+"""
+import redis
+
+from flask import Flask
+from flask import json
+from flask.ext import restful
+from flask.ext.restful.representations.json import output_json
+
+from celery import Celery
+
+from twisted.internet import reactor
+
+from scrapy.crawler import Crawler
+from scrapy import log, signals
+from scrapy.utils.project import get_project_settings
+
+from social_scraper.spiders.twitter import TwitterSpider
+from social_scraper.spiders.fb import FacebookSpider
+
+from social_scraper.settings import (API_HOST, API_PORT, API_DEBUG_MODE,
+ CELERY_BROKER_URL, CELERY_IMPORTS, CELERY_RESULT_BACKEND,
+ CELERYD_MAX_TASKS_PER_CHILD, REDIS_HOST, REDIS_PORT)
+
+
+# flask app configuration
+flask_app = Flask('profile_api')
+api = restful.Api(flask_app)
+
+# database setup
+flask_app.redis = redis.StrictRedis(REDIS_HOST, port=REDIS_PORT, db=0)
+
+# api output json encoding
+output_json.func_globals['settings'] = {'ensure_ascii': False, 'encoding': 'utf8'}
+
+# bind celery to flask app
+flask_app.config.update(CELERY_BROKER_URL=CELERY_BROKER_URL,
+ CELERY_RESULT_BACKEND=CELERY_RESULT_BACKEND,
+ CELERYD_MAX_TASKS_PER_CHILD=CELERYD_MAX_TASKS_PER_CHILD,
+ CELERY_IMPORTS=CELERY_IMPORTS,
+)
+celery = Celery(flask_app.import_name, broker=flask_app.config['CELERY_BROKER_URL'])
+celery.conf.update(flask_app.config)
+
+# Tasks
+@celery.task(name='tasks.crawl')
+def crawl(username, media):
+ """
+ Start crawling celery task,
+ """
+ assert media in ('twitter', 'facebook'), \
+ 'media :`{}` not supported yet!'.format(media)
+ spider = TwitterSpider(username) if media=='twitter' else FacebookSpider(username)
+ settings = get_project_settings()
+ crawler = Crawler(settings)
+ crawler.signals.connect(reactor.stop, signal=signals.spider_closed)
+ crawler.configure()
+ crawler.crawl(spider)
+ crawler.start()
+ log.start()
+ reactor.run(installSignalHandlers=0)
+
+def get_json_from_redis(username):
+ """ display helper """
+ value = flask_app.redis.get('twitter_{}'.format(username))
+ if value:
+ data = json.loads(value)
+ data.pop('id')
+ data.pop('search_name')
+ if 'description' in data and not str(data['description']).strip():
+ data.pop('description')
+ return data
+
+# Exposed Resources
+class Twitter(restful.Resource):
+ def get(self, username):
+ data = get_json_from_redis(username)
+ if data:
+ return data
+ crawl.delay(username, 'twitter')
+ return 'Processing request'
+api.add_resource(Twitter, '/api/v0.1/users/twitter/')
+
+
+class Facebook(restful.Resource):
+ def get(self, username):
+ data = get_json_from_redis(username)
+ if data:
+ return data
+ crawl.delay(username, media='facebook')
+ return 'Processing request'
+api.add_resource(Facebook, '/api/v0.1/users/facebook/')
+
+
+if __name__ == "__main__":
+ flask_app.debug = API_DEBUG_MODE
+ flask_app.run(host=API_HOST, port=int(API_PORT))
diff --git a/pool/shard003/Python/0028855_certificates.py b/pool/shard003/Python/0028855_certificates.py
new file mode 100644
index 0000000000000000000000000000000000000000..cadc6abcb8d1b0093549f488b81b347746f186bb
--- /dev/null
+++ b/pool/shard003/Python/0028855_certificates.py
@@ -0,0 +1,28 @@
+"""
+Python support for Azure automation is now public preview!
+
+Azure Automation documentation : https://aka.ms/azure-automation-python-documentation
+Azure Python SDK documentation : https://aka.ms/azure-python-sdk
+"""
+
+import binascii
+from OpenSSL import crypto
+
+from automationassets import *
+
+# get a certificate
+cert_binary = get_automation_certificate("AzureRunAsCertificate")
+
+# convert to b64
+cert_b64 = binascii.b2a_base64(cert_binary)
+print cert_b64
+
+# load certificate and dump the private key
+pks12_cert = crypto.load_pkcs12(cert_binary)
+pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM, pks12_cert.get_privatekey())
+
+# handling non-existant certificate
+try:
+ value = get_automation_certificate("non-existant-cert")
+except AutomationAssetNotFound:
+ print "Certificate not found."
diff --git a/pool/shard003/Python/0028857_shell.py b/pool/shard003/Python/0028857_shell.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc7b1eb18a223f61daf4076d9f3cefa269ad6ffe
--- /dev/null
+++ b/pool/shard003/Python/0028857_shell.py
@@ -0,0 +1,78 @@
+import getopt
+import sys
+import json
+
+import redpen.client
+import redpen.default
+import redpen.flymake
+
+def _as_bytes(f):
+ try:
+ return f.buffer
+ except AttributeError:
+ return f
+
+def validate():
+ conf = redpen.default.Config()
+ url = None
+ limit = None
+ opts, args = getopt.getopt(sys.argv[1:], 'c:s:mpwejl:', ['conf', 'server', 'markdown', 'plain', 'wiki', 'english', 'japanese', 'limit'])
+ for o,a in opts:
+ if o in ('-c', '--conf'):
+ with open(a, 'rb') as f:
+ conf.config['config'] = json.loads(f.read().decode('UTF-8'))
+ if o in ('-s', '--server'):
+ url = a
+ if o in ('-m', '--markdown'):
+ conf.parser('MARKDOWN')
+ if o in ('-p', '--plain'):
+ conf.parser('PLAIN')
+ if o in ('-w', '--wiki'):
+ conf.parser('WIKI')
+ if o in ('-e', '--english'):
+ conf.language('en')
+ if o in ('-j', '--japanese'):
+ conf.language('ja')
+ if o in ('-l', '--limit'):
+ limit = int(a)
+
+ try:
+ fn = args[0]
+ with open(fn, "rb") as f:
+ rp = redpen.client.RedPen(conf, f.read().decode("utf-8"))
+ except IndexError:
+ fn = None
+ rp = redpen.client.RedPen(conf, _as_bytes(sys.stdin).read().decode('utf-8'))
+
+ if url is not None:
+ rp.url(url)
+ return rp.validate(), fn, limit
+
+def commandline():
+ results, fn, limit = validate()
+ if not results['errors']:
+ print("Succeeded validation")
+ sys.exit(0)
+ else:
+ errors_found = len(results['errors'])
+ if limit is None or limit >= errors_found:
+ print("Found errors (%d)" % errors_found)
+ sys.exit(1)
+ else:
+ print("Found errors more than specified limit... (%d > %d)" % (errors_found, limit))
+ print(len(results["errors"]))
+ sys.exit(1)
+
+def flymake():
+ results, fn, limit = validate()
+ shaper = redpen.flymake.FlymakeShaper(fn, results)
+ for e in shaper.shape():
+ _as_bytes(sys.stdout).write((e + "\n").encode('utf-8'))
+ sys.exit(shaper.code())
+
+def sublimelinter():
+ results, fn, limit = validate()
+ shaper = redpen.flymake.SublimeLinterShaper(fn, results)
+ for e in shaper.shape():
+ _as_bytes(sys.stdout).write((e + "\n").encode('utf-8'))
+ sys.exit(shaper.code())
diff --git a/pool/shard003/Python/0028859_upload.py b/pool/shard003/Python/0028859_upload.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5ce428c25ff9dfb9126eb48548d0ccdcb6e9797
--- /dev/null
+++ b/pool/shard003/Python/0028859_upload.py
@@ -0,0 +1,282 @@
+# -*- coding: utf-8 -*-
+#########################################################################
+#
+# Copyright (C) 2018 OSGeo
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+#
+#########################################################################
+
+import uuid
+import logging
+import geoserver
+
+from geoserver.catalog import ConflictingDataError, UploadError
+from geoserver.resource import FeatureType, Coverage
+
+from django.conf import settings
+
+from geonode import GeoNodeException
+from geonode.layers.utils import layer_type, get_files
+from .helpers import (GEOSERVER_LAYER_TYPES,
+ gs_catalog,
+ get_store,
+ get_sld_for,
+ ogc_server_settings,
+ _create_db_featurestore,
+ _create_featurestore,
+ _create_coveragestore)
+
+logger = logging.getLogger(__name__)
+
+
+def geoserver_layer_type(filename):
+ the_type = layer_type(filename)
+ return GEOSERVER_LAYER_TYPES[the_type]
+
+
+def geoserver_upload(
+ layer,
+ base_file,
+ user,
+ name,
+ overwrite=True,
+ title=None,
+ abstract=None,
+ permissions=None,
+ keywords=(),
+ charset='UTF-8'):
+
+ # Step 2. Check that it is uploading to the same resource type as
+ # the existing resource
+ logger.debug('>>> Step 2. Make sure we are not trying to overwrite a '
+ 'existing resource named [%s] with the wrong type', name)
+ the_layer_type = geoserver_layer_type(base_file)
+
+ # Get a short handle to the gsconfig geoserver catalog
+ cat = gs_catalog
+
+ # Ahmed Nour: get workspace by name instead of get default one.
+ workspace = cat.get_workspace(settings.DEFAULT_WORKSPACE)
+ # Check if the store exists in geoserver
+ try:
+ store = get_store(cat, name, workspace=workspace)
+ except geoserver.catalog.FailedRequestError:
+ # There is no store, ergo the road is clear
+ pass
+ else:
+ # If we get a store, we do the following:
+ resources = cat.get_resources(names=[name], stores=[store], workspaces=[workspace])
+
+ if len(resources) > 0:
+ # If our resource is already configured in the store it needs
+ # to have the right resource type
+ for resource in resources:
+ if resource.name == name:
+ msg = 'Name already in use and overwrite is False'
+ assert overwrite, msg
+ existing_type = resource.resource_type
+ if existing_type != the_layer_type:
+ msg = ('Type of uploaded file %s (%s) '
+ 'does not match type of existing '
+ 'resource type '
+ '%s' % (name, the_layer_type, existing_type))
+ logger.debug(msg)
+ raise GeoNodeException(msg)
+
+ # Step 3. Identify whether it is vector or raster and which extra files
+ # are needed.
+ logger.debug('>>> Step 3. Identifying if [%s] is vector or raster and '
+ 'gathering extra files', name)
+ if the_layer_type == FeatureType.resource_type:
+ logger.debug('Uploading vector layer: [%s]', base_file)
+ if ogc_server_settings.DATASTORE:
+ create_store_and_resource = _create_db_featurestore
+ else:
+ create_store_and_resource = _create_featurestore
+ elif the_layer_type == Coverage.resource_type:
+ logger.debug("Uploading raster layer: [%s]", base_file)
+ create_store_and_resource = _create_coveragestore
+ else:
+ msg = ('The layer type for name %s is %s. It should be '
+ '%s or %s,' % (name,
+ the_layer_type,
+ FeatureType.resource_type,
+ Coverage.resource_type))
+ logger.warn(msg)
+ raise GeoNodeException(msg)
+
+ # Step 4. Create the store in GeoServer
+ logger.debug('>>> Step 4. Starting upload of [%s] to GeoServer...', name)
+
+ # Get the helper files if they exist
+ files = get_files(base_file)
+ data = files
+ if 'shp' not in files:
+ data = base_file
+ try:
+ store, gs_resource = create_store_and_resource(
+ name,
+ data,
+ charset=charset,
+ overwrite=overwrite,
+ workspace=workspace)
+ except UploadError as e:
+ msg = ('Could not save the layer %s, there was an upload '
+ 'error: %s' % (name, str(e)))
+ logger.warn(msg)
+ e.args = (msg,)
+ raise
+ except ConflictingDataError as e:
+ # A datastore of this name already exists
+ msg = ('GeoServer reported a conflict creating a store with name %s: '
+ '"%s". This should never happen because a brand new name '
+ 'should have been generated. But since it happened, '
+ 'try renaming the file or deleting the store in '
+ 'GeoServer.' % (name, str(e)))
+ logger.warn(msg)
+ e.args = (msg,)
+ raise
+ else:
+ logger.debug('Finished upload of [%s] to GeoServer without '
+ 'errors.', name)
+
+ # Step 5. Create the resource in GeoServer
+ logger.debug('>>> Step 5. Generating the metadata for [%s] after '
+ 'successful import to GeoSever', name)
+
+ # Verify the resource was created
+ if not gs_resource:
+ gs_resource = gs_catalog.get_resource(
+ name=name,
+ workspace=workspace)
+
+ if not gs_resource:
+ msg = ('GeoNode encountered problems when creating layer %s.'
+ 'It cannot find the Layer that matches this Workspace.'
+ 'try renaming your files.' % name)
+ logger.warn(msg)
+ raise GeoNodeException(msg)
+
+ assert gs_resource.name == name
+
+ # Step 6. Make sure our data always has a valid projection
+ logger.debug('>>> Step 6. Making sure [%s] has a valid projection' % name)
+ _native_bbox = None
+ try:
+ _native_bbox = gs_resource.native_bbox
+ except Exception:
+ pass
+
+ if _native_bbox and len(_native_bbox) >= 5 and _native_bbox[4:5][0] == 'EPSG:4326':
+ box = _native_bbox[:4]
+ minx, maxx, miny, maxy = [float(a) for a in box]
+ if -180 <= round(minx, 5) <= 180 and -180 <= round(maxx, 5) <= 180 and \
+ -90 <= round(miny, 5) <= 90 and -90 <= round(maxy, 5) <= 90:
+ gs_resource.latlon_bbox = _native_bbox
+ gs_resource.projection = "EPSG:4326"
+ else:
+ logger.warning('BBOX coordinates outside normal EPSG:4326 values for layer '
+ '[%s].', name)
+ _native_bbox = [-180, -90, 180, 90, "EPSG:4326"]
+ gs_resource.latlon_bbox = _native_bbox
+ gs_resource.projection = "EPSG:4326"
+ logger.debug('BBOX coordinates forced to [-180, -90, 180, 90] for layer [%s].', name)
+
+ # Step 7. Create the style and assign it to the created resource
+ logger.debug('>>> Step 7. Creating style for [%s]' % name)
+ cat.save(gs_resource)
+ publishing = cat.get_layer(name) or gs_resource
+ sld = None
+ if 'sld' in files:
+ f = open(files['sld'], 'rb')
+ sld = f.read()
+ f.close()
+ else:
+ sld = get_sld_for(cat, publishing)
+
+ style = None
+ if sld:
+ try:
+ style = cat.get_style(name, workspace=workspace)
+ except geoserver.catalog.FailedRequestError:
+ style = cat.get_style(name)
+
+ try:
+ overwrite = style or False
+ cat.create_style(name, sld, overwrite=overwrite, raw=True, workspace=workspace)
+ cat.reset()
+ except geoserver.catalog.ConflictingDataError as e:
+ msg = ('There was already a style named %s in GeoServer, '
+ 'try to use: "%s"' % (name + "_layer", str(e)))
+ logger.warn(msg)
+ e.args = (msg,)
+ except geoserver.catalog.UploadError as e:
+ msg = ('Error while trying to upload style named %s in GeoServer, '
+ 'try to use: "%s"' % (name + "_layer", str(e)))
+ e.args = (msg,)
+ logger.exception(e)
+
+ if style is None:
+ try:
+ style = cat.get_style(name, workspace=workspace) or cat.get_style(name)
+ except Exception:
+ try:
+ style = cat.get_style(name + '_layer', workspace=workspace) or \
+ cat.get_style(name + '_layer')
+ overwrite = style or False
+ cat.create_style(name + '_layer', sld, overwrite=overwrite, raw=True,
+ workspace=workspace)
+ cat.reset()
+ style = cat.get_style(name + '_layer', workspace=workspace) or \
+ cat.get_style(name + '_layer')
+ except geoserver.catalog.ConflictingDataError as e:
+ msg = ('There was already a style named %s in GeoServer, '
+ 'cannot overwrite: "%s"' % (name, str(e)))
+ logger.warn(msg)
+ e.args = (msg,)
+
+ style = cat.get_style(name + "_layer", workspace=workspace) or \
+ cat.get_style(name + "_layer")
+ if style is None:
+ style = cat.get_style('point')
+ msg = ('Could not find any suitable style in GeoServer '
+ 'for Layer: "%s"' % (name))
+ logger.error(msg)
+
+ if style:
+ publishing.default_style = style
+ logger.debug('default style set to %s', name)
+ try:
+ cat.save(publishing)
+ except geoserver.catalog.FailedRequestError as e:
+ msg = ('Error while trying to save resource named %s in GeoServer, '
+ 'try to use: "%s"' % (publishing, str(e)))
+ e.args = (msg,)
+ logger.exception(e)
+
+ # Step 8. Create the Django record for the layer
+ logger.debug('>>> Step 8. Creating Django record for [%s]', name)
+ alternate = workspace.name + ':' + gs_resource.name
+ layer_uuid = str(uuid.uuid1())
+
+ defaults = dict(store=gs_resource.store.name,
+ storeType=gs_resource.store.resource_type,
+ alternate=alternate,
+ title=title or gs_resource.title,
+ uuid=layer_uuid,
+ abstract=abstract or gs_resource.abstract or '',
+ owner=user)
+
+ return name, workspace.name, defaults, gs_resource
diff --git a/pool/shard003/Python/0028863_angleDiff.py b/pool/shard003/Python/0028863_angleDiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..398cca9fd4662fc4f5fb0d897cb6a2c7657e441d
--- /dev/null
+++ b/pool/shard003/Python/0028863_angleDiff.py
@@ -0,0 +1,18 @@
+# coding=utf-8
+import numpy as np
+
+
+def angleDiff(angle1, angle2, take_smaller=True):
+ """
+ smallest difference between 2 angles
+ code from http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
+ """
+ a = np.arctan2(np.sin(angle1 - angle2), np.cos(angle1 - angle2))
+ if isinstance(a, np.ndarray) and take_smaller:
+ a = np.abs(a)
+ # take smaller of both possible angles:
+ ab = np.abs(np.pi - a)
+ with np.errstate(invalid='ignore'):
+ i = a > ab
+ a[i] = ab[i]
+ return a
diff --git a/pool/shard003/Python/0028865_account_payment_register.py b/pool/shard003/Python/0028865_account_payment_register.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed7287b5eaa1ce0bff53912d75febf3d049c924f
--- /dev/null
+++ b/pool/shard003/Python/0028865_account_payment_register.py
@@ -0,0 +1,77 @@
+# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
+# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
+from odoo import _, api, fields, models
+from odoo.exceptions import UserError
+from odoo.tools import float_compare
+
+
+class AccountPaymentRegister(models.TransientModel):
+ _inherit = "account.payment.register"
+
+ payment_difference_handling = fields.Selection(
+ selection_add=[
+ ("reconcile_multi_deduct", "Mark invoice as fully paid (multi deduct)")
+ ],
+ ondelete={"reconcile_multi_deduct": "cascade"},
+ )
+ deduct_residual = fields.Monetary(
+ string="Remainings", compute="_compute_deduct_residual"
+ )
+ deduction_ids = fields.One2many(
+ comodel_name="account.payment.deduction",
+ inverse_name="payment_id",
+ string="Deductions",
+ copy=False,
+ help="Sum of deduction amount(s) must equal to the payment difference",
+ )
+
+ def action_create_payments(self):
+ if self.payment_difference_handling == "reconcile_multi_deduct":
+ self = self.with_context(
+ skip_account_move_synchronization=True,
+ dont_redirect_to_payments=True,
+ )
+ return super().action_create_payments()
+
+ @api.constrains("deduction_ids", "payment_difference_handling")
+ def _check_deduction_amount(self):
+ prec_digits = self.env.user.company_id.currency_id.decimal_places
+ for rec in self:
+ if rec.payment_difference_handling == "reconcile_multi_deduct":
+ if (
+ float_compare(
+ rec.payment_difference,
+ sum(rec.deduction_ids.mapped("amount")),
+ precision_digits=prec_digits,
+ )
+ != 0
+ ):
+ raise UserError(
+ _("The total deduction should be %s") % rec.payment_difference
+ )
+
+ @api.depends("payment_difference", "deduction_ids")
+ def _compute_deduct_residual(self):
+ for rec in self:
+ rec.deduct_residual = rec.payment_difference - sum(
+ rec.deduction_ids.mapped("amount")
+ )
+
+ def _create_payment_vals_from_wizard(self):
+ payment_vals = super()._create_payment_vals_from_wizard()
+ if (
+ self.payment_difference
+ and self.payment_difference_handling == "reconcile_multi_deduct"
+ ):
+ payment_vals["write_off_line_vals"] = [
+ self._prepare_deduct_move_line(deduct)
+ for deduct in self.deduction_ids.filtered(lambda l: not l.open)
+ ]
+ return payment_vals
+
+ def _prepare_deduct_move_line(self, deduct):
+ return {
+ "name": deduct.name,
+ "amount": deduct.amount,
+ "account_id": deduct.account_id.id,
+ }
diff --git a/pool/shard003/Python/0028869_unpack_op_test.py b/pool/shard003/Python/0028869_unpack_op_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..4929af035ff66cd4911f9bd580f06c28113b58bc
--- /dev/null
+++ b/pool/shard003/Python/0028869_unpack_op_test.py
@@ -0,0 +1,56 @@
+"""Functional tests for Unpack Op."""
+import tensorflow.python.platform
+
+import numpy as np
+import tensorflow as tf
+
+from tensorflow.python.kernel_tests import gradient_checker
+
+
+class UnpackOpTest(tf.test.TestCase):
+
+ def testSimple(self):
+ np.random.seed(7)
+ for use_gpu in False, True:
+ with self.test_session(use_gpu=use_gpu):
+ for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
+ data = np.random.randn(*shape)
+ # Convert data to a single tensorflow tensor
+ x = tf.constant(data)
+ # Unpack into a list of tensors
+ cs = tf.unpack(x, num=shape[0])
+ self.assertEqual(type(cs), list)
+ self.assertEqual(len(cs), shape[0])
+ cs = [c.eval() for c in cs]
+ self.assertAllEqual(cs, data)
+
+ def testGradients(self):
+ for use_gpu in False, True:
+ for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
+ data = np.random.randn(*shape)
+ shapes = [shape[1:]] * shape[0]
+ for i in xrange(shape[0]):
+ with self.test_session(use_gpu=use_gpu):
+ x = tf.constant(data)
+ cs = tf.unpack(x, num=shape[0])
+ err = gradient_checker.ComputeGradientError(x, shape, cs[i],
+ shapes[i])
+ self.assertLess(err, 1e-6)
+
+ def testInferNum(self):
+ with self.test_session():
+ for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2):
+ x = tf.placeholder(np.float32, shape=shape)
+ cs = tf.unpack(x)
+ self.assertEqual(type(cs), list)
+ self.assertEqual(len(cs), shape[0])
+
+ def testCannotInferNum(self):
+ x = tf.placeholder(np.float32)
+ with self.assertRaisesRegexp(
+ ValueError, r'Cannot infer num from shape TensorShape\(None\)'):
+ tf.unpack(x)
+
+
+if __name__ == '__main__':
+ tf.test.main()
diff --git a/pool/shard003/Python/0028870_views.py b/pool/shard003/Python/0028870_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d43b166fe97928b39e1a2f336479d9f41023754
--- /dev/null
+++ b/pool/shard003/Python/0028870_views.py
@@ -0,0 +1,37 @@
+from django.shortcuts import render
+from django.http import JsonResponse, HttpResponse
+from django.core import serializers
+from django.views.decorators.csrf import csrf_exempt
+import urllib.request
+
+from .models import Result
+
+
+def assets(request, url):
+ url = str(url).replace("https://", "https:/").replace("https:/", "https://") # This is stupid
+ request = urllib.request.Request(url)
+ response = urllib.request.urlopen(request)
+ info = response.info()
+ return HttpResponse(response.read(), content_type=info.get_content_type())
+
+
+def liu_crawler(request):
+ return render(request, 'liu_crawler/liu_crawler.html')
+
+
+@csrf_exempt
+def add_result(request):
+ if request.method == 'POST':
+ try:
+ name = request.POST.get('name')
+ score = request.POST.get('score')
+ Result(name=name, score=score).save()
+ return JsonResponse({'success': True})
+ except:
+ pass
+ return JsonResponse({'success': False})
+
+
+@csrf_exempt
+def get_result(request):
+ return HttpResponse(serializers.serialize("json", Result.objects.all().order_by('-score')[0:10]), content_type='application/json')
diff --git a/pool/shard003/Python/0028873_model.py b/pool/shard003/Python/0028873_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..00862f0c70d5df175a33f4a7d4e05df70bdaa519
--- /dev/null
+++ b/pool/shard003/Python/0028873_model.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# Copyright (C) 2013 Agile Business Group sagl ()
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#
+##############################################################################
+
+from openerp.osv import orm, fields
+from openerp import SUPERUSER_ID
+from openerp.tools.translate import _
+
+
+class ir_model(orm.Model):
+ _inherit = 'ir.model'
+
+ _columns = {
+ 'avoid_quick_create': fields.boolean('Avoid quick create'),
+ }
+
+ def _wrap_name_create(self, old_create, model):
+ def wrapper(cr, uid, name, context=None):
+ raise orm.except_orm(
+ _('Error'),
+ _("Can't create quickly. Opening create form"))
+ return wrapper
+
+ def _register_hook(self, cr, ids=None):
+ if ids is None:
+ ids = self.search(cr, SUPERUSER_ID, [])
+ for model in self.browse(cr, SUPERUSER_ID, ids):
+ if model.avoid_quick_create:
+ model_name = model.model
+ model_obj = self.pool.get(model_name)
+ if model_obj and not hasattr(model_obj, 'check_quick_create'):
+ model_obj.name_create = self._wrap_name_create(
+ model_obj.name_create, model_name)
+ model_obj.check_quick_create = True
+ return True
+
+ def create(self, cr, uid, vals, context=None):
+ res_id = super(ir_model, self).create(cr, uid, vals, context=context)
+ self._register_hook(cr, [res_id])
+ return res_id
+
+ def write(self, cr, uid, ids, vals, context=None):
+ if isinstance(ids, (int, long)):
+ ids = [ids]
+ res = super(ir_model, self).write(cr, uid, ids, vals, context=context)
+ self._register_hook(cr, ids)
+ return res
diff --git a/pool/shard003/Python/0028874_settings.py b/pool/shard003/Python/0028874_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b98d94fa3509c94dbbc5b56f9801ab28f2bc2fe0
--- /dev/null
+++ b/pool/shard003/Python/0028874_settings.py
@@ -0,0 +1,117 @@
+from django.conf import settings
+from brushfire.core.exceptions import BrushfireConfigException
+from django.utils.importlib import import_module
+
+conf = getattr(settings, 'BRUSHFIRE', None)
+if conf is None:
+ raise BrushfireConfigException("`BRUSHFIRE` dict must be present in settings module")
+
+"""
+BRUSHFIRE = {
+ 'host': 'http://localhost:8080/solr',
+ 'cache': {
+ 'method': 'file', # or django
+ 'path': '/tmp/.cache', # if file
+ 'prefix': 'solrcache', # if django
+ },
+ 'cores': {
+ 'query': 'collection1',
+ 'index': 'collection2',
+ 'admin': '/admin/cores',
+ },
+ 'handlers': {
+ 'default': 'edismax',
+ 'custom': {
+ 'typename': 'handlername',
+ 'typename2': 'handlername2',
+ 'mlt': 'morelikethis',
+ },
+ },
+ 'index': {
+ 'method': 'dih', # or 'document add' -- not sure about this name
+ 'dih': {
+ 'handler': '/dataimport',
+ 'command': 'full-import',
+ 'clear': True,
+ 'swap_cores_on_complete': 'othercore',
+ },
+ },
+ 'query': {
+ 'fields': '*,score',
+ 'lparams': "{!edismax qf='text^2 name^100' bf='name'}",
+ 'rows': 20,
+ },
+}
+"""
+
+class Configuration(object):
+ def __init__(self, c):
+ self.c = c
+ self.__set('host')
+ self.__set('query_core', 'cores.query', False, '')
+ self.__set('default_handler', 'handlers.default', False, 'select')
+ self.__set('default_lparams', 'query.lparams', False, '')
+ self.set_query_cache()
+
+ def set_query_cache(self):
+ c = self.get('cache.method', False)
+ if c is None:
+ self.query_cache = None
+ else:
+ if c not in ('file', 'django'):
+ self.query_cache = import_module(c)()
+ elif c == 'file':
+ self.query_cache = self.get('cache.path')
+ elif c == 'django':
+ from django.core.cache import get_cache
+ self.query_cache = get_cache(self.get('cache.which', False, 'default'))
+
+ def __set(self, property, dict_key=None, required=True, default=None):
+ if dict_key is None:
+ dict_key = property
+ value = None
+ try:
+ value = self.get(dict_key, required, default)
+ except BrushfireConfigException as e:
+ if default is not None:
+ value = default
+ else:
+ raise
+ setattr(self, property, value)
+
+ def get(self, dict_key, required=True, default=None):
+ value = self.c
+ try:
+ keypath = dict_key.split('.')
+ for k in keypath:
+ value = value[k]
+ except KeyError:
+ if required:
+ setting_path = "BRUSHFIRE['" + "']['".join([x for x in dict_key.split('.')]) + "']"
+ raise BrushfireConfigException("%s is a required setting" % setting_path)
+ else:
+ return default
+ else:
+ return value
+
+ def set_solr(self, solr):
+ setattr(self, 'solr_connection', solr)
+
+
+ def configure_solr(self, solr):
+ self.solr_conn = solr(
+ server=self.host,
+ core=self.query_core,
+ query_handler=self.default_handler,
+ lparams=self.default_lparams,
+ cache=self.query_cache,
+ fields=self.get('query.fields', False, '*,score'),
+ rows=self.get('query.rows', False, 20),
+ )
+ return self.solr_conn
+
+configuration = Configuration(conf)
+
+if __name__ == '__main__':
+ c = Configuration(BRUSHFIRE)
+ import pdb; pdb.set_trace()
diff --git a/pool/shard003/Python/0028879_install.py b/pool/shard003/Python/0028879_install.py
new file mode 100644
index 0000000000000000000000000000000000000000..2da21542f4dfb36e2aede10cf04e988b48e3ee48
--- /dev/null
+++ b/pool/shard003/Python/0028879_install.py
@@ -0,0 +1,79 @@
+from __future__ import division, absolute_import, print_function
+
+import sys
+if 'setuptools' in sys.modules:
+ import setuptools.command.install as old_install_mod
+ have_setuptools = True
+else:
+ import distutils.command.install as old_install_mod
+ have_setuptools = False
+old_install = old_install_mod.install
+from distutils.file_util import write_file
+
+class install(old_install):
+
+ # Always run install_clib - the command is cheap, so no need to bypass it;
+ # but it's not run by setuptools -- so it's run again in install_data
+ sub_commands = old_install.sub_commands + [
+ ('install_clib', lambda x: True)
+ ]
+
+ def finalize_options (self):
+ old_install.finalize_options(self)
+ self.install_lib = self.install_libbase
+
+ def setuptools_run(self):
+ """ The setuptools version of the .run() method.
+
+ We must pull in the entire code so we can override the level used in the
+ _getframe() call since we wrap this call by one more level.
+ """
+ # Explicit request for old-style install? Just do it
+ if self.old_and_unmanageable or self.single_version_externally_managed:
+ return old_install_mod._install.run(self)
+
+ # Attempt to detect whether we were called from setup() or by another
+ # command. If we were called by setup(), our caller will be the
+ # 'run_command' method in 'distutils.dist', and *its* caller will be
+ # the 'run_commands' method. If we were called any other way, our
+ # immediate caller *might* be 'run_command', but it won't have been
+ # called by 'run_commands'. This is slightly kludgy, but seems to
+ # work.
+ #
+ caller = sys._getframe(3)
+ caller_module = caller.f_globals.get('__name__', '')
+ caller_name = caller.f_code.co_name
+
+ if caller_module != 'distutils.dist' or caller_name!='run_commands':
+ # We weren't called from the command line or setup(), so we
+ # should run in backward-compatibility mode to support bdist_*
+ # commands.
+ old_install_mod._install.run(self)
+ else:
+ self.do_egg_install()
+
+ def run(self):
+ if not have_setuptools:
+ r = old_install.run(self)
+ else:
+ r = self.setuptools_run()
+ if self.record:
+ # bdist_rpm fails when INSTALLED_FILES contains
+ # paths with spaces. Such paths must be enclosed
+ # with double-quotes.
+ f = open(self.record, 'r')
+ lines = []
+ need_rewrite = False
+ for l in f:
+ l = l.rstrip()
+ if ' ' in l:
+ need_rewrite = True
+ l = '"%s"' % (l)
+ lines.append(l)
+ f.close()
+ if need_rewrite:
+ self.execute(write_file,
+ (self.record, lines),
+ "re-writing list of installed files to '%s'" %
+ self.record)
+ return r
diff --git a/pool/shard003/Python/0028880_Utilities.py b/pool/shard003/Python/0028880_Utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..64210eea3b8d316480aabf40f32820fdc64ea351
--- /dev/null
+++ b/pool/shard003/Python/0028880_Utilities.py
@@ -0,0 +1,163 @@
+"""Utilities used by the documentation scripts."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from __future__ import absolute_import
+
+from builtins import open
+
+import atexit
+import os
+import re
+import sys
+import shlex
+import logging
+import subprocess32 as subprocess
+
+
+LOG = logging.getLogger(__name__)
+
+
+def mkdir(folder):
+ """Create a folder, ignore if it exists.
+
+ :param str folder: folder to create
+ """
+ try:
+ folder = os.path.join(os.getcwd(), folder)
+ os.mkdir(folder)
+ except OSError as e:
+ LOG.debug("Exception when creating folder %s: %r", folder, e)
+
+
+def writeLinesToFile(filename, lines):
+ """Write a list of lines into a file.
+
+ Checks that there are actual changes to be done.
+
+ :param str filename: name of the files
+ :param list lines: list of lines to write to the file
+ """
+ if isinstance(lines, list):
+ newContent = "\n".join(lines)
+ else:
+ newContent = lines
+ oldContent = None
+ if os.path.exists(filename):
+ with open(filename, "r") as oldFile:
+ oldContent = "".join(oldFile.readlines())
+ # try creating the directory in case it is not there
+ # and filename is an absolute path
+ elif os.path.isabs(filename):
+ try:
+ os.makedirs(os.path.dirname(filename))
+ # the directory may already exist
+ except OSError:
+ LOG.debug("Cannot create directory %s", os.path.dirname(filename))
+ if oldContent is None or oldContent != newContent:
+ with open(filename, "w") as rst:
+ LOG.info("Writing new content for %s", os.path.join(os.getcwd(), filename))
+ try: # decode only needed/possible in python2
+ newContent = newContent.decode("utf-8")
+ except AttributeError:
+ # ignore decode if newContent is python3 str
+ pass
+ except (UnicodeDecodeError) as e:
+ LOG.error('Failed to decode newContent with "utf-8": %r', e)
+ raise
+ rst.write(newContent)
+ else:
+ LOG.debug("Not updating file content for %s", os.path.join(os.getcwd(), filename))
+
+
+def setUpReadTheDocsEnvironment(moduleName="DIRAC", location="../../"):
+ """Create the necessary links and environment variables to create documentation inside readthedocs.
+
+ Ensure that ``moduleName`` is in the PYTHONPATH by creating a link pointing to the basefolder of the source code.
+
+ :param str moduleName: name of the base source code module, default 'DIRAC'
+ :param str location: Path to the location where the module can be found relative to the 'conf.py'. Default '../../'
+ """
+ LOG.info("Running for READTHEDOCS")
+ sys.path.append(os.path.abspath("."))
+ diracPath = os.path.abspath(os.path.join(os.getcwd(), location))
+ LOG.info("Path To Module(?): %r", diracPath)
+
+ buildfolder = "_build"
+ mkdir(os.path.abspath("../" + buildfolder))
+
+ # We need to have the moduleName somewhere, or we cannot import it, as
+ # readtheDocs clones the repo into something based on the branchname
+ if not os.path.exists(os.path.join(location, moduleName)):
+ diracLink = os.path.abspath(os.path.join(os.getcwd(), "../", buildfolder, moduleName))
+ LOG.info("Link: %r", diracLink)
+ if not os.path.exists(diracLink):
+ LOG.info("Creating symbolic link %r -> %r", diracPath, diracLink)
+ os.symlink(diracPath, diracLink)
+ diracPath = os.path.abspath(os.path.join(diracLink, ".."))
+
+ sys.path.insert(0, diracPath)
+
+ for path in sys.path:
+ LOG.info("Adding locations to PYTHONPATH: %r", path)
+ os.environ["PYTHONPATH"] = os.environ.get("PYTHONPATH", "") + ":" + path
+
+ os.environ["DIRAC"] = diracPath
+ LOG.info("DIRAC ENVIRON: %r", os.environ["DIRAC"])
+
+
+def runCommand(command):
+ """Execute shell command, return output, catch exceptions."""
+ try:
+ result = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT, universal_newlines=True)
+ if "NOTICE:" in result:
+ lines = []
+ LOG.warning("NOTICE in output for: %s; cleaning output from datestamp..", command)
+ for line in result.split("\n"):
+ lines.append(re.sub(r"^.*NOTICE: ", "", line))
+ # if the output is less than 3 lines something went wrong
+ result = "\n".join(lines) if len(lines) > 2 else ""
+ return result
+ except (OSError, subprocess.CalledProcessError) as e:
+ LOG.error("Error when runnning command %s: %r", command, getattr(e, "output", None))
+ return ""
+
+
+def makeLogger(name):
+ """Create a logger and return instance."""
+ logging.basicConfig(level=logging.INFO, format="%(name)25s: %(levelname)8s: %(message)s", stream=sys.stdout)
+ return logging.getLogger(name)
+
+
+def registerValidatingExitHandler():
+ """Registers an exit handler which checks for errors after the build completes"""
+
+ def check():
+ outputDir = "build/html"
+ for arg in sys.argv:
+ if arg.endswith("/html"):
+ outputDir = arg
+ LOG.info("Found outputDir as %s", outputDir)
+ break
+ cmd = [
+ "grep",
+ "--color",
+ "-nH",
+ "-e",
+ " :param", # :param: is a legit thing that happens,
+ "-e",
+ ":param ", # so we look for space before or after
+ "-e",
+ ":return",
+ "-r",
+ os.path.join(outputDir, "CodeDocumentation"),
+ ]
+ ret = subprocess.run(cmd, check=False)
+ if ret.returncode != 1:
+ print("Return code from {} was {}".format(" ".join(cmd), ret.returncode))
+ print("This means :param or :return in the html and points to faulty " "syntax, missing empty lines, etc.")
+ # https://bugs.python.org/issue27035
+ os._exit(1) # pylint: disable=protected-access
+
+ atexit.register(check)
diff --git a/pool/shard003/Python/0028891_fqueue.py b/pool/shard003/Python/0028891_fqueue.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bb0899dfe6065491f3342d4fe6d26a47377182d
--- /dev/null
+++ b/pool/shard003/Python/0028891_fqueue.py
@@ -0,0 +1,250 @@
+from __future__ import absolute_import, unicode_literals, print_function
+
+import os
+import time
+import zlib
+
+import fcntl
+from contextlib import contextmanager
+import posix_ipc
+import sysv_ipc
+
+import Queue
+import marshal
+
+import logging
+logger = logging.getLogger(__name__)
+
+
+# Try to use a semaphore that supports timeout natively
+if sysv_ipc.SEMAPHORE_TIMEOUT_SUPPORTED or posix_ipc.SEMAPHORE_TIMEOUT_SUPPORTED:
+ if sysv_ipc.SEMAPHORE_TIMEOUT_SUPPORTED:
+ IPC_CREAT = sysv_ipc.IPC_CREAT
+ BusyError = sysv_ipc.BusyError
+ Semaphore = sysv_ipc.Semaphore
+ sem_hash = hash
+ else:
+ IPC_CREAT = posix_ipc.O_CREAT
+ BusyError = posix_ipc.BusyError
+ Semaphore = posix_ipc.Semaphore
+ sem_hash = lambda x: b'/%s%s' % (hash(x) & 0xffffffff, hash(x) >> 32 & 0xffffffff)
+
+ def acquire(sem, timeout=None):
+ return sem.acquire(timeout)
+else:
+ IPC_CREAT = sysv_ipc.IPC_CREAT
+ BusyError = sysv_ipc.BusyError
+ Semaphore = sysv_ipc.Semaphore
+ sem_hash = hash
+
+ def acquire(sem, timeout=None):
+ start = time.time()
+ block = sem.block
+ if timeout is None:
+ sleep = 0
+ sem.block = True
+ else:
+ sleep = min(max(timeout / 5.0, 0.5), 2.0)
+ sem.block = False
+ try:
+ while not timeout or time.time() - start < timeout:
+ try:
+ return sem.acquire(timeout)
+ except BusyError:
+ if not timeout or sem.block:
+ raise
+ _sleep = min(max(0, timeout - time.time() + start), sleep)
+ time.sleep(_sleep)
+ raise BusyError
+ finally:
+ sem.block = block
+
+
+@contextmanager
+def flock(fd):
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ try:
+ yield fd
+ finally:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+
+
+class FileQueue(object):
+ STOPPED = False
+
+ shm_size = len(marshal.dumps((0, 0, 0)))
+ bucket_size = 10 * 1024 * 1024 # 10MB
+ sync_age = 500
+
+ def __init__(self, name=None, log=None):
+ self.name = name
+ self.log = log or logger
+
+ semname = self.name
+ self.sem = Semaphore(sem_hash(b'%s.sem' % semname), IPC_CREAT, initial_value=1)
+ self.lock = Semaphore(sem_hash(b'%s.lock' % semname), IPC_CREAT, initial_value=1)
+ self.spos = sysv_ipc.SharedMemory(hash(b'%s.spos' % semname), sysv_ipc.IPC_CREAT, size=self.shm_size)
+
+ fnamepos = '%s.pos' % self.name
+ if not os.path.exists(fnamepos):
+ empty = marshal.dumps((0, 0, 0))
+ self.spos.write(empty) # clean memory
+ with open(fnamepos, 'wb') as f: # touch file
+ f.write(empty)
+
+ self.fpos = open(fnamepos, 'r+b')
+
+ self.fread = None
+ self.frnum = None
+
+ self.fwrite = None
+ self.fwnum = None
+
+ frnum, _ = self._update_pos()
+ self._open_write(frnum)
+
+ def _update_pos(self, fnum=None, offset=None):
+ with flock(self.fpos) as fpos:
+ fpos.seek(0)
+ try:
+ _fnum, _offset = marshal.load(fpos)
+ except (EOFError, ValueError, TypeError):
+ _fnum, _offset = 0, 0 # New, perhaps empty or corrupt pos file
+ finally:
+ if fnum is not None and offset is not None:
+ fpos.seek(0)
+ marshal.dump((fnum, offset), fpos)
+ fpos.flush()
+ os.fsync(fpos.fileno())
+ return _fnum, _offset
+
+ def _cleanup(self, fnum):
+ """
+ Deletes all files for the queue up to, and including, fnum.
+
+ """
+ while os.path.exists('%s.%s' % (self.name, fnum)):
+ try:
+ fname = '%s.%s' % (self.name, fnum)
+ os.unlink(fname)
+ # self.log.debug("Cleaned up file: %s", fname)
+ except:
+ pass
+ fnum -= 1
+
+ def _open_read(self, frnum):
+ if self.frnum == frnum:
+ return
+ if self.fread:
+ self.fread.close()
+ fname = '%s.%s' % (self.name, frnum)
+ if not os.path.exists(fname):
+ open(fname, 'wb').close() # touch file
+ self.fread = open(fname, 'rb')
+ self.frnum = frnum
+ # self.log.debug("New read bucket: %s", self.frnum)
+
+ def _open_write(self, fwnum):
+ _fwnum = fwnum
+ while os.path.exists('%s.%s' % (self.name, _fwnum)):
+ fwnum = _fwnum
+ _fwnum += 1
+ if self.fwnum == fwnum:
+ return
+ if self.fwrite:
+ self.fwrite.close()
+ self.fwrite = open('%s.%s' % (self.name, fwnum), 'ab')
+ self.fwnum = fwnum
+ # self.log.debug("New write bucket: %s", self.fwnum)
+
+ def __del__(self):
+ self.fpos.close()
+ if self.fwrite:
+ self.fwrite.close()
+ if self.fread:
+ self.fread.close()
+
+ def get(self, block=True, timeout=None):
+ while True:
+ try:
+ # Try acquiring the semaphore (in case there's something to read)
+ acquire(self.sem, block and timeout or 0)
+ except BusyError:
+ raise Queue.Empty
+ try:
+ acquire(self.lock, 5)
+ except BusyError:
+ if self.STOPPED:
+ raise Queue.Empty
+ raise
+ try:
+ # Get nest file/offset (from shared memory):
+ try:
+ frnum, offset, age = marshal.loads(self.spos.read())
+ except (EOFError, ValueError, TypeError):
+ # New, perhaps empty or corrupt pos file
+ frnum, offset = self._update_pos()
+ age = 0
+ # self.log.debug('%s @ %s' % (self.name, repr((frnum, offset, age))))
+
+ # Open proper queue file for reading (if it isn't open yet):
+ self._open_read(frnum)
+ self.fread.seek(offset)
+
+ # Read from the queue
+ try:
+ crc32, value = marshal.load(self.fread)
+ if crc32 != zlib.crc32(value):
+ raise ValueError
+ except EOFError:
+ pass # The file could not be read, ignore
+ except (ValueError, TypeError):
+ # New, perhaps empty or corrupt pos file (since the position offset has an invalid marshal)
+ frnum, offset = self._update_pos()
+ age = 0
+ else:
+ offset = self.fread.tell()
+ if offset > self.bucket_size:
+ self._cleanup(frnum - 1)
+ self._open_read(frnum + 1)
+ age = self.sync_age # Force updateing position
+ offset = 0
+ peek = self.fread.read(1)
+ if len(peek):
+ # If there's something more to read in the file,
+ # release (or re-release) the semaphore.
+ self.sem.release()
+ break
+ finally:
+ # Update position
+ if age >= self.sync_age:
+ self._update_pos(self.frnum, offset)
+ age = 0
+ self.spos.write(marshal.dumps((self.frnum, offset, age + 1)))
+
+ finally:
+ self.lock.release()
+
+ return value and marshal.loads(zlib.decompress(value))
+
+ def put(self, value, block=True, timeout=None):
+ value = zlib.compress(marshal.dumps(value))
+ crc32 = zlib.crc32(value)
+ with flock(self.fwrite) as fwrite:
+ marshal.dump((crc32, value), fwrite)
+ fwrite.flush()
+ os.fsync(fwrite.fileno())
+ offset = fwrite.tell()
+ self.sem.release()
+ if offset > self.bucket_size:
+ # Switch to a new queue file:
+ self._open_write(self.fwnum + 1)
+
+
+# def main(argv):
+# queue = FileQueue('/tmp/testing')
+# queue.put('TEST')
+# queue.get()
+
+# if __name__ == '__main__':
+# main(sys.argv)
diff --git a/pool/shard003/Python/0028894_DistinctSubserquences.py b/pool/shard003/Python/0028894_DistinctSubserquences.py
new file mode 100644
index 0000000000000000000000000000000000000000..002cd62947e11e48c1311baf298e326a97995b75
--- /dev/null
+++ b/pool/shard003/Python/0028894_DistinctSubserquences.py
@@ -0,0 +1,18 @@
+class Solution:
+ def numDistinct(self, s: str, t: str) -> int:
+ dp = []
+ dp.append([1] * (len(s) + 1))
+ for i in range(len(t)):
+ dp.append([0] * (len(s) + 1))
+
+ for i in range(1, len(t) + 1):
+ for j in range(1, len(s) + 1):
+ dp[i][j] = dp[i][j-1]
+ if s[j-1] == t[i-1]:
+ dp[i][j] += dp[i-1][j-1]
+ return dp[len(t)][len(s)]
+
+ob = Solution()
+s = "rabbbit"
+t = "rabbit"
+print(ob.numDistinct(t, s))
\ No newline at end of file
diff --git a/pool/shard003/Python/0028898_setup.py b/pool/shard003/Python/0028898_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9f973798ad5a8ae6ee5fecef8b7e97e73bf1aa3
--- /dev/null
+++ b/pool/shard003/Python/0028898_setup.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+# Always prefer setuptools over distutils
+from setuptools import setup, find_packages
+from codecs import open
+from os import path
+
+here = path.abspath(path.dirname(__file__))
+
+with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
+ long_description = f.read()
+
+setup(name='etcdwatch',
+ version='0.3',
+ description='Program to run a command whenever etcd registry changes',
+ long_description=long_description,
+ author='Santeri Paavolainen',
+ author_email='santtu@iki.fi',
+ license='MIT',
+ url='https://github.com/santtu/etcdwatch',
+ packages=find_packages(exclude=['tests']),
+ classifiers=[
+ 'Development Status :: 3 - Alpha',
+ 'License :: OSI Approved :: MIT License',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5'
+ ],
+
+ install_requires=[
+ 'pyyaml',
+ 'python-etcd'
+ ],
+
+ entry_points={
+ 'console_scripts': [
+ 'etcdwatch=etcdwatch:main',
+ ],
+ })
diff --git a/pool/shard003/Python/0028901_test_rest_bridge.py b/pool/shard003/Python/0028901_test_rest_bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb8cd2ec29bc649e75115e87d05abab44dc230a0
--- /dev/null
+++ b/pool/shard003/Python/0028901_test_rest_bridge.py
@@ -0,0 +1,27 @@
+"""
+
+"""
+import os
+import tempfile
+import unittest
+
+import jiracli
+from jiracli.bridge import JiraRestBridge
+from jiracli.utils import Config
+from .common_bridge_cases import BridgeTests, jiravcr
+
+
+class RestBridgeTests(unittest.TestCase, BridgeTests):
+ def setUp(self):
+ tmp_config = tempfile.mktemp()
+ self.config = Config(tmp_config)
+ jiracli.utils.CONFIG_FILE = tmp_config
+ self.cache_dir = tempfile.mkdtemp()
+ jiracli.cache.CACHE_DIR = self.cache_dir
+ self.config.username = "testuser"
+ self.config.password = "testpassword"
+ self.vcr_directory = "fixtures/rest"
+ with jiravcr.use_cassette(os.path.join(self.vcr_directory, "login.yaml")):
+ self.bridge = JiraRestBridge("https://indydevs.atlassian.net",
+ self.config)
+ self.bridge.login(self.config.username, self.config.password)
diff --git a/pool/shard003/Python/0028902_printer.py b/pool/shard003/Python/0028902_printer.py
new file mode 100644
index 0000000000000000000000000000000000000000..c294b7f255e8ae06c53a5ed8a10780c41f221ab2
--- /dev/null
+++ b/pool/shard003/Python/0028902_printer.py
@@ -0,0 +1,97 @@
+from collections import OrderedDict
+from lxml import builder, etree
+from termcolor import colored
+
+from wscheck.checker import RULES
+
+BUILD = builder.ElementMaker()
+
+
+class ErrorPrinter(object):
+ def __init__(self, files, issues):
+ """
+ :type files: list
+ :type issues: list
+ """
+ self._files = sorted(files)
+ self._issues = sorted(issues, key=lambda issue: (issue['path'], issue['line'], issue['col']))
+
+ def print_to_tty(self, colored_output):
+ """
+ :type colored_output: bool
+ """
+ glue_text = ''
+
+ for issue in self._issues:
+ context = issue['context']
+ message_indent = issue['col'] - 1
+ message = self._get_message(issue)
+
+ index = 0
+ while index >= 0:
+ index = context.find('\t', index)
+ if index == -1:
+ break
+
+ context = '{}--->{}'.format(context[:index], context[index + 1:])
+ if index < message_indent:
+ message_indent += 3
+
+ index += 4
+
+ position = 'In {path} line {row}:'.format(
+ path=issue['path'],
+ row=issue['line']
+ )
+ message = '^-- {}: {}'.format(issue['rule'], message)
+
+ if colored_output:
+ position = colored(position, attrs=['bold'])
+ message = colored(message, color='yellow')
+
+ print('{glue}{position}\n{context}\n{message_indent}{message}'.format(
+ glue=glue_text,
+ position=position,
+ context=context,
+ message_indent=' ' * message_indent,
+ message=message
+ ))
+
+ glue_text = '\n'
+
+ def _get_message(self, issue):
+ """
+ :type issue: dict
+ :rtype: str
+ """
+ message = RULES[issue['rule']]
+ if issue['message_suffix']:
+ message = '{} {}'.format(message, issue['message_suffix'])
+ return message
+
+ def write_checkstyle(self, file_path):
+ """
+ :type file_path: str
+ """
+ file_elements = OrderedDict(
+ (path, BUILD.file(name=path))
+ for path in sorted(self._files, key=lambda path: path.lower())
+ )
+
+ for issue in self._issues:
+ file_elements[issue['path']].append(
+ BUILD.error(
+ line='{}'.format(issue['line']),
+ column='{}'.format(issue['col']),
+ severity='warning',
+ message=self._get_message(issue),
+ source='WhitespaceCheck.{}'.format(issue['rule'])
+ )
+ )
+
+ checkstyle_element = BUILD.checkstyle(version='4.3')
+ for file_element in file_elements.values():
+ checkstyle_element.append(file_element)
+ tree = etree.ElementTree(checkstyle_element)
+
+ tree.write(file_path, encoding='utf-8', xml_declaration=True, pretty_print=True)
diff --git a/pool/shard003/Python/0028903_date_utils.py b/pool/shard003/Python/0028903_date_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d9ff086746c1741196798e4d0d84c210116cc41
--- /dev/null
+++ b/pool/shard003/Python/0028903_date_utils.py
@@ -0,0 +1,397 @@
+"""
+Convenience methods for working with datetime objects
+"""
+
+import re
+from datetime import datetime, timedelta
+
+from django.utils.translation import pgettext, ugettext
+from pytz import UnknownTimeZoneError, timezone, utc
+
+
+def get_default_time_display(dtime):
+ """
+ Converts a datetime to a string representation. This is the default
+ representation used in Studio and LMS.
+
+ It will use the "DATE_TIME" format in the current language, if provided,
+ or defaults to "Apr 09, 2013 at 16:00 UTC".
+
+ If None is passed in for dt, an empty string will be returned.
+
+ """
+ if dtime is None:
+ return u""
+ if dtime.tzinfo is not None:
+ try:
+ timezone = u" " + dtime.tzinfo.tzname(dtime)
+ except NotImplementedError:
+ timezone = dtime.strftime('%z')
+ else:
+ timezone = u" UTC"
+
+ localized = strftime_localized(dtime, "DATE_TIME")
+ return (localized + timezone).strip()
+
+
+def get_time_display(dtime, format_string=None, coerce_tz=None):
+ """
+ Converts a datetime to a string representation.
+
+ If None is passed in for dt, an empty string will be returned.
+
+ If the format_string is None, or if format_string is improperly
+ formatted, this method will return the value from `get_default_time_display`.
+
+ Coerces aware datetime to tz=coerce_tz if set. coerce_tz should be a pytz timezone string
+ like "US/Pacific", or None
+
+ format_string should be a unicode string that is a valid argument for datetime's strftime method.
+ """
+ if dtime is not None and dtime.tzinfo is not None and coerce_tz:
+ try:
+ to_tz = timezone(coerce_tz)
+ except UnknownTimeZoneError:
+ to_tz = utc
+ dtime = to_tz.normalize(dtime.astimezone(to_tz))
+ if dtime is None or format_string is None:
+ return get_default_time_display(dtime)
+ try:
+ return unicode(strftime_localized(dtime, format_string))
+ except ValueError:
+ return get_default_time_display(dtime)
+
+
+def almost_same_datetime(dt1, dt2, allowed_delta=timedelta(minutes=1)):
+ """
+ Returns true if these are w/in a minute of each other. (in case secs saved to db
+ or timezone aren't same)
+
+ :param dt1:
+ :param dt2:
+ """
+ return abs(dt1 - dt2) < allowed_delta
+
+
+def to_timestamp(datetime_value):
+ """
+ Convert a datetime into a timestamp, represented as the number
+ of seconds since January 1, 1970 UTC.
+ """
+ return int((datetime_value - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())
+
+
+def from_timestamp(timestamp):
+ """
+ Convert a timestamp (number of seconds since Jan 1, 1970 UTC)
+ into a timezone-aware datetime.
+
+ If the timestamp cannot be converted, returns None instead.
+ """
+ try:
+ return datetime.utcfromtimestamp(int(timestamp)).replace(tzinfo=utc)
+ except (ValueError, TypeError):
+ return None
+
+
+DEFAULT_SHORT_DATE_FORMAT = "%b %d, %Y"
+DEFAULT_LONG_DATE_FORMAT = "%A, %B %d, %Y"
+DEFAULT_TIME_FORMAT = "%I:%M:%S %p"
+DEFAULT_DATE_TIME_FORMAT = "%b %d, %Y at %H:%M"
+DEFAULT_DAY_AND_TIME_FORMAT = "%A at %-I%P"
+
+
+def strftime_localized(dtime, format): # pylint: disable=redefined-builtin
+ """
+ Format a datetime, just like the built-in strftime, but with localized words.
+
+ The format string can also be one of:
+
+ * "SHORT_DATE" for a date in brief form, localized.
+
+ * "LONG_DATE" for a longer form of date, localized.
+
+ * "DATE_TIME" for a date and time together, localized.
+
+ * "TIME" for just the time, localized.
+
+ The localization is based on the current language Django is using for the
+ request. The exact format strings used for each of the names above is
+ determined by the translator for each language.
+
+ Args:
+ dtime (datetime): The datetime value to format.
+
+ format (str): The format string to use, as specified by
+ :ref:`datetime.strftime`.
+
+ Returns:
+ A unicode string with the formatted datetime.
+
+ """
+
+ if format == "SHORT_DATE":
+ format = "%x"
+ elif format == "LONG_DATE":
+ # Translators: the translation for "LONG_DATE_FORMAT" must be a format
+ # string for formatting dates in a long form. For example, the
+ # American English form is "%A, %B %d %Y".
+ # See http://strftime.org for details.
+ format = ugettext("LONG_DATE_FORMAT")
+ if format == "LONG_DATE_FORMAT":
+ format = DEFAULT_LONG_DATE_FORMAT
+ elif format == "DATE_TIME":
+ # Translators: the translation for "DATE_TIME_FORMAT" must be a format
+ # string for formatting dates with times. For example, the American
+ # English form is "%b %d, %Y at %H:%M".
+ # See http://strftime.org for details.
+ format = ugettext("DATE_TIME_FORMAT")
+ if format == "DATE_TIME_FORMAT":
+ format = DEFAULT_DATE_TIME_FORMAT
+ elif format == "DAY_AND_TIME":
+ format = DEFAULT_DAY_AND_TIME_FORMAT
+ elif format == "TIME":
+ format = "%X"
+
+ def process_percent_code(match):
+ """
+ Convert one percent-prefixed code in the format string.
+
+ Called by re.sub just below.
+
+ """
+ code = match.group()
+ if code == "%":
+ # This only happens if the string ends with a %, which is not legal.
+ raise ValueError("strftime format ends with raw %")
+
+ if code == "%a":
+ part = pgettext('abbreviated weekday name', WEEKDAYS_ABBREVIATED[dtime.weekday()])
+ elif code == "%A":
+ part = pgettext('weekday name', WEEKDAYS[dtime.weekday()])
+ elif code == "%b":
+ part = pgettext('abbreviated month name', MONTHS_ABBREVIATED[dtime.month])
+ elif code == "%B":
+ part = pgettext('month name', MONTHS[dtime.month])
+ elif code == "%p":
+ part = pgettext('am/pm indicator', AM_PM[dtime.hour // 12])
+ elif code == "%x":
+ # Get the localized short date format, and recurse.
+ # Translators: the translation for "SHORT_DATE_FORMAT" must be a
+ # format string for formatting dates in a brief form. For example,
+ # the American English form is "%b %d %Y".
+ # See http://strftime.org for details.
+ actual_format = ugettext("SHORT_DATE_FORMAT")
+ if actual_format == "SHORT_DATE_FORMAT":
+ actual_format = DEFAULT_SHORT_DATE_FORMAT
+ if "%x" in actual_format:
+ # Prevent infinite accidental recursion.
+ actual_format = DEFAULT_SHORT_DATE_FORMAT
+ part = strftime_localized(dtime, actual_format)
+ elif code == "%X":
+ # Get the localized time format, and recurse.
+ # Translators: the translation for "TIME_FORMAT" must be a format
+ # string for formatting times. For example, the American English
+ # form is "%H:%M:%S". See http://strftime.org for details.
+ actual_format = ugettext("TIME_FORMAT")
+ if actual_format == "TIME_FORMAT":
+ actual_format = DEFAULT_TIME_FORMAT
+ if "%X" in actual_format:
+ # Prevent infinite accidental recursion.
+ actual_format = DEFAULT_TIME_FORMAT
+ part = strftime_localized(dtime, actual_format)
+ else:
+ # All the other format codes: just let built-in strftime take
+ # care of them.
+ part = dtime.strftime(code)
+
+ return part
+
+ formatted_date = re.sub(r"%-.|%.|%", process_percent_code, format)
+ return formatted_date
+
+
+# In order to extract the strings below, we have to mark them with pgettext.
+# But we'll do the actual pgettext later, so use a no-op for now, and save the
+# real pgettext so we can assign it back to the global name later.
+real_pgettext = pgettext
+pgettext = lambda context, text: text # pylint: disable=invalid-name
+
+AM_PM = {
+ # Translators: This is an AM/PM indicator for displaying times. It is
+ # used for the %p directive in date-time formats. See http://strftime.org
+ # for details.
+ 0: pgettext('am/pm indicator', 'AM'),
+ # Translators: This is an AM/PM indicator for displaying times. It is
+ # used for the %p directive in date-time formats. See http://strftime.org
+ # for details.
+ 1: pgettext('am/pm indicator', 'PM'),
+}
+
+WEEKDAYS = {
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Monday Februrary 10, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 0: pgettext('weekday name', 'Monday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Tuesday Februrary 11, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 1: pgettext('weekday name', 'Tuesday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Wednesday Februrary 12, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 2: pgettext('weekday name', 'Wednesday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Thursday Februrary 13, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 3: pgettext('weekday name', 'Thursday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Friday Februrary 14, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 4: pgettext('weekday name', 'Friday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Saturday Februrary 15, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 5: pgettext('weekday name', 'Saturday'),
+ # Translators: this is a weekday name that will be used when displaying
+ # dates, as in "Sunday Februrary 16, 2014". It is used for the %A
+ # directive in date-time formats. See http://strftime.org for details.
+ 6: pgettext('weekday name', 'Sunday'),
+}
+
+WEEKDAYS_ABBREVIATED = {
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Mon Feb 10, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 0: pgettext('abbreviated weekday name', 'Mon'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Tue Feb 11, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 1: pgettext('abbreviated weekday name', 'Tue'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Wed Feb 12, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 2: pgettext('abbreviated weekday name', 'Wed'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Thu Feb 13, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 3: pgettext('abbreviated weekday name', 'Thu'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Fri Feb 14, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 4: pgettext('abbreviated weekday name', 'Fri'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Sat Feb 15, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 5: pgettext('abbreviated weekday name', 'Sat'),
+ # Translators: this is an abbreviated weekday name that will be used when
+ # displaying dates, as in "Sun Feb 16, 2014". It is used for the %a
+ # directive in date-time formats. See http://strftime.org for details.
+ 6: pgettext('abbreviated weekday name', 'Sun'),
+}
+
+MONTHS_ABBREVIATED = {
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Jan 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 1: pgettext('abbreviated month name', 'Jan'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Feb 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 2: pgettext('abbreviated month name', 'Feb'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Mar 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 3: pgettext('abbreviated month name', 'Mar'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Apr 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 4: pgettext('abbreviated month name', 'Apr'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "May 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 5: pgettext('abbreviated month name', 'May'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Jun 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 6: pgettext('abbreviated month name', 'Jun'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Jul 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 7: pgettext('abbreviated month name', 'Jul'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Aug 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 8: pgettext('abbreviated month name', 'Aug'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Sep 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 9: pgettext('abbreviated month name', 'Sep'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Oct 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 10: pgettext('abbreviated month name', 'Oct'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Nov 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 11: pgettext('abbreviated month name', 'Nov'),
+ # Translators: this is an abbreviated month name that will be used when
+ # displaying dates, as in "Dec 10, 2014". It is used for the %b
+ # directive in date-time formats. See http://strftime.org for details.
+ 12: pgettext('abbreviated month name', 'Dec'),
+}
+
+MONTHS = {
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "January 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 1: pgettext('month name', 'January'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "February 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 2: pgettext('month name', 'February'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "March 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 3: pgettext('month name', 'March'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "April 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 4: pgettext('month name', 'April'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "May 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 5: pgettext('month name', 'May'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "June 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 6: pgettext('month name', 'June'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "July 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 7: pgettext('month name', 'July'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "August 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 8: pgettext('month name', 'August'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "September 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 9: pgettext('month name', 'September'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "October 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 10: pgettext('month name', 'October'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "November 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 11: pgettext('month name', 'November'),
+ # Translators: this is a month name that will be used when displaying
+ # dates, as in "December 10, 2014". It is used for the %B directive in
+ # date-time formats. See http://strftime.org for details.
+ 12: pgettext('month name', 'December'),
+}
+
+# Now that we are done defining constants, we have to restore the real pgettext
+# so that the functions in this module will have the right definition.
+pgettext = real_pgettext
diff --git a/pool/shard003/Python/0028907_0007_auto_20170307_1859.py b/pool/shard003/Python/0028907_0007_auto_20170307_1859.py
new file mode 100644
index 0000000000000000000000000000000000000000..31d06791f471c5dc9958af75bc2c1dfb691b49fe
--- /dev/null
+++ b/pool/shard003/Python/0028907_0007_auto_20170307_1859.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.1 on 2017-03-07 18:59
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('interactive_shocks', '0006_settings_prompt_sound_interval'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='survey',
+ name='bugs',
+ field=models.TextField(null=True),
+ ),
+ migrations.AddField(
+ model_name='survey',
+ name='education',
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ migrations.AddField(
+ model_name='survey',
+ name='pay',
+ field=models.TextField(null=True),
+ ),
+ ]
diff --git a/pool/shard003/Python/0028910_code.py b/pool/shard003/Python/0028910_code.py
new file mode 100644
index 0000000000000000000000000000000000000000..34a40510a48ea8e13c31546b4ad22bb683a14ea1
--- /dev/null
+++ b/pool/shard003/Python/0028910_code.py
@@ -0,0 +1,14 @@
+#!/usr/bin/env python3
+import os
+import sys
+
+from subprocess import call
+
+cur_dir = os.path.dirname(os.path.realpath(__file__))
+
+if sys.argv[1] == "e":
+ call(sys.executable + ' "' + os.path.join(cur_dir, "encode.py") + '"' + " " + sys.argv[2], shell=True)
+elif sys.argv[1] == "d":
+ call(sys.executable + ' "' + os.path.join(cur_dir, "decode.py") + '"' + " " + sys.argv[2], shell=True)
+else:
+ print("Unknown")
diff --git a/pool/shard003/Python/0028916_batch-sqlite-query.py b/pool/shard003/Python/0028916_batch-sqlite-query.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0bb5ee6db67b1e73cc55c9294801c402a699355
--- /dev/null
+++ b/pool/shard003/Python/0028916_batch-sqlite-query.py
@@ -0,0 +1,22 @@
+import sys
+import os
+import sqlite3
+from Bio import SeqIO
+
+
+def main(argv):
+
+ # Put stuff in JSON config file
+ sqliteDB = '../datasets/testseq'
+ conn = sqlite3.connect( sqliteDB )
+
+ c = conn.cursor()
+ # Create table
+ for row in c.execute('SELECT seq from SEQS where id="'+argv[0]+'"') :
+ print row[0]
+
+ conn.close()
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
diff --git a/pool/shard003/Python/0028917_who_is_who_view.py b/pool/shard003/Python/0028917_who_is_who_view.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a4eb150944c376503f3035270ccce9473c9002f
--- /dev/null
+++ b/pool/shard003/Python/0028917_who_is_who_view.py
@@ -0,0 +1,35 @@
+from django.contrib.auth.decorators import login_required
+from django.db.models import Q
+from django.http import Http404
+from django.shortcuts import render
+from django.views.decorators.cache import never_cache
+from django.views.decorators.csrf import csrf_protect
+
+from repanier.models.customer import Customer
+from repanier.models.staff import Staff
+from repanier.tools import get_repanier_template_name
+
+
+@login_required()
+@csrf_protect
+@never_cache
+def who_is_who_view(request):
+ from repanier.apps import REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO
+
+ if not REPANIER_SETTINGS_DISPLAY_WHO_IS_WHO:
+ raise Http404
+ q = request.POST.get("q", None)
+ customer_list = Customer.objects.filter(
+ may_order=True, represent_this_buyinggroup=False
+ ).order_by("long_basket_name")
+ if q is not None:
+ customer_list = customer_list.filter(
+ Q(long_basket_name__icontains=q) | Q(city__icontains=q)
+ )
+ staff_list = Staff.objects.filter(is_active=True, can_be_contacted=True)
+ template_name = get_repanier_template_name("who_is_who.html")
+ return render(
+ request,
+ template_name,
+ {"staff_list": staff_list, "customer_list": customer_list, "q": q},
+ )
diff --git a/pool/shard003/Python/0028921_cotendohelper.py b/pool/shard003/Python/0028921_cotendohelper.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aa05ebea0be96ea1897de39de792d35a71774d7
--- /dev/null
+++ b/pool/shard003/Python/0028921_cotendohelper.py
@@ -0,0 +1,163 @@
+from lxml import etree
+from BeautifulSoup import BeautifulSoup
+from records import *
+
+dns_tag_lookup = {
+ 'soa': SOARecord,
+ 'ns': NSRecord,
+ 'a': ARecord,
+ 'cname': CNAMERecord,
+ 'mx': MXRecord,
+ 'ptr': PTRRecord,
+ 'srv': SRVRecord,
+ 'txt': TXTRecord
+ }
+
+self_closing_tags = [
+ 'result'
+ ]
+
+class CotendoObject(object):
+ def __init__(self, response):
+ self.token = response[0]
+ self._add_config(response[1])
+
+ def _add_config(self, config):
+ soup = BeautifulSoup(
+ config, selfClosingTags=self_closing_tags)
+ self._data = etree.XML(soup.prettify())
+
+class CotendoDNS(CotendoObject):
+ def __init__(self, response):
+ super(CotendoDNS, self).__init__(response)
+ self._entries = self._get_entries()
+ self.sort()
+
+ def _get_entries(self):
+ records = self._data.getchildren()[0]
+ record_list = []
+ for record in records:
+ # Do not show SOA/NS Records
+ if record.tag in ['soa', 'ns', 'comment']:
+ continue
+
+ # Do not show comments
+ if record.tag == etree.Comment:
+ continue
+
+ recordObj = dns_tag_lookup[record.tag](record)
+ record_list.append(recordObj)
+
+ return record_list
+
+ def show(self):
+ """This could use some love, it's currently here as reference"""
+ for entry in self._entries:
+ print "{'%s': %s, 'records': %s}" % (
+ entry._record_type, entry.host, entry.records)
+ print
+
+ def add_record(self, record):
+ """Add or update a given DNS record"""
+ rec = self.get_record(record._record_type, record.host)
+ if rec:
+ rec = record
+ for i,r in enumerate(self._entries):
+ if r._record_type == record._record_type \
+ and r.host == record.host:
+ self._entries[i] = record
+ else:
+ self._entries.append(record)
+ self.sort()
+ return True
+
+ def diff_record(self, record):
+ """Return the removed and added diffs"""
+ rec = self.get_record(record._record_type, record.host)
+ if rec is not None and record is not None:
+ return {'removed': tuple(set(rec.results) - set(record.results)),
+ 'added': tuple(set(record.results) - set(rec.recults))}
+ else:
+ return False
+
+ def get_record(self, dns_record_type, host):
+ """Fetch a DNS record"""
+ record_list = self._entries
+ for record in record_list:
+ if record._record_type == dns_record_type \
+ and record.host == host:
+ return record
+ return False
+
+ def del_record(self, dns_record_type, host):
+ """Remove a DNS record"""
+ rec = self.get_record(dns_record_type, host)
+ if rec:
+ self._entries = list(set(self._entries) - set([rec]))
+ return True
+
+ def sort(self):
+ unsorted = {
+ 'a': [],
+ 'cname': [],
+ 'mx': [],
+ 'ptr': [],
+ 'srv': [],
+ 'txt': []
+ }
+ for record in self._entries:
+ if record._record_type in unsorted.keys():
+ unsorted[record._record_type].append(record)
+
+ for key in unsorted.keys():
+ unsorted[key] = sorted(
+ unsorted[key], key=lambda result: result.host)
+
+ sorted_entries = []
+ for key in ('a', 'cname', 'mx', 'ptr', 'txt'):
+ for record in unsorted[key]:
+ sorted_entries.append(record)
+
+ self._entries = sorted_entries
+
+ @staticmethod
+ def CreateRecord(record_type, host, results):
+ """
+ Create a record of type (record_type) and fill it with the given
+ dict of results
+ """
+ record_class = dns_tag_lookup[record_type]
+ record = etree.Element("a")
+ record.set("host", host)
+ for params in results:
+ result = etree.Element("result")
+ for k,v in params.iteritems():
+ result.set(k, v)
+ record.append(result)
+
+ return record_class(record)
+
+ @property
+ def config(self):
+ """Create the finalized configuration"""
+ root = etree.Element("xml")
+ resource_records = etree.SubElement(root, "resource_records")
+
+ # Append SOA and NS records
+ resource_records.append(SOARecord()._etree)
+ resource_records.append(NSRecord()._etree)
+
+ # Append the rest
+ for record in self._entries:
+ resource_records.append(record._etree)
+
+ return etree.tostring(root, encoding="utf-8",
+ pretty_print=True)
+
+class CotendoCDN(CotendoObject):
+ def entries(self):
+ return etree.tostring(self._data)
+
+class UnescapedText(unicode):
+ def escape(self):
+ return self
diff --git a/pool/shard003/Python/0028931_imagedir_to_hdf5.py b/pool/shard003/Python/0028931_imagedir_to_hdf5.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d2acd95beb2f4c6f8a8a73481eed5a558734da5
--- /dev/null
+++ b/pool/shard003/Python/0028931_imagedir_to_hdf5.py
@@ -0,0 +1,31 @@
+import tooncol
+import gflags
+import sys
+import os
+
+
+FLAGS = gflags.FLAGS
+
+gflags.DEFINE_string('image_dir','',"""Directory with .png images""")
+gflags.DEFINE_string('output','',"""Output HDF5 file with extension '.h5'""")
+gflags.DEFINE_string('img_dims','',"""e.g. '64,64,3''""")
+
+
+
+def main(argv):
+ #image_dir = "/media/apartment_ssd/Pokemonify/PKMN.NETSR4/PokBmon/BW"
+ #output_file = "pokemon_bw.h5"
+
+ #Parse gflags
+ try:
+ py_file = FLAGS(argv) # parse flags
+ except gflags.FlagsError, e:
+ print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
+ sys.exit(1)
+
+ img_dims = [int(d) for d in FLAGS.img_dims.split(',')] #e.g. 96,96,4 Must include alpha channel
+ converter = tooncol.ImagesToHdf5(FLAGS.image_dir,FLAGS.output,img_dims=img_dims,drop_channel=3)
+ converter.create_hdf5()
+
+if __name__=='__main__':
+ main(sys.argv)
diff --git a/pool/shard003/Python/0028932_MulAdd.py b/pool/shard003/Python/0028932_MulAdd.py
new file mode 100644
index 0000000000000000000000000000000000000000..74258af075f289b0b23285c4293b928b8d71a754
--- /dev/null
+++ b/pool/shard003/Python/0028932_MulAdd.py
@@ -0,0 +1,220 @@
+# -*- encoding: utf-8 -*-
+from supriya.tools.ugentools.UGen import UGen
+
+
+class MulAdd(UGen):
+ r'''An Optimized multiplication / addition ugen.
+
+ ::
+
+ >>> source = ugentools.SinOsc.ar()
+ >>> mul_add = ugentools.MulAdd.new(
+ ... addend=0.5,
+ ... multiplier=-1.5,
+ ... source=source,
+ ... )
+ >>> mul_add
+ MulAdd.ar()
+
+ '''
+
+ ### CLASS VARIABLES ###
+
+ __documentation_section__ = 'Basic Operator UGens'
+
+ __slots__ = ()
+
+ _ordered_input_names = (
+ 'source',
+ 'multiplier',
+ 'addend',
+ )
+
+ ### INITIALIZER ###
+
+ def __init__(
+ self,
+ addend=0.0,
+ multiplier=1.0,
+ calculation_rate=None,
+ source=None,
+ ):
+ UGen.__init__(
+ self,
+ addend=addend,
+ multiplier=multiplier,
+ calculation_rate=calculation_rate,
+ source=source,
+ )
+
+ ### PRIVATE METHODS ###
+
+ @staticmethod
+ def _inputs_are_valid(
+ source,
+ multiplier,
+ addend,
+ ):
+ from supriya.tools import synthdeftools
+ CalculationRate = synthdeftools.CalculationRate
+ if CalculationRate.from_input(source) == CalculationRate.AUDIO:
+ return True
+ if CalculationRate.from_input(source) == CalculationRate.CONTROL:
+ if CalculationRate.from_input(multiplier) in (
+ CalculationRate.CONTROL, CalculationRate.SCALAR):
+ if CalculationRate.from_input(addend) in (
+ CalculationRate.CONTROL, CalculationRate.SCALAR):
+ return True
+ return False
+
+ @classmethod
+ def _new_single(
+ cls,
+ addend=None,
+ multiplier=None,
+ calculation_rate=None,
+ source=None,
+ ):
+ from supriya.tools import synthdeftools
+ if multiplier == 0.0:
+ return addend
+ minus = multiplier == -1
+ no_multiplier = multiplier == 1
+ no_addend = addend == 0
+ if no_multiplier and no_addend:
+ return source
+ if minus and no_addend:
+ return synthdeftools.Op.negative(source)
+ if no_addend:
+ return source * multiplier
+ if minus:
+ return addend - source
+ if no_multiplier:
+ return source + addend
+ if cls._inputs_are_valid(source, multiplier, addend):
+ return cls(
+ addend=addend,
+ multiplier=multiplier,
+ calculation_rate=calculation_rate,
+ source=source,
+ )
+ if cls._inputs_are_valid(multiplier, source, addend):
+ return cls(
+ addend=addend,
+ multiplier=source,
+ calculation_rate=calculation_rate,
+ source=multiplier,
+ )
+ return (source * multiplier) + addend
+
+ ### PUBLIC METHODS ###
+
+ @classmethod
+ def new(
+ cls,
+ source=None,
+ multiplier=1.0,
+ addend=0.0,
+ ):
+ r'''Constructs a multiplication / addition ugen.
+
+ ::
+
+ >>> addend = 0.5
+ >>> multiplier = 1.5
+ >>> source = ugentools.SinOsc.ar(frequency=[440, 442])
+ >>> mul_add = ugentools.MulAdd.new(
+ ... addend=addend,
+ ... multiplier=multiplier,
+ ... source=source,
+ ... )
+ >>> mul_add
+ UGenArray({2})
+
+ Returns ugen graph.
+ '''
+ from supriya.tools import synthdeftools
+ # TODO: handle case of array as source
+ calculation_rate = synthdeftools.CalculationRate.from_input((source, multiplier, addend))
+ ugen = cls._new_expanded(
+ addend=addend,
+ multiplier=multiplier,
+ calculation_rate=calculation_rate,
+ source=source,
+ )
+ return ugen
+
+ ### PUBLIC PROPERTIES ###
+
+ @property
+ def addend(self):
+ r'''Gets `addend` input of MulAdd.
+
+ ::
+
+ >>> addend = 0.5
+ >>> multiplier = 1.5
+ >>> source = ugentools.SinOsc.ar()
+ >>> mul_add = ugentools.MulAdd.new(
+ ... addend=addend,
+ ... multiplier=multiplier,
+ ... source=source,
+ ... )
+ >>> mul_add.addend
+ 0.5
+
+ Returns input.
+ '''
+ index = self._ordered_input_names.index('addend')
+ return self._inputs[index]
+
+ @property
+ def multiplier(self):
+ r'''Gets `multiplier` input of MulAdd.
+
+ ::
+
+ >>> addend = 0.5
+ >>> multiplier = 1.5
+ >>> source = ugentools.SinOsc.ar()
+ >>> mul_add = ugentools.MulAdd.new(
+ ... addend=addend,
+ ... multiplier=multiplier,
+ ... source=source,
+ ... )
+ >>> mul_add.multiplier
+ 1.5
+
+ Returns input.
+ '''
+ index = self._ordered_input_names.index('multiplier')
+ return self._inputs[index]
+
+ @property
+ def source(self):
+ r'''Gets `source` input of MulAdd.
+
+ ::
+
+ >>> addend = 0.5
+ >>> multiplier = 1.5
+ >>> source = ugentools.SinOsc.ar()
+ >>> mul_add = ugentools.MulAdd.new(
+ ... addend=addend,
+ ... multiplier=multiplier,
+ ... source=source,
+ ... )
+ >>> mul_add.source
+ OutputProxy(
+ source=SinOsc(
+ calculation_rate=CalculationRate.AUDIO,
+ frequency=440.0,
+ phase=0.0
+ ),
+ output_index=0
+ )
+
+ Returns input.
+ '''
+ index = self._ordered_input_names.index('source')
+ return self._inputs[index]
\ No newline at end of file
diff --git a/pool/shard003/Python/0028933_main.py b/pool/shard003/Python/0028933_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1c8913610242d5c10e08375fa01768a20941bdb
--- /dev/null
+++ b/pool/shard003/Python/0028933_main.py
@@ -0,0 +1,136 @@
+from os import path, makedirs
+import logging
+
+from errbot.errBot import ErrBot
+from errbot.plugin_manager import BotPluginManager
+from errbot.repo_manager import BotRepoManager
+from errbot.specific_plugin_manager import SpecificPluginManager
+import sys
+
+from errbot.storage.base import StoragePluginBase
+from errbot.utils import PLUGINS_SUBDIR
+
+log = logging.getLogger(__name__)
+
+HERE = path.dirname(path.abspath(__file__))
+CORE_BACKENDS = path.join(HERE, 'backends')
+CORE_STORAGE = path.join(HERE, 'storage')
+
+PLUGIN_DEFAULT_INDEX = 'https://repos.errbot.io/repos.json'
+
+
+def setup_bot(backend_name, logger, config, restore=None):
+ # from here the environment is supposed to be set (daemon / non daemon,
+ # config.py in the python path )
+
+ from .errBot import bot_config_defaults
+
+ bot_config_defaults(config)
+
+ if config.BOT_LOG_FILE:
+ hdlr = logging.FileHandler(config.BOT_LOG_FILE)
+ hdlr.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)-25s %(message)s"))
+ logger.addHandler(hdlr)
+
+ if config.BOT_LOG_SENTRY:
+ try:
+ from raven.handlers.logging import SentryHandler
+ except ImportError:
+ log.exception(
+ "You have BOT_LOG_SENTRY enabled, but I couldn't import modules "
+ "needed for Sentry integration. Did you install raven? "
+ "(See http://raven.readthedocs.org/en/latest/install/index.html "
+ "for installation instructions)"
+ )
+ exit(-1)
+
+ sentryhandler = SentryHandler(config.SENTRY_DSN, level=config.SENTRY_LOGLEVEL)
+ logger.addHandler(sentryhandler)
+
+ logger.setLevel(config.BOT_LOG_LEVEL)
+
+ # init the storage plugin
+ storage_name = getattr(config, 'STORAGE', 'Shelf')
+ extra_storage_plugins_dir = getattr(config, 'BOT_EXTRA_STORAGE_PLUGINS_DIR', None)
+ spm = SpecificPluginManager(config, 'storage', StoragePluginBase, CORE_STORAGE, extra_storage_plugins_dir)
+ storage_pluginfo = spm.get_candidate(storage_name)
+ log.info("Found Storage plugin: '%s'\nDescription: %s" % (storage_pluginfo.name, storage_pluginfo.description))
+ storage_plugin = spm.get_plugin_by_name(storage_name)
+
+ # init the botplugin manager
+ botplugins_dir = path.join(config.BOT_DATA_DIR, PLUGINS_SUBDIR)
+ if not path.exists(botplugins_dir):
+ makedirs(botplugins_dir, mode=0o755)
+
+ plugin_indexes = getattr(config, 'BOT_PLUGIN_INDEXES', (PLUGIN_DEFAULT_INDEX,))
+ if type(plugin_indexes) is str:
+ plugin_indexes = (plugin_indexes, )
+
+ repo_manager = BotRepoManager(storage_plugin,
+ botplugins_dir,
+ plugin_indexes)
+ botpm = BotPluginManager(storage_plugin,
+ repo_manager,
+ config.BOT_EXTRA_PLUGIN_DIR,
+ config.AUTOINSTALL_DEPS,
+ getattr(config, 'CORE_PLUGINS', None))
+
+ # init the backend manager & the bot
+ backendpm = bpm_from_config(config)
+
+ backend_plug = backendpm.get_candidate(backend_name)
+
+ log.info("Found Backend plugin: '%s'\n\t\t\t\t\t\tDescription: %s" % (backend_plug.name, backend_plug.description))
+
+ try:
+ bot = backendpm.get_plugin_by_name(backend_name)
+ bot.attach_storage_plugin(storage_plugin)
+ bot.attach_repo_manager(repo_manager)
+ bot.attach_plugin_manager(botpm)
+ bot.initialize_backend_storage()
+ except Exception:
+ log.exception("Unable to load or configure the backend.")
+ exit(-1)
+
+ # restore the bot from the restore script
+ if restore:
+ # Prepare the context for the restore script
+ if 'repos' in bot:
+ log.fatal('You cannot restore onto a non empty bot.')
+ sys.exit(-1)
+ log.info('**** RESTORING the bot from %s' % restore)
+ with open(restore) as f:
+ exec(f.read())
+ bot.close_storage()
+ print('Restore complete. You can restart the bot normally')
+ sys.exit(0)
+
+ errors = bot.plugin_manager.update_dynamic_plugins()
+ if errors:
+ log.error('Some plugins failed to load:\n' + '\n'.join(errors.values()))
+ bot._plugin_errors_during_startup = "\n".join(errors.values())
+ return bot
+
+
+def bpm_from_config(config):
+ """Creates a backend plugin manager from a given config."""
+ extra = getattr(config, 'BOT_EXTRA_BACKEND_DIR', [])
+ return SpecificPluginManager(
+ config,
+ 'backends',
+ ErrBot,
+ CORE_BACKENDS,
+ extra_search_dirs=extra)
+
+
+def enumerate_backends(config):
+ """ Returns all the backends found for the given config.
+ """
+ bpm = bpm_from_config(config)
+ return [plug.name for (_, _, plug) in bpm.getPluginCandidates()]
+
+
+def main(bot_class, logger, config, restore=None):
+ bot = setup_bot(bot_class, logger, config, restore)
+ log.debug('Start serving commands from the %s backend' % bot.mode)
+ bot.serve_forever()
diff --git a/pool/shard003/Python/0028934_dirac.py b/pool/shard003/Python/0028934_dirac.py
new file mode 100644
index 0000000000000000000000000000000000000000..7166ed979289014061be019941bb7ea553d16a4f
--- /dev/null
+++ b/pool/shard003/Python/0028934_dirac.py
@@ -0,0 +1,14 @@
+from arybo.lib import MBA, boolean_expr_solve
+mba = MBA(64)
+x = mba.var('x')
+def f(X):
+ T = ((X+1)&(~X))
+ C = ((T | 0x7AFAFA697AFAFA69) & 0x80A061440A061440)\
+ + ((~T & 0x10401050504) | 0x1010104)
+ return C
+r = f(x)
+sols = boolean_expr_solve(r[63], x, 1)
+C0 = sols[0].get_int_be()
+print(hex(C0))
+print(hex(f(0)))
+print(hex(f(C0)))
diff --git a/pool/shard003/Python/0028938_testTrades.py b/pool/shard003/Python/0028938_testTrades.py
new file mode 100644
index 0000000000000000000000000000000000000000..b585e94b872d47eed2f54ba84bb749016953b977
--- /dev/null
+++ b/pool/shard003/Python/0028938_testTrades.py
@@ -0,0 +1,55 @@
+import unittest
+import ccs
+import time
+
+####################################################################################################################
+# BITFINEX #
+####################################################################################################################
+
+class Valid(unittest.TestCase):
+ def setUp(self):
+ self.stock = ccs.constants.BITFINEX
+ self.base = ccs.constants.BTC
+ self.quote = ccs.constants.USD
+ self.trades = ccs.trades(self.stock, self.base, self.quote)
+ self.m = ccs.bitfinex.public.response
+ #time.sleep(3)
+
+ def testLen(self):
+ self.assertIsInstance(len(self.trades), int)
+
+ def testGetItem(self):
+ self.assertIsInstance(self.trades[0], self.m.Trade)
+
+ def testStock(self):
+ self.assertEqual(self.trades.stock(), self.stock)
+
+ def testMethod(self):
+ self.assertEqual(self.trades.method(), ccs.constants.TRADES)
+
+ def testUsymbol(self):
+ self.assertEqual(self.trades.usymbol(), self.base + ":" + self.quote)
+
+ def testOsymbol(self):
+ pass
+
+ def testData(self):
+ pass
+
+ def testRaw(self):
+ pass
+
+ def testStr(self):
+ pass
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+
+
+
+
+
+
+
diff --git a/pool/shard003/Python/0028943_GUICG22.py b/pool/shard003/Python/0028943_GUICG22.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e9959a1ef18aed2fd5d08aaa8a3662a38051671
--- /dev/null
+++ b/pool/shard003/Python/0028943_GUICG22.py
@@ -0,0 +1,135 @@
+# GemRB - Infinity Engine Emulator
+# Copyright (C) 2003 The GemRB Project
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+#
+#character generation, class kit (GUICG22)
+import GemRB
+from GUIDefines import *
+from ie_stats import *
+import CharGenCommon
+import GUICommon
+import CommonTables
+
+
+KitWindow = 0
+TextAreaControl = 0
+DoneButton = 0
+SchoolList = 0
+ClassID = 0
+
+def OnLoad():
+ global KitWindow, TextAreaControl, DoneButton
+ global SchoolList, ClassID
+
+ if GUICommon.CloseOtherWindow(OnLoad):
+ if(KitWindow):
+ KitWindow.Unload()
+ KitWindow = None
+ return
+
+ GemRB.LoadWindowPack("GUICG")
+ RaceName = CommonTables.Races.GetRowName(GemRB.GetVar("Race")-1 )
+ Class = GemRB.GetVar("Class")-1
+ ClassName = CommonTables.Classes.GetRowName(Class)
+ ClassID = CommonTables.Classes.GetValue(Class, 5)
+ KitTable = GemRB.LoadTable("kittable")
+ KitTableName = KitTable.GetValue(ClassName, RaceName)
+ KitTable = GemRB.LoadTable(KitTableName,1)
+
+ SchoolList = GemRB.LoadTable("magesch")
+
+ #there is only a specialist mage window for bg1
+ KitWindow = GemRB.LoadWindow(12)
+
+ for i in range(8):
+ Button = KitWindow.GetControl(i+2)
+ Button.SetState(IE_GUI_BUTTON_DISABLED)
+ Button.SetFlags(IE_GUI_BUTTON_RADIOBUTTON, OP_OR)
+
+ if not KitTable:
+ RowCount = 1
+ else:
+ RowCount = KitTable.GetRowCount()
+
+ for i in range(RowCount):
+ Button = KitWindow.GetControl(i+2)
+ if not KitTable:
+ if ClassID == 1:
+ Kit=GemRB.GetVar("MAGESCHOOL")
+ KitName = SchoolList.GetValue(i, 0)
+ else:
+ Kit = 0
+ KitName = CommonTables.Classes.GetValue(GemRB.GetVar("Class")-1, 0)
+
+ else:
+ Kit = KitTable.GetValue(i,0)
+ if ClassID == 1:
+ if Kit:
+ Kit = Kit - 21
+ KitName = SchoolList.GetValue(Kit, 0)
+ else:
+ if Kit:
+ KitName = CommonTables.KitList.GetValue(Kit, 1)
+ else:
+ KitName = CommonTables.Classes.GetValue(GemRB.GetVar("Class")-1, 0)
+
+ Button.SetState(IE_GUI_BUTTON_ENABLED)
+ Button.SetText(KitName)
+ Button.SetVarAssoc("Class Kit",Kit)
+ if i==0:
+ GemRB.SetVar("Class Kit",Kit)
+ Button.SetEvent(IE_GUI_BUTTON_ON_PRESS, KitPress)
+
+ BackButton = KitWindow.GetControl(12)
+ BackButton.SetText(15416)
+ DoneButton = KitWindow.GetControl(0)
+ DoneButton.SetText(11973)
+ DoneButton.SetFlags(IE_GUI_BUTTON_DEFAULT,OP_OR)
+
+ TextAreaControl = KitWindow.GetControl(11)
+ TextAreaControl.SetText(17247)
+
+ DoneButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, NextPress)
+ BackButton.SetEvent(IE_GUI_BUTTON_ON_PRESS, CharGenCommon.BackPress)
+ #KitPress()
+ KitWindow.ShowModal(MODAL_SHADOW_NONE)
+ return
+
+def KitPress():
+ Kit = GemRB.GetVar("Class Kit")
+ if Kit == 0:
+ KitName = CommonTables.Classes.GetValue(GemRB.GetVar("Class")-1, 1)
+ else:
+ if ClassID==1:
+ KitName = SchoolList.GetValue(Kit, 1)
+ else:
+ KitName = CommonTables.KitList.GetValue(Kit, 3)
+ TextAreaControl.SetText(KitName)
+ DoneButton.SetState(IE_GUI_BUTTON_ENABLED)
+ return
+
+def NextPress():
+ #class
+ ClassIndex = GemRB.GetVar ("Class")-1
+ Class = CommonTables.Classes.GetValue (ClassIndex, 5)
+ MyChar = GemRB.GetVar ("Slot")
+ GemRB.SetPlayerStat (MyChar, IE_CLASS, Class)
+ KitIndex = GemRB.GetVar ("Class Kit")
+ #the same as the unusable field
+ Kit = CommonTables.KitList.GetValue(KitIndex, 6)
+ GemRB.SetPlayerStat (MyChar, IE_KIT, Kit)
+ CharGenCommon.next()
diff --git a/pool/shard003/Python/0028945_logcollector.py b/pool/shard003/Python/0028945_logcollector.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5a788c4e74b73d02a267f4912bfa74d3a992bad
--- /dev/null
+++ b/pool/shard003/Python/0028945_logcollector.py
@@ -0,0 +1,177 @@
+## begin license ##
+#
+# "Meresco Components" are components to build searchengines, repositories
+# and archives, based on "Meresco Core".
+#
+# Copyright (C) 2014, 2020 SURF https://www.surf.nl
+# Copyright (C) 2014, 2020 Seecr (Seek You Too B.V.) https://seecr.nl
+# Copyright (C) 2014 Stichting Bibliotheek.nl (BNL) http://www.bibliotheek.nl
+# Copyright (C) 2014, 2020 Stichting Kennisnet https://www.kennisnet.nl
+# Copyright (C) 2020 Data Archiving and Network Services https://dans.knaw.nl
+# Copyright (C) 2020 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
+#
+# This file is part of "Meresco Components"
+#
+# "Meresco Components" is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# "Meresco Components" is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with "Meresco Components"; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+#
+## end license ##
+
+from meresco.core import Observable
+from weightless.core import NoneOfTheObserversRespond, DeclineMessage, local
+from traceback import print_exc
+
+
+class LogCollector(Observable):
+ """
+ Collects logs from different 'loggers'.
+
+ Typical Usage:
+ ...
+ (ObservableHttpServer(...),
+ (LogCollector(),
+ # Some logwriters, will listen to writeLog(**logItems)
+ (ApachLogWriter(...),),
+ (QueryLogWriter(...),),
+
+ # Handling of http requests, with log appenders
+ (...,
+ (HandleRequestLog(),
+ ...,
+ (SruParser(...),
+ ...,
+ (SruHandler(enableLog=True, ...),
+ ...
+ )
+ )
+ )
+ )
+ )
+ )
+
+ Writers, like ApacheLogWriter, work together with appenders,
+ like HandleRequestLog. Make sure to align correctly.
+ """
+
+ def all_unknown(self, message, *args, **kwargs):
+ try:
+ __callstack_var_logCollector__ = self._logCollector()
+ yield self.all.unknown(message, *args, **kwargs)
+ finally:
+ self._writeLog(__callstack_var_logCollector__)
+
+ def any_unknown(self, message, *args, **kwargs):
+ try:
+ __callstack_var_logCollector__ = self._logCollector()
+ try:
+ response = yield self.any.unknown(message, *args, **kwargs)
+ except NoneOfTheObserversRespond:
+ raise DeclineMessage
+ return response
+ finally:
+ self._writeLog(__callstack_var_logCollector__)
+
+ def do_unknown(self, message, *args, **kwargs):
+ try:
+ __callstack_var_logCollector__ = self._logCollector()
+ self.do.unknown(message, *args, **kwargs)
+ finally:
+ self._writeLog(__callstack_var_logCollector__)
+
+ def call_unknown(self, message, *args, **kwargs):
+ try:
+ __callstack_var_logCollector__ = self._logCollector()
+ try:
+ return self.call.unknown(message, *args, **kwargs)
+ except NoneOfTheObserversRespond:
+ raise DeclineMessage
+ finally:
+ self._writeLog(__callstack_var_logCollector__)
+
+ _logCollector = dict
+
+ def _writeLog(self, collectedLog):
+ if collectedLog:
+ try:
+ self.do.writeLog(collectedLog=collectedLog)
+ except AssertionError:
+ raise
+ except Exception:
+ print_exc()
+
+
+
+class LogCollectorScope(Observable):
+ def __init__(self, scopeName=None, name=None, **kwargs):
+ if scopeName is None and name is None:
+ raise TypeError("No name set for LogCollectorScope.")
+ elif scopeName is None:
+ scopeName = name
+ if name is None:
+ name = scopeName
+ Observable.__init__(self, name=name, **kwargs)
+ self._scopeName = scopeName
+
+ def all_unknown(self, message, *args, **kwargs):
+ myLogCollector = local('__callstack_var_logCollector__')
+ try:
+ __callstack_var_logCollector__ = LogCollector._logCollector()
+ yield self.all.unknown(message, *args, **kwargs)
+ finally:
+ myLogCollector[self._scopeName] = __callstack_var_logCollector__
+
+ def any_unknown(self, message, *args, **kwargs):
+ myLogCollector = local('__callstack_var_logCollector__')
+ try:
+ __callstack_var_logCollector__ = LogCollector._logCollector()
+ try:
+ response = yield self.any.unknown(message, *args, **kwargs)
+ except NoneOfTheObserversRespond:
+ raise DeclineMessage
+ return response
+ finally:
+ myLogCollector[self._scopeName] = __callstack_var_logCollector__
+
+ def do_unknown(self, message, *args, **kwargs):
+ myLogCollector = local('__callstack_var_logCollector__')
+ try:
+ __callstack_var_logCollector__ = LogCollector._logCollector()
+ self.do.unknown(message, *args, **kwargs)
+ finally:
+ myLogCollector[self._scopeName] = __callstack_var_logCollector__
+
+ def call_unknown(self, message, *args, **kwargs):
+ myLogCollector = local('__callstack_var_logCollector__')
+ try:
+ __callstack_var_logCollector__ = LogCollector._logCollector()
+ try:
+ return self.call.unknown(message, *args, **kwargs)
+ except NoneOfTheObserversRespond:
+ raise DeclineMessage
+ finally:
+ myLogCollector[self._scopeName] = __callstack_var_logCollector__
+
+
+
+def collectLog(*logDicts):
+ collector=local('__callstack_var_logCollector__')
+ for aLogDict in logDicts:
+ for key, value in aLogDict.items():
+ collector.setdefault(key, []).append(value)
+
+def collectLogForScope(**scopes):
+ for scope, aLogDict in scopes.items():
+ collector=local('__callstack_var_logCollector__').setdefault(scope, dict())
+ for key, value in aLogDict.items():
+ collector.setdefault(key, []).append(value)
diff --git a/pool/shard003/Python/0028948_views.py b/pool/shard003/Python/0028948_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..b465595b1409c19ab315dbbed15e8aee490a90e6
--- /dev/null
+++ b/pool/shard003/Python/0028948_views.py
@@ -0,0 +1,31 @@
+from django.shortcuts import render
+from rest_framework import generics
+from rest_framework.response import Response
+from rest_framework import views
+from geomat.feedback.serializers import FeedBackSerializer
+from django.core.mail import send_mail
+from rest_framework import status
+from drf_yasg.utils import swagger_auto_schema
+
+
+class FeedBackView(generics.GenericAPIView):
+ serializer_class = FeedBackSerializer
+
+ permission_classes = ()
+
+ @swagger_auto_schema(responses={200:"The Views response is 200 if mail is sent"})
+ def post(self, request, *args, **kwargs):
+ serializer = FeedBackSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ serializer = serializer.data
+
+ message = send_mail(subject=serializer["emailTitle"],
+ from_email= "{0} <{1}>".format(serializer["username"],serializer["userEmail"]),
+ message=serializer["emailContent"],
+ recipient_list=["geomatdigital@dlist.uni-frankfurt.de"],
+ fail_silently=False)
+ if not message:
+ return Response(status=status.HTTP_400_BAD_REQUEST)
+ return Response(data=serializer)
+
+# Create your views here.
diff --git a/pool/shard003/Python/0028949_upload.py b/pool/shard003/Python/0028949_upload.py
new file mode 100644
index 0000000000000000000000000000000000000000..e95664f0b23918ad9f0800380eda440a7eb7be88
--- /dev/null
+++ b/pool/shard003/Python/0028949_upload.py
@@ -0,0 +1,19 @@
+import urllib2
+import urllib
+import sys
+import json
+
+UPLOAD_URL = 'http://localhost:8080/upload'
+
+message = {}
+message['body'] = sys.stdin.read()
+
+if len(sys.argv) > 1:
+ message['authenticated'] = True
+if len(sys.argv) > 2:
+ message['overwrite'] = sys.argv[2]
+data = urllib.urlencode({'data': json.dumps(message)})
+req = urllib2.Request(UPLOAD_URL, data)
+if len(sys.argv) > 1:
+ req.add_header('Cookie', sys.argv[1])
+print urllib2.urlopen(req).read()
diff --git a/pool/shard003/Python/0028952_test_utils.py b/pool/shard003/Python/0028952_test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e523757a5f7c35e80d718f6d1e06e70adb789f3
--- /dev/null
+++ b/pool/shard003/Python/0028952_test_utils.py
@@ -0,0 +1,84 @@
+import pytest
+from name import utils
+
+
+@pytest.mark.django_db
+def test_filter_names_with_empty_query(rf, search_fixtures):
+ request = rf.get('/')
+ names = utils.filter_names(request)
+ assert names.count() == search_fixtures.count()
+
+
+@pytest.mark.django_db
+def test_filter_names_with_query(rf, search_fixtures):
+ request = rf.get('/', {'q': 1})
+ names = utils.filter_names(request)
+ assert names.count() == 5
+
+
+@pytest.mark.django_db
+@pytest.mark.parametrize('q_type,expected', [
+ ('Personal', 1),
+ ('Personal,Organization', 2),
+ ('Personal,Organization,Event', 3),
+ ('Personal,Organization,Event,Software,Building', 5)
+])
+def test_filter_names_with_query_and_name_types(rf, q_type,
+ expected, search_fixtures):
+ request = rf.get('/', {'q': '1', 'q_type': q_type})
+ names = utils.filter_names(request)
+ assert names.count() == expected
+
+
+@pytest.mark.django_db
+@pytest.mark.parametrize('q_type,expected', [
+ ('Personal', 4),
+ ('Personal,Organization', 8),
+ ('Personal,Organization,Event', 12),
+ ('Personal,Organization,Event,Software,Building', 20)
+])
+def test_filter_names_with_no_query_and_name_types(rf, q_type,
+ expected, search_fixtures):
+ request = rf.get('/', {'q_type': q_type})
+ names = utils.filter_names(request)
+ assert names.count() == expected
+
+
+# rf is a pytest-django fixture
+@pytest.mark.parametrize('query,expected', [
+ ('Personal', 1),
+ ('Personal,Building,Organization', 3),
+ ('Personal,Building,Organization,Software,Event', 5),
+ ('Personal,Building,Organization,', 3),
+ ('Personal, Location, Organiztion', 1),
+ ('Personal, Building, Organiztion,', 1),
+ ('Personal Building Organiztion', 0),
+ ('Unknown,Types', 0),
+ ('Unknown,Types', 0)
+])
+def test_resolve_type(rf, query, expected):
+ types = utils.resolve_type(query)
+ assert len(types) == expected
+
+
+def test_compose_query_with_single_term():
+ result = utils.compose_query('testname')
+ assert 'AND' in result.connector
+ assert 'testname' in result.children[0]
+
+
+def test_compose_query_with_multiple_terms():
+ result = utils.compose_query('foo bar baz bub')
+ assert 'AND' in result.connector
+ assert len(result.children) is 4
+
+
+@pytest.mark.parametrize('query,expected', [
+ ('one two three four', 4),
+ ('extra spaces Here', 3),
+ ('\try escape sequence', 3),
+ ('"Pun. cua," tion! !!', 3),
+])
+def test_normalize_query(query, expected):
+ normalized = utils.normalize_query(query)
+ assert len(normalized) == expected
diff --git a/pool/shard003/Python/0028954_volumeutilsv2.py b/pool/shard003/Python/0028954_volumeutilsv2.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fafe4c32a3af0058bde563f1a52442ed29eab89
--- /dev/null
+++ b/pool/shard003/Python/0028954_volumeutilsv2.py
@@ -0,0 +1,84 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+#
+# Copyright 2012 Pedro Navarro Perez
+# Copyright 2013 Cloudbase Solutions Srl
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+"""
+Helper methods for operations related to the management of volumes
+and storage repositories on Windows Server 2012 and above
+"""
+import sys
+import time
+
+if sys.platform == 'win32':
+ import wmi
+
+from oslo.config import cfg
+
+from nova.openstack.common import log as logging
+from nova import utils
+from nova.virt.hyperv import basevolumeutils
+
+LOG = logging.getLogger(__name__)
+CONF = cfg.CONF
+
+
+class VolumeUtilsV2(basevolumeutils.BaseVolumeUtils):
+ def __init__(self, host='.'):
+ super(VolumeUtilsV2, self).__init__(host)
+
+ storage_namespace = '//%s/root/microsoft/windows/storage' % host
+ if sys.platform == 'win32':
+ self._conn_storage = wmi.WMI(moniker=storage_namespace)
+
+ def login_storage_target(self, target_lun, target_iqn, target_portal):
+ """Add target portal, list targets and logins to the target."""
+ (target_address,
+ target_port) = utils.parse_server_string(target_portal)
+
+ #Adding target portal to iscsi initiator. Sending targets
+ portal = self._conn_storage.MSFT_iSCSITargetPortal
+ portal.New(TargetPortalAddress=target_address,
+ TargetPortalPortNumber=target_port)
+ #Connecting to the target
+ target = self._conn_storage.MSFT_iSCSITarget
+ target.Connect(NodeAddress=target_iqn,
+ IsPersistent=True)
+ #Waiting the disk to be mounted.
+ #TODO(pnavarro): Check for the operation to end instead of
+ #relying on a timeout
+ time.sleep(CONF.hyperv.volume_attach_retry_interval)
+
+ def logout_storage_target(self, target_iqn):
+ """Logs out storage target through its session id."""
+ targets = self._conn_storage.MSFT_iSCSITarget(NodeAddress=target_iqn)
+ if targets:
+ target = targets[0]
+ if target.IsConnected:
+ sessions = self._conn_storage.MSFT_iSCSISession(
+ TargetNodeAddress=target_iqn)
+
+ for session in sessions:
+ if session.IsPersistent:
+ session.Unregister()
+
+ target.Disconnect()
+
+ def execute_log_out(self, session_id):
+ sessions = self._conn_wmi.MSiSCSIInitiator_SessionClass(
+ SessionId=session_id)
+ if sessions:
+ self.logout_storage_target(sessions[0].TargetName)
diff --git a/pool/shard003/Python/0028958_download_test.py b/pool/shard003/Python/0028958_download_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6c6670c80d830e94d262646c8f51442ebc63a2e
--- /dev/null
+++ b/pool/shard003/Python/0028958_download_test.py
@@ -0,0 +1,107 @@
+import unittest
+from conans.test.tools import TestClient, TestServer
+from conans.test.utils.test_files import hello_source_files
+from conans.client.manager import CONANFILE
+import os
+from conans.model.ref import ConanFileReference, PackageReference
+from conans.paths import CONAN_MANIFEST, CONANINFO
+from conans.util.files import save
+from conans.model.manifest import FileTreeManifest
+from conans.client.proxy import ConanProxy
+
+
+myconan1 = """
+from conans import ConanFile
+import platform
+
+class HelloConan(ConanFile):
+ name = "Hello"
+ version = "1.2.1"
+"""
+
+
+class DownloadTest(unittest.TestCase):
+
+ def complete_test(self):
+ """ basic installation of a new conans
+ """
+ servers = {}
+ # All can write (for avoid authentication until we mock user_io)
+ test_server = TestServer([("*/*@*/*", "*")], [("*/*@*/*", "*")])
+ servers["default"] = test_server
+
+ conan_digest = FileTreeManifest(123123123, {})
+
+ client = TestClient(servers=servers)
+ client.init_dynamic_vars()
+ conan_ref = ConanFileReference.loads("Hello/1.2.1@frodo/stable")
+ reg_folder = client.paths.export(conan_ref)
+
+ files = hello_source_files()
+ client.save(files, path=reg_folder)
+ client.save({CONANFILE: myconan1,
+ CONAN_MANIFEST: str(conan_digest),
+ "include/math/lib1.h": "//copy",
+ "my_lib/debug/libd.a": "//copy",
+ "my_data/readme.txt": "//copy"}, path=reg_folder)
+
+ package_ref = PackageReference(conan_ref, "fakeid")
+ package_folder = client.paths.package(package_ref)
+ save(os.path.join(package_folder, CONANINFO), "info")
+ save(os.path.join(package_folder, CONAN_MANIFEST), "manifest")
+ save(os.path.join(package_folder, "include", "lib1.h"), "//header")
+ save(os.path.join(package_folder, "lib", "my_lib", "libd.a"), "//lib")
+ save(os.path.join(package_folder, "res", "shares", "readme.txt"),
+ "//res")
+
+ digest_path = client.client_cache.digestfile_package(package_ref)
+ expected_manifest = FileTreeManifest.create(os.path.dirname(digest_path))
+ save(os.path.join(package_folder, CONAN_MANIFEST), str(expected_manifest))
+
+ client.run("upload %s" % str(conan_ref))
+ client.run("upload %s -p %s" % (str(conan_ref), package_ref.package_id))
+
+ client2 = TestClient(servers=servers)
+ client2.init_dynamic_vars()
+
+ installer = ConanProxy(client2.paths, client2.user_io, client2.remote_manager, "default")
+
+ installer.get_recipe(conan_ref)
+ installer.get_package(package_ref, short_paths=False)
+ # Check that the output is done in order
+ lines = [line.strip() for line in str(client2.user_io.out).splitlines()
+ if line.startswith("Downloading")]
+ self.assertEqual(lines, ["Downloading conanmanifest.txt",
+ "Downloading conanfile.py",
+ "Downloading conan_export.tgz",
+ "Downloading conanmanifest.txt",
+ "Downloading conaninfo.txt",
+ "Downloading conan_package.tgz"
+ ])
+
+ reg_path = client2.paths.export(ConanFileReference.loads("Hello/1.2.1/frodo/stable"))
+ pack_folder = client2.paths.package(package_ref)
+
+ # Test the file in the downloaded conans
+ files = ['CMakeLists.txt',
+ 'my_lib/debug/libd.a',
+ 'hello.cpp',
+ 'hello0.h',
+ CONANFILE,
+ CONAN_MANIFEST,
+ 'main.cpp',
+ 'include/math/lib1.h',
+ 'my_data/readme.txt']
+
+ for _file in files:
+ self.assertTrue(os.path.exists(os.path.join(reg_path, _file)))
+ self.assertTrue(os.path.exists(pack_folder))
+
+ # Test the file in the downloaded package
+ self.assertTrue(os.path.exists(pack_folder))
+ self.assertTrue(os.path.exists(os.path.join(pack_folder, "include",
+ "lib1.h")))
+ self.assertTrue(os.path.exists(os.path.join(pack_folder, "lib",
+ "my_lib/libd.a")))
+ self.assertTrue(os.path.exists(os.path.join(pack_folder, "res",
+ "shares/readme.txt")))
diff --git a/pool/shard003/Python/0028961_losses_test.py b/pool/shard003/Python/0028961_losses_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccb8509c0347f9c9b6f1e8f4f620230aac9a6c2d
--- /dev/null
+++ b/pool/shard003/Python/0028961_losses_test.py
@@ -0,0 +1,97 @@
+# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ==============================================================================
+"""Tests for trainer hooks."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import numpy as np
+
+from tensorflow.contrib.boosted_trees.python.utils import losses
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import test_util
+from tensorflow.python.ops import array_ops
+from tensorflow.python.platform import googletest
+
+
+class LossesTest(test_util.TensorFlowTestCase):
+
+ def test_per_example_exp_loss(self):
+
+ def _logit(p):
+ return np.log(p) - np.log(1 - p)
+
+ labels_positive = array_ops.ones([10, 1], dtypes.float32)
+ weights = array_ops.ones([10, 1], dtypes.float32)
+ labels_negative = array_ops.zeros([10, 1], dtypes.float32)
+ predictions_probs = np.array(
+ [[0.1], [0.2], [0.3], [0.4], [0.5], [0.6], [0.7], [0.8], [0.9], [0.99]],
+ dtype=np.float32)
+ prediction_logits = _logit(predictions_probs)
+
+ eps = 0.2
+
+ with self.test_session():
+ predictions_tensor = constant_op.constant(
+ prediction_logits, dtype=dtypes.float32)
+ loss_for_positives, _ = losses.per_example_exp_loss(
+ labels_positive, weights, predictions_tensor, eps=eps)
+
+ loss_for_negatives, _ = losses.per_example_exp_loss(
+ labels_negative, weights, predictions_tensor, eps=eps)
+
+ pos_loss = loss_for_positives.eval()
+ neg_loss = loss_for_negatives.eval()
+ # For positive labels, points <= 0.3 get max loss of e.
+ # For negative labels, these points have minimum loss of 1/e.
+ self.assertAllClose(np.exp(np.ones([2, 1])), pos_loss[:2], atol=1e-4)
+ self.assertAllClose(np.exp(-np.ones([2, 1])), neg_loss[:2], atol=1e-4)
+
+ # For positive lables, p oints with predictions 0.7 and larger get minimum
+ # loss value of 1/e. For negative labels, these points are wrongly
+ # classified and get loss e.
+ self.assertAllClose(np.exp(-np.ones([4, 1])), pos_loss[6:10], atol=1e-4)
+ self.assertAllClose(np.exp(np.ones([4, 1])), neg_loss[6:10], atol=1e-4)
+
+ # Points in between 0.5-eps, 0..5+eps get loss exp(-label_m*y), where
+ # y = 1/eps *x -1/(2eps), where x is the probability and label_m is either
+ # 1 or -1 (for label of 0).
+ self.assertAllClose(
+ np.exp(-(predictions_probs[2:6] * 1.0 / eps - 0.5 / eps)),
+ pos_loss[2:6], atol=1e-4)
+ self.assertAllClose(
+ np.exp(predictions_probs[2:6] * 1.0 / eps - 0.5 / eps),
+ neg_loss[2:6], atol=1e-4)
+
+ def test_per_example_squared_loss(self):
+
+ labels = np.array([[0.123], [224.2], [-3], [2], [.3]], dtype=np.float32)
+ weights = array_ops.ones([5, 1], dtypes.float32)
+ predictions = np.array(
+ [[0.123], [23.2], [233], [52], [3]], dtype=np.float32)
+
+ with self.test_session():
+ loss_tensor, _ = losses.per_example_squared_loss(labels, weights,
+ predictions)
+
+ loss = loss_tensor.eval()
+ self.assertAllClose(
+ np.square(labels[:5] - predictions[:5]), loss[:5], atol=1e-4)
+
+
+if __name__ == "__main__":
+ googletest.main()
diff --git a/pool/shard003/Python/0028964_notification_picture.py b/pool/shard003/Python/0028964_notification_picture.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d0d71a395a9fc5005438952957bcdaf459a3ab7
--- /dev/null
+++ b/pool/shard003/Python/0028964_notification_picture.py
@@ -0,0 +1,18 @@
+from yowsup.structs import ProtocolEntity, ProtocolTreeNode
+from .notification import NotificationProtocolEntity
+class PictureNotificationProtocolEntity(NotificationProtocolEntity):
+ '''
+
+
+ '''
+
+ def __init__(self, _id, _from, status, timestamp, notify, offline, setJid, setId):
+ super(PictureNotificationProtocolEntity, self).__init__("picture", _id, _from, timestamp, notify, offline)
+ self.setData(setJid, setId)
+
+ @staticmethod
+ def fromProtocolTreeNode(node):
+ entity = NotificationProtocolEntity.fromProtocolTreeNode(node)
+ entity.__class__ = PictureNotificationProtocolEntity
+ return entity
\ No newline at end of file
diff --git a/pool/shard003/Python/0028966_exporter.py b/pool/shard003/Python/0028966_exporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbe97230d1f944dbead90b7e4dfd9db62057f703
--- /dev/null
+++ b/pool/shard003/Python/0028966_exporter.py
@@ -0,0 +1,260 @@
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Low level facilities for exporting JAX programs.
+
+This is not the primary user-oriented API (although pieces of types here will
+be user manipulable in the course of interacting with the machinery).
+"""
+
+from collections import namedtuple
+import functools
+import logging
+from typing import Any, Dict, Optional, Sequence
+import weakref
+
+import numpy as np
+import jax.core
+from numpy import array
+
+from . import array_types
+from . import ir_utils
+from . import jax_utils
+from . import tracing
+
+from iree.compiler import (
+ ir,)
+
+from jax.tree_util import (tree_map, tree_flatten, tree_unflatten)
+
+__all__ = [
+ "ExportModule",
+]
+
+logger = logging.getLogger("iree_jax")
+
+# Opaque value to indicate something is empty. Used in cases where 'None'
+# may have a different meaning.
+_Empty = object()
+
+
+class ExportModule:
+ """An exported module under construction."""
+
+ def __init__(self, *, module: ir.Module):
+ self.module = module
+ self.context = module.context
+ self.op = self.module.operation
+ self.loc = self.op.location
+ self._body = self.op.regions[0].blocks[0]
+ self._symbol_table = ir.SymbolTable(self.op)
+ self.ip = ir.InsertionPoint(self._body)
+ self._refs = RefTracker()
+ self.exports = AttributeDict()
+
+ @classmethod
+ def create_empty(cls,
+ *,
+ context: Optional[ir.Context] = None,
+ name: Optional[str] = None):
+ if not context:
+ context = ir_utils.create_context()
+ loc = ir.Location.unknown(context=context)
+ module = ir.Module.create(loc)
+ if name:
+ module.operation.attributes["sym_name"] = ir.StringAttr.get(
+ name, context=context)
+ return cls(module=module)
+
+ def def_global(self,
+ symbol_name: str,
+ value,
+ *,
+ initialize: bool = False,
+ mutable: bool = True) -> jax.core.AbstractValue:
+ if symbol_name in self.exports:
+ raise ValueError(f"Duplicate export definition: {symbol_name}")
+ # Abstractify.
+ concrete_value = _Empty
+ if not isinstance(value, jax.core.AbstractValue):
+ concrete_value = value
+ value = jax_utils.abstractify(concrete_value)
+
+ # Convert to IR type.
+ ir_types = jax_utils.aval_to_ir_types(self.context, value)
+
+ # If we have a concrete value, then it may already be associated with a
+ # global.
+ info = self._refs.track(concrete_value)
+ if info.tracked_value is not _Empty:
+ return info.tracked_value
+
+ # TODO: Other types?
+ result = None
+ if isinstance(value, jax.core.ShapedArray):
+ if len(ir_types) != 1:
+ raise TypeError(f"Composite JAX types not yet supported: {ir_types}")
+ with self.loc, self.ip:
+ initial_value = None
+ if initialize:
+ initial_value = ir_utils.create_array_attribute(
+ concrete_value, ir_types)
+ actual_symbol_name = ir_utils.create_global(self._symbol_table,
+ symbol_name,
+ ir_types[0],
+ mutable=mutable,
+ initial_value=initial_value)
+ info.tracked_value = array_types.ExportedGlobalArray(
+ value, actual_symbol_name, ir_types[0])
+ result = jax.core.ConcreteArray(value.dtype, info.tracked_value)
+ else:
+ raise TypeError(f"Export not implemented for JAX abstract value: {value}")
+
+ self.exports[symbol_name] = result
+ return result
+
+ def def_global_tree(self,
+ symbol_name: str,
+ treeish: Any,
+ *,
+ initialize: bool = False,
+ mutable: bool = True) -> Any:
+ """Defines a PyTree with a symbolic name.
+
+ Note that the tree can either consist of concrete or abstract values.
+ If concrete, only their metadata is retained (the backing values will not
+ have initializers set).
+ """
+ if symbol_name in self.exports:
+ raise ValueError(f"Duplicate export definition: {symbol_name}")
+
+ concrete_leaves, tree_def = tree_flatten(treeish)
+ imported_leaves = []
+ tracked_leaf_count = 0
+ for concrete_leaf in concrete_leaves:
+ # We fork between trackable things and static constants. Currently this
+ # is just array vs not, but this should match Jax's heuristic.
+ # TODO: Make sure this is the right way to detect array.
+ if hasattr(concrete_leaf, "__array__"):
+ leaf_symbol = f"{symbol_name}${tracked_leaf_count}"
+ logger.debug("def_global_tree: array %s=%r:%r", leaf_symbol,
+ concrete_leaf.shape, concrete_leaf.dtype)
+ imported_leaves.append(
+ self.def_global(leaf_symbol,
+ concrete_leaf,
+ initialize=initialize,
+ mutable=mutable))
+ tracked_leaf_count += 1
+ else:
+ logger.debug("def_global_tree: literal=%r", type(concrete_leaf))
+ imported_leaves.append(concrete_leaf)
+ result = tree_unflatten(tree_def, imported_leaves)
+ logger.debug("def_global_tree: new tree=%r", result)
+ self.exports[symbol_name] = result
+ return result
+
+ def def_func(self,
+ f=None,
+ *,
+ symbol_name: Optional[str] = None,
+ arguments: Sequence[Any] = ()):
+ if f is None:
+ return functools.partial(self.def_func,
+ symbol_name=symbol_name,
+ arguments=arguments)
+ if symbol_name is None:
+ # TODO: Inspect name properly.
+ symbol_name = f.__name__
+ if symbol_name in self.exports:
+ raise ValueError(f"Duplicate export definition: {symbol_name}")
+
+ # Unpack arguments.
+ # TODO: Make this match how JAX handles arguments (and make nicer).
+ arguments_flat, arguments_tree_def = tree_flatten(arguments)
+ argument_avals = [jax_utils.abstractify(x) for x in arguments_flat]
+ argument_ir_types = []
+ for argument_aval in argument_avals:
+ aval_ir_types = jax_utils.aval_to_ir_types(self.context, argument_aval)
+ if len(aval_ir_types) != 1:
+ raise TypeError(f"TODO: Composite abstract types not yet supported")
+ argument_ir_types.extend(aval_ir_types)
+
+ with self.loc, self.ip:
+ actual_symbol_name, func_op = ir_utils.create_func_op(
+ self._symbol_table, symbol_name, argument_ir_types)
+
+ with tracing.new_ir_trace_scope(
+ tracing.FunctionIrTrace(
+ func_op=func_op,
+ module=self.module,
+ module_symbol_table=self._symbol_table)) as trace:
+ # TODO: Lots wrong with the argument packing/unpacking here. Should
+ # map trees in the same way JAX does.
+ argument_py_values = [
+ array_types.IrValueArray(aval, ir_value)
+ for aval, ir_value in zip(argument_avals, trace.arguments)
+ ]
+ argument_py_tree = tree_unflatten(arguments_tree_def, argument_py_values)
+ return_py_value = f(*argument_py_tree)
+ if return_py_value is None:
+ trace.emit_return()
+ else:
+ return_ir_values = trace.materialize_py_values(return_py_value)
+ trace.emit_return(*return_ir_values)
+
+ def __str__(self):
+ return str(self.module)
+
+
+class RefInfo:
+ __slots__ = [
+ "_referrent",
+ "tracked_value",
+ ]
+
+ def __init__(self, referrent: Any):
+ self._referrent = weakref.ref(referrent)
+ self.tracked_value = _Empty
+
+
+class RefTracker:
+ """Tracks live references from Python values to symbolic associations."""
+
+ def __init__(self):
+ self._refs: Dict[int, RefInfo] = {}
+
+ def track(self, referrent: Any) -> RefInfo:
+ ref_id = id(referrent)
+ existing = self._refs.get(ref_id)
+ if existing:
+ return existing
+ info = RefInfo(referrent)
+ weakref.finalize(referrent, self._ref_finalizer, ref_id)
+ self._refs[ref_id] = info
+ return info
+
+ def _ref_finalizer(self, ref_id: int):
+ del self._refs[ref_id]
+
+
+class AttributeDict(dict):
+ """Dict that allows access to keys as attributes.
+
+ TODO: Move this to the higher level user API when it exists.
+ """
+
+ def __getattribute__(self, name: str) -> Any:
+ try:
+ return self[name]
+ except KeyError:
+ raise AttributeError(name)
diff --git a/pool/shard003/Python/0028969_SSP.py b/pool/shard003/Python/0028969_SSP.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cf93198c80a2c25dd892ddfa73ebf9145bfb3d2
--- /dev/null
+++ b/pool/shard003/Python/0028969_SSP.py
@@ -0,0 +1,152 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, print_function, division
+
+import numpy as np
+import os
+from scipy import interpolate
+import sqlite3
+
+from .. import df
+
+col_dict = {'sdss': 'm_ini, m_act, u, g, r, i, z, J, H, Ks',
+ 'des': 'm_ini, m_act, u, g, r, i, z, Y'}
+
+class SSP(object):
+ def __init__(self, age, met, mf='kroupa', **kwargs):
+
+ self.age = age
+ self.met = met
+ self._ISOCDIR = kwargs['isocdir']
+ self.col_dict = col_dict
+
+ try:
+ self.isoc = self._getiso(group=kwargs['group'],
+ filterset=kwargs['filterset'])
+ except:
+ self.isoc = self._getiso()
+
+ self.max_mass = np.max(self.isoc[:,0])
+ self.min_mass = np.min(self.isoc[:,0])
+
+ if mf == 'kroupa':
+ try:
+ # Try to use values given by user.
+ self.mf = df.Kroupa(kwargs['a'], kwargs['mlim'])
+ except:
+ # Fall back to default if not given
+ self.mf = df.Kroupa()
+ elif mf == 'user':
+ try:
+ self.mf = df.UserMF(kwargs['mass'])
+ except:
+ print("Give me a mass array")
+ raise ValueError
+ elif mf == 'texp':
+ # Not implemented
+ # self.mf = df.TaperedExp()
+ raise ValueError("Not implemented")
+ else:
+ raise ValueError("Not implemented or inexistent")
+
+ def populate(self, n=10000, fbin=0.0):
+
+ flux = lambda x: 10**(-x/2.5)
+
+ self.n = n
+ try:
+ masses = self.mf.sample(n)
+ except:
+ # User mass array
+ masses = self.mf.sample()
+
+ # Total mass sampled from the full IMF
+ total_mass = sum(masses)
+
+ # Mask to exclude values outside the range covered by the model
+ mask = (masses < self.max_mass)&(masses > self.min_mass)
+ masses = masses[mask]
+ n = len(masses)
+
+ ivals = self._interpolate()
+ stars = np.array(masses)
+ for vname in self.cols[1:]:
+ stars = np.c_[stars, ivals[vname](masses)]
+
+ if fbin > 0.0:
+ print("Binaries are buggy, beware")
+ magic = 0.63
+ idx = np.random.randint(int(n*fbin), size=int((1.0/magic)*n*fbin))
+ cmasses = self.mf.sample(len(idx))
+ for i, vname in enumerate(self.cols[2:]):
+ stars[idx, i+2] = -2.5*np.log10(flux(stars[idx, i+2]) +
+ flux(ivals[vname](cmasses)))
+
+ elif 1.0 < fbin < 0.0:
+ raise ValueError("f_bin must be less than 1 and positive")
+
+ self._stars = stars
+ self._total_mass = total_mass
+
+ return total_mass, stars
+
+ def _getiso (self, group='padova12', filterset='des'):
+ """
+ Find the corresponding isochrone for a given age and metallicity
+ """
+
+ age = self.age
+ met = self.met
+
+ _ISOCDIR = self._ISOCDIR
+
+ table_name = 'padova_'+filterset
+ self.cols = col_dict[filterset].split()
+
+ print(_ISOCDIR)
+ connection=sqlite3.connect(_ISOCDIR+'/isoc_'+group+'_'+filterset+'.sqlite')
+ cursor=connection.cursor()
+
+ # this return a list of tuples
+ cursor.execute('SELECT Z_met FROM met_grid ORDER BY ABS(Z_met - '+str(met)+') LIMIT 1')
+ n_Z = cursor.fetchall()[0][0]
+
+ cursor.execute('SELECT lage FROM age_grid ORDER BY ABS(lage - '+str(age)+') LIMIT 1')
+ n_age = cursor.fetchall()[0][0]
+
+ if float(n_Z) != met or float(n_age) != age:
+ print("Model with Z = "+str(met)+" and log(age/yr) = "+str(age)+" not found.")
+ print("Using Z = "+str(n_Z)+" and log(age/yr) = "+str(n_age))
+ else:
+ print("Using Z = "+str(n_Z)+" and log(age/yr) = "+str(n_age))
+
+ age = str(n_age)
+ met = str(n_Z)
+ cursor.execute('SELECT '+ col_dict[filterset] +' FROM '+table_name+' WHERE lage = '+age+' AND Z_met = '+met)
+ self.isoc = np.asarray(cursor.fetchall())
+ self.age = n_age
+ self.met = n_Z
+
+ return self.isoc
+
+ def _interpolate(self):
+ """
+ This method can be generalized to interpolate any quantity given in the
+ isochrone table.
+
+ NOTES:
+ - higher order interpolation are broken. Scipy.interpolate.interp1d
+ does not provide a good solution. Why?
+ """
+ m = {}
+ z = self.isoc[:,0] # mass array
+ for idx, name in enumerate(self.cols):
+ m[name] = interpolate.interp1d(z, self.isoc[:,idx],
+ bounds_error=False)
+
+ return m
+
+ def _setisocdir(self, dir):
+
+ self._ISOCDIR = dir
+ return
diff --git a/pool/shard003/Python/0028976_SudokuGenerator.py b/pool/shard003/Python/0028976_SudokuGenerator.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cbf2cb0a45c4f34ca6228a78101ef09349afcbd
--- /dev/null
+++ b/pool/shard003/Python/0028976_SudokuGenerator.py
@@ -0,0 +1,44 @@
+import RandomGenerator
+import CandidateChecker
+import ArrayTools
+import SudokuIOConverter
+
+#NOTE: evtl. x / y vertauscht
+#NOTE: Doc Kommentare einbinden
+
+def GenerateSudoku():
+ """
+ Generates a full Sudoku with all numbers
+
+ Returns:
+ 3D-Array
+
+ """
+ succesfull = 0
+ countTries = 0
+
+ while succesfull < 1:
+ Sudoku = ArrayTools.nullBased2DArray(9)
+
+ for x in range (0,9):
+ for y in range(0,9):
+ cands = CandidateChecker.getCandidates(Sudoku, x, y)
+
+ #Check if there are no more candidates
+ if(len(cands) == 0):
+ succesfull = -1
+ countTries = countTries + 1
+ break
+ else:
+ Sudoku[x][y] = RandomGenerator.GenerateRandom(cands)
+
+ #Check if succesfull
+ if((x == 8) & (y == 8)):
+ succesfull = 1
+ print("Generation succesfull with " + str(countTries) + " Tries!")
+ if(succesfull == -1 | succesfull == 1):
+ break
+ return Sudoku
+
+if __name__ == "__main__":
+ SudokuIOConverter.printSudoku(GenerateSudoku())
\ No newline at end of file
diff --git a/pool/shard003/Python/0028981_Dynamic.py b/pool/shard003/Python/0028981_Dynamic.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7cf987d4d9862d40545007d4d91b5e35030a319
--- /dev/null
+++ b/pool/shard003/Python/0028981_Dynamic.py
@@ -0,0 +1,118 @@
+import abjad
+from abjad import iterate
+from abjad.tools import scoretools
+from abjad.tools import systemtools
+
+
+class Dynamic(abjad.Dynamic):
+ r'''A fancy dynamic.
+
+ ::
+
+
+ >>> staff = abjad.Staff("c'2 d'2 e'2 f'2 g'2 a'2 b'2 c''2")
+ >>> piano = abjad.Dynamic('p')
+ >>> forte = abjad.Dynamic('f')
+ >>> abjad.attach(piano, staff[0])
+ >>> abjad.attach(piano, staff[1])
+ >>> abjad.attach(piano, staff[2])
+ >>> abjad.attach(piano, staff[6])
+ >>> abjad.attach(forte, staff[7])
+ >>> print(format(staff))
+ \new Staff {
+ c'2 \p
+ d'2 \p
+ e'2 \p
+ f'2
+ g'2
+ a'2
+ b'2 \p
+ c''2 \f
+ }
+
+ ::
+
+ >>> staff = abjad.Staff("c'2 d'2 e'2 f'2 g'2 a'2 b'2 c''2")
+ >>> piano = consort.Dynamic('p')
+ >>> forte = consort.Dynamic('f')
+ >>> abjad.attach(piano, staff[0])
+ >>> abjad.attach(piano, staff[1])
+ >>> abjad.attach(piano, staff[2])
+ >>> abjad.attach(piano, staff[6])
+ >>> abjad.attach(forte, staff[7])
+ >>> print(format(staff))
+ \new Staff {
+ c'2 \p
+ d'2
+ e'2 \parenthesizeDynamic \p
+ f'2
+ g'2
+ a'2
+ b'2 \p
+ c''2 \f
+ }
+
+ '''
+
+ ### CLASS VARIABLES ###
+
+ __slots__ = ()
+
+ _scheme = abjad.String.normalize('''
+ parenthesizeDynamic = #(define-event-function (parser location dyn) (ly:event?)
+ (make-dynamic-script
+ #{ \markup \concat {
+ \normal-text \italic \fontsize #2 (
+ \pad-x #0.2 #(ly:music-property dyn 'text)
+ \normal-text \italic \fontsize #2 )
+ }
+ #}))
+ ''')
+
+ ### PRIVATE METHODS ###
+
+ def _attachment_test_all(self, component_expression):
+ return True
+
+ def _get_lilypond_format_bundle(self, component):
+ indicators = component._get_indicators(abjad.Dynamic)
+ assert len(indicators) == 1
+ bundle = systemtools.LilyPondFormatBundle()
+ if self.name == 'niente':
+ return bundle
+ string = r'\{}'.format(self.name)
+ if not isinstance(component, abjad.Leaf):
+ component = next(iterate(component).by_leaf())
+ indicator_expression = component._get_effective(
+ abjad.Dynamic,
+ unwrap=False,
+ n=-1,
+ )
+ if indicator_expression is None:
+ bundle.right.indicators.append(string)
+ return bundle
+ previous_indicator = indicator_expression.indicator
+ previous_component = indicator_expression.component
+ previous_name = previous_indicator.name
+ previous_name = \
+ self._composite_dynamic_name_to_steady_state_dynamic_name.get(
+ previous_name, previous_name)
+ if previous_name != self.name:
+ bundle.right.indicators.append(string)
+ return bundle
+ if not isinstance(previous_component, abjad.Leaf):
+ previous_component = next(iterate(previous_component).by_leaf())
+ if component._logical_measure_number is None:
+ component._update_logical_measure_numbers()
+ measure_number = component._logical_measure_number
+ previous_measure_number = previous_component._logical_measure_number
+ assert measure_number is not None
+ assert previous_measure_number is not None
+ if measure_number == previous_measure_number:
+ return bundle
+ elif abs(measure_number - previous_measure_number) == 1:
+ string = r'\parenthesizeDynamic {}'.format(string)
+ bundle.right.indicators.append(string)
+ return bundle
+ bundle.right.indicators.append(string)
+ return bundle
diff --git a/pool/shard003/Python/0028983_views.py b/pool/shard003/Python/0028983_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5045d9f7d2872f3036d7486001f84a0f8394b06
--- /dev/null
+++ b/pool/shard003/Python/0028983_views.py
@@ -0,0 +1,129 @@
+from django.http import JsonResponse
+from django.views.generic import TemplateView
+
+import requests
+
+
+class JSONResponseMixin(object):
+ """
+ A mixin that can be used to render a JSON response.
+ """
+ def render_to_json_response(self, context, **response_kwargs):
+ """
+ Returns a JSON response, transforming 'context' to make the payload.
+ """
+ return JsonResponse(
+ self.get_data(context),
+ **response_kwargs
+ )
+
+ def get_data(self, context):
+ """
+ Returns an object that will be serialized as JSON by json.dumps().
+ """
+ url = self.request.GET.get('url')
+ counts = {}
+ if url:
+ twitter = self.twitter_count(url)
+ if twitter:
+ counts['twitter'] = twitter
+ facebook = self.facebook_count(url)
+ if facebook:
+ counts['facebook'] = facebook
+ flattr = self.flattr_count(url)
+ if flattr:
+ counts['flattr'] = flattr
+ google_plus = self.google_plus_count(url)
+ if google_plus:
+ counts['googleplus'] = google_plus
+ linkedin = self.linkedin_count(url)
+ if linkedin:
+ counts['linkedin'] = linkedin
+ xing = self.xing_count(url)
+ if xing:
+ counts['xing'] = xing
+ pinterest = self.pinterest_count(url)
+ if pinterest:
+ counts['pinterest'] = pinterest
+
+ return counts
+
+ def twitter_count(self, url):
+ twitter_url = 'http://urls.api.twitter.com/1/urls/count.json?url='
+ response = requests.get(twitter_url + url)
+ if response.status_code == 200 and u'count' in response.json().keys():
+ return response.json()['count']
+
+ def facebook_count(self, url):
+ facebook_url = 'https://api.facebook.com/method/fql.query?format=json'
+ facebook_url += '&query=select share_count from link_stat where url=\"'
+ response = requests.get(facebook_url + url + '\"')
+ if (
+ response.status_code == 200 and
+ len(response.json()) and
+ u'share_count' in response.json()[0].keys()
+ ):
+ return response.json()[0]['share_count']
+
+ def flattr_count(self, url):
+ flattr_url = 'https://api.flattr.com/rest/v2/things/lookup/?url='
+ response = requests.get(flattr_url + url)
+ if response.status_code == 200 and u'flattrs' in response.json().keys():
+ return response.json()['flattrs']
+
+ def google_plus_count(self, url):
+ google_plus_url = 'https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ'
+ if url[:4] != 'http':
+ url = 'http://' + url
+ payload = {
+ 'method': 'pos.plusones.get',
+ 'params': {
+ 'nolog': True,
+ 'id': url,
+ 'source': 'widget',
+ 'userId': '@viewer',
+ 'groupId': '@serf'
+ },
+ 'jsonrpc': '2.0',
+ 'key': 'p',
+ 'apiVersion': 'v1'
+ }
+ response = requests.post(google_plus_url, json=payload)
+ resp_json = response.json()
+ if (
+ response.status_code == 200 and
+ 'error' not in resp_json.keys() and
+ 'count' in resp_json['result']['metadata']['globalCounts'].keys()
+ ):
+ return resp_json['result']['metadata']['globalCounts']['count']
+
+ def linkedin_count(self, url):
+ linkedin_url = 'https://www.linkedin.com/countserv/count/share?url='
+ response = requests.get(linkedin_url + url + '&lang=de_DE&format=json')
+ if response.status_code == 200 and u'count' in response.json().keys():
+ return response.json()['count']
+
+ def xing_count(self, url):
+ xing_url = 'https://www.xing-share.com/spi/shares/statistics'
+ payload = {'url': url}
+ response = requests.post(xing_url, data=payload)
+ if (
+ response.status_code == 200 and
+ 'share_counter' in response.json().keys()
+ ):
+ return int(response.json()['share_counter'])
+
+ def pinterest_count(self, url):
+ pinterest_url = 'http://api.pinterest.com/v1/urls/count.json?callback=_&url='
+ if url[:4] != 'http':
+ url = 'http://' + url
+ response = requests.get(pinterest_url + url)
+ import json
+ json_response = json.loads(response.text[2:-1])
+ if response.status_code == 200 and u'count' in json_response.keys():
+ return json_response['count']
+
+
+class DataBackendView(JSONResponseMixin, TemplateView):
+ def render_to_response(self, context, **response_kwargs):
+ return self.render_to_json_response(context, **response_kwargs)
diff --git a/pool/shard003/Python/0028988_merge.py b/pool/shard003/Python/0028988_merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5dde709083c5cc61ba53f2c4b3c6ba21bbc3118
--- /dev/null
+++ b/pool/shard003/Python/0028988_merge.py
@@ -0,0 +1,95 @@
+from django.conf import settings
+from django.core.exceptions import PermissionDenied
+from django.utils.translation import ugettext as _, ungettext
+
+from rest_framework.response import Response
+
+from misago.acl import add_acl
+
+from ...permissions.threads import exclude_invisible_posts
+from ...serializers import PostSerializer
+
+
+MERGE_LIMIT = settings.MISAGO_POSTS_PER_PAGE + settings.MISAGO_POSTS_TAIL
+
+
+class MergeError(Exception):
+ def __init__(self, msg):
+ self.msg = msg
+
+
+def posts_merge_endpoint(request, thread):
+ if not thread.acl['can_merge_posts']:
+ raise PermissionDenied(_("You can't merge posts in this thread."))
+
+ try:
+ posts = clean_posts_for_merge(request, thread)
+ except MergeError as e:
+ return Response({'detail': e.msg}, status=400)
+
+ first_post, merged_posts = posts[0], posts[1:]
+ for post in merged_posts:
+ post.merge(first_post)
+ post.delete()
+ first_post.save()
+
+ thread.synchronize()
+ thread.save()
+
+ thread.category.synchronize()
+ thread.category.save()
+
+ first_post.thread = thread
+ first_post.category = thread.category
+
+ add_acl(request.user, first_post)
+
+ return Response(PostSerializer(first_post, context={'user': request.user}).data)
+
+
+def clean_posts_for_merge(request, thread):
+ try:
+ posts_ids = list(map(int, request.data.get('posts', [])))
+ except (ValueError, TypeError):
+ raise MergeError(_("One or more post ids received were invalid."))
+
+ if len(posts_ids) < 2:
+ raise MergeError(_("You have to select at least two posts to merge."))
+ elif len(posts_ids) > MERGE_LIMIT:
+ message = ungettext(
+ "No more than %(limit)s post can be merged at single time.",
+ "No more than %(limit)s posts can be merged at single time.",
+ MERGE_LIMIT)
+ raise MergeError(message % {'limit': MERGE_LIMIT})
+
+ posts_queryset = exclude_invisible_posts(request.user, thread.category, thread.post_set)
+ posts_queryset = posts_queryset.select_for_update().filter(id__in=posts_ids).order_by('id')
+
+ posts = []
+ for post in posts_queryset:
+ if post.is_event:
+ raise MergeError(_("Events can't be merged."))
+ if post.is_hidden and not (post.pk == thread.first_post_id or thread.category.acl['can_hide_posts']):
+ raise MergeError(_("You can't merge posts the content you can't see."))
+
+ if not posts:
+ posts.append(post)
+ else:
+ authorship_error = _("Posts made by different users can't be merged.")
+ if posts[0].poster_id:
+ if post.poster_id != posts[0].poster_id:
+ raise MergeError(authorship_error)
+ else:
+ if post.poster_id or post.poster_name != posts[0].poster_name:
+ raise MergeError(authorship_error)
+
+ if posts[0].pk != thread.first_post_id:
+ if posts[0].is_hidden != post.is_hidden or posts[0].is_unapproved != post.is_unapproved:
+ raise MergeError(_("Posts with different visibility can't be merged."))
+
+ posts.append(post)
+
+ if len(posts) != len(posts_ids):
+ raise MergeError(_("One or more posts to merge could not be found."))
+
+ return posts
diff --git a/pool/shard003/Python/0028990_init__.py b/pool/shard003/Python/0028990_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..37966c73bd67a8da641a5851a54a9d22ed002421
--- /dev/null
+++ b/pool/shard003/Python/0028990_init__.py
@@ -0,0 +1,193 @@
+# Authors: David Goodger, Ueli Schlaepfer
+# Contact: goodger@users.sourceforge.net
+# Revision: $Revision: 21817 $
+# Date: $Date: 2005-07-21 13:39:57 -0700 (Thu, 21 Jul 2005) $
+# Copyright: This module has been placed in the public domain.
+
+"""
+This package contains modules for standard tree transforms available
+to Docutils components. Tree transforms serve a variety of purposes:
+
+- To tie up certain syntax-specific "loose ends" that remain after the
+ initial parsing of the input plaintext. These transforms are used to
+ supplement a limited syntax.
+
+- To automate the internal linking of the document tree (hyperlink
+ references, footnote references, etc.).
+
+- To extract useful information from the document tree. These
+ transforms may be used to construct (for example) indexes and tables
+ of contents.
+
+Each transform is an optional step that a Docutils Reader may choose to
+perform on the parsed document, depending on the input context. A Docutils
+Reader may also perform Reader-specific transforms before or after performing
+these standard transforms.
+"""
+
+__docformat__ = 'reStructuredText'
+
+
+from docutils import languages, ApplicationError, TransformSpec
+
+
+class TransformError(ApplicationError): pass
+
+
+class Transform:
+
+ """
+ Docutils transform component abstract base class.
+ """
+
+ default_priority = None
+ """Numerical priority of this transform, 0 through 999 (override)."""
+
+ def __init__(self, document, startnode=None):
+ """
+ Initial setup for in-place document transforms.
+ """
+
+ self.document = document
+ """The document tree to transform."""
+
+ self.startnode = startnode
+ """Node from which to begin the transform. For many transforms which
+ apply to the document as a whole, `startnode` is not set (i.e. its
+ value is `None`)."""
+
+ self.language = languages.get_language(
+ document.settings.language_code)
+ """Language module local to this document."""
+
+ def apply(self, **kwargs):
+ """Override to apply the transform to the document tree."""
+ raise NotImplementedError('subclass must override this method')
+
+
+class Transformer(TransformSpec):
+
+ """
+ Stores transforms (`Transform` classes) and applies them to document
+ trees. Also keeps track of components by component type name.
+ """
+
+ from docutils.transforms import universal
+
+ stage1_transforms = (universal.Decorations,
+ universal.ExposeInternals)
+ """Suggested replacement for `default_transforms` when generating
+ a document tree without writing it."""
+
+ stage2_transforms = (universal.Messages,
+ universal.FilterMessages)
+ """Suggested replacement for `default_transforms` when writing a
+ previously-parsed document tree. Only transforms which *must* be applied
+ after writer-specific transforms should be added to this list."""
+
+ default_transforms = stage1_transforms + stage2_transforms
+ """These transforms are applied to all document trees."""
+
+ def __init__(self, document):
+ self.transforms = []
+ """List of transforms to apply. Each item is a 3-tuple:
+ ``(priority string, transform class, pending node or None)``."""
+
+ self.unknown_reference_resolvers = []
+ """List of hook functions which assist in resolving references"""
+
+ self.document = document
+ """The `nodes.document` object this Transformer is attached to."""
+
+ self.applied = []
+ """Transforms already applied, in order."""
+
+ self.sorted = 0
+ """Boolean: is `self.tranforms` sorted?"""
+
+ self.components = {}
+ """Mapping of component type name to component object. Set by
+ `self.populate_from_components()`."""
+
+ self.serialno = 0
+ """Internal serial number to keep track of the add order of
+ transforms."""
+
+ def add_transform(self, transform_class, priority=None, **kwargs):
+ """
+ Store a single transform. Use `priority` to override the default.
+ `kwargs` is a dictionary whose contents are passed as keyword
+ arguments to the `apply` method of the transform. This can be used to
+ pass application-specific data to the transform instance.
+ """
+ if priority is None:
+ priority = transform_class.default_priority
+ priority_string = self.get_priority_string(priority)
+ self.transforms.append(
+ (priority_string, transform_class, None, kwargs))
+ self.sorted = 0
+
+ def add_transforms(self, transform_list):
+ """Store multiple transforms, with default priorities."""
+ for transform_class in transform_list:
+ priority_string = self.get_priority_string(
+ transform_class.default_priority)
+ self.transforms.append(
+ (priority_string, transform_class, None, {}))
+ self.sorted = 0
+
+ def add_pending(self, pending, priority=None):
+ """Store a transform with an associated `pending` node."""
+ transform_class = pending.transform
+ if priority is None:
+ priority = transform_class.default_priority
+ priority_string = self.get_priority_string(priority)
+ self.transforms.append(
+ (priority_string, transform_class, pending, {}))
+ self.sorted = 0
+
+ def get_priority_string(self, priority):
+ """
+ Return a string, `priority` combined with `self.serialno`.
+
+ This ensures FIFO order on transforms with identical priority.
+ """
+ self.serialno += 1
+ return '%03d-%03d' % (priority, self.serialno)
+
+ def populate_from_components(self, components):
+ """
+ Store each component's default transforms, with default priorities.
+ Also, store components by type name in a mapping for later lookup.
+ """
+ self.add_transforms(self.default_transforms)
+ for component in components:
+ if component is None:
+ continue
+ self.add_transforms(component.default_transforms)
+ self.components[component.component_type] = component
+ self.sorted = 0
+ # Set up all of the reference resolvers for this transformer. Each
+ # component of this transformer is able to register its own helper
+ # functions to help resolve references.
+ unknown_reference_resolvers = []
+ for i in components:
+ unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
+ decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
+ decorated_list.sort()
+ self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
+
+ def apply_transforms(self):
+ """Apply all of the stored transforms, in priority order."""
+ self.document.reporter.attach_observer(
+ self.document.note_transform_message)
+ while self.transforms:
+ if not self.sorted:
+ # Unsorted initially, and whenever a transform is added.
+ self.transforms.sort()
+ self.transforms.reverse()
+ self.sorted = 1
+ priority, transform_class, pending, kwargs = self.transforms.pop()
+ transform = transform_class(self.document, startnode=pending)
+ transform.apply(**kwargs)
+ self.applied.append((priority, transform_class, pending, kwargs))
diff --git a/pool/shard003/Python/0028991_test_graph.py b/pool/shard003/Python/0028991_test_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..780a165b20fb6f34a5db2bd118dc9f93ef66edbf
--- /dev/null
+++ b/pool/shard003/Python/0028991_test_graph.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+import sys
+sys.path.append("../")
+from unittest import TestCase, main
+from chat.graph import Database
+from chat.mytools import Walk, time_me
+
+
+class WalkUserData(Walk):
+ def handle_file(self, filepath, pattern=None):
+ self.db.handle_excel(filepath)
+
+
+class TestMe(TestCase):
+ def setUp(self):
+ self.database = Database(password="train", userid="A0001")
+ self.db2 = Database(password="train", userid="A0002")
+ self.db3 = Database(password="train", userid="A0003")
+
+ def test_add_userdata(self):
+ """Add userdata from usb.
+ """
+ # path = "D:/新知识库"
+ # walker = WalkUserData(db=self.database)
+ # fnamelist = walker.dir_process(1, path, style="fnamelist")
+ pass
+
+ def test_delete(self):
+ pass
+
+ def test_reset(self):
+ self.database.delete(pattern='n', label='Config') # 删除知识库配置
+ # self.database.reset(pattern="n", label='NluCell', filename="chat_context.xls")
+ self.database.reset(pattern="n", label='NluCell', filename="chat.xls")
+ self.db2.handle_excel("chat_bank.xls")
+ self.db3.handle_excel("chat_hospital.xls")
+ pass
+
+ def test_reset_ts(self):
+ """Reset data of label 'TestStandard' in database.
+ """
+ # self.database.reset_ts(pattern="n", label="TestStandard", filename="C:/nlu/data/kb/ts.xls")
+ pass
+
+ def test_add_ts(self):
+ # self.database.handle_ts("C:/nlu/data/kb/ts.xls")
+ pass
+
+ # @time_me(format_string="ms")
+ def test_add_qa(self):
+ # 1.Add qa with excel
+ # self.db2.handle_excel("chat_bank.xls")
+ # self.db3.handle_excel("chat_hospital.xls")
+ # 2.Add qa with txt
+ # self.database.handle_txt("C:/nlu/data/kb/bank.txt")
+ pass
+
+ def test_download(self):
+ # akbs = self.database.get_available_kb()
+ # self.database.download(filename="全部.xls", names=akbs)
+ # self.database.download(filename="银行业务.xls", names=["银行业务"])
+ # self.database.download_scene(filename="理财产品.xls", topic="理财产品")
+ pass
+
+ def test_generate_test_cases(self):
+ # self.database.generate_test_cases(
+ # filename="chat.xls",
+ # custom_sheets=["银行业务"],
+ # savedir="."
+ # )
+ pass
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard003/Python/0028994_runserver.py b/pool/shard003/Python/0028994_runserver.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8669477e0db999104f9eb79a786bc5c1f49fa20
--- /dev/null
+++ b/pool/shard003/Python/0028994_runserver.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+import argparse
+
+from foodninja import app
+from foodninja.settings import DEBUG
+
+
+if __name__ == '__main__':
+ """Runs the foodninja application"""
+ parser = argparse.ArgumentParser(description='Run the foodninja webserver')
+ parser.add_argument("--host", type=str, default='localhost',
+ help="Webserver host")
+ parser.add_argument("--port", type=int, default=5000,
+ help="Webserver port")
+ parser.add_argument("--debug", action="store_true", default=DEBUG,
+ help="Set debug mode")
+ args_dict = vars(parser.parse_args())
+ app.run(host=args_dict['host'], port=args_dict['port'],
+ debug=args_dict['debug'])
diff --git a/pool/shard003/Python/0028998_Fermat.py b/pool/shard003/Python/0028998_Fermat.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9587d6b7733270043361a9f96592067bf978c75
--- /dev/null
+++ b/pool/shard003/Python/0028998_Fermat.py
@@ -0,0 +1,21 @@
+'''
+Created on 11 May 2016
+
+@author: wnm24546
+'''
+
+import matplotlib.pyplot as plt
+import numpy as np
+
+def makePlot(a=1, b=4.8):
+ fig = plt.figure()
+ ax = fig.add_axes([0.12, 0.12, 0.76, 0.76], polar=True)
+ r = np.arange(-8*np.pi, 8*np.pi, 0.01)
+ theta = ((r+a)/b)**2
+ ax.plot(theta, r, color='#00c000', lw=2)
+
+ plt.show()
+
+ fig.savefig(r"FermatSpiral.svg")
+
+makePlot()
\ No newline at end of file
diff --git a/pool/shard003/Python/0029001_become.py b/pool/shard003/Python/0029001_become.py
new file mode 100644
index 0000000000000000000000000000000000000000..374411cb141d62111d0eef940d41774fc0f58f25
--- /dev/null
+++ b/pool/shard003/Python/0029001_become.py
@@ -0,0 +1,92 @@
+# (c) 2012-2014, Michael DeHaan
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible. If not, see .
+
+# Make coding more python3-ish
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+from ansible import constants as C
+from ansible.errors import AnsibleParserError
+from ansible.playbook.attribute import FieldAttribute
+from ansible.utils.display import Display
+
+display = Display()
+
+
+class Become:
+
+ # Privilege escalation
+ _become = FieldAttribute(isa='bool')
+ _become_method = FieldAttribute(isa='string')
+ _become_user = FieldAttribute(isa='string')
+ _become_flags = FieldAttribute(isa='string')
+
+ def __init__(self):
+ super(Become, self).__init__()
+
+ def _detect_privilege_escalation_conflict(self, ds):
+
+ # Fail out if user specifies conflicting privilege escalations
+ has_become = 'become' in ds or 'become_user'in ds
+ has_sudo = 'sudo' in ds or 'sudo_user' in ds
+ has_su = 'su' in ds or 'su_user' in ds
+
+ if has_become:
+ msg = 'The become params ("become", "become_user") and'
+ if has_sudo:
+ raise AnsibleParserError('%s sudo params ("sudo", "sudo_user") cannot be used together' % msg)
+ elif has_su:
+ raise AnsibleParserError('%s su params ("su", "su_user") cannot be used together' % msg)
+ elif has_sudo and has_su:
+ raise AnsibleParserError('sudo params ("sudo", "sudo_user") and su params ("su", "su_user") cannot be used together')
+
+ def _preprocess_data_become(self, ds):
+ """Preprocess the playbook data for become attributes
+
+ This is called from the Base object's preprocess_data() method which
+ in turn is called pretty much anytime any sort of playbook object
+ (plays, tasks, blocks, etc) is created.
+ """
+
+ self._detect_privilege_escalation_conflict(ds)
+
+ # Privilege escalation, backwards compatibility for sudo/su
+ if 'sudo' in ds or 'sudo_user' in ds:
+ ds['become_method'] = 'sudo'
+ if 'sudo' in ds:
+ ds['become'] = ds['sudo']
+ del ds['sudo']
+
+ if 'sudo_user' in ds:
+ ds['become_user'] = ds['sudo_user']
+ del ds['sudo_user']
+
+ display.deprecated("Instead of sudo/sudo_user, use become/become_user and make sure become_method is 'sudo' (default)", '2.9')
+
+ elif 'su' in ds or 'su_user' in ds:
+ ds['become_method'] = 'su'
+ if 'su' in ds:
+ ds['become'] = ds['su']
+ del ds['su']
+
+ if 'su_user' in ds:
+ ds['become_user'] = ds['su_user']
+ del ds['su_user']
+
+ display.deprecated("Instead of su/su_user, use become/become_user and set become_method to 'su' (default is sudo)", '2.9')
+
+ return ds
diff --git a/pool/shard003/Python/0029005_nltk_scikit_ngram_liu.py b/pool/shard003/Python/0029005_nltk_scikit_ngram_liu.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebfae0065d08a43b60205fffde2ee101397aab98
--- /dev/null
+++ b/pool/shard003/Python/0029005_nltk_scikit_ngram_liu.py
@@ -0,0 +1,124 @@
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+# Authors: Felipe Bravo-Marquez
+
+
+import pandas as pd
+from nltk.tokenize import TweetTokenizer
+from nltk.sentiment.util import mark_negation
+from nltk.corpus import opinion_lexicon
+
+from sklearn.feature_extraction.text import CountVectorizer
+from sklearn.linear_model import LogisticRegression
+from sklearn.pipeline import Pipeline, FeatureUnion
+from sklearn.base import BaseEstimator, TransformerMixin
+from sklearn.metrics import confusion_matrix, cohen_kappa_score, classification_report
+import numpy as np
+
+
+# load training and testing datasets as a pandas dataframe
+train_data = pd.read_csv("dataset/twitter-train-B.txt", header=None, delimiter="\t",usecols=(2,3), names=("sent","tweet"))
+test_data = pd.read_csv("dataset/twitter-test-gold-B.tsv", header=None, delimiter="\t",usecols=(2,3), names=("sent","tweet"))
+
+# replace objective-OR-neutral and objective to neutral
+train_data.sent = train_data.sent.replace(['objective-OR-neutral','objective'],['neutral','neutral'])
+
+# use a Twitter-specific tokenizer
+tokenizer = TweetTokenizer(preserve_case=False, reduce_len=True)
+
+
+
+
+#####################################################################################
+#
+# Train a linear model using n-grams features + features derived from Bing Liu's lexicon
+#
+######################################################################################
+#import nltk
+#nltk.download('opinion_lexicon')
+
+
+# load training and testing datasets as a pandas dataframe
+train_data = pd.read_csv("dataset/twitter-train-B.txt", header=None, delimiter="\t",usecols=(2,3), names=("sent","tweet"))
+test_data = pd.read_csv("dataset/twitter-test-gold-B.tsv", header=None, delimiter="\t",usecols=(2,3), names=("sent","tweet"))
+
+# replace objective-OR-neutral and objective to neutral
+train_data.sent = train_data.sent.replace(['objective-OR-neutral','objective'],['neutral','neutral'])
+
+# use a Twitter-specific tokenizer
+tokenizer = TweetTokenizer(preserve_case=False, reduce_len=True)
+
+
+
+
+class LiuFeatureExtractor(BaseEstimator, TransformerMixin):
+ """Takes in a corpus of tweets and calculates features using Bing Liu's lexicon"""
+
+ def __init__(self, tokenizer):
+ self.tokenizer = tokenizer
+ self.pos_set = set(opinion_lexicon.positive())
+ self.neg_set = set(opinion_lexicon.negative())
+
+ def liu_score(self,sentence):
+ """Calculates the number of positive and negative words in the sentence using Bing Liu's Lexicon"""
+ tokenized_sent = self.tokenizer.tokenize(sentence)
+ pos_words = 0
+ neg_words = 0
+ for word in tokenized_sent:
+ if word in self.pos_set:
+ pos_words += 1
+ elif word in self.neg_set:
+ neg_words += 1
+ return [pos_words,neg_words]
+
+ def transform(self, X, y=None):
+ """Applies liu_score and vader_score on a data.frame containing tweets """
+ values = []
+ for tweet in X:
+ values.append(self.liu_score(tweet))
+
+ return(np.array(values))
+
+ def fit(self, X, y=None):
+ """This function must return `self` unless we expect the transform function to perform a
+ different action on training and testing partitions (e.g., when we calculate unigram features,
+ the dictionary is only extracted from the first batch)"""
+ return self
+
+
+
+
+
+liu_feat = LiuFeatureExtractor(tokenizer)
+vectorizer = CountVectorizer(tokenizer = tokenizer.tokenize, preprocessor = mark_negation, ngram_range=(1,4))
+log_mod = LogisticRegression(solver='liblinear',multi_class='ovr')
+liu_ngram_clf = Pipeline([ ('feats',
+ FeatureUnion([ ('ngram', vectorizer), ('liu',liu_feat) ])),
+ ('clf', log_mod)])
+
+
+liu_ngram_clf.fit(train_data.tweet, train_data.sent)
+pred_liu_ngram = liu_ngram_clf.predict(test_data.tweet)
+
+
+conf_liu_ngram = confusion_matrix(test_data.sent, pred_liu_ngram)
+kappa_liu_ngram = cohen_kappa_score(test_data.sent, pred_liu_ngram)
+class_rep_liu_ngram = classification_report(test_data.sent, pred_liu_ngram)
+
+print('Confusion Matrix for Logistic Regression + ngrams + features from Bing Liu\'s Lexicon')
+print(conf_liu_ngram)
+print('Classification Report')
+print(class_rep_liu_ngram)
+print('kappa:'+str(kappa_liu_ngram))
+
diff --git a/pool/shard003/Python/0029011_config_flow.py b/pool/shard003/Python/0029011_config_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b2f622d6e71ab7b522f44119e4427a4b6f4203a
--- /dev/null
+++ b/pool/shard003/Python/0029011_config_flow.py
@@ -0,0 +1,160 @@
+"""Config flow for the Abode Security System component."""
+from abodepy import Abode
+from abodepy.exceptions import AbodeAuthenticationException, AbodeException
+from abodepy.helpers.errors import MFA_CODE_REQUIRED
+from requests.exceptions import ConnectTimeout, HTTPError
+import voluptuous as vol
+
+from homeassistant import config_entries
+from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_BAD_REQUEST
+
+from .const import DEFAULT_CACHEDB, DOMAIN, LOGGER
+
+CONF_MFA = "mfa_code"
+CONF_POLLING = "polling"
+
+
+class AbodeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
+ """Config flow for Abode."""
+
+ VERSION = 1
+
+ def __init__(self):
+ """Initialize."""
+ self.data_schema = {
+ vol.Required(CONF_USERNAME): str,
+ vol.Required(CONF_PASSWORD): str,
+ }
+ self.mfa_data_schema = {
+ vol.Required(CONF_MFA): str,
+ }
+
+ self._cache = None
+ self._mfa_code = None
+ self._password = None
+ self._polling = False
+ self._username = None
+
+ async def _async_abode_login(self, step_id):
+ """Handle login with Abode."""
+ self._cache = self.hass.config.path(DEFAULT_CACHEDB)
+ errors = {}
+
+ try:
+ await self.hass.async_add_executor_job(
+ Abode, self._username, self._password, True, False, False, self._cache
+ )
+
+ except (AbodeException, ConnectTimeout, HTTPError) as ex:
+ if ex.errcode == MFA_CODE_REQUIRED[0]:
+ return await self.async_step_mfa()
+
+ LOGGER.error("Unable to connect to Abode: %s", ex)
+
+ if ex.errcode == HTTP_BAD_REQUEST:
+ errors = {"base": "invalid_auth"}
+
+ else:
+ errors = {"base": "cannot_connect"}
+
+ if errors:
+ return self.async_show_form(
+ step_id=step_id, data_schema=vol.Schema(self.data_schema), errors=errors
+ )
+
+ return await self._async_create_entry()
+
+ async def _async_abode_mfa_login(self):
+ """Handle multi-factor authentication (MFA) login with Abode."""
+ try:
+ # Create instance to access login method for passing MFA code
+ abode = Abode(
+ auto_login=False,
+ get_devices=False,
+ get_automations=False,
+ cache_path=self._cache,
+ )
+ await self.hass.async_add_executor_job(
+ abode.login, self._username, self._password, self._mfa_code
+ )
+
+ except AbodeAuthenticationException:
+ return self.async_show_form(
+ step_id="mfa",
+ data_schema=vol.Schema(self.mfa_data_schema),
+ errors={"base": "invalid_mfa_code"},
+ )
+
+ return await self._async_create_entry()
+
+ async def _async_create_entry(self):
+ """Create the config entry."""
+ config_data = {
+ CONF_USERNAME: self._username,
+ CONF_PASSWORD: self._password,
+ CONF_POLLING: self._polling,
+ }
+ existing_entry = await self.async_set_unique_id(self._username)
+
+ if existing_entry:
+ self.hass.config_entries.async_update_entry(
+ existing_entry, data=config_data
+ )
+ # Reload the Abode config entry otherwise devices will remain unavailable
+ self.hass.async_create_task(
+ self.hass.config_entries.async_reload(existing_entry.entry_id)
+ )
+
+ return self.async_abort(reason="reauth_successful")
+
+ return self.async_create_entry(title=self._username, data=config_data)
+
+ async def async_step_user(self, user_input=None):
+ """Handle a flow initialized by the user."""
+ if self._async_current_entries():
+ return self.async_abort(reason="single_instance_allowed")
+
+ if user_input is None:
+ return self.async_show_form(
+ step_id="user", data_schema=vol.Schema(self.data_schema)
+ )
+
+ self._username = user_input[CONF_USERNAME]
+ self._password = user_input[CONF_PASSWORD]
+
+ return await self._async_abode_login(step_id="user")
+
+ async def async_step_mfa(self, user_input=None):
+ """Handle a multi-factor authentication (MFA) flow."""
+ if user_input is None:
+ return self.async_show_form(
+ step_id="mfa", data_schema=vol.Schema(self.mfa_data_schema)
+ )
+
+ self._mfa_code = user_input[CONF_MFA]
+
+ return await self._async_abode_mfa_login()
+
+ async def async_step_reauth(self, config):
+ """Handle reauthorization request from Abode."""
+ self._username = config[CONF_USERNAME]
+
+ return await self.async_step_reauth_confirm()
+
+ async def async_step_reauth_confirm(self, user_input=None):
+ """Handle reauthorization flow."""
+ if user_input is None:
+ return self.async_show_form(
+ step_id="reauth_confirm",
+ data_schema=vol.Schema(
+ {
+ vol.Required(CONF_USERNAME, default=self._username): str,
+ vol.Required(CONF_PASSWORD): str,
+ }
+ ),
+ )
+
+ self._username = user_input[CONF_USERNAME]
+ self._password = user_input[CONF_PASSWORD]
+
+ return await self._async_abode_login(step_id="reauth_confirm")
diff --git a/pool/shard003/Python/0029013_contract.py b/pool/shard003/Python/0029013_contract.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9bbc1ad9abfd3392a66a32f8a5b82294f1b3c2a
--- /dev/null
+++ b/pool/shard003/Python/0029013_contract.py
@@ -0,0 +1,26 @@
+import pandas as pd
+import numpy as np
+
+contract1 = {'id': 1,
+ 'id_client': 1,
+ 'id_corporation': 1,
+ 'monthly_price': 200.00,
+ 'price': 0.0,
+ 'start':'23-07-2016',
+ 'end': '23-07-2017',
+ 'name': 'seguro falso'}
+
+contract2 = {'id': 2,
+ 'id_client': 2,
+ 'id_corporation': 2,
+ 'monthly_price': 0.0,
+ 'price': 1700.00,
+ 'start': '02-02-2015',
+ 'end': '05-05-2017',
+ 'name': 'Seguro auto falso'}
+
+Contract1 = pd.Series(contract1)
+Contract2 = pd.Series(contract2)
+Contracts = pd.DataFrame([Contract1, Contract2])
+
+Contracts.to_csv('contract.csv')
\ No newline at end of file
diff --git a/pool/shard003/Python/0029017_test_morse_cluster.py b/pool/shard003/Python/0029017_test_morse_cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..256482f49dd9120fa78b746fe6189495c23e74c9
--- /dev/null
+++ b/pool/shard003/Python/0029017_test_morse_cluster.py
@@ -0,0 +1,31 @@
+import unittest
+
+from pele.systems import MorseCluster
+
+
+class TestLJClusterSystem(unittest.TestCase):
+ def setUp(self):
+ self.natoms = 13
+ self.system = MorseCluster(self.natoms)
+
+ def test_database_property(self):
+ db = self.system.create_database()
+ p = db.get_property("natoms")
+ self.assertIsNotNone(p)
+ self.assertEqual(p.value(), 13)
+
+ def test_permlist(self):
+ permlist = self.system.get_permlist()
+ self.assertEqual(len(permlist), 1)
+ for i, v in enumerate(sorted(permlist[0])):
+ self.assertEqual(i, v)
+
+ def test_bh(self):
+ db = self.system.create_database()
+ bh = self.system.get_basinhopping(db)
+ bh.run(3)
+ self.assertGreater(db.number_of_minima(), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
diff --git a/pool/shard003/Python/0029018_ec2_ami_search.py b/pool/shard003/Python/0029018_ec2_ami_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e0f25831e32a8c0bb346c9f3690825771616be1
--- /dev/null
+++ b/pool/shard003/Python/0029018_ec2_ami_search.py
@@ -0,0 +1,216 @@
+#!/usr/bin/python
+#
+# (c) 2013, Nimbis Services
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible. If not, see .
+
+ANSIBLE_METADATA = {'status': ['deprecated'],
+ 'supported_by': 'community',
+ 'version': '1.0'}
+
+DOCUMENTATION = '''
+---
+module: ec2_ami_search
+short_description: Retrieve AWS AMI information for a given operating system.
+deprecated: "Use M(ec2_ami_find) instead."
+version_added: "1.6"
+description:
+ - Look up the most recent AMI on AWS for a given operating system.
+ - Returns C(ami), C(aki), C(ari), C(serial), C(tag)
+ - If there is no AKI or ARI associated with an image, these will be C(null).
+ - Only supports images from cloud-images.ubuntu.com
+ - 'Example output: C({"ami": "ami-69f5a900", "changed": false, "aki": "aki-88aa75e1", "tag": "release", "ari": null, "serial": "20131024"})'
+options:
+ distro:
+ description: Linux distribution (e.g., C(ubuntu))
+ required: true
+ choices: ["ubuntu"]
+ release:
+ description: short name of the release (e.g., C(precise))
+ required: true
+ stream:
+ description: Type of release.
+ required: false
+ default: "server"
+ choices: ["server", "desktop"]
+ store:
+ description: Back-end store for instance
+ required: false
+ default: "ebs"
+ choices: ["ebs", "ebs-io1", "ebs-ssd", "instance-store"]
+ arch:
+ description: CPU architecture
+ required: false
+ default: "amd64"
+ choices: ["i386", "amd64"]
+ region:
+ description: EC2 region
+ required: false
+ default: us-east-1
+ choices: ["ap-northeast-1", "ap-southeast-1", "ap-northeast-2",
+ "ap-southeast-2", "ca-central-1", "eu-central-1", "eu-west-1",
+ "eu-west-2", "sa-east-1", "us-east-1", "us-east-2", "us-west-1",
+ "us-west-2", "us-gov-west-1"]
+ virt:
+ description: virutalization type
+ required: false
+ default: paravirtual
+ choices: ["paravirtual", "hvm"]
+
+author: "Ansible Core Team (deprecated)"
+'''
+
+EXAMPLES = '''
+- name: Launch an Ubuntu 12.04 (Precise Pangolin) EC2 instance
+ hosts: 127.0.0.1
+ connection: local
+ tasks:
+ - name: Get the Ubuntu precise AMI
+ ec2_ami_search:
+ distro: ubuntu
+ release: precise
+ region: us-west-1
+ store: instance-store
+ register: ubuntu_image
+
+ - name: Start the EC2 instance
+ ec2:
+ image: "{{ ubuntu_image.ami }}"
+ instance_type: m1.small
+ key_name: mykey
+'''
+
+import csv
+
+from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils.urls import fetch_url
+
+
+SUPPORTED_DISTROS = ['ubuntu']
+
+AWS_REGIONS = ['ap-northeast-1',
+ 'ap-southeast-1',
+ 'ap-northeast-2',
+ 'ap-southeast-2',
+ 'ap-south-1',
+ 'ca-central-1',
+ 'eu-central-1',
+ 'eu-west-1',
+ 'eu-west-2',
+ 'sa-east-1',
+ 'us-east-1',
+ 'us-east-2',
+ 'us-west-1',
+ 'us-west-2',
+ "us-gov-west-1"]
+
+
+def get_url(module, url):
+ """ Get url and return response """
+
+ r, info = fetch_url(module, url)
+ if info['status'] != 200:
+ # Backwards compat
+ info['status_code'] = info['status']
+ module.fail_json(**info)
+ return r
+
+
+def ubuntu(module):
+ """ Get the ami for ubuntu """
+
+ release = module.params['release']
+ stream = module.params['stream']
+ store = module.params['store']
+ arch = module.params['arch']
+ region = module.params['region']
+ virt = module.params['virt']
+
+ url = get_ubuntu_url(release, stream)
+
+ req = get_url(module, url)
+ reader = csv.reader(req, delimiter='\t')
+ try:
+ ami, aki, ari, tag, serial = lookup_ubuntu_ami(reader, release, stream,
+ store, arch, region, virt)
+ module.exit_json(changed=False, ami=ami, aki=aki, ari=ari, tag=tag,
+ serial=serial)
+ except KeyError:
+ module.fail_json(msg="No matching AMI found")
+
+
+def lookup_ubuntu_ami(table, release, stream, store, arch, region, virt):
+ """ Look up the Ubuntu AMI that matches query given a table of AMIs
+
+ table: an iterable that returns a row of
+ (release, stream, tag, serial, region, ami, aki, ari, virt)
+ release: ubuntu release name
+ stream: 'server' or 'desktop'
+ store: 'ebs', 'ebs-io1', 'ebs-ssd' or 'instance-store'
+ arch: 'i386' or 'amd64'
+ region: EC2 region
+ virt: 'paravirtual' or 'hvm'
+
+ Returns (ami, aki, ari, tag, serial)"""
+ expected = (release, stream, store, arch, region, virt)
+
+ for row in table:
+ (actual_release, actual_stream, tag, serial,
+ actual_store, actual_arch, actual_region, ami, aki, ari,
+ actual_virt) = row
+ actual = (actual_release, actual_stream, actual_store, actual_arch,
+ actual_region, actual_virt)
+ if actual == expected:
+ # aki and ari are sometimes blank
+ if aki == '':
+ aki = None
+ if ari == '':
+ ari = None
+ return (ami, aki, ari, tag, serial)
+
+ raise KeyError()
+
+
+def get_ubuntu_url(release, stream):
+ url = "https://cloud-images.ubuntu.com/query/%s/%s/released.current.txt"
+ return url % (release, stream)
+
+
+def main():
+ arg_spec = dict(
+ distro=dict(required=True, choices=SUPPORTED_DISTROS),
+ release=dict(required=True),
+ stream=dict(required=False, default='server',
+ choices=['desktop', 'server']),
+ store=dict(required=False, default='ebs',
+ choices=['ebs', 'ebs-io1', 'ebs-ssd', 'instance-store']),
+ arch=dict(required=False, default='amd64',
+ choices=['i386', 'amd64']),
+ region=dict(required=False, default='us-east-1', choices=AWS_REGIONS),
+ virt=dict(required=False, default='paravirtual',
+ choices=['paravirtual', 'hvm']),
+ )
+ module = AnsibleModule(argument_spec=arg_spec)
+ distro = module.params['distro']
+
+ if distro == 'ubuntu':
+ ubuntu(module)
+ else:
+ module.fail_json(msg="Unsupported distro: %s" % distro)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard003/Python/0029019_utils.py b/pool/shard003/Python/0029019_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..31da502b278effd1e27d4d253d7d26d56b2ecedd
--- /dev/null
+++ b/pool/shard003/Python/0029019_utils.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2013 by Pablo Martín and
+# Alejandro Blanco
+#
+# This software is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This software is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License
+# along with this software. If not, see .
+
+
+def is_mymetype_python(doc, text_plain=False):
+ mimetype = doc.mimeType()
+ if mimetype == 'text/x-python':
+ return True
+ elif mimetype == 'text/plain' and text_plain:
+ return True
+ return False
+
+
+def canCheckDocument(doc, text_plain=False):
+ return not doc or (is_mymetype_python(doc, text_plain) and
+ not doc.isModified())
+
+# kate: space-indent on; indent-width 4;
diff --git a/pool/shard003/Python/0029022_first_unique_character_solution.py b/pool/shard003/Python/0029022_first_unique_character_solution.py
new file mode 100644
index 0000000000000000000000000000000000000000..8394f16026ec3dbfd70eb5e276666f3271e28389
--- /dev/null
+++ b/pool/shard003/Python/0029022_first_unique_character_solution.py
@@ -0,0 +1,29 @@
+"""
+Finds the first non-repeated character in a string
+
+https://www.codeeval.com/open_challenges/12/
+"""
+import unittest
+
+
+def first_unique_character(s):
+ before = ''
+ for i in range(0, len(s)):
+ char = s[i]
+ after = s[i+1:]
+ if char not in before + after:
+ return char
+ before += char
+
+
+class FirstUniqueCharacterTest(unittest.TestCase):
+ def test_yellow(self):
+ self.assertEquals('y', first_unique_character('yellow'))
+
+ def test_tooth(self):
+ self.assertEquals('h', first_unique_character('tooth'))
+
+
+if __name__ == '__main__':
+ unittest.main(exit=False)
+
diff --git a/pool/shard003/Python/0029023_lbscloud.py b/pool/shard003/Python/0029023_lbscloud.py
new file mode 100644
index 0000000000000000000000000000000000000000..57c68543e9ffc66f977bc025879489d1072e45a7
--- /dev/null
+++ b/pool/shard003/Python/0029023_lbscloud.py
@@ -0,0 +1,92 @@
+# -*- coding:utf-8 -*-
+from __future__ import unicode_literals
+
+
+class GeoTable(object):
+ """
+ 位置数据表
+ """
+ optional_attrs = (
+ 'id', 'create_time', 'modify_time', '_version', 'name', 'geotype',
+ 'is_published'
+ )
+
+ def __init__(self, name, geotype, is_published, **kwargs):
+ self.__data = {}
+ self.__data['name'] = name
+ self.__data['geotype'] = geotype
+ self.__data['is_published'] = is_published
+
+ for key in kwargs:
+ if key not in self.optional_attrs:
+ kwargs.pop(key)
+ self.__data.update(kwargs)
+
+ def __getattr__(self, attr_name):
+ if attr_name in self.__data:
+ return self.__data[attr_name]
+ else:
+ return None
+
+ def __setattr__(self, attr_name, value):
+ if attr_name == 'optional_attrs':
+ pass
+ if attr_name in self.optional_attrs:
+ self.__data[attr_name] = value
+ else:
+ object.__setattr__(self, attr_name, value)
+
+ def __unicode__(self):
+ class_name = str(self.__class__).strip('<>')
+ return "<{0} {1}>".format(class_name, self.name)
+
+ def __str__(self):
+ return self.__unicode__().encode('utf-8')
+
+
+class Column(object):
+ """
+ 百度 LBS 云自定义扩展列
+ """
+ optional_attrs = (
+ 'id', 'max_length', 'default_value', 'is_unique_field',
+ )
+
+ def __init__(
+ self,
+ name,
+ key,
+ type,
+ is_sortfilter_field,
+ is_search_field,
+ is_index_field,
+ **kwargs
+ ):
+
+ self.__data = {}
+ self.__data['name'] = name
+ self.__data['key'] = key
+ self.__data['type'] = type
+ self.__data['is_sortfilter_field'] = is_sortfilter_field
+ self.__data['is_search_field'] = is_search_field
+ self.__data['is_index_field'] = is_index_field
+
+ _kwargs = kwargs.copy()
+ for key in _kwargs:
+ if key not in self.optional_attrs:
+ kwargs.pop(key)
+ self.__data.update(kwargs)
+
+ def __check(self):
+ return self.__data
+
+ @property
+ def data(self):
+ return self.__check()
+
+ def __unicode__(self):
+ class_name = str(self.__class__).strip('<>')
+ return "<{0} {1}>".format(class_name, self.data['name'])
+
+ def __str__(self):
+ return self.__unicode__().encode('utf-8')
diff --git a/pool/shard003/Python/0029027_00-hf_with_dftd3.py b/pool/shard003/Python/0029027_00-hf_with_dftd3.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec34051d65fdd301a607be295a476cc2e30d56f6
--- /dev/null
+++ b/pool/shard003/Python/0029027_00-hf_with_dftd3.py
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+#
+# Author: Qiming Sun
+#
+
+'''
+A simple example of using solvent model in the mean-field calculations.
+'''
+
+from pyscf import gto
+from pyscf import scf
+from pyscf import dftd3
+
+mol = gto.Mole()
+mol.atom = ''' O 0.00000000 0.00000000 -0.11081188
+ H -0.00000000 -0.84695236 0.59109389
+ H -0.00000000 0.89830571 0.52404783 '''
+mol.basis = 'cc-pvdz'
+mol.build()
+
+mf = dftd3.dftd3(scf.RHF(mol))
+print(mf.kernel()) # -75.99396273778923
+
diff --git a/pool/shard003/Python/0029039_account_config_settings.py b/pool/shard003/Python/0029039_account_config_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f19bf37b194025c96f4e854c4719034215cb2a0a
--- /dev/null
+++ b/pool/shard003/Python/0029039_account_config_settings.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# Copyright (C) 2014 Agile Business Group sagl ()
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#
+##############################################################################
+
+from openerp.osv import orm, fields
+
+
+class AccountConfigSettings(orm.TransientModel):
+ _inherit = 'account.config.settings'
+ _columns = {
+ 'vat_on_payment': fields.related(
+ 'company_id', 'vat_on_payment',
+ type='boolean',
+ string="VAT on payment treatment"),
+ }
+
+ def onchange_company_id(self, cr, uid, ids, company_id, context=None):
+ res = super(AccountConfigSettings, self).onchange_company_id(
+ cr, uid, ids, company_id, context=context)
+ if company_id:
+ company = self.pool.get('res.company').browse(
+ cr, uid, company_id, context=context)
+ res['value'].update({
+ 'vat_on_payment': company.vat_on_payment,
+ })
+ else:
+ res['value'].update({
+ 'vat_on_payment': False,
+ })
+ return res
diff --git a/pool/shard003/Python/0029041_stat.py b/pool/shard003/Python/0029041_stat.py
new file mode 100644
index 0000000000000000000000000000000000000000..4813e6b5ef7f18032e1b7965b7d75dd8661ab234
--- /dev/null
+++ b/pool/shard003/Python/0029041_stat.py
@@ -0,0 +1,63 @@
+import operator
+
+# Find the mean, median, and mode in a list of numbers:
+#1) list(range(1,11)); append(1); append(1)
+#2) entered one per line in a file
+#3) Write functions to read from file & calculate each statistic
+
+def range_input():
+ numbers = list(range(1,11))
+ numbers.append(1)
+ numbers.append(1)
+ return numbers
+
+def file_input(filename):
+ with open(filename) as f:
+ result = [int(line) for line in f]
+ return result
+
+def input_list(filename):
+ file = open(filename)
+ numbers = []
+ for line in file:
+ numbers.append(int(line))
+ return numbers
+
+def mean(numbers):
+ return sum(numbers) / len(numbers)
+
+def median(numbers):
+ count = len(numbers)
+ #print(numbers, "Count: ", count, numbers[count // 2])
+ if count % 2 == 0: # even
+ median = numbers[count // 2 - 1] + numbers[count // 2]
+ median /= 2
+ else: # odd
+ median = numbers[count // 2]
+ return median
+
+def mode(numbers):
+ freq = {}
+ for n in numbers:
+ if n in freq:
+ freq[n]+=1
+ else:
+ freq[n] = 1
+ #return sorted(freq.items(), key=operator.itemgetter(1), reverse=True)[0][0]
+ mode = 0
+ mode_freq = 0
+ for key in freq:
+ if mode_freq < freq[key]:
+ mode_freq = freq[key]
+ mode = key
+ return mode
+
+numbers = file_input("numbers.txt")
+numbers = input_list("numbers.txt")
+#numbers = range_input()
+numbers.sort()
+#print(numbers)
+
+print("Mean:", mean(numbers))
+print("Medn:", median(numbers))
+print("Mode:", mode(numbers))
\ No newline at end of file
diff --git a/pool/shard003/Python/0029043_path_helpers.py b/pool/shard003/Python/0029043_path_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..22d21e820d319a82128aba904cbc01ed2d8419de
--- /dev/null
+++ b/pool/shard003/Python/0029043_path_helpers.py
@@ -0,0 +1,49 @@
+import ui
+import objc_util
+
+
+def get_path_image(path):
+ """ Get an image of a path """
+ bounds = path.bounds
+ with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx:
+ path.fill()
+ return ctx.get_image()
+
+
+def copy_path(path):
+ """ Make a copy of a ui.Path and return it. Preserves all data. """
+ new = ui.Path()
+ new.append_path(path)
+ # Copy over the attributes
+ new.line_cap_style = path.line_cap_style
+ new.line_join_style = path.line_join_style
+ new.line_width = path.line_width
+
+ return new
+
+
+def scale_path(path, scale):
+ """ Stretch or scale a path. Pass either a scale or a tuple of scales """
+ if not hasattr(scale, "__iter__"):
+ scale = (scale, scale)
+ sx, sy = scale
+
+ newpath = copy_path(path)
+ # Construct an affine transformation matrix
+ transform = objc_util.CGAffineTransform(sx, 0, 0, sy, 0, 0)
+ # Apply it to the path
+ objcpath = objc_util.ObjCInstance(newpath)
+ objcpath.applyTransform_(transform)
+ return newpath
+
+
+if __name__ == "__main__":
+ a = ui.Path()
+ a.line_to(25, 0)
+ a.line_to(25, 25)
+ a.close()
+
+ b = scale_path(a, 2)
+
+ get_path_image(a).show() # Note that the original is not mutated
+ get_path_image(b).show()
diff --git a/pool/shard003/Python/0029045_tristate.py b/pool/shard003/Python/0029045_tristate.py
new file mode 100644
index 0000000000000000000000000000000000000000..f87e5ce2b8fef6e9388980b9e2a1ee3ff510bc51
--- /dev/null
+++ b/pool/shard003/Python/0029045_tristate.py
@@ -0,0 +1,47 @@
+from hwt.hdl.constants import DIRECTION
+from hwt.hdl.types.bits import Bits
+from hwt.interfaces.std import Signal, Clk
+from hwt.synthesizer.interface import Interface
+from hwt.synthesizer.param import Param
+from ipCorePackager.intfIpMeta import IntfIpMetaNotSpecified
+from hwtSimApi.agents.peripheral.tristate import TristateAgent, TristateClkAgent
+from hwtSimApi.hdlSimulator import HdlSimulator
+
+
+class TristateSig(Interface):
+ """
+ Tristate interface
+
+ :ivar ~.force_vector: in order to make this a vector[0] instead of single bit
+ use FORCE_VECTOR=True
+ """
+
+ def _config(self):
+ self.DATA_WIDTH = Param(1)
+ self.FORCE_VECTOR = False
+
+ def _declr(self):
+ t = Bits(self.DATA_WIDTH, force_vector=self.FORCE_VECTOR)
+
+ # connect
+ self.t = Signal(dtype=t)
+ # input
+ self.i = Signal(dtype=t, masterDir=DIRECTION.IN)
+ # output
+ self.o = Signal(dtype=t)
+
+ def _initSimAgent(self, sim: HdlSimulator):
+ rst = self._getAssociatedRst()
+ self._ag = TristateAgent(sim, self, (rst, rst._dtype.negated))
+
+
+class TristateClk(Clk, TristateSig):
+ def _config(self):
+ Clk._config(self)
+ TristateSig._config(self)
+
+ def _getIpCoreIntfClass(self):
+ raise IntfIpMetaNotSpecified()
+
+ def _initSimAgent(self, sim: HdlSimulator):
+ self._ag = TristateClkAgent(sim, self)
diff --git a/pool/shard003/Python/0029054_admin_lib.py b/pool/shard003/Python/0029054_admin_lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2dc6b8b6c7add8c5816091b3f5017a8e37ea106
--- /dev/null
+++ b/pool/shard003/Python/0029054_admin_lib.py
@@ -0,0 +1,364 @@
+# Copyright (c) 2006-2007 Open Source Applications Foundation
+# Copyright (c) 2008-2009 Mikeal Rogers
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import windmill
+import logging
+from time import sleep
+import os, sys
+from datetime import datetime
+from threading import Thread
+import shutil
+import socket
+import functest
+functest.configure()
+
+def process_options(argv_list):
+ """Process all the command line options"""
+ import admin_options
+ admin_options.process_module(admin_options)
+ argv_list.pop(0)
+
+ action = None
+
+ # This might be the hairiest code in windmill :)
+ # We have a very specific way we need to parse arguments
+ # because of the way different arguments interact with each other
+ # 8/27/2007 Gawd this is ugly, i would love to refactor this but I've
+ # forgotten what it does -Mikeal
+ # 12/15/2007 Oh man, I'm going to add a feature to this without refactoring it.
+ # The issue with this code remains the same and no standard arg parsing
+ # module can do what we need.
+ for arg in argv_list:
+ # Grab the test url if one is given
+ if arg.startswith('http://') or arg.startswith('https://'):
+ windmill.settings['TEST_URL'] = arg
+ functest.registry['url'] = arg
+ elif arg.startswith('-'):
+ # Take something like -efg and set the e, f, and g options
+ options = arg.replace('-', '')
+ for option in options:
+ admin_options.flags_dict[option]()
+ else:
+ # Any argument not starting with - is a regular named option
+ value = None
+ if arg.find('=') is not -1:
+ name, value = arg.split('=')
+ else:
+ name = arg
+
+ if name in admin_options.options_dict:
+ processor = admin_options.options_dict[name]
+ if value is None:
+ processor()
+ else:
+ processor(value)
+ elif name in action_mapping:
+ action = action_mapping[name]
+ else:
+ print name, 'is not a windmill argument. Sticking in functest registry.'
+ if value is None:
+ value = True
+ functest.registry[name] = value
+
+ if action is None:
+ # If an action is not defined we default to running the service in the foreground
+ return action_mapping['runserver']
+ else:
+ return action
+
+def setup_servers(console_level=logging.INFO):
+ """Setup the server and return httpd and loggers"""
+ windmill.is_active = True
+ windmill.ide_is_awake = False
+ if len(logging.getLogger().handlers) > 0:
+ console_handler = logging.getLogger().handlers[0]
+ console_handler.setLevel(console_level)
+ httpd = windmill.server.wsgi.make_windmill_server()
+ return httpd
+
+def run_threaded(console_level=logging.INFO):
+ """Run the server threaded."""
+
+ httpd = setup_servers(console_level)
+
+ httpd_thread = Thread(target=httpd.start)
+ getattr(httpd_thread, 'setDaemon', lambda x: x)(True)
+ httpd_thread.start()
+ while not httpd.ready:
+ sleep(.25)
+
+ return httpd, httpd_thread
+
+def configure_global_settings(logging_on=True):
+ """Configure that global settings for the current run"""
+
+ # This logging stuff probably shouldn't be here, it should probably be abstracted
+
+ if logging_on:
+ logging.getLogger().setLevel(0)
+
+ console = logging.StreamHandler()
+ console.setLevel(logging.INFO)
+ formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
+ console.setFormatter(formatter)
+ logging.getLogger().addHandler(console)
+
+ if os.environ.has_key('WINDMILL_CONFIG_FILE'):
+ local_settings = os.environ['WINDMILL_CONFIG_FILE']
+ else:
+ local_settings = None
+
+ windmill.settings = windmill.conf.configure_settings(localSettings=local_settings)
+
+ port = windmill.settings['SERVER_HTTP_PORT']
+
+ while 1:
+ try:
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect(('127.0.0.1', port))
+ s.close()
+ port += 1
+ except socket.error:
+ break
+
+ windmill.settings['SERVER_HTTP_PORT'] = port
+
+ return windmill.settings
+
+on_ide_awake = []
+
+def setup():
+ """Setup server and shell objects"""
+ global shell_objects_dict
+ shell_objects_dict = {}
+
+ windmill.settings['shell_objects'] = shell_objects_dict
+ assert not windmill.settings.get('setup_has_run', False)
+
+ httpd, httpd_thread = run_threaded(windmill.settings['CONSOLE_LOG_LEVEL'])
+
+ shell_objects_dict['httpd'] = httpd
+ shell_objects_dict['httpd_thread'] = httpd_thread
+
+ from windmill.bin import shell_objects
+
+ if windmill.settings['CONTINUE_ON_FAILURE'] is not False:
+ shell_objects.jsonrpc_client.add_json_command('{"method": "commands.setOptions", "params": {"stopOnFailure" : false}}')
+
+ if windmill.settings['EXTENSIONS_DIR'] is not None:
+ shell_objects.load_extensions_dir(windmill.settings['EXTENSIONS_DIR'])
+
+ if windmill.settings['RUN_TEST'] is not None:
+ shell_objects.run_test(windmill.settings['RUN_TEST'])
+ if windmill.settings['LOAD_TEST'] is not None:
+ shell_objects.load_test(windmill.settings['LOAD_TEST'])
+
+ if windmill.settings['JAVASCRIPT_TEST_DIR']:
+ shell_objects.run_js_tests(windmill.settings['JAVASCRIPT_TEST_DIR'],
+ windmill.settings['JAVASCRIPT_TEST_FILTER'],
+ windmill.settings['JAVASCRIPT_TEST_PHASE'])
+
+ browser = [setting for setting in windmill.settings.keys() if setting.startswith('START_') and \
+ windmill.settings[setting] is True]
+
+ import shell_objects
+
+ if len(browser) is 1:
+ shell_objects_dict['browser'] = getattr(shell_objects, browser[0].lower())()
+
+ for attribute in dir(shell_objects):
+ shell_objects_dict[attribute] = getattr(shell_objects, attribute)
+
+ shell_objects_dict['setup_has_run'] = True
+
+ return shell_objects_dict
+
+def teardown(shell_objects):
+ """Teardown the server, threads, and open browsers."""
+ if windmill.is_active:
+ windmill.is_active = False
+
+ shell_objects['clear_queue']()
+
+ for controller in windmill.settings['controllers']:
+ controller.stop()
+ del(controller)
+
+ if windmill.settings['START_FIREFOX'] and windmill.settings['MOZILLA_CREATE_NEW_PROFILE']:
+ shutil.rmtree(windmill.settings['MOZILLA_PROFILE'])
+
+ for directory in windmill.teardown_directories:
+ if os.path.isdir(directory):
+ shutil.rmtree(directory)
+
+ # while shell_objects['httpd_thread'].isAlive():
+ # try:
+ # shell_objects['httpd'].stop()
+ # except Exception, e:
+ # print "Exception occurred while shutting server down:"
+ # print e
+ #
+ # # Hacking workaround for port locking up on linux.
+ # if sys.platform == 'linux2':
+ # try:
+ # shell_objects['httpd'].socket.shutdown(socket.SHUT_RDWR)
+ # shell_objects['httpd'].socket.close()
+ # except: pass
+
+ shell_objects['httpd'].stop()
+ #shell_objects['httpd_thread'].join()
+
+
+def runserver_action(shell_objects):
+ """Run the server in the foreground with the options given to the command line"""
+ try:
+ if 'runserver' in sys.argv or len(windmill.settings['controllers']) is 0:
+ print 'Server running...'
+ if windmill.settings['EXIT_ON_DONE'] and not windmill.settings['JAVASCRIPT_TEST_DIR']:
+ while windmill.block_exit or (
+ len(shell_objects['httpd'].controller_queue.queue) is not 0 ) or (
+ len(shell_objects['httpd'].test_resolution_suite.unresolved) is not 0 ):
+ sleep(.25)
+ elif ( windmill.settings['RUN_TEST'] ):
+ windmill.runserver_running = True
+ while windmill.runserver_running:
+ sleep(.25)
+
+ else:
+ windmill.runserver_running = True
+ while windmill.runserver_running:
+ sleep(.25)
+
+ teardown(shell_objects)
+ if windmill.test_has_failed:
+ sys.exit(1)
+
+ except KeyboardInterrupt:
+ teardown(shell_objects)
+ sys.exit(1)
+
+def shell_action(shell_objects):
+ """Start the windmill shell environment"""
+ windmill.in_shell = True
+ # If ipython is installed and we weren't given the usecode option
+ try:
+ assert not windmill.settings['USECODE']
+ from IPython.Shell import IPShellEmbed
+ ipshell = IPShellEmbed()
+
+ ipshell(local_ns=shell_objects)
+ except:
+ import code
+ code.interact(local=shell_objects)
+
+ teardown(shell_objects)
+
+
+# def wxui_action(shell_objects):
+# """Start the wxPython based service GUI"""
+# try:
+# import wxui
+# app = wxui.App(shell_objects)
+# shell_objects['wxui_app'] = app
+# app.MainLoop()
+# teardown(shell_objects)
+# except ImportError:
+# print 'Failed to import wx, defaulting to the shell'
+# shell_action(shell_objects)
+
+# def tinderbox_action(shell_objects):
+# """Tinderbox action for continuous integration"""
+# shell_objects['jsonrpc_client'].add_json_command('{"method": "commands.setOptions", "params": {"stopOnFailure" : false}}')
+#
+# class ResultsProcessor(object):
+# passed = 0
+# failed = 0
+# def success(self, test, debug):
+# self.passed += 1
+# def failure(self, test, debug):
+# self.failed += 1
+#
+# result_processor = ResultsProcessor()
+# shell_objects['httpd'].test_resolution_suite.result_processor = result_processor
+#
+# starttime = datetime.now()
+# result = None
+#
+# if windmill.settings['RUN_TEST']:
+# try:
+# while ( len(shell_objects['httpd'].controller_queue.queue) is not 0 ) or (
+# len(shell_objects['httpd'].test_resolution_suite.unresolved) is not 0 ):
+# sleep(1)
+#
+# print '#TINDERBOX# Testname = FullSuite'
+# print '#TINDERBOX# Time elapsed = %s' % str (datetime.now() - starttime)
+#
+# if result_processor.failed > 0 or result_processor.passed is 0:
+# result = "FAILED"
+# else:
+# result = "PASSED"
+#
+# print '#TINDERBOX# Status = %s' % result
+# teardown(shell_objects)
+# if result == "FAILED":
+# sys.exit(1)
+#
+# except KeyboardInterrupt:
+# teardown(shell_objects)
+# if result == "FAILED":
+# sys.exit(1)
+# else:
+# try:
+# while not windmill.TESTS_COMPLETED:
+# sleep(1)
+# except KeyboardInterrupt:
+# teardown(shell_objects)
+# if result == "FAILED":
+# sys.exit(1)
+#
+# print '#TINDERBOX# Testname = FullSuite'
+# print '#TINDERBOX# Time elapsed = %s' % str (datetime.now() - starttime)
+# if windmill.RESULTS['fail'] > 0 or windmill.RESULTS['pass'] is 0:
+# result = "FAILED"
+# else:
+# result = "PASSED"
+#
+# print '#TINDERBOX# Status = %s' % result
+# teardown(shell_objects)
+# if result == "FAILED":
+# sys.exit(1)
+
+def start_windmill():
+ """Start windmill and return shell_objects"""
+ configure_global_settings()
+ shell_objects = setup()
+ return shell_objects
+
+def command_line_startup():
+ """Command line startup"""
+ windmill.stdout, windmill.stdin = sys.stdout, sys.stdin
+
+ configure_global_settings()
+
+ action = process_options(sys.argv)
+
+ shell_objects = setup()
+
+ action(shell_objects)
+
+
+action_mapping = {'shell':shell_action, 'runserver':runserver_action,
+ 'run_service':runserver_action}
+
diff --git a/pool/shard003/Python/0029057_Watchmaker.py b/pool/shard003/Python/0029057_Watchmaker.py
new file mode 100644
index 0000000000000000000000000000000000000000..1627b8f97f26e96f7973dfbe55feae49860e67c4
--- /dev/null
+++ b/pool/shard003/Python/0029057_Watchmaker.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+import argparse
+
+from watchmaker import Prepare
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--noreboot', dest='noreboot', action='store_true',
+ help='No reboot after provisioning.')
+ parser.add_argument('--sourceiss3bucket', dest='sourceiss3bucket', action='store_true',
+ help='Use S3 buckets instead of internet locations for files.')
+ parser.add_argument('--config', dest='config', default='config.yaml',
+ help='Path or URL to the config.yaml file.')
+ parser.add_argument('--logger', dest='logger', action='store_true', default=False,
+ help='Use stream logger for debugging.')
+ parser.add_argument('--log-path', dest='log_path', default=None,
+ help='Path to the logfile for stream logging.')
+ parser.add_argument('--saltstates', dest='saltstates', default=None,
+ help='Define the saltstates to use. Must be None, Highstate, or comma-separated-string')
+
+ if parser.parse_args().saltstates:
+ if parser.parse_args().saltstates.lower() not in ['None'.lower(),
+ 'Highstate'.lower(),
+ 'comma-separated-string'.lower()]:
+ parser.print_help()
+
+ systemprep = Prepare(parser.parse_args())
+ systemprep.install_system()
+
+
+def append_file(build, file_paths):
+ # The version line must have the form
+ # __version__ = 'ver'
+ pattern = r"^(__version__ = ['\"])([^'\"]*)(['\"])"
+ repl = r"\g<1>\g<2>.dev{0}\g<3>".format(build)
+ version_file = os.path.join(PROJECT_ROOT, *file_paths)
+ print(
+ 'Updating version in version_file "{0}" with build "{1}"'
+ .format(version_file, build)
+ )
+ replace(version_file, pattern, repl, flags=re.M)
+
+def main(args):
+ skip = args.skip
+ build = args.build
+ file_paths = args.file_paths
+
+ if skip:
+ print(
+ 'Not updating version for this build, `skip` set to "{0}"'
+ .format(skip)
+ )
+ else:
+ append_file(build, file_paths)
diff --git a/pool/shard003/Python/0029063_urls.py b/pool/shard003/Python/0029063_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..e01824df34643d11ac68075f1dfa044ec026a26d
--- /dev/null
+++ b/pool/shard003/Python/0029063_urls.py
@@ -0,0 +1,15 @@
+from django.conf.urls import url, include
+from rest_framework import routers
+import views
+
+router = routers.DefaultRouter()
+router.register(r'flights', views.FlightViewSet)
+
+# Wire up our API using automatic URL routing.
+# Additionally, we include login URLs for the browsable API.
+urlpatterns = [
+ url(r'', include(router.urls)),
+ url(r'^users/$', views.UserCreateView.as_view()),
+ url(r'^token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
+ url(r'^email-confirmation/', include('email_confirm_la.urls')),
+]
diff --git a/pool/shard003/Python/0029066_countries.py b/pool/shard003/Python/0029066_countries.py
new file mode 100644
index 0000000000000000000000000000000000000000..c331e9217c71e544fa913f0e162ccb29e077b882
--- /dev/null
+++ b/pool/shard003/Python/0029066_countries.py
@@ -0,0 +1,43 @@
+"""Conuntries Class."""
+
+from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
+import logging
+
+
+class Countries(APIClassTemplate):
+ """The Countries Object in the FMC."""
+
+ VALID_JSON_DATA = ["id", "name", "iso2", "iso3"]
+ VALID_FOR_KWARGS = VALID_JSON_DATA + []
+ URL_SUFFIX = "/object/countries"
+ VALID_CHARACTERS_FOR_NAME = """[.\w\d_\- ]"""
+
+ def __init__(self, fmc, **kwargs):
+ """
+ Initialize Countries object.
+
+ Set self.type to "Country" and parse the kwargs.
+
+ :param fmc: (object) FMC object
+ :param kwargs: Any other values passed during instantiation.
+ :return: None
+ """
+ super().__init__(fmc, **kwargs)
+ logging.debug("In __init__() for Countries class.")
+ self.parse_kwargs(**kwargs)
+ self.type = "Country"
+
+ def post(self):
+ """POST method for API for Countries not supported."""
+ logging.info("POST method for API for Countries not supported.")
+ pass
+
+ def put(self):
+ """PUT method for API for Countries not supported."""
+ logging.info("PUT method for API for Countries not supported.")
+ pass
+
+ def delete(self):
+ """DELETE method for API for Countries not supported."""
+ logging.info("DELETE method for API for Countries not supported.")
+ pass
diff --git a/pool/shard003/Python/0029069_02_modify_box.py b/pool/shard003/Python/0029069_02_modify_box.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9df0e98ccb524c42c44c40d54ccc235ea5a5539
--- /dev/null
+++ b/pool/shard003/Python/0029069_02_modify_box.py
@@ -0,0 +1,13 @@
+import configurator, os
+p = configurator.start_it_up(getBundlePath(), "collider_box.blend")
+try:
+ wait("3dview_locator_collision.png", 5)
+ click("box_z_size_1.png"); type("2" + Key.ENTER); find("box_resized_z_2.png")
+ click("locator_centered_op.png"); find("box_centered.png")
+ click("locator_centered_op_pressed.png"); find("box_resized_z_2.png")
+ click("box_y_size_1.png"); type("0.5" + Key.ENTER); find("box_resized_y_0_5.png")
+except:
+ configurator.save_screenshot(getBundlePath(), Screen())
+ raise
+finally:
+ configurator.close_blender(p)
\ No newline at end of file
diff --git a/pool/shard003/Python/0029082_recipe-128243.py b/pool/shard003/Python/0029082_recipe-128243.py
new file mode 100644
index 0000000000000000000000000000000000000000..0412d0668b279674667f69477ce2b72e466396b3
--- /dev/null
+++ b/pool/shard003/Python/0029082_recipe-128243.py
@@ -0,0 +1,86 @@
+#################################################################
+# Function InvLap(t,omega,sigma,nint), numerically inverts a #
+# Laplace transform F(s) into f(t) using the Fast Fourier #
+# Transform (FFT) algorithm for a specific time "t", an #
+# upper frequency limit "omega", a real parameter "sigma" #
+# and the number of integration intervals "nint" . #
+# #
+# Function F(s) is defined in separate as Fs(s) (see code #
+# below). Fs(s) has to be changed accordingly everytime the #
+# user wants to invert a different function. #
+# #
+# I suggest to use omega>100 and nint=50*omega. The higher #
+# the values for omega, the more accurate the results will be #
+# in general, but at the expense of longer processing times. #
+# #
+# Sigma is a real number which must be a little bigger than #
+# the real part of rightmost pole of the function F(s). For #
+# example, F(s) = 1/s + 1/(s-2) + 1/(s+1) has poles for s=0, #
+# s=2 and s=-1. Hence, sigma must be made equal to, say, #
+# 2.05 so as to keep all poles at the left of this value. #
+# The analytical inverse for this simple function is #
+# f(t) = 1 + exp(-t) + exp(2t). For t=1.25, omega=200, #
+# nint=10000 and sigma=2.05, the numerical inversion yields #
+# f(1.25) ~= 13.456844516, or -0.09% away from the actual #
+# analytical result, 13.468998757 (results truncated to 9 #
+# decimal places). This is the example used in this code. #
+# #
+# Creator: Fausto Arinos de Almeida Barbuto (Calgary, Canada) #
+# Date: May 18, 2002 #
+# E-mail: fausto_barbuto@yahoo.ca #
+# #
+# Reference: #
+# Huddleston, T. and Byrne, P: "Numerical Inversion of #
+# Laplace Transforms", University of South Alabama, April #
+# 1999 (found at http://www.eng.usouthal.edu/huddleston/ #
+# SoftwareSupport/Download/Inversion99.doc) #
+# #
+# Usage: invoke InvLap(t,omega,sigma,nint), for t>0. #
+# #
+#################################################################
+# We need cmath because F(s) is a function operating on the
+# complex argument s = a + bj
+from math import ceil
+from cmath import *
+
+# *** Driver InvLap function ***
+def InvLap(t,omega,sigma,nint):
+# Sanity check on some parameters.
+ omega = ceil(omega)
+ nint = ceil(nint)
+
+ if omega <= 0:
+ omega = 200
+
+ if nint <= 0:
+ nint = 10000
+
+ return (trapezoid(t,omega,sigma,nint))
+
+# *** Function trapezoid computes the numerical inversion. ***
+def trapezoid(t,omega,sigma,nint):
+ sum = 0.0
+ delta = float(omega)/nint
+ wi = 0.0
+
+# The for-loop below computes the FFT Inversion Algorithm.
+# It is in fact the trapezoidal rule for numerical integration.
+ for i in range(1,(nint+1)):
+ witi = complex(0,wi*t)
+
+ wf = wi + delta
+ wfti = complex(0,wf*t)
+
+ fi = (exp(witi)*Fs(complex(sigma,wi))).real
+ ff = (exp(wfti)*Fs(complex(sigma,wf))).real
+ sum = sum + 0.5*(wf-wi)*(fi+ff)
+ wi = wf
+
+ return ((sum*exp(sigma*t)/pi).real)
+
+# *** The Laplace function F(s) is defined here. ***
+def Fs(s):
+ return (1.0/s + 1.0/(s+1.0) + 1.0/(s-2.0))
+
+# Function InvLap(t,omega,sigma,nint) is invoked.
+print InvLap(1.25,200,2.05,10000)
diff --git a/pool/shard003/Python/0029089_setup.py b/pool/shard003/Python/0029089_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e95e53c51fb383d1e518762d07dda4b62f44f11
--- /dev/null
+++ b/pool/shard003/Python/0029089_setup.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+
+"""Setup script for GDM."""
+
+import setuptools
+
+from gdm import __project__, __version__, CLI, DESCRIPTION
+
+import os
+if os.path.exists('README.rst'):
+ README = open('README.rst').read()
+else:
+ README = "" # a placeholder, readme is generated on release
+CHANGES = open('CHANGES.md').read()
+
+
+setuptools.setup(
+ name=__project__,
+ version=__version__,
+
+ description=DESCRIPTION,
+ url='https://github.com/jacebrowning/gdm',
+ author='Jace Browning',
+ author_email='jacebrowning@gmail.com',
+
+ packages=setuptools.find_packages(),
+
+ entry_points={'console_scripts': [CLI + ' = gdm.cli:main']},
+
+ long_description=(README + '\n' + CHANGES),
+ license='MIT',
+ classifiers=[
+ 'Development Status :: 1 - Planning',
+ 'Natural Language :: English',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ ],
+
+ install_requires=open('requirements.txt').readlines(),
+)
diff --git a/pool/shard003/Python/0029091_027.py b/pool/shard003/Python/0029091_027.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ae67dc0778dc654614660b9ea53a0b1400ebdd5
--- /dev/null
+++ b/pool/shard003/Python/0029091_027.py
@@ -0,0 +1,22 @@
+from prime import Prime
+
+
+def f(n, a, b):
+ return n ** 2 + a * n + b
+
+
+def ans():
+ lim = 1000
+ largest = (None, None, 0)
+ for a in range(-lim + 1, lim):
+ for b in range(-lim, lim + 1):
+ n = 0
+ while Prime.contains(f(n, a, b)):
+ n += 1
+ if largest[2] < n:
+ largest = (a, b, n)
+ return largest[0] * largest[1]
+
+
+if __name__ == '__main__':
+ print(ans())
diff --git a/pool/shard003/Python/0029092_search.py b/pool/shard003/Python/0029092_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b10d0d879b1e8eada355bdce0692626348bc7c7
--- /dev/null
+++ b/pool/shard003/Python/0029092_search.py
@@ -0,0 +1,45 @@
+from bisect import bisect_left, bisect_right
+
+"""
+From documentation of the bisect module.
+"""
+
+
+def index(a, x):
+ 'Locate the leftmost value exactly equal to x'
+ i = bisect_left(a, x)
+ if i != len(a) and a[i] == x:
+ return i
+ raise ValueError
+
+
+def find_lt(a, x):
+ 'Find rightmost value less than x'
+ i = bisect_left(a, x)
+ if i:
+ return i-1, a[i-1]
+ raise ValueError
+
+
+def find_le(a, x):
+ 'Find rightmost value less than or equal to x'
+ i = bisect_right(a, x)
+ if i:
+ return i-1, a[i-1]
+ raise ValueError
+
+
+def find_gt(a, x):
+ 'Find leftmost value greater than x'
+ i = bisect_right(a, x)
+ if i != len(a):
+ return i, a[i]
+ raise ValueError
+
+
+def find_ge(a, x):
+ 'Find leftmost item greater than or equal to x'
+ i = bisect_left(a, x)
+ if i != len(a):
+ return i, a[i]
+ raise ValueError
diff --git a/pool/shard003/Python/0029095_views.py b/pool/shard003/Python/0029095_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed4aff649d0dbd1c01a493ca80e9a3da47f4fd0
--- /dev/null
+++ b/pool/shard003/Python/0029095_views.py
@@ -0,0 +1,144 @@
+# -*- coding: utf-8 -*-
+# Create your views here.
+import json
+from django.core.files import File
+from django.core.files.storage import FileSystemStorage
+from django.utils import timezone
+from django.http import HttpResponse
+from django.views.generic import View, ListView, DetailView, TemplateView
+from django.views.generic.edit import CreateView
+from eztables.views import DatatablesView
+from core.views import login_required, ajax_view
+from core.masterlist import WbsMasterList
+from .models import Bill, BillingSchedule, Account, FileRepo
+from wkhtmltopdf.views import PDFTemplateView
+
+
+import os, tempfile, zipfile
+from django.core.servers.basehttp import FileWrapper
+
+@login_required
+class BillListView(TemplateView):
+ pass
+
+@login_required
+@ajax_view
+class BillDatatablesView(DatatablesView):
+ model = Bill
+ fields = (
+ 'id',
+ '{account__customer__last_name}, {account__customer__first_name}',
+ 'bill_date',
+ 'due_date',
+ 'amount_due',
+ 'account__status',
+ 'account__remarks',
+ )
+
+@login_required
+@ajax_view
+class FileRepoDatatablesView(DatatablesView):
+ model = FileRepo
+ fields = (
+ 'id',
+ 'file_name',
+ #'file_path',
+ 'generation_date',
+ 'file_name'
+ )
+
+
+@login_required
+class FileDownloadView(View):
+ model = FileRepo
+
+ def get(self, request, *args, **kwargs):
+ print "args: " + str(args)
+ print "kwargs: " + str(kwargs)
+ fl = self.model.objects.get(id=kwargs['pk'])
+ fs = FileSystemStorage()
+ filename = fl.file_name
+ print "filename: " + str(filename)
+ wrapper = FileWrapper(fs.open(filename))
+ response = HttpResponse(wrapper, content_type='application/pdf')
+ response['Content-Disposition'] = 'attachment; filename=' + fl.file_name + ''
+ response['Content-Length'] = os.path.getsize(fs.location+'/'+filename)
+ return response
+
+@login_required
+class PdfBillDetailView(PDFTemplateView):
+
+ model = Bill
+ context_object_name = 'bill_detail'
+
+ def get_context_data(self, **kwargs):
+ print "kwargs: " + str(kwargs)
+ context = super(PdfBillDetailView, self).get_context_data(**kwargs)
+ print
+ context['bill_detail'] = self.model.objects.get(pk=context['pk'])
+ self.object = context['bill_detail']
+ context['account'] = context['bill_detail'].account
+ #context['now'] = timezone.now()
+ return context
+
+@login_required
+@ajax_view
+class GenerateMasterlistView(View):
+
+ model = Account
+
+ def render_to_json_response(self, context, **response_kwargs):
+ data = json.dumps(context)
+ response_kwargs['content_type'] = 'application/json'
+ return HttpResponse(data, **response_kwargs)
+
+ def get(self, request, *args, **kwargs):
+ print "This GET", args, kwargs
+ today = timezone.now().date()
+ bs = BillingSchedule.objects.get(start_date__lte=today, end_date__gte=today)
+
+
+ try:
+ wbx = WbsMasterList()
+ wbx.render()
+ wbx.save()
+
+ print "Done with Master List Generation"
+
+ data = {'status': 200, 'msg': 'Done with Master List Generation'}
+ status = 200
+ except Exception, e:
+ print "e: ", str(e)
+ data = {'status': 400, 'msg': 'Unable to Generate Master List' }
+ status = 400
+
+ return self.render_to_json_response(data, status=status)
+
+
+@login_required
+class GetMasterlistView(View):
+
+ model = Account
+
+ def render_to_json_response(self, context, **response_kwargs):
+ data = json.dumps(context)
+ response_kwargs['content_type'] = 'application/json'
+ return HttpResponse(data, **response_kwargs)
+
+ def get(self, request, *args, **kwargs):
+ print "This GET", args, kwargs
+ today = timezone.now().date()
+ bs = BillingSchedule.objects.get(start_date__lte=today, end_date__gte=today)
+
+ wbx = WbsMasterList()
+
+ fs = FileSystemStorage()
+ filename = wbx.filename
+
+ print "filename: " + str(filename)
+ wrapper = FileWrapper(fs.open(filename))
+ response = HttpResponse(wrapper, content_type='application/vnd.ms-excel')
+ response['Content-Disposition'] = 'attachment; filename=' + filename + ''
+ response['Content-Length'] = os.path.getsize(fs.location+'/'+filename)
+ return response
+
diff --git a/pool/shard003/Python/0029098_capture_audio.py b/pool/shard003/Python/0029098_capture_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..40644437bbaf6fa72e5ca89b0e773691e0bbe1ee
--- /dev/null
+++ b/pool/shard003/Python/0029098_capture_audio.py
@@ -0,0 +1,29 @@
+import pyaudio
+
+FORMAT = pyaudio.paInt16
+CHANNELS = 1
+
+def capture_buffers(num_buffers, chunk, rate, skip=None):
+ if skip == None:
+ skip = rate / 2
+
+ p = pyaudio.PyAudio()
+ stream = p.open(format=FORMAT, channels=CHANNELS, rate=rate, input=True, frames_per_buffer=chunk)
+
+ # ignore some data at the beginning as it is usually weird
+ if skip > 0:
+ data = stream.read(skip)
+
+ buffers = [stream.read(chunk) for i in range(0, num_buffers)]
+
+ # close the audio stream
+ stream.stop_stream()
+ stream.close()
+ p.terminate()
+
+ return buffers
+
+def capture_seconds(num_seconds, chunksize, rate, width):
+ num_buffers = int(float(num_seconds * rate) / chunksize)
+ return capture_buffers(num_buffers, chunksize, rate, width)
+
diff --git a/pool/shard003/Python/0029099_spi_adc.py b/pool/shard003/Python/0029099_spi_adc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d18a1f19a06fdf8847ec95ceeda3c93c1c737055
--- /dev/null
+++ b/pool/shard003/Python/0029099_spi_adc.py
@@ -0,0 +1,33 @@
+import spidev
+
+import common
+import config
+from config import C
+from logger import LOGGER_FACTORY
+
+
+class SpiAdc:
+ _CHANNELS = C.ADC_CHANNELS()
+ _VREFS = C.ADC_VREFS()
+
+ def __init__(self):
+ self._log = LOGGER_FACTORY.get_logger('ipa.adc')
+ self._spi = spidev.SpiDev()
+ self._spi.open(0, 0)
+ if len(SpiAdc._CHANNELS) != len(SpiAdc._VREFS):
+ raise config.InvalidConfigException(
+ 'config has %d channels, but %d vrefs' % (len(SpiAdc._CHANNELS), len(SpiAdc._VREFS)))
+ self._log.info('initialized (channels: %s; vrefs: %s)' % (SpiAdc._CHANNELS, SpiAdc._VREFS))
+
+ def _read(self, channel):
+ """Reads ADC channel 0..7"""
+ response = self._spi.xfer2([1, (8 + channel) << 4, 0])
+ value = ((response[1] & 3) << 8) + response[2]
+ return value / 1023.0 # 10 bit resolution
+
+ def get_sample(self):
+ sample = {}
+ for i, channel in enumerate(SpiAdc._CHANNELS):
+ vref = SpiAdc._VREFS[i]
+ sample[channel] = (common.timestamp(), self._read(channel) * vref)
+ return 'adc', sample
diff --git a/pool/shard003/Python/0029103_0011_auto_20150930_0243.py b/pool/shard003/Python/0029103_0011_auto_20150930_0243.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e605681415be086e43fdfc01e14ea375cd3bd76
--- /dev/null
+++ b/pool/shard003/Python/0029103_0011_auto_20150930_0243.py
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('contenttypes', '0002_remove_content_type_name'),
+ ('popit', '0010_links_field'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='links',
+ name='content_type',
+ field=models.ForeignKey(default='', to='contenttypes.ContentType'),
+ preserve_default=False,
+ ),
+ migrations.AddField(
+ model_name='links',
+ name='object_id',
+ field=models.CharField(default='', max_length=255),
+ preserve_default=False,
+ ),
+ ]
diff --git a/pool/shard003/Python/0029106_jsonrenderer.py b/pool/shard003/Python/0029106_jsonrenderer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6150f6acca5315c3dab505a1ca980d8b50ba7132
--- /dev/null
+++ b/pool/shard003/Python/0029106_jsonrenderer.py
@@ -0,0 +1,34 @@
+# Yith Library Server is a password storage server.
+# Copyright (C) 2012-2013 Lorenzo Gil Sanchez
+#
+# This file is part of Yith Library Server.
+#
+# Yith Library Server is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Yith Library Server is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Yith Library Server. If not, see .
+
+import datetime
+import bson
+
+from pyramid.renderers import JSON
+
+json_renderer = JSON()
+
+
+def bson_adapter(obj, request):
+ return str(obj)
+json_renderer.add_adapter(bson.ObjectId, bson_adapter)
+
+
+def datetime_adapter(obj, request):
+ return obj.isoformat()
+json_renderer.add_adapter(datetime.datetime, datetime_adapter)
diff --git a/pool/shard003/Python/0029107_sdl2events.py b/pool/shard003/Python/0029107_sdl2events.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f65f88dcacc55ab990212c97acadcbebffd19ff
--- /dev/null
+++ b/pool/shard003/Python/0029107_sdl2events.py
@@ -0,0 +1,82 @@
+import ctypes as ct
+
+import sdl2 as sdl
+
+from ed2d.platforms import sdl2keymap as keymap
+from ed2d.events import Events
+from ed2d import cursor
+
+MOUSE_LEFT = 1
+MOUSE_MIDDLE = 2
+MOUSE_RIGHT = 3
+MOUSE_EX1 = 4
+MOUSE_EX2 = 5
+
+class SystemEvents(object):
+ ''' Handles Event stuff... '''
+ def __init__(self):
+ sdl.SDL_InitSubSystem(sdl.SDL_INIT_EVENTS)
+
+ def process(self):
+ '''
+ Processes the events polled from sdl.
+ Custom events might be a possiblility if we need them.
+ '''
+
+ event = sdl.SDL_Event()
+
+ while sdl.SDL_PollEvent(ct.byref(event)):
+
+ eventName = None
+ data = None
+
+ if event.type == sdl.SDL_QUIT:
+ eventName = 'quit'
+ data = ()
+ elif event.type == sdl.SDL_MOUSEMOTION:
+ eventName = 'mouse_move'
+ if cursor.is_relative():
+ data = (event.motion.xrel, event.motion.yrel)
+ else:
+ data = (event.motion.x, event.motion.y)
+ elif event.type == sdl.SDL_WINDOWEVENT:
+ winEvent = event.window
+ wEventName = event.window.event
+ # For now this will only support one window
+ # If we want two later on then we can do it then.
+ if wEventName == sdl.SDL_WINDOWEVENT_CLOSE:
+ eventName = 'window_close'
+ data = (winEvent.windowID)
+ elif wEventName == sdl.SDL_WINDOWEVENT_RESIZED:
+ eventName = 'window_resized'
+ data = (winEvent.windowID, winEvent.data1, winEvent.data2)
+
+ elif event.type == sdl.SDL_KEYUP:
+ if not event.key.repeat:
+ eventName = 'key_up'
+ keyID = keymap.keymap[event.key.keysym.scancode]
+ keyName = keymap.process_key_char(event.key.keysym.sym)
+ modKeys = keymap.process_modkeys(event.key.keysym.mod)
+ data = (keyName, keyID, modKeys)
+
+ elif event.type == sdl.SDL_KEYDOWN:
+ if not event.key.repeat:
+ eventName = 'key_down'
+ keyID = keymap.keymap[event.key.keysym.scancode]
+ keyName = keymap.process_key_char(event.key.keysym.sym)
+ modKeys = keymap.process_modkeys(event.key.keysym.mod)
+ data = (keyName, keyID, modKeys)
+ elif event.type == sdl.SDL_MOUSEBUTTONUP:
+ eventName = 'mouse_button_up'
+ data = (event.button.button, event.button.clicks, event.button.x, event.button.y)
+ elif event.type == sdl.SDL_MOUSEBUTTONDOWN:
+ eventName = 'mouse_button_down'
+ data = (event.button.button, event.button.clicks, event.button.x, event.button.y)
+ else:
+ # Will add more event types later
+ pass
+
+ if eventName is not None:
+ Events.broadcast_event(eventName, data)
+
+__all__ = ['Events']
diff --git a/pool/shard003/Python/0029110_smtp.py b/pool/shard003/Python/0029110_smtp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0567811f2ec84b676428f3d982d98eae2c1d60c6
--- /dev/null
+++ b/pool/shard003/Python/0029110_smtp.py
@@ -0,0 +1,123 @@
+"""
+owtf.protocols.smtp
+~~~~~~~~~~~~~~~~~~~
+
+Description:
+This is the OWTF SMTP handler, to simplify sending emails.
+"""
+from email.mime import base, multipart, text as mimetext
+from email import encoders
+import logging
+import os
+import smtplib
+
+from owtf.utils.file import FileOperations, get_file_as_list
+
+__all__ = ["smtp"]
+
+
+class SMTP(object):
+
+ def __init__(self):
+ self.msg_prefix = "OWTF SMTP Client - "
+
+ def pprint(self, message):
+ logging.info(self.msg_prefix + message)
+
+ def create_connection_with_mail_server(self, options):
+ return smtplib.SMTP(options["SMTP_HOST"], int(options["SMTP_PORT"]))
+
+ def connect(self, options):
+ try:
+ mail_server = self.create_connection_with_mail_server(options)
+ mail_server.ehlo()
+ except Exception:
+ self.pprint("Error connecting to {!s} on port {!s}".format(options["SMTP_HOST"], options["SMTP_PORT"]))
+ return None
+ try:
+ mail_server.starttls() # Give start TLS a shot
+ except Exception as e:
+ self.pprint("{} - Assuming TLS unsupported and trying to continue..".format(str(e)))
+ try:
+ mail_server.login(options["SMTP_LOGIN"], options["SMTP_PASS"])
+ except Exception as e:
+ self.pprint("ERROR: {} - Assuming open-relay and trying to continue..".format(str(e)))
+ return mail_server
+
+ def is_file(self, target):
+ return os.path.isfile(target)
+
+ def get_file_content_as_list(self, options):
+ return get_file_as_list(options["EMAIL_TARGET"])
+
+ def build_target_list(self, options):
+ """Build a list of targets for simplification purposes."""
+ if self.is_file(options["EMAIL_TARGET"]):
+ target_list = self.get_file_content_as_list(options)
+ else:
+ target_list = [options["EMAIL_TARGET"]]
+ return target_list
+
+ def send(self, options):
+ num_errors = 0
+ for target in self.build_target_list(options):
+ target = target.strip()
+ if not target:
+ continue # Skip blank lines!
+ self.pprint("Sending email for target: {!s}".format(target))
+ try:
+ message = self.build_message(options, target)
+ mail_server = self.connect(options)
+ if mail_server is None:
+ raise Exception("Error connecting to {}".format(str(target)))
+ mail_server.sendmail(options["SMTP_LOGIN"], target, message.as_string())
+ self.pprint("Email relay successful!")
+ except Exception as e:
+ logging.error("Error delivering email: %s", str(e))
+ num_errors += 1
+ return num_errors == 0
+
+ def build_message(self, options, target):
+ message = multipart.MIMEMultipart()
+ for name, value in list(options.items()):
+ if name == "EMAIL_BODY":
+ self.add_body(message, value)
+ elif name == "EMAIL_ATTACHMENT":
+ self.add_attachment(message, value)
+ else: # From, To, Subject, etc.
+ self.set_option(message, name, value, target)
+ return message
+
+ def set_option(self, message, option, value, target):
+ if option == "EMAIL_FROM":
+ message["From"] = value
+ elif option == "EMAIL_TARGET":
+ message["To"] = target
+ elif option == "EMAIL_PRIORITY":
+ if value == "yes":
+ message["X-Priority"] = " 1 (Highest)"
+ message["X-MSMail-Priority"] = " High"
+ elif option == "EMAIL_SUBJECT":
+ message["Subject"] = value
+
+ def add_body(self, message, text):
+ # If a file has been specified as Body, then set Body to file contents.
+ if os.path.isfile(text):
+ body = FileOperations.open(text).read().strip()
+ else:
+ body = text
+ message.attach(mimetext.MIMEText(body, message))
+
+ def add_attachment(self, message, attachment):
+ if not attachment:
+ return False
+ binary_blob = base.MIMEBase("application", "octet-stream")
+ binary_blob.set_payload(FileOperations.open(attachment, "rb").read())
+ encoders.encode_base64(binary_blob) # base64 encode the Binary Blob.
+ # Binary Blob headers.
+ binary_blob.add_header("Content-Disposition", 'attachment; filename="{}"'.format(os.path.basename(attachment)))
+ message.attach(binary_blob)
+ return True
+
+
+smtp = SMTP()
diff --git a/pool/shard003/Python/0029111_conf.py b/pool/shard003/Python/0029111_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..48e19bc4985f289d361fc14984ee7c9890e437d4
--- /dev/null
+++ b/pool/shard003/Python/0029111_conf.py
@@ -0,0 +1,275 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# emanate documentation build configuration file, created by
+# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+
+# If extensions (or modules to document with autodoc) are in another
+# directory, add these directories to sys.path here. If the directory is
+# relative to the documentation root, use os.path.abspath to make it
+# absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# Get the project root dir, which is the parent dir of this
+cwd = os.getcwd()
+project_root = os.path.dirname(cwd)
+
+# Insert the project root dir as the first element in the PYTHONPATH.
+# This lets us ensure that the source package is imported, and that its
+# version is used.
+sys.path.insert(0, project_root)
+
+import emanate
+
+# -- General configuration ---------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'emanate'
+copyright = u"2016, YouGov, plc"
+
+# The version info for the project you're documenting, acts as replacement
+# for |version| and |release|, also used in various other places throughout
+# the built documents.
+#
+# The short X.Y version.
+version = emanate.__version__
+# The full version, including alpha/beta/rc tags.
+release = emanate.__version__
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to
+# some non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built
+# documents.
+#keep_warnings = False
+
+
+# -- Options for HTML output -------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a
+# theme further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# " v documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as
+# html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the
+# top of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon
+# of the docs. This file should be a Windows icon file (.ico) being
+# 16x16 or 32x32 pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets)
+# here, relative to this directory. They are copied after the builtin
+# static files, so a file named "default.css" will overwrite the builtin
+# "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page
+# bottom, using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names
+# to template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer.
+# Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer.
+# Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages
+# will contain a tag referring to it. The value of this option
+# must be the base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'emanatedoc'
+
+
+# -- Options for LaTeX output ------------------------------------------
+
+latex_elements = {
+ # The paper size ('letterpaper' or 'a4paper').
+ #'papersize': 'letterpaper',
+
+ # The font size ('10pt', '11pt' or '12pt').
+ #'pointsize': '10pt',
+
+ # Additional stuff for the LaTeX preamble.
+ #'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass
+# [howto/manual]).
+latex_documents = [
+ ('index', 'emanate.tex',
+ u'emanate Documentation',
+ u'YouGov, plc', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at
+# the top of the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings
+# are parts, not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output ------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'emanate',
+ u'emanate Documentation',
+ [u'YouGov, plc'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output ----------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ ('index', 'emanate',
+ u'emanate Documentation',
+ u'YouGov, plc',
+ 'emanate',
+ 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
diff --git a/pool/shard003/Python/0029119_APOGEEWindow.py b/pool/shard003/Python/0029119_APOGEEWindow.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ec344b1e13944e64a6979d5eaeb6609576243b7
--- /dev/null
+++ b/pool/shard003/Python/0029119_APOGEEWindow.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+"""Display status of APOGEE QuickLook Actor
+
+History:
+2011-08-16 ROwen Save window state.
+"""
+import Tkinter
+import RO.Wdg
+import APOGEEWdg
+
+WindowName = "Inst.APOGEE"
+
+def addWindow(tlSet, visible=False):
+ """Create the window.
+ """
+ tlSet.createToplevel(
+ name = WindowName,
+ defGeom = "+346+398",
+ visible = visible,
+ resizable = False,
+ wdgFunc = APOGEEWdg.APOGEEWdg,
+ doSaveState = True,
+ )
+
+
+if __name__ == '__main__':
+ import TUI.Base.TestDispatcher
+
+ testDispatcher = TUI.Base.TestDispatcher.TestDispatcher("tcc")
+ tuiModel = testDispatcher.tuiModel
+ root = tuiModel.tkRoot
+
+ addWindow(tuiModel.tlSet, visible=True)
+
+ tuiModel.reactor.run()
diff --git a/pool/shard003/Python/0029121_sexpr.py b/pool/shard003/Python/0029121_sexpr.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a35f09c42704da9adb29f27fca4ec0949fb4736
--- /dev/null
+++ b/pool/shard003/Python/0029121_sexpr.py
@@ -0,0 +1,109 @@
+# -*- coding: utf-8 -*-
+
+"""
+S-expr parser, a LISP front-end for Python
+"""
+
+import re
+
+class Parser(object):
+ RE_NUM = re.compile(r'^[+-]?[0-9]+(\.[0-9]+)?')
+ RE_STR = re.compile(r'^\"(\\\\|\\\"|[^"])*\"', re.DOTALL)
+ RE_SYM = re.compile(r'^[^0-9\s\(\)\[\]{}\",][^\s\(\)\[\]{}\",]*')
+ RE_LITERAL = re.compile(r'^?', re.DOTALL)
+ RE_BLANK = re.compile(r'^[\s,]*(;[^\r\n]*[\r\n\s,]+)*', re.DOTALL)
+
+ PARN = {
+ '(' : ('tuple', ')'),
+ '[' : ('list', ']'),
+ '{' : ('dict', '}')}
+
+ def __init__(self, prefixes, types):
+ self.prefixes = prefixes
+ self.types = types
+
+ @staticmethod
+ def next(src, pattern):
+ if isinstance(pattern, basestring):
+ if src.startswith(pattern):
+ return (pattern,), src[len(pattern):]
+ else:
+ return None, src
+ else:
+ m = pattern.search(src)
+ if m is not None and m.start() == 0:
+ return (src[:m.end()],) + m.groups(), src[m.end():]
+ else:
+ return None, src
+
+ def parse(self, src):
+ # Clear blank and comment
+ unused_match, src = Parser.next(src, Parser.RE_BLANK)
+ if not src:
+ raise StopIteration
+
+ if src[0] in Parser.PARN:
+ typename, endch = Parser.PARN[src[0]]
+
+ unused, src = Parser.next(src[1:], Parser.RE_BLANK)
+ output = []
+ while src and src[0] != endch:
+ elim, src = self.parse(src)
+ output.append(elim)
+ unused, src = Parser.next(src, Parser.RE_BLANK)
+ if not src:
+ raise SyntaxError, src
+ return self.types[typename](output), src[1:]
+
+ # prefixes char (quote etc)
+ if src[0] in self.prefixes and (
+ len(src) > 1 and src[1] not in ' \t\r\n'):
+ prefix_func = self.prefixes[src[0]]
+ ret, src = self.parse(src[1:])
+ return prefix_func(ret), src
+
+ m, src = Parser.next(src, Parser.RE_LITERAL)
+ if m is not None:
+ unused, typename, content = m
+ return self.types[typename](content), src
+
+ m, src = Parser.next(src, Parser.RE_STR)
+ if m is not None:
+ return self.types['str'](m[0]), src
+
+ m, src = Parser.next(src, Parser.RE_NUM)
+ if m is not None:
+ return self.types['num'](m[0]), src
+
+ # OK, it will be symbol hah?
+ m, src= Parser.next(src, Parser.RE_SYM)
+ if m is not None:
+ return self.types['sym'](m[0]), src
+
+ raise SyntaxError, src[:80]
+
+ def parseall(self, src):
+ output = []
+ while True:
+ try:
+ obj, src = self.parse(src)
+ output.append(obj)
+ except StopIteration:
+ break
+ return output
+
+if __name__ == '__main__':
+ import sys
+ parser = Parser(
+ prefixes = {'\'' : lambda x: ('QUOTE', x)},
+ types = {
+ 'num' : eval,
+ 'str' : eval,
+ 'sym' : lambda x: '' % (x,),
+ '' : lambda x: x,
+ 'py' : lambda x: '' % (x,),
+ 'tuple' : tuple,
+ 'list' : lambda x: ('list',) + tuple(x),
+ 'dict' : lambda x: ('dict',) + tuple(x)}
+ )
+ print parser.parseall(sys.stdin.read())
diff --git a/pool/shard003/Python/0029122_slow-history.py b/pool/shard003/Python/0029122_slow-history.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ba3860d69ec2882b82a71ebcb75bccda7679f90
--- /dev/null
+++ b/pool/shard003/Python/0029122_slow-history.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python
+"""
+Simple example of a custom, very slow history, that is loaded asynchronously.
+
+By wrapping it in `ThreadedHistory`, the history will load in the background
+without blocking any user interaction.
+"""
+import time
+
+from prompt_toolkit import PromptSession
+from prompt_toolkit.history import History, ThreadedHistory
+
+
+class SlowHistory(History):
+ """
+ Example class that loads the history very slowly...
+ """
+
+ def load_history_strings(self):
+ for i in range(1000):
+ time.sleep(1) # Emulate slowness.
+ yield "item-%s" % (i,)
+
+ def store_string(self, string):
+ pass # Don't store strings.
+
+
+def main():
+ print(
+ "Asynchronous loading of history. Notice that the up-arrow will work "
+ "for as far as the completions are loaded.\n"
+ "Even when the input is accepted, loading will continue in the "
+ "background and when the next prompt is displayed.\n"
+ )
+ our_history = ThreadedHistory(SlowHistory())
+
+ # The history needs to be passed to the `PromptSession`. It can't be passed
+ # to the `prompt` call because only one history can be used during a
+ # session.
+ session = PromptSession(history=our_history)
+
+ while True:
+ text = session.prompt("Say something: ")
+ print("You said: %s" % text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard003/Python/0029123_service.py b/pool/shard003/Python/0029123_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..074b1361d5a59d2540719d1ef7b90a2e25856857
--- /dev/null
+++ b/pool/shard003/Python/0029123_service.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2013 Spotify AB
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may not
+# use this file except in compliance with the License. You may obtain a copy of
+# the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations under
+# the License.
+
+from snakebite.channel import SocketRpcChannel
+import google.protobuf.service as service
+
+
+class RpcService(object):
+
+ def __init__(self, service_stub_class, port, host, hadoop_version, effective_user=None,use_sasl=False):
+ self.service_stub_class = service_stub_class
+ self.port = port
+ self.host = host
+
+ # Setup the RPC channel
+ self.channel = SocketRpcChannel(host=self.host, port=self.port, version=hadoop_version, effective_user=effective_user,use_sasl=use_sasl)
+ self.service = self.service_stub_class(self.channel)
+
+ # go through service_stub methods and add a wrapper function to
+ # this object that will call the method
+ for method in service_stub_class.GetDescriptor().methods:
+ # Add service methods to the this object
+ rpc = lambda request, service=self, method=method.name: service.call(service_stub_class.__dict__[method], request)
+
+ self.__dict__[method.name] = rpc
+
+ def call(self, method, request):
+ controller = SocketRpcController()
+ return method(self.service, controller, request)
+
+
+class SocketRpcController(service.RpcController):
+ ''' RpcController implementation to be used by the SocketRpcChannel class.
+
+ The RpcController is used to mediate a single method call.
+ '''
+
+ def __init__(self):
+ '''Constructor which initializes the controller's state.'''
+ self._fail = False
+ self._error = None
+ self.reason = None
+
+ def handleError(self, error_code, message):
+ '''Log and set the controller state.'''
+ self._fail = True
+ self.reason = error_code
+ self._error = message
+
+ def reset(self):
+ '''Resets the controller i.e. clears the error state.'''
+ self._fail = False
+ self._error = None
+ self.reason = None
+
+ def failed(self):
+ '''Returns True if the controller is in a failed state.'''
+ return self._fail
+
+ def error(self):
+ return self._error
diff --git a/pool/shard003/Python/0029124_geojson_europe_test.py b/pool/shard003/Python/0029124_geojson_europe_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..243123f80300b7896729a2739fe19f3e1e6b1968
--- /dev/null
+++ b/pool/shard003/Python/0029124_geojson_europe_test.py
@@ -0,0 +1,42 @@
+import json
+from pathlib import Path
+
+import pytest
+
+
+BOUNDS = (
+ (-28, 56), # Azores (West), Novaya Zemlya (East)
+ (34, 71), # Gavdos (South), Nordkapp (North)
+)
+
+
+path = Path(__file__).parent / '../../../pythoncz/static/data/business.geojson'
+with path.open() as f:
+ features = json.load(f)['features']
+assert len(features) > 0
+
+
+@pytest.mark.parametrize('feature', [
+ pytest.param(feature, id=feature['properties']['name'])
+ for feature in features
+])
+def test_geojson_coords_are_in_europe(feature):
+ """Tests whether entries in GeoJSON are in Europe. If this test failed
+ for you, it's very likely because you have
+
+ "coordinates": [50.0703272, 14.4006753]
+
+ (which is Yemen) instead of
+
+ "coordinates": [14.4006753, 50.0703272]
+
+ (which is Prague) in your GeoJSON entry.
+ """
+ # For Point, convert list of coords to nested list
+ geometry_type = feature['geometry']['type']
+ coords = feature['geometry']['coordinates']
+ places = [coords] if geometry_type == 'Point' else coords
+
+ for place_coords in places:
+ for i, coord in enumerate(place_coords):
+ assert BOUNDS[i][0] < place_coords[i] < BOUNDS[i][1]
diff --git a/pool/shard003/Python/0029125_test_oauth2_authorization_code.py b/pool/shard003/Python/0029125_test_oauth2_authorization_code.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c634b91828c9d8b2bbc8674bce8dcb3050958c9
--- /dev/null
+++ b/pool/shard003/Python/0029125_test_oauth2_authorization_code.py
@@ -0,0 +1,67 @@
+try:
+ import mock
+except ImportError:
+ from unittest import mock
+
+import globus_sdk
+from tests.framework import CapturedIOTestCase
+
+
+class GlobusAuthorizationCodeFlowManagerTests(CapturedIOTestCase):
+
+ def setUp(self):
+ """
+ Inits a GlobusAuthorizationCodeFlowManager using a mock AuthClient
+ """
+ super(GlobusAuthorizationCodeFlowManagerTests, self).setUp()
+
+ self.ac = mock.Mock()
+ self.ac.client_id = "client_id"
+ self.ac.base_url = "base_url/"
+ self.flow_manager = globus_sdk.auth.GlobusAuthorizationCodeFlowManager(
+ self.ac, requested_scopes="scopes", redirect_uri="uri",
+ state="state")
+
+ def test_init_handles_iterable_scopes(self):
+ flow_manager = globus_sdk.auth.GlobusAuthorizationCodeFlowManager(
+ self.ac, requested_scopes=["scope1", "scope2"], redirect_uri="uri",
+ state="state")
+ self.assertEquals(flow_manager.requested_scopes, "scope1 scope2")
+
+ def test_get_authorize_url(self):
+ """
+ Creates an authorize url, confirms results match object values
+ Confirms additional params passed appear in the url
+ """
+ url = self.flow_manager.get_authorize_url()
+
+ expected_vals = [self.ac.base_url + "v2/oauth2/authorize?",
+ "client_id=", self.ac.client_id,
+ "redirect_uri=", self.flow_manager.redirect_uri,
+ "scope=", self.flow_manager.requested_scopes,
+ "state=", self.flow_manager.state,
+ "response_type=code",
+ "access_type=online"
+ ]
+ for val in expected_vals:
+ self.assertIn(val, url)
+
+ # confirm additional params are passed
+ params = {"param1": "value1", "param2": "value2"}
+ param_url = self.flow_manager.get_authorize_url(
+ additional_params=params)
+ for param, value in params.items():
+ self.assertIn(param + "=" + value, param_url)
+
+ def test_exchange_code_for_tokens(self):
+ """
+ Makes a token exchange with the mock AuthClient,
+ Confirms AuthClient gets and sends correct data.
+ """
+ auth_code = "code"
+ self.flow_manager.exchange_code_for_tokens(auth_code)
+
+ expected = {"grant_type": "authorization_code",
+ "code": auth_code.encode("utf-8"),
+ "redirect_uri": self.flow_manager.redirect_uri}
+ self.ac.oauth2_token.assert_called_with(expected)
diff --git a/pool/shard003/Python/0029126_layout.py b/pool/shard003/Python/0029126_layout.py
new file mode 100644
index 0000000000000000000000000000000000000000..56ac7421f4ad36a02936aef535b6269c79c55625
--- /dev/null
+++ b/pool/shard003/Python/0029126_layout.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+#
+# -*- coding: utf-8 -*-
+#
+
+import video
+import widgets
+
+import pygame
+import threading
+import logging
+logger = logging.getLogger(__name__)
+_DEB = logger.debug
+_INF = logger.info
+_WRN = logger.warning
+
+
+class LayoutLayer(threading.Thread):
+ def __init__(self):
+ threading.Thread.__init__(self)
+
+ self.__show = False
+ self.__active = True
+
+ self.__layouts = {}
+ self.__current = None
+
+ @property
+ def current(self):
+ return self.__layouts[self.__current]
+
+ def add_layout(self, layout_name, layout_config):
+ _DEB('Adding layout: %s' % layout_name)
+ self.__layouts[layout_name] = Layout(layout_config)
+ if self.__current is None:
+ self.__current = layout_name
+
+ def show(self, layout_name=None):
+ self.__show = True
+ if layout_name is None:
+ return
+ if layout_name not in self.__layouts.keys():
+ _WRN('Layout not found: %s (ignored)' % layout_name)
+ return
+ self.__current = layout_name
+
+ def hide(self):
+ self.__show = False
+
+ def update(self):
+ if not self.__show:
+ return
+ self.current.update()
+
+ def kill(self):
+ self.__show = False
+ self.__active = False
+
+ def run(self):
+ while self.__active:
+ self.update()
+
+
+class Layout(object):
+ def __init__(self, config={}):
+ self.__config = config
+ self.__frame = pygame.Surface(
+ video.Screen().get_size()).convert_alpha()
+ self.__frame.fill(pygame.Color(0, 0, 0, 0))
+ self.__widgets = {}
+ for widget_name in self.__config.keys():
+ self.__widgets[widget_name] = widgets.factory(
+ self.__config[widget_name])
+
+ self.__ready = False
+
+ @property
+ def frame(self):
+ return self.__frame
+
+ @property
+ def ready(self):
+ return self.__ready
+
+ def update(self):
+ self.__frame.fill(pygame.Color(0, 0, 0, 0))
+ ready = True
+ for widget in self.__widgets.values():
+ if not widget.ready:
+ ready = False
+ widget.update()
+ self.__frame.blit(widget.surface, widget.position)
+ self.__ready = ready
diff --git a/pool/shard003/Python/0029127_0028_auto_20180213_1050.py b/pool/shard003/Python/0029127_0028_auto_20180213_1050.py
new file mode 100644
index 0000000000000000000000000000000000000000..df94b725245ab4b1c97655e0deff50d62ab34f02
--- /dev/null
+++ b/pool/shard003/Python/0029127_0028_auto_20180213_1050.py
@@ -0,0 +1,46 @@
+# Generated by Django 2.0.2 on 2018-02-13 10:50
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('fdi', '0027_auto_20180208_1059'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='MarketGroupCountry',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('country', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='fdi.Country')),
+ ],
+ ),
+ migrations.RemoveField(
+ model_name='marketgroupmarket',
+ name='market',
+ ),
+ migrations.RemoveField(
+ model_name='marketgroupmarket',
+ name='market_group',
+ ),
+ migrations.RemoveField(
+ model_name='marketgroup',
+ name='markets',
+ ),
+ migrations.DeleteModel(
+ name='MarketGroupMarket',
+ ),
+ migrations.AddField(
+ model_name='marketgroupcountry',
+ name='market_group',
+ field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='fdi.MarketGroup'),
+ ),
+ migrations.AddField(
+ model_name='marketgroup',
+ name='countries',
+ field=models.ManyToManyField(through='fdi.MarketGroupCountry', to='fdi.Country'),
+ ),
+ ]
diff --git a/pool/shard003/Python/0029132_tests.py b/pool/shard003/Python/0029132_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..89e0d174b1f78dc331c8768d91d76b6fb300ab82
--- /dev/null
+++ b/pool/shard003/Python/0029132_tests.py
@@ -0,0 +1,39 @@
+import unittest
+from web import app
+from utils import parse, plot_sbg_results, plot_sbg_retention_distribution
+
+
+class SbgTestCase(unittest.TestCase):
+
+ def test_predict(self):
+ data = {'csvurl': './zoo/2.csv'}
+
+ response = app.test_client().post('/predict', data=data)
+
+ self.assertIn('Alpha', response.data)
+
+ def test_predict_values(self):
+ res = parse('zoo/2.csv', 0, 0, 0)
+
+ # Regular
+ self.assertAlmostEqual(res[0].alpha, 0.697, 3)
+ self.assertAlmostEqual(res[0].beta, 1.169, 3)
+
+ # High end
+ self.assertAlmostEqual(res[1].alpha, 0.596, 3)
+ self.assertAlmostEqual(res[1].beta, 3.327, 3)
+
+ def test_sbg_plot(self):
+ res = parse('zoo/2.csv', 0, 0, 0)
+ script, div = plot_sbg_results(res)
+ self.assertIn("