'
+print container.sitemap()
+print container.searchBox()
+if not (user.has_role(['Manager'], container) or hasattr(ROOT.people, username)):
+ print container.loginBox()
+print '
'
+
+print ''
+
+return printed
diff --git a/pool/shard009/Python/0085577_shapes.py b/pool/shard009/Python/0085577_shapes.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee58a7e7c46500bf4a040de3b9208839fc6e7ca2
--- /dev/null
+++ b/pool/shard009/Python/0085577_shapes.py
@@ -0,0 +1,140 @@
+# coding=utf-8
+# Copyright 2022 The Trax 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.
+
+"""Core class and functions for handling data abstractly as shapes/dtypes."""
+
+import numpy as np
+import tensorflow as tf
+
+
+class ShapeDtype:
+ """A NumPy ndarray-like object abstracted as shape and dtype.
+
+ Main use is for representing input and output signatures.
+ """
+ __slots__ = ['shape', 'dtype']
+
+ def __init__(self, shape, dtype=np.float32):
+ """Creates a `ShapeDtype` instance, with canonicalized `shape` and `dtype`.
+
+ Args:
+ shape: A tuple or list, each element of which is an int or, less often,
+ `None`.
+ dtype: A `dtype` object, either from NumPy or TensorFlow.
+
+ Returns:
+ A `ShapeDtype` instance whose `shape` is a tuple and `dtype` is a NumPy
+ `dtype` object.
+ """
+ # Canonicalize shape and dtype.
+ if isinstance(shape, tf.TensorShape):
+ shape = shape.as_list()
+ if isinstance(shape, list):
+ shape = tuple(shape)
+ if not isinstance(shape, tuple):
+ raise TypeError('shape must be tuple or list; got: {}'.format(shape))
+ if isinstance(dtype, tf.DType):
+ dtype = dtype.as_numpy_dtype
+
+ self.shape = shape
+ self.dtype = dtype
+
+ def __eq__(self, other):
+ return (isinstance(other, self.__class__)
+ and self.shape == other.shape
+ and self.dtype == other.dtype)
+
+ def __ne__(self, other):
+ return not self == other
+
+ def __repr__(self):
+ return 'ShapeDtype{{shape:{}, dtype:{}}}'.format(self.shape, self.dtype)
+
+ def __len__(self):
+ """Returns length of 1; relevant to input and output signatures."""
+ return 1
+
+ def as_tuple(self):
+ return self.shape, self.dtype
+
+ def replace(self, **kwargs):
+ """Creates a copy of the object with some parameters replaced."""
+ return type(self)(
+ shape=kwargs.pop('shape', self.shape),
+ dtype=kwargs.pop('dtype', self.dtype),
+ )
+
+
+def signature(obj):
+ """Returns a `ShapeDtype` signature for the given `obj`.
+
+ A signature is either a `ShapeDtype` instance or a tuple of `ShapeDtype`
+ instances. Note that this function is permissive with respect to its inputs
+ (accepts lists or tuples or dicts, and underlying objects can be any type
+ as long as they have shape and dtype attributes) and returns the corresponding
+ nested structure of `ShapeDtype`.
+
+ Args:
+ obj: An object that has `shape` and `dtype` attributes, or a list/tuple/dict
+ of such objects.
+
+ Returns:
+ A corresponding nested structure of `ShapeDtype` instances.
+ """
+ if isinstance(obj, (list, tuple)):
+ output = tuple(signature(x) for x in obj)
+ return output if isinstance(obj, tuple) else list(output)
+ elif isinstance(obj, dict):
+ return {k: signature(v) for (k, v) in obj.items()}
+ else:
+ return ShapeDtype(obj.shape, obj.dtype)
+
+
+def splice_signatures(*sigs):
+ """Creates a new signature by splicing together any number of signatures.
+
+ The splicing effectively flattens the top level input signatures. For
+ instance, it would perform the following mapping:
+
+ - `*sigs: sd1, (sd2, sd3, sd4), (), sd5`
+ - return: `(sd1, sd2, sd3, sd4, sd5)`
+
+ Args:
+ *sigs: Any number of signatures. A signature is either a `ShapeDtype`
+ instance or a tuple of `ShapeDtype` instances.
+
+ Returns:
+ A single `ShapeDtype` instance if the spliced signature has one element,
+ else a tuple of `ShapeDtype` instances.
+ """
+ result_sigs = []
+ for sig in sigs:
+ if isinstance(sig, (list, tuple)):
+ result_sigs.extend(sig)
+ else:
+ result_sigs.append(sig)
+ return result_sigs[0] if len(result_sigs) == 1 else tuple(result_sigs)
+
+
+def assert_shape_equals(array, shape):
+ """Asserts that an array has the given shape."""
+ assert array.shape == shape, (
+ 'Invalid shape {}; expected {}.'.format(array.shape, shape)
+ )
+
+
+def assert_same_shape(array1, array2):
+ """Asserts that two arrays have the same shapes."""
+ assert_shape_equals(array1, array2.shape)
diff --git a/pool/shard009/Python/0085579_ok.py b/pool/shard009/Python/0085579_ok.py
new file mode 100644
index 0000000000000000000000000000000000000000..e962404430c579a000caa5b65f105f980b0c59a5
--- /dev/null
+++ b/pool/shard009/Python/0085579_ok.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
+import odnoklassniki
+from django.conf import settings
+from social_publisher.backends import base
+
+
+class OKBackend(base.BaseBackend):
+ name = 'ok'
+ auth_provider = 'odnoklassniki'
+
+ def get_api(self, social_user):
+ return odnoklassniki.Odnoklassniki(
+ client_key=settings.ODNOKLASSNIKI_OAUTH2_CLIENT_KEY,
+ client_secret=settings.ODNOKLASSNIKI_OAUTH2_CLIENT_SECRET,
+ token=social_user.extra_data.get('access_token')
+ )
+
+ def get_api_publisher(self, social_user):
+ """
+ and other https://vk.com/dev.php?method=wall.post
+ """
+
+ def _post(**kwargs):
+ api = self.get_api(social_user)
+ from pudb import set_trace; set_trace()
+ # api.group.getInfo('uids'='your_group_id', 'fields'='members_count')
+ #response = api.wall.post(**kwargs)
+ return response
+
+ return _post
diff --git a/pool/shard009/Python/0085582_pyslurmtopbs.py b/pool/shard009/Python/0085582_pyslurmtopbs.py
new file mode 100644
index 0000000000000000000000000000000000000000..001a77d50abb51ec8f7ff326ccba759c8969759f
--- /dev/null
+++ b/pool/shard009/Python/0085582_pyslurmtopbs.py
@@ -0,0 +1,171 @@
+#!/usr/bin/env python
+
+import sys
+import math
+import getopt
+import re
+import copy
+import time
+import subprocess
+import xml.dom
+from xml.dom.minidom import parse, parseString
+
+
+element_node='Node' # Basic node of pbsnodes xml output
+
+# Only for debugging: Arguments overwritten by input
+args=['-s','status','-n','mike[001-130,210,343]',\
+ '-u','foo1,foo2','-u','foo3','-f','file',\
+ '-u','user','-j','jobid1,jobid2', '-j', 'jobid3']
+
+# Options to be parsed
+opts='-f:-u:-s:-j:-n:-h'
+
+#----------------------------
+# Compile useful re searches
+#----------------------------
+#
+# For parsing name,state and status
+np_srch= re.compile('(np=)([0-9]+)') #-Processors
+gpus_srch= re.compile('(gpus=)([0-9]+)') #-GPUs
+time_srch= re.compile('(rectime=)([0-9]+)') #-Recent Time
+load_srch= re.compile('(loadave=)([0-9.]+)') #-Node Load
+jobs_srch= re.compile('(jobs=)([0-9.a-z ]+)') #-Node Jobs
+amem_srch= re.compile('(availmem=)([0-9]+)([a-zA-Z]b)') #-Avail Mem
+pmem_srch= re.compile('(physmem=)([0-9]+)([a-zA-Z]b)') #-Phys Mem
+tmem_srch= re.compile('(totmem=)([0-9]+)([a-zA-Z]b)') #-Total Mem
+gpu_usrch= re.compile('gpu_utilization=([0-9]+%)')
+gpu_msrch= re.compile('gpu_memory_utilization=([0-9]+%)')
+# For parsing hostlist passed via '-n'
+hname_srch = re.compile('[a-zA-Z]+') # Hostname
+htacc_srch = re.compile('[a-zA-Z]+')
+intvl_srch = re.compile(':([0-9]+)') # Interval
+solo_node_srch = re.compile('[0-9]+') # Single node
+nodes_list_srch = re.compile('[0-9,-:]+') # Block of nodes
+split_nodes_srch= re.compile('([0-9]+)-([0-9]+)') # Comma sep. block
+
+helptext="""
++-------+
+| Usage :
++-------+
+
+ python -n host[001-020:2,101-120:3,202,430]
+ Run pbsnodes on 001 though 003 at intervals of 2
+ Run pbsnodes on 101 though 120 at intervals of 3
+ and additionally on comma separated values 202,430
+
+ python Without arguments, it runs pbsnodes on all nodes
+
+ python -h Will print help message and exit
+
+"""
+def help():
+ print helptext
+
+# +------------------------------------------------
+# ! Scan nodes:
+# ! -n host[001-100:10,113]
+# ! will scan host001,host011,...,host091,host113
+# +------------------------------------------------
+def process_nodes(a):
+ # +--------------------------------
+ # ! Transforms hosts to a flat list
+ # +--------------------------------
+ m0=hname_srch.search(a)
+ cluster=a[m0.start():m0.end()]
+ m1=nodes_list_srch.search(a)
+ nodelist=a[m1.start():m1.end()]
+ b=[]
+ if m1:
+ for x in nodelist.split(','):
+ m2=split_nodes_srch.search(x)
+ if m2:
+ begin=m2.groups()[0]
+ end=m2.groups()[1] if m2.groups()[1] else begin
+ m4=intvl_srch.search(x)
+ #print begin,end,x[m4.start()+1:m4.end()]
+ intvl=int(x[m4.start()+1:m4.end()]) if m4 else 1
+ pow=int(math.log(int(begin),10))
+ for y in range(int(begin) ,int(end)+1,intvl):
+ pow=int(math.log(y,10))+1
+ node=cluster+begin[0:len(begin)-pow]+str(y)
+ b.insert(0,str(node))
+ else:
+ m3=solo_node_srch.search(x)
+ #print 'solo',m3
+ if m3:
+ node=cluster+x[m3.start():m3.end()]
+ b.insert(0,node)
+ if b==[]:
+ print "No useful nodes found with -n "
+ # sys.exit()
+ return b
+
+
+#----------------------------
+# Parse Input: getopt
+#----------------------------
+#
+if sys.argv:
+ args=sys.argv[1:]
+
+optlist,arglist=getopt.getopt(args,opts)
+#print optlist
+print "Options Supplied \n %s" %optlist
+
+opts_dic={}
+
+for o,a in optlist:
+ if o=='-u':
+ if o in opts_dic:
+ opts_dic[o]+=a
+ else:
+ opts_dic[o]=[a]
+ print "User search %s" %a
+ elif o=='-j':
+ print "Jobid search %s" %a
+ if o in opts_dic:
+ opts_dic[o]+=[a]
+ else:
+ opts_dic[o]=[a]
+ elif o=='-n':
+ b=process_nodes(a)
+ if o in opts_dic:
+ opts_dic[o]+=b
+ else:
+ opts_dic[o]=b
+ #print "Scanning Nodes \n %s " %(opts_dic[o])
+ #sys.exit()
+ elif o=='-s':
+ print "Status search %s" %a
+ if o in opts_dic:
+ opts_dic[o]+=[a]
+ else:
+ opts_dic[o]=[a]
+ elif o=='-f':
+ print "Using file %s" %a
+ if o in opts_dic:
+ opts_dic[o]+=[a]
+ else:
+ opts_dic[o]=[a]
+ elif o=='-h':
+ help()
+ sys.exit()
+ else:
+ print "Unrecognized option %s" %a
+
+nodelist=[]
+#print opts_dic['-n']
+if '-n' in opts_dic:
+ nodelist.extend(opts_dic['-n'])
+elif '-u' in opts_dic:
+ print "ToDo: Union of n and u"
+elif '-j' in opts_dic:
+ print "ToDo: Union of n, u and"
+
+
+#-------------------------------------------
+# System command to get output from pbsnodes
+#-------------------------------------------
+#
+print b
diff --git a/pool/shard009/Python/0085600_simple.py b/pool/shard009/Python/0085600_simple.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f93af7551d7b9b5ac2ac7c9a1396a465a91d447
--- /dev/null
+++ b/pool/shard009/Python/0085600_simple.py
@@ -0,0 +1,16 @@
+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+class Emitter(object):
+ def __init__(self, **kwargs):
+ self.filename = kwargs['filename']
+
+ def emit(self, metrics):
+ """ Ship the metrics off """
+ with open(self.filename, 'a') as fh:
+ for metric in metrics:
+ mline = '|'.join([str(m) for m in metric])
+ logger.debug('Writing metric out to file - {0}'.format(mline))
+ fh.write(mline+'\n')
diff --git a/pool/shard009/Python/0085604_test_webdriver_phantomjs.py b/pool/shard009/Python/0085604_test_webdriver_phantomjs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3be7401a4b5ae82caf2bf8fc15b9cd9b1a87f467
--- /dev/null
+++ b/pool/shard009/Python/0085604_test_webdriver_phantomjs.py
@@ -0,0 +1,75 @@
+import unittest
+
+from splinter import Browser
+from .fake_webapp import EXAMPLE_APP
+from .base import WebDriverTests
+
+
+class PhantomJSBrowserTest(WebDriverTests, unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.browser = Browser("phantomjs")
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.browser.quit()
+
+ def setUp(self):
+ self.browser.visit(EXAMPLE_APP)
+
+ def test_get_alert(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_right_click(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.find_by_id('visible').right_click()
+
+ def test_double_click(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.find_by_id('visible').double_click()
+
+ def test_access_prompts_and_be_able_to_fill_then(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_access_confirm_and_accept_and_dismiss_them_using_with(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_access_confirm_and_accept_and_dismiss_them(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_access_alerts_using_with(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_access_alerts_and_accept_them(self):
+ with self.assertRaises(NotImplementedError):
+ self.browser.get_alert()
+
+ def test_can_work_on_popups(self):
+ # FIXME: Check https://github.com/detro/ghostdriver/issues/180 to see if
+ # we can implement this test
+ pass
+
+
+class PhantomJSBrowserTestWithCustomHeaders(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ custom_headers = {'X-Splinter-Customheaders-1': 'Hello',
+ 'X-Splinter-Customheaders-2': 'Bye'}
+ cls.browser = Browser("phantomjs", custom_headers=custom_headers)
+
+ def test_create_a_phantomjs_with_custom_headers(self):
+ self.browser.visit(EXAMPLE_APP + 'headers')
+ self.assertTrue(
+ self.browser.is_text_present('X-Splinter-Customheaders-1: Hello'))
+ self.assertTrue(
+ self.browser.is_text_present('X-Splinter-Customheaders-2: Bye'))
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.browser.quit()
diff --git a/pool/shard009/Python/0085608_msgbus_cmd.py b/pool/shard009/Python/0085608_msgbus_cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..569affd1a9801ed3c063bda610eb99c2190b36f5
--- /dev/null
+++ b/pool/shard009/Python/0085608_msgbus_cmd.py
@@ -0,0 +1,100 @@
+#!/usr/local/bin/python
+#CHIPSEC: Platform Security Assessment Framework
+#Copyright (c) 2010-2016, Intel Corporation
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU General Public License
+#as published by the Free Software Foundation; Version 2.
+#
+#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.
+#
+#Contact information:
+#chipsec@intel.com
+#
+
+
+
+__version__ = '1.0'
+
+import os
+import sys
+import time
+
+import chipsec_util
+from chipsec.command import BaseCommand
+
+from chipsec.logger import *
+from chipsec.file import *
+from chipsec.hal.msgbus import MsgBus
+
+
+# Message Bus
+class MsgBusCommand(BaseCommand):
+ """
+ >>> chipsec_util msgbus read
+ >>> chipsec_util msgbus write
+ >>> chipsec_util msgbus message [value]
+ >>>
+ >>> : message bus port of the target unit
+ >>> : message bus register/offset in the target unit port
+ >>> : value to be written to the message bus register/offset
+ >>> : opcode of the message on the message bus
+
+ Examples:
+
+ >>> chipsec_util msgbus read 0x3 0x2E
+ >>> chipsec_util msgbus write 0x3 0x27 0xE0000001
+ >>> chipsec_util msgbus message 0x3 0x2E 0x10
+ >>> chipsec_util msgbus message 0x3 0x2E 0x11 0x0
+ """
+ def requires_driver(self):
+ # No driver required when printing the util documentation
+ if len(self.argv) < 3:
+ return False
+ return True
+
+ def run(self):
+ if len(self.argv) > 7 or len(self.argv) < 5:
+ print MsgBusCommand.__doc__
+ return
+
+ op = self.argv[2]
+ t = time.time()
+
+ _msgbus = self.cs.msgbus
+
+ res = None
+ port = int(self.argv[3], 16)
+ reg = int(self.argv[4], 16)
+
+ if 'read' == op:
+ self.logger.log("[CHIPSEC] msgbus read: port 0x%02X + 0x%08X" % (port, reg))
+ res = _msgbus.msgbus_reg_read( port, reg )
+ elif 'write' == op:
+ if len(self.argv) < 6:
+ print msgbuscmd.__doc__
+ return
+ val = int(self.argv[5], 16)
+ self.logger.log("[CHIPSEC] msgbus write: port 0x%02X + 0x%08X < 0x%08X" % (port, reg, val))
+ res = _msgbus.msgbus_reg_write( port, reg, val )
+ elif 'message' == op:
+ opcode = int(self.argv[5], 16)
+ val = None if len(self.argv) < 7 else int(self.argv[6], 16)
+ self.logger.log("[CHIPSEC] msgbus message: port 0x%02X + 0x%08X, opcode: 0x%02X" % (port, reg, opcode))
+ if val is not None: self.logger.log("[CHIPSEC] data: 0x%08X" % val)
+ res = _msgbus.msgbus_send_message( port, reg, opcode, val )
+ else:
+ print msgbuscmd.__doc__
+ return
+
+ if res is not None: self.logger.log("[CHIPSEC] result: 0x%08X" % res)
+ self.logger.log( "[CHIPSEC] (msgbus) time elapsed %.3f" % (time.time()-t) )
+
+commands = { 'msgbus': MsgBusCommand }
diff --git a/pool/shard009/Python/0085609_decay_of_LD_lowd.py b/pool/shard009/Python/0085609_decay_of_LD_lowd.py
new file mode 100644
index 0000000000000000000000000000000000000000..d983ba8cead8203f7b747fc77baa02389153c74f
--- /dev/null
+++ b/pool/shard009/Python/0085609_decay_of_LD_lowd.py
@@ -0,0 +1,63 @@
+# vim: fdm=indent
+'''
+author: Richard Neher, Fabio Zanini
+date: 23/08/12
+content: Example of haploid_lowd on linkage relaxation via recombination
+'''
+# Import modules (setting the path should not be necessary when the module is
+# installed in the PYTHONPATH)
+import sys
+sys.path.insert(0, '../pkg/python')
+
+import numpy as np
+import matplotlib.pyplot as plt
+import FFPopSim as h
+
+
+# specify parameters
+N = 500000 # Population size
+L = 4 # number of loci
+mu = 0.0 # no new mutations
+r = 0.01 # recombination rate
+
+### set up
+pop = h.haploid_lowd(L) # produce an instance of haploid_lowd with L loci
+pop.carrying_capacity = N # set the steady-state population size
+pop.set_recombination_rates(r) # assign the recombination rate
+pop.set_mutation_rates(mu) # assign the mutation rate
+
+# initialize the population with
+# - N/2 individuals with genotype 0, that is ----
+# - N/2 with the opposite genotype, that is ++++
+pop.set_genotypes([0, 2**L - 1],
+ [N/2, N/2])
+
+print "\nTrack LD and compare to deterministic expectations\n"
+
+pop.status()
+
+# get initial LD
+LD_trajectories = [[pop.generation, pop.get_LD(0,1), pop.get_LD(0,2), pop.get_LD(0,3)]]
+
+# evolve with accuracy of 5 generations and save LD along the way
+for ii in xrange(50):
+
+ pop.evolve(5)
+
+ # get LD and time
+ LD_trajectories.append([pop.generation, pop.get_LD(0,1), pop.get_LD(0,2), pop.get_LD(0,3)])
+
+LD_trajectories=np.array(LD_trajectories)
+
+# plot the LD trajectories and compare to exponential decay
+cols = ['r', 'b', 'g', 'm', 'c']
+for ii in xrange(LD_trajectories.shape[1]-1):
+ plt.plot(LD_trajectories[:,0], LD_trajectories[:,ii+1], color=cols[ii], label=r'$D_{0'+str(ii+1)+'}$')
+ plt.plot(LD_trajectories[:,0], 0.25 * np.exp(-LD_trajectories[:,0] * r * (ii+1)), ls='--', color=cols[ii])
+
+plt.legend()
+plt.xlabel('Time [generations]')
+plt.ylabel('LD $D_{ij}$')
+
+plt.ion()
+plt.show()
diff --git a/pool/shard009/Python/0085620_test.py b/pool/shard009/Python/0085620_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..d77ff335f36073c53ebaec8b403f54c1d5685339
--- /dev/null
+++ b/pool/shard009/Python/0085620_test.py
@@ -0,0 +1,64 @@
+from particles import Ion
+
+from accelerator import Accelerator
+from pipes import Pipe
+from magnets import QuadrupoleMagnet
+from magnets import SectorBendingMagnet
+from magnets import HorizontalKickerMagnet
+from diagnostic import Transformator
+from diagnostic import Screen
+from diagnostic import Slit
+import xml.etree.ElementTree as ET
+
+ion = Ion(92, 146, 19, 1000)
+
+print(ion)
+
+ion = Ion(protons=6, neutrons=8, electrons=4, energy=1000)
+
+print(ion)
+
+acc = Accelerator()
+
+width = 0.4
+height = 0.2
+
+t0 = Transformator("T0", width, height)
+p1 = Pipe(width, height, 1.0)
+s0 = Screen("Screen", width, height, 0.2, 0.2)
+t1 = Transformator("T1", width, height)
+q1 = QuadrupoleMagnet("UN4QD11", width, height, 1.0, 0.8)
+q2 = QuadrupoleMagnet("UN4QD12", width, height, 1.0, -0.5)
+sl1 = Slit("Slit1", width, height)
+p2 = Pipe(width, height, 3.0)
+sl2 = Slit("Slit2", width, height)
+k1 = HorizontalKickerMagnet("kicker", width, height, 0.02)
+p3 = Pipe(width, height, 3.0)
+t2 = Transformator("T2", width, height)
+m1 = SectorBendingMagnet("UN4MU1", width, height, length=1.0, angle=0.5)
+t3 = Transformator("T3", width, height)
+s1 = Screen("Screen1", width, height, 0.2, 0.2)
+s2 = Screen("Screen2", width, height, 0.2, 0.2)
+
+#acc.append_devices([t0])
+#print(repr(acc))
+sl1.set_positions(xpos_left=-0.01, xpos_right=0.01, ypos_bottom=-0.01, ypos_top=0.01)
+acc.append_devices([t0, p1, sl1, s0, t1, q2, p2, sl2, s1, k1, p3, t2, m1, t3, s2])
+
+#print(acc.to_xml())
+acc.to_file('acc.xml')
+
+xml_root = ET.parse('acc.xml').getroot()
+acc2 = Accelerator(xml_root=xml_root)
+print(acc)
+print(acc2)
+
+
+acc.start_simulation(100000)
+acc.get_device_by_nomenclature("Screen1").show()
+print("T0:", acc.get_device_by_nomenclature("T0").count.value)
+print("T1:", acc.get_device_by_nomenclature("T1").count.value)
+
+#acc2.start_simulation(10000)
+#acc2.get_device_by_nomenclature("Screen2").show()
+#print("T1:", acc.get_device_by_nomenclature("T1").count.value)
\ No newline at end of file
diff --git a/pool/shard009/Python/0085623_package_state.py b/pool/shard009/Python/0085623_package_state.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0eb10a8f08eebb0dcfd522b77cddace9ada89c6
--- /dev/null
+++ b/pool/shard009/Python/0085623_package_state.py
@@ -0,0 +1,81 @@
+# vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0:
+# License: GPL2 or later see COPYING
+# Written by Seth Vidal
+# Copyright (C) 2012 Red Hat, Inc
+
+# this plugin dumps out two lists of pkgs:
+# A list of all available pkgs + repos + other data
+# A list of all installed pkgs + repos + other data
+# into the results dir
+# two files - available_pkgs
+# installed_pkgs
+
+# our imports
+from mockbuild.trace_decorator import traceLog
+import mockbuild.util
+import tempfile
+import os
+
+# repoquery used
+repoquery_avail_opts = "--qf '%{name}-%{epoch}:%{version}-%{release}.%{arch} %{buildtime} %{size} %{pkgid} %{repoid}' '*'"
+
+# set up logging, module options
+requires_api_version = "1.1"
+
+
+# plugin entry point
+@traceLog()
+def init(plugins, conf, buildroot):
+ PackageState(plugins, conf, buildroot)
+
+
+class PackageState(object):
+ """dumps out a list of packages available and in the chroot"""
+ @traceLog()
+ def __init__(self, plugins, conf, buildroot):
+ self.buildroot = buildroot
+ self.config = buildroot.config
+ self.state = buildroot.state
+ self.avail_done = False
+ self.inst_done = False
+ self.online = self.config['online']
+ plugins.add_hook("postyum", self._availablePostYumHook)
+ plugins.add_hook("prebuild", self._installedPreBuildHook)
+
+ @traceLog()
+ def _availablePostYumHook(self):
+ if self.online and not self.avail_done:
+ self.buildroot.uid_manager.dropPrivsTemp()
+ self.state.start("Outputting list of available packages")
+ out_file = self.buildroot.resultdir + '/available_pkgs'
+ chrootpath = self.buildroot.make_chroot_path()
+ if self.config['package_manager'] == 'dnf':
+ cmd = "/usr/bin/repoquery --installroot={0} -c {0}/etc/yum.conf {1} > {2}".format(
+ chrootpath, repoquery_avail_opts, out_file)
+ else:
+ cmd = "/usr/bin/dnf --installroot={0} repoquery -c {0}/etc/dnf.conf {1} > {2}".format(
+ chrootpath, repoquery_avail_opts, out_file)
+ # print(cmd)
+ mockbuild.util.do(cmd, shell=True, env=self.buildroot.env)
+ self.avail_done = True
+ self.state.finish("Outputting list of available packages")
+ self.buildroot.uid_manager.restorePrivs()
+
+ @traceLog()
+ def _installedPreBuildHook(self):
+ if self.online and not self.inst_done:
+ self.state.start("Outputting list of installed packages")
+ fd, fn = tempfile.mkstemp()
+ fo = os.fdopen(fd, 'w')
+ fo.write('[main]\ninstallroot=%s' % self.buildroot.make_chroot_path())
+ fo.flush()
+ fo.close()
+ out_file = self.buildroot.resultdir + '/installed_pkgs'
+ cmd = "rpm -qa --root '%s' --qf '%%{nevra} %%{buildtime} %%{size} %%{pkgid} installed\\n' > %s" % (
+ self.buildroot.make_chroot_path(), out_file)
+ self.buildroot.uid_manager.restorePrivs()
+ mockbuild.util.do(cmd, shell=True, env=self.buildroot.env)
+ self.buildroot.uid_manager.dropPrivsTemp()
+ self.inst_done = True
+ os.unlink(fn)
+ self.state.finish("Outputting list of installed packages")
diff --git a/pool/shard009/Python/0085628_setup.py b/pool/shard009/Python/0085628_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..a67ed77baf9853826c3c95fc25fc16763886e14f
--- /dev/null
+++ b/pool/shard009/Python/0085628_setup.py
@@ -0,0 +1,54 @@
+# -*- coding: utf-8 -*-
+#
+# Author: Taylor Smith
+#
+# Setup for submodules of pmdarima
+
+import os
+import sys
+
+from pmdarima._build_utils import cythonize_extensions
+
+
+# DEFINE CONFIG
+def configuration(parent_package='', top_path=None):
+ from numpy.distutils.misc_util import Configuration
+
+ libs = []
+ if os.name == 'posix':
+ libs.append('m')
+
+ config = Configuration('pmdarima', parent_package, top_path)
+
+ # build utilities
+ config.add_subpackage('__check_build')
+ config.add_subpackage('_build_utils')
+
+ # submodules that do NOT have their own setup.py. manually add their tests
+ config.add_subpackage('compat')
+ config.add_subpackage('compat/tests')
+ config.add_subpackage('datasets')
+ config.add_subpackage('datasets/tests')
+ config.add_subpackage('model_selection')
+ config.add_subpackage('model_selection/tests')
+
+ # the following packages have cython or their own setup.py files.
+ config.add_subpackage('arima')
+ config.add_subpackage('preprocessing')
+ config.add_subpackage('utils')
+
+ # add test directory
+ config.add_subpackage('tests')
+
+ # Do cythonization, but only if this is not a release tarball, since the
+ # C/C++ files are not necessarily forward compatible with future versions
+ # of python.
+ if 'sdist' not in sys.argv:
+ cythonize_extensions(top_path, config)
+
+ return config
+
+
+if __name__ == '__main__':
+ from numpy.distutils.core import setup
+ setup(**configuration(top_path='').todict())
diff --git a/pool/shard009/Python/0085633_moviegen.py b/pool/shard009/Python/0085633_moviegen.py
new file mode 100644
index 0000000000000000000000000000000000000000..3798231eb3b890deee4516b5a0f9a6800ecb04ba
--- /dev/null
+++ b/pool/shard009/Python/0085633_moviegen.py
@@ -0,0 +1,96 @@
+
+from __future__ import print_function
+
+import sys
+from tempfile import NamedTemporaryFile as TmpFile
+import shutil
+
+import numpy as np
+
+import vis
+from utils import find_nearest
+from scipy.io.wavfile import write
+from subprocess import call
+
+import matplotlib.pyplot as plt
+from vis import tf_detail
+from matplotlib import animation
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+import matplotlib.gridspec as gridspec
+
+
+def animate_tf_detail(TF,
+ ods,
+ t_ods,
+ sr_ods,
+ T,
+ signal,
+ outfile,
+ fps=24,
+ title=None):
+
+ # First set up the figure, the axis, and the plot element we want
+ # to animate
+ (fig, tf_line, t_line, detail) = tf_detail(TF,
+ t_ods,
+ T,
+ title,
+ np.max(t_ods) / 2.0,
+ ods,
+ np.abs)
+
+ # initialization function
+ def init():
+ tf_line.set_xdata([0, 0])
+ t_line.set_xdata([0, 0])
+ detail.set_xdata(np.abs(TF[:, 0]))
+ return tf_line, t_line, detail
+
+ # animation function. This is called sequentially
+ def animate(i):
+ t_detail = 1.0*i/fps
+ __, detail_idx = find_nearest(t_ods, t_detail)
+ tf_line.set_xdata([t_detail, t_detail])
+ t_line.set_xdata([t_detail, t_detail])
+ detail.set_xdata(np.abs(TF[:, detail_idx]))
+
+ print(' {0:.2f}/{1:.2f}'.format(t_detail, max(t_ods)),
+ end='\r')
+ sys.stdout.flush()
+
+ return tf_line, t_line, detail
+
+ # call the animator. blit=True means only re-draw the parts that
+ # have changed.
+ anim = animation.FuncAnimation(fig,
+ animate,
+ init_func=init,
+ frames=int(fps*np.max(t_ods))+1, # +1?
+ interval=1000.0/fps,
+ # blit=True)
+ blit=False)
+
+ with TmpFile(suffix='.mp4') as temp_video, \
+ TmpFile(suffix='.wav') as temp_audio:
+
+ # FFwriter = animation.FFMpegWriter(fps=fps, bitrate=40000)
+ FFwriter = animation.FFMpegWriter(fps=fps, bitrate=10000)
+ anim.save(temp_video.name,
+ writer=FFwriter,
+ extra_args=['-vcodec', 'libx264', '-preset', 'slow'])
+
+ # add audio
+ import pdb
+ pdb.set_trace()
+
+ write(temp_audio.name, signal.sr, signal)
+ call(['ffmpeg', '-i', temp_video.name,
+ # '-itsoffset', '00:00:00.1', # for some reason, the first bit of audio is lost if not delayed
+ '-i', temp_audio.name,
+ '-vcodec', 'copy',
+ '-acodec', 'aac',
+ '-strict', 'experimental',
+ '-y', # overwrite output file w/o asking
+ outfile])
+
diff --git a/pool/shard009/Python/0085638_conf.py b/pool/shard009/Python/0085638_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..573e42c39b70e08b57d3cc477ec7cc50383d9192
--- /dev/null
+++ b/pool/shard009/Python/0085638_conf.py
@@ -0,0 +1,275 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# zipfreeinfo 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 zipfreeinfo
+
+# -- 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'zipfreeinfo'
+copyright = u"2016, Marcellus Easley"
+
+# 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 = zipfreeinfo.__version__
+# The full version, including alpha/beta/rc tags.
+release = zipfreeinfo.__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 = 'zipfreeinfodoc'
+
+
+# -- 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', 'zipfreeinfo.tex',
+ u'zipfreeinfo Documentation',
+ u'Marcellus Easley', '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', 'zipfreeinfo',
+ u'zipfreeinfo Documentation',
+ [u'Marcellus Easley'], 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', 'zipfreeinfo',
+ u'zipfreeinfo Documentation',
+ u'Marcellus Easley',
+ 'zipfreeinfo',
+ '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/shard009/Python/0085639_urls.py b/pool/shard009/Python/0085639_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..140d4b0944c561b849e9207dbdd8e5952bf701f1
--- /dev/null
+++ b/pool/shard009/Python/0085639_urls.py
@@ -0,0 +1,23 @@
+from django.conf.urls import include, url
+from django.contrib import admin
+from his import views as hi_views
+from letsencrypt import views as le_views
+
+api_patterns = [
+ url(r'^$', hi_views.api_docs),
+ url(r'^user/(?P\w+)', hi_views.api_user_hi),
+ url(r'^post', hi_views.api_post_hi),
+]
+
+urlpatterns = [
+ url(r'^$', hi_views.all_hi),
+ url(r'^user/(?P\w+)', hi_views.user_hi),
+ url(r'^api/', include(api_patterns)),
+ url(r'^admin/', include(admin.site.urls)),
+ url(r'^account/', include('allauth_2fa.urls')),
+ url(r'^account/', include('allauth.urls')),
+ url(r'^account/profile/$', hi_views.profile),
+ url(r'^account/refresh_token/$', hi_views.refresh_token),
+
+ url(r'^.well-known/acme-challenge/(?P\w+)', le_views.challenge)
+]
diff --git a/pool/shard009/Python/0085641_vad.py b/pool/shard009/Python/0085641_vad.py
new file mode 100644
index 0000000000000000000000000000000000000000..af92a70775631933899685cc07e163c3b776b424
--- /dev/null
+++ b/pool/shard009/Python/0085641_vad.py
@@ -0,0 +1,90 @@
+"""
+ Voice Activity Detector based on WebRTC VAD (https://github.com/wiseman/py-webrtcvad)
+ Copyright (c) 2016 Seeed Technology Limited.
+
+ 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 collections
+import sys
+
+import webrtcvad
+
+
+class WebRTCVAD:
+ def __init__(self, sample_rate=16000, level=3):
+ """
+
+ Args:
+ sample_rate: audio sample rate
+ level: between 0 and 3. 0 is the least aggressive about filtering out non-speech, 3 is the most aggressive.
+ """
+ self.sample_rate = sample_rate
+
+ self.frame_ms = 30
+ self.frame_bytes = int(2 * self.frame_ms * self.sample_rate / 1000) # S16_LE, 2 bytes width
+
+ self.vad = webrtcvad.Vad(level)
+ self.active = False
+ self.data = b''
+ self.history = collections.deque(maxlen=128)
+
+ def is_speech(self, data):
+ self.data += data
+ while len(self.data) >= self.frame_bytes:
+ frame = self.data[:self.frame_bytes]
+ self.data = self.data[self.frame_bytes:]
+
+ if self.vad.is_speech(frame, self.sample_rate):
+ sys.stdout.write('1')
+ self.history.append(1)
+ else:
+ sys.stdout.write('0')
+ self.history.append(0)
+
+ num_voiced = 0
+ for i in range(-8, 0):
+ try:
+ num_voiced += self.history[i]
+ except IndexError:
+ continue
+
+ if not self.active:
+ if num_voiced >= 4:
+ sys.stdout.write('+')
+ self.active = True
+ break
+ elif len(self.history) == self.history.maxlen and sum(self.history) == 0:
+ for _ in range(self.history.maxlen / 2):
+ self.history.popleft()
+
+ else:
+ if num_voiced < 1:
+ sys.stdout.write('-')
+ self.active = False
+ elif sum(self.history) > self.history.maxlen * 0.9:
+ for _ in range(int(self.history.maxlen / 2)):
+ self.history.popleft()
+
+ sys.stdout.flush()
+
+ return self.active
+
+ def reset(self):
+ self.data = b''
+ self.active = False
+ self.history.clear()
+
+
+vad = WebRTCVAD()
+
diff --git a/pool/shard009/Python/0085644_kubernetes_build.py b/pool/shard009/Python/0085644_kubernetes_build.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebc79151b94d527cf811c59a6294dda1f39b2f89
--- /dev/null
+++ b/pool/shard009/Python/0085644_kubernetes_build.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+
+# Copyright 2016 The Kubernetes 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.
+
+# Need to figure out why this only fails on travis
+# pylint: disable=bad-continuation
+
+"""Builds kubernetes with specified config"""
+
+import argparse
+import os
+import subprocess
+import sys
+
+
+def check(*cmd):
+ """Log and run the command, raising on errors."""
+ print >>sys.stderr, 'Run:', cmd
+ subprocess.check_call(cmd)
+
+
+def main(args):
+ """Build kubernetes."""
+ env = {}
+ if args.kops:
+ env['GCS_LOCATION'] = args.kops
+ if args.unstable:
+ env['DEB_CHANNEL'] = 'unstable'
+ if args.suffix:
+ env['KUBE_GCS_RELEASE_SUFFIX'] = args.suffix
+ env['KUBE_FASTBUILD'] = 'true' if args.fast else 'false'
+ if args.federation:
+ env['PROJECT'] = args.federation
+ env['FEDERATION'] = 'true'
+ env['FEDERATION_PUSH_REPO_BASE'] = 'gcr.io/%s' % args.federation
+ if args.release:
+ env['KUBE_GCS_RELEASE_BUCKET'] = args.release
+ env['KUBE_GCS_RELEASE_BUCKET_MIRROR'] = args.release
+
+
+ for key, value in env.items():
+ os.environ[key] = value
+
+ if args.script == 'make gcs-publish-ci':
+ # TODO(fejta): fix this hack
+ check('make', 'gcs-publish-ci')
+ else:
+ check(args.script)
+
+
+if __name__ == '__main__':
+ PARSER = argparse.ArgumentParser(
+ 'Runs verification checks on the kubernetes repo')
+ PARSER.add_argument(
+ '--script',
+ default='./hack/jenkins/build.sh',
+ help='Script relative to repo which builds')
+ PARSER.add_argument('--fast', action='store_true', help='Build quickly')
+ PARSER.add_argument(
+ '--release', help='Upload binaries to the specified gs:// path')
+ PARSER.add_argument(
+ '--suffix', help='Append suffix to the upload path if set')
+ PARSER.add_argument(
+ '--unstable',
+ action='store_true',
+ help='Use the unstable debian channel')
+ PARSER.add_argument(
+ '--federation',
+ help='Push federation images to the specified project')
+ PARSER.add_argument(
+ '--kops', help='Upload kops to the specified gs:// path')
+ ARGS = PARSER.parse_args()
+ main(ARGS)
diff --git a/pool/shard009/Python/0085645_sphdist.py b/pool/shard009/Python/0085645_sphdist.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ad2c623040b0057d50c62f396c2a578d5f2bc1f
--- /dev/null
+++ b/pool/shard009/Python/0085645_sphdist.py
@@ -0,0 +1,27 @@
+from numpy import deg2rad,rad2deg,sin,cos,sqrt,arcsin
+
+def sphdist (ra1, dec1, ra2, dec2):
+ """measures the spherical distance in degrees
+ The input has to be in degrees too
+ """
+ dec1_r = deg2rad(dec1)
+ dec2_r = deg2rad(dec2)
+ return 2 *\
+ rad2deg \
+ (
+ arcsin
+ (
+ sqrt
+ (
+ (
+ sin((dec1_r - dec2_r) / 2)
+ )**2
+ +
+ cos(dec1_r) * cos(dec2_r) *
+ (
+ sin((deg2rad(ra1 - ra2)) / 2)
+ )**2
+ )
+ )
+ )
+
diff --git a/pool/shard009/Python/0085646_virtual_bot.py b/pool/shard009/Python/0085646_virtual_bot.py
new file mode 100644
index 0000000000000000000000000000000000000000..805c558e3fb23c9b9dec58e7595868ebedf6e4ef
--- /dev/null
+++ b/pool/shard009/Python/0085646_virtual_bot.py
@@ -0,0 +1,149 @@
+from basestation.bot.connection.tcp_connection import TCPConnection
+from basestation.bot.sensors.sensor_center import SensorCenter
+from basestation.bot.commands.command_center import CommandCenter
+from basestation.util.exception_handling import *
+import basestation.bot.bot_exchange as bot_exchange
+
+import threading
+
+
+class VirtualBot(object):
+ """
+ An instance of VirtualBot represents any MiniBot. We assume vbots may
+ present information and receive information, so this is separated into
+ the CommandCenter and SensorCenter. VirtualBots also have a persistent
+ connection which is represented by Connection
+ """
+
+ def __init__(self, vbot_name: str, ip: str, port: int = 10000):
+ """
+ Sets up an instance of the VirtualBot using a TCP Connection.
+
+ Args:
+ vbot_name (str): The name of the MiniBot.
+ ip (str): The IP of the MiniBot.
+ port (int, optional): The port to establish the TCP connection on.
+ Default=10000.
+ """
+ self.__tcp_connection = TCPConnection(ip, port=port)
+ self.__name = vbot_name
+
+ self.__command_center_obj = CommandCenter(self.__tcp_connection)
+ self.__sensor_center_obj = SensorCenter()
+
+ self.__tcp_listener_thread = self.TCPListener(self.__tcp_connection)
+ self.__tcp_listener_thread.start()
+
+ return
+
+ def __del__(self):
+ """
+ Destructor for a VirtualBot object. Automatically called when
+ destroying a VirtualBot object.
+
+ Examples:
+ `del `
+ """
+ self.__tcp_connection.destroy()
+ return
+
+ def get_command_center(self) -> CommandCenter:
+ """
+ Returns:
+ (CommandCenter): The Command Center associated with this
+ VirtualBot.
+ """
+ return self.__command_center_obj
+
+ def get_sensor_center(self) -> SensorCenter:
+ """
+ Returns:
+ (SensorCenter): The Sensor Center associated with this VirtualBot.
+ """
+ return self.__sensor_center_obj
+
+ def get_name(self) -> str:
+ """
+ Returns:
+ (str): The name of this VirtualBot
+ """
+ return self.__name
+
+ def is_bot_connection_active(self) -> bool:
+ """
+ Returns:
+ (bool): True if the TCP connection associated with this
+ VirtualBot is active. False otherwise
+ """
+ return self.__tcp_connection.is_connection_active()
+
+ class TCPListener(threading.Thread):
+
+ def __init__(self, t):
+ """
+ Create a TCPListener object using `t`'s TCP properties,
+ and listens forever on a thread.
+
+ Args:
+ t (TCPConnection): Object of the TCP Connection to associate
+ this listener with.
+ """
+ super().__init__()
+ self.tcp_connection_obj = t
+
+ def run(self):
+ """
+ Run the TCP listener on a thread, parse and act on incoming
+ information from the MiniBots.
+ """
+ try:
+ while True:
+ if self.tcp_connection_obj.is_connection_active():
+ msg = self.tcp_connection_obj.receive()
+ if msg is not None:
+ self.__tcp_parse_incoming(msg)
+
+ except RuntimeError as e:
+ msg = "TCP receive failed."
+ log_exn_info(e, msg=msg)
+
+ def __tcp_parse_incoming(self, data: str):
+ """
+ Breaks the data into key and value; calls
+ `self.__tcp_act_on_incoming(...)` to act on the information
+ received..
+
+ Precondition: `data is not None`
+
+ Args:
+ data (str): A string to be parsed. Must start with* "<<<<" and
+ end with ">>>>". Key-value pair should be separated by ":"
+ """
+ start = data.find("<<<<")
+ comma = data.find(",")
+ end = data.find(">>>>")
+ if start != -1 and comma != -1 and end != -1:
+ key = data[start + 4:comma]
+ value = data[comma + 1:end]
+ self.__tcp_act_on_incoming(key, value)
+
+ return
+
+ def __tcp_act_on_incoming(self, key: str, value: str):
+ """
+ Acts based on key and value, MiniBot sending information should send
+ key and value, MiniBot requesting information should only send key.
+
+ Args:
+ key (str): An instruction to be executed.
+ value (str): Should qualify the `key`.
+ """
+ if len(value) != 0:
+ # MiniBot requesting information
+ value_to_send = bot_exchange.msg_map.get(key, None)
+ self.tcp_connection_obj.sendKV(key, value_to_send)
+ else:
+ # MiniBot sending information
+ bot_exchange.msg_map[key] = value
+
+ return
diff --git a/pool/shard009/Python/0085649_post_save.py b/pool/shard009/Python/0085649_post_save.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a367cd7c3aef001948295974d4abdc94f54c116
--- /dev/null
+++ b/pool/shard009/Python/0085649_post_save.py
@@ -0,0 +1,18 @@
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+
+from posts.models import Post
+from tags.models import Tag
+
+
+@receiver(post_save, sender=Post)
+def post_save_post_tags(sender, instance, created, **kwargs):
+ from tags.utils.tagify import get_tag_list
+
+ tag_list = get_tag_list(instance.content)
+
+ for tag_name in tag_list:
+ tag, is_tag_created = Tag.objects.get_or_create(
+ name=tag_name,
+ )
+ instance.tag_set.add(tag)
diff --git a/pool/shard009/Python/0085652_rigid_body_cloth_coupling.py b/pool/shard009/Python/0085652_rigid_body_cloth_coupling.py
new file mode 100644
index 0000000000000000000000000000000000000000..3555b15807300e79fd4ab74690454aed587ddd67
--- /dev/null
+++ b/pool/shard009/Python/0085652_rigid_body_cloth_coupling.py
@@ -0,0 +1,265 @@
+import pygame
+from pygame.locals import *
+
+from OpenGL.GL import *
+from OpenGL.GLU import *
+
+from math_tools import *
+from render_tools import *
+
+import pypbd as pbd
+import numpy as np
+
+nRows = 30
+nCols = 30
+clothWidth = 10.0
+clothHeight = 10.0
+width = 0.2
+height = 2.0
+depth = 0.2
+
+def buildModel():
+ sim = pbd.Simulation.getCurrent()
+
+ # Init simulation and collision detection with standard settings
+ sim.initDefault()
+ model = sim.getModel()
+
+ # 1 = distance constraints (PBD)
+ # 2 = FEM triangle constraints (PBD)
+ # 3 = strain triangle constraints (PBD)
+ # 4 = distance constraints (XPBD)
+ simModel = 2
+
+ # 1 = dihedral angle (PBD)
+ # 2 = isometric bending (PBD)
+ # 3 = isometric bending (XPBD)
+ bendingModel = 2
+
+ # Create the mesh for the cloth model
+ createMesh(simModel, bendingModel)
+ # Create rigid bodies
+ createRigidBodyModel()
+
+ ts = sim.getTimeStep()
+ ts.setValueUInt(pbd.TimeStepController.NUM_SUB_STEPS, 3)
+
+
+# Create a particle model mesh
+def createMesh(simModel, bendingModel):
+ sim = pbd.Simulation.getCurrent()
+ model = sim.getModel()
+
+ # Generate a regular triangle model with nCols*nRows vertices
+ triModel = model.addRegularTriangleModel(nCols, nRows,
+ translation=[-5.0, 4.0, -5.0], # position
+ rotation=rotation_matrix(math.pi*0.5, [1.0, 0.0, 0.0]), # rotation matrix
+ scale=[clothWidth, clothHeight], # scaling
+ testMesh=False) # test mesh vertices against other signed distance fields
+
+ # init constraints
+ stiffness = 1.0
+ if (simModel == 4):
+ stiffness = 100000
+ poissonRatio = 0.3
+
+ # Generate a default set of constraints for the cloth model to simulate stretching and shearing resistance
+ # simModel:
+ # 1 = distance constraints (PBD)
+ # 2 = FEM triangle constraints (PBD)
+ # 3 = strain triangle constraints (PBD)
+ # 4 = distance constraints (XPBD)
+ model.addClothConstraints(triModel, simModel, stiffness, stiffness, stiffness, stiffness,
+ poissonRatio, poissonRatio, False, False)
+
+ bending_stiffness = 0.01
+ if (bendingModel == 3):
+ bending_stiffness = 50.0
+
+ # Generate a default set of bending constraints for the cloth model
+ # bendingModel:
+ # 1 = dihedral angle (PBD)
+ # 2 = isometric bending (PBD)
+ # 3 = isometric bending (XPBD)
+ model.addBendingConstraints(triModel, bendingModel, bending_stiffness)
+
+ print("Number of triangles: " + str(triModel.getParticleMesh().numFaces()))
+ print("Number of vertices: " + str(nRows*nCols))
+
+
+def createRigidBodyModel():
+ sim = pbd.Simulation.getCurrent()
+ model = sim.getModel()
+ rb = model.getRigidBodies()
+
+ # Load geometry from OBJ files
+ fileName = "../../data/models/cube.obj"
+ (vd, mesh) = pbd.OBJLoader.loadObjToMesh(fileName, [width, height, depth])
+ (vd_static, mesh_static) = pbd.OBJLoader.loadObjToMesh(fileName, [0.5, 0.5, 0.5])
+
+ # -5, -5
+ body = model.addRigidBody(1.0, # density
+ vd_static, mesh_static, # vertices, mesh
+ translation=[-5.0, 0.0, -5.0], # position
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+ body.setMass(0.0)
+
+ # dynamic body
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [-5.0, 1.0, -5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [-5.0, 3.0, -5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ model.addBallJoint(0, 1, [-5.0, 0.0, -5.0])
+ model.addBallJoint(1, 2, [-5.0, 2.0, -5.0])
+
+ # 5, -5
+ body = model.addRigidBody(1.0, # density
+ vd_static, mesh_static, # vertices, mesh
+ [5.0, 0.0, -5.0], # position
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+ body.setMass(0.0)
+
+ # dynamic body
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [5.0, 1.0, -5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [5.0, 3.0, -5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ model.addBallJoint(3, 4, [5.0, 0.0, -5.0])
+ model.addBallJoint(4, 5, [5.0, 2.0, -5.0])
+
+ # 5, 5
+ body = model.addRigidBody(1.0, # density
+ vd_static, mesh_static, # vertices, mesh
+ [5.0, 0.0, 5.0], # position
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+ body.setMass(0.0)
+
+ # dynamic body
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [5.0, 1.0, 5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [5.0, 3.0, 5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ model.addBallJoint(6, 7, [5.0, 0.0, 5.0])
+ model.addBallJoint(7, 8, [5.0, 2.0, 5.0])
+
+ # -5, 5
+ body = model.addRigidBody(1.0, # density
+ vd_static, mesh_static, # vertices, mesh
+ [-5.0, 0.0, 5.0], # position
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+ body.setMass(0.0)
+
+ # dynamic body
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [-5.0, 1.0, 5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ body = model.addRigidBody(1.0,
+ vd, mesh,
+ [-5.0, 3.0, 5.0],
+ testMesh=False, # no collision handling
+ generateCollisionObject=False)
+
+ model.addBallJoint(9, 10, [-5.0, 0.0, 5.0])
+ model.addBallJoint(10, 11, [-5.0, 2.0, 5.0])
+
+ model.addRigidBodyParticleBallJoint(2, 0)
+ model.addRigidBodyParticleBallJoint(5, nCols - 1)
+ model.addRigidBodyParticleBallJoint(8, nRows*nCols - 1)
+ model.addRigidBodyParticleBallJoint(11, (nRows-1)*nCols)
+
+def render():
+ sim = pbd.Simulation.getCurrent()
+ model = sim.getModel()
+ pd = model.getParticles()
+ triModel = model.getTriangleModels()[0]
+ offset = triModel.getIndexOffset()
+ drawMesh(pd, triModel.getParticleMesh(), offset, [0,0.3,0.8])
+
+ rbs = model.getRigidBodies()
+ for rb in rbs:
+ vd = rb.getGeometry().getVertexData()
+ mesh = rb.getGeometry().getMesh()
+ drawMesh(vd, mesh, 0, [0.5,0.5,0.5])
+
+ glPushMatrix()
+ glLoadIdentity()
+ drawText([-0.95,0.9], "Time: {:.2f}".format(pbd.TimeManager.getCurrent().getTime()))
+ glPopMatrix()
+
+def timeStep():
+ sim = pbd.Simulation.getCurrent()
+ model = sim.getModel()
+ for i in range(8):
+ sim.getTimeStep().step(model)
+
+ for triModel in model.getTriangleModels():
+ triModel.updateMeshNormals(model.getParticles())
+
+def reset():
+ pbd.Simulation.getCurrent().reset()
+ pbd.Simulation.getCurrent().getModel().cleanup()
+ buildModel()
+
+def main():
+ pbd.Logger.addConsoleSink(pbd.LogLevel.INFO)
+
+ initGL(1280, 1024)
+ #initLights()
+ gluLookAt (0, 10, -30, 0, 0, 0, 0, 1, 0)
+ glRotatef(20.0, 0, 1, 0)
+
+ buildModel()
+
+ running = True
+ while running:
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ running = False
+ if event.type == pygame.KEYDOWN:
+ if event.key == pygame.K_r:
+ reset()
+ if event.key == pygame.K_ESCAPE:
+ running = False
+
+ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
+ glClearColor(0.3, 0.3, 0.3, 1.0)
+ timeStep()
+ render()
+ pygame.display.flip()
+
+ pygame.quit()
+ pbd.Timing.printAverageTimes()
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/pool/shard009/Python/0085655_cache_test.py b/pool/shard009/Python/0085655_cache_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..c91614415db5b0895cf36f891afc7bde8cd894d4
--- /dev/null
+++ b/pool/shard009/Python/0085655_cache_test.py
@@ -0,0 +1,32 @@
+from dogpile.cache import make_region
+from dogpile.cache.proxy import ProxyBackend
+
+import logging
+log = logging.getLogger(__name__)
+
+class LoggingProxy(ProxyBackend):
+ def set(self, key, value):
+ log.debug('setting cache key: %s' % key)
+ print 'setting cache key: %s' % key
+ self.proxied.set(key, value)
+
+ def get(self, key):
+ log.debug('getting cache key: %s' % key)
+ print 'getting cache key: %s' % key
+ return self.proxied.get(key)
+
+region = make_region().configure(
+ 'dogpile.cache.memory',
+ expiration_time = 3600, wrap = [LoggingProxy])
+
+@region.cache_on_arguments()
+def add(a):
+ return a+2
+
+print add(3)
+for i in [1,2,3]:
+ print add(3)
+import pdb; pdb.set_trace()
+region.invalidate()
+print "invalidated"
+print add(3)
diff --git a/pool/shard009/Python/0085657_Utilities.py b/pool/shard009/Python/0085657_Utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..9226edc91113f20b63f14efdf2da9c6881ccd659
--- /dev/null
+++ b/pool/shard009/Python/0085657_Utilities.py
@@ -0,0 +1,105 @@
+########################################################################
+# $HeadURL$
+########################################################################
+
+""" DIRAC FileCatalog client utilities
+"""
+
+__RCSID__ = "$Id$"
+
+import os
+import errno
+import functools
+
+from DIRAC import S_OK, S_ERROR
+
+def checkArgumentFormat( path, generateMap = False ):
+ """ Bring the various possible form of arguments to FileCatalog methods to
+ the standard dictionary form
+ """
+
+ def checkArgumentDict( path ):
+ """ Check and process format of the arguments to FileCatalog methods """
+ if isinstance( path, basestring ):
+ urls = {path:True}
+ elif isinstance( path, list ):
+ urls = {}
+ for url in path:
+ urls[url] = True
+ elif isinstance( path, dict ):
+ urls = path
+ else:
+ return S_ERROR( errno.EINVAL, "Utils.checkArgumentFormat: Supplied path is not of the correct format." )
+ return S_OK( urls )
+
+ if not path:
+ return S_ERROR( errno.EINVAL, 'Empty input: %s' % str( path ) )
+
+ result = checkArgumentDict( path )
+ if not result['OK']:
+ return result
+
+ pathDict = result['Value']
+
+ # Bring the lfn path to the normalized form
+ urls = {}
+ urlMap = {}
+ for url in pathDict:
+ # avoid empty path...
+ if not url:
+ continue
+ mUrl = url
+ if url.lower().startswith( 'lfn:' ):
+ mUrl = url[4:]
+ # Strip off the leading /grid prefix as required for the LFC
+ if mUrl.startswith('/grid/'):
+ uList = mUrl.split('/')
+ uList.pop( 1 )
+ mUrl = '/'.join( uList )
+ normPath = os.path.normpath( mUrl )
+ urls[normPath] = pathDict[url]
+ if normPath != url:
+ urlMap[normPath] = url
+ if generateMap:
+ return S_OK( ( urls, urlMap ) )
+ else:
+ return S_OK( urls )
+
+def checkCatalogArguments( f ):
+ """ Decorator to check arguments of FileCatalog calls in the clients
+ """
+ @functools.wraps(f)
+ def processWithCheckingArguments(*args, **kwargs):
+
+ checkFlag = kwargs.pop( 'LFNChecking', True )
+ if checkFlag:
+ argList = list( args )
+ lfnArgument = argList[1]
+ result = checkArgumentFormat( lfnArgument, generateMap = True )
+ if not result['OK']:
+ return result
+ checkedLFNDict, lfnMap = result['Value']
+ argList[1] = checkedLFNDict
+ argTuple = tuple( argList )
+ else:
+ argTuple = args
+ result = f(*argTuple, **kwargs)
+ if not result['OK']:
+ return result
+
+ if not checkFlag:
+ return result
+
+ # Restore original paths
+ argList[1] = lfnArgument
+ failed = {}
+ successful = {}
+ for lfn in result['Value']['Failed']:
+ failed[lfnMap.get( lfn, lfn )] = result['Value']['Failed'][lfn]
+ for lfn in result['Value']['Successful']:
+ successful[lfnMap.get( lfn, lfn )] = result['Value']['Successful'][lfn]
+
+ result['Value'].update( { "Successful": successful, "Failed": failed } )
+ return result
+
+ return processWithCheckingArguments
diff --git a/pool/shard009/Python/0085658_formfields.py b/pool/shard009/Python/0085658_formfields.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e568c2e63dac52ae5fdfac996e38edf03f88a73
--- /dev/null
+++ b/pool/shard009/Python/0085658_formfields.py
@@ -0,0 +1,26 @@
+from netaddr import EUI, AddrFormatError
+
+from django import forms
+from django.core.exceptions import ValidationError
+
+
+#
+# Form fields
+#
+
+class MACAddressFormField(forms.Field):
+ default_error_messages = {
+ 'invalid': "Enter a valid MAC address.",
+ }
+
+ def to_python(self, value):
+ if not value:
+ return None
+
+ if isinstance(value, EUI):
+ return value
+
+ try:
+ return EUI(value, version=48)
+ except AddrFormatError:
+ raise ValidationError("Please specify a valid MAC address.")
diff --git a/pool/shard009/Python/0085661_main.py b/pool/shard009/Python/0085661_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cb265d8fab6f42013d076abde61b27f4e834c14
--- /dev/null
+++ b/pool/shard009/Python/0085661_main.py
@@ -0,0 +1,45 @@
+"""
+Copyright (c) Jupyter Development Team.
+Distributed under the terms of the Modified BSD License.
+"""
+from notebook.notebookapp import NotebookApp
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from traitlets import Unicode
+
+
+HERE = os.path.dirname(__file__)
+LOADER = FileSystemLoader(HERE)
+
+
+class ExampleHander(IPythonHandler):
+ """Handle requests between the main app page and notebook server."""
+
+ def get(self):
+ """Get the main page for the application's interface."""
+ return self.write(self.render_template("index.html",
+ static=self.static_url, base_url=self.base_url,
+ token=self.settings['token']))
+
+ def get_template(self, name):
+ return LOADER.load(self.settings['jinja2_env'], name)
+
+
+class ExampleApp(NotebookApp):
+ """A notebook app that runs the example."""
+
+ default_url = Unicode('/example')
+
+ def start(self):
+ handlers = [
+ (r'/example/?', ExampleHander),
+ (r"/example/(.*)", FileFindHandler,
+ {'path': HERE}),
+ ]
+ self.web_app.add_handlers(".*$", handlers)
+ super(ExampleApp, self).start()
+
+
+if __name__ == '__main__':
+ ExampleApp.launch_instance()
diff --git a/pool/shard009/Python/0085662_uo_20030109.py b/pool/shard009/Python/0085662_uo_20030109.py
new file mode 100644
index 0000000000000000000000000000000000000000..22bc1eb3b124cae4fc997e98cb6df19c4afb71ea
--- /dev/null
+++ b/pool/shard009/Python/0085662_uo_20030109.py
@@ -0,0 +1,30 @@
+from Xml.Xslt import test_harness
+
+sheet_1 = """
+
+
+
+
+
+
+
+
+
+"""
+
+expected = "\nHELLO WORLD"
+
+from Ft.Lib import Uri
+INC_PATH = Uri.OsPathToUri('Xml/Xslt/Borrowed/etc/', attemptAbsolute=1)
+
+def Test(tester):
+ source = test_harness.FileInfo(string="")
+ sheet = test_harness.FileInfo(string=sheet_1)
+ test_harness.XsltTest(tester, source, [sheet], expected,
+ stylesheetAltUris=[INC_PATH],
+ title='EXSLT functions defined in imported script')
+ return
diff --git a/pool/shard009/Python/0085665_export_course.py b/pool/shard009/Python/0085665_export_course.py
new file mode 100644
index 0000000000000000000000000000000000000000..090143c9d98811f4bbc88f480070cfc55af27ca0
--- /dev/null
+++ b/pool/shard009/Python/0085665_export_course.py
@@ -0,0 +1,96 @@
+"""
+A Django command that exports a course to a tar.gz file.
+
+If is '-', it pipes the file to stdout
+
+"""
+
+import os
+import shutil
+import tarfile
+from tempfile import mktemp, mkdtemp
+from textwrap import dedent
+
+from path import path
+
+from django.core.management.base import BaseCommand, CommandError
+
+from xmodule.modulestore.django import modulestore
+from xmodule.modulestore.xml_exporter import export_to_xml
+from opaque_keys import InvalidKeyError
+from xmodule.modulestore.locations import SlashSeparatedCourseKey
+
+
+class Command(BaseCommand):
+ """
+ Export a course to XML. The output is compressed as a tar.gz file
+
+ """
+ args = " "
+ help = dedent(__doc__).strip()
+
+ def handle(self, *args, **options):
+ course_id, filename, pipe_results = self._parse_arguments(args)
+
+ export_course_to_tarfile(course_id, filename)
+
+ results = self._get_results(filename) if pipe_results else None
+
+ return results
+
+ def _parse_arguments(self, args):
+ """Parse command line arguments"""
+ try:
+ course_id = SlashSeparatedCourseKey.from_deprecated_string(args[0])
+ filename = args[1]
+ except InvalidKeyError:
+ raise CommandError("Unparsable course_id")
+ except IndexError:
+ raise CommandError("Insufficient arguments")
+
+ # If filename is '-' save to a temp file
+ pipe_results = False
+ if filename == '-':
+ filename = mktemp()
+ pipe_results = True
+
+ return course_id, filename, pipe_results
+
+ def _get_results(self, filename):
+ """Load results from file"""
+ with open(filename) as f:
+ results = f.read()
+ os.remove(filename)
+ return results
+
+
+def export_course_to_tarfile(course_id, filename):
+ """Exports a course into a tar.gz file"""
+ tmp_dir = mkdtemp()
+ try:
+ course_dir = export_course_to_directory(course_id, tmp_dir)
+ compress_directory(course_dir, filename)
+ finally:
+ shutil.rmtree(tmp_dir)
+
+
+def export_course_to_directory(course_id, root_dir):
+ """Export course into a directory"""
+ store = modulestore()
+ course = store.get_course(course_id)
+ if course is None:
+ raise CommandError("Invalid course_id")
+
+ course_name = course.id.to_deprecated_string().replace('/', '-')
+ export_to_xml(store, None, course.id, root_dir, course_name)
+
+ course_dir = path(root_dir) / course_name
+ return course_dir
+
+
+def compress_directory(directory, filename):
+ """Compress a directrory into a tar.gz file"""
+ mode = 'w:gz'
+ name = path(directory).name
+ with tarfile.open(filename, mode) as tar_file:
+ tar_file.add(directory, arcname=name)
diff --git a/pool/shard009/Python/0085666_external_process.py b/pool/shard009/Python/0085666_external_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..b96956c5d07975820a67105c6665da22f2aa1286
--- /dev/null
+++ b/pool/shard009/Python/0085666_external_process.py
@@ -0,0 +1,112 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+#
+# Copyright 2012 New Dream Network, LLC (DreamHost)
+#
+# 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.
+#
+# @author: Mark McClain, DreamHost
+
+import os
+import tempfile
+
+from quantum.agent.linux import ip_lib
+from quantum.agent.linux import utils
+from quantum.openstack.common import cfg
+from quantum.openstack.common import log as logging
+
+LOG = logging.getLogger(__name__)
+
+OPTS = [
+ cfg.StrOpt('external_pids',
+ default='$state_path/external/pids',
+ help='Location to store child pid files'),
+]
+
+cfg.CONF.register_opts(OPTS)
+
+
+class ProcessManager(object):
+ """An external process manager for Quantum spawned processes.
+
+ Note: The manager expects uuid to be in cmdline.
+ """
+ def __init__(self, conf, uuid, root_helper='sudo', namespace=None):
+ self.conf = conf
+ self.uuid = uuid
+ self.root_helper = root_helper
+ self.namespace = namespace
+
+ def enable(self, cmd_callback):
+ if not self.active:
+ cmd = cmd_callback(self.get_pid_file_name(ensure_pids_dir=True))
+
+ if self.namespace:
+ ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
+ ip_wrapper.netns.execute(cmd)
+ else:
+ # For normal sudo prepend the env vars before command
+ utils.execute(cmd, self.root_helper)
+
+ def disable(self):
+ pid = self.pid
+
+ if self.active:
+ cmd = ['kill', '-9', pid]
+ if self.namespace:
+ ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace)
+ ip_wrapper.netns.execute(cmd)
+ else:
+ utils.execute(cmd, self.root_helper)
+
+ elif pid:
+ LOG.debug(_('Process for %(uuid)s pid %(pid)d is stale, ignoring '
+ 'command') % {'uuid': self.uuid, 'pid': pid})
+ else:
+ LOG.debug(_('No process started for %s') % self.uuid)
+
+ def get_pid_file_name(self, ensure_pids_dir=False):
+ """Returns the file name for a given kind of config file."""
+ pids_dir = os.path.abspath(os.path.normpath(self.conf.external_pids))
+ if ensure_pids_dir and not os.path.isdir(pids_dir):
+ os.makedirs(pids_dir, 0755)
+
+ return os.path.join(pids_dir, self.uuid + '.pid')
+
+ @property
+ def pid(self):
+ """Last known pid for this external process spawned for this uuid."""
+ file_name = self.get_pid_file_name()
+ msg = _('Error while reading %s')
+
+ try:
+ with open(file_name, 'r') as f:
+ return int(f.read())
+ except IOError, e:
+ msg = _('Unable to access %s')
+ except ValueError, e:
+ msg = _('Unable to convert value in %s')
+
+ LOG.debug(msg % file_name)
+ return None
+
+ @property
+ def active(self):
+ pid = self.pid
+ if pid is None:
+ return False
+
+ cmd = ['cat', '/proc/%s/cmdline' % pid]
+ try:
+ return self.uuid in utils.execute(cmd, self.root_helper)
+ except RuntimeError, e:
+ return False
diff --git a/pool/shard009/Python/0085669_PyVennerable.py b/pool/shard009/Python/0085669_PyVennerable.py
new file mode 100644
index 0000000000000000000000000000000000000000..76d603b7638e8491716c87d0e3fe643e0d576a06
--- /dev/null
+++ b/pool/shard009/Python/0085669_PyVennerable.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+
+import itertools
+import rpy2.robjects as ro
+import sys
+
+try:
+ ro.r(r"library('Vennerable')")
+except RRuntimeError:
+ print "Unable to load Vennerable in R, make sure it's properly installed"
+ sys.exit(1)
+
+
+def makeSubsets(S):
+ '''
+ Arguments:
+ S - List of sets to make in to a Venn diagram
+ Takes a list of sets a list of the sizes of non-overlapping intersections between them
+ '''
+
+ if any([type(s) != set for s in S]):
+ raise TypeError("Arguments must be a list of sets")
+
+ N = len(S)
+
+ # Generate a truth table of intersections to calculate
+ truth_table = [x for x in itertools.product("01", repeat=N)][1:]
+
+
+ weights = {}
+ for t in truth_table:
+ ones = [S[i] for i in range(N) if t[i] =='1']
+ zeros = [S[i] for i in range(N) if t[i] =='0']
+
+ X = set.intersection(*ones)
+ X.difference_update(*zeros)
+
+ weights[''.join(t)] = len(X)
+
+ return(weights)
+
+
+def Venn(S, labels, r_name = 'x', venn_kwargs = {}, plot_kwargs = {}):
+ '''
+ Arguments:
+ S - List of sets to make in to a Venn diagram
+ labels - List of names of the sets
+ r_name - R object name to save Venn diagram to
+ venn_kwargs - Dict of args passed directly to Vennerable.Venn()
+ plot_kwargs - Dict of args passed directly to plot()
+
+ '''
+
+ assert len(S) == len(labels), "Number of labels must match number of sets"
+
+ weights = makeSubsets(S)
+ weight_string = "c(" + ", ".join(["\'" + k + "\'=" + str(v) for k,v in weights.items() ]) + ")"
+
+ ven_kw = ", ".join([k + " = " + v for k,v in venn_kwargs.items()])
+ plot_kw = ", ".join([k + " = " + v for k,v in plot_kwargs.items()])
+
+ lab = "c(\'" + "\', \'".join(labels) + "\')"
+ call = r_name + " = " + "Venn(" + "Weight = " + weight_string + ", SetNames = " + lab + ", " + ven_kw + ")"
+ print call
+ ro.r(call)
+ ro.r("plot(" + r_name + "," + plot_kw + ")")
+
+
+
diff --git a/pool/shard009/Python/0085670_zun_service.py b/pool/shard009/Python/0085670_zun_service.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c76df19054158d02fd2768944f588bf6ab0d35d
--- /dev/null
+++ b/pool/shard009/Python/0085670_zun_service.py
@@ -0,0 +1,172 @@
+# 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 oslo_versionedobjects import fields
+
+from zun.db import api as dbapi
+from zun.objects import base
+
+
+@base.ZunObjectRegistry.register
+class ZunService(base.ZunPersistentObject, base.ZunObject):
+
+ # Version 1.0: Initial version
+ # Version 1.1: Add update method
+ VERSION = '1.1'
+
+ fields = {
+ 'id': fields.IntegerField(),
+ 'host': fields.StringField(nullable=True),
+ 'binary': fields.StringField(nullable=True),
+ 'disabled': fields.BooleanField(),
+ 'disabled_reason': fields.StringField(nullable=True),
+ 'last_seen_up': fields.DateTimeField(nullable=True),
+ 'forced_down': fields.BooleanField(),
+ 'report_count': fields.IntegerField(),
+ }
+
+ @staticmethod
+ def _from_db_object(zun_service, db_zun_service):
+ """Converts a database entity to a formal object."""
+ for field in zun_service.fields:
+ setattr(zun_service, field, db_zun_service[field])
+
+ zun_service.obj_reset_changes()
+ return zun_service
+
+ @staticmethod
+ def _from_db_object_list(db_objects, cls, context):
+ """Converts a list of database entities to a list of formal objects."""
+ return [ZunService._from_db_object(cls(context), obj)
+ for obj in db_objects]
+
+ @base.remotable_classmethod
+ def get_by_host_and_binary(cls, context, host, binary):
+ """Find a zun_service based on its hostname and binary.
+
+ :param host: The host on which the binary is running.
+ :param binary: The name of the binary.
+ :param context: Security context.
+ :returns: a :class:`ZunService` object.
+ """
+ db_zun_service = dbapi.get_zun_service(
+ context, host, binary)
+ if db_zun_service is None:
+ return None
+ zun_service = ZunService._from_db_object(
+ cls(context), db_zun_service)
+ return zun_service
+
+ @base.remotable_classmethod
+ def list(cls, context, limit=None, marker=None,
+ sort_key=None, sort_dir=None):
+ """Return a list of ZunService objects.
+
+ :param context: Security context.
+ :param limit: maximum number of resources to return in a single result.
+ :param marker: pagination marker for large data sets.
+ :param sort_key: column to sort results by.
+ :param sort_dir: direction to sort. "asc" or "desc".
+ :returns: a list of :class:`ZunService` object.
+
+ """
+ db_zun_services = dbapi.list_zun_services(
+ context, limit=limit, marker=marker, sort_key=sort_key,
+ sort_dir=sort_dir)
+ return ZunService._from_db_object_list(db_zun_services, cls,
+ context)
+
+ @base.remotable_classmethod
+ def list_by_binary(cls, context, binary):
+ db_zun_services = dbapi.list_zun_services_by_binary(
+ context, binary)
+ return ZunService._from_db_object_list(db_zun_services, cls, context)
+
+ @base.remotable
+ def create(self, context=None):
+ """Create a ZunService record in the DB.
+
+ :param context: Security context. NOTE: This should only
+ be used internally by the indirection_api.
+ Unfortunately, RPC requires context as the first
+ argument, even though we don't use it.
+ A context should be set when instantiating the
+ object, e.g.: ZunService(context)
+ """
+ values = self.obj_get_changes()
+ db_zun_service = dbapi.create_zun_service(values)
+ self._from_db_object(self, db_zun_service)
+
+ @base.remotable
+ def destroy(self, context=None):
+ """Delete the ZunService from the DB.
+
+ :param context: Security context. NOTE: This should only
+ be used internally by the indirection_api.
+ Unfortunately, RPC requires context as the first
+ argument, even though we don't use it.
+ A context should be set when instantiating the
+ object, e.g.: ZunService(context)
+ """
+ dbapi.destroy_zun_service(self.host, self.binary)
+ self.obj_reset_changes()
+
+ @base.remotable
+ def save(self, context=None):
+ """Save updates to this ZunService.
+
+ Updates will be made column by column based on the result
+ of self.what_changed().
+
+ :param context: Security context. NOTE: This should only
+ be used internally by the indirection_api.
+ Unfortunately, RPC requires context as the first
+ argument, even though we don't use it.
+ A context should be set when instantiating the
+ object, e.g.: ZunService(context)
+ """
+ updates = self.obj_get_changes()
+ dbapi.update_zun_service(self.host, self.binary, updates)
+ self.obj_reset_changes()
+
+ @base.remotable
+ def report_state_up(self, context=None):
+ """Touching the zun_service record to show aliveness.
+
+ :param context: Security context. NOTE: This should only
+ be used internally by the indirection_api.
+ Unfortunately, RPC requires context as the first
+ argument, even though we don't use it.
+ A context should be set when instantiating the
+ object, e.g.: ZunService(context)
+ """
+ self.report_count += 1
+ self.save()
+
+ @base.remotable
+ def update(self, context, kwargs):
+ """Update the ZunService, then save it.
+
+ :param context: Security context. NOTE: This should only
+ be used internally by the indirection_api.
+ Unfortunately, RPC requires context as the first
+ argument, even though we don't use it.
+ A context should be set when instantiating the
+ object, e.g.: ZunService(context)
+ """
+ if 'disabled' in kwargs:
+ self.disabled = kwargs['disabled']
+ if 'disabled_reason' in kwargs:
+ self.disabled_reason = kwargs['disabled_reason']
+ if 'forced_down' in kwargs:
+ self.forced_down = kwargs['forced_down']
+ self.save()
diff --git a/pool/shard009/Python/0085671_triples.py b/pool/shard009/Python/0085671_triples.py
new file mode 100644
index 0000000000000000000000000000000000000000..186ce28b4316093b23b294eb58456ec4a2d4cde2
--- /dev/null
+++ b/pool/shard009/Python/0085671_triples.py
@@ -0,0 +1,133 @@
+"""
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
+ This file is part of the Smart Developer Hub Project:
+ http://www.smartdeveloperhub.org
+
+ Center for Open Middleware
+ http://www.centeropenmiddleware.com/
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
+ Copyright (C) 2015 Center for Open Middleware.
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
+ 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 calendar
+import logging
+import shutil
+from datetime import datetime as dt
+
+import os
+import shortuuid
+from concurrent.futures import ThreadPoolExecutor
+from rdflib import ConjunctiveGraph, URIRef, Literal, XSD, BNode
+from sdh.curator.server import app
+from sdh.curator.store import r
+
+__author__ = 'Fernando Serena'
+
+log = logging.getLogger('sdh.curator.store.triples')
+pool = ThreadPoolExecutor(max_workers=4)
+
+
+def load_stream_triples(fid, until):
+ def __triplify(x):
+ def __term(elm):
+ if elm.startswith('<'):
+ return URIRef(elm.lstrip('<').rstrip('>'))
+ elif '^^' in elm:
+ (value, ty) = tuple(elm.split('^^'))
+ return Literal(value.replace('"', ''), datatype=URIRef(ty.lstrip('<').rstrip('>')))
+ elif elm.startswith('_:'):
+ return BNode(elm.replace('_:', ''))
+ else:
+ return Literal(elm.replace('"', ''), datatype=XSD.string)
+
+ c, s, p, o = eval(x)
+ return c, __term(s), __term(p), __term(o)
+
+ for x in r.zrangebyscore('fragments:{}:stream'.format(fid), '-inf', '{}'.format(float(until))):
+ yield __triplify(x)
+
+
+def add_stream_triple(fid, tp, (s, p, o), timestamp=None):
+ if timestamp is None:
+ timestamp = calendar.timegm(dt.utcnow().timetuple())
+ quad = (tp, s.n3(), p.n3(), o.n3())
+ stream_key = 'fragments:{}:stream'.format(fid)
+ not_found = not bool(r.zscore(stream_key, quad))
+ if not_found:
+ with r.pipeline() as pipe:
+ pipe.zadd(stream_key, timestamp, quad)
+ pipe.execute()
+ return not_found
+
+
+class GraphProvider(object):
+ def __init__(self):
+ self.__graph_dict = {}
+
+ @staticmethod
+ def __clean(name):
+ shutil.rmtree('store/query/{}'.format(name))
+
+ def create(self, conjunctive=False):
+ uuid = shortuuid.uuid()
+ if conjunctive:
+ if 'persist' in app.config['STORE']:
+ g = ConjunctiveGraph('Sleepycat')
+ g.open('store/query/{}'.format(uuid), create=True)
+ g.store.graph_aware = False
+ else:
+ g = ConjunctiveGraph()
+ g.store.graph_aware = False
+ else:
+ g = query.get_context(uuid)
+ self.__graph_dict[g] = uuid
+ return g
+
+ def destroy(self, g):
+ if g in self.__graph_dict:
+ if isinstance(g, ConjunctiveGraph):
+ if 'persist' in app.config['STORE']:
+ g.close()
+ pool.submit(self.__clean, self.__graph_dict[g])
+ else:
+ g.remove((None, None, None))
+ g.close()
+ else:
+ query.remove_context(query.get_context(self.__graph_dict[g]))
+ del self.__graph_dict[g]
+
+
+graph_provider = GraphProvider()
+store_mode = app.config['STORE']
+if 'persist' in store_mode:
+ if not os.path.exists('store'):
+ os.makedirs('store')
+ if os.path.exists('store/query'):
+ shutil.rmtree('store/query/')
+ if os.path.exists('store/tmp'):
+ shutil.rmtree('store/tmp')
+ os.makedirs('store/query')
+ log.info('Loading known triples...')
+ cache = ConjunctiveGraph('Sleepycat')
+ cache.open('store/cache', create=True)
+ query = ConjunctiveGraph('Sleepycat')
+ query.open('store/tmp', create=True)
+else:
+ cache = ConjunctiveGraph()
+ query = ConjunctiveGraph()
+
+cache.store.graph_aware = False
+query.store.graph_aware = False
diff --git a/pool/shard009/Python/0085674_test_node_group_operations.py b/pool/shard009/Python/0085674_test_node_group_operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ca0d80847d16efc73837554e39a67770a6416fc
--- /dev/null
+++ b/pool/shard009/Python/0085674_test_node_group_operations.py
@@ -0,0 +1,60 @@
+# -*- coding: utf-8 -*-
+# Copyright 2015 Mirantis, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, 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 functools
+
+from nailgun import consts
+from nailgun.test.base import EnvironmentManager
+from nailgun.test.performance import base
+
+
+class NodeGroupOperationsLoadTest(base.BaseUnitLoadTestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ super(NodeGroupOperationsLoadTest, cls).setUpClass()
+
+ cls.env = EnvironmentManager(app=cls.app, session=cls.db)
+ cls.env.upload_fixtures(cls.fixtures)
+ cls.cluster = cls.env.create_cluster(
+ api=False,
+ net_provider=consts.CLUSTER_NET_PROVIDERS.neutron,
+ net_segment_type=consts.NEUTRON_SEGMENT_TYPES.gre,
+ )
+ cls.group = cls.env.create_node_group()
+
+ cls.env.create_nodes(cls.NODES_NUM, cluster_id=cls.cluster['id'])
+
+ @base.evaluate_unit_performance
+ def test_node_group_collection_retrieve(self):
+ func = functools.partial(
+ self.get_handler,
+ 'NodeGroupCollectionHandler',
+ )
+
+ self.check_time_exec(func)
+
+ @base.evaluate_unit_performance
+ def test_node_group_collection_create(self):
+ func = functools.partial(
+ self.post_handler,
+ 'NodeGroupCollectionHandler',
+ {
+ 'cluster_id': self.cluster.id,
+ 'name': 'test_group',
+ }
+ )
+
+ self.check_time_exec(func)
diff --git a/pool/shard009/Python/0085675_test_config.py b/pool/shard009/Python/0085675_test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..67457af85ae46b83fd799a701cb014330a0c4a83
--- /dev/null
+++ b/pool/shard009/Python/0085675_test_config.py
@@ -0,0 +1,194 @@
+# This file is part of PyEMMA.
+#
+# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
+#
+# PyEMMA 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 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 Lesser General Public License
+# along with this program. If not, see .
+'''
+Created on 11.06.2015
+
+@author: marscher
+'''
+
+from __future__ import absolute_import, print_function
+
+from six.moves import configparser
+import os
+import sys
+import unittest
+
+
+
+from pyemma.util.files import TemporaryDirectory
+from pyemma.util.exceptions import ConfigDirectoryException
+import pkg_resources
+import pyemma
+
+
+class TestConfig(unittest.TestCase):
+
+ def setUp(self):
+ self.config_inst = pyemma.config()
+
+ def tearDown(self):
+ try:
+ del os.environ['PYEMMA_CFG_DIR']
+ except KeyError:
+ pass
+
+ def test_config_vals_match_properties_in_wrapper(self):
+ with TemporaryDirectory() as td:
+ self.config_inst.cfg_dir = td
+ self.assertEqual(self.config_inst.cfg_dir, td)
+ from pyemma import config as config_module
+ assert hasattr(config_module, 'default_config_file')
+ my_cfg = os.path.join(td, 'pyemma.cfg')
+ self.assertEqual(pkg_resources.resource_filename('pyemma', 'pyemma.cfg'),
+ config_module.default_config_file)
+ reader = configparser.ConfigParser()
+ reader.read(my_cfg)
+
+ opts = sorted(reader.options('pyemma'))
+ actual = sorted(config_module.keys())
+ self.assertEqual(opts, actual)
+
+ @unittest.skipIf(sys.platform == 'win32', 'unix based test')
+ def test_can_not_create_cfg_dir(self):
+ with self.assertRaises(ConfigDirectoryException) as cm:
+ self.config_inst.cfg_dir = '/dev/null'
+ self.assertIn("no valid directory", str(cm.exception))
+
+ @unittest.skipIf(sys.platform == 'win32', 'unix based test')
+ def test_non_writeable_cfg_dir(self):
+ with TemporaryDirectory() as tmp:
+ # make cfg dir non-writeable
+ os.chmod(tmp, 0x300)
+ assert not os.access(tmp, os.W_OK)
+
+ with self.assertRaises(ConfigDirectoryException) as cm:
+ self.config_inst.cfg_dir = tmp
+ self.assertIn("is not writeable", str(cm.exception))
+
+ def test_shortcuts(self):
+ self.config_inst.show_progress_bars = False
+ assert not self.config_inst.show_progress_bars
+
+ def test_shortcuts2(self):
+ self.config_inst.show_progress_bars = 'True'
+ assert self.config_inst.show_progress_bars
+
+ def test_shortcut3(self):
+ self.config_inst['show_progress_bars'] = 'True'
+ assert self.config_inst.show_progress_bars
+
+ def test_types(self):
+ self.config_inst.show_progress_bars = 0
+ assert isinstance(self.config_inst.show_progress_bars, bool)
+
+ def test_keys(self):
+ self.config_inst.keys()
+
+ def test_set_non_existing_key(self):
+ with self.assertRaises(ValueError):
+ self.config_inst.fooobarr = False
+
+ def test_set(self):
+ self.config_inst.show_progress_bars = 'False'
+ self.config_inst.use_trajectory_lengths_cache = 0
+
+ def test_save_load_user_cfg_file(self):
+ # replace a value with a non default value:
+ self.config_inst.show_progress_bars = not self.config_inst.show_progress_bars
+ import tempfile
+
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.cfg', delete=False) as f:
+ f.close()
+ self.config_inst.save(f.name)
+ cfg = configparser.ConfigParser()
+ cfg.read(f.name)
+ self.assertEqual(cfg.getboolean('pyemma', 'show_progress_bars'), self.config_inst.show_progress_bars)
+
+ def test_save_load_no_cfg_file_given(self):
+ """ test that in case no cfg dir has been set, the default location is being used and values changed at
+ runtime are used afterwards."""
+ # replace a value with a non default value:
+ with TemporaryDirectory() as td:
+ os.environ['PYEMMA_CFG_DIR'] = td
+ self.config_inst = pyemma.config()
+ self.config_inst.show_progress_bars = not self.config_inst.show_progress_bars
+ self.config_inst.save()
+
+ supposed_to_use_cfg = os.path.join(td, self.config_inst.DEFAULT_CONFIG_FILE_NAME)
+
+ cfg = configparser.RawConfigParser()
+ cfg.read(supposed_to_use_cfg)
+ self.assertEqual(cfg.getboolean('pyemma', 'show_progress_bars'),
+ self.config_inst.show_progress_bars)
+
+ def test_load(self):
+ with TemporaryDirectory() as td:
+ new_file = os.path.join(td, "test.cfg")
+ self.config_inst.show_progress_bars = not self.config_inst.show_progress_bars
+ old_val = self.config_inst.show_progress_bars
+ self.config_inst.save(new_file)
+
+ # set a runtime value, differing from what used to be state before save
+ self.config_inst.show_progress_bars = not self.config_inst.show_progress_bars
+
+ self.config_inst.load(new_file)
+ self.assertEqual(self.config_inst.show_progress_bars, old_val)
+
+ def test_interpolation_from_multiple_files(self):
+ # TODO: impl
+ pass
+
+ def test_traj_info_max_entries(self):
+ assert isinstance(self.config_inst.traj_info_max_entries, int)
+ self.config_inst.traj_info_max_entries = 1
+ self.assertEqual(self.config_inst.traj_info_max_entries, 1)
+
+ def test_mute_logging(self):
+ self.config_inst.mute = False
+
+ import logging
+ logger = logging.getLogger('pyemma')
+ old_level = logger.level
+
+ self.config_inst.mute = True
+ assert logger.level >= 50
+
+ # unmute again and check level got restored
+ self.config_inst.mute = False
+ self.assertEqual(logger.level, old_level)
+
+ def test_mute_progress(self):
+ """ switch mute on shall turn off progress bars"""
+ from pyemma._base.progress import ProgressReporterMixin
+ import mock
+ rp = ProgressReporterMixin()
+
+ self.config_inst.mute = True
+ with mock.patch('pyemma.config', self.config_inst):
+ assert not rp.show_progress
+
+ def test_default_chunksize(self):
+ self.config_inst.default_chunksize = '0'
+ self.config_inst.default_chunksize = '2k'
+ self.config_inst.default_chunksize = '0.5G'
+ with self.assertRaises(RuntimeError): # negative not allowed
+ self.config_inst.default_chunksize = '-1'
+ with self.assertRaises(RuntimeError): # unknown suffix
+ self.config_inst.default_chunksize = '23 j'
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pool/shard009/Python/0085677_colorscheme.py b/pool/shard009/Python/0085677_colorscheme.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae8d74f6a87fba55fc55d233bc6a2b29a15ac3b
--- /dev/null
+++ b/pool/shard009/Python/0085677_colorscheme.py
@@ -0,0 +1,155 @@
+# vim:fileencoding=utf-8:noet
+from __future__ import (unicode_literals, division, absolute_import, print_function)
+
+from copy import copy
+
+from powerline.lib.unicode import unicode
+
+
+DEFAULT_MODE_KEY = None
+ATTR_BOLD = 1
+ATTR_ITALIC = 2
+ATTR_UNDERLINE = 4
+
+
+def get_attr_flag(attributes):
+ '''Convert an attribute array to a renderer flag.'''
+ attr_flag = 0
+ if 'bold' in attributes:
+ attr_flag |= ATTR_BOLD
+ if 'italic' in attributes:
+ attr_flag |= ATTR_ITALIC
+ if 'underline' in attributes:
+ attr_flag |= ATTR_UNDERLINE
+ return attr_flag
+
+
+def pick_gradient_value(grad_list, gradient_level):
+ '''Given a list of colors and gradient percent, return a color that should be used.
+
+ Note: gradient level is not checked for being inside [0, 100] interval.
+ '''
+ return grad_list[int(round(gradient_level * (len(grad_list) - 1) / 100))]
+
+
+def hl_iter(value):
+ if type(value) is list:
+ for v in value:
+ yield v
+ else:
+ yield value
+
+
+class Colorscheme(object):
+ def __init__(self, colorscheme_config, colors_config):
+ '''Initialize a colorscheme.'''
+ self.colors = {}
+ self.gradients = {}
+
+ self.groups = colorscheme_config['groups']
+ self.translations = colorscheme_config.get('mode_translations', {})
+
+ # Create a dict of color tuples with both a cterm and hex value
+ for color_name, color in colors_config['colors'].items():
+ try:
+ self.colors[color_name] = (color[0], int(color[1], 16))
+ except TypeError:
+ self.colors[color_name] = (color, cterm_to_hex[color])
+
+ # Create a dict of gradient names with two lists: for cterm and hex
+ # values. Two lists in place of one list of pairs were chosen because
+ # true colors allow more precise gradients.
+ for gradient_name, gradient in colors_config['gradients'].items():
+ if len(gradient) == 2:
+ self.gradients[gradient_name] = (
+ (gradient[0], [int(color, 16) for color in gradient[1]]))
+ else:
+ self.gradients[gradient_name] = (
+ (gradient[0], [cterm_to_hex[color] for color in gradient[0]]))
+
+ def get_gradient(self, gradient, gradient_level):
+ if gradient in self.gradients:
+ return tuple((pick_gradient_value(grad_list, gradient_level) for grad_list in self.gradients[gradient]))
+ else:
+ return self.colors[gradient]
+
+ def get_group_props(self, mode, trans, group, translate_colors=True):
+ if isinstance(group, (str, unicode)):
+ try:
+ group_props = trans['groups'][group]
+ except KeyError:
+ try:
+ group_props = self.groups[group]
+ except KeyError:
+ return None
+ else:
+ return self.get_group_props(mode, trans, group_props, True)
+ else:
+ return self.get_group_props(mode, trans, group_props, False)
+ else:
+ if translate_colors:
+ group_props = copy(group)
+ try:
+ ctrans = trans['colors']
+ except KeyError:
+ pass
+ else:
+ for key in ('fg', 'bg'):
+ try:
+ group_props[key] = ctrans[group_props[key]]
+ except KeyError:
+ pass
+ return group_props
+ else:
+ return group
+
+ def get_highlighting(self, groups, mode, gradient_level=None):
+ trans = self.translations.get(mode, {})
+ for group in hl_iter(groups):
+ group_props = self.get_group_props(mode, trans, group)
+ if group_props:
+ break
+ else:
+ raise KeyError('Highlighting groups not found in colorscheme: ' + ', '.join(hl_iter(groups)))
+
+ if gradient_level is None:
+ pick_color = self.colors.__getitem__
+ else:
+ pick_color = lambda gradient: self.get_gradient(gradient, gradient_level)
+
+ return {
+ 'fg': pick_color(group_props['fg']),
+ 'bg': pick_color(group_props['bg']),
+ 'attr': get_attr_flag(group_props.get('attr', [])),
+ }
+
+
+# 0 1 2 3 4 5 6 7 8 9
+cterm_to_hex = (
+ 0x000000, 0xc00000, 0x008000, 0x804000, 0x0000c0, 0xc000c0, 0x008080, 0xc0c0c0, 0x808080, 0xff6060, # 0
+ 0x00ff00, 0xffff00, 0x8080ff, 0xff40ff, 0x00ffff, 0xffffff, 0x000000, 0x00005f, 0x000087, 0x0000af, # 1
+ 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f, # 2
+ 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, # 3
+ 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7, 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, # 4
+ 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f, # 5
+ 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, # 6
+ 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7, 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, # 7
+ 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f, # 8
+ 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, # 9
+ 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7, 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, # 10
+ 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f, # 11
+ 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, # 12
+ 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7, 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, # 13
+ 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f, # 14
+ 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, # 15
+ 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7, 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, # 16
+ 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f, # 17
+ 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, # 18
+ 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7, 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, # 19
+ 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f, # 20
+ 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, # 21
+ 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7, 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, # 22
+ 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e, # 23
+ 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, # 24
+ 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4, 0xeeeeee # 25
+)
diff --git a/pool/shard009/Python/0085678_getch.py b/pool/shard009/Python/0085678_getch.py
new file mode 100644
index 0000000000000000000000000000000000000000..5179d2c41d967787a282128b624d99a8b9e8c892
--- /dev/null
+++ b/pool/shard009/Python/0085678_getch.py
@@ -0,0 +1,41 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+class _Getch:
+ """Gets a single character from standard input. Does not echo to the
+ screen."""
+ def __init__(self):
+ try:
+ self.impl = _GetchWindows()
+ except ImportError:
+ self.impl = _GetchUnix()
+
+ def __call__(self): return self.impl()
+
+
+class _GetchUnix:
+ def __init__(self):
+ import tty, sys, termios
+
+ def __call__(self):
+ import sys, tty, termios
+ fd = sys.stdin.fileno()
+ old_settings = termios.tcgetattr(fd)
+ try:
+ tty.setraw(sys.stdin.fileno())
+ ch = sys.stdin.read(1)
+ finally:
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
+ return ch
+
+
+class _GetchWindows:
+ def __init__(self):
+ import msvcrt
+
+ def __call__(self):
+ import msvcrt
+ return msvcrt.getch()
+
+
+getch = _Getch()
diff --git a/pool/shard009/Python/0085680_pl_options_container.py b/pool/shard009/Python/0085680_pl_options_container.py
new file mode 100644
index 0000000000000000000000000000000000000000..600ed25db525deb55093037b3fdd1e9b93b9598a
--- /dev/null
+++ b/pool/shard009/Python/0085680_pl_options_container.py
@@ -0,0 +1,43 @@
+# TODO we should also allow accessing by name, i. e.
+# oc = OptionsContainer()
+# oc(foo=11, bar=22)
+# oc.baz=33
+# print(oc.baz)
+class OptionsContainer(dict):
+ '''
+ A dict that can be updated by calling it.
+ '''
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._by_tag = dict()
+
+ def __call__(self, **kwargs):
+ self.update(kwargs)
+
+ def by_tag(self, tag_selector):
+ '''tag_selector must be a single string tag for now'''
+ # TODO allow functions
+ # TODO allow combinations of tags (and-list)
+
+ # TODO right now, by_tag itself is an OptionsContainer, so it can be
+ # recursive (i. e. can have a by_tag again). Is this what we want?
+ # TODO use a defaultdict instead?
+ if tag_selector not in self._by_tag:
+ self._by_tag[tag_selector] = OptionsContainer()
+
+ return self._by_tag[tag_selector]
+
+ # TODO should also accept single tags?
+ # TODO should be tag selectors
+ def for_tags(self, tags_list):
+ result = dict()
+
+ result.update(self)
+
+ for tag in tags_list:
+ # TODO when we allow functions as selectors, there will have to be
+ # more elaborate matching.
+ if tag in self._by_tag:
+ result.update(self._by_tag[tag])
+
+ return result
\ No newline at end of file
diff --git a/pool/shard009/Python/0085682_create_dataset_steps.py b/pool/shard009/Python/0085682_create_dataset_steps.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aa3ac8327a68bfb1843635ebe205410ec69f7e0
--- /dev/null
+++ b/pool/shard009/Python/0085682_create_dataset_steps.py
@@ -0,0 +1,203 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2012-2022 BigML
+#
+# 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 time
+import json
+from datetime import datetime
+from .world import world, res_filename
+from nose.tools import eq_, assert_less
+from bigml.api import HTTP_CREATED
+from bigml.api import HTTP_OK
+from bigml.api import HTTP_ACCEPTED
+from bigml.api import FINISHED
+from bigml.api import FAULTY
+from bigml.api import get_status
+
+from .read_resource_steps import wait_until_status_code_is
+
+
+#@step(r'I create a dataset$')
+def i_create_a_dataset(step, shared=None):
+ if shared is None or world.shared.get("dataset", {}).get(shared) is None:
+ resource = world.api.create_dataset(world.source['resource'])
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+#@step(r'I download the dataset file to "(.*)"$')
+def i_export_a_dataset(step, local_file):
+ world.api.download_dataset(world.dataset['resource'],
+ filename=res_filename(local_file))
+
+#@step(r'file "(.*)" is like file "(.*)"$')
+def files_equal(step, local_file, data):
+ contents_local_file = open(res_filename(local_file)).read()
+ contents_data = open(res_filename(data)).read()
+ eq_(contents_local_file, contents_data)
+
+#@step(r'I create a dataset with "(.*)"')
+def i_create_a_dataset_with(step, data="{}"):
+ resource = world.api.create_dataset(world.source['resource'],
+ json.loads(data))
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+
+#@step(r'I wait until the dataset status code is either (\d) or (\d) less than (\d+)')
+def wait_until_dataset_status_code_is(step, code1, code2, secs):
+ world.dataset = wait_until_status_code_is(
+ code1, code2, secs, world.dataset)
+
+
+#@step(r'I wait until the dataset is ready less than (\d+)')
+def the_dataset_is_finished_in_less_than(step, secs, shared=None):
+ if shared is None or world.shared.get("dataset", {}).get(shared) is None:
+ wait_until_dataset_status_code_is(step, FINISHED, FAULTY, secs)
+ if shared is not None:
+ if "dataset" not in world.shared:
+ world.shared["dataset"] = {}
+ world.shared["dataset"][shared]= world.dataset
+ else:
+ world.dataset = world.shared["dataset"][shared]
+ print("Reusing %s" % world.dataset["resource"])
+
+#@step(r'I make the dataset public')
+def make_the_dataset_public(step):
+ resource = world.api.update_dataset(world.dataset['resource'],
+ {'private': False})
+ world.status = resource['code']
+ eq_(world.status, HTTP_ACCEPTED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+
+#@step(r'I get the dataset status using the dataset\'s public url')
+def build_local_dataset_from_public_url(step):
+ world.dataset = world.api.get_dataset("public/%s" %
+ world.dataset['resource'])
+
+#@step(r'the dataset\'s status is FINISHED')
+def dataset_status_finished(step):
+ eq_(get_status(world.dataset)['code'], FINISHED)
+
+#@step(r'I create a dataset extracting a (.*) sample$')
+def i_create_a_split_dataset(step, rate):
+ world.origin_dataset = world.dataset
+ resource = world.api.create_dataset(world.dataset['resource'],
+ {'sample_rate': float(rate)})
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+#@step(r'I create a multidataset with ranges (.*)$')
+def i_create_a_multidataset(step, ranges):
+ ranges = json.loads(ranges)
+ datasets = world.datasets[-len(ranges):]
+ world.origin_dataset = world.dataset
+ resource = world.api.create_dataset( \
+ datasets,
+ {'sample_rates': dict([(dataset, d_range) for dataset, d_range in
+ zip(datasets, ranges)])})
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+
+#@step(r'I create a multi-dataset with same datasets and the first sample rate (.*)$')
+def i_create_a_multidataset_mixed_format(step, ranges):
+ ranges = json.loads(ranges)
+ dataset = world.dataset['resource']
+ origins = []
+ for value in ranges:
+ if value == 1:
+ origins.append(dataset)
+ else:
+ origins.append({"id": dataset,
+ "sample_rate": value})
+ world.origin_dataset = world.dataset
+ resource = world.api.create_dataset( \
+ origins)
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+
+#@step(r'I compare the datasets\' instances$')
+def i_compare_datasets_instances(step):
+ world.datasets_instances = (world.dataset['rows'],
+ world.origin_dataset['rows'])
+
+#@step(r'the proportion of instances between datasets is (.*)$')
+def proportion_datasets_instances(step, rate):
+ eq_(int(world.datasets_instances[1] * float(rate)),
+ world.datasets_instances[0])
+
+#@step(r'I create a dataset associated to centroid "(.*)"')
+def i_create_a_dataset_from_cluster(step, centroid_id):
+ resource = world.api.create_dataset(
+ world.cluster['resource'],
+ args={'centroid': centroid_id})
+ world.status = resource['code']
+ eq_(world.status, HTTP_CREATED)
+ world.location = resource['location']
+ world.dataset = resource['object']
+ world.datasets.append(resource['resource'])
+
+#@step(r'I create a dataset from the cluster and the centroid$')
+def i_create_a_dataset_from_cluster_centroid(step):
+ i_create_a_dataset_from_cluster(step, world.centroid['centroid_id'])
+
+#@step(r'the dataset is associated to the centroid "(.*)" of the cluster')
+def is_associated_to_centroid_id(step, centroid_id):
+ cluster = world.api.get_cluster(world.cluster['resource'])
+ world.status = cluster['code']
+ eq_(world.status, HTTP_OK)
+ eq_("dataset/%s" % (cluster['object']['cluster_datasets'][centroid_id]),
+ world.dataset['resource'])
+
+#@step(r'I check that the dataset is created for the cluster and the centroid$')
+def i_check_dataset_from_cluster_centroid(step):
+ is_associated_to_centroid_id(step, world.centroid['centroid_id'])
+
+#@step(r'I update the dataset with params "(.*)"')
+def i_update_dataset_with(step, data="{}"):
+ resource = world.api.update_dataset(world.dataset.get('resource'),
+ json.loads(data))
+ world.status = resource['code']
+ eq_(world.status, HTTP_ACCEPTED)
+
+#@step(r'I clone dataset')
+def clone_dataset(step, dataset):
+ resource = world.api.clone_dataset(dataset, {'project': world.project_id})
+ # update status
+ world.status = resource['code']
+ world.location = resource['location']
+ world.dataset = resource['object']
+ # save reference
+ world.datasets.append(resource['resource'])
+
+def the_cloned_dataset_is(step, dataset):
+ eq_(world.dataset["origin"], dataset)
diff --git a/pool/shard009/Python/0085685_run_exp_generator.py b/pool/shard009/Python/0085685_run_exp_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..c596cc32b40b73d9c08308e3da0b98b2eb7e9342
--- /dev/null
+++ b/pool/shard009/Python/0085685_run_exp_generator.py
@@ -0,0 +1,117 @@
+#! /usr/bin/env python
+# ----------------------------------------------------------------------
+# Numenta Platform for Intelligent Computing (NuPIC)
+# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and conditions apply:
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero Public License version 3 as
+# published by the Free Software Foundation.
+#
+# 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 Public License for more details.
+#
+# You should have received a copy of the GNU Affero Public License
+# along with this program. If not, see http://www.gnu.org/licenses.
+#
+# http://numenta.org/licenses/
+# ----------------------------------------------------------------------
+
+"""
+Run ExpGenerator to generate the description and permutations file for a
+spatial classification experiment
+"""
+
+import os
+import json
+from optparse import OptionParser
+
+from nupic.swarming.exp_generator.ExpGenerator import expGenerator
+
+
+
+if __name__ == '__main__':
+
+ helpString = \
+ """%prog [options] searchDef
+ This script is used to create the description.py and permutations.py files
+ for an experiment. The searchDef argument should be the name of a python
+ script with a getSearch() method which returns the search definition as a
+ dict. The schema for this dict can be found at
+ py/nupic/swarming/exp_generator/experimentDescriptionSchema.json
+ """
+
+
+ # ============================================================================
+ # Process command line arguments
+ parser = OptionParser(helpString)
+
+ parser.add_option("--verbosity", default=0, type="int",
+ help="Verbosity level, either 0, 1, 2, or 3 [default: %default].")
+
+ parser.add_option("--outDir", dest='outDir', default=None,
+ help="Where to place generated files. Default is in the same directory"
+ " as the searchDef script.")
+
+
+ (options, args) = parser.parse_args()
+
+ # Must provide the name of a script
+ if len(args) != 1:
+ parser.error("Missing required 'searchDef' argument")
+ searchFileName = args[0]
+
+ # ------------------------------------------------------------------------
+ # Read in the search script and get the search definition
+ searchFile = open(searchFileName)
+ vars = {}
+ exec(searchFile, vars)
+ searchFile.close()
+
+ getSearchFunc = vars.get('getSearch', None)
+ if getSearchFunc is None:
+ raise RuntimeError("Error: the %s python script does not provide the "
+ "required getSearch() method")
+
+ searchDef = getSearchFunc(os.path.dirname(__file__))
+ if not isinstance(searchDef, dict):
+ raise RuntimeError("The searchDef function should return a dict, but it "
+ "returned %s" % (str(searchDef)))
+
+
+ # ------------------------------------------------------------------------
+ # Figure out the output directory if not provided
+ if options.outDir is None:
+ options.outDir = os.path.dirname(searchFileName)
+
+
+ # ------------------------------------------------------------------------
+ # Run through expGenerator
+ expGenArgs = ['--description={0!s}'.format((json.dumps(searchDef))),
+ '--version=v2',
+ '--outDir={0!s}'.format((options.outDir))]
+ print "Running ExpGenerator with the following arguments: ", expGenArgs
+ expGenerator(expGenArgs)
+
+
+ # Get the permutations file name
+ permutationsFilename = os.path.join(options.outDir, 'permutations.py')
+
+ print "Successfully generated permutations file: {0!s}".format((permutationsFilename))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pool/shard009/Python/0085686_test_user_draft_registration_list.py b/pool/shard009/Python/0085686_test_user_draft_registration_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dcb37761d118fb822abf18642245cbd3de92fa1
--- /dev/null
+++ b/pool/shard009/Python/0085686_test_user_draft_registration_list.py
@@ -0,0 +1,139 @@
+import pytest
+from django.utils import timezone
+
+from api.base.settings.defaults import API_BASE
+from api.users.views import UserDraftRegistrations
+from api_tests.nodes.views.test_node_draft_registration_list import DraftRegistrationTestCase
+from api_tests.utils import only_supports_methods
+from osf.models import RegistrationSchema
+from osf_tests.factories import (
+ RegistrationFactory,
+ AuthUserFactory,
+ DraftRegistrationFactory,
+)
+from osf.utils import permissions
+
+SCHEMA_VERSION = 2
+
+
+@pytest.mark.django_db
+class TestDraftRegistrationList(DraftRegistrationTestCase):
+
+ @pytest.fixture()
+ def other_admin(self, project_public):
+ user = AuthUserFactory()
+ project_public.add_contributor(user, permissions=permissions.ADMIN, save=True)
+ return user
+
+ @pytest.fixture()
+ def schema(self):
+ return RegistrationSchema.objects.get(
+ name='Open-Ended Registration',
+ schema_version=SCHEMA_VERSION)
+
+ @pytest.fixture()
+ def draft_registration(self, user, project_public, schema):
+ return DraftRegistrationFactory(
+ initiator=user,
+ registration_schema=schema,
+ branched_from=project_public
+ )
+
+ @pytest.fixture()
+ def url_draft_registrations(self, project_public):
+ return '/{}users/me/draft_registrations/'.format(API_BASE)
+
+ def test_unacceptable_methods(self):
+ assert only_supports_methods(UserDraftRegistrations, ['GET'])
+
+ def test_view_permissions(
+ self, app, user, other_admin, draft_registration,
+ user_write_contrib, user_read_contrib, user_non_contrib,
+ schema, url_draft_registrations):
+ res = app.get(url_draft_registrations, auth=user.auth)
+ assert res.status_code == 200
+ data = res.json['data']
+ assert len(data) == 1
+ assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
+ assert data[0]['id'] == draft_registration._id
+ assert data[0]['attributes']['registration_metadata'] == {}
+
+ res = app.get(url_draft_registrations, auth=user.auth)
+ assert res.status_code == 200
+ data = res.json['data']
+ assert len(data) == 1
+ assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
+ assert data[0]['id'] == draft_registration._id
+ assert data[0]['attributes']['registration_metadata'] == {}
+
+ # test_read_only_contributor_can_view_draft_list
+ res = app.get(
+ url_draft_registrations,
+ auth=user_read_contrib.auth)
+ assert len(res.json['data']) == 0
+
+ # test_read_write_contributor_can_view_draft_list
+ res = app.get(
+ url_draft_registrations,
+ auth=user_write_contrib.auth)
+ assert len(res.json['data']) == 0
+
+ # test_logged_in_non_contributor_cannot_view_draft_list
+ res = app.get(
+ url_draft_registrations,
+ auth=user_non_contrib.auth)
+ assert len(res.json['data']) == 0
+
+ # test_unauthenticated_user_cannot_view_draft_list
+ res = app.get(url_draft_registrations, expect_errors=True)
+ assert res.status_code == 401
+
+ def test_deleted_draft_registration_does_not_show_up_in_draft_list(
+ self, app, user, draft_registration, url_draft_registrations):
+ draft_registration.deleted = timezone.now()
+ draft_registration.save()
+ res = app.get(url_draft_registrations, auth=user.auth)
+ assert res.status_code == 200
+ data = res.json['data']
+ assert len(data) == 0
+
+ def test_draft_with_registered_node_does_not_show_up_in_draft_list(
+ self, app, user, project_public, draft_registration, url_draft_registrations):
+ reg = RegistrationFactory(project=project_public, draft_registration=draft_registration)
+ draft_registration.registered_node = reg
+ draft_registration.save()
+ res = app.get(url_draft_registrations, auth=user.auth)
+ assert res.status_code == 200
+ data = res.json['data']
+ assert len(data) == 0
+
+ def test_draft_with_deleted_registered_node_shows_up_in_draft_list(
+ self, app, user, project_public,
+ draft_registration, schema,
+ url_draft_registrations):
+ reg = RegistrationFactory(project=project_public, draft_registration=draft_registration)
+ draft_registration.registered_node = reg
+ draft_registration.save()
+ reg.is_deleted = True
+ reg.save()
+ res = app.get(url_draft_registrations, auth=user.auth)
+ assert res.status_code == 200
+ data = res.json['data']
+ assert len(data) == 1
+ assert schema._id in data[0]['relationships']['registration_schema']['links']['related']['href']
+ assert data[0]['id'] == draft_registration._id
+ assert data[0]['attributes']['registration_metadata'] == {}
+
+ def test_cannot_access_other_users_draft_registration(
+ self, app, user, other_admin, project_public,
+ draft_registration, schema):
+ url = '/{}users/{}/draft_registrations/'.format(API_BASE, user._id)
+ res = app.get(url, auth=other_admin.auth, expect_errors=True)
+ assert res.status_code == 403
+
+ def test_can_access_own_draft_registrations_with_guid(
+ self, app, user, draft_registration):
+ url = '/{}users/{}/draft_registrations/'.format(API_BASE, user._id)
+ res = app.get(url, auth=user.auth, expect_errors=True)
+ assert res.status_code == 200
+ assert len(res.json['data']) == 1
diff --git a/pool/shard009/Python/0085689_forgot_password.py b/pool/shard009/Python/0085689_forgot_password.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cef5e5467d96737f65013846229c1d8d116a06d
--- /dev/null
+++ b/pool/shard009/Python/0085689_forgot_password.py
@@ -0,0 +1,25 @@
+from cornflake.exceptions import ValidationError
+from flask import Response
+
+from radar.api.serializers.auth import ForgotPasswordSerializer
+from radar.api.views.generics import ApiView, request_json
+from radar.auth.forgot_password import forgot_password, UserNotFound
+
+
+class ForgotPasswordView(ApiView):
+ @request_json(ForgotPasswordSerializer)
+ def post(self, data):
+ username = data['username']
+ email = data['email']
+
+ try:
+ forgot_password(username, email)
+ except UserNotFound:
+ raise ValidationError({'username': 'No user found with that username and email.'})
+
+ return Response(status=200)
+
+
+def register_views(app):
+ app.add_public_endpoint('forgot_password')
+ app.add_url_rule('/forgot-password', view_func=ForgotPasswordView.as_view('forgot_password'))
diff --git a/pool/shard009/Python/0085690_autobop.py b/pool/shard009/Python/0085690_autobop.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc45f16b03fb809a75b9b11a83d220d060074003
--- /dev/null
+++ b/pool/shard009/Python/0085690_autobop.py
@@ -0,0 +1,18 @@
+#
+# Each time a song starts, the bot vote up.
+# WARNING: Turntable no longer allows bots that autobop. This script is provided for educational purposes only.
+# For more information, visit http://faq.turntable.fm/customer/portal/articles/258935
+#
+
+from ttapi import Bot
+
+AUTH = 'auth+live+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
+USERID = 'xxxxxxxxxxxxxxxxxxxxxxxx'
+ROOMID = 'xxxxxxxxxxxxxxxxxxxxxxxx'
+bot = Bot(AUTH, USERID, ROOMID)
+
+def autobop(data): bot.bop()
+
+bot.on('newsong', autobop)
+
+bot.start()
diff --git a/pool/shard009/Python/0085692_main__.py b/pool/shard009/Python/0085692_main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ec65b9d29a2e8d3b7dc3fe71d9a8e4752b90b6f
--- /dev/null
+++ b/pool/shard009/Python/0085692_main__.py
@@ -0,0 +1,115 @@
+# -*- coding: UTF-8 -*-
+
+import re
+import subprocess
+import time
+import sys
+
+from location import Location
+from measurement import ipsec_status, restart_ipsec
+from notifier import pusher
+from settings import PROWL_NOTIFY_API_KEYS, CHECK_INTERVAL, SENDGRID_API_KEY
+
+
+def check_settings():
+ try:
+ assert len(PROWL_NOTIFY_API_KEYS) > 0, "NO PROWL_NOTIFY_API_KEYS is set."
+ assert len(SENDGRID_API_KEY) > 0, "NO SENDGRID_API_KEY is set."
+ return True
+ except AssertionError as e:
+ print e.message
+
+
+def check_all_locations(locations):
+ try:
+ ips = [l.ip for l in locations]
+ p = subprocess.Popen(['fping'] + ips, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ output, err = p.communicate(b"input data that is passed to subprocess' stdin")
+ return output
+ except OSError as e:
+ pusher.push('Check All Locations', str(e))
+
+
+def main():
+ status_regex = re.compile("(\d+\.\d+\.\d+\.\d+).*?(alive|unreachable)")
+ locations = [
+ Location('Basel', '192.168.81.1', 'basel@physio-zentrum.ch'),
+ Location('St.Gallen', '192.168.129.1', 'stgallen@physio-zentrum.ch'),
+ Location('Wetzikon', '172.16.6.1', 'wetzikon@physio-zentrum.ch'),
+ Location('Server', '192.168.70.5', 'remo@liebi.net')
+ ]
+ restarted = False
+ downtime_counter = 0
+ while True:
+ down_connections = []
+ result = status_regex.findall(check_all_locations(locations))
+ for i in range(len(result)):
+ ip = result[i][0]
+ reply = result[i][1]
+ location = (item for item in locations if item.ip == ip).next()
+ if reply == 'unreachable':
+ down_connections.append(location)
+ location.check_location(False)
+ else:
+ location.check_location(True)
+
+ if len(down_connections) >= 3:
+ downtime_counter += 1
+
+ if not restarted and downtime_counter == 4:
+ message = """ Hallo. Es gab ein Problem mit den Verbindungen mit mehreren Standorten
+ ({down})
+ Der Server wird nun automatisch neu gestartet.
+ Dies kann dazu führen, dass Simed kurzzeitig unterbrochen wird.
+
+ Sorry für die umstände.
+ Lieber Gruss
+ Remo
+
+ ===
+ {locations}
+ """.format(locations='
'.join([i.get_connection_phrase() for i in locations]),
+ down=','.join([i.name for i in down_connections]))
+
+ pusher.send_mail(locations, "Neustart", message)
+ pusher.push('trying to restart the l2tp service in 60 seconds',
+ '{} Connections are down!({})'.format(len(down_connections),
+ ', '.join([i.name for i in down_connections])),
+ 2)
+
+ ipsec_status()
+ time.sleep(60)
+ restart_ipsec()
+ restarted = True
+
+ if restarted and downtime_counter % 6 == 0:
+ ipsec_status()
+
+ elif restarted:
+ restarted = False
+ pusher.push('IPSec seems to be running again.',
+ ','.join([i.get_connection_phrase() for i in locations]))
+ downtime_counter = 0
+ time.sleep(CHECK_INTERVAL)
+
+
+if __name__ == '__main__':
+
+ if len(sys.argv) == 1:
+ if check_settings():
+ print 'starting script'
+ main()
+ else:
+ print 'failed loading settings. please check your vpn_checker.conf' \
+ ' and settings.py or that the env variables are set correctly!'
+ else:
+ for arg in sys.argv:
+ if arg == '__main__.py':
+ pass
+
+ if arg == 'testmail':
+ l = Location('testlocation', '', 'remo@liebi.net')
+ pusher.send_mail(l, 'TestMail', 'TestMail')
+ print 'TestMail sent.'
\ No newline at end of file
diff --git a/pool/shard009/Python/0085696_test_cli.py b/pool/shard009/Python/0085696_test_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..c23863d3c663932d602bf615e4e2d7ac0e0cbc9c
--- /dev/null
+++ b/pool/shard009/Python/0085696_test_cli.py
@@ -0,0 +1,37 @@
+from pkg_resources import iter_entry_points
+
+from click.testing import CliRunner
+
+
+import orangery
+from orangery.cli.orangery import cli
+
+
+def test_orangery():
+ runner = CliRunner()
+ result = runner.invoke(cli, ['--help'])
+ assert result.exit_code == 0
+
+
+def test_adjust():
+ runner = CliRunner()
+ result = runner.invoke(cli, ['adjust', '--help'])
+ assert result.exit_code == 0
+
+
+def test_info():
+ runner = CliRunner()
+ result = runner.invoke(cli, ['info', '--help'])
+ assert result.exit_code == 0
+
+
+def test_section():
+ runner = CliRunner()
+ result = runner.invoke(cli, ['section', '--help'])
+ assert result.exit_code == 0
+
+
+def test_segment():
+ runner = CliRunner()
+ result = runner.invoke(cli, ['segment', '--help'])
+ assert result.exit_code == 0
diff --git a/pool/shard009/Python/0085699_apply.py b/pool/shard009/Python/0085699_apply.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd025f4e1c3dc43ce42ad0b9ac9cf936e80b2b42
--- /dev/null
+++ b/pool/shard009/Python/0085699_apply.py
@@ -0,0 +1,86 @@
+import logging
+import os
+
+from dvc.repo import locked
+from dvc.repo.scm_context import scm_context
+from dvc.utils.fs import remove
+
+from .base import (
+ EXEC_APPLY,
+ ApplyConflictError,
+ BaselineMismatchError,
+ InvalidExpRevError,
+)
+from .executor.base import BaseExecutor
+
+logger = logging.getLogger(__name__)
+
+
+@locked
+@scm_context
+def apply(repo, rev, force=True, **kwargs):
+ from scmrepo.exceptions import MergeConflictError
+
+ from dvc.repo.checkout import checkout as dvc_checkout
+ from dvc.scm import RevError, SCMError, resolve_rev
+
+ exps = repo.experiments
+
+ try:
+ exp_rev = resolve_rev(repo.scm, rev)
+ exps.check_baseline(exp_rev)
+ except (RevError, BaselineMismatchError) as exc:
+ raise InvalidExpRevError(rev) from exc
+
+ stash_rev = exp_rev in exps.stash_revs
+ if not stash_rev and not exps.get_branch_by_rev(
+ exp_rev, allow_multiple=True
+ ):
+ raise InvalidExpRevError(exp_rev)
+
+ # Note that we don't use stash_workspace() here since we need finer control
+ # over the merge behavior when we unstash everything
+ if repo.scm.is_dirty(untracked_files=True):
+ logger.debug("Stashing workspace")
+ workspace = repo.scm.stash.push(include_untracked=True)
+ else:
+ workspace = None
+
+ from scmrepo.exceptions import SCMError as _SCMError
+
+ try:
+ repo.scm.merge(exp_rev, commit=False)
+ except _SCMError as exc:
+ raise SCMError(str(exc))
+
+ if workspace:
+ try:
+ repo.scm.stash.apply(workspace)
+ except MergeConflictError as exc:
+ # Applied experiment conflicts with user's workspace changes
+ if force:
+ # prefer applied experiment changes over prior stashed changes
+ repo.scm.checkout_index(ours=True)
+ else:
+ # revert applied changes and restore user's workspace
+ repo.scm.reset(hard=True)
+ repo.scm.stash.pop()
+ raise ApplyConflictError(rev) from exc
+ except _SCMError as exc:
+ raise ApplyConflictError(rev) from exc
+ repo.scm.stash.drop()
+ repo.scm.reset()
+
+ if stash_rev:
+ args_path = os.path.join(repo.tmp_dir, BaseExecutor.PACKED_ARGS_FILE)
+ if os.path.exists(args_path):
+ remove(args_path)
+
+ dvc_checkout(repo, **kwargs)
+
+ repo.scm.set_ref(EXEC_APPLY, exp_rev)
+ logger.info(
+ "Changes for experiment '%s' have been applied to your current "
+ "workspace.",
+ rev,
+ )
diff --git a/pool/shard009/Python/0085700_ex19.py b/pool/shard009/Python/0085700_ex19.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8526a08e46a2803dcf27bf2dbeb16eeea40ff67
--- /dev/null
+++ b/pool/shard009/Python/0085700_ex19.py
@@ -0,0 +1,24 @@
+def cheese_and_crackers(cheese_count, boxes_of_crackers):
+ print "You have %d cheeses!" % cheese_count
+ print "You have %d boxes of crackers!" % boxes_of_crackers
+ print "Man that's enough for a party!"
+ print "Get a blanket.\n"
+
+
+print "We can just give the function numbers directly:"
+cheese_and_crackers(20, 30)
+
+
+print "Or, we can use variables from our scrip:"
+amount_of_cheese = 10
+amount_of_crackers = 50
+
+cheese_and_crackers(amount_of_cheese, amount_of_crackers)
+
+
+print "And we can combine the two, variables and math:"
+cheese_and_crackers(10 + 20, 5 + 6)
+
+
+print "And we can combine the two, variables and math:"
+cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
diff --git a/pool/shard009/Python/0085701_setup-cx_freeze.py b/pool/shard009/Python/0085701_setup-cx_freeze.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ed9e0a8908117910b71ff349873d33f4b8671d
--- /dev/null
+++ b/pool/shard009/Python/0085701_setup-cx_freeze.py
@@ -0,0 +1,26 @@
+import os
+###############################################################################
+project = 'GoogleSheets'
+#
+name = __import__(project).get_project()
+description = __import__(project).get_description()
+version = __import__(project).get_version()
+###############################################################################
+
+from cx_Freeze import setup, Executable
+
+# Dependencies are automatically detected, but it might need
+# fine tuning.
+buildOptions = dict(packages = [], excludes = [])
+
+base = 'Console'
+
+executables = [
+ Executable(os.path.join(name, 'main.py'), base=base, targetName=name)
+]
+
+setup(name=name,
+ version=version,
+ description='Google Spreadsheet Read/Write (more?) manipulation',
+ options=dict(build_exe = buildOptions),
+ executables=executables)
diff --git a/pool/shard009/Python/0085703_simrun.py b/pool/shard009/Python/0085703_simrun.py
new file mode 100644
index 0000000000000000000000000000000000000000..019150a7b643694a85bdcbcff5a4c782614dda48
--- /dev/null
+++ b/pool/shard009/Python/0085703_simrun.py
@@ -0,0 +1,77 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Thu Jan 07 11:08:01 2016
+
+@author: Radu
+"""
+
+from neuron import h
+from matplotlib import pyplot
+
+def set_recording_vectors(cell):
+ """Set soma, dendrite, and time recording vectors on the cell.
+
+ :param cell: Cell to record from.
+ :return: the soma, dendrite, and time vectors as a tuple.
+ """
+ soma_v_vec = h.Vector() # Membrane potential vector at soma
+ dend_v_vec = h.Vector() # Membrane potential vector at dendrite
+ t_vec = h.Vector() # Time stamp vector
+
+ soma_m_vec = h.Vector() # Sodium m parameter vector at soma
+ soma_h_vec = h.Vector() # Sodium m parameter vector at soma
+ soma_n_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_ina_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_ikrect_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_ical_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_inap_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_idap_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_ican_vec = h.Vector() # Potassium n parameter vector at soma
+ soma_ikca_vec = h.Vector() # Potassium n parameter vector at soma
+
+ soma_v_vec.record(cell.soma(0.5)._ref_v)
+
+ soma_m_vec.record(cell.soma(0.5)._ref_m_clarke)
+ soma_h_vec.record(cell.soma(0.5)._ref_h_clarke)
+ soma_inap_vec.record(cell.soma(0.5)._ref_inap_clarke)
+ soma_ina_vec.record(cell.soma(0.5)._ref_ina_clarke)
+ soma_ikrect_vec.record(cell.soma(0.5)._ref_ikrect_clarke)
+ soma_idap_vec.record(cell.dap_syn_._ref_i)
+ soma_n_vec.record(cell.soma(0.5)._ref_n_clarke)
+
+ soma_ical_vec.record(cell.soma(0.5)._ref_icaL_clarke)
+ soma_ican_vec.record(cell.soma(0.5)._ref_icaN_clarke)
+ soma_ikca_vec.record(cell.soma(0.5)._ref_ikca_clarke)
+
+ dend_v_vec.record(cell.dend(0.5)._ref_v)
+ t_vec.record(h._ref_t)
+
+ return soma_v_vec, soma_m_vec, soma_h_vec, soma_n_vec,\
+ soma_inap_vec, soma_idap_vec, soma_ical_vec,\
+ soma_ican_vec, soma_ikca_vec, soma_ina_vec, soma_ikrect_vec,\
+ dend_v_vec, t_vec
+
+def simulate(tstop=10000):
+ """Initialize and run a simulation.
+
+ :param tstop: Duration of the simulation.
+ """
+ h.tstop = tstop
+ h.run()
+
+def show_output(soma_v_vec, dend_v_vec, t_vec, new_fig=True):
+ """Draw the output.
+
+ :param soma_v_vec: Membrane potential vector at the soma.
+ :param dend_v_vec: Membrane potential vector at the dendrite.
+ :param t_vec: Timestamp vector.
+ :param new_fig: Flag to create a new figure (and not draw on top
+ of previous results)
+ """
+ if new_fig:
+ pyplot.figure(figsize=(8,4)) # Default figsize is (8,6)
+ soma_plot = pyplot.plot(t_vec, soma_v_vec, color='black')
+ dend_plot = pyplot.plot(t_vec, dend_v_vec, color='red')
+ pyplot.legend(soma_plot + dend_plot, ['soma', 'dend(0.5)'])
+ pyplot.xlabel('time (ms)')
+ pyplot.ylabel('mV')
\ No newline at end of file
diff --git a/pool/shard009/Python/0085706_effective.py b/pool/shard009/Python/0085706_effective.py
new file mode 100644
index 0000000000000000000000000000000000000000..45da564c2ddfe32fb1eb29c0e9639221cb2e2a55
--- /dev/null
+++ b/pool/shard009/Python/0085706_effective.py
@@ -0,0 +1,75 @@
+from __future__ import (absolute_import, division,
+ print_function, unicode_literals)
+from future.builtins import ( # noqa
+ bytes, dict, int, list, object, range, str,
+ ascii, chr, hex, input, next, oct, open,
+ pow, round, super,
+ filter, map, zip)
+
+from orchestrator.cluster_config.base import AbstractConfigProvider
+from orchestrator.util import dict_merge
+
+
+class MergedConfigProvider(AbstractConfigProvider):
+ """
+ Provider that merges the config from different providers and optionally
+ caches it.
+ """
+ def __init__(self, *providers, **kwargs):
+ """
+ :param providers: List of Config providers.
+ :param write_provider: Config provider for writing the config to. If
+ None, then no write will be done.
+ """
+ self.providers = providers
+ self.write_provider = kwargs.get('write_provider', None)
+
+ def write(self, name, config, *paths):
+ """
+ Writes config using write_provider (if set).
+
+ :param config: Dictionary based config. (This will be serialized to
+ Yaml by the underlying provider.
+ :param paths: Nested path list where config needs to be written to.
+ :return: None
+ """
+ # Delegate to write_provider if set. Else NOOP
+ if self.write_provider:
+ self.write_provider.write(config, *paths)
+
+ def delete(self, name, *paths):
+ """
+ Deletes config using write_provider (if set).
+
+ :param paths: Nested path list where config needs to be written to.
+ :return: None
+ """
+ # Delegate to write_provider if set. Else NOOP
+ if self.write_provider:
+ self.write_provider.delete(name, *paths)
+
+ def load(self, name, *paths):
+ """
+ Loads config for given path list.
+
+ :param paths: Path list used for loading the config.
+ :return: Merged config from different providers.
+ :rtype: dict
+ """
+ merged_config = {}
+
+ def merge(current_config, provider, *merge_paths):
+ return dict_merge(
+ current_config,
+ provider.load(name, *merge_paths))
+
+ use_paths = list(paths)
+ while True:
+ for provider in self.providers:
+ merged_config = merge(merged_config, provider, *use_paths)
+ if use_paths:
+ use_paths.pop()
+ else:
+ break
+
+ return merged_config
diff --git a/pool/shard009/Python/0085710_console.py b/pool/shard009/Python/0085710_console.py
new file mode 100644
index 0000000000000000000000000000000000000000..27d5c08a1df7267d69eb2c773672164f0bb1da49
--- /dev/null
+++ b/pool/shard009/Python/0085710_console.py
@@ -0,0 +1,35 @@
+from time import sleep
+import os
+import signal
+
+from crawler import Crawler
+import functions
+
+quit=False
+def SigInt(signal, frame):
+ print "QUIT!"
+ global quit
+ quit=True
+
+
+if __name__=="__main__":
+ c=Crawler("lolo.save")
+ c.Start(5)
+ c.ToggleTOR()
+ c.EnableTasksToFile("tasks.txt")
+
+ c.AddURLs(["//orf.at"])
+
+ i=0
+ signal.signal(signal.SIGINT, SigInt)
+ while not quit:
+ c.Update()
+ c.Print()
+ sleep(1)
+ os.system("cls")
+ i+=1
+ if i==60:
+ c.DumpURLs("dump.txt")
+ i=0
+
+ c.Join("lolo.save")
diff --git a/pool/shard009/Python/0085716_xlspy.py b/pool/shard009/Python/0085716_xlspy.py
new file mode 100644
index 0000000000000000000000000000000000000000..e65ea306ace97d38f6e75e8e75dea1b7630914ed
--- /dev/null
+++ b/pool/shard009/Python/0085716_xlspy.py
@@ -0,0 +1,116 @@
+"""
+XLSPy.
+
+Simple wrapper for openpyxl::
+
+>>> from xlspy import Book
+>>> book = Book('filename.xlsx')
+>>> book
+
+
+
+>>> book.active
+
+
+# Get a sheet directly:
+
+>>> home = book['Home renovations']
+>>> home
+
+
+>>> column_a = home['A']
+"""
+
+from itertools import chain
+
+import openpyxl
+
+
+class Sheet(object):
+ """Wrapper for openpyxl sheets.
+
+ Basic usage of a Sheet instance:
+
+ >>> s['F']
+ # Result: list of cells of column 'F'
+
+ >>> s['F1:F4']
+ # Result: tuple of one element tuples (openpyxl)
+ """
+
+ # I wonder if I'm going to change the standard way openpyxl returns
+ # a cell range (tuple of tuples) as I did with the whole column.
+ def __init__(self, sheet):
+ """Initialize the sheet."""
+ self._sheet = sheet
+
+ def __getitem__(self, key):
+ """Make access to "columns" easier. Cell access remains the same."""
+ if ':' not in key:
+ # Use wants to access a column, example: Sheet['F'].
+ # We return Fmin_row:Fmax_row cells under the hood.
+ return list(chain.from_iterable(
+ self._sheet['{key}{min_row}:{key}{max_row}'.format(
+ key=key,
+ min_row=self._sheet.min_row,
+ max_row=self._sheet.max_row)
+ ])
+ )
+
+ else:
+ # User wants to access specific cells Sheet['F1:F3']
+ return self._sheet[key]
+
+ def __getattr__(self, name):
+ """Return the original openpyxl arguments for whatever is not ours."""
+ return getattr(self._sheet, name)
+
+ def __repr__(self):
+ """Nice representation."""
+ return "<{}: '{}'>".format(self.__class__.__name__, self._sheet.title)
+
+
+class Book(object):
+ """Wrapper for openpyxl."""
+
+ def __init__(self, filename, **kwargs):
+ """Initialize the book."""
+ self._filename = filename
+ self._book = openpyxl.load_workbook(filename, **kwargs)
+ self._sheet_names = self._book.get_sheet_names()
+ self._sheets = [self._book.get_sheet_by_name(key) for key in self.sheet_names]
+
+ def __getitem__(self, key):
+ """Access worksheets in book as you would items in a dictionary.
+
+ >>> sheet = book['sheet_name']
+ """
+ return self._book.get_sheet_by_name(key)
+
+ @property
+ def active(self):
+ """Return the active sheet."""
+ return Sheet(self._book.active)
+
+ @property
+ def sheet_names(self):
+ """Return sheet names."""
+ return self._sheet_names
+
+ @property
+ def sheets(self):
+ """Return actual sheet objects."""
+ return [Sheet(sheet) for sheet in self._sheets]
+
+ def __getattr__(self, name):
+ """Return original openpyxl Workbook attributes."""
+ return getattr(self._book, name)
+
+ def __repr__(self):
+ """Nice repr."""
+ msg = "<{}:\t{}>\n" \
+ "".format(
+ self.__class__.__name__,
+ self._filename,
+ " | ".join(["{}".format(name) for name in self.sheet_names]))
+ return msg
diff --git a/pool/shard009/Python/0085717_errors.py b/pool/shard009/Python/0085717_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..5da225a0a4ad4095bc7f4c88e8c991b17967c663
--- /dev/null
+++ b/pool/shard009/Python/0085717_errors.py
@@ -0,0 +1,36 @@
+try:
+ from jira.utils import JIRAError
+except: # pragma: no cover
+ from jira.exceptions import JIRAError
+
+from suds import WebFault
+
+
+class JiraInitializationError(Exception):
+ pass
+
+
+class JiraAuthenticationError(Exception):
+ pass
+
+
+class UsageError(Exception):
+ pass
+
+class UsageWarning(Exception):
+ pass
+
+
+class JiraCliError(Exception):
+ def __init__(self, exc):
+ if isinstance(exc, WebFault):
+ msg = ":".join(exc.fault.faultstring.split(":")[1:]).strip()
+ super(JiraCliError, self).__init__(msg)
+ elif isinstance(exc, JIRAError):
+ if exc.status_code == 401:
+ super(JiraCliError, self).__init__("invalid username/password")
+ else:
+ super(JiraCliError, self).__init__(exc.text)
+ else:
+ super(JiraCliError, self).__init__(exc)
+
diff --git a/pool/shard009/Python/0085719_fibonacci.py b/pool/shard009/Python/0085719_fibonacci.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cf53e229067dd97828852d7b63092552ae89c58
--- /dev/null
+++ b/pool/shard009/Python/0085719_fibonacci.py
@@ -0,0 +1,20 @@
+def fibonacci():
+ "A lazy stream of Fibonacci numbers starting at 0 (0, 1, 1, 2, 3, 5, ...)."
+ a = 0
+ b = 1
+ while True:
+ yield a
+ c = a + b
+ a = b
+ b = c
+
+
+def index(f):
+ "Given a Fibonacci number return its position in the stream."
+ if f < 0:
+ raise ValueError("%d is not a fibonacci number" % f)
+ for i, n in enumerate(fibonacci()):
+ if f == n:
+ return i
+ if n > f:
+ raise ValueError("%d is not a fibonacci number" % f)
diff --git a/pool/shard009/Python/0085720_test_template.py b/pool/shard009/Python/0085720_test_template.py
new file mode 100644
index 0000000000000000000000000000000000000000..12720fee95037a2fb048d95663ee70a7372af763
--- /dev/null
+++ b/pool/shard009/Python/0085720_test_template.py
@@ -0,0 +1,87 @@
+# coding: utf-8
+
+from __future__ import absolute_import, unicode_literals
+
+from django.contrib.auth.models import User
+from django.template import Context, RequestContext, Template
+
+from ..base import BaseTestCase
+from ..models import NonAsciiRepr
+
+
+class TemplatesPanelTestCase(BaseTestCase):
+
+ def setUp(self):
+ super(TemplatesPanelTestCase, self).setUp()
+ self.panel = self.toolbar.get_panel_by_id('TemplatesPanel')
+ self.panel.enable_instrumentation()
+ self.sql_panel = self.toolbar.get_panel_by_id('SQLPanel')
+ self.sql_panel.enable_instrumentation()
+
+ def tearDown(self):
+ self.sql_panel.disable_instrumentation()
+ self.panel.disable_instrumentation()
+ super(TemplatesPanelTestCase, self).tearDown()
+
+ def test_queryset_hook(self):
+ t = Template("No context variables here!")
+ c = Context({
+ 'queryset': User.objects.all(),
+ 'deep_queryset': {
+ 'queryset': User.objects.all(),
+ }
+ })
+ t.render(c)
+
+ # ensure the query was NOT logged
+ self.assertEqual(len(self.sql_panel._queries), 0)
+
+ ctx = self.panel.templates[0]['context'][1]
+ self.assertIn('<>', ctx)
+ self.assertIn('<>', ctx)
+
+ def test_object_with_non_ascii_repr_in_context(self):
+ self.panel.process_request(self.request)
+ t = Template("{{ object }}")
+ c = Context({'object': NonAsciiRepr()})
+ t.render(c)
+ self.panel.process_response(self.request, self.response)
+ self.panel.generate_stats(self.request, self.response)
+ self.assertIn('nôt åscíì', self.panel.content)
+
+ def test_insert_content(self):
+ """
+ Test that the panel only inserts content after generate_stats and
+ not the process_response.
+ """
+ t = Template("{{ object }}")
+ c = Context({'object': NonAsciiRepr()})
+ t.render(c)
+ self.panel.process_response(self.request, self.response)
+ # ensure the panel does not have content yet.
+ self.assertNotIn('nôt åscíì', self.panel.content)
+ self.panel.generate_stats(self.request, self.response)
+ # ensure the panel renders correctly.
+ self.assertIn('nôt åscíì', self.panel.content)
+
+ def test_custom_context_processor(self):
+ self.panel.process_request(self.request)
+ t = Template("{{ content }}")
+ c = RequestContext(self.request, processors=[context_processor])
+ t.render(c)
+ self.panel.process_response(self.request, self.response)
+ self.panel.generate_stats(self.request, self.response)
+ self.assertIn('tests.panels.test_template.context_processor', self.panel.content)
+
+ def test_disabled(self):
+ config = {
+ 'DISABLE_PANELS': set([
+ 'debug_toolbar.panels.templates.TemplatesPanel'])
+ }
+ self.assertTrue(self.panel.enabled)
+ with self.settings(DEBUG_TOOLBAR_CONFIG=config):
+ self.assertFalse(self.panel.enabled)
+
+
+def context_processor(request):
+ return {'content': 'set by processor'}
diff --git a/pool/shard009/Python/0085723_puzzle_record_the_players_score.py b/pool/shard009/Python/0085723_puzzle_record_the_players_score.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f4f00b00ca2c1530ec707305af5f137920e46f6
--- /dev/null
+++ b/pool/shard009/Python/0085723_puzzle_record_the_players_score.py
@@ -0,0 +1,137 @@
+# Another code written by Jagger Kyne
+# Copyright 2006 - 2013 Jagger Kyne
+__author__ = 'Jagger Kyne'
+
+
+
+from tkinter import *
+import random
+import time
+
+
+# create the ball class takes parameters for the canvas and color of the ball
+class Ball:
+ def __init__(self,canvas, paddle, color,score):
+ self.canvas = canvas
+ self.paddle = paddle
+ self.score =score
+ self.id = canvas.create_oval(10,10,25,25,fill=color) # create a ball
+ self.canvas.move(self.id,245,100) # move the oval to the middle of the canvas
+ # self.x = 0 # 0 tell the ball does not move horizontally,
+ # self.y = -1 # and the -1 says move 1 pixel up
+ starts = [-3,-2,-1,1,2,3]
+ random.shuffle(starts)
+ self.x = starts[0]
+ self.y = -3
+ self.canvas_height = self.canvas.winfo_height()
+ self.canvas_width =self.canvas.winfo_width()
+ self.hit_bottom = False
+
+
+ def draw(self):
+ self.canvas.move(self.id,self.x,self.y) # don't move ball horizontally, 1 pixel up
+ pos = self.canvas.coords(self.id) # returns the current x and y coordinate of current object drawn on the canvas
+ # print(pos)# print out the coordinate
+ if pos[1] <= 0: # top left coordinate of the ball hit the top
+ self.y = 3 # bounce back down
+ # Check if the ball hits the paddle
+ if self.hit_paddle(pos) == True:
+ self.y = -3
+ if pos[3] >= self.canvas_height: # bottom right coordinate of the ball
+ # self.y = -3 # bounce back up
+ self.hit_bottom = True
+ if pos[0] <= 0:
+ self.x = 3 # Left bounce
+ if pos[2] >= self.canvas_width:
+ self.x = -3 # right bounce
+
+# check if the ball hits the paddle.
+ def hit_paddle(self,pos):
+ paddle_pos = self.canvas.coords(self.paddle.id)
+ if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
+ if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
+ # accelerate speed
+ self.x += self.paddle.x
+
+ self.score.hit()
+
+ return True
+ return False
+
+# Creating a Paddle class
+class Paddle:
+
+ def __init__(self,canvas,color):
+ self.canvas = canvas
+ self.id = canvas.create_rectangle(0,0,100,10, fill=color)
+ self.canvas.move(self.id,200,300)
+ self.x = 0
+ self.canvas_width =self.canvas.winfo_width()
+
+ self.started = False
+ # self.start_game = False
+ self.canvas.bind_all('',self.turn_left)
+ self.canvas.bind_all('',self.turn_right)
+ self.canvas.bind_all('',self.start_game)
+
+ def draw(self):
+ self.canvas.move(self.id,self.x,0) # y coordinate is set
+ pos = self.canvas.coords(self.id)
+ if pos[0] <= 0:
+ self.x = 0
+ elif pos[2] >= self.canvas_width:
+ self.x = 0
+
+ def turn_left(self,evt):
+ self.x = -3
+
+ def turn_right(self,evt):
+ self.x = 3
+
+ def start_game(self,evt):
+ self.start_game = True
+ # self.started = True
+
+class Score:
+ def __init__(self,canvas,color):
+ self.score = 0
+ self.canvas = canvas
+ self.id = canvas.create_text(450,10, text = self.score, fill=color)
+
+ #record score
+ def hit(self):
+ self.score +=1
+ self.canvas.itemconfig(self.id,text=self.score)
+ pass
+
+
+tk = Tk()
+tk.title("!!Bounce!!") # windows title
+tk.resizable(0,0) # size of the window cannot be changed either horizontally or vertically.
+tk.wm_attributes("-topmost",1) # tell this game window is on top of everything else
+canvas = Canvas(tk,width=500,height=400,bd=0,highlightthickness=0) # no border around the outside of the canvas
+canvas.pack()
+tk.update() # tells tkinter to initialize itself itself for the animation in our game.
+
+score = Score(canvas, 'green')
+
+paddle = Paddle(canvas,'blue')
+
+ball = Ball(canvas,paddle,'red',score)
+
+# Hidden text in the middle.
+game_over_text = canvas.create_text(250,200,text ='Game Over', state='hidden')
+
+
+while 1:
+ if ball.hit_bottom == False and paddle.start_game==True:
+ ball.draw()
+ paddle.draw()
+ if ball.hit_bottom == True:
+ time.sleep(0.03 )
+ # change the state of the item to be shown.
+ canvas.itemconfig(game_over_text,state='normal')
+ tk.update_idletasks()
+ tk.update()
+ time.sleep(0.01)
+
diff --git a/pool/shard009/Python/0085732_validators.py b/pool/shard009/Python/0085732_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..b27036e71a9c08a9c4841bcd0356dbc41f53e404
--- /dev/null
+++ b/pool/shard009/Python/0085732_validators.py
@@ -0,0 +1,37 @@
+# --------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# --------------------------------------------------------------------------------------------
+from azure.cli.core.commands.client_factory import get_mgmt_service_client
+from azure.mgmt.datalake.store import DataLakeStoreAccountManagementClient
+from azure.cli.core.commands.arm import parse_resource_id
+from azure.cli.core.util import CLIError
+
+
+# Helpers
+def _get_resource_group_from_account_name(client, account_name):
+ """
+ Fetch resource group from vault name
+ :param str vault_name: name of the key vault
+ :return: resource group name or None
+ :rtype: str
+ """
+ for acct in client.list():
+ id_comps = parse_resource_id(acct.id)
+ if id_comps['name'] == account_name:
+ return id_comps['resource_group']
+ raise CLIError(
+ "The Resource 'Microsoft.DataLakeStore/accounts/{}'".format(account_name) +
+ " not found within subscription: {}".format(client.config.subscription_id))
+
+
+# COMMAND NAMESPACE VALIDATORS
+def validate_resource_group_name(ns):
+ if not ns.resource_group_name:
+ try:
+ account_name = ns.name
+ except AttributeError:
+ account_name = ns.account_name
+ client = get_mgmt_service_client(DataLakeStoreAccountManagementClient).account
+ group_name = _get_resource_group_from_account_name(client, account_name)
+ ns.resource_group_name = group_name
diff --git a/pool/shard009/Python/0085736_TestExprsBug35310.py b/pool/shard009/Python/0085736_TestExprsBug35310.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9987ce3ed523e8a6540eb73c7fab68241260855
--- /dev/null
+++ b/pool/shard009/Python/0085736_TestExprsBug35310.py
@@ -0,0 +1,30 @@
+
+import lldb
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+class ExprBug35310(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "main.cpp"
+ self.main_source_spec = lldb.SBFileSpec(self.main_source)
+
+ def test_issue35310(self):
+ """Test invoking functions with non-standard linkage names.
+
+ The GNU abi_tag extension used by libstdc++ is a common source
+ of these, but they could originate from other reasons as well.
+ """
+ self.build()
+
+ lldbutil.run_to_source_breakpoint(self,
+ '// Break here', self.main_source_spec)
+
+ self.expect_expr("a.test_abi_tag()", result_value='1')
+ self.expect_expr("a.test_asm_name()", result_value='2')
diff --git a/pool/shard009/Python/0085745_myparser.py b/pool/shard009/Python/0085745_myparser.py
new file mode 100644
index 0000000000000000000000000000000000000000..77b98446bdd160b9feb69f11efdf70ffd8d16b28
--- /dev/null
+++ b/pool/shard009/Python/0085745_myparser.py
@@ -0,0 +1,143 @@
+import string
+import re
+
+class parser:
+ def __init__(self,results,word):
+ self.results=results
+ self.word=word
+ self.temp=[]
+
+ def genericClean(self):
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('%2f', ' ', self.results)
+ self.results = re.sub('%3a', ' ', self.results)
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('', '', self.results)
+
+
+ for e in ('>',':','=', '<', '/', '\\',';','&','%3A','%3D','%3C'):
+ self.results = string.replace(self.results, e, ' ')
+
+ def urlClean(self):
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('', '', self.results)
+ self.results = re.sub('%2f', ' ', self.results)
+ self.results = re.sub('%3a', ' ', self.results)
+ for e in ('<','>',':','=',';','&','%3A','%3D','%3C'):
+ self.results = string.replace(self.results, e, ' ')
+
+ def emails(self):
+ self.genericClean()
+ reg_emails = re.compile('[a-zA-Z0-9.-_]*' + '@' + '[a-zA-Z0-9.-]*' + self.word)
+ self.temp = reg_emails.findall(self.results)
+ emails=self.unique()
+ return emails
+
+ def fileurls(self,file):
+ urls=[]
+ reg_urls = re.compile('[a-zA-Z0-9._ -]* profiles | LinkedIn')
+ self.temp = reg_people.findall(self.results)
+ reg_people2 = re.compile('">[a-zA-Z0-9._ -]* - [a-zA-Z0-9._ -]*| LinkedIn')
+ self.temp2 = reg_people2.findall(self.results)
+ self.tempmix = self.temp + self.temp2
+ resul = []
+ for x in self.tempmix:
+ y = string.replace(x, ' LinkedIn', '')
+ y = string.replace(y, ' profiles ', '')
+ y = string.replace(y, 'LinkedIn', '')
+ y = string.replace(y, '"', '')
+ y = string.replace(y, '>', '')
+ y = string.split(y," -")[0]
+ if y !=" ":
+ resul.append(y)
+ self.temp = resul
+ results = self.unique()
+ return results
+
+ def people_123people(self):
+ reg_people = re.compile('www\.123people\.com/s/[a-zA-Z0-9.-_]*\+[a-zA-Z0-9.-_]*\+?[a-zA-Z0-9.-_]*\"')
+ self.temp = reg_people.findall(self.results)
+ self.temp2 = []
+ for x in self.temp:
+ y=x.replace("www.123people.com/s/","")
+ y=y.replace('"','')
+ self.temp2.append(y)
+ return self.temp2
+
+ def people_jigsaw(self):
+ res=[]
+ #reg_people = re.compile("'tblrow' title='[a-zA-Z0-9.-]*'>")
+ reg_people = re.compile("href=javascript:showContact\('[0-9]*'\)>[a-zA-Z0-9., ]*")
+ self.temp = reg_people.findall(self.results)
+ for x in self.temp:
+ a=x.split('>')[1].replace("[a-zA-Z0-9._ -]* - Google Profile')
+ self.temp = reg_people.findall(self.results)
+ resul = []
+ for x in self.temp:
+ y = string.replace(x, ' Google Profile', '')
+ y = string.replace(y, '-', '')
+ y = string.replace(y, '">', '')
+ if y !=" ":
+ resul.append(y)
+ return resul
+
+
+ def hostnames(self):
+ self.genericClean()
+ reg_hosts = re.compile('[a-zA-Z0-9.-]*\.'+ self.word)
+ self.temp = reg_hosts.findall(self.results)
+ hostnames=self.unique()
+ return hostnames
+
+ def set(self):
+ reg_sets = re.compile('>[a-zA-Z0-9]*')
+ self.temp = reg_sets.findall(self.results)
+ sets=[]
+ for x in self.temp:
+ y = string.replace(x, '>','')
+ y = string.replace(y, '(.*?)')
+ temp = reg_hosts.findall(self.results)
+ for x in temp:
+ if x.count(':'):
+ res=x.split(':')[1].split('/')[2]
+ else:
+ res=x.split("/")[0]
+ self.temp.append(res)
+ hostnames=self.unique()
+ return hostnames
+
+ def unique(self):
+ self.new=[]
+ for x in self.temp:
+ if x[0] != "@":
+ if x not in self.new:
+ self.new.append(x)
+ return self.new
diff --git a/pool/shard009/Python/0085748_make_database.py b/pool/shard009/Python/0085748_make_database.py
new file mode 100644
index 0000000000000000000000000000000000000000..823ad3654539f50164ca7da6d56e7e9dfb7ff568
--- /dev/null
+++ b/pool/shard009/Python/0085748_make_database.py
@@ -0,0 +1,105 @@
+#! /usr/bin/env python
+
+#===========================================================================
+# Program: SPINGO - SPecies level IdentificatioN of metaGenOmic amplicons.
+# File: make_database.py
+# Author: Guy Allard
+# Copyright (C) 2014 Department of Microbiology, University College Cork
+#
+# 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 __future__ import print_function
+import os.path
+import sys
+import argparse
+
+#------------------------------------------------------------------------------
+
+def open_input_file( parser, file_name):
+ """Try and open the specified input file"""
+ if not os.path.exists(file_name):
+ parser.error("File '%s' does not exist" % file_name)
+ else:
+ try:
+ return open(file_name, "r")
+ except IOError:
+ parser.error("Could not open file '%s'" % file_name)
+
+#------------------------------------------------------------------------------
+
+class DnaSequence:
+ def __init__(self, header="", sequence=""):
+ self.header = header
+ self.sequence = sequence
+
+#------------------------------------------------------------------------------
+
+def fasta_iterator( fasta_file ):
+ seq = None
+ for line in fasta_file:
+ if line[0] == '>':
+ if seq:
+ yield seq
+ seq = DnaSequence(line.strip()[1:])
+ else:
+ seq.sequence += line.strip()
+
+ if seq:
+ yield seq
+
+#------------------------------------------------------------------------------
+
+def parse_args():
+ """Process command line arguments"""
+ description = ("""Create database from RDP data""")
+
+ parser = argparse.ArgumentParser(description=description)
+
+ parser.add_argument("taxonomy",
+ help="Taxonomy file name",
+ metavar="TAX_FILE",
+ type=lambda x: open_input_file(parser, x))
+
+ return parser.parse_args()
+
+#------------------------------------------------------------------------------
+
+def main():
+ # handle command line params
+ args = parse_args()
+
+ # load the taxonomy dictionary
+ taxonomy_map = dict()
+ for line in args.taxonomy:
+ line = [x.strip() for x in line.split("\t")]
+ taxonomy_map[line[0]] = "\t".join(line[1:])
+
+ # process the file
+ for record in fasta_iterator(sys.stdin):
+ seq_id = [x.strip() for x in record.header.split()][0]
+ try:
+ tax = taxonomy_map[seq_id]
+ except KeyError:
+ continue
+
+ print(">%s\t%s\n%s" % (seq_id, tax, record.sequence.upper()), file=sys.stdout)
+
+#------------------------------------------------------------------------------
+
+if __name__ == '__main__':
+ try:
+ main()
+ except KeyboardInterrupt:
+ sys.exit("make_database.py - interrupted by user")
diff --git a/pool/shard009/Python/0085751_view.py b/pool/shard009/Python/0085751_view.py
new file mode 100644
index 0000000000000000000000000000000000000000..88915e702b995148ea53e3fb0a9bfd7254fefb71
--- /dev/null
+++ b/pool/shard009/Python/0085751_view.py
@@ -0,0 +1,37 @@
+# Webhooks for external integrations.
+from typing import Any, Dict, Text
+
+from django.http import HttpRequest, HttpResponse
+from django.utils.translation import ugettext as _
+
+from zerver.decorator import api_key_only_webhook_view
+from zerver.lib.actions import check_send_stream_message
+from zerver.lib.request import REQ, has_request_variables
+from zerver.lib.response import json_error, json_success
+from zerver.models import UserProfile
+
+AIRBRAKE_SUBJECT_TEMPLATE = '{project_name}'
+AIRBRAKE_MESSAGE_TEMPLATE = '[{error_class}]({error_url}): "{error_message}" occurred.'
+
+@api_key_only_webhook_view('Airbrake')
+@has_request_variables
+def api_airbrake_webhook(request, user_profile,
+ payload=REQ(argument_type='body'),
+ stream=REQ(default='airbrake')):
+ # type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse
+ subject = get_subject(payload)
+ body = get_body(payload)
+ check_send_stream_message(user_profile, request.client,
+ stream, subject, body)
+ return json_success()
+
+def get_subject(payload: Dict[str, Any]) -> str:
+ return AIRBRAKE_SUBJECT_TEMPLATE.format(project_name=payload['error']['project']['name'])
+
+def get_body(payload: Dict[str, Any]) -> str:
+ data = {
+ 'error_url': payload['airbrake_error_url'],
+ 'error_class': payload['error']['error_class'],
+ 'error_message': payload['error']['error_message'],
+ }
+ return AIRBRAKE_MESSAGE_TEMPLATE.format(**data)
diff --git a/pool/shard009/Python/0085756_test_manifest_report.py b/pool/shard009/Python/0085756_test_manifest_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6c32e11c6ff97d8ead1c4fa11880eddc8d9c491
--- /dev/null
+++ b/pool/shard009/Python/0085756_test_manifest_report.py
@@ -0,0 +1,146 @@
+from django.contrib.auth.models import User
+from django.test import TestCase, tag
+
+from ..models import Box, BoxItem, BoxType, Aliquot
+from ..models import Manifest, Shipper, Consignee, ManifestItem
+from ..reports import ManifestReport, ManifestReportError
+
+
+class TestManifest(TestCase):
+
+ def test_manifest(self):
+ consignee = Consignee.objects.create(name='consignee')
+ shipper = Shipper.objects.create(name='shipper')
+ Manifest.objects.create(
+ consignee=consignee,
+ shipper=shipper)
+
+ def test_manifest_with_items(self):
+ consignee = Consignee.objects.create(name='consignee')
+ shipper = Shipper.objects.create(name='shipper')
+ manifest = Manifest.objects.create(
+ consignee=consignee,
+ shipper=shipper)
+ ManifestItem.objects.create(
+ manifest=manifest,
+ identifier='aaaaaaaaaaaa')
+
+ def test_manifest_with_items_slug(self):
+ consignee = Consignee.objects.create(name='consignee')
+ shipper = Shipper.objects.create(name='shipper')
+ manifest = Manifest.objects.create(
+ consignee=consignee,
+ shipper=shipper)
+ manifest_item = ManifestItem.objects.create(
+ manifest=manifest,
+ identifier='aaaaaaaaaaaabb')
+ self.assertIn(
+ 'aaaaaaaaaaaabb', manifest_item.slug)
+ self.assertIn(
+ manifest_item.human_readable_identifier, manifest_item.slug)
+
+
+class TestManifestReport(TestCase):
+
+ def setUp(self):
+ self.user = User.objects.create(first_name='Noam', last_name='Chomsky')
+ consignee = Consignee.objects.create(name='consignee')
+ shipper = Shipper.objects.create(name='shipper')
+ self.manifest = Manifest.objects.create(
+ consignee=consignee,
+ shipper=shipper)
+
+ def test_report(self):
+ self.assertEqual(self.manifest.site.name, 'example.com')
+ report = ManifestReport(manifest=self.manifest, user=self.user)
+ report.render()
+
+ def test_report_shipped(self):
+ self.manifest.shipped = True
+ self.manifest.save()
+ self.assertEqual(self.manifest.site.name, 'example.com')
+ report = ManifestReport(manifest=self.manifest, user=self.user)
+ report.render()
+
+ def test_report_items_not_in_box(self):
+ self.manifest.shipped = True
+ self.manifest.save()
+ for i in range(0, 3):
+ ManifestItem.objects.create(
+ manifest=self.manifest,
+ identifier=f'{self.manifest.manifest_identifier}{i}')
+ self.assertEqual(self.manifest.site.name, 'example.com')
+ report = ManifestReport(manifest=self.manifest, user=self.user)
+ self.assertRaises(ManifestReportError, report.render)
+ try:
+ report.render()
+ except ManifestReportError as e:
+ self.assertEqual(e.code, 'unboxed_item')
+
+ def test_box_type(self):
+ BoxType.objects.create(
+ name='box_type',
+ across=8, down=8, total=64)
+
+ def test_box(self):
+ box_type = BoxType.objects.create(
+ name='box_type',
+ across=8, down=8, total=64)
+ Box.objects.create(box_type=box_type)
+
+ def test_box_item(self):
+ box_type = BoxType.objects.create(
+ name='box_type', across=8, down=8, total=64)
+ box = Box.objects.create(box_type=box_type)
+ BoxItem.objects.create(
+ box=box,
+ identifier=box.box_identifier,
+ position=0)
+
+ @tag('1')
+ def test_report_invalid_invalid_aliquot_identifier(self):
+ self.manifest.shipped = True
+ self.manifest.save()
+ box_type = BoxType.objects.create(
+ name='box_type', across=8, down=8, total=64)
+ box = Box.objects.create(box_type=box_type)
+ # add box items with invalid aliquot identifiers
+ for i in range(0, 3):
+ BoxItem.objects.create(
+ box=box,
+ identifier=f'{i}',
+ position=i)
+ ManifestItem.objects.create(
+ manifest=self.manifest, identifier=box.box_identifier)
+ self.assertEqual(self.manifest.site.name, 'example.com')
+ report = ManifestReport(manifest=self.manifest, user=self.user)
+ self.assertRaises(ManifestReportError, report.render)
+ try:
+ report.render()
+ except ManifestReportError as e:
+ self.assertEqual(e.code, 'invalid_aliquot_identifier')
+
+ def test_report_invalid_invalid_requisition_identifier(self):
+ self.manifest.shipped = True
+ self.manifest.save()
+ prefix = 'ABCDEFG'
+ for i in range(0, 3):
+ Aliquot.objects.create(count=i, aliquot_identifier=f'{prefix}{i}')
+ box_type = BoxType.objects.create(
+ name='box_type', across=8, down=8, total=64)
+ box = Box.objects.create(box_type=box_type)
+ # add box items with invalid aliquot identifiers
+ for index, aliquot in enumerate(Aliquot.objects.all()):
+ BoxItem.objects.create(
+ box=box,
+ identifier=aliquot.aliquot_identifier,
+ position=index)
+ ManifestItem.objects.create(
+ manifest=self.manifest, identifier=box.box_identifier)
+ self.assertEqual(self.manifest.site.name, 'example.com')
+ report = ManifestReport(manifest=self.manifest, user=self.user)
+ self.assertRaises(ManifestReportError, report.render)
+ try:
+ report.render()
+ except ManifestReportError as e:
+ self.assertEqual(e.code, 'invalid_requisition_identifier')
diff --git a/pool/shard009/Python/0085760_explore_training_data.py b/pool/shard009/Python/0085760_explore_training_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2cebdcba0d284c958ad91edc861c544005c21dd
--- /dev/null
+++ b/pool/shard009/Python/0085760_explore_training_data.py
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+import csv
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+csv_lines = []
+
+with open("../training_data/training_data.csv") as csvfile:
+ reader = csv.reader(csvfile, delimiter=",", quotechar='|')
+ for line in reader:
+ csv_lines.append(line)
+
+steering_commands = []
+
+left_count = 0
+right_count = 0
+
+for csv_line in csv_lines:
+ steering_angle = float(csv_line[1])
+
+ if steering_angle > 0:
+ left_count += 1
+ else:
+ right_count += 1
+
+print("Left turns count: " + str(left_count))
+print("Right turns count: " + str(right_count))
diff --git a/pool/shard009/Python/0085763_compiler_d.py b/pool/shard009/Python/0085763_compiler_d.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7d4f2a7c5779d646a96c3038039e07eb2d4bf80
--- /dev/null
+++ b/pool/shard009/Python/0085763_compiler_d.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python
+# encoding: utf-8
+# Carlos Rafael Giani, 2007 (dv)
+# Thomas Nagy, 2010 (ita)
+
+"""
+Try to detect a D compiler from the list of supported compilers::
+
+ def options(opt):
+ opt.load('compiler_d')
+ def configure(cnf):
+ cnf.load('compiler_d')
+ def build(bld):
+ bld.program(source='main.d', target='app')
+
+Only two D compilers are really present at the moment:
+
+* gdc, the ldc compiler having a very similar command-line interface
+* dmd
+"""
+
+import os, sys, imp, types
+from waflib import Utils, Configure, Options, Logs
+
+def configure(conf):
+ """
+ Try to find a suitable D compiler or raise a :py:class:`waflib.Errors.ConfigurationError`.
+ """
+ for compiler in conf.options.dcheck.split(','):
+ conf.env.stash()
+ conf.start_msg('Checking for %r (d compiler)' % compiler)
+ try:
+ conf.load(compiler)
+ except conf.errors.ConfigurationError as e:
+ conf.env.revert()
+ conf.end_msg(False)
+ Logs.debug('compiler_cxx: %r' % e)
+ else:
+ if conf.env.D:
+ conf.end_msg(conf.env.get_flat('D'))
+ conf.env['COMPILER_D'] = compiler
+ conf.env.D_COMPILER = conf.env.D # TODO remove this, left for compatibility
+ break
+ conf.end_msg(False)
+ else:
+ conf.fatal('no suitable d compiler was found')
+
+def options(opt):
+ """
+ Restrict the compiler detection from the command-line::
+
+ $ waf configure --check-d-compiler=dmd
+ """
+ d_compiler_opts = opt.add_option_group('D Compiler Options')
+ d_compiler_opts.add_option('--check-d-compiler', default='gdc,dmd', action='store',
+ help='check for the compiler [Default:gdc,dmd]', dest='dcheck')
+ for d_compiler in ['gdc', 'dmd']:
+ opt.load('%s' % d_compiler)
+
diff --git a/pool/shard009/Python/0085764_runtests.py b/pool/shard009/Python/0085764_runtests.py
new file mode 100644
index 0000000000000000000000000000000000000000..6420b5d265b83f141cac4cfaae3ae624f68f51a1
--- /dev/null
+++ b/pool/shard009/Python/0085764_runtests.py
@@ -0,0 +1,19 @@
+import unittest
+from tests import test_base
+
+# runs the baseline software tests:
+# * opening and closing a socket
+# * testing for PUT methods
+# * testing for GET methods
+# * testing for CLEAR methods
+# * testing for QUIT methods
+# * running the example sequence
+#
+def base_suite():
+ suite = unittest.TestSuite()
+ suite.addTest(test_base.base_suite())
+ return suite
+
+# base test runner, will run the base suite
+if __name__ == '__main__':
+ unittest.main(defaultTest='base_suite')
diff --git a/pool/shard009/Python/0085765_init__.py b/pool/shard009/Python/0085765_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85c7e38c7899c168d1ef2a00d29dd44036e93997
--- /dev/null
+++ b/pool/shard009/Python/0085765_init__.py
@@ -0,0 +1,14 @@
+"""
+Import all submodules main classes into the package space
+"""
+import inspect
+from base import *
+from tag import *
+from blob import *
+from tree import *
+from commit import *
+from submodule import *
+from util import Actor
+
+__all__ = [ name for name, obj in locals().items()
+ if not (name.startswith('_') or inspect.ismodule(obj)) ]
\ No newline at end of file
diff --git a/pool/shard009/Python/0085774_server.py b/pool/shard009/Python/0085774_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..046ab4362010bd1086c2ac750362bf0cc13696ad
--- /dev/null
+++ b/pool/shard009/Python/0085774_server.py
@@ -0,0 +1,255 @@
+#!/usr/bin/env python
+# encoding: utf-8
+'''
+Created on 2015年3月7日
+
+@author: Sunday
+'''
+import os
+import zlib
+import struct
+import logging
+
+from twisted.internet.protocol import Factory
+from twisted.protocols.policies import TimeoutMixin
+from twisted.internet.abstract import FileDescriptor
+from twisted.internet import fdesc, protocol, reactor
+
+import util
+import webconsole
+
+logger = logging.getLogger("pyvpn")
+
+
+class AppException(Exception):
+ pass
+
+
+class TundevException(AppException):
+ pass
+
+
+class IpFullException(TundevException):
+ pass
+
+
+class TunDevice(FileDescriptor, object):
+ def __init__(self, reactor=None):
+ FileDescriptor.__init__(self, reactor=reactor)
+ self.dev, self._tun = util.make_tun()
+ self.tunfd = self._tun.fileno()
+ fdesc.setNonBlocking(self.tunfd)
+ self._write_buf = ''
+
+ def get_free_addr(self):
+ addr = self._netaddr
+ while True:
+ addr = addr + 1
+ if addr == self._gwaddr:
+ continue
+ if addr in self.allocated_addr:
+ continue
+ if addr >= self._boardcast:
+ raise IpFullException("IP分配已满")
+ self.allocated_addr.append(addr)
+ return addr, util.inet_atol(self.netmask)
+
+ def remove_addr(self, addr):
+ self.allocated_addr.remove(addr)
+
+ def ifconfig(self, gwaddr, netmask):
+ assert util.is_valid_ip(gwaddr)
+ assert util.is_valid_netmask(netmask)
+ self.gwaddr = gwaddr
+ self.netmask = netmask
+ self._netaddr = util.addr_netaddr(self.gwaddr, self.netmask)
+ self._boardcast = util.addr_boardcast(self.gwaddr, self.netmask)
+ self._gwaddr = util.inet_atol(self.gwaddr)
+ # 已分配地址,整形地址
+ self.allocated_addr = []
+ util.ifconfig(self.dev, gwaddr, netmask)
+
+ def fileno(self):
+ return self.tunfd
+
+ def _doRead(self, in_):
+ '''
+ @summary: 操作系统发给虚拟网卡的数据包,拆出其目标地址,发给目标用户
+ //先群发。
+ :param data:
+ '''
+ self.factory.tunRecv(in_)
+
+ def doRead(self):
+ print '~~~~~~~~~~~~~~~~~~~~~~~~~'
+ fdesc.readFromFD(self.tunfd, self._doRead)
+ print '~~~~~~~~~~~~~~~~~~~~~~~~~'
+
+ @staticmethod
+ def get_frame(buf):
+ if len(buf) <= 20:
+ return -1
+ pack_len = struct.unpack('!H', buf[2:4])[0]
+ logger.info('FRAME:[%d], BUF:[%d]' % (pack_len, len(buf)))
+ if len(buf) < pack_len:
+ return -1
+ return pack_len
+
+ def writeSomeData(self, data):
+ self._write_buf += data
+ while True:
+ length = self.get_frame(self._write_buf)
+ if length == -1:
+ break
+ frame = self._write_buf[:length]
+ self._write_buf = self._write_buf[length:]
+ fdesc.writeToFD(self.tunfd, frame)
+
+ def connectionLost(self, reason):
+ if self.tunfd >= 0:
+ try:
+ os.close(self.tunfd)
+ except OSError as _:
+ logger.error("cannot close tunfd")
+ FileDescriptor.connectionLost(self, reason)
+
+
+class VPNProtocol(protocol.Protocol, TimeoutMixin):
+ def connectionMade(self):
+ self._is_authed = False
+ self._is_gzip = True
+ self._is_encrypt = False
+ self._interval = 120
+ self._client_addr = None
+ self._client_mask = None
+ self._flow_count = 0
+ self.buf = ''
+ self._user = ''
+ self._addr, self._netmask = None, None
+ self.setTimeout(self._interval)
+
+ def connectionLost(self, reason):
+ '''
+ @summary: 释放超时信号,释放已分配IP,写入流量等数据
+ :param reason:
+ '''
+ self.setTimeout(None)
+ self.factory.clients.remove(self)
+ if self._addr:
+ self.tundev.remove_addr(self._addr)
+
+ def getpackage(self):
+ if len(self.buf) <= 2:
+ return None
+ d_length = struct.unpack('@H', self.buf[:2])[0]
+ if len(self.buf) < d_length:
+ return None
+ pack = self.buf[:d_length]
+ self.buf = self.buf[d_length:]
+ return pack
+
+ def user_auth(self, pack):
+ user_len = struct.unpack('@b', pack[3])[0]
+ assert user_len
+ user = pack[4: 4 + user_len]
+ pwd_len = struct.unpack('@b', pack[4 + user_len])[0]
+ assert pwd_len
+ pwd = pack[4 + user_len + 1:]
+ assert user and pwd
+ retpack = struct.pack('@Hbb', 4, 0, 0)
+ self.transport.write(retpack)
+ self._is_authed = True
+ self._user = user
+ return True
+
+ def heartbeat(self):
+ assert self._is_authed
+ retpack = struct.pack('@Hb', 3, 1)
+ self.transport.write(retpack)
+
+ def peer_ifconfig(self):
+ assert self._is_authed
+ self._addr, self._netmask = self.tundev.get_free_addr()
+ # 返回类型2, ip与掩码各4字节,总长度11字节
+ retpack = struct.pack('@HbII', 11, 2, self._addr, self._netmask)
+ self.transport.write(retpack)
+
+ def trans_data(self, pack):
+ assert self._is_authed
+ raw_data = zlib.decompress(pack[3:])
+ self.tundev.writeSomeData(raw_data)
+
+ def add_flow_count(self, count):
+ self._flow_count += count
+
+ def dataReceived(self, data):
+ self.setTimeout(None)
+ self.buf += data
+ self._flow_count += len(data)
+ while True:
+ pack = self.getpackage()
+ if not pack:
+ break
+ pack_type = struct.unpack('@b', pack[2])[0]
+ if pack_type == util.PackageType.AUTH:
+ self.user_auth(pack)
+ elif pack_type == util.PackageType.HEARTBEAT:
+ self.heartbeat()
+ elif pack_type == util.PackageType.IFCONFIG:
+ self.peer_ifconfig()
+ elif pack_type == util.PackageType.DATA:
+ self.trans_data(pack)
+
+
+class VPNFactory(Factory):
+ def __init__(self, tundev):
+ self.protocol = VPNProtocol
+ self.tundev = tundev
+ # 将工厂 赋值到 tundev,使之可以将数据群发出去
+ self.tundev.factory = self
+ self.clients = []
+
+ def tunRecv(self, in_):
+ for client in self.clients:
+ client.transport.write(in_)
+ client.add_flow_count()
+
+ def buildProtocol(self, addr):
+ p = self.protocol()
+ self.clients.append(p)
+ p.factory = self
+ p.tundev = self.tundev
+ return p
+
+
+def main():
+ # TUN dev
+ tundev = TunDevice(reactor)
+ tundev.ifconfig('192.168.10.3', '255.255.255.240')
+ tundev.startReading()
+ # tcp for client
+ serverfactory = VPNFactory(tundev)
+ reactor.listenTCP(1234, serverfactory) # @UndefinedVariable
+ # web console
+ reactor.listenTCP(8080, webconsole.factory) # @UndefinedVariable
+ # run
+ reactor.run() # @UndefinedVariable
+
+
+if __name__ == '__main__':
+ main()
+
+
+# TODO:
+r"""
+1, VPN
+1.1, 自动的IP配置
+2, Win32 client
+2.1, Android client
+3, 简单的认证机制,地址端口用户名密码
+4, 压缩与可选的加密机制
+5, 流量控制
+6, 限速
+7, Web控制与状态显示
+LAST, 性能
+"""
\ No newline at end of file
diff --git a/pool/shard009/Python/0085775_gettext.py b/pool/shard009/Python/0085775_gettext.py
new file mode 100644
index 0000000000000000000000000000000000000000..887aced51c60948105a0d8ea64e05715867164dc
--- /dev/null
+++ b/pool/shard009/Python/0085775_gettext.py
@@ -0,0 +1,97 @@
+# vi: syntax=python:et:ts=4
+from os.path import join
+import os
+from SCons.Builder import Builder
+from SCons.Util import WhereIs
+from config_check_utils import find_include
+
+def exists():
+ return True
+
+def generate(env):
+ env.AppendENVPath("PATH", join(env["gettextdir"], "bin"))
+ env["MSGFMT"] = WhereIs("msgfmt")
+ msgfmt = Builder(
+ action = "$MSGFMT --check-format --check-domain --statistics -o $TARGET $SOURCE",
+ src_suffix = ".po",
+ suffix = ".mo",
+ single_source = True
+ )
+ env["BUILDERS"]["Msgfmt"] = msgfmt
+
+ env["MSGMERGE"] = WhereIs("msgmerge")
+ msgmerge = Builder(
+ action = "$MSGMERGE $TARGET $SOURCE -o $TARGET",
+ src_suffix = ".pot",
+ suffix = ".po",
+ single_source = True
+ )
+ env["BUILDERS"]["MsgMerge"] = msgmerge
+
+ env["MSGINIT"] = WhereIs("msginit")
+ msginit = Builder(
+ action = "$MSGINIT -i $SOURCE -o $TARGET --no-translator",
+ src_suffix = ".pot",
+ suffix = ".po",
+ single_source = True
+ )
+ env["BUILDERS"]["MsgInit"] = msginit
+ env["ENV"]["LANG"] = os.environ.get("LANG")
+
+ def MsgInitMerge(env, target, source):
+ if os.path.exists(target + ".po"):
+ return env.MsgMerge(target, source)
+ else:
+ return env.MsgInit(target, source)
+ env.AddMethod(MsgInitMerge)
+
+ env["PO4A_GETTEXTIZE"] = WhereIs("po4a-gettextize")
+ po4a_gettextize = Builder(
+ action = "$PO4A_GETTEXTIZE -f $PO4A_FORMAT ${''.join([' -m ' + str(source) for source in SOURCES])} -p $TARGET",
+ )
+ env["BUILDERS"]["Po4aGettextize"] = po4a_gettextize
+
+ env["PO4A_TRANSLATE"] = WhereIs("po4a-translate")
+ po4a_translate = Builder(
+ action = "$PO4A_TRANSLATE -f $PO4A_FORMAT -L $PO4A_CHARSET -m ${SOURCES[0]} -p ${SOURCES[1]} -l $TARGET"
+ )
+ env["BUILDERS"]["Po4aTranslate"] = po4a_translate
+
+def CheckGettextLibintl(context):
+ env = context.env
+ backup = env.Clone().Dictionary()
+ context.Message("Checking for Gettext's libintl... ")
+
+ test_program = """
+ #include
+
+ int main()
+ {
+ textdomain("test");
+ char* text = gettext("foo");
+ }
+ \n"""
+
+ if not env.get("gettextdir") and context.TryLink(test_program, ".c"):
+ context.Result("libc built-in")
+ return True
+
+ prefixes = [env["prefix"]]
+ if env.get("gettextdir"):
+ prefixes = [env["gettextdir"]] + prefixes
+ includes = find_include(prefixes, "libintl.h", default_prefixes=not env["host"])
+ if includes:
+ env.AppendUnique(
+ CPPPATH = [join(includes[0][0], "include")],
+ LIBPATH = [join(includes[0][0], "lib")]
+ )
+ env.AppendUnique(LIBS = ["intl"])
+ if context.TryLink("/* external libintl*/\n" + test_program, ".c"):
+ context.Result("external")
+ return True
+
+ context.Result("no")
+ env.Replace(**backup)
+ return False
+
+config_checks = { "CheckGettextLibintl" : CheckGettextLibintl }
diff --git a/pool/shard009/Python/0085779_221_fix_category_column_defaults.py b/pool/shard009/Python/0085779_221_fix_category_column_defaults.py
new file mode 100644
index 0000000000000000000000000000000000000000..4caf20092b2e410cfd92df1150325850b283c727
--- /dev/null
+++ b/pool/shard009/Python/0085779_221_fix_category_column_defaults.py
@@ -0,0 +1,36 @@
+"""Fix Category column defaults.
+
+Revision ID: 516024977fc5
+Revises: 59e1cc690da9
+Create Date: 2016-04-13 00:05:16.542436
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '516024977fc5'
+down_revision = '59e1cc690da9'
+
+from alembic import op
+from sqlalchemy.sql import text
+
+
+def upgrade():
+ conn = op.get_bind()
+ conn.execute(text("set @@lock_wait_timeout = 20;"))
+
+ conn.execute(text("ALTER TABLE category "
+ "MODIFY COLUMN name VARCHAR(191) NOT NULL DEFAULT '', "
+ "MODIFY COLUMN deleted_at DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00'"))
+
+ conn.execute(text("ALTER TABLE folder "
+ "MODIFY COLUMN name VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, "
+ "MODIFY COLUMN canonical_name VARCHAR(191) NOT NULL DEFAULT '', "
+ "DROP INDEX account_id, "
+ "ADD CONSTRAINT UNIQUE account_id (account_id, name, canonical_name)"))
+
+ conn.execute(text("ALTER TABLE label "
+ "MODIFY COLUMN canonical_name VARCHAR(191) NOT NULL DEFAULT ''"))
+
+
+def downgrade():
+ pass
diff --git a/pool/shard009/Python/0085781_monitoring_v3_generated_service_monitoring_service_list_services_sync.py b/pool/shard009/Python/0085781_monitoring_v3_generated_service_monitoring_service_list_services_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..b02fc5850e9a045b52d94d85a6458f67ba89fd48
--- /dev/null
+++ b/pool/shard009/Python/0085781_monitoring_v3_generated_service_monitoring_service_list_services_sync.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+# Copyright 2022 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or 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.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for ListServices
+# NOTE: This snippet has been automatically generated for illustrative purposes only.
+# It may require modifications to work in your environment.
+
+# To install the latest published package dependency, execute the following:
+# python3 -m pip install google-cloud-monitoring
+
+
+# [START monitoring_v3_generated_ServiceMonitoringService_ListServices_sync]
+from google.cloud import monitoring_v3
+
+
+def sample_list_services():
+ # Create a client
+ client = monitoring_v3.ServiceMonitoringServiceClient()
+
+ # Initialize request argument(s)
+ request = monitoring_v3.ListServicesRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_services(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+# [END monitoring_v3_generated_ServiceMonitoringService_ListServices_sync]
diff --git a/pool/shard009/Python/0085782_array.py b/pool/shard009/Python/0085782_array.py
new file mode 100644
index 0000000000000000000000000000000000000000..47015ed334ddfc0b685f7ed8af3cfc88ee11b5d4
--- /dev/null
+++ b/pool/shard009/Python/0085782_array.py
@@ -0,0 +1,132 @@
+"""
+Test extension array for storing nested data in a pandas container.
+
+The ListArray stores an ndarray of lists.
+"""
+from __future__ import annotations
+
+import numbers
+import random
+import string
+
+import numpy as np
+
+from pandas._typing import type_t
+
+from pandas.core.dtypes.base import ExtensionDtype
+
+import pandas as pd
+from pandas.api.types import (
+ is_object_dtype,
+ is_string_dtype,
+)
+from pandas.core.arrays import ExtensionArray
+
+
+class ListDtype(ExtensionDtype):
+ type = list
+ name = "list"
+ na_value = np.nan
+
+ @classmethod
+ def construct_array_type(cls) -> type_t[ListArray]:
+ """
+ Return the array type associated with this dtype.
+
+ Returns
+ -------
+ type
+ """
+ return ListArray
+
+
+class ListArray(ExtensionArray):
+ dtype = ListDtype()
+ __array_priority__ = 1000
+
+ def __init__(self, values, dtype=None, copy=False):
+ if not isinstance(values, np.ndarray):
+ raise TypeError("Need to pass a numpy array as values")
+ for val in values:
+ if not isinstance(val, self.dtype.type) and not pd.isna(val):
+ raise TypeError("All values must be of type " + str(self.dtype.type))
+ self.data = values
+
+ @classmethod
+ def _from_sequence(cls, scalars, dtype=None, copy=False):
+ data = np.empty(len(scalars), dtype=object)
+ data[:] = scalars
+ return cls(data)
+
+ def __getitem__(self, item):
+ if isinstance(item, numbers.Integral):
+ return self.data[item]
+ else:
+ # slice, list-like, mask
+ return type(self)(self.data[item])
+
+ def __len__(self) -> int:
+ return len(self.data)
+
+ def isna(self):
+ return np.array(
+ [not isinstance(x, list) and np.isnan(x) for x in self.data], dtype=bool
+ )
+
+ def take(self, indexer, allow_fill=False, fill_value=None):
+ # re-implement here, since NumPy has trouble setting
+ # sized objects like UserDicts into scalar slots of
+ # an ndarary.
+ indexer = np.asarray(indexer)
+ msg = (
+ "Index is out of bounds or cannot do a "
+ "non-empty take from an empty array."
+ )
+
+ if allow_fill:
+ if fill_value is None:
+ fill_value = self.dtype.na_value
+ # bounds check
+ if (indexer < -1).any():
+ raise ValueError
+ try:
+ output = [
+ self.data[loc] if loc != -1 else fill_value for loc in indexer
+ ]
+ except IndexError as err:
+ raise IndexError(msg) from err
+ else:
+ try:
+ output = [self.data[loc] for loc in indexer]
+ except IndexError as err:
+ raise IndexError(msg) from err
+
+ return self._from_sequence(output)
+
+ def copy(self):
+ return type(self)(self.data[:])
+
+ def astype(self, dtype, copy=True):
+ if isinstance(dtype, type(self.dtype)) and dtype == self.dtype:
+ if copy:
+ return self.copy()
+ return self
+ elif is_string_dtype(dtype) and not is_object_dtype(dtype):
+ # numpy has problems with astype(str) for nested elements
+ return np.array([str(x) for x in self.data], dtype=dtype)
+ return np.array(self.data, dtype=dtype, copy=copy)
+
+ @classmethod
+ def _concat_same_type(cls, to_concat):
+ data = np.concatenate([x.data for x in to_concat])
+ return cls(data)
+
+
+def make_data():
+ # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
+ data = np.empty(100, dtype=object)
+ data[:] = [
+ [random.choice(string.ascii_letters) for _ in range(random.randint(0, 10))]
+ for _ in range(100)
+ ]
+ return data
diff --git a/pool/shard009/Python/0085785_urls.py b/pool/shard009/Python/0085785_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8dff9980f2db953e5c666e302c4a1f621980fc9
--- /dev/null
+++ b/pool/shard009/Python/0085785_urls.py
@@ -0,0 +1,19 @@
+from django.conf.urls import patterns, include, url
+
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns('',
+ url(r'^reg_query/$', 'registry.views.reg_query', name='reg_query'),
+ url(r'^reg_connect/$', 'registry.views.reg_connect'),
+ url(r'^reg_remove/$', 'registry.views.reg_remove'),
+ url(r'^reg/$', 'registry.views.reg'),
+ url(r'^regp/$', 'registry.views.regp'),
+ url(r'^reg_config/$', 'registry.views.reg_config'),
+ url(r'^reg_becomeguide/$', 'registry.views.reg_becomeguide'),
+ url(r'^reg_notification/$', 'registry.views.reg_notification'),
+ url(r'^reg_setNotification/$', 'registry.views.reg_setNotification'),
+ url(r'^reg_getNotification/$', 'registry.views.reg_getNotification'),
+ url(r'^reg_delNotification/$', 'registry.views.reg_delNotification'),
+)
+
diff --git a/pool/shard009/Python/0085790_plot_10_epochs_overview.py b/pool/shard009/Python/0085790_plot_10_epochs_overview.py
new file mode 100644
index 0000000000000000000000000000000000000000..92bdbcc9db887081c2236414631ab3df695f3af9
--- /dev/null
+++ b/pool/shard009/Python/0085790_plot_10_epochs_overview.py
@@ -0,0 +1,439 @@
+# -*- coding: utf-8 -*-
+"""
+.. _tut-epochs-class:
+
+The Epochs data structure: discontinuous data
+=============================================
+
+This tutorial covers the basics of creating and working with :term:`epoched
+` data. It introduces the :class:`~mne.Epochs` data structure in
+detail, including how to load, query, subselect, export, and plot data from an
+:class:`~mne.Epochs` object. For more information about visualizing
+:class:`~mne.Epochs` objects, see :ref:`tut-visualize-epochs`. For info on
+creating an :class:`~mne.Epochs` object from (possibly simulated) data in a
+:class:`NumPy array `, see :ref:`tut_creating_data_structures`.
+
+.. contents:: Page contents
+ :local:
+ :depth: 2
+
+As usual we'll start by importing the modules we need:
+"""
+
+import os
+import mne
+
+###############################################################################
+# :class:`~mne.Epochs` objects are a data structure for representing and
+# analyzing equal-duration chunks of the EEG/MEG signal. :class:`~mne.Epochs`
+# are most often used to represent data that is time-locked to repeated
+# experimental events (such as stimulus onsets or subject button presses), but
+# can also be used for storing sequential or overlapping frames of a continuous
+# signal (e.g., for analysis of resting-state activity; see
+# :ref:`fixed-length-events`). Inside an :class:`~mne.Epochs` object, the data
+# are stored in an :class:`array ` of shape ``(n_epochs,
+# n_channels, n_times)``.
+#
+# :class:`~mne.Epochs` objects have many similarities with :class:`~mne.io.Raw`
+# objects, including:
+#
+# - They can be loaded from and saved to disk in ``.fif`` format, and their
+# data can be exported to a :class:`NumPy array ` through the
+# :meth:`~mne.Epochs.get_data` method or to a :class:`Pandas DataFrame
+# ` through the :meth:`~mne.Epochs.to_data_frame` method.
+#
+# - Both :class:`~mne.Epochs` and :class:`~mne.io.Raw` objects support channel
+# selection by index or name, including :meth:`~mne.Epochs.pick`,
+# :meth:`~mne.Epochs.pick_channels` and :meth:`~mne.Epochs.pick_types`
+# methods.
+#
+# - :term:`SSP projector ` manipulation is possible through
+# :meth:`~mne.Epochs.add_proj`, :meth:`~mne.Epochs.del_proj`, and
+# :meth:`~mne.Epochs.plot_projs_topomap` methods.
+#
+# - Both :class:`~mne.Epochs` and :class:`~mne.io.Raw` objects have
+# :meth:`~mne.Epochs.copy`, :meth:`~mne.Epochs.crop`,
+# :meth:`~mne.Epochs.time_as_index`, :meth:`~mne.Epochs.filter`, and
+# :meth:`~mne.Epochs.resample` methods.
+#
+# - Both :class:`~mne.Epochs` and :class:`~mne.io.Raw` objects have
+# :attr:`~mne.Epochs.times`, :attr:`~mne.Epochs.ch_names`,
+# :attr:`~mne.Epochs.proj`, and :class:`info ` attributes.
+#
+# - Both :class:`~mne.Epochs` and :class:`~mne.io.Raw` objects have built-in
+# plotting methods :meth:`~mne.Epochs.plot`, :meth:`~mne.Epochs.plot_psd`,
+# and :meth:`~mne.Epochs.plot_psd_topomap`.
+#
+#
+# Creating Epoched data from a ``Raw`` object
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# The example dataset we've been using thus far doesn't include pre-epoched
+# data, so in this section we'll load the continuous data and create epochs
+# based on the events recorded in the :class:`~mne.io.Raw` object's STIM
+# channels. As we often do in these tutorials, we'll :meth:`~mne.io.Raw.crop`
+# the :class:`~mne.io.Raw` data to save memory:
+
+sample_data_folder = mne.datasets.sample.data_path()
+sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
+ 'sample_audvis_raw.fif')
+raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=60)
+
+###############################################################################
+# As we saw in the :ref:`tut-events-vs-annotations` tutorial, we can extract an
+# events array from :class:`~mne.io.Raw` objects using :func:`mne.find_events`:
+
+events = mne.find_events(raw, stim_channel='STI 014')
+
+###############################################################################
+# .. note::
+#
+# We could also have loaded the events from file, using
+# :func:`mne.read_events`::
+#
+# sample_data_events_file = os.path.join(sample_data_folder,
+# 'MEG', 'sample',
+# 'sample_audvis_raw-eve.fif')
+# events_from_file = mne.read_events(sample_data_events_file)
+#
+# See :ref:`tut-section-events-io` for more details.
+#
+#
+# The :class:`~mne.io.Raw` object and the events array are the bare minimum
+# needed to create an :class:`~mne.Epochs` object, which we create with the
+# :class:`mne.Epochs` class constructor. However, you will almost surely want
+# to change some of the other default parameters. Here we'll change ``tmin``
+# and ``tmax`` (the time relative to each event at which to start and end each
+# epoch). Note also that the :class:`~mne.Epochs` constructor accepts
+# parameters ``reject`` and ``flat`` for rejecting individual epochs based on
+# signal amplitude. See the :ref:`tut-reject-epochs-section` section for
+# examples.
+
+epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7)
+
+###############################################################################
+# You'll see from the output that:
+#
+# - all 320 events were used to create epochs
+#
+# - baseline correction was automatically applied (by default, baseline is
+# defined as the time span from ``tmin`` to ``0``, but can be customized with
+# the ``baseline`` parameter)
+#
+# - no additional metadata was provided (see :ref:`tut-epochs-metadata` for
+# details)
+#
+# - the projection operators present in the :class:`~mne.io.Raw` file were
+# copied over to the :class:`~mne.Epochs` object
+#
+# If we print the :class:`~mne.Epochs` object, we'll also see a note that the
+# epochs are not copied into memory by default, and a count of the number of
+# epochs created for each integer Event ID.
+
+print(epochs)
+
+###############################################################################
+# Notice that the Event IDs are in quotes; since we didn't provide an event
+# dictionary, the :class:`mne.Epochs` constructor created one automatically and
+# used the string representation of the integer Event IDs as the dictionary
+# keys. This is more clear when viewing the ``event_id`` attribute:
+
+print(epochs.event_id)
+
+###############################################################################
+# This time let's pass ``preload=True`` and provide an event dictionary; our
+# provided dictionary will get stored as the ``event_id`` attribute and will
+# make referencing events and pooling across event types easier:
+
+event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
+ 'visual/right': 4, 'face': 5, 'buttonpress': 32}
+epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7, event_id=event_dict,
+ preload=True)
+print(epochs.event_id)
+del raw # we're done with raw, free up some memory
+
+###############################################################################
+# Notice that the output now mentions "1 bad epoch dropped". In the tutorial
+# section :ref:`tut-reject-epochs-section` we saw how you can specify channel
+# amplitude criteria for rejecting epochs, but here we haven't specified any
+# such criteria. In this case, it turns out that the last event was too close
+# the end of the (cropped) raw file to accommodate our requested ``tmax`` of
+# 0.7 seconds, so the final epoch was dropped because it was too short. Here
+# are the ``drop_log`` entries for the last 4 epochs (empty lists indicate
+# epochs that were *not* dropped):
+
+print(epochs.drop_log[-4:])
+
+###############################################################################
+# .. note::
+#
+# If you forget to provide the event dictionary to the :class:`~mne.Epochs`
+# constructor, you can add it later by assigning to the ``event_id``
+# attribute::
+#
+# epochs.event_id = event_dict
+#
+#
+# Basic visualization of ``Epochs`` objects
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The :class:`~mne.Epochs` object can be visualized (and browsed interactively)
+# using its :meth:`~mne.Epochs.plot` method:
+
+epochs.plot(n_epochs=10)
+
+###############################################################################
+# Notice that the individual epochs are sequentially numbered along the bottom
+# axis; the event ID associated with the epoch is marked on the top axis;
+# epochs are separated by vertical dashed lines; and a vertical solid green
+# line marks time=0 for each epoch (i.e., in this case, the stimulus onset
+# time for each trial). Epoch plots are interactive (similar to
+# :meth:`raw.plot() `) and have many of the same interactive
+# controls as :class:`~mne.io.Raw` plots. Horizontal and vertical scrollbars
+# allow browsing through epochs or channels (respectively), and pressing
+# :kbd:`?` when the plot is focused will show a help screen with all the
+# available controls. See :ref:`tut-visualize-epochs` for more details (as well
+# as other ways of visualizing epoched data).
+#
+#
+# .. _tut-section-subselect-epochs:
+#
+# Subselecting epochs
+# ^^^^^^^^^^^^^^^^^^^
+#
+# Now that we have our :class:`~mne.Epochs` object with our descriptive event
+# labels added, we can subselect epochs easily using square brackets. For
+# example, we can load all the "catch trials" where the stimulus was a face:
+
+print(epochs['face'])
+
+###############################################################################
+# We can also pool across conditions easily, thanks to how MNE-Python handles
+# the ``/`` character in epoch labels (using what is sometimes called
+# "tag-based indexing"):
+
+# pool across left + right
+print(epochs['auditory'])
+assert len(epochs['auditory']) == (len(epochs['auditory/left']) +
+ len(epochs['auditory/right']))
+# pool across auditory + visual
+print(epochs['left'])
+assert len(epochs['left']) == (len(epochs['auditory/left']) +
+ len(epochs['visual/left']))
+
+###############################################################################
+# You can also pool conditions by passing multiple tags as a list. Note that
+# MNE-Python will not complain if you ask for tags not present in the object,
+# as long as it can find *some* match: the below example is parsed as
+# (inclusive) ``'right'`` **or** ``'bottom'``, and you can see from the output
+# that it selects only ``auditory/right`` and ``visual/right``.
+
+print(epochs[['right', 'bottom']])
+
+###############################################################################
+# However, if no match is found, an error is returned:
+
+try:
+ print(epochs[['top', 'bottom']])
+except KeyError:
+ print('Tag-based selection with no matches raises a KeyError!')
+
+###############################################################################
+# Selecting epochs by index
+# ~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# :class:`~mne.Epochs` objects can also be indexed with integers, :term:`slices
+# `, or lists of integers. This method of selection ignores event
+# labels, so if you want the first 10 epochs of a particular type, you can
+# select the type first, then use integers or slices:
+
+print(epochs[:10]) # epochs 0-9
+print(epochs[1:8:2]) # epochs 1, 3, 5, 7
+
+print(epochs['buttonpress'][:4]) # first 4 "buttonpress" epochs
+print(epochs['buttonpress'][[0, 1, 2, 3]]) # same as previous line
+
+###############################################################################
+# Selecting, dropping, and reordering channels
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# You can use the :meth:`~mne.Epochs.pick`, :meth:`~mne.Epochs.pick_channels`,
+# :meth:`~mne.Epochs.pick_types`, and :meth:`~mne.Epochs.drop_channels` methods
+# to modify which channels are included in an :class:`~mne.Epochs` object. You
+# can also use :meth:`~mne.Epochs.reorder_channels` for this purpose; any
+# channel names not provided to :meth:`~mne.Epochs.reorder_channels` will be
+# dropped. Note that these *channel* selection methods modify the object
+# in-place (unlike the square-bracket indexing to select *epochs* seen above)
+# so in interactive/exploratory sessions you may want to create a
+# :meth:`~mne.Epochs.copy` first.
+
+epochs_eeg = epochs.copy().pick_types(meg=False, eeg=True)
+print(epochs_eeg.ch_names)
+
+new_order = ['EEG 002', 'STI 014', 'EOG 061', 'MEG 2521']
+epochs_subset = epochs.copy().reorder_channels(new_order)
+print(epochs_subset.ch_names)
+
+###############################################################################
+
+del epochs_eeg, epochs_subset
+
+###############################################################################
+# Changing channel name and type
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# You can change the name or type of a channel using
+# :meth:`~mne.Epochs.rename_channels` or :meth:`~mne.Epochs.set_channel_types`.
+# Both methods take :class:`dictionaries ` where the keys are existing
+# channel names, and the values are the new name (or type) for that channel.
+# Existing channels that are not in the dictionary will be unchanged.
+
+epochs.rename_channels({'EOG 061': 'BlinkChannel'})
+
+epochs.set_channel_types({'EEG 060': 'ecg'})
+print(list(zip(epochs.ch_names, epochs.get_channel_types()))[-4:])
+
+###############################################################################
+
+# let's set them back to the correct values before moving on
+epochs.rename_channels({'BlinkChannel': 'EOG 061'})
+epochs.set_channel_types({'EEG 060': 'eeg'})
+
+###############################################################################
+# Selection in the time domain
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# To change the temporal extent of the :class:`~mne.Epochs`, you can use the
+# :meth:`~mne.Epochs.crop` method:
+
+shorter_epochs = epochs.copy().crop(tmin=-0.1, tmax=0.1, include_tmax=True)
+
+for name, obj in dict(Original=epochs, Cropped=shorter_epochs).items():
+ print('{} epochs has {} time samples'
+ .format(name, obj.get_data().shape[-1]))
+
+###############################################################################
+# However, if you wanted to *expand* the time domain of an :class:`~mne.Epochs`
+# object, you would need to go back to the :class:`~mne.io.Raw` data and
+# recreate the :class:`~mne.Epochs` with different values for ``tmin`` and/or
+# ``tmax``.
+#
+# It is also possible to change the "zero point" that defines the time values
+# in an :class:`~mne.Epochs` object, with the :meth:`~mne.Epochs.shift_time`
+# method. :meth:`~mne.Epochs.shift_time` allows shifting times relative to the
+# current values, or specifying a fixed time to set as the new time value of
+# the first sample (deriving the new time values of subsequent samples based on
+# the :class:`~mne.Epochs` object's sampling frequency).
+
+# shift times so that first sample of each epoch is at time zero
+later_epochs = epochs.copy().shift_time(tshift=0., relative=False)
+print(later_epochs.times[:3])
+
+# shift times by a relative amount
+later_epochs.shift_time(tshift=-7, relative=True)
+print(later_epochs.times[:3])
+
+###############################################################################
+
+del shorter_epochs, later_epochs
+
+###############################################################################
+# Note that although time shifting respects the sampling frequency (the spacing
+# between samples), it does not enforce the assumption that there is a sample
+# occurring at exactly time=0.
+#
+#
+# Extracting data in other forms
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The :meth:`~mne.Epochs.get_data` method returns the epoched data as a
+# :class:`NumPy array `, of shape ``(n_epochs, n_channels,
+# n_times)``; an optional ``picks`` parameter selects a subset of channels by
+# index, name, or type:
+
+eog_data = epochs.get_data(picks='EOG 061')
+meg_data = epochs.get_data(picks=['mag', 'grad'])
+channel_4_6_8 = epochs.get_data(picks=slice(4, 9, 2))
+
+for name, arr in dict(EOG=eog_data, MEG=meg_data, Slice=channel_4_6_8).items():
+ print('{} contains {} channels'.format(name, arr.shape[1]))
+
+###############################################################################
+# Note that if your analysis requires repeatedly extracting single epochs from
+# an :class:`~mne.Epochs` object, ``epochs.get_data(item=2)`` will be much
+# faster than ``epochs[2].get_data()``, because it avoids the step of
+# subsetting the :class:`~mne.Epochs` object first.
+#
+# You can also export :class:`~mne.Epochs` data to :class:`Pandas DataFrames
+# `. Here, the :class:`~pandas.DataFrame` index will be
+# constructed by converting the time of each sample into milliseconds and
+# rounding it to the nearest integer, and combining it with the event types and
+# epoch numbers to form a hierarchical :class:`~pandas.MultiIndex`. Each
+# channel will appear in a separate column. Then you can use any of Pandas'
+# tools for grouping and aggregating data; for example, here we select any
+# epochs numbered 10 or less from the ``auditory/left`` condition, and extract
+# times between 100 and 107 ms on channels ``EEG 056`` through ``EEG 058``
+# (note that slice indexing within Pandas' :obj:`~pandas.DataFrame.loc` is
+# inclusive of the endpoint):
+
+df = epochs.to_data_frame(index=['condition', 'epoch', 'time'])
+df.sort_index(inplace=True)
+print(df.loc[('auditory/left', slice(0, 10), slice(100, 107)),
+ 'EEG 056':'EEG 058'])
+
+del df
+
+###############################################################################
+# See the :ref:`tut-epochs-dataframe` tutorial for many more examples of the
+# :meth:`~mne.Epochs.to_data_frame` method.
+#
+#
+# Loading and saving ``Epochs`` objects to disk
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# :class:`~mne.Epochs` objects can be loaded and saved in the ``.fif`` format
+# just like :class:`~mne.io.Raw` objects, using the :func:`mne.read_epochs`
+# function and the :meth:`~mne.Epochs.save` method. Functions are also
+# available for loading data that was epoched outside of MNE-Python, such as
+# :func:`mne.read_epochs_eeglab` and :func:`mne.read_epochs_kit`.
+
+epochs.save('saved-audiovisual-epo.fif', overwrite=True)
+epochs_from_file = mne.read_epochs('saved-audiovisual-epo.fif', preload=False)
+
+###############################################################################
+# The MNE-Python naming convention for epochs files is that the file basename
+# (the part before the ``.fif`` or ``.fif.gz`` extension) should end with
+# ``-epo`` or ``_epo``, and a warning will be issued if the filename you
+# provide does not adhere to that convention.
+#
+# As a final note, be aware that the class of the epochs object is different
+# when epochs are loaded from disk rather than generated from a
+# :class:`~mne.io.Raw` object:
+
+print(type(epochs))
+print(type(epochs_from_file))
+
+###############################################################################
+# In almost all cases this will not require changing anything about your code.
+# However, if you need to do type checking on epochs objects, you can test
+# against the base class that these classes are derived from:
+
+print(all([isinstance(epochs, mne.BaseEpochs),
+ isinstance(epochs_from_file, mne.BaseEpochs)]))
+
+###############################################################################
+# Iterating over ``Epochs``
+# ^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# Iterating over an :class:`~mne.Epochs` object will yield :class:`arrays
+# ` rather than single-trial :class:`~mne.Epochs` objects:
+
+for epoch in epochs[:3]:
+ print(type(epoch))
+
+###############################################################################
+# If you want to iterate over :class:`~mne.Epochs` objects, you can use an
+# integer index as the iterator:
+
+for index in range(3):
+ print(type(epochs[index]))
diff --git a/pool/shard009/Python/0085792_testpref.py b/pool/shard009/Python/0085792_testpref.py
new file mode 100644
index 0000000000000000000000000000000000000000..8349110a0332301e629a49817db92c4422d897f0
--- /dev/null
+++ b/pool/shard009/Python/0085792_testpref.py
@@ -0,0 +1,29 @@
+import cPickle, time, uuid, sys, random
+import transaction
+from ZODB.FileStorage import FileStorage
+from ZODB.DB import DB
+from BTrees.IOBTree import IOBTree
+import testlib
+
+storage = FileStorage('Data.fs')
+db = DB(storage)
+connection = db.open()
+root = connection.root()
+
+root['graphdb']=testlib.gdb()
+
+g=root['graphdb']
+g.nodes=IOBTree()
+g.edges=IOBTree()
+
+for i in range(1,100001):
+ node = [i,{}]
+ g.nodes[i]=node
+
+for j in range(1,1000001):
+ edge = testlib.PersistentList([j,g.nodes[random.randint(1,100000)],random.randint(1,100000),{}])
+ g.edges[j]=edge
+transaction.commit()
+connection.close()
+db.close()
+
diff --git a/pool/shard009/Python/0085799_test_account.py b/pool/shard009/Python/0085799_test_account.py
new file mode 100644
index 0000000000000000000000000000000000000000..af6794253784f19aeee47883a6443d83e8f7a40c
--- /dev/null
+++ b/pool/shard009/Python/0085799_test_account.py
@@ -0,0 +1,90 @@
+# flake8: noqa: F811
+from inbox.test.util.base import (generic_account, gmail_account, db,
+ add_fake_yahoo_account)
+from inbox.test.api.base import api_client, new_api_client
+
+__all__ = ['db', 'api_client', 'generic_account', 'gmail_account']
+
+
+def test_account(db, api_client, generic_account, gmail_account):
+ # Because we're using the generic_account namespace
+ api_client = new_api_client(db, generic_account.namespace)
+
+ resp_data = api_client.get_data('/account')
+
+ assert resp_data['id'] == generic_account.namespace.public_id
+ assert resp_data['object'] == 'account'
+ assert resp_data['account_id'] == generic_account.namespace.public_id
+ assert resp_data['email_address'] == generic_account.email_address
+ assert resp_data['name'] == generic_account.name
+ assert resp_data['organization_unit'] == 'folder'
+ assert 'sync_state' in resp_data
+ assert 'server_settings' not in resp_data
+
+ # Because we're using the gmail account namespace
+ api_client = new_api_client(db, gmail_account.namespace)
+
+ resp_data = api_client.get_data('/account')
+
+ assert resp_data['id'] == gmail_account.namespace.public_id
+ assert resp_data['provider'] == 'gmail'
+ assert resp_data['organization_unit'] == 'label'
+ assert 'sync_state' in resp_data
+ assert 'server_settings' not in resp_data
+
+
+def test_account_expanded(db, api_client, generic_account, gmail_account):
+ # Generic accounts expose a `server_settings` attribute
+ # Custom IMAP
+ api_client = new_api_client(db, generic_account.namespace)
+ resp_data = api_client.get_data('/account/?view=expanded')
+ assert resp_data['provider'] == 'custom'
+ assert 'server_settings' in resp_data
+ assert set(resp_data['server_settings']) == set({
+ 'imap_host': 'imap.custom.com',
+ 'smtp_host': 'smtp.custom.com',
+ 'imap_port': 993,
+ 'smtp_port': 587,
+ 'ssl_required': True})
+
+ # Yahoo
+ yahoo_account = add_fake_yahoo_account(db.session)
+ api_client = new_api_client(db, yahoo_account.namespace)
+ resp_data = api_client.get_data('/account/?view=expanded')
+ assert resp_data['provider'] == 'yahoo'
+ assert 'server_settings' in resp_data
+ assert set(resp_data['server_settings']) == set({
+ 'imap_host': 'imap.mail.yahoo.com',
+ 'smtp_host': 'smtp.mail.yahoo.com',
+ 'imap_port': 993,
+ 'smtp_port': 587,
+ 'ssl_required': True})
+
+ # Gmail accounts don't expose a `server_settings` attribute
+ api_client = new_api_client(db, gmail_account.namespace)
+ resp_data = api_client.get_data('/account/?view=expanded')
+ assert resp_data['provider'] == 'gmail'
+ assert 'server_settings' not in resp_data
+
+
+def test_account_repr_for_new_account(db):
+ account = add_fake_yahoo_account(db.session)
+
+ # Sync for the account has not started yet.
+ assert account.sync_state is None
+
+ # However the API-returned account object has `sync_state=running`
+ # so API clients can do the right thing.
+ api_client = new_api_client(db, account.namespace)
+ resp_data = api_client.get_data('/account')
+ assert resp_data['id'] == account.namespace.public_id
+ assert resp_data['sync_state'] == 'running'
+
+ # Verify other sync_states are not masked.
+ account.sync_state = 'invalid'
+ db.session.commit()
+
+ api_client = new_api_client(db, account.namespace)
+ resp_data = api_client.get_data('/account')
+ assert resp_data['id'] == account.namespace.public_id
+ assert resp_data['sync_state'] == 'invalid'
diff --git a/pool/shard009/Python/0085800_files_store.py b/pool/shard009/Python/0085800_files_store.py
new file mode 100644
index 0000000000000000000000000000000000000000..438aa73d07a697eda1c706f5a9d251cbb927362b
--- /dev/null
+++ b/pool/shard009/Python/0085800_files_store.py
@@ -0,0 +1,248 @@
+from __future__ import with_statement
+import os
+import glob
+import shutil
+import re
+
+from .base import BaseTileStore
+from . import utils
+
+import logging
+log = logging.getLogger("tile_storage.files_store")
+
+PARTIAL_TILE_FILE_SUFFIX = ".part"
+
+def _get_toplevel_tile_folder_list(path):
+ """Return a list of toplevel tile folders
+ The toplevel tile folders correspond to the zoom level number.
+
+ :param str path: path where to check for top level tile folders
+ :returns: a list of top level tile folders
+ :rtype: list
+ """
+ tile_folders = [folder for folder in os.listdir(path) if re.match("[0-9]+", folder)]
+ return [folder for folder in tile_folders if os.path.isdir(os.path.join(path, folder))]
+
+
+class FileBasedTileStore(BaseTileStore):
+
+ @staticmethod
+ def is_store(path):
+ """We consider the path to be a files tile store if it is a folder
+ that contains at least one top level tile folder.
+ This basically means that at least one tile needs to be stored in it.
+
+ :param str path: path to test
+ :returns: True if the path leads to an existing folder, else False
+ :rtype: bool
+ """
+ is_files_store = False
+ if os.path.isdir(path):
+ is_files_store = bool(_get_toplevel_tile_folder_list(path))
+ return is_files_store
+
+ def __init__(self, store_path, prevent_media_indexing = False):
+ BaseTileStore.__init__(self, store_path, prevent_media_indexing=prevent_media_indexing)
+
+ # make sure the folder for the file based tile store exists and is in a correct state,
+ # such as that it contains a file that disables media indexing on platforms where this is needed
+ utils.check_folder(self.store_path, prevent_media_indexing=prevent_media_indexing)
+
+ def __str__(self):
+ return "file based store @ %s" % self.store_path
+
+ def __repr__(self):
+ return str(self)
+
+ def store_tile_data(self, lzxy, tile_data):
+ """Store the given tile to a file"""
+ # get the folder path
+ file_path = self._get_tile_file_path(lzxy)
+ partial_file_path = file_path + PARTIAL_TILE_FILE_SUFFIX
+ (folder_path, tail) = os.path.split(file_path)
+ if not os.path.exists(folder_path): # does it exist ?
+ try:
+ os.makedirs(folder_path) # create the folder
+ except Exception:
+ import sys
+ e = sys.exc_info()[1]
+ # errno 17 - folder already exists
+ # this is most probably cased by another thread creating the folder between
+ # the check & our os.makedirs() call
+ # -> we can safely ignore it (as the the only thing we are now interested in,
+ # is having a folder to store the tile in)
+ if e.errno != 17:
+ log.exception("can't create folder %s for %s", folder_path, file_path)
+ try:
+ with open(partial_file_path, 'wb') as f:
+ f.write(tile_data)
+ os.rename(partial_file_path, file_path)
+ # TODO: fsync the file (optionally ?)?
+ except:
+ log.exception("saving tile to file %s failed", file_path)
+ try:
+ if os.path.exists(partial_file_path):
+ os.remove(partial_file_path)
+ if os.path.exists(file_path):
+ os.remove(file_path)
+ except:
+ log.exception("failed storage operation cleanup failed for %s", file_path)
+
+ def get_tile(self, lzxy, fuzzy_matching=True):
+ """Get tile data and timestamp corresponding to the given coordinate tuple from
+ this file based tile store. The timestamp correspond to the time the tile has
+ been last modified.
+
+ :param tuple lzxy: layer, z, x, y coordinate tuple describing a single tile
+ (layer is actually not used and can be None)
+ :param bool fuzzy_matching: if fuzzy tile matching should be used
+ Fuzzy tile matching looks for any image files on the given coordinates
+ in case an image file with extension given by the layer.type property is
+ not found in the store.
+ :returns: (tile data, timestamp) or None if tile is not found in the database
+ :rtype: a (bytes, int) tuple or None
+ """
+ if fuzzy_matching:
+ file_path = self._fuzzy_find_tile(lzxy)
+ else:
+ file_path = self._get_tile_file_path(lzxy)
+
+ if file_path and os.path.isfile(file_path):
+ try:
+ tile_mtime = os.path.getmtime(file_path)
+ with open(file_path, "rb") as f:
+ return f.read(), tile_mtime
+ except:
+ log.exception("tile file reading failed for: %s", file_path)
+ return None
+ else:
+ return None
+
+ def tile_is_stored(self, lzxy, fuzzy_matching=True):
+ """Report if the tile specified by the lzxy tuple is present
+ in this file based tile store
+
+ :param tuple lzxy: layer, z, x, y coordinate tuple describing a single tile
+ :param bool fuzzy_matching: if fuzzy tile matching should be used
+ Fuzzy tile matching looks for any image files on the given coordinates
+ in case an image file with extension given by the layer.type property is
+ not found in the store.
+ :returns: True if tile is present in the store, else False
+ :rtype: bool
+ """
+ if fuzzy_matching:
+ file_path = self._fuzzy_find_tile(lzxy)
+ else:
+ file_path = self._get_tile_file_path(lzxy)
+ if file_path and os.path.isfile(file_path):
+ return True, os.path.getmtime(file_path)
+ else:
+ return False
+
+ def _delete_empty_folders(self, z, x):
+ # x-level folder
+ x_path = os.path.join(self.store_path, z, x)
+ if not os.listdir(x_path):
+ try:
+ try:
+ os.rmdir(x_path)
+ except OSError:
+ # most probably caused by something being created in the folder
+ # since the check
+ pass
+ # z-level folder
+ z_path = os.path.join(self.store_path, z)
+ if os.listdir(z_path):
+ try:
+ os.rmdir(z_path)
+ except OSError:
+ # most probably caused by something being created in the folder
+ # since the check
+ pass
+ except:
+ log.exception("empty folder cleanup failed for: %s", x_path)
+
+ def delete_tile(self, lzxy):
+ # TODO: delete empty folders ?
+ tile_path = self._get_tile_file_path(lzxy)
+ try:
+ if os.path.isfile(tile_path):
+ os.remove(tile_path)
+ # remove any empty folders that might have been
+ # left after the deleted tile file
+ self._delete_empty_folders(lzxy[1], lzxy[2])
+ else:
+ log.error("can't delete file - path is not a file: %s", tile_path)
+ except:
+ log.exception("removing of tile at %s failed", tile_path)
+
+ def clear(self):
+ """Delete the tile folders and files corresponding to this store from permanent storage
+ This basically means we delete all folders that have just number in name
+ (1, 2, 23, 1337 but not aa1, b23, .git, etc.) as they are the the toplevel (z coordinates)
+ tile storage folders.
+ We don't just remove the toplevel folder as for example in modRana a single folder
+ is used to store both tiles and sqlite tile storage database and we would
+ also remove any databases if we just removed the toplevel folder.
+ """
+ try:
+ for folder in _get_toplevel_tile_folder_list(self.store_path):
+ folder_path = os.path.join(self.store_path, folder)
+ shutil.rmtree(folder_path)
+ except:
+ log.exception("clearing of files tile store at path %s failed", self.store_path)
+
+ def _get_tile_file_path(self, lzxy):
+ """Return full filesystem path to the tile file corresponding to the coordinates
+ given by the lzxy tuple.
+
+ :param tuple lzxy: tile coordinates
+ :returns: full filesystem path to the tile
+ :rtype: str
+ """
+ return os.path.join(
+ self.store_path,
+ str(lzxy[1]),
+ str(lzxy[2]),
+ "%d.%s" % (lzxy[3], lzxy[0].type)
+ )
+
+ def _fuzzy_find_tile(self, lzxy):
+ """Try to find a tile image file for the given coordinates
+
+ :returns: path to a suitable tile or None if no can be found
+ :rtype: str or None
+ """
+ # first check if the primary tile path exists
+ tile_path = self._get_tile_file_path(lzxy)
+ # check if the primary file path exists and also if it actually
+ # is an image file
+ if os.path.exists(tile_path):
+ try:
+ with open(tile_path, "rb") as f:
+ if utils.is_an_image(f.read(32)):
+ return tile_path
+ else:
+ log.warning("%s is not an image", tile_path)
+ except Exception:
+ log.exception("checking if primary tile file is an image failed for %s", lzxy)
+
+ # look also for other supported image formats
+ alternative_tile_path = None
+ # TODO: might be good to investigate the performance impact,
+ # just to be sure :P
+
+ # replace the extension with a * so that the path can be used
+ # as wildcard in glob
+ wildcard_tile_path = "%s.*" % os.path.splitext(tile_path)[0]
+ # iterate over potential paths returned by the glob iterator
+ for path in glob.iglob(wildcard_tile_path):
+ # go over the paths and check if they point to an image files
+ with open(path, "rb") as f:
+ if utils.is_an_image(f.read(32)):
+ # once an image file is found, break & returns its path
+ alternative_tile_path = path
+ break
+ else:
+ log.warning("%s is not an image", tile_path)
+ return alternative_tile_path
\ No newline at end of file
diff --git a/pool/shard009/Python/0085801_device_sun_light_trigger.py b/pool/shard009/Python/0085801_device_sun_light_trigger.py
new file mode 100644
index 0000000000000000000000000000000000000000..641ade7308b829341c97739170b6887705582e2e
--- /dev/null
+++ b/pool/shard009/Python/0085801_device_sun_light_trigger.py
@@ -0,0 +1,182 @@
+"""
+Provides functionality to turn on lights based on the states.
+
+For more details about this component, please refer to the documentation at
+https://home-assistant.io/components/device_sun_light_trigger/
+"""
+import asyncio
+import logging
+from datetime import timedelta
+
+import voluptuous as vol
+
+from homeassistant.core import callback
+import homeassistant.util.dt as dt_util
+from homeassistant.const import STATE_HOME, STATE_NOT_HOME
+from homeassistant.helpers.event import (
+ async_track_point_in_utc_time, async_track_state_change)
+from homeassistant.helpers.sun import is_up, get_astral_event_next
+import homeassistant.helpers.config_validation as cv
+
+DOMAIN = 'device_sun_light_trigger'
+DEPENDENCIES = ['light', 'device_tracker', 'group']
+
+CONF_DEVICE_GROUP = 'device_group'
+CONF_DISABLE_TURN_OFF = 'disable_turn_off'
+CONF_LIGHT_GROUP = 'light_group'
+CONF_LIGHT_PROFILE = 'light_profile'
+
+DEFAULT_DISABLE_TURN_OFF = False
+DEFAULT_LIGHT_PROFILE = 'relax'
+
+LIGHT_TRANSITION_TIME = timedelta(minutes=15)
+
+CONFIG_SCHEMA = vol.Schema({
+ DOMAIN: vol.Schema({
+ vol.Optional(CONF_DEVICE_GROUP): cv.entity_id,
+ vol.Optional(CONF_DISABLE_TURN_OFF, default=DEFAULT_DISABLE_TURN_OFF):
+ cv.boolean,
+ vol.Optional(CONF_LIGHT_GROUP): cv.string,
+ vol.Optional(CONF_LIGHT_PROFILE, default=DEFAULT_LIGHT_PROFILE):
+ cv.string,
+ }),
+}, extra=vol.ALLOW_EXTRA)
+
+
+@asyncio.coroutine
+def async_setup(hass, config):
+ """Set up the triggers to control lights based on device presence."""
+ logger = logging.getLogger(__name__)
+ device_tracker = hass.components.device_tracker
+ group = hass.components.group
+ light = hass.components.light
+ conf = config[DOMAIN]
+ disable_turn_off = conf.get(CONF_DISABLE_TURN_OFF)
+ light_group = conf.get(CONF_LIGHT_GROUP, light.ENTITY_ID_ALL_LIGHTS)
+ light_profile = conf.get(CONF_LIGHT_PROFILE)
+ device_group = conf.get(
+ CONF_DEVICE_GROUP, device_tracker.ENTITY_ID_ALL_DEVICES)
+ device_entity_ids = group.get_entity_ids(
+ device_group, device_tracker.DOMAIN)
+
+ if not device_entity_ids:
+ logger.error("No devices found to track")
+ return False
+
+ # Get the light IDs from the specified group
+ light_ids = group.get_entity_ids(light_group, light.DOMAIN)
+
+ if not light_ids:
+ logger.error("No lights found to turn on")
+ return False
+
+ def calc_time_for_light_when_sunset():
+ """Calculate the time when to start fading lights in when sun sets.
+
+ Returns None if no next_setting data available.
+
+ Async friendly.
+ """
+ next_setting = get_astral_event_next(hass, 'sunset')
+ if not next_setting:
+ return None
+ return next_setting - LIGHT_TRANSITION_TIME * len(light_ids)
+
+ def async_turn_on_before_sunset(light_id):
+ """Turn on lights."""
+ if not device_tracker.is_on() or light.is_on(light_id):
+ return
+ light.async_turn_on(light_id,
+ transition=LIGHT_TRANSITION_TIME.seconds,
+ profile=light_profile)
+
+ def async_turn_on_factory(light_id):
+ """Generate turn on callbacks as factory."""
+ @callback
+ def async_turn_on_light(now):
+ """Turn on specific light."""
+ async_turn_on_before_sunset(light_id)
+
+ return async_turn_on_light
+
+ # Track every time sun rises so we can schedule a time-based
+ # pre-sun set event
+ @callback
+ def schedule_light_turn_on(now):
+ """Turn on all the lights at the moment sun sets.
+
+ We will schedule to have each light start after one another
+ and slowly transition in.
+ """
+ start_point = calc_time_for_light_when_sunset()
+ if not start_point:
+ return
+
+ for index, light_id in enumerate(light_ids):
+ async_track_point_in_utc_time(
+ hass, async_turn_on_factory(light_id),
+ start_point + index * LIGHT_TRANSITION_TIME)
+
+ async_track_point_in_utc_time(hass, schedule_light_turn_on,
+ get_astral_event_next(hass, 'sunrise'))
+
+ # If the sun is already above horizon schedule the time-based pre-sun set
+ # event.
+ if is_up(hass):
+ schedule_light_turn_on(None)
+
+ @callback
+ def check_light_on_dev_state_change(entity, old_state, new_state):
+ """Handle tracked device state changes."""
+ lights_are_on = group.is_on(light_group)
+ light_needed = not (lights_are_on or is_up(hass))
+
+ # These variables are needed for the elif check
+ now = dt_util.utcnow()
+ start_point = calc_time_for_light_when_sunset()
+
+ # Do we need lights?
+ if light_needed:
+ logger.info("Home coming event for %s. Turning lights on", entity)
+ light.async_turn_on(light_ids, profile=light_profile)
+
+ # Are we in the time span were we would turn on the lights
+ # if someone would be home?
+ # Check this by seeing if current time is later then the point
+ # in time when we would start putting the lights on.
+ elif (start_point and
+ start_point < now < get_astral_event_next(hass, 'sunset')):
+
+ # Check for every light if it would be on if someone was home
+ # when the fading in started and turn it on if so
+ for index, light_id in enumerate(light_ids):
+ if now > start_point + index * LIGHT_TRANSITION_TIME:
+ light.async_turn_on(light_id)
+
+ else:
+ # If this light didn't happen to be turned on yet so
+ # will all the following then, break.
+ break
+
+ async_track_state_change(
+ hass, device_entity_ids, check_light_on_dev_state_change,
+ STATE_NOT_HOME, STATE_HOME)
+
+ if disable_turn_off:
+ return True
+
+ @callback
+ def turn_off_lights_when_all_leave(entity, old_state, new_state):
+ """Handle device group state change."""
+ if not group.is_on(light_group):
+ return
+
+ logger.info(
+ "Everyone has left but there are lights on. Turning them off")
+ light.async_turn_off(light_ids)
+
+ async_track_state_change(
+ hass, device_group, turn_off_lights_when_all_leave,
+ STATE_HOME, STATE_NOT_HOME)
+
+ return True
diff --git a/pool/shard009/Python/0085803_hole-in-plate-full.py b/pool/shard009/Python/0085803_hole-in-plate-full.py
new file mode 100644
index 0000000000000000000000000000000000000000..258bb0307bc75d8a5986c05539e7e53b78c3d379
--- /dev/null
+++ b/pool/shard009/Python/0085803_hole-in-plate-full.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+import sys
+
+import pycalculix as pyc
+
+# Vertical hole in plate model, make model
+proj_name = 'hole-in-plate-full'
+model = pyc.FeaModel(proj_name)
+model.set_units('m') # this sets dist units to meters
+
+# set whether or not to show gui plots
+show_gui = True
+if '-nogui' in sys.argv:
+ show_gui = False
+# set element shape
+eshape = 'quad'
+if '-tri' in sys.argv:
+ eshape = 'tri'
+
+# Define variables we'll use to draw part geometry
+diam = 2.0 # hole diam
+ratio = 0.45
+width = diam/ratio #plate width
+print('D=%f, H=%f, D/H=%f' % (diam, width, diam/width))
+length = 2*width #plate length
+
+# Draw part geometry, you must draw the part CLOCKWISE,
+# x, y = radial, axial
+part = pyc.Part(model)
+part.goto(length*0.5, -width*0.5)
+part.draw_line_ax(width)
+part.draw_line_rad(-length)
+part.draw_line_ax(-width)
+part.draw_line_rad(length)
+hole_lines = part.draw_hole(0, 0, diam*0.5, filled=False)
+model.set_ediv(hole_lines, 10)
+part.chunk()
+# view the geometry
+model.plot_geometry(proj_name+'_geom', display=show_gui)
+
+# set loads and constraints
+pressure = -1000
+model.set_load('press', part.top, pressure)
+model.set_load('press', part.bottom, pressure)
+model.set_constr('fix', ['P6', 'P8'], 'y')
+model.set_constr('fix', ['P4', 'P7'], 'x')
+
+# set part material
+mat = pyc.Material('steel')
+mat.set_mech_props(7800, 210*(10**9), 0.3)
+model.set_matl(mat, part)
+
+# set the element type and mesh database
+model.set_eshape(eshape, 2)
+model.set_etype('plstress', part, 0.1)
+model.mesh(1.0, 'gmsh') # mesh 1.0 fineness, smaller is finer
+model.plot_elements(proj_name+'_elem', display=show_gui)
+model.plot_pressures(proj_name+'_press', display=show_gui)
+model.plot_constraints(proj_name+'_constr', display=show_gui)
+
+# make and solve the model
+prob = pyc.Problem(model, 'struct')
+prob.solve()
+
+# view and query results
+sx = prob.rfile.get_nmax('Sx')
+print('Sx_max: %f' % sx)
+
+# Plot results
+# store the fields to plot
+fields = 'Sx,Sy,S1,S2,S3,Seqv,ux,uy,utot,ex'
+fields = fields.split(',')
+for field in fields:
+ fname = proj_name+'_'+field
+ prob.rfile.nplot(field, fname, display=False)
diff --git a/pool/shard009/Python/0085814_setup.py b/pool/shard009/Python/0085814_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8609ab21910d8b6fdd58a3d5d5ca7abb5bd988a
--- /dev/null
+++ b/pool/shard009/Python/0085814_setup.py
@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+# -*- coding: latin-1 -*-
+# #
+# Copyright 2009-2013 Ghent University
+#
+# This file is part of hanythingondemand
+# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
+# with support of Ghent University (http://ugent.be/hpc),
+# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
+# the Hercules foundation (http://www.herculesstichting.be/in_English)
+# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
+#
+# http://github.com/hpcugent/hanythingondemand
+#
+# hanythingondemand 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 v2.
+#
+# hanythingondemand 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 hanythingondemand. If not, see .
+# #
+"""
+Setup for Hanything on Demand
+"""
+import os
+import sys
+import subprocess
+from os.path import join as mkpath
+from setuptools import setup, Command
+
+import hod
+
+
+def setup_openmpi_libpath():
+ libpath = os.getenv('LD_LIBRARY_PATH')
+ os.environ['LD_LIBRARY_PATH'] = '/usr/lib64/openmpi/lib:%s' % libpath
+
+class BaseCommand(Command):
+ user_options = []
+ def initialize_options(self):
+ pass
+ def finalize_options(self):
+ pass
+
+class TestCommand(BaseCommand):
+ description = "Run unit tests."
+
+ def run(self):
+ # Cheeky cheeky LD_LIBRARY_PATH hack for Fedora
+ setup_openmpi_libpath()
+ ret = subprocess.call(["coverage", "run", "-m", "pytest", "--cov-config=.coveragerc"])
+ sys.exit(ret)
+
+def find_files(*dirs):
+ results = []
+ for src_dir in dirs:
+ for root, dirs, files in os.walk(src_dir):
+ results.append((root, map(lambda f: mkpath(root, f), files)))
+ return results
+
+PACKAGE = {
+ 'name': hod.NAME,
+ 'version': hod.VERSION,
+ 'author': ['stijn.deweirdt@ugent.be', 'jens.timmerman@ugent.be', 'ewan.higgs@ugent.be'],
+ 'maintainer': ['stijn.deweirdt@ugent.be', 'jens.timmerman@ugent.be', 'ewan.higgs@ugent.be'],
+ 'license': "GPL v2",
+ 'classifiers' : [
+ 'Programming Language :: Python :: 2'
+ ],
+ 'install_requires': [
+ 'vsc-base >= 1.7.3',
+ 'setuptools',
+ 'mpi4py',
+ 'pbs-python',
+ 'netifaces',
+ 'netaddr',
+ ],
+ 'tests_require': ['tox', 'pytest', 'pytest-cov', 'coverage', 'mock'],
+ 'packages': [
+ 'hod',
+ 'hod.commands',
+ 'hod.config',
+ 'hod.config.autogen',
+ 'hod.config.writer',
+ 'hod.node',
+ 'hod.rmscheduler',
+ 'hod.subcommands',
+ 'hod.work',
+ ],
+ 'data_files': find_files('etc'),
+ 'scripts': ['bin/hod'],
+ 'cmdclass' : {'test': TestCommand},
+ 'long_description': open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
+ 'zip_safe': False,
+}
+
+if __name__ == '__main__':
+ setup(**PACKAGE)
diff --git a/pool/shard009/Python/0085816_runme.py b/pool/shard009/Python/0085816_runme.py
new file mode 100644
index 0000000000000000000000000000000000000000..572a24c080e62a0c184a7e2766b8fe1d039388cd
--- /dev/null
+++ b/pool/shard009/Python/0085816_runme.py
@@ -0,0 +1,78 @@
+#!/usr/bin/python
+
+"""
+HOWIE
+Description: Magical conversational/sysadmin bot.
+Author: Cort Stratton (cort@andrew.cmu.edu)
+
+Usage: runme.py [OPTIONS]
+
+Valid Options:
+ -h,--help: Prints this help message.
+ -v,--verbose: Enables verbose mode (extra debug output)
+ -l,--local: Enabled "local-only" mode; only the TTY interface
+ to Howie is initialized. Useful for having quick
+ conversations with Howie without putting him
+ online.
+ -f,--config-file=FILE Specifies an alternate location for Howie's
+ configuration file (default is "howie.ini")
+"""
+
+import getopt
+import os
+import random
+import string
+import sys
+import time
+
+# Add the current directory to the python search path
+sys.path.append(os.getcwd())
+
+import howie.configFile
+import howie.core
+
+def usage():
+ "Prints a usage message."
+ print __doc__
+
+def main():
+ random.seed()
+
+ # Process command-line arguments
+ try:
+ opts,args = getopt.getopt(sys.argv[1:], "hlf:v",
+ ["help","local","config-file","verbose"])
+ except getopt.GetoptError:
+ usage()
+ sys.exit(2)
+ localMode = "no"
+ configFile = "howie.ini"
+ verboseMode = "no"
+ for o,a in opts:
+ if o in ["-h","--help"]:
+ usage()
+ sys.exit(2)
+ elif o in ["-v","--verbose"]:
+ verboseMode = "yes"
+ elif o in ["-f","--config-file"]:
+ configFile = a
+ elif o in ["-l","--local"]:
+ localMode = "yes"
+
+ # Read config file
+ config = howie.configFile.load(configFile)
+
+ # Add config data from command-line arguments to the "cla" group.
+ # TODO: find a clean way to iterate over the destination variables in
+ # options, so the following code can be used instead:
+ ## for k,v in options.dict:
+ ## config["cla.%s" % k] = str(v)
+ for k in ["localMode", "configFile", "verboseMode"]:
+ config["cla.%s" % k] = str( eval("%s" % k) )
+
+ # Bootstrap the AI.
+ howie.core.init()
+
+# if this file is run directly, call main.
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard009/Python/0085823_test_certificates.py b/pool/shard009/Python/0085823_test_certificates.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac30a8ec66602e58841d8200574245f82940f12c
--- /dev/null
+++ b/pool/shard009/Python/0085823_test_certificates.py
@@ -0,0 +1,118 @@
+# Copyright (c) 2012 OpenStack Foundation
+# All Rights Reserved.
+# Copyright 2013 Red Hat, 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.
+
+import mock
+from mox3 import mox
+from webob import exc
+
+from oslo_policy import policy as oslo_policy
+
+from nova.api.openstack.compute import certificates \
+ as certificates_v21
+from nova.api.openstack.compute.legacy_v2.contrib import certificates \
+ as certificates_v2
+from nova.cert import rpcapi
+from nova import context
+from nova import exception
+from nova import policy
+from nova import test
+from nova.tests.unit.api.openstack import fakes
+
+
+class CertificatesTestV21(test.NoDBTestCase):
+ certificates = certificates_v21
+ url = '/v2/fake/os-certificates'
+ certificate_show_extension = 'os_compute_api:os-certificates:show'
+ certificate_create_extension = \
+ 'os_compute_api:os-certificates:create'
+
+ def setUp(self):
+ super(CertificatesTestV21, self).setUp()
+ self.context = context.RequestContext('fake', 'fake')
+ self.controller = self.certificates.CertificatesController()
+ self.req = fakes.HTTPRequest.blank('')
+
+ def test_translate_certificate_view(self):
+ pk, cert = 'fakepk', 'fakecert'
+ view = self.certificates._translate_certificate_view(cert, pk)
+ self.assertEqual(view['data'], cert)
+ self.assertEqual(view['private_key'], pk)
+
+ def test_certificates_show_root(self):
+ self.mox.StubOutWithMock(self.controller.cert_rpcapi, 'fetch_ca')
+
+ self.controller.cert_rpcapi.fetch_ca(
+ mox.IgnoreArg(), project_id='fake').AndReturn('fakeroot')
+
+ self.mox.ReplayAll()
+
+ res_dict = self.controller.show(self.req, 'root')
+
+ response = {'certificate': {'data': 'fakeroot', 'private_key': None}}
+ self.assertEqual(res_dict, response)
+
+ def test_certificates_show_policy_failed(self):
+ rules = {
+ self.certificate_show_extension: "!"
+ }
+ policy.set_rules(oslo_policy.Rules.from_dict(rules))
+ exc = self.assertRaises(exception.PolicyNotAuthorized,
+ self.controller.show, self.req, 'root')
+ self.assertIn(self.certificate_show_extension,
+ exc.format_message())
+
+ def test_certificates_create_certificate(self):
+ self.mox.StubOutWithMock(self.controller.cert_rpcapi,
+ 'generate_x509_cert')
+
+ self.controller.cert_rpcapi.generate_x509_cert(
+ mox.IgnoreArg(),
+ user_id='fake_user',
+ project_id='fake').AndReturn(('fakepk', 'fakecert'))
+
+ self.mox.ReplayAll()
+
+ res_dict = self.controller.create(self.req)
+
+ response = {
+ 'certificate': {'data': 'fakecert',
+ 'private_key': 'fakepk'}
+ }
+ self.assertEqual(res_dict, response)
+
+ def test_certificates_create_policy_failed(self):
+ rules = {
+ self.certificate_create_extension: "!"
+ }
+ policy.set_rules(oslo_policy.Rules.from_dict(rules))
+ exc = self.assertRaises(exception.PolicyNotAuthorized,
+ self.controller.create, self.req)
+ self.assertIn(self.certificate_create_extension,
+ exc.format_message())
+
+ @mock.patch.object(rpcapi.CertAPI, 'fetch_ca',
+ side_effect=exception.CryptoCAFileNotFound(project='fake'))
+ def test_non_exist_certificates_show(self, mock_fetch_ca):
+ self.assertRaises(
+ exc.HTTPNotFound,
+ self.controller.show,
+ self.req, 'root')
+
+
+class CertificatesTestV2(CertificatesTestV21):
+ certificates = certificates_v2
+ certificate_show_extension = 'compute_extension:certificates'
+ certificate_create_extension = 'compute_extension:certificates'
diff --git a/pool/shard009/Python/0085824_lewenxiaoshuo.py b/pool/shard009/Python/0085824_lewenxiaoshuo.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2a1d34da31cb7a88b5db9b5e8f3490ceff816b9
--- /dev/null
+++ b/pool/shard009/Python/0085824_lewenxiaoshuo.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""
+Created on April 15 2017
+
+@author: yytang
+"""
+
+from scrapy import Selector
+
+from libs.misc import get_spider_name_from_domain
+from libs.polish import polish_title, polish_subtitle, polish_content
+from novelsCrawler.spiders.novelSpider import NovelSpider
+
+
+class LewenxiaoshuoSpider(NovelSpider):
+ """
+ classdocs
+
+ example: https://www.lewenxiaoshuo.com/books/momenyaonv/
+ """
+
+ allowed_domains = ['www.lewenxiaoshuo.com']
+ name = get_spider_name_from_domain(allowed_domains[0])
+ # custom_settings = {
+ # 'DOWNLOAD_DELAY': 0.3,
+ # }
+
+ def parse_title(self, response):
+ sel = Selector(response)
+ title = sel.xpath('//h1/text()').extract()[0]
+ title = polish_title(title, self.name)
+ return title
+
+ def parse_episodes(self, response):
+ sel = Selector(response)
+ episoders = []
+ subtitle_selectors = sel.xpath('//div[@id="list"]/dl/dd/a')
+ for page_id, subtitle_selector in enumerate(subtitle_selectors):
+ subtitle_url = subtitle_selector.xpath('@href').extract()[0]
+ subtitle_url = response.urljoin(subtitle_url.strip())
+ subtitle_name = subtitle_selector.xpath('text()').extract()[0]
+ subtitle_name = polish_subtitle(subtitle_name)
+ episoders.append((page_id, subtitle_name, subtitle_url))
+ return episoders
+
+ def parse_content(self, response):
+ sel = Selector(response)
+ content = sel.xpath('//div[@id="content"]/text()').extract()
+ content = polish_content(content)
+ return content
diff --git a/pool/shard009/Python/0085835_Class14_InClassDemoFunctions.py b/pool/shard009/Python/0085835_Class14_InClassDemoFunctions.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ac240ebb58d4f1f349204494adb47c5440b2dcd
--- /dev/null
+++ b/pool/shard009/Python/0085835_Class14_InClassDemoFunctions.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Provides functions for plotting time series stored in ODM.
+
+"""
+
+import pymysql
+import matplotlib.pyplot as plt
+from matplotlib import dates
+
+__author__ = "Jon Goodall"
+__copyright__ = "Copyright 2014, Jon Goodall"
+__credits__ = ["Jon Goodall"]
+__license__ = "GPL"
+__version__ = "1.0.0"
+__maintainer__ = "Jon Goodall"
+__email__ = "goodall@virginia.edu"
+__status__ = "alpha"
+
+def get_timeseries(SiteID, VariableID):
+ """Gets a time series from the LBRODM_small MySQL database
+
+ Retrieves only the LocalDateTime and DataValue fields. Returns only raw
+ data (QualityControlLevel=1).
+
+ Arguments:
+ SiteID - the SiteID field for the time series
+ VariableID - the VariableID field in ODM for the time series
+ Returns:
+ LocalDateTimes - the date/times for the time series in the local time zone
+ DataValues - the values for the time series
+ """
+
+ conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', \
+ db='LBRODM_small')
+ sql_statement = "SELECT LocalDateTime, DataValue FROM DataValues \
+ WHERE \
+ SiteID = " + str(SiteID) + " AND \
+ VariableID = " + str(VariableID) + " AND \
+ QualityControlLevelID = 1 \
+ ORDER BY LocalDateTime"
+ cursor = conn.cursor()
+ cursor.execute(sql_statement)
+ rows = cursor.fetchall()
+ cursor.close()
+ conn.close()
+ LocalDateTimes, DataValues = zip(*rows)
+ return LocalDateTimes, DataValues
+
+def get_site_name(SiteID):
+ """ Gets the SiteName field for a given SiteID value.
+
+ Uses the LBRODM_small database.
+
+ Arguments:
+ SiteID
+
+ Returns:
+ SiteName
+ """
+ conn = pymysql.connect(host='localhost', port=3306, user='root', \
+ passwd='', db='LBRODM_small')
+ sql_statement = "SELECT SiteName FROM Sites \
+ WHERE SiteID = " + str(SiteID)
+ cursor = conn.cursor()
+ cursor.execute(sql_statement)
+ rows = cursor.fetchall()
+ cursor.close()
+ conn.close()
+ return rows[0][0] #Assumes one and only one row is returned with one and
+ #and only one field
+
+def create_new_figure():
+ """Creates a new figure for time series plots.
+
+ Sets properities for figure.
+
+ Arguments:
+ None
+
+ Returns:
+ fig - the figure object
+ """
+
+ fig = plt.figure()
+
+ from matplotlib import rc
+ font = {'family' : 'normal',
+ 'weight' : 'normal',
+ 'size' : 12}
+ rc('font', **font)
+
+ return fig
+
+def configure_subplot(ax, title):
+ """Configures a new subplot for a figure.
+
+ Sets default properties include the title of the subplot.
+
+ arguments:
+ ax - the axes object
+ title - the title for the subplot
+ returns:
+ N/A
+ """
+ ax.set_title(title)
+ ax.set_ylabel("Temperature ($^\circ$C)") #hardcoded for now
+ ax.set_xlabel("Date/Time") # hard coded for now
+ ax.xaxis.set_minor_locator(dates.MonthLocator())
+ ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
+ ax.xaxis.set_major_locator(dates.YearLocator())
+ ax.xaxis.set_major_formatter(dates.DateFormatter('\n%Y'))
+ ax.grid(True)
+
+if __name__ == '__main__': #code to execute if called from command-line
+
+ fig = create_new_figure()
+
+ ax = fig.add_subplot(211) #2 rows, 1 column, 1st plot
+ configure_subplot(ax, get_site_name(1))
+
+ dateTimes, dataValues = get_timeseries(2, 36)
+
+ ax.plot(dateTimes, dataValues, color='black', linestyle='solid', markersize=0)
+
+ ax2 = fig.add_subplot(212) #2 rows, 1 column, 2nd plot
+ configure_subplot(ax2, get_site_name(2))
+
+ dateTimes, dataValues = get_timeseries(4, 36)
+ ax2.plot(dateTimes, dataValues, color='black', linestyle='solid', markersize=0)
+
+ fig.tight_layout()
+ fig.savefig("Class14_InClassDemoFunctions.png")
+
+
+
+
+
diff --git a/pool/shard009/Python/0085849_05A_knn_with_diff_k.py b/pool/shard009/Python/0085849_05A_knn_with_diff_k.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e9c5d5103ba34cbc62838e42a1d85cfef674bc6
--- /dev/null
+++ b/pool/shard009/Python/0085849_05A_knn_with_diff_k.py
@@ -0,0 +1,30 @@
+from sklearn.datasets import load_iris
+from sklearn.model_selection import train_test_split
+
+
+iris = load_iris()
+X = iris.data
+y = iris.target
+
+X_train, X_test, y_train, y_test = train_test_split(X, y,
+ test_size=0.25,
+ random_state=1234,
+ stratify=y)
+
+X_trainsub, X_valid, y_trainsub, y_valid = train_test_split(X_train, y_train,
+ test_size=0.5,
+ random_state=1234,
+ stratify=y_train)
+
+for k in range(1, 20):
+ knn = KNeighborsClassifier(n_neighbors=k)
+ train_score = knn.fit(X_trainsub, y_trainsub).\
+ score(X_trainsub, y_trainsub)
+ valid_score = knn.score(X_valid, y_valid)
+ print('k: %d, Train/Valid Acc: %.3f/%.3f' %
+ (k, train_score, valid_score))
+
+
+knn = KNeighborsClassifier(n_neighbors=9)
+knn.fit(X_train, y_train)
+print('k=9 Test Acc: %.3f' % knn.score(X_test, y_test))
diff --git a/pool/shard009/Python/0085853_appveyor.py b/pool/shard009/Python/0085853_appveyor.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc291e21bcd92f887450db691223975aaf175554
--- /dev/null
+++ b/pool/shard009/Python/0085853_appveyor.py
@@ -0,0 +1,81 @@
+import os
+import sys
+
+appcast_ver = os.environ['APPVEYOR_BUILD_VERSION']
+
+
+def write_legacy(appcast_os, appcast_rid, appcast_file):
+ xml = '''
+-
+ %s
+ https://github.com/stakira/OpenUtau/releases/download/OpenUtau-Latest/OpenUtau.zip
+ false
+
''' % (appcast_ver)
+
+ with open("release.xml", 'w') as f:
+ f.write(xml)
+
+
+def write_appcast(appcast_os, appcast_rid, appcast_file):
+
+ xml = '''
+
+
+ OpenUtau
+ en
+ -
+ OpenUtau %s
+ Tue, 26 Oct 2021 21:01:52 -07:00
+
+
+
+''' % (appcast_ver, appcast_file, appcast_ver, appcast_ver, appcast_os)
+
+ with open("appcast.%s.xml" % (appcast_rid), 'w') as f:
+ f.write(xml)
+
+
+os.system("rm *.dmg")
+os.system("rm *.xml")
+
+if sys.platform == 'win32':
+ write_legacy("windows", "win", "OpenUtau.zip")
+ write_appcast("windows", "win", "OpenUtau.zip")
+
+ os.system("dotnet restore OpenUtau -r win-x86")
+ os.system(
+ "dotnet publish OpenUtau -c Release -r win-x86 --self-contained true -o bin/win-x86")
+ write_appcast("windows", "win-x86", "OpenUtau-win-x86.zip")
+
+ os.system("dotnet restore OpenUtau -r win-x64")
+ os.system(
+ "dotnet publish OpenUtau -c Release -r win-x64 --self-contained true -o bin/win-x64")
+ write_appcast("windows", "win-x64", "OpenUtau-win-x64.zip")
+
+elif sys.platform == 'darwin':
+ os.system("git checkout OpenUtau/OpenUtau.csproj")
+ os.system("rm LICENSE.txt")
+ os.system(
+ "sed -i '' \"s/0.0.0/%s/g\" OpenUtau/OpenUtau.csproj" % (appcast_ver))
+ os.system("dotnet restore OpenUtau -r osx.10.14-x64")
+ os.system("dotnet msbuild OpenUtau -t:BundleApp -p:Configuration=Release -p:RuntimeIdentifier=osx.10.14-x64 -p:UseAppHost=true -p:OutputPath=../bin/osx-x64/")
+ os.system(
+ "cp OpenUtau/Assets/OpenUtau.icns bin/osx-x64/publish/OpenUtau.app/Contents/Resources/")
+ os.system("rm *.dmg")
+ os.system("npm install -g create-dmg")
+ os.system("create-dmg bin/osx-x64/publish/OpenUtau.app")
+ os.system("mv *.dmg OpenUtau-osx-x64.dmg")
+ os.system("git checkout OpenUtau/OpenUtau.csproj")
+
+ write_appcast("macos", "osx-x64", "OpenUtau-osx-x64.dmg")
+
+else:
+ os.system("dotnet restore OpenUtau -r linux-x64")
+ os.system(
+ "dotnet publish OpenUtau -c Release -r linux-x64 --self-contained true -o bin/linux-x64")
+ write_appcast("linux", "linux-x64", "OpenUtau-linux-x64.zip")
diff --git a/pool/shard009/Python/0085854_mediaobj.py b/pool/shard009/Python/0085854_mediaobj.py
new file mode 100644
index 0000000000000000000000000000000000000000..57ef699cd188b444af63c5f2c73a80fee900d1b7
--- /dev/null
+++ b/pool/shard009/Python/0085854_mediaobj.py
@@ -0,0 +1,285 @@
+#
+# Gramps - a GTK+/GNOME based genealogy program
+#
+# Copyright (C) 2000-2007 Donald N. Allingham
+# Copyright (C) 2010 Michiel D. Nauta
+# Copyright (C) 2010 Nick Hall
+# Copyright (C) 2011 Tim G L Lyons
+#
+# 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$
+
+"""
+Media object for GRAMPS.
+"""
+
+#-------------------------------------------------------------------------
+#
+# standard python modules
+#
+#-------------------------------------------------------------------------
+import os
+from urlparse import urlparse
+import logging
+LOG = logging.getLogger(".citation")
+
+#-------------------------------------------------------------------------
+#
+# GRAMPS modules
+#
+#-------------------------------------------------------------------------
+from primaryobj import PrimaryObject
+from citationbase import CitationBase
+from notebase import NoteBase
+from datebase import DateBase
+from attrbase import AttributeBase
+from tagbase import TagBase
+
+#-------------------------------------------------------------------------
+#
+# MediaObject class
+#
+#-------------------------------------------------------------------------
+class MediaObject(CitationBase, NoteBase, DateBase, AttributeBase,
+ TagBase, PrimaryObject):
+ """
+ Container for information about an image file, including location,
+ description and privacy.
+ """
+
+ def __init__(self, source=None):
+ """
+ Initialize a MediaObject.
+
+ If source is not None, then object is initialized from values of the
+ source object.
+
+ :param source: Object used to initialize the new object
+ :type source: MediaObject
+ """
+ PrimaryObject.__init__(self, source)
+ CitationBase.__init__(self, source)
+ NoteBase.__init__(self, source)
+ DateBase.__init__(self, source)
+ AttributeBase.__init__(self, source)
+ TagBase.__init__(self)
+
+ if source:
+ self.path = source.path
+ self.mime = source.mime
+ self.desc = source.desc
+ self.thumb = source.thumb
+ else:
+ self.path = ""
+ self.mime = ""
+ self.desc = ""
+ self.thumb = None
+
+ def serialize(self, no_text_date = False):
+ """
+ Convert the data held in the event to a Python tuple that
+ represents all the data elements.
+
+ This method is used to convert the object into a form that can easily
+ be saved to a database.
+
+ These elements may be primitive Python types (string, integers),
+ complex Python types (lists or tuples, or Python objects. If the
+ target database cannot handle complex types (such as objects or
+ lists), the database is responsible for converting the data into
+ a form that it can use.
+
+ :returns: Returns a python tuple containing the data that should
+ be considered persistent.
+ :rtype: tuple
+ """
+ return (self.handle, self.gramps_id, self.path, self.mime, self.desc,
+ AttributeBase.serialize(self),
+ CitationBase.serialize(self),
+ NoteBase.serialize(self),
+ self.change,
+ DateBase.serialize(self, no_text_date),
+ TagBase.serialize(self),
+ self.private)
+
+ def to_struct(self):
+ """
+ Convert the data held in this object to a structure (eg,
+ struct) that represents all the data elements.
+
+ This method is used to recursively convert the object into a
+ self-documenting form that can easily be used for various
+ purposes, including diffs and queries.
+
+ These structures may be primitive Python types (string,
+ integer, boolean, etc.) or complex Python types (lists,
+ tuples, or dicts). If the return type is a dict, then the keys
+ of the dict match the fieldname of the object. If the return
+ struct (or value of a dict key) is a list, then it is a list
+ of structs. Otherwise, the struct is just the value of the
+ attribute.
+
+ :returns: Returns a struct containing the data of the object.
+ :rtype: dict
+ """
+ return {"handle": self.handle,
+ "gramps_id": self.gramps_id,
+ "path": self.path,
+ "mime": self.mime,
+ "desc": self.desc,
+ "attribute_list": AttributeBase.to_struct(self),
+ "citation_list": CitationBase.to_struct(self),
+ "note_list": NoteBase.to_struct(self),
+ "change": self.change,
+ "date": DateBase.to_struct(self),
+ "tag_list": TagBase.to_struct(self),
+ "private": self.private}
+
+ def unserialize(self, data):
+ """
+ Convert the data held in a tuple created by the serialize method
+ back into the data in an Event structure.
+
+ :param data: tuple containing the persistent data associated the object
+ :type data: tuple
+ """
+ (self.handle, self.gramps_id, self.path, self.mime, self.desc,
+ attribute_list, citation_list, note_list, self.change,
+ date, tag_list, self.private) = data
+
+ AttributeBase.unserialize(self, attribute_list)
+ CitationBase.unserialize(self, citation_list)
+ NoteBase.unserialize(self, note_list)
+ DateBase.unserialize(self, date)
+ TagBase.unserialize(self, tag_list)
+ return self
+
+ def get_text_data_list(self):
+ """
+ Return the list of all textual attributes of the object.
+
+ :returns: Returns the list of all textual attributes of the object.
+ :rtype: list
+ """
+ return [self.path, self.mime, self.desc, self.gramps_id]
+
+ def get_text_data_child_list(self):
+ """
+ Return the list of child objects that may carry textual data.
+
+ :returns: Returns the list of child objects that may carry textual data.
+ :rtype: list
+ """
+ return self.attribute_list
+
+ def get_citation_child_list(self):
+ """
+ Return the list of child secondary objects that may refer to citations.
+
+ :returns: Returns the list of child secondary child objects that may
+ refer to citations.
+ :rtype: list
+ """
+ return self.attribute_list
+
+ def get_note_child_list(self):
+ """
+ Return the list of child secondary objects that may refer notes.
+
+ :returns: Returns the list of child secondary child objects that may
+ refer notes.
+ :rtype: list
+ """
+ return self.attribute_list + self.citation_list
+
+ def get_referenced_handles(self):
+ """
+ Return the list of (classname, handle) tuples for all directly
+ referenced primary objects.
+
+ :returns: List of (classname, handle) tuples for referenced objects.
+ :rtype: list
+ """
+ return self.get_referenced_note_handles() + \
+ self.get_referenced_tag_handles() + \
+ self.get_referenced_citation_handles()
+
+ def get_handle_referents(self):
+ """
+ Return the list of child objects which may, directly or through
+ their children, reference primary objects.
+
+ :returns: Returns the list of objects referencing primary objects.
+ :rtype: list
+ """
+ return self.get_citation_child_list()
+
+ def merge(self, acquisition):
+ """
+ Merge the content of acquisition into this media object.
+
+ Lost: handle, id, file, date of acquisition.
+
+ :param acquisition: The media object to merge with the present object.
+ :rtype acquisition: MediaObject
+ """
+ self._merge_privacy(acquisition)
+ self._merge_attribute_list(acquisition)
+ self._merge_note_list(acquisition)
+ self._merge_citation_list(acquisition)
+ self._merge_tag_list(acquisition)
+
+ def set_mime_type(self, mime_type):
+ """
+ Set the MIME type associated with the MediaObject.
+
+ :param mime_type: MIME type to be assigned to the object
+ :type mime_type: str
+ """
+ self.mime = mime_type
+
+ def get_mime_type(self):
+ """
+ Return the MIME type associated with the MediaObject.
+
+ :returns: Returns the associated MIME type
+ :rtype: str
+ """
+ return self.mime
+
+ def set_path(self, path):
+ """Set the file path to the passed path."""
+ res = urlparse(path)
+ if res.scheme == '' or res.scheme == 'file':
+ self.path = os.path.normpath(path)
+ else:
+ # The principal case this path caters for is where the scheme is
+ # 'http' or 'https'. It would be possible to do some more extensive
+ # checking or processing, but for now we just store the reference
+ self.path = path
+
+ def get_path(self):
+ """Return the file path."""
+ return self.path
+
+ def set_description(self, text):
+ """Set the description of the image."""
+ self.desc = text
+
+ def get_description(self):
+ """Return the description of the image."""
+ return self.desc
diff --git a/pool/shard009/Python/0085856_views.py b/pool/shard009/Python/0085856_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..3da532dc64fe0b53f4e3dc8ee964498aefda8f1f
--- /dev/null
+++ b/pool/shard009/Python/0085856_views.py
@@ -0,0 +1,201 @@
+# Copyright 2012 United States Government as represented by the
+# Administrator of the National Aeronautics and Space Administration.
+# All Rights Reserved.
+#
+# Copyright 2012 OpenStack Foundation
+# 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.core.urlresolvers import reverse
+from django.core.urlresolvers import reverse_lazy
+from django.utils.datastructures import SortedDict
+from django.utils.translation import ugettext_lazy as _
+
+from horizon import exceptions
+from horizon import forms
+from horizon import tables
+from horizon.utils import memoized
+
+from openstack_dashboard import api
+from openstack_dashboard.dashboards.admin.instances \
+ import forms as project_forms
+from openstack_dashboard.dashboards.admin.instances \
+ import tables as project_tables
+from openstack_dashboard.dashboards.project.instances import views
+from openstack_dashboard.dashboards.project.instances.workflows \
+ import update_instance
+
+
+# re-use console from project.instances.views to make reflection work
+def console(args, **kvargs):
+ return views.console(args, **kvargs)
+
+
+# re-use vnc from project.instances.views to make reflection work
+def vnc(args, **kvargs):
+ return views.vnc(args, **kvargs)
+
+
+# re-use spice from project.instances.views to make reflection work
+def spice(args, **kvargs):
+ return views.spice(args, **kvargs)
+
+
+# re-use rdp from project.instances.views to make reflection work
+def rdp(args, **kvargs):
+ return views.rdp(args, **kvargs)
+
+
+class AdminUpdateView(views.UpdateView):
+ workflow_class = update_instance.AdminUpdateInstance
+ success_url = reverse_lazy("horizon:admin:instances:index")
+
+
+class AdminIndexView(tables.DataTableView):
+ table_class = project_tables.AdminInstancesTable
+ template_name = 'admin/instances/index.html'
+ page_title = _("Instances")
+
+ def has_more_data(self, table):
+ return self._more
+
+ def get_data(self):
+ instances = []
+ marker = self.request.GET.get(
+ project_tables.AdminInstancesTable._meta.pagination_param, None)
+ search_opts = self.get_filters({'marker': marker, 'paginate': True})
+ # Gather our tenants to correlate against IDs
+ try:
+ tenants, has_more = api.keystone.tenant_list(self.request)
+ except Exception:
+ tenants = []
+ msg = _('Unable to retrieve instance project information.')
+ exceptions.handle(self.request, msg)
+
+ if 'project' in search_opts:
+ ten_filter_ids = [t.id for t in tenants
+ if t.name == search_opts['project']]
+ del search_opts['project']
+ if len(ten_filter_ids) > 0:
+ search_opts['tenant_id'] = ten_filter_ids[0]
+ else:
+ self._more = False
+ return []
+
+ try:
+ instances, self._more = api.nova.server_list(
+ self.request,
+ search_opts=search_opts,
+ all_tenants=True)
+ except Exception:
+ self._more = False
+ exceptions.handle(self.request,
+ _('Unable to retrieve instance list.'))
+ if instances:
+ try:
+ api.network.servers_update_addresses(self.request, instances,
+ all_tenants=True)
+ except Exception:
+ exceptions.handle(
+ self.request,
+ message=_('Unable to retrieve IP addresses from Neutron.'),
+ ignore=True)
+
+ # Gather our flavors to correlate against IDs
+ try:
+ flavors = api.nova.flavor_list(self.request)
+ except Exception:
+ # If fails to retrieve flavor list, creates an empty list.
+ flavors = []
+
+ full_flavors = SortedDict([(f.id, f) for f in flavors])
+ tenant_dict = SortedDict([(t.id, t) for t in tenants])
+ # Loop through instances to get flavor and tenant info.
+ for inst in instances:
+ flavor_id = inst.flavor["id"]
+ try:
+ if flavor_id in full_flavors:
+ inst.full_flavor = full_flavors[flavor_id]
+ else:
+ # If the flavor_id is not in full_flavors list,
+ # gets it via nova api.
+ inst.full_flavor = api.nova.flavor_get(
+ self.request, flavor_id)
+ except Exception:
+ msg = _('Unable to retrieve instance size information.')
+ exceptions.handle(self.request, msg)
+ tenant = tenant_dict.get(inst.tenant_id, None)
+ inst.tenant_name = getattr(tenant, "name", None)
+ return instances
+
+ def get_filters(self, filters):
+ filter_field = self.table.get_filter_field()
+ filter_action = self.table._meta._filter_action
+ if filter_action.is_api_filter(filter_field):
+ filter_string = self.table.get_filter_string()
+ if filter_field and filter_string:
+ filters[filter_field] = filter_string
+ return filters
+
+
+class LiveMigrateView(forms.ModalFormView):
+ form_class = project_forms.LiveMigrateForm
+ template_name = 'admin/instances/live_migrate.html'
+ context_object_name = 'instance'
+ success_url = reverse_lazy("horizon:admin:instances:index")
+ page_title = _("Live Migrate")
+
+ def get_context_data(self, **kwargs):
+ context = super(LiveMigrateView, self).get_context_data(**kwargs)
+ context["instance_id"] = self.kwargs['instance_id']
+ return context
+
+ @memoized.memoized_method
+ def get_hosts(self, *args, **kwargs):
+ try:
+ return api.nova.host_list(self.request)
+ except Exception:
+ redirect = reverse("horizon:admin:instances:index")
+ msg = _('Unable to retrieve host information.')
+ exceptions.handle(self.request, msg, redirect=redirect)
+
+ @memoized.memoized_method
+ def get_object(self, *args, **kwargs):
+ instance_id = self.kwargs['instance_id']
+ try:
+ return api.nova.server_get(self.request, instance_id)
+ except Exception:
+ redirect = reverse("horizon:admin:instances:index")
+ msg = _('Unable to retrieve instance details.')
+ exceptions.handle(self.request, msg, redirect=redirect)
+
+ def get_initial(self):
+ initial = super(LiveMigrateView, self).get_initial()
+ _object = self.get_object()
+ if _object:
+ current_host = getattr(_object, 'OS-EXT-SRV-ATTR:host', '')
+ initial.update({'instance_id': self.kwargs['instance_id'],
+ 'current_host': current_host,
+ 'hosts': self.get_hosts()})
+ return initial
+
+
+class DetailView(views.DetailView):
+ redirect_url = 'horizon:admin:instances:index'
+ image_url = 'horizon:admin:images:detail'
+ volume_url = 'horizon:admin:volumes:volumes:detail'
+
+ def _get_actions(self, instance):
+ table = project_tables.AdminInstancesTable(self.request)
+ return table.render_row_actions(instance)
diff --git a/pool/shard009/Python/0085858_after_exit.py b/pool/shard009/Python/0085858_after_exit.py
new file mode 100644
index 0000000000000000000000000000000000000000..a858b639829a61fbe81800200dfdf1e697ea577a
--- /dev/null
+++ b/pool/shard009/Python/0085858_after_exit.py
@@ -0,0 +1,98 @@
+import argparse
+import logging
+import os
+import sys
+import subprocess
+import threading
+
+from typing import Sequence, Optional, List
+
+import orangecanvas.utils.shtools as sh
+
+
+def run_after_exit(
+ command: Sequence[str] = (), log: Optional[str] = None
+) -> None:
+ """
+ Run the `command` after this process exits.
+ """
+ # pass read end of a pipe to subprocess. It blocks to read from it
+ # and will not succeed until the write end is closed which will happen at
+ # this process's exit (assuming `w` is not leaked in a fork).
+ command = ["--arg=" + c for c in command]
+ if log is not None:
+ command.append("--log=" + log)
+ command = ["-m", __name__, *command]
+ with __write_fds_lock:
+ r, w = os.pipe()
+ __write_fds.append(w)
+ p = sh.python_process(
+ command,
+ stdin=r, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ # close the read end of the pipe
+ os.close(r)
+ # Popen warns in __del__ if child did not complete yet (should
+ # double fork to do this right, but since we exit immediately anyways).
+ __run_after_exit_processes.append(p)
+
+
+__run_after_exit_processes: List[subprocess.Popen] = []
+__write_fds: List[int] = []
+__write_fds_lock = threading.Lock()
+
+
+def __close_write_fd_after_fork():
+ while __write_fds:
+ w = __write_fds.pop()
+ try:
+ os.close(w)
+ except OSError:
+ pass
+ __write_fds_lock.release()
+
+
+if hasattr(os, "register_at_fork"):
+ os.register_at_fork(
+ before=__write_fds_lock.acquire,
+ after_in_child=__close_write_fd_after_fork,
+ after_in_parent=__write_fds_lock.release,
+ )
+
+
+def main(argv):
+ ap = argparse.ArgumentParser()
+ ap.add_argument("-f", default=0, type=int)
+ ap.add_argument("-a", "--arg", action='append', default=[])
+ ap.add_argument("--log", help="Log file", type=argparse.FileType("w"))
+ ns, rest = ap.parse_known_args(argv)
+
+ if ns.log is not None:
+ logging.basicConfig(level=logging.INFO, stream=ns.log)
+ log = logging.getLogger(__name__)
+
+ if ns.f is not None:
+ readfd = int(ns.f)
+ else:
+ readfd = 0
+
+ # read form readfd (an os.pipe read end) until EOF indicating parent
+ # closed the pipe (i.e. did exit)
+ log.info("Blocking on read from fd: %d", readfd)
+ c = os.read(readfd, 1)
+ if c != b"":
+ log.error("Unexpected content %r from parent", c)
+ else:
+ log.info("Parent closed fd; %d")
+
+ if ns.arg:
+ log.info("Starting new process with cmd: %r", ns.arg)
+ p = sh.create_process(
+ ns.arg, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ main.p = p
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/pool/shard009/Python/0085859_string.py b/pool/shard009/Python/0085859_string.py
new file mode 100644
index 0000000000000000000000000000000000000000..2610b7777207f8fffc000c25da51831352b485e0
--- /dev/null
+++ b/pool/shard009/Python/0085859_string.py
@@ -0,0 +1,215 @@
+"""
+Module for formatting output data in console (to string).
+"""
+from __future__ import annotations
+
+from shutil import get_terminal_size
+from typing import Iterable
+
+import numpy as np
+
+from pandas.io.formats.format import DataFrameFormatter
+from pandas.io.formats.printing import pprint_thing
+
+
+class StringFormatter:
+ """Formatter for string representation of a dataframe."""
+
+ def __init__(self, fmt: DataFrameFormatter, line_width: int | None = None):
+ self.fmt = fmt
+ self.adj = fmt.adj
+ self.frame = fmt.frame
+ self.line_width = line_width
+
+ def to_string(self) -> str:
+ text = self._get_string_representation()
+ if self.fmt.should_show_dimensions:
+ text = "".join([text, self.fmt.dimensions_info])
+ return text
+
+ def _get_strcols(self) -> list[list[str]]:
+ strcols = self.fmt.get_strcols()
+ if self.fmt.is_truncated:
+ strcols = self._insert_dot_separators(strcols)
+ return strcols
+
+ def _get_string_representation(self) -> str:
+ if self.fmt.frame.empty:
+ return self._empty_info_line
+
+ strcols = self._get_strcols()
+
+ if self.line_width is None:
+ # no need to wrap around just print the whole frame
+ return self.adj.adjoin(1, *strcols)
+
+ if self._need_to_wrap_around:
+ return self._join_multiline(strcols)
+
+ return self._fit_strcols_to_terminal_width(strcols)
+
+ @property
+ def _empty_info_line(self) -> str:
+ return (
+ f"Empty {type(self.frame).__name__}\n"
+ f"Columns: {pprint_thing(self.frame.columns)}\n"
+ f"Index: {pprint_thing(self.frame.index)}"
+ )
+
+ @property
+ def _need_to_wrap_around(self) -> bool:
+ return bool(self.fmt.max_cols is None or self.fmt.max_cols > 0)
+
+ def _insert_dot_separators(self, strcols: list[list[str]]) -> list[list[str]]:
+ str_index = self.fmt._get_formatted_index(self.fmt.tr_frame)
+ index_length = len(str_index)
+
+ if self.fmt.is_truncated_horizontally:
+ strcols = self._insert_dot_separator_horizontal(strcols, index_length)
+
+ if self.fmt.is_truncated_vertically:
+ strcols = self._insert_dot_separator_vertical(strcols, index_length)
+
+ return strcols
+
+ @property
+ def _adjusted_tr_col_num(self) -> int:
+ return self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num
+
+ def _insert_dot_separator_horizontal(
+ self, strcols: list[list[str]], index_length: int
+ ) -> list[list[str]]:
+ strcols.insert(self._adjusted_tr_col_num, [" ..."] * index_length)
+ return strcols
+
+ def _insert_dot_separator_vertical(
+ self, strcols: list[list[str]], index_length: int
+ ) -> list[list[str]]:
+ n_header_rows = index_length - len(self.fmt.tr_frame)
+ row_num = self.fmt.tr_row_num
+ for ix, col in enumerate(strcols):
+ cwidth = self.adj.len(col[row_num])
+
+ if self.fmt.is_truncated_horizontally:
+ is_dot_col = ix == self._adjusted_tr_col_num
+ else:
+ is_dot_col = False
+
+ if cwidth > 3 or is_dot_col:
+ dots = "..."
+ else:
+ dots = ".."
+
+ if ix == 0 and self.fmt.index:
+ dot_mode = "left"
+ elif is_dot_col:
+ cwidth = 4
+ dot_mode = "right"
+ else:
+ dot_mode = "right"
+
+ dot_str = self.adj.justify([dots], cwidth, mode=dot_mode)[0]
+ col.insert(row_num + n_header_rows, dot_str)
+ return strcols
+
+ def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str:
+ lwidth = self.line_width
+ adjoin_width = 1
+ strcols = list(strcols_input)
+
+ if self.fmt.index:
+ idx = strcols.pop(0)
+ # error: Argument 1 to "__call__" of "_NumberOp" has incompatible type
+ # "None"; expected "Union[int, float, complex, number, bool_]"
+ # error: Incompatible types in assignment (expression has type "number",
+ # variable has type "Optional[int]")
+ lwidth -= ( # type: ignore[assignment,arg-type]
+ np.array([self.adj.len(x) for x in idx]).max() + adjoin_width
+ )
+
+ col_widths = [
+ np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0
+ for col in strcols
+ ]
+
+ assert lwidth is not None
+ # error: Argument 1 to "_binify" has incompatible type "List[object]"; expected
+ # "List[int]"
+ col_bins = _binify(col_widths, lwidth) # type: ignore[arg-type]
+ nbins = len(col_bins)
+
+ if self.fmt.is_truncated_vertically:
+ assert self.fmt.max_rows_fitted is not None
+ nrows = self.fmt.max_rows_fitted + 1
+ else:
+ nrows = len(self.frame)
+
+ str_lst = []
+ start = 0
+ for i, end in enumerate(col_bins):
+ row = strcols[start:end]
+ if self.fmt.index:
+ row.insert(0, idx)
+ if nbins > 1:
+ if end <= len(strcols) and i < nbins - 1:
+ row.append([" \\"] + [" "] * (nrows - 1))
+ else:
+ row.append([" "] * nrows)
+ str_lst.append(self.adj.adjoin(adjoin_width, *row))
+ start = end
+ return "\n\n".join(str_lst)
+
+ def _fit_strcols_to_terminal_width(self, strcols: list[list[str]]) -> str:
+ from pandas import Series
+
+ lines = self.adj.adjoin(1, *strcols).split("\n")
+ max_len = Series(lines).str.len().max()
+ # plus truncate dot col
+ width, _ = get_terminal_size()
+ dif = max_len - width
+ # '+ 1' to avoid too wide repr (GH PR #17023)
+ adj_dif = dif + 1
+ col_lens = Series([Series(ele).apply(len).max() for ele in strcols])
+ n_cols = len(col_lens)
+ counter = 0
+ while adj_dif > 0 and n_cols > 1:
+ counter += 1
+ mid = round(n_cols / 2)
+ mid_ix = col_lens.index[mid]
+ col_len = col_lens[mid_ix]
+ # adjoin adds one
+ adj_dif -= col_len + 1
+ col_lens = col_lens.drop(mid_ix)
+ n_cols = len(col_lens)
+
+ # subtract index column
+ max_cols_fitted = n_cols - self.fmt.index
+ # GH-21180. Ensure that we print at least two.
+ max_cols_fitted = max(max_cols_fitted, 2)
+ self.fmt.max_cols_fitted = max_cols_fitted
+
+ # Call again _truncate to cut frame appropriately
+ # and then generate string representation
+ self.fmt.truncate()
+ strcols = self._get_strcols()
+ return self.adj.adjoin(1, *strcols)
+
+
+def _binify(cols: list[int], line_width: int) -> list[int]:
+ adjoin_width = 1
+ bins = []
+ curr_width = 0
+ i_last_column = len(cols) - 1
+ for i, w in enumerate(cols):
+ w_adjoined = w + adjoin_width
+ curr_width += w_adjoined
+ if i_last_column == i:
+ wrap = curr_width + 1 > line_width and i > 0
+ else:
+ wrap = curr_width + 2 > line_width and i > 0
+ if wrap:
+ bins.append(i)
+ curr_width = w_adjoined
+
+ bins.append(len(cols))
+ return bins
diff --git a/pool/shard009/Python/0085862_test_inject.py b/pool/shard009/Python/0085862_test_inject.py
new file mode 100644
index 0000000000000000000000000000000000000000..40280c24fdcd89429547d40721abdee99ab061d0
--- /dev/null
+++ b/pool/shard009/Python/0085862_test_inject.py
@@ -0,0 +1,130 @@
+# Copyright (C) 2013, 2014 Red Hat, Inc.
+#
+# This work is licensed under the GNU GPLv2 or later.
+# See the COPYING file in the top-level directory.
+
+import os
+import sys
+
+
+_alldistros = {}
+
+DEVFEDORA_URL = "http://dl.fedoraproject.org/pub/fedora/linux/development/%s/Server/%s/os/"
+FEDORA_URL = "http://dl.fedoraproject.org/pub/fedora/linux/releases/%s/Server/%s/os/"
+
+(WARN_RHEL5,
+ WARN_DEBIAN,
+ WARN_FEDORA) = range(1, 4)
+
+
+def prompt():
+ sys.stdout.write("(press enter to continue)")
+ sys.stdout.flush()
+ return sys.stdin.readline()
+
+
+KSOLD = "tests/data/inject/old-kickstart.ks"
+KSNEW = "tests/data/inject/new-kickstart.ks"
+PRESEED = "tests/data/inject/preseed.cfg"
+
+
+class Distro(object):
+ def __init__(self, name, url, filename, warntype=WARN_FEDORA):
+ self.name = name
+ self.url = url
+ self.warntype = warntype
+ self.filename = filename
+
+ self.kernel = None
+ self.initrd = None
+
+
+def _add(*args, **kwargs):
+ _d = Distro(*args, **kwargs)
+ _alldistros[_d.name] = _d
+
+
+_add("centos5.11", "http://vault.centos.org/5.11/os/x86_64/",
+ warntype=WARN_RHEL5, filename=KSOLD)
+_add("centos6.10", "http://vault.centos.org/6.10/os/x86_64",
+ warntype=WARN_RHEL5, filename=KSOLD)
+_add("centos7latest", "http://ftp.linux.ncsu.edu/pub/CentOS/7/os/x86_64/",
+ filename=KSNEW)
+_add("centos8stream",
+ "http://ftp.linux.ncsu.edu/pub/CentOS/8-stream/BaseOS/x86_64/os/",
+ filename=KSNEW)
+_add("fedora35", FEDORA_URL % ("29", "x86_64"), filename=KSNEW)
+_add("fedora36", DEVFEDORA_URL % ("35", "x86_64"), filename=KSNEW)
+_add("debian9",
+ "http://ftp.us.debian.org/debian/dists/stretch/main/installer-amd64/",
+ filename=PRESEED, warntype=WARN_DEBIAN)
+_add("debian11",
+ "http://ftp.us.debian.org/debian/dists/bullseye/main/installer-amd64/",
+ filename=PRESEED, warntype=WARN_DEBIAN)
+
+
+def _test_distro(distro):
+ os.system("clear")
+ print("\n")
+ if distro.warntype == WARN_RHEL5:
+ print("RHEL5, RHEL6, Fedora < 17: You'll get an error about a ")
+ print("bogus bootproto ITREADTHEKICKSTART. This means anaconda ")
+ print("read our busted kickstart.")
+ elif distro.warntype == WARN_DEBIAN:
+ print("Debian: Won't ask any questions, will autoconfig network, "
+ "then print a big red text box about a bad mirror config.")
+ elif distro.warntype == WARN_FEDORA:
+ print("RHEL, Fedora >= 17: Chokes on the bogus URI in the early ")
+ print("console screen when fetching the installer squashfs image.")
+
+ os.environ.pop("VIRTINST_TEST_SUITE", None)
+ os.environ["VIRTINST_INITRD_TEST"] = "1"
+
+ if distro.warntype == WARN_DEBIAN:
+ append = "auto=true"
+ else:
+ append = "\"ks=file:/%s\"" % os.path.basename(distro.filename)
+ cmd = ("./virt-install --connect qemu:///system "
+ "--name __virtinst__test__initrd__ --ram 2048 "
+ "--transient --destroy-on-exit --disk none "
+ "--location %s --initrd-inject %s "
+ "--install kernel_args=%s,kernel_args_overwrite=yes --debug" %
+ (distro.url, distro.filename, append))
+ print("\n\n" + cmd)
+ os.system(cmd)
+
+
+def _print_intro():
+ print("""
+
+
+This is an interactive test suite.
+
+We are going to launch various transient virt-installs, using initrd
+injections, that will cause installs to quickly fail. Look for the
+failure pattern to confirm that initrd injections are working as expected.
+
+""")
+ prompt()
+
+
+def _build_testfunc(dobj, do_setup):
+ def testfunc():
+ if do_setup:
+ _print_intro()
+ _test_distro(dobj)
+ return testfunc
+
+
+def _make_tests():
+ idx = 0
+ for dname, dobj in _alldistros.items():
+ idx += 1
+ name = "testInitrd%.3d_%s" % (idx, dname)
+
+ do_setup = idx == 1
+ testfunc = _build_testfunc(dobj, do_setup)
+ globals()[name] = testfunc
+
+
+_make_tests()
diff --git a/pool/shard009/Python/0085863_lc.py b/pool/shard009/Python/0085863_lc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3a453d65e6d51db799701fa40e47acc3aa86990
--- /dev/null
+++ b/pool/shard009/Python/0085863_lc.py
@@ -0,0 +1,148 @@
+"""The lagged coherence algorithm for estimating the rhythmicity of a neural signal."""
+
+from warnings import warn
+
+import numpy as np
+from scipy.signal.windows import hann
+
+from neurodsp.utils.checks import check_n_cycles
+from neurodsp.utils.data import create_freqs, split_signal
+from neurodsp.utils.decorators import multidim
+
+###################################################################################################
+###################################################################################################
+
+@multidim(select=[1])
+def compute_lagged_coherence(sig, fs, freqs, n_cycles=3, return_spectrum=False):
+ """Compute lagged coherence, reflecting the rhythmicity across a frequency range.
+
+ Parameters
+ ----------
+ sig : 1d array
+ Time series.
+ fs : float
+ Sampling rate, in Hz.
+ freqs : 1d array or list of float
+ The frequency values at which to estimate lagged coherence.
+ If array, defines the frequency values to use.
+ If list, define the frequency range, as [freq_start, freq_stop, freq_step].
+ The `freq_step` is optional, and defaults to 1. Range is inclusive of `freq_stop` value.
+ n_cycles : float or list of float, default: 3
+ The number of cycles to use to compute lagged coherence, for each frequency.
+ If a single value, the same number of cycles is used for each frequency.
+ If a list or list_like, there should be a value corresponding to each frequency.
+ return_spectrum : bool, optional, default: False
+ If True, return the lagged coherence for all frequency values.
+ Otherwise, only the mean lagged coherence value across the frequency range is returned.
+
+ Returns
+ -------
+ lcs : float or 1d array
+ If `return_spectrum` is False: mean lagged coherence value across the frequency range.
+ If `return_spectrum` is True: lagged coherence values for all frequencies.
+ freqs : 1d array
+ Frequencies, corresponding to the lagged coherence values, in Hz.
+ Only returned if `return_spectrum` is True.
+
+ Notes
+ -----
+ - The lagged coherence algorithm is described in [1]_.
+
+ References
+ ----------
+ .. [1] Fransen, A. M., van Ede, F., & Maris, E. (2015). Identifying neuronal
+ oscillations using rhythmicity. NeuroImage, 118, 256-267.
+ DOI: https://doi.org/10.1016/j.neuroimage.2015.06.003
+
+ Examples
+ --------
+ Compute lagged coherence for a simulated signal with beta oscillations:
+
+ >>> from neurodsp.sim import sim_combined
+ >>> sig = sim_combined(n_seconds=10, fs=500,
+ ... components={'sim_synaptic_current': {},
+ ... 'sim_bursty_oscillation': {'freq': 20,
+ ... 'enter_burst': .50,
+ ... 'leave_burst': .25}})
+ >>> lag_cohs = compute_lagged_coherence(sig, fs=500, freqs=(5, 35))
+ """
+
+ if isinstance(freqs, (tuple, list)):
+ freqs = create_freqs(*freqs)
+ n_cycles = check_n_cycles(n_cycles, len(freqs))
+
+ # Calculate lagged coherence for each frequency
+ lcs = np.zeros(len(freqs))
+ for ind, (freq, n_cycle) in enumerate(zip(freqs, n_cycles)):
+ lcs[ind] = lagged_coherence_1freq(sig, fs, freq, n_cycles=n_cycle)
+
+ # Check if all values were properly estimated
+ if sum(np.isnan(lcs)) > 0:
+ warn("NEURODSP - LAGGED COHERENCE WARNING:"
+ "\nLagged coherence could not be estimated for at least some requested frequencies."
+ "\nThis happens, especially with low frequencies, when there are not enough samples "
+ "per segment and/or not enough segments available to estimate the measure."
+ "\nTry using a greater number of cycles and/or a longer signal length, and/or "
+ "adjust the frequency range.")
+
+ if return_spectrum:
+ return lcs, freqs
+ else:
+ return np.mean(lcs)
+
+
+def lagged_coherence_1freq(sig, fs, freq, n_cycles):
+ """Compute the lagged coherence at a particular frequency.
+
+ Parameters
+ ----------
+ sig : 1d array
+ Time series.
+ fs : float
+ Sampling rate, in Hz.
+ freq : float
+ The frequency at which to estimate lagged coherence.
+ n_cycles : float
+ The number of cycles of the given frequency to use to compute lagged coherence.
+
+ Returns
+ -------
+ lc : float
+ The computed lagged coherence value.
+
+ Notes
+ -----
+ - Lagged coherence is computed using hanning-tapered FFTs.
+ - The returned lagged coherence value is bound between 0 and 1.
+ """
+
+ # Determine number of samples to be used in each window to compute lagged coherence
+ n_samps = int(np.ceil(n_cycles * fs / freq))
+
+ # Split the signal into chunks
+ chunks = split_signal(sig, n_samps)
+ n_chunks = len(chunks)
+
+ # Create the window to apply to each chunk
+ hann_window = hann(n_samps)
+
+ # Create the frequency vector, finding the frequency value of interest
+ fft_freqs = np.fft.fftfreq(n_samps, 1 / float(fs))
+ fft_freqs_idx = np.argmin(np.abs(fft_freqs - freq))
+
+ # Calculate the Fourier coefficients across chunks for the frequency of interest
+ fft_coefs = np.zeros(n_chunks, dtype=complex)
+ for ind, chunk in enumerate(chunks):
+ fourier_coef = np.fft.fft(chunk * hann_window)
+ fft_coefs[ind] = fourier_coef[fft_freqs_idx]
+
+ # Compute lagged coherence across data segments
+ lcs_num = 0
+ for ind in range(n_chunks - 1):
+ lcs_num += fft_coefs[ind] * np.conj(fft_coefs[ind + 1])
+ lcs_denom = np.sqrt(np.sum(np.abs(fft_coefs[:-1])**2) * np.sum(np.abs(fft_coefs[1:])**2))
+
+ # Normalize the lagged coherence value
+ lc_val = np.abs(lcs_num / lcs_denom)
+
+ return lc_val
diff --git a/pool/shard009/Python/0085864_Tools.py b/pool/shard009/Python/0085864_Tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..112edb6322db3ae53e6c99558cac38b84d641b47
--- /dev/null
+++ b/pool/shard009/Python/0085864_Tools.py
@@ -0,0 +1,91 @@
+#***************************************************************************
+#* *
+#* Copyright (c) 2016 *
+#* Jose Luis Cercos Pita *
+#* *
+#* This program is free software; you can redistribute it and/or modify *
+#* it under the terms of the GNU Lesser General Public License (LGPL) *
+#* as published by the Free Software Foundation; either version 2 of *
+#* the License, or (at your option) any later version. *
+#* for detail see the LICENCE text file. *
+#* *
+#* 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 Library General Public License for more details. *
+#* *
+#* You should have received a copy of the GNU Library 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 *
+#* *
+#***************************************************************************
+
+
+import FreeCAD as App
+import Units
+import WeightInstance as Instance
+import shipUtils.Units as USys
+
+
+def createWeight(shapes, ship, density):
+ """Create a new weight instance
+
+ Position arguments:
+ shapes -- List of shapes of the weight
+ ship -- Ship owner
+ density -- Density of the object. 4 possibilities are considered here:
+ * Density as Mass/Volume: then the weight will be considered as a
+ volumetric object. Used for blocks or similar.
+ * Density as Mass/Area: then the weight will be considered as an area
+ element. Used for structural shells.
+ * Density as Mass/Length: then the weight will be cosidered as a linear
+ element. Used for linear structural reinforcements.
+ * Mass: Then a punctual mass will be considered. Used for complex
+ weights, like engines or other machines.
+
+ Returned value:
+ The new weight object
+
+ It is strongly recommended to pass just shapes matching with the provided
+ density, e.g. don't use volumetric shapes with a linear density value (kg/m)
+
+ The tool will claim the new weight as a child of the ship object. Please do
+ not remove the partner ship object before removing this new weight before.
+ """
+ # Create the object
+ obj = App.ActiveDocument.addObject("Part::FeaturePython", "Weight")
+ weight = Instance.Weight(obj, shapes, ship)
+ Instance.ViewProviderWeight(obj.ViewObject)
+
+ # Setup the mass/density value
+ m_unit = "kg"
+ l_unit = "m"
+ m_qty = Units.Quantity(1, Units.Mass)
+ l_qty = Units.Quantity(1, Units.Length)
+ a_qty = Units.Quantity(1, Units.Area)
+ v_qty = Units.Quantity(1, Units.Volume)
+ if density.Unit == m_qty.Unit:
+ w_unit = m_unit
+ obj.Mass = density.getValueAs(w_unit).Value
+ elif density.Unit == (m_qty / l_qty).Unit:
+ w_unit = m_unit + '/' + l_unit
+ obj.LineDens = density.getValueAs(w_unit).Value
+ elif density.Unit == (m_qty / a_qty).Unit:
+ w_unit = m_unit + '/' + l_unit + '^2'
+ obj.AreaDens = density.getValueAs(w_unit).Value
+ elif density.Unit == (m_qty / v_qty).Unit:
+ w_unit = m_unit + '/' + l_unit + '^3'
+ obj.Dens = density.getValueAs(w_unit).Value
+
+ # Set it as a child of the ship
+ weights = ship.Weights[:]
+ weights.append(obj.Name)
+ ship.Weights = weights
+ ship.Proxy.cleanWeights(ship)
+ ship.Proxy.cleanTanks(ship)
+ ship.Proxy.cleanLoadConditions(ship)
+
+ App.ActiveDocument.recompute()
+
+ return obj
\ No newline at end of file
diff --git a/pool/shard009/Python/0085870_urls.py b/pool/shard009/Python/0085870_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c65a0b24d7a20afe346a412e8b4814f3fbad069
--- /dev/null
+++ b/pool/shard009/Python/0085870_urls.py
@@ -0,0 +1,27 @@
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.conf.urls import include, url
+from django.core.urlresolvers import reverse_lazy
+from django.conf.urls.static import static
+from django.contrib import admin
+from django.views.generic.base import RedirectView
+from rest_framework.routers import DefaultRouter
+from services_areas.views import ServiceAreaViewSet
+
+from users.views import UserViewSet
+
+router = DefaultRouter()
+router.register(r'providers', UserViewSet)
+router.register(r'services-areas', ServiceAreaViewSet)
+
+urlpatterns = [
+ url(r'^admin/', include(admin.site.urls)),
+ url(r'^api/v1/', include('authentication.urls')),
+ url(r'^api/v1/', include(router.urls)),
+
+ # the 'api-root' from django rest-frameworks default router
+ # http://www.django-rest-framework.org/api-guide/routers/#defaultrouter
+ url(r'^$', RedirectView.as_view(url=reverse_lazy('api-root'), permanent=False)),
+
+] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
diff --git a/pool/shard009/Python/0085874_jquery_tags.py b/pool/shard009/Python/0085874_jquery_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..30544a3c28e341dbd5db613bb23ae7b2c8986ae6
--- /dev/null
+++ b/pool/shard009/Python/0085874_jquery_tags.py
@@ -0,0 +1,12 @@
+import os
+from django.conf import settings
+from django import template
+
+register = template.Library()
+
+@register.simple_tag
+def include_jquery():
+ url = getattr(settings, 'MEDIA_URL')
+ if hasattr(settings, 'STATIC_URL'):
+ url = getattr(settings, 'STATIC_URL')
+ return "" % os.path.join(url, 'jquery', 'jquery-1.4.3.min.js')
diff --git a/pool/shard009/Python/0085877_test_power_control_rest.py b/pool/shard009/Python/0085877_test_power_control_rest.py
new file mode 100644
index 0000000000000000000000000000000000000000..445b4a98716c5778cd0a6efbea0e79a4c5e9036f
--- /dev/null
+++ b/pool/shard009/Python/0085877_test_power_control_rest.py
@@ -0,0 +1,218 @@
+# -*- coding: utf-8 -*-
+import pytest
+
+from cfme import test_requirements
+from cfme.common.vm import VM
+from utils import testgen
+from utils.generators import random_vm_name
+from utils.wait import wait_for
+from utils.log import logger
+from cfme.cloud.provider.gce import GCEProvider
+from cfme.cloud.provider.ec2 import EC2Provider
+from cfme.infrastructure.provider.scvmm import SCVMMProvider
+from cfme.infrastructure.provider.rhevm import RHEVMProvider
+
+
+pytestmark = [
+ test_requirements.power,
+ pytest.mark.usefixtures('uses_infra_providers', 'uses_cloud_providers'),
+ pytest.mark.tier(2)
+]
+
+
+def pytest_generate_tests(metafunc):
+ argnames, argvalues, idlist = testgen.all_providers(metafunc)
+ testgen.parametrize(metafunc, argnames, argvalues, ids=idlist, scope="module")
+
+
+@pytest.fixture(scope='function')
+def vm_name():
+ return random_vm_name('pwrctl')
+
+
+@pytest.fixture(scope="function")
+def vm_obj(request, provider, setup_provider, small_template, vm_name):
+ vm_obj = VM.factory(vm_name, provider, template_name=small_template)
+
+ @request.addfinalizer
+ def _delete_vm():
+ try:
+ provider.mgmt.delete_vm(vm_obj.name)
+ except Exception:
+ logger.warning("Failed to delete vm `{}`.".format(vm_obj.name))
+
+ vm_obj.create_on_provider(timeout=2400, find_in_cfme=True, allow_skip="default")
+ return vm_obj
+
+
+def wait_for_vm_state_change(vm_obj, state):
+ vm = vm_obj.get_vm_via_rest()
+ if vm_obj.provider.one_of(GCEProvider, EC2Provider, SCVMMProvider):
+ num_sec = 4000 # extra time for slow providers
+ else:
+ num_sec = 1200
+
+ def _state_changed():
+ vm.reload()
+ return vm.power_state == state
+ wait_for(_state_changed, num_sec=num_sec, delay=45, silent_failure=True,
+ message="Wait for VM state `{}` (current state: {})".format(state, vm.power_state))
+
+
+def verify_vm_power_state(vm, state):
+ vm.reload()
+ return vm.power_state == state
+
+
+def verify_action_result(rest_api, assert_success=True):
+ assert rest_api.response.status_code == 200
+ response = rest_api.response.json()
+ if 'results' in response:
+ response = response['results'][0]
+ message = response['message']
+ success = response['success']
+ if assert_success:
+ assert success
+ return success, message
+
+
+@pytest.mark.parametrize("from_detail", [True, False], ids=["cfrom_detail", "from_collection"])
+def test_stop_vm_rest(appliance, vm_obj, verify_vm_running, soft_assert, from_detail):
+ """Test stop of vm
+
+ Prerequisities:
+
+ * An appliance with ``/api`` available.
+ * VM
+
+ Steps:
+
+ * POST /api/vms/ (method ``stop``)
+ OR
+ * POST /api/vms (method ``stop``) with ``href`` of the vm or vms
+
+ Metadata:
+ test_flag: rest
+ """
+ rest_api = appliance.rest_api
+ vm_obj.wait_for_vm_state_change(desired_state=vm_obj.STATE_ON)
+ vm = rest_api.collections.vms.get(name=vm_obj.name)
+
+ if from_detail:
+ vm.action.stop()
+ else:
+ rest_api.collections.vms.action.stop(vm)
+ verify_action_result(rest_api)
+ wait_for_vm_state_change(vm_obj, vm_obj.STATE_OFF)
+ soft_assert(not verify_vm_power_state(vm, vm_obj.STATE_ON), "vm still running")
+
+
+@pytest.mark.parametrize("from_detail", [True, False], ids=["from_detail", "from_collection"])
+def test_start_vm_rest(appliance, vm_obj, verify_vm_stopped, soft_assert, from_detail):
+ """Test start vm
+
+ Prerequisities:
+
+ * An appliance with ``/api`` available.
+ * VM
+
+ Steps:
+
+ * POST /api/vms/ (method ``start``)
+ OR
+ * POST /api/vms (method ``start``) with ``href`` of the vm or vms
+
+ Metadata:
+ test_flag: rest
+ """
+ rest_api = appliance.rest_api
+ vm_obj.wait_for_vm_state_change(desired_state=vm_obj.STATE_OFF, timeout=1200)
+ vm = rest_api.collections.vms.get(name=vm_obj.name)
+
+ if from_detail:
+ vm.action.start()
+ else:
+ rest_api.collections.vms.action.start(vm)
+ verify_action_result(rest_api)
+ wait_for_vm_state_change(vm_obj, vm_obj.STATE_ON)
+ soft_assert(verify_vm_power_state(vm, vm_obj.STATE_ON), "vm not running")
+
+
+@pytest.mark.parametrize("from_detail", [True, False], ids=["from_detail", "from_collection"])
+def test_suspend_vm_rest(appliance, vm_obj, verify_vm_running, soft_assert, from_detail):
+ """Test suspend vm
+
+ Prerequisities:
+
+ * An appliance with ``/api`` available.
+ * VM
+
+ Steps:
+
+ * POST /api/vms/ (method ``suspend``)
+ OR
+ * POST /api/vms (method ``suspend``) with ``href`` of the vm or vms
+
+ Metadata:
+ test_flag: rest
+ """
+ rest_api = appliance.rest_api
+ vm_obj.wait_for_vm_state_change(desired_state=vm_obj.STATE_ON)
+ vm = rest_api.collections.vms.get(name=vm_obj.name)
+
+ if from_detail:
+ vm.action.suspend()
+ else:
+ rest_api.collections.vms.action.suspend(vm)
+ success, message = verify_action_result(rest_api, assert_success=False)
+ if vm_obj.provider.one_of(GCEProvider, EC2Provider):
+ assert success is False
+ assert "not available" in message
+ else:
+ assert success
+ wait_for_vm_state_change(vm_obj, vm_obj.STATE_SUSPENDED)
+ soft_assert(verify_vm_power_state(vm, vm_obj.STATE_SUSPENDED), "vm not suspended")
+
+
+@pytest.mark.uncollectif(lambda provider: provider.one_of(RHEVMProvider),
+ reason='Not supported for RHV provider')
+@pytest.mark.parametrize("from_detail", [True, False], ids=["from_detail", "from_collection"])
+def test_reset_vm_rest(vm_obj, verify_vm_running, from_detail, appliance):
+ """
+ Test reset vm
+
+ Prerequisities:
+
+ * An appliance with ``/api`` available.
+ * VM
+
+ Steps:
+
+ * POST /api/vms/ (method ``reset``)
+ OR
+ * POST /api/vms (method ``reset``) with ``href`` of the vm or vms
+
+ Metadata:
+ test_flag: rest
+ """
+ rest_api = appliance.rest_api
+ vm_obj.wait_for_vm_state_change(desired_state=vm_obj.STATE_ON)
+ vm = rest_api.collections.vms.get(name=vm_obj.name)
+
+ old_date = vm.updated_on
+ if from_detail:
+ vm.action.reset()
+ else:
+ rest_api.collections.vms.action.reset(vm)
+ success, message = verify_action_result(rest_api, assert_success=False)
+ if appliance.version < '5.7':
+ unsupported_providers = (GCEProvider, EC2Provider, SCVMMProvider)
+ else:
+ unsupported_providers = (GCEProvider, EC2Provider)
+ if vm_obj.provider.one_of(*unsupported_providers):
+ assert success is False
+ assert "not available" in message
+ else:
+ assert success
+ wait_for(lambda: vm.updated_on >= old_date,
+ num_sec=600, delay=20, fail_func=vm.reload, message='Wait for VM to reset')
diff --git a/pool/shard009/Python/0085879_status.py b/pool/shard009/Python/0085879_status.py
new file mode 100644
index 0000000000000000000000000000000000000000..59f74d7bf9aa774548b059c0112bb6503d7b8143
--- /dev/null
+++ b/pool/shard009/Python/0085879_status.py
@@ -0,0 +1,191 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright © 2012 Pierre Raybaut
+# Licensed under the terms of the MIT License
+# (see SMlib/__init__.py for details)
+
+"""Status bar widgets"""
+
+from SMlib.QtGui import QWidget, QHBoxLayout, QLabel
+from SMlib.QtCore import QTimer, SIGNAL
+
+# Local import
+from SMlib.configs.baseconfig import _
+from SMlib.configs.guiconfig import get_font
+
+
+class StatusBarWidget(QWidget):
+ def __init__(self, parent, statusbar):
+ QWidget.__init__(self, parent)
+
+ self.label_font = font = get_font('editor')
+ font.setPointSize(self.font().pointSize())
+ font.setBold(True)
+
+ layout = QHBoxLayout()
+ layout.setContentsMargins(0, 0, 0, 0)
+ self.setLayout(layout)
+
+ statusbar.addPermanentWidget(self)
+
+
+#==============================================================================
+# Main window-related status bar widgets
+#==============================================================================
+class BaseTimerStatus(StatusBarWidget):
+ TITLE = None
+ TIP = None
+ def __init__(self, parent, statusbar):
+ StatusBarWidget.__init__(self, parent, statusbar)
+ self.setToolTip(self.TIP)
+ layout = self.layout()
+ layout.addWidget(QLabel(self.TITLE))
+ self.label = QLabel()
+ self.label.setFont(self.label_font)
+ layout.addWidget(self.label)
+ layout.addSpacing(20)
+ if self.is_supported():
+ self.timer = QTimer()
+ self.connect(self.timer, SIGNAL('timeout()'), self.update_label)
+ self.timer.start(2000)
+ else:
+ self.timer = None
+ self.hide()
+
+ def set_interval(self, interval):
+ """Set timer interval (ms)"""
+ if self.timer is not None:
+ self.timer.setInterval(interval)
+
+ def import_test(self):
+ """Raise ImportError if feature is not supported"""
+ raise NotImplementedError
+
+ def is_supported(self):
+ """Return True if feature is supported"""
+ try:
+ self.import_test()
+ return True
+ except ImportError:
+ return False
+
+ def get_value(self):
+ """Return value (e.g. CPU or memory usage)"""
+ raise NotImplementedError
+
+ def update_label(self):
+ """Update status label widget, if widget is visible"""
+ if self.isVisible():
+ self.label.setText('%d %%' % self.get_value())
+
+class MemoryStatus(BaseTimerStatus):
+ TITLE = _("Memory:")
+ TIP = _("Memory usage status: "
+ "requires the `psutil` (>=v0.3) library on non-Windows platforms")
+ def import_test(self):
+ """Raise ImportError if feature is not supported"""
+ from SMlib.utils.system import memory_usage # analysis:ignore
+
+ def get_value(self):
+ """Return memory usage"""
+ from SMlib.utils.system import memory_usage
+ return memory_usage()
+
+class CPUStatus(BaseTimerStatus):
+ TITLE = _("CPU:")
+ TIP = _("CPU usage status: requires the `psutil` (>=v0.3) library")
+ def import_test(self):
+ """Raise ImportError if feature is not supported"""
+ from SMlib.utils import programs
+ if not programs.is_module_installed('psutil', '>=0.2.0'):
+ # The `interval` argument in `psutil.cpu_percent` function
+ # was introduced in v0.2.0
+ raise ImportError
+
+ def get_value(self):
+ """Return CPU usage"""
+ import psutil
+ return psutil.cpu_percent(interval=0)
+
+
+#==============================================================================
+# Editor-related status bar widgets
+#==============================================================================
+class ReadWriteStatus(StatusBarWidget):
+ def __init__(self, parent, statusbar):
+ StatusBarWidget.__init__(self, parent, statusbar)
+ layout = self.layout()
+ layout.addWidget(QLabel(_("Permissions:")))
+ self.readwrite = QLabel()
+ self.readwrite.setFont(self.label_font)
+ layout.addWidget(self.readwrite)
+ layout.addSpacing(20)
+
+ def readonly_changed(self, readonly):
+ readwrite = "R" if readonly else "RW"
+ self.readwrite.setText(readwrite.ljust(3))
+
+class EOLStatus(StatusBarWidget):
+ def __init__(self, parent, statusbar):
+ StatusBarWidget.__init__(self, parent, statusbar)
+ layout = self.layout()
+ layout.addWidget(QLabel(_("End-of-lines:")))
+ self.eol = QLabel()
+ self.eol.setFont(self.label_font)
+ layout.addWidget(self.eol)
+ layout.addSpacing(20)
+
+ def eol_changed(self, os_name):
+ os_name = unicode(os_name)
+ self.eol.setText({"nt": "CRLF", "posix": "LF"}.get(os_name, "CR"))
+
+class EncodingStatus(StatusBarWidget):
+ def __init__(self, parent, statusbar):
+ StatusBarWidget.__init__(self, parent, statusbar)
+ layout = self.layout()
+ layout.addWidget(QLabel(_("Encoding:")))
+ self.encoding = QLabel()
+ self.encoding.setFont(self.label_font)
+ layout.addWidget(self.encoding)
+ layout.addSpacing(20)
+
+ def encoding_changed(self, encoding):
+ self.encoding.setText(str(encoding).upper().ljust(15))
+
+class CursorPositionStatus(StatusBarWidget):
+ def __init__(self, parent, statusbar):
+ StatusBarWidget.__init__(self, parent, statusbar)
+ layout = self.layout()
+ layout.addWidget(QLabel(_("Line:")))
+ self.line = QLabel()
+ self.line.setFont(self.label_font)
+ layout.addWidget(self.line)
+ layout.addWidget(QLabel(_("Column:")))
+ self.column = QLabel()
+ self.column.setFont(self.label_font)
+ layout.addWidget(self.column)
+ self.setLayout(layout)
+
+ def cursor_position_changed(self, line, index):
+ self.line.setText("%-6d" % (line+1))
+ self.column.setText("%-4d" % (index+1))
+
+
+def test():
+ from SMlib.QtGui import QMainWindow
+ from SMlib.utils.qthelpers import qapplication
+ app = qapplication()
+ win = QMainWindow()
+ win.setWindowTitle("Status widgets test")
+ win.resize(900, 300)
+ statusbar = win.statusBar()
+ swidgets = []
+ for klass in (ReadWriteStatus, EOLStatus, EncodingStatus,
+ CursorPositionStatus, MemoryStatus, CPUStatus):
+ swidget = klass(win, statusbar)
+ swidgets.append(swidget)
+ win.show()
+ app.exec_()
+
+if __name__ == "__main__":
+ test()
diff --git a/pool/shard009/Python/0085882_contemporary.py b/pool/shard009/Python/0085882_contemporary.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4488a09dec8ec313f00572b101e20b16efc76e4
--- /dev/null
+++ b/pool/shard009/Python/0085882_contemporary.py
@@ -0,0 +1,72 @@
+# coding: utf-8
+from django.db import models
+from django.core.urlresolvers import reverse
+from django.core.validators import RegexValidator
+
+from edc.audit.audit_trail import AuditTrail
+from edc.choices.common import YES_NO
+
+from .base_scheduled_visit_model import BaseScheduledVisitModel
+
+
+class Contemporary (BaseScheduledVisitModel):
+
+ diagnosis_date = models.DateField(
+ verbose_name="Date of Diagnosis",
+ help_text="", )
+ specimen_collecton = models.DateField(
+ verbose_name="Specimen Collection",
+ help_text="", )
+ specimen_size = models.CharField(
+ verbose_name="Specimen size",
+ max_length=25,
+ help_text="", )
+ nature_of_specimen = models.CharField(
+ verbose_name="Nature of specimen",
+ max_length=45,
+ help_text="", )
+ tissues = models.CharField(
+ verbose_name="Tissues",
+ max_length=45,
+ help_text="", )
+ topography_code = models.CharField(
+ max_length=15,
+ verbose_name="Cancer Site",
+ validators=[RegexValidator(
+ regex=r'^([C](\d{2})|[C](\d{2}\.\d{1}))$',
+ message=('A site code always starts with a C, followed by numbers: integer or'
+ 'decimal.FORMAT is CXX or CXX.X')), ],
+ help_text="record ICD topography code", )
+ morphology_code = models.CharField(
+ max_length=15,
+ verbose_name="Clinical and/or Pathologic Diagnosis",
+ validators=[RegexValidator(
+ regex=r'^[M]{1}[0-9]{4}[/][3]{1}$',
+ message='A site code always starts with a M, followed by four numbers and a /3'), ],
+ help_text="record ICD morphology code", )
+ diagnosis = models.TextField(
+ verbose_name="Diagnosis",
+ max_length=150,
+ help_text="", )
+ any_duplications = models.CharField(
+ verbose_name="Any sample duplications?",
+ max_length=3,
+ choices=YES_NO, )
+
+ history = AuditTrail()
+
+ def get_visit(self):
+ return self.hnscc_visit
+
+ def __unicode__(self):
+ return unicode(self.hnscc_visit)
+
+ def get_absolute_url(self):
+ return reverse('admin:hnscc_subject_contemporary_change', args=(self.id,))
+
+ objects = models.Manager()
+
+ class Meta:
+ app_label = "hnscc_subject"
+ verbose_name = "Contemporary"
+ verbose_name_plural = "Contemporary"
diff --git a/pool/shard009/Python/0085884_train_flair_POS.py b/pool/shard009/Python/0085884_train_flair_POS.py
new file mode 100644
index 0000000000000000000000000000000000000000..a62995fc1e40d7513b1674b0a0bcf5d2d76f3a12
--- /dev/null
+++ b/pool/shard009/Python/0085884_train_flair_POS.py
@@ -0,0 +1,61 @@
+from flair.data import TaggedCorpus, Sentence
+from flair.data_fetcher import NLPTaskDataFetcher, NLPTask
+from flair.embeddings import TokenEmbeddings, WordEmbeddings, StackedEmbeddings, FlairEmbeddings
+from typing import List
+from flair.models import SequenceTagger
+from torch.optim.adam import Adam
+
+columns = {0: 'text', 1: 'pos'}
+data_folder = 'data/'
+corpus: TaggedCorpus = NLPTaskDataFetcher.load_column_corpus(data_folder, columns,
+ train_file='Miami_Universal_Tagged.tsv',
+ test_file='S7_Universal_Tagged.tsv',
+ dev_file='KC_ARIS_Universal_Tagged.tsv')
+temp = corpus.train[0]
+def split_sentence(tokens, seq_len = 30):
+ tokens = [tokens[i: seq_len+i] for i in range(0, len(tokens), seq_len)]
+ train = []
+ for t in tokens:
+ s = Sentence()
+ s.tokens = t
+ train.append(s)
+ return train
+train = split_sentence(corpus.train[0])
+print(corpus.test)
+test = split_sentence(corpus.test[0])
+dev = split_sentence(corpus.dev[0])
+print(len(train))
+print(len(test))
+print(len(dev))
+corpus = TaggedCorpus(train, dev, test)
+tag_type = 'pos'
+tag_dictionary = corpus.make_tag_dictionary(tag_type=tag_type)
+print(tag_dictionary.idx2item)
+embedding_types: List[TokenEmbeddings] = [
+ FlairEmbeddings('news-forward'),
+ FlairEmbeddings('news-backward'),
+ FlairEmbeddings('spanish-forward'),
+ FlairEmbeddings('spanish-backward')
+]
+embeddings: StackedEmbeddings = StackedEmbeddings(embeddings=embedding_types)
+tagger: SequenceTagger = SequenceTagger(
+ hidden_size=512,
+ embeddings=embeddings,
+ tag_dictionary=tag_dictionary,
+ tag_type=tag_type,
+ use_rnn=True,
+ use_crf=True,
+ rnn_layers = 3,
+ dropout = 0.3
+)
+
+
+from flair.trainers import ModelTrainer
+
+trainer: ModelTrainer = ModelTrainer(tagger, corpus, optimizer = Adam)
+trainer.train('resources/taggers/pos',
+ learning_rate = 1e-4,
+ mini_batch_size=32,
+ max_epochs=50)
+
+
diff --git a/pool/shard009/Python/0085890_test_mp2.py b/pool/shard009/Python/0085890_test_mp2.py
new file mode 100644
index 0000000000000000000000000000000000000000..25cced24f90b0780d7634c8b8b72ea9a34d4dab9
--- /dev/null
+++ b/pool/shard009/Python/0085890_test_mp2.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# mpirun -np 2 python test_mp2.py
+
+import numpy
+from pyscf import lib
+from pyscf import gto
+from pyscf import scf
+from pyscf import mp
+from mpi4pyscf import mp as mpimp
+
+mol = gto.Mole()
+mol.atom = [
+ [8 , (0. , 0. , 0.)],
+ [1 , (0. , -0.757 , 0.587)],
+ [1 , (0. , 0.757 , 0.587)]]
+mol.basis = 'cc-pvdz'
+mol.build()
+mf = scf.RHF(mol).run()
+e = mp.RMP2(mf).kernel()[0]
+
+pt = mpimp.RMP2(mf)
+emp2 = pt.kernel()[0]
+print(emp2 - e)
+
diff --git a/pool/shard009/Python/0085896_test_schema_migration.py b/pool/shard009/Python/0085896_test_schema_migration.py
new file mode 100644
index 0000000000000000000000000000000000000000..708eafa41a1c883993ea58de5cbd3f6e9281dafb
--- /dev/null
+++ b/pool/shard009/Python/0085896_test_schema_migration.py
@@ -0,0 +1,33 @@
+import json
+import pytest
+
+from randovania.game_description import data_reader, data_writer, game_migration
+
+
+def test_round_trip_small(test_files_dir):
+ # Setup
+ with test_files_dir.joinpath("prime2_small_v1.json").open("r") as data_file:
+ original_data = game_migration.migrate_to_current(json.load(data_file))
+
+ game = data_reader.decode_data(original_data)
+
+ encoded_data = data_writer.write_game_description(game)
+ assert encoded_data == original_data
+
+def test_round_trip_area_conflict(test_files_dir):
+ with test_files_dir.joinpath("prime2_small_v1.json").open("r") as data_file:
+ json_data = json.load(data_file)
+
+ json_data["worlds"][0]["areas"].append(dict(json_data["worlds"][0]["areas"][0]))
+
+ with pytest.raises(ValueError):
+ game_migration.migrate_to_current(json_data)
+
+def test_round_trip_node_conflict(test_files_dir):
+ with test_files_dir.joinpath("prime2_small_v1.json").open("r") as data_file:
+ json_data = json.load(data_file)
+
+ json_data["worlds"][0]["areas"][0]["nodes"].append(dict(json_data["worlds"][0]["areas"][0]["nodes"][0]))
+
+ with pytest.raises(ValueError):
+ game_migration.migrate_to_current(json_data)
diff --git a/pool/shard009/Python/0085897_init__.py b/pool/shard009/Python/0085897_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ce967e29abbb9268dd60d53e7cc2ec2bcd26dd
--- /dev/null
+++ b/pool/shard009/Python/0085897_init__.py
@@ -0,0 +1,34 @@
+import logging
+import sys
+
+LOG = logging.getLogger(__name__)
+handler = logging.StreamHandler(sys.stdout)
+LOG.addHandler(handler)
+error_handler = logging.StreamHandler(sys.stderr)
+error_handler.setFormatter(logging.Formatter(format))
+error_handler.setLevel(logging.ERROR)
+LOG.addHandler(error_handler)
+
+# The order here is important...
+# We start with stateless objects that have few to no internal dependencies
+from .objects import * # NOQA
+
+# Global lists
+from .event import Events # NOQA
+event = Events()
+
+from .substitutions import Substitutions # NOQA
+substitutions = Substitutions()
+
+# Then we move on to the factory
+from .factory import Factory # NOQA
+
+# Most of the rest of the application depend on the factory being present
+from . import core # NOQA
+from . import scheduler # NOQA
+from . import brain # NOQA
+from .decorators import * # NOQA
+
+# CONSTANTS
+PRIORITY_ALWAYS = -1
+SELF_MENTION = 'SELF_MENTION'
diff --git a/pool/shard009/Python/0085898_test_lib_cli.py b/pool/shard009/Python/0085898_test_lib_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4fac99c06af8f438cbba2f20027cb9e007366df
--- /dev/null
+++ b/pool/shard009/Python/0085898_test_lib_cli.py
@@ -0,0 +1,119 @@
+import synapse.lib.cli as s_cli
+
+from synapse.tests.common import *
+
+class Hehe:
+
+ def cmd_hehe(self, cli, line):
+ '''
+ The hehe cmd.
+ '''
+ cli.vprint('hehe')
+
+class CliTest(SynTest):
+
+ def test_cli_quit(self):
+ outp = s_output.OutPutStr()
+ with s_cli.Cli(outp=outp) as cli:
+ cli.runCmdLine('quit')
+ self.true(cli.isfini)
+
+ def test_cli_help(self):
+ outp = s_output.OutPutStr()
+ with s_cli.Cli(outp=outp) as cli:
+ cli.runCmdLine('help')
+
+ self.true( str(outp).find('Quit the current command line interpreter.') != -1 )
+
+ def test_cli_cmdret(self):
+
+ class WootCmd(s_cli.Cmd):
+ _cmd_name = 'woot'
+ def runCmdOpts(self, opts):
+ return 20
+
+ with s_cli.Cli() as cli:
+ cli.addCmdClass(WootCmd)
+ self.eq( cli.runCmdLine('woot'), 20 )
+
+ def test_cli_cmd(self):
+ with s_cli.Cli() as cli:
+ quit = cli.getCmdByName('quit')
+ self.nn( quit.getCmdDoc() )
+ self.nn( quit.getCmdBrief() )
+
+ def test_cli_opts_flag(self):
+ with s_cli.Cli() as cli:
+
+ quit = cli.getCmdByName('quit')
+
+ quit._cmd_syntax = (
+ ('--bar',{}),
+ ('haha',{'type':'valu'}),
+ )
+
+ opts = quit.getCmdOpts('quit --bar hoho')
+
+ self.eq( opts.get('bar'), True )
+ self.eq( opts.get('haha'), 'hoho')
+
+ def test_cli_opts_flag(self):
+ with s_cli.Cli() as cli:
+
+ quit = cli.getCmdByName('quit')
+
+ quit._cmd_syntax = (
+ ('--bar',{}),
+ ('haha',{'type':'valu'}),
+ )
+
+ opts = quit.getCmdOpts('quit --bar hoho')
+
+ self.eq( opts.get('bar'), True )
+ self.eq( opts.get('haha'), 'hoho')
+
+ def test_cli_opts_list(self):
+
+ with s_cli.Cli() as cli:
+
+ quit = cli.getCmdByName('quit')
+
+ quit._cmd_syntax = (
+ ('--bar',{}),
+ ('haha',{'type':'list'}),
+ )
+
+ opts = quit.getCmdOpts('quit --bar hoho haha "hehe hehe"')
+
+ self.eq( opts.get('bar'), True )
+ self.eq( tuple(opts.get('haha')), ('hoho','haha','hehe hehe') )
+
+ def test_cli_opts_glob(self):
+
+ with s_cli.Cli() as cli:
+
+ quit = cli.getCmdByName('quit')
+
+ quit._cmd_syntax = (
+ ('--bar',{}),
+ ('haha',{'type':'glob'}),
+ )
+
+ opts = quit.getCmdOpts('quit --bar hoho lulz')
+
+ self.eq( opts.get('bar'), True )
+ self.eq( opts.get('haha'), 'hoho lulz')
+
+ def test_cli_opts_defval(self):
+
+ with s_cli.Cli() as cli:
+
+ quit = cli.getCmdByName('quit')
+
+ quit._cmd_syntax = (
+ ('--bar',{'type':'valu','defval':'lol'}),
+ ('haha',{'type':'glob'}),
+ )
+
+ opts = quit.getCmdOpts('quit hoho lulz')
+ self.eq( opts.get('bar'), 'lol' )
diff --git a/pool/shard009/Python/0085899_settings.py b/pool/shard009/Python/0085899_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b049e1794ab854fc88af510b9c3f1d82b6959d6e
--- /dev/null
+++ b/pool/shard009/Python/0085899_settings.py
@@ -0,0 +1,112 @@
+import sys, os
+
+# Quick hack to put frontendadmin from the parent directory into pythonpath
+# If this is not working correctly, uncomment these lines and put
+# frontendadmin manually into pythonpath.
+sys.path.append(
+ os.path.abspath(
+ os.path.normpath('%s/../' % os.path.dirname(__file__))
+ )
+)
+
+PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+ # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+DATABASE_NAME = 'myproject.db' # Or path to database file if using sqlite3.
+DATABASE_USER = '' # Not used with sqlite3.
+DATABASE_PASSWORD = '' # Not used with sqlite3.
+DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
+DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'America/Chicago'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media')
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = '/site_media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '^6qlxq*maky)*u!fl+!_97m^zcywod0c)tujsm5+fngj1+y55x'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+ 'django.template.loaders.filesystem.load_template_source',
+ 'django.template.loaders.app_directories.load_template_source',
+# 'django.template.loaders.eggs.load_template_source',
+)
+
+MIDDLEWARE_CLASSES = (
+ 'django.middleware.common.CommonMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
+)
+
+TEMPLATE_CONTEXT_PROCESSORS = (
+ 'django.core.context_processors.request',
+ 'django.core.context_processors.auth',
+ 'django.core.context_processors.debug',
+ 'django.core.context_processors.i18n',
+ 'django.core.context_processors.media',
+)
+
+ROOT_URLCONF = 'example_project.urls'
+
+TEMPLATE_DIRS = (
+ os.path.join(PROJECT_ROOT, 'templates'),
+)
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.admin',
+ 'django.contrib.comments',
+ 'django.contrib.flatpages',
+
+ # Put frontendadmin before your applications, so that they can overwrite
+ # the frontendadmin templates.
+ 'frontendadmin',
+ 'example_project.weblog',
+)
+
+# Define custom forms to handle any model
+FRONTEND_FORMS = {
+ # ``app_label.model_name`` : ``form_class``,
+ 'weblog.entry': 'weblog.forms.EntryForm',
+}
+
+# Define which fields to exclude on a particular model
+FRONTEND_EXCLUDES = {
+ # ``app_label.model_name`` : ``tuple``,
+ 'weblog.entry': ('public',),
+}
diff --git a/pool/shard009/Python/0085902_pubfilmto_scraper.py b/pool/shard009/Python/0085902_pubfilmto_scraper.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6a194dad1c5c37d9f70517d8055c2c5404d373d
--- /dev/null
+++ b/pool/shard009/Python/0085902_pubfilmto_scraper.py
@@ -0,0 +1,108 @@
+"""
+ SALTS XBMC Addon
+ Copyright (C) 2014 tknorris
+
+ 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 re
+import scraper
+import kodi
+import log_utils # @UnusedImport
+import dom_parser2
+from salts_lib import scraper_utils
+from salts_lib.constants import VIDEO_TYPES
+from salts_lib.constants import FORCE_NO_MATCH
+
+logger = log_utils.Logger.get_logger(__name__)
+BASE_URL = 'http://pubfilm.to'
+
+class Scraper(scraper.Scraper):
+ base_url = BASE_URL
+
+ def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
+ self.timeout = timeout
+ self.base_url = kodi.get_setting('%s-base_url' % (self.get_name()))
+
+ @classmethod
+ def provides(cls):
+ return frozenset([VIDEO_TYPES.MOVIE, VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE])
+
+ @classmethod
+ def get_name(cls):
+ return 'Pubfilm.to'
+
+ def get_sources(self, video):
+ hosters = []
+ source_url = self.get_url(video)
+ if not source_url or source_url == FORCE_NO_MATCH: return hosters
+ page_url = scraper_utils.urljoin(self.base_url, source_url)
+ html = self._http_get(page_url, cache_limit=.5)
+ iframe_url = dom_parser2.parse_dom(html, 'iframe', {'id': 'myiframe'}, req='src', exclude_comments=True)
+ if not iframe_url: return hosters
+ iframe_url = iframe_url[0].attrs['src']
+ html = self._http_get(iframe_url, headers={'Referer': page_url}, cache_limit=.5)
+
+ for source in dom_parser2.parse_dom(html, 'source', {'type': 'video/mp4'}, req=['src', 'data-res']):
+ stream_url = source.attrs['src']
+ host = scraper_utils.get_direct_hostname(self, stream_url)
+ if host == 'gvideo':
+ quality = scraper_utils.gv_get_quality(stream_url)
+ stream_url += scraper_utils.append_headers({'User-Agent': scraper_utils.get_ua()})
+ else:
+ quality = scraper_utils.height_get_quality(source.attrs['data-res'])
+ stream_url += scraper_utils.append_headers({'User-Agent': scraper_utils.get_ua(), 'Referer': page_url})
+
+ source = {'multi-part': False, 'url': stream_url, 'host': host, 'class': self, 'quality': quality, 'views': None, 'rating': None, 'direct': True}
+ hosters.append(source)
+
+ return hosters
+
+ def _get_episode_url(self, show_url, video):
+ episode_pattern = 'href="([^"]+season-0*%s-episode-0*%s-[^"]*)' % (video.season, video.episode)
+ page_url = show_url
+ pages = 0
+ while page_url and pages < MAX_PAGES:
+ page_url = scraper_utils.urljoin(self.base_url, page_url)
+ html = self._http_get(page_url, cache_limit=2)
+ ep_url = self._default_get_episode_url(html, video, episode_pattern)
+ if ep_url: return ep_url
+
+ fragment = dom_parser2.parse_dom(html, 'div', {'class': 'pagination'})
+ if not fragment: break
+ match = re.search('href="([^"]+)[^>]+>\s*>\s*<', fragment[0].content)
+ if not match: break
+ page_url = scraper_utils.cleanse_title(match.group(1))
+ pages += 1
+
+ def search(self, video_type, title, year, season=''): # @UnusedVariable
+ results = []
+ params = {'c': 'movie', 'm': 'filter', 'keyword': title}
+ html = self._http_get(self.base_url, params=params, cache_limit=8)
+ for attrs, item in dom_parser2.parse_dom(html, 'div', {'class': 'recent-item'}, req='title'):
+ match_url = dom_parser2.parse_dom(item, 'a', req='href')
+ if not match_url: continue
+
+ match_url = match_url[0].attrs['href']
+ is_series = re.search('/series/', match_url, re.I)
+ if (video_type == VIDEO_TYPES.MOVIE and is_series) or (video_type == VIDEO_TYPES.TVSHOW and not is_series):
+ continue
+
+ match_title_year = attrs['title']
+ match_title, match_year = scraper_utils.extra_year(match_title_year)
+
+ if not year or not match_year or year == match_year:
+ result = {'title': scraper_utils.cleanse_title(match_title), 'year': match_year, 'url': scraper_utils.pathify_url(match_url)}
+ results.append(result)
+
+ return results
diff --git a/pool/shard009/Python/0085905_test_pmfops.py b/pool/shard009/Python/0085905_test_pmfops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bf2c541cc00526875c05f1621847144ae6f49d9
--- /dev/null
+++ b/pool/shard009/Python/0085905_test_pmfops.py
@@ -0,0 +1,189 @@
+"""
+Tests for dit.math.pmfops
+"""
+
+import dit
+from dit.exceptions import ditException
+import numpy as np
+
+import pytest
+
+module = dit.math.pmfops
+
+
+def test_perturb_one():
+ # Smoke test
+ d = np.array([0.0, 0.5, 0.5])
+ d2 = module.perturb_support(d, 0.00001)
+ d3 = d2.round(2)
+ assert np.allclose(d, d3)
+
+
+def test_perturb_one_square():
+ # Smoke test
+ d = np.array([0.0, 0.5, 0.5])
+ d2 = module.perturb_support(d, 0.00001, shape='square')
+ d3 = d2.round(2)
+ assert np.allclose(d, d3)
+
+
+def test_perturb_one_bad():
+ # Smoke test
+ d = np.array([0.0, 0.5, 0.5])
+ with pytest.raises(ditException):
+ module.perturb_support(d, 0.00001, shape='bad')
+
+
+def test_perturb_many():
+ # Smoke test
+ d = np.array([[0.0, 0.5, 0.5], [0.5, 0.5, .0]])
+ d2 = module.perturb_support(d, 0.00001)
+ d3 = d2.round(2)
+ assert np.allclose(d, d3)
+
+
+def test_convex_combination():
+ d1 = np.array([0.0, 0.5, 0.5])
+ d2 = np.array([0.5, 0.5, 0.0])
+ d3_ = np.array([0.25, 0.5, 0.25])
+ d3 = module.convex_combination(np.array([d1, d2]))
+ assert np.allclose(d3, d3_)
+
+
+def test_convex_combination_weights():
+ d1 = np.array([0, 0.5, 0.5])
+ d2 = np.array([0.5, 0.5, 0])
+ weights = [1, 0]
+ d3 = module.convex_combination(np.array([d1, d2]), weights)
+ assert np.allclose(d3, d1)
+
+
+def test_downsample_onepmf():
+ # One pmf
+ d1 = np.array([0.0, 0.51, .49])
+ d2_ = np.array([0.0, 0.5, 0.5])
+ d2 = module.downsample(d1, 2)
+ assert np.allclose(d2, d2_)
+
+
+def test_downsample_twopmf():
+ # Two pmf
+ d1 = np.array([[0.0, 0.51, 0.49], [0.6, 0.3, 0.1]])
+ d2_ = np.array([[0.0, 0.5, 0.5], [0.5, 0.5, 0.0]])
+ d2 = module.downsample(d1, 2)
+ assert np.allclose(d2, d2_)
+
+
+def test_downsample_badmethod():
+ d1 = np.array([0, 0.51, 0.49])
+ with pytest.raises(NotImplementedError):
+ module.downsample(d1, 2**3, method='whatever')
+
+
+def test_projections1():
+ d = np.array([0.03231933, 0.89992681, 0.06775385])
+ d2_ = np.array([
+ [0.03231933, 0.89992681, 0.06775385],
+ [0.0, 0.92998325, 0.07001675],
+ [0.0, 0.875, 0.125]
+ ])
+ d2 = module.projections(d, 2**3)
+ assert np.allclose(d2, d2_)
+
+
+def test_projections2():
+ d = np.array([0.51, 0.48, 0.01])
+ d2_ = np.array([
+ [0.51, 0.48, 0.01],
+ [0.5, 0.48979592, 0.01020408],
+ [0.5, 0.5, 0.0]
+ ])
+ d2 = module.projections(d, 2**3)
+ assert np.allclose(d2, d2_, rtol=1e-7, atol=1e-8)
+
+
+def test_projections_max():
+ d = np.array([0.51, 0.48, 0.01])
+ d2_ = np.array([
+ [0.51, 0.48, 0.01],
+ [0.625, 0.36734694, 0.00765306],
+ [0.625, 0.25, 0.125]
+ ])
+ d2 = module.projections(d, 2**3, [np.argmax, np.argmax, np.argmax])
+ assert np.allclose(d2, d2_, rtol=1e-7, atol=1e-8)
+
+
+def test_projections_0element():
+ # During projections, if an element is equal to 0, then searchsorted
+ # returns 0, and `lower - 1` gives it index -1...which incorrectly
+ # compares locs[-1] instead of locs[0]. So without the line:
+ # lower[lower == -1] = 0
+ # we would have an error.
+ d = np.array([0.23714859, 0.35086749, 0.01870522,
+ 0.32914084, 0.05896644, 0.00517141])
+ ops = [np.argmin, np.argmin, np.argmin, np.argmin, np.argmax]
+ x = dit.math.pmfops.projections(d, 2**3, ops)
+ # We would have had:
+ x_bad = np.array([ # noqa: F841
+ [0.23714859, 0.35086749, 0.01870522, 0.32914084, 0.05896644, 0.00517141],
+ [0.25, 0.34495659, 0.0183901, 0.32359596, 0.05797306, 0.00508429],
+ [0.25, 0.375, 0.01702605, 0.29959378, 0.05367301, 0.00470717],
+ [0.25, 0.375, 0.0, 0.31384313, 0.05622582, 0.00493105],
+ [0.25, 0.375, 0.0, 0.375, 0.0, 0.0],
+ [0.25, 0.375, 0.0, 0.375, 1.0, np.nan]
+ ])
+ # Since the error has been fixed. We get:
+ x_good = np.array([
+ [0.23714859, 0.35086749, 0.01870522, 0.32914084, 0.05896644, 0.00517141],
+ [0.25, 0.34495659, 0.0183901, 0.32359596, 0.05797306, 0.00508429],
+ [0.25, 0.375, 0.01702605, 0.29959378, 0.05367301, 0.00470717],
+ [0.25, 0.375, 0.0, 0.31384313, 0.05622582, 0.00493105],
+ [0.25, 0.375, 0.0, 0.375, 0.0, 0.0],
+ [0.25, 0.375, 0.0, 0.375, 0.0, 0.0],
+ ])
+ assert np.allclose(x, x_good, rtol=1e-7, atol=1e-8)
+
+
+def test_clamps():
+ d = np.array([0.51, 0.48, 0.01])
+ locs = np.linspace(0, 1, 2**3 + 1)
+ out_ = np.array([[4, 3, 0], [5, 4, 1]])
+ out = module.clamped_indexes(d, locs)
+ assert np.allclose(out, out_)
+
+
+def test_replace_nonzero_rand():
+ d = np.array([0.25, 0.75, 0.0])
+ x = module.replace_zeros(d, 0.0001)
+ assert np.allclose(d, x.round(2))
+
+
+def test_replace_nonzero_norand():
+ d = np.array([0.25, 0.75, 0.0])
+ x = module.replace_zeros(d, 0.0001, rand=False)
+ assert x[2] == 0.0001
+ assert np.allclose(d, x.round(2))
+
+
+def test_jittered_zeros():
+ d = np.array([0.25, 0.75, 0.0])
+ prng = np.random.RandomState(1)
+ x = module.jittered(d, jitter=1e-5, zeros=True, prng=prng)
+ x_ = np.array([2.49998269e-01, 7.49997561e-01, 4.17024317e-06])
+ assert np.allclose(x, x_)
+
+
+def test_jittered():
+ d = np.array([0.25, 0.75, 0.0])
+ prng = np.random.RandomState(1)
+ x = module.jittered(d, jitter=1e-5, zeros=False, prng=prng)
+ x_ = np.array([0.24999923, 0.75000077, 0.0])
+ assert np.allclose(x, x_)
+
+
+def test_jittered_noprng():
+ d = np.array([0.25, 0.75, 0.0])
+ dit.math.prng.seed(1)
+ x = module.jittered(d, jitter=1e-5, zeros=False)
+ x_ = np.array([0.24999923, 0.75000077, 0.0])
+ assert np.allclose(x, x_)
diff --git a/pool/shard009/Python/0085913_NormaliseSpectraTest.py b/pool/shard009/Python/0085913_NormaliseSpectraTest.py
new file mode 100644
index 0000000000000000000000000000000000000000..dab8c500ab399fbc4864a274a737e5891ec0d869
--- /dev/null
+++ b/pool/shard009/Python/0085913_NormaliseSpectraTest.py
@@ -0,0 +1,80 @@
+# Mantid Repository : https://github.com/mantidproject/mantid
+#
+# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
+# NScD Oak Ridge National Laboratory, European Spallation Source
+# & Institut Laue - Langevin
+# SPDX - License - Identifier: GPL - 3.0 +
+from __future__ import (absolute_import, division, print_function)
+
+import unittest
+import platform
+from mantid.simpleapi import *
+from mantid.api import MatrixWorkspace, WorkspaceGroup
+
+class NormaliseSpectraTest(unittest.TestCase):
+
+ _positive ='1,2,3,4,5'
+ _negative ='-5,-4,-3,-2,-1'
+ _zeros ='0,0,0,0,0'
+ _mixed ='-2,-1,0,1,2'
+
+
+#----------------------------------Algorithm tests----------------------------------------
+
+ def test_one_hist_positive(self):
+ in_ws = self._create_workspace(1, 'test', self._positive)
+ out_ws = NormaliseSpectra(InputWorkspace=in_ws)
+ self._check_workspace_is_within_boundaries(out_ws, 1, 0)
+
+ def test_one_hist_negative(self):
+ in_ws = self._create_workspace(1, 'test', self._negative)
+ self.assertRaises(RuntimeError, NormaliseSpectra,
+ InputWorkspace=in_ws, OutputWorkspace='out_ws')
+
+ def test_one_hist_zeros(self):
+ in_ws = self._create_workspace(1, 'test', self._zeros)
+ self.assertRaises(RuntimeError, NormaliseSpectra,
+ InputWorkspace=in_ws, OutputWorkspace='out_ws')
+
+ def test_one_hist_mixed(self):
+ in_ws = self._create_workspace(1, 'test', self._mixed)
+ out_ws = NormaliseSpectra(InputWorkspace=in_ws)
+ self._check_workspace_is_within_boundaries(out_ws, 1, -1)
+
+ def test_with_MatrixWorkspace_multi_hist_(self):
+ in_ws = self._create_workspace(3, 'test', self._positive)
+ out_ws = NormaliseSpectra(InputWorkspace=in_ws)
+ self._check_workspace_is_within_boundaries(out_ws, 1, 0)
+
+#--------------------------------Validate results-----------------------------------------
+
+ def _check_workspace_is_within_boundaries(self, matrixWs, max, min):
+ for i in range(matrixWs.getNumberHistograms()):
+ self._check_spectrum_less_than(matrixWs.readY(i), max)
+ self._check_spectrum_more_than(matrixWs.readY(i), min)
+
+ def _check_spectrum_less_than(self, y_data, upper_boundary):
+ for i in range(len(y_data)):
+ self.assertTrue(y_data[i] <= upper_boundary)
+
+ def _check_spectrum_more_than(self, y_data, lower_boundary):
+ for i in range(len(y_data)):
+ self.assertTrue(y_data[i] >= lower_boundary)
+
+#--------------------------------Helper Functions-----------------------------------------
+ def _create_workspace(self, nhists, out_name, data_string):
+ """
+ Creates a basic Matrixworkspace
+ """
+ data = ""
+ for i in range(nhists):
+ data += data_string
+ if i != (nhists - 1):
+ data += ','
+ CreateWorkspace(OutputWorkspace=out_name, DataX=data,
+ DataY=data, DataE=data, Nspec=nhists)
+ return mtd[out_name]
+
+
+if __name__=="__main__":
+ unittest.main()
diff --git a/pool/shard009/Python/0085914_test_lib_http.py b/pool/shard009/Python/0085914_test_lib_http.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd645f1fffd4d59c494ec77457889329de83db91
--- /dev/null
+++ b/pool/shard009/Python/0085914_test_lib_http.py
@@ -0,0 +1,73 @@
+"""
+ Package to test the openlp.plugin.bible.lib.https package.
+"""
+
+from unittest import TestCase
+from mock import MagicMock
+
+from openlp.core.lib import Registry
+from openlp.plugins.bibles.lib.http import BGExtract, CWExtract
+
+
+class TestBibleHTTP(TestCase):
+
+ def setUp(self):
+ """
+ Set up the Registry
+ """
+ Registry.create()
+ Registry().register('service_list', MagicMock())
+ Registry().register('application', MagicMock())
+
+ def bible_gateway_extract_books_test(self):
+ """
+ Test the Bible Gateway retrieval of book list for NIV bible
+ """
+ # GIVEN: A new Bible Gateway extraction class
+ handler = BGExtract()
+
+ # WHEN: The Books list is called
+ books = handler.get_books_from_http('NIV')
+
+ # THEN: We should get back a valid service item
+ assert len(books) == 66, 'The bible should not have had any books added or removed'
+
+ def bible_gateway_extract_verse_test(self):
+ """
+ Test the Bible Gateway retrieval of verse list for NIV bible John 3
+ """
+ # GIVEN: A new Bible Gateway extraction class
+ handler = BGExtract()
+
+ # WHEN: The Books list is called
+ results = handler.get_bible_chapter('NIV', 'John', 3)
+
+ # THEN: We should get back a valid service item
+ assert len(results.verse_list) == 36, 'The book of John should not have had any verses added or removed'
+
+ def crosswalk_extract_books_test(self):
+ """
+ Test Crosswalk retrieval of book list for NIV bible
+ """
+ # GIVEN: A new Bible Gateway extraction class
+ handler = CWExtract()
+
+ # WHEN: The Books list is called
+ books = handler.get_books_from_http('niv')
+
+ # THEN: We should get back a valid service item
+ assert len(books) == 66, 'The bible should not have had any books added or removed'
+
+ def crosswalk_extract_verse_test(self):
+ """
+ Test Crosswalk retrieval of verse list for NIV bible John 3
+ """
+ # GIVEN: A new Bible Gateway extraction class
+ handler = CWExtract()
+
+ # WHEN: The Books list is called
+ results = handler.get_bible_chapter('niv', 'john', 3)
+
+ # THEN: We should get back a valid service item
+ assert len(results.verse_list) == 36, 'The book of John should not have had any verses added or removed'
+
diff --git a/pool/shard009/Python/0085916_parse_sources.py b/pool/shard009/Python/0085916_parse_sources.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bf3a48d193e4d63f5a9e69ab855e317cd532ef5
--- /dev/null
+++ b/pool/shard009/Python/0085916_parse_sources.py
@@ -0,0 +1,44 @@
+#!/usr/bin/python3
+# This script parses contents of given 'Source' files, and creates rsync
+# command line to synchronize mirror
+
+import re
+import sys
+
+# Regex to parse
+regex = re.compile("^(?P[a-zA-Z0-9_-]+):\s?(?P.*)$")
+files_regex = re.compile("(?P[a-f0-9]{32}) [0-9]+ (?P.*)")
+
+for pkgfile in sys.argv[1:]:
+ if pkgfile.endswith(".gz"):
+ import gzip
+
+ file = gzip.open(pkgfile, mode='rt', encoding="utf-8")
+ elif pkgfile.endswith(".bz2"):
+ import bz2
+
+ file = bz2.open(pkgfile, mode='rt', encoding="utf-8")
+ else:
+ file = open(pkgfile, mode='rt', encoding="utf-8")
+
+ pkg = {}
+ cur_param = ""
+
+ for line in file:
+ if line == "\n":
+ basedir = pkg['directory']
+ files = files_regex.findall(pkg['files'])
+ for md5, file in files:
+ print(basedir + "/" + file)
+ pkg = {}
+ continue
+
+ m = regex.match(line)
+ if m:
+ cur_param = m.group("param").lower()
+ pkg[cur_param] = m.group("value")
+ elif line.startswith(" "):
+ # We got a multiliner continuation
+ pkg[cur_param] += line.lstrip()
+ else:
+ sys.exit(999)
diff --git a/pool/shard009/Python/0085918_test_webhook.py b/pool/shard009/Python/0085918_test_webhook.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf2f609e786cc1436d7902aae5c0e8de8233630
--- /dev/null
+++ b/pool/shard009/Python/0085918_test_webhook.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2017, Frappe Technologies and Contributors
+# See license.txt
+from __future__ import unicode_literals
+
+import unittest
+
+import frappe
+from frappe.integrations.doctype.webhook.webhook import get_webhook_headers, get_webhook_data
+
+
+class TestWebhook(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ # delete any existing webhooks
+ frappe.db.sql("DELETE FROM tabWebhook")
+ # create test webhooks
+ cls.create_sample_webhooks()
+
+ @classmethod
+ def create_sample_webhooks(cls):
+ samples_webhooks_data = [
+ {
+ "webhook_doctype": "User",
+ "webhook_docevent": "after_insert",
+ "request_url": "https://httpbin.org/post",
+ "condition": "doc.email",
+ "enabled": True
+ },
+ {
+ "webhook_doctype": "User",
+ "webhook_docevent": "after_insert",
+ "request_url": "https://httpbin.org/post",
+ "condition": "doc.first_name",
+ "enabled": False
+ }
+ ]
+
+ cls.sample_webhooks = []
+ for wh_fields in samples_webhooks_data:
+ wh = frappe.new_doc("Webhook")
+ wh.update(wh_fields)
+ wh.insert()
+ cls.sample_webhooks.append(wh)
+
+ @classmethod
+ def tearDownClass(cls):
+ # delete any existing webhooks
+ frappe.db.sql("DELETE FROM tabWebhook")
+
+ def setUp(self):
+ # retrieve or create a User webhook for `after_insert`
+ webhook_fields = {
+ "webhook_doctype": "User",
+ "webhook_docevent": "after_insert",
+ "request_url": "https://httpbin.org/post"
+ }
+
+ if frappe.db.exists("Webhook", webhook_fields):
+ self.webhook = frappe.get_doc("Webhook", webhook_fields)
+ else:
+ self.webhook = frappe.new_doc("Webhook")
+ self.webhook.update(webhook_fields)
+
+ # create a User document
+ self.user = frappe.new_doc("User")
+ self.user.first_name = frappe.mock("name")
+ self.user.email = frappe.mock("email")
+ self.user.save()
+
+ # Create another test user specific to this test
+ self.test_user = frappe.new_doc("User")
+ self.test_user.email = "user1@integration.webhooks.test.com"
+ self.test_user.first_name = "user1"
+
+ def tearDown(self) -> None:
+ self.user.delete()
+ self.test_user.delete()
+ super().tearDown()
+
+ def test_webhook_trigger_with_enabled_webhooks(self):
+ """Test webhook trigger for enabled webhooks"""
+
+ frappe.cache().delete_value('webhooks')
+ frappe.flags.webhooks = None
+
+ # Insert the user to db
+ self.test_user.insert()
+
+ self.assertTrue("User" in frappe.flags.webhooks)
+ # only 1 hook (enabled) must be queued
+ self.assertEqual(
+ len(frappe.flags.webhooks.get("User")),
+ 1
+ )
+ self.assertTrue(self.test_user.email in frappe.flags.webhooks_executed)
+ self.assertEqual(
+ frappe.flags.webhooks_executed.get(self.test_user.email)[0],
+ self.sample_webhooks[0].name
+ )
+
+ def test_validate_doc_events(self):
+ "Test creating a submit-related webhook for a non-submittable DocType"
+
+ self.webhook.webhook_docevent = "on_submit"
+ self.assertRaises(frappe.ValidationError, self.webhook.save)
+
+ def test_validate_request_url(self):
+ "Test validation for the webhook request URL"
+
+ self.webhook.request_url = "httpbin.org?post"
+ self.assertRaises(frappe.ValidationError, self.webhook.save)
+
+ def test_validate_headers(self):
+ "Test validation for request headers"
+
+ # test incomplete headers
+ self.webhook.set("webhook_headers", [{
+ "key": "Content-Type"
+ }])
+ self.webhook.save()
+ headers = get_webhook_headers(doc=None, webhook=self.webhook)
+ self.assertEqual(headers, {})
+
+ # test complete headers
+ self.webhook.set("webhook_headers", [{
+ "key": "Content-Type",
+ "value": "application/json"
+ }])
+ self.webhook.save()
+ headers = get_webhook_headers(doc=None, webhook=self.webhook)
+ self.assertEqual(headers, {"Content-Type": "application/json"})
+
+ def test_validate_request_body_form(self):
+ "Test validation of Form URL-Encoded request body"
+
+ self.webhook.request_structure = "Form URL-Encoded"
+ self.webhook.set("webhook_data", [{
+ "fieldname": "name",
+ "key": "name"
+ }])
+ self.webhook.webhook_json = """{
+ "name": "{{ doc.name }}"
+ }"""
+ self.webhook.save()
+ self.assertEqual(self.webhook.webhook_json, None)
+
+ data = get_webhook_data(doc=self.user, webhook=self.webhook)
+ self.assertEqual(data, {"name": self.user.name})
+
+ def test_validate_request_body_json(self):
+ "Test validation of JSON request body"
+
+ self.webhook.request_structure = "JSON"
+ self.webhook.set("webhook_data", [{
+ "fieldname": "name",
+ "key": "name"
+ }])
+ self.webhook.webhook_json = """{
+ "name": "{{ doc.name }}"
+ }"""
+ self.webhook.save()
+ self.assertEqual(self.webhook.webhook_data, [])
+
+ data = get_webhook_data(doc=self.user, webhook=self.webhook)
+ self.assertEqual(data, {"name": self.user.name})
diff --git a/pool/shard009/Python/0085919_secret.py b/pool/shard009/Python/0085919_secret.py
new file mode 100644
index 0000000000000000000000000000000000000000..e287075c346f5994304a70d092d19beb45fa292c
--- /dev/null
+++ b/pool/shard009/Python/0085919_secret.py
@@ -0,0 +1,183 @@
+#
+# Copyright 2015 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# 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
+#
+# Refer to the README and COPYING files for full details of the license
+#
+
+from xml.etree import ElementTree as etree
+import base64
+import libvirt
+import logging
+import uuid
+
+from vdsm import libvirtconnection
+from vdsm import response
+
+
+def register(secrets, clear=False):
+ try:
+ secrets = [Secret(params) for params in secrets]
+ except ValueError as e:
+ logging.warning("Attempt to register invalid secret: %s", e)
+ return response.error("secretBadRequestErr")
+
+ con = libvirtconnection.get()
+ try:
+ for secret in secrets:
+ logging.info("Registering secret %s", secret)
+ secret.register(con)
+ if clear:
+ uuids = frozenset(sec.uuid for sec in secrets)
+ for virsecret in con.listAllSecrets():
+ if (virsecret.UUIDString() not in uuids and
+ _is_ovirt_secret(virsecret)):
+ virsecret.undefine()
+ except libvirt.libvirtError as e:
+ logging.error("Could not register secret %s: %s", secret, e)
+ return response.error("secretRegisterErr")
+
+ return response.success()
+
+
+def unregister(uuids):
+ try:
+ uuids = [str(uuid.UUID(s)) for s in uuids]
+ except ValueError as e:
+ logging.warning("Attempt to unregister invalid uuid %s: %s" %
+ (uuids, e))
+ return response.error("secretBadRequestErr")
+
+ con = libvirtconnection.get()
+ try:
+ for sec_uuid in uuids:
+ logging.info("Unregistering secret %r", sec_uuid)
+ try:
+ virsecret = con.secretLookupByUUIDString(sec_uuid)
+ except libvirt.libvirtError as e:
+ if e.get_error_code() != libvirt.VIR_ERR_NO_SECRET:
+ raise
+ logging.debug("No such secret %r", sec_uuid)
+ else:
+ virsecret.undefine()
+ except libvirt.libvirtError as e:
+ logging.error("Could not unregister secrets: %s", e)
+ return response.error("secretUnregisterErr")
+
+ return response.success()
+
+
+def clear():
+ """
+ Clear all regsistered ovirt secrets.
+
+ Should be called during startup and shutdown to ensure that we don't leave
+ around stale or unneeded secrets.
+ """
+ logging.info("Unregistering all secrets")
+ con = libvirtconnection.get()
+ for virsecret in con.listAllSecrets():
+ try:
+ if _is_ovirt_secret(virsecret):
+ virsecret.undefine()
+ except libvirt.libvirtError as e:
+ logging.error("Could not unregister %s: %s", virsecret, e)
+
+
+def _is_ovirt_secret(virsecret):
+ return virsecret.usageID().startswith("ovirt/")
+
+
+class Secret(object):
+ """
+ Validate libvirt secret parameters and create secret xml string.
+
+ Raises ValueError if params dictionary does not contain the required valid
+ secret parameters.
+ """
+
+ _USAGE_TYPES = {"ceph": "name", "volume": "volume", "iscsi": "target"}
+
+ def __init__(self, params):
+ self.uuid = str(uuid.UUID(_get_required(params, "uuid")))
+ self.usage_type = _get_enum(params, "usageType", self._USAGE_TYPES)
+ self.usage_id = _get_required(params, "usageID")
+ self.password = _decode_password(_get_required(params, "password"))
+ self.description = params.get("description")
+
+ def register(self, con):
+ # This is racy, but we don't have a better way. This is unlikely to
+ # fail, as we own libvirt and its secrets, and we do not modify the
+ # same secrets concurrently.
+ try:
+ virsecret = con.secretLookupByUUIDString(self.uuid)
+ except libvirt.libvirtError as e:
+ if e.get_error_code() != libvirt.VIR_ERR_NO_SECRET:
+ raise
+ else:
+ if virsecret.usageID() != self.usage_id:
+ virsecret.undefine()
+
+ virsecret = con.secretDefineXML(self.toxml())
+ virsecret.setValue(self.password.value)
+
+ def toxml(self):
+ secret = etree.Element("secret", ephemeral="yes", private="yes")
+ if self.description:
+ description = etree.Element("description")
+ description.text = self.description
+ secret.append(description)
+ uuid = etree.Element("uuid")
+ uuid.text = self.uuid
+ secret.append(uuid)
+ usage = etree.Element("usage", type=self.usage_type)
+ usage_type = etree.Element(self._USAGE_TYPES[self.usage_type])
+ usage_type.text = self.usage_id
+ usage.append(usage_type)
+ secret.append(usage)
+ return etree.tostring(secret)
+
+ def __str__(self):
+ return ("Secret(uuid={self.uuid}, "
+ "usage_type={self.usage_type}, "
+ "usage_id={self.usage_id}, "
+ "description={self.description})").format(self=self)
+
+
+# TODO: Move following helpers to reusable validation module
+
+
+def _decode_password(password):
+ try:
+ password.value = base64.b64decode(password.value)
+ except TypeError as e:
+ # Note: encoded value is intentionally not displayed
+ raise ValueError("Unable to decode base64 password: %s" % e)
+ return password
+
+
+def _get_enum(params, name, values):
+ value = _get_required(params, name)
+ if value not in values:
+ raise ValueError("Invalid value %r for %r, expecting one of %s" %
+ (value, name, values))
+ return value
+
+
+def _get_required(params, name):
+ if name not in params:
+ raise ValueError("Missing required property %r" % name)
+ return params[name]
diff --git a/pool/shard009/Python/0085922_hr_attendance_byweek.py b/pool/shard009/Python/0085922_hr_attendance_byweek.py
new file mode 100644
index 0000000000000000000000000000000000000000..139ff94cd5aa42abd33bd42308e5adf275b2253b
--- /dev/null
+++ b/pool/shard009/Python/0085922_hr_attendance_byweek.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (C) 2004-2010 Tiny SPRL ().
+#
+# 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 .
+#
+##############################################################################
+import time
+
+from osv import osv, fields
+
+class hr_attendance_byweek(osv.osv_memory):
+ _name = 'hr.attendance.week'
+ _description = 'Print Week Attendance Report'
+ _columns = {
+ 'init_date': fields.date('Starting Date', required=True),
+ 'end_date': fields.date('Ending Date', required=True)
+ }
+ _defaults = {
+ 'init_date': lambda *a: time.strftime('%Y-%m-%d'),
+ 'end_date': lambda *a: time.strftime('%Y-%m-%d'),
+ }
+
+ def print_report(self, cr, uid, ids, context=None):
+ datas = {
+ 'ids': [],
+ 'model': 'hr.employee',
+ 'form': self.read(cr, uid, ids)[0]
+ }
+ return {
+ 'type': 'ir.actions.report.xml',
+ 'report_name': 'hr.attendance.allweeks',
+ 'datas': datas,
+ }
+
+hr_attendance_byweek()
+
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
\ No newline at end of file
diff --git a/pool/shard009/Python/0085926_hooks.py b/pool/shard009/Python/0085926_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f4d9db7ac8f3b299d0030dfd67c4060e230187
--- /dev/null
+++ b/pool/shard009/Python/0085926_hooks.py
@@ -0,0 +1,113 @@
+# -*- coding: iso-8859-1 -*-
+"""Some hooks that might be useful."""
+
+import os
+import subprocess
+try:
+ from StringIO import StringIO
+except ImportError:
+ # Python 3
+ from io import StringIO
+import logging
+
+from woklib.util import slugify
+
+try:
+ from lxml import etree
+except ImportError:
+ etree = None
+
+
+class HeadingAnchors(object):
+ """
+ Put some paragraph heading anchors.
+
+ Serves as a 'page.template.post' wok hook.
+ """
+
+ def __init__(self, max_heading=3):
+ """Initialize heading anchor hook."""
+ if not etree:
+ logging.warning('To use the HeadingAnchors hook, you must install '
+ 'the library lxml.')
+ return
+ self.max_heading = max_heading
+ logging.info('Loaded hook HeadingAnchors')
+
+ def __call__(self, config, page):
+ """Add heading anchor."""
+ if not etree:
+ return
+ logging.debug('Called hook HeadingAnchors on {0}'.format(page))
+ parser = etree.HTMLParser()
+ sio_source = StringIO(page.rendered)
+ tree = etree.parse(sio_source, parser)
+
+ for lvl in range(1, self.max_heading+1):
+ headings = tree.iterfind('//h{0}'.format(lvl))
+ for heading in headings:
+ if not heading.text:
+ continue
+ logging.debug('[HeadingAnchors] {0} {1}'
+ .format(heading, heading.text))
+
+ name = 'heading-{0}'.format(slugify(heading.text))
+ anchor = etree.Element('a')
+ anchor.set('class', 'heading_anchor')
+ anchor.set('href', '#' + name)
+ anchor.set('title', 'Permalink to this section.')
+ anchor.text = u'¶'
+ heading.append(anchor)
+
+ heading.set('id', name)
+
+ sio_destination = StringIO()
+
+ # Use the extension of the template to determine the type of document
+ if page.template.filename.endswith(".html") or page.filename.endswith(".htm"):
+ logging.debug('[HeadingAnchors] outputting {0} as HTML'.format(page))
+ tree.write(sio_destination, method='html')
+ else:
+ logging.debug('[HeadingAnchors] outputting {0} as XML'.format(page))
+ tree.write(sio_destination)
+ page.rendered = sio_destination.getvalue()
+
+
+def compile_sass(config, output_dir):
+ '''
+ Compile Sass files -> CSS in the output directory.
+
+ Any .scss or .sass files found in the output directory will be compiled
+ to CSS using Sass. The compiled version of the file will be created in the
+ same directory as the Sass file with the same name and an extension of
+ .css. For example, foo.scss -> foo.css.
+
+ Serves as a 'site.output.post' wok hook, e.g., your __hooks__.py file might
+ look like this:
+
+ from woklib.contrib.hooks import compile_sass
+
+ hooks = {
+ 'site.output.post':[compile_sass]
+ }
+
+ Dependencies:
+
+ - Ruby
+ - Sass (http://sass-lang.com)
+ '''
+ logging.info('Running hook compile_sass on {0}.'.format(output_dir))
+ for root, dirs, files in os.walk(output_dir):
+ for f in files:
+ fname, fext = os.path.splitext(f)
+ if fext == ".scss" or fext == ".sass":
+ abspath = os.path.abspath(root)
+ sass_src = "%s/%s"%(abspath, f)
+ sass_dest = "%s/%s.css"%(abspath, fname)
+ sass_arg = "%s:%s"%(sass_src, sass_dest)
+ logging.debug('[hook/sass] sass {0}'.format(sass_arg))
+ try:
+ subprocess.call(['sass', sass_arg])
+ except OSError:
+ logging.warning('[hook/compile_sass] Could not run SASS ' +
+ 'hook. (Is SASS installed?)')
diff --git a/pool/shard009/Python/0085928_middleware.py b/pool/shard009/Python/0085928_middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cafe3cda254263e577663d9f5bdbe360914e08b
--- /dev/null
+++ b/pool/shard009/Python/0085928_middleware.py
@@ -0,0 +1,72 @@
+#
+# Copyright 2013 eNovance
+#
+# 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 oslo_config import cfg
+import oslo_messaging
+
+from ceilometer.agent import plugin_base
+from ceilometer import sample
+
+cfg.CONF.import_opt('nova_control_exchange',
+ 'ceilometer.compute.notifications')
+cfg.CONF.import_opt('glance_control_exchange',
+ 'ceilometer.image.notifications')
+cfg.CONF.import_opt('neutron_control_exchange',
+ 'ceilometer.network.notifications')
+cfg.CONF.import_opt('cinder_control_exchange',
+ 'ceilometer.volume.notifications')
+
+OPTS = [
+ cfg.MultiStrOpt('http_control_exchanges',
+ default=[cfg.CONF.nova_control_exchange,
+ cfg.CONF.glance_control_exchange,
+ cfg.CONF.neutron_control_exchange,
+ cfg.CONF.cinder_control_exchange],
+ help="Exchanges name to listen for notifications."),
+]
+
+cfg.CONF.register_opts(OPTS)
+
+
+class HTTPRequest(plugin_base.NotificationBase,
+ plugin_base.NonMetricNotificationBase):
+ event_types = ['http.request']
+
+ @staticmethod
+ def get_targets(conf):
+ """Return a sequence of oslo_messaging.Target
+
+ This sequence is defining the exchange and topics to be connected for
+ this plugin.
+ """
+ return [oslo_messaging.Target(topic=topic, exchange=exchange)
+ for topic in conf.notification_topics
+ for exchange in conf.http_control_exchanges]
+
+ def process_notification(self, message):
+ yield sample.Sample.from_notification(
+ name=message['event_type'],
+ type=sample.TYPE_DELTA,
+ volume=1,
+ unit=message['event_type'].split('.')[1],
+ user_id=message['payload']['request'].get('HTTP_X_USER_ID'),
+ project_id=message['payload']['request'].get('HTTP_X_PROJECT_ID'),
+ resource_id=message['payload']['request'].get(
+ 'HTTP_X_SERVICE_NAME'),
+ message=message)
+
+
+class HTTPResponse(HTTPRequest):
+ event_types = ['http.response']
diff --git a/pool/shard009/Python/0085931_run_v5.0_predict.py b/pool/shard009/Python/0085931_run_v5.0_predict.py
new file mode 100644
index 0000000000000000000000000000000000000000..124650f01d7afc135f51b1b234c1c9bdf1b7a28d
--- /dev/null
+++ b/pool/shard009/Python/0085931_run_v5.0_predict.py
@@ -0,0 +1,96 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Mon Dec 28 02:31:03 2015
+
+@author: winpython
+"""
+
+import os
+import sys, getopt
+import time
+import numpy as np
+from cnn_training_computation import fit, predict
+import pickle, cPickle
+
+from matplotlib.pyplot import imshow
+import matplotlib.pyplot as plt
+from PIL import Image
+
+
+def run():
+ print '... loading data'
+
+ test_set = np.zeros((200,147456),dtype=np.float32)
+ pil_im = Image.open( "P_20160109_190757.jpg" ).convert('L')
+ pil_im = pil_im.resize((512, 288), Image.BILINEAR )
+ pil_im = np.array(pil_im)
+ fig = plt.figure()
+ plotwindow = fig.add_subplot()
+ plt.imshow(pil_im, cmap='gray')
+ plt.show()
+ note = 0
+ for j in range(288):
+ for k in range(512):
+ test_set[0][note]= ((255 - pil_im[j][k])/225.)
+ note += 1
+ """
+ # read the data, labels
+ data = np.genfromtxt("data/mnist_train.data")
+ print ". .",
+ test_data = np.genfromtxt("data/mnist_test.data")
+ print ". .",
+ valid_data = np.genfromtxt("data/mnist_valid.data")
+ labels = np.genfromtxt("data/mnist_train.solution")
+ """
+ print ". . finished reading"
+ """
+ # DO argmax
+ labels = np.argmax(labels, axis=1)
+ print labels
+
+
+ # normalization
+ amean = np.mean(data)
+ data = data - amean
+ astd = np.std(data)
+ data = data / astd
+ # normalise using coefficients from training data
+ test_data = (test_data - amean) / astd
+ valid_data = (valid_data - amean) / astd
+ """
+
+ #fit(data, labels)
+ print "開始預測..."
+ rv = predict(test_set)
+
+
+
+ # UNDO argmax and save results x 2
+ r = rv
+ N = len(r)
+ res = np.zeros((N, 20))
+ for i in range(N):
+ res[i][r[i]] = 1
+
+ print "=================================================================="
+ print " "
+ print " "
+ print "predict Tag : [ 0 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 19 ]"
+ print " "
+ print " ---------------------------------------------------- "
+ print " "
+ print "predict Value:",
+ print res[0]
+ print res[1]
+ print " "
+ print " "
+ print "=================================================================="
+
+ #np.savetxt("test.predict", res, fmt='%i')
+
+ print "finished predicting."
+
+
+
+if __name__ == '__main__':
+ run()
\ No newline at end of file
diff --git a/pool/shard009/Python/0085936_auto.py b/pool/shard009/Python/0085936_auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cb7ecfc07ab6562035410f1697a1720fb5fb504
--- /dev/null
+++ b/pool/shard009/Python/0085936_auto.py
@@ -0,0 +1,80 @@
+# Copyright 2016 Timothy M. Shead
+#
+# This file is part of Pipecat.
+#
+# Pipecat 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.
+#
+# Pipecat 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 Pipecat. If not, see .
+
+"""Data sources that retrieve on-board diagnostics from an automobile using OBD-II."""
+
+from __future__ import absolute_import, division, print_function
+
+import sys
+import time
+
+import obd as obdii
+
+from pipecat import quantity, units
+from pipecat.record import add_field
+
+
+def obd(connection, commands=None, rate=quantity(5, units.second)):
+ """Retrieve OBD-II data from an automobile.
+
+ This component requires the `Python-OBD` module (http://python-obd.readthedocs.io).
+
+ Parameters
+ ----------
+ connection: :class:`obd.OBD` instance, required.
+ rate: time quantity, required
+ Rate at which data will be retrieved.
+
+ Yields
+ ------
+ record: dict
+ Records will contain OBD-II data retrieved from an automobile computer.
+ """
+
+ # Caller must supply an obd.OBD instance that's already connected.
+ if not (isinstance(connection, obdii.OBD) and connection.is_connected()):
+ raise ValueError("A valid obd.OBD connection is required.")
+
+ # Get the set of available commands.
+ if commands is None:
+ commands = []
+ for command in connection.supported_commands:
+ try:
+ if command.mode not in [1]:
+ continue
+ if command.pid in [0x00, 0x01, 0x02, 0x20, 0x40, 0x41]:
+ continue
+ commands.append(command)
+ except: # pylint: disable=bare-except
+ pass
+
+ rate = rate.to(units.seconds).magnitude
+
+ while True:
+ record = dict()
+ for command in commands:
+ sys.stdout.flush()
+ try:
+ response = connection.query(command)
+ name = command.name.lower().replace("_", "-")
+ add_field(record, name, response.value)
+ except: # pylint: disable=bare-except
+ pass
+
+ yield record
+
+ time.sleep(rate)
diff --git a/pool/shard009/Python/0085939_list.py b/pool/shard009/Python/0085939_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e28f4af0577d446d6acf54a9cd6da2c44554010
--- /dev/null
+++ b/pool/shard009/Python/0085939_list.py
@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+from cms.management.commands.subcommands.base import SubcommandsCommand
+from cms.models.pluginmodel import CMSPlugin
+from cms.models.titlemodels import Title
+from cms.plugin_pool import plugin_pool
+from django.core.management.base import NoArgsCommand
+from django.db.utils import DatabaseError
+
+class ListApphooksCommand(NoArgsCommand):
+
+ help = 'Lists all apphooks in pages'
+ def handle_noargs(self, **options):
+ urls = Title.objects.filter(application_urls__gt='').values_list("application_urls", flat=True)
+ for url in urls:
+ self.stdout.write('%s\n' % url)
+
+def plugin_report():
+ # structure of report:
+ # [
+ # {
+ # 'type': CMSPlugin class,
+ # 'model': plugin_type.model,
+ # 'instances': instances in the CMSPlugin table,
+ # 'unsaved_instances': those with no corresponding model instance,
+ # },
+ # ]
+ plugin_report = []
+ all_plugins = CMSPlugin.objects.order_by("plugin_type")
+ plugin_types = list(set(all_plugins.values_list("plugin_type", flat=True)))
+ plugin_types.sort()
+
+ for plugin_type in plugin_types:
+ plugin = {}
+ plugin["type"] = plugin_type
+ try:
+ # get all plugins of this type
+ plugins = CMSPlugin.objects.filter(plugin_type=plugin_type)
+ plugin["instances"] = plugins
+ # does this plugin have a model? report unsaved instances
+ plugin["model"] = plugin_pool.get_plugin(name=plugin_type).model
+ unsaved_instances = [p for p in plugins if not p.get_plugin_instance()[0]]
+ plugin["unsaved_instances"] = unsaved_instances
+
+ # catch uninstalled plugins
+ except KeyError:
+ plugin["model"] = None
+ plugin["instances"] = plugins
+ plugin["unsaved_instances"] = []
+
+ plugin_report.append(plugin)
+
+ return plugin_report
+
+
+
+class ListPluginsCommand(NoArgsCommand):
+
+ help = 'Lists all plugins in CMSPlugin'
+ def handle_noargs(self, **options):
+ self.stdout.write("==== Plugin report ==== \n\n")
+ self.stdout.write("There are %s plugin types in your database \n" % len(plugin_report()))
+ for plugin in plugin_report():
+ self.stdout.write("\n%s \n" % plugin["type"])
+
+ plugin_model = plugin["model"]
+ instances = len(plugin["instances"])
+ unsaved_instances = len(plugin["unsaved_instances"])
+
+ if not plugin_model:
+ self.stdout.write(self.style.ERROR(" ERROR : not installed \n"))
+
+ elif plugin_model == CMSPlugin:
+ self.stdout.write(" model-less plugin \n")
+ self.stdout.write(" unsaved instance(s) : %s \n" % unsaved_instances)
+
+ else:
+ self.stdout.write(" model : %s.%s \n" %
+ (plugin_model.__module__, plugin_model.__name__))
+ if unsaved_instances:
+ self.stdout.write(self.style.ERROR(" ERROR : %s unsaved instance(s) \n" % unsaved_instances))
+
+ self.stdout.write(" instance(s): %s \n" % instances)
+
+
+class ListCommand(SubcommandsCommand):
+ help = 'List commands'
+ subcommands = {
+ 'apphooks': ListApphooksCommand,
+ 'plugins': ListPluginsCommand
+ }
\ No newline at end of file
diff --git a/pool/shard009/Python/0085945_vlan_allocation.py b/pool/shard009/Python/0085945_vlan_allocation.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b5f0866d0bb2a387cb8a170afb05aacf034d6fb
--- /dev/null
+++ b/pool/shard009/Python/0085945_vlan_allocation.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+
+import sys
+import MySQLdb
+from MySQLdb.cursors import DictCursor
+from optparse import OptionParser
+
+parser = OptionParser(usage="usage: %prog [options] devstack_name")
+parser.add_option("-a", "--allocate", action="store_false", default=True)
+parser.add_option("-r", "--release", action="store_false", default=False)
+
+(options, args) = parser.parse_args()
+
+class VlanRanges(object):
+
+ def __init__(self):
+ self.db = MySQLdb.connect(
+ host="10.21.7.41",
+ user="jenkins-slave",
+ passwd="cMo83Hdef8d",
+ db="cbs_data",
+ read_default_file="~/.my.cnf",
+ cursorclass = DictCursor)
+ self.conn = self.db.cursor()
+
+ def get_range(self, devstack):
+ # escape input
+ name = self.db.escape_string(str(devstack))
+
+ # Check if we already have a vlan range alocated for this devstack.
+ # For situations where we execute this cript as part of an
+ # exec_withretry block
+ ret = self.conn.execute("""select * from vlanIds where devstack="%s";""" % name)
+ if ret:
+ row = self.conn.fetchone()
+ return "%s:%s" % (row['vlanStart'], row['vlanEnd'])
+
+ # Allocate new vlan range
+ self.conn.execute("""start transaction;""")
+ ret = self.conn.execute("""select * from vlanIds where devstack is NULL LIMIT 1 FOR UPDATE;""")
+ if ret:
+ row = self.conn.fetchone()
+ update_ret = self.conn.execute("""update vlanIds set devstack="%s" where id='%s';""" % (name, row['id']))
+ if update_ret == 0:
+ self.conn.execute("""rollback;""")
+ raise Exception("Failed to get range")
+ self.conn.execute("""COMMIT;""")
+ return "%s:%s" % (row['vlanStart'], row['vlanEnd'])
+
+ def release_range(self, devstack):
+ """ Release range associated to devstack """
+ # escape input
+ name = self.db.escape_string(str(devstack))
+ ret = self.conn.execute("""select * from vlanIds where devstack="%s";""" % name)
+ if ret == 0:
+ return True
+
+ # release range
+ self.conn.execute("""start transaction;""")
+ update_ret = self.conn.execute("""update vlanIds set devstack=NULL where devstack='%s';""" % name)
+ if update_ret == 0:
+ self.conn.execute("""rollback;""")
+ raise Exception("Failed to get range")
+ self.conn.execute("""COMMIT;""")
+ return True
+
+
+if __name__ == "__main__":
+ parser = OptionParser(usage="usage: %prog [options] devstack_name")
+ parser.add_option("-a", "--allocate", action="store_true", default=False)
+ parser.add_option("-r", "--release", action="store_true", default=False)
+
+ (options, args) = parser.parse_args()
+
+ if options.allocate and options.release:
+ parser.error("options -a and -r are mutually exclusive")
+
+ if len(args) == 0:
+ print("You must specify devstack name")
+ sys.exit(1)
+
+ ranges = VlanRanges()
+ if options.allocate:
+ print ranges.get_range(args[0])
+ if options.release:
+ ranges.release_range(args[0])
diff --git a/pool/shard009/Python/0085949_test_aspects.py b/pool/shard009/Python/0085949_test_aspects.py
new file mode 100644
index 0000000000000000000000000000000000000000..433aa1e81744dc832bd46df0e6d8a806ee67986f
--- /dev/null
+++ b/pool/shard009/Python/0085949_test_aspects.py
@@ -0,0 +1,59 @@
+import unittest
+
+import synapse.cortex as s_cortex
+import synapse.aspects as s_aspects
+
+class AspectTest(unittest.TestCase):
+
+ def test_aspect_iter_up(self):
+ tags = tuple( s_aspects.iterTagUp('foo.bar.baz') )
+ self.assertEqual( tags, ('foo.bar.baz','foo.bar','foo') )
+
+ def test_aspect_iter_down(self):
+ tags = tuple( s_aspects.iterTagDown('foo.bar.baz') )
+ self.assertEqual( tags, ('foo','foo.bar','foo.bar.baz') )
+
+ def test_aspect_adddel(self):
+ core = s_cortex.openurl('ram:///')
+ tufo = core.formTufoByProp('foo','bar')
+ tufo = core.addTufoTag(tufo, 'baz.faz.gaz', valu=None)
+
+ tags = s_aspects.getTufoTags(tufo)
+
+ self.assertIsNotNone( tags.get('baz') )
+ self.assertIsNotNone( tags.get('baz.faz') )
+ self.assertIsNotNone( tags.get('baz.faz.gaz') )
+
+ tufos = core.getTufosByTag('foo','baz.faz')
+ self.assertEqual( len(tufos), 1 )
+
+ tufo = core.delTufoTag(tufo,'baz.faz')
+
+ tufos = core.getTufosByTag('foo','baz.faz')
+ self.assertEqual( len(tufos), 0 )
+
+ tufos = core.getTufosByTag('foo','baz.faz.gaz')
+ self.assertEqual( len(tufos), 0 )
+
+ def test_aspect_bytag(self):
+ bytag = s_aspects.ByTag()
+
+ bytag.put('foo0',('foos.foo0','bar.baz'))
+ bytag.put('foo1',('foos.foo1','bar.faz'))
+
+ vals = tuple( sorted( bytag.get('bar') ) )
+ self.assertEqual( vals, ('foo0','foo1') )
+
+ vals = tuple( sorted( bytag.get('foos') ) )
+ self.assertEqual( vals, ('foo0','foo1') )
+
+ vals = tuple( sorted( bytag.get('foos.foo0') ) )
+ self.assertEqual( vals, ('foo0',) )
+
+ vals = tuple( sorted( bytag.get('newp.foo0') ) )
+ self.assertEqual( vals, () )
+
+ bytag.pop('foo0')
+
+ vals = tuple( sorted( bytag.get('foos') ) )
+ self.assertEqual( vals, ('foo1',) )
diff --git a/pool/shard009/Python/0085956_handlers.py b/pool/shard009/Python/0085956_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe26dcdcd650bcd10b7ed09cad5a738e8088b044
--- /dev/null
+++ b/pool/shard009/Python/0085956_handlers.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) the Contributors
+#
+# 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.
+#
+
+import logging
+import zmq
+from zmq.eventloop import zmqstream
+
+logger = logging.getLogger('cqrs-core')
+
+
+class CommandHandler:
+
+ def __init__(self, registry, name, end_point, sockt):
+ self._name = name
+ self._end_point = end_point
+ self._stream = zmqstream.ZMQStream(sockt)
+ self._registry = registry
+ logger.info('command handler initialized')
+
+ @property
+ def get_name(self):
+ return self._name
+
+ def start(self):
+ self._stream.on_recv_stream(self._on_recv)
+ self._stream.on_send_stream(self._on_send)
+ self._stream.bind(self._end_point)
+ logger.info('command request started')
+
+ def stop(self):
+ self._stream.stop_on_send()
+ self._stream.stop_on_recv()
+ logger.info('command request stopped')
+
+ def _on_recv(self, stream, msg):
+ logger.info('data received')
+
+ def _on_send(self, stream, msg, status):
+ pass
+
+ def on_validation(self):
+ return False
+
+ def on_execution(self):
+ pass
+
+ def handle(self, arguments):
+
+ if self.on_validation(arguments):
+ self.on_execution()
+
+
+class CommandHandlerRegistry:
+
+ def __init__(self, context=None):
+ self._context = context or zmq.Context.instance()
+ self._commands = {}
+
+ def createCommandHandler(self, name, end_point):
+
+ if not self._commands.get(end_point):
+ s = self._context.socket(zmq.ROUTER)
+ self._commands[end_point] = CommandHandler(self, name, end_point, s)
+ return self._commands.get(end_point)
+
+ def add_command(self, end_point):
+ pass
+
+
diff --git a/pool/shard009/Python/0085963_excutils.py b/pool/shard009/Python/0085963_excutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f50f6a2644282041f11c56d7ab90d8f251ab1372
--- /dev/null
+++ b/pool/shard009/Python/0085963_excutils.py
@@ -0,0 +1,99 @@
+# Copyright 2011 OpenStack Foundation.
+# Copyright 2012, Red Hat, 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.
+
+"""
+Exception related utilities.
+"""
+
+import logging
+import sys
+import time
+import traceback
+
+import six
+
+from solum.openstack.common.gettextutils import _
+
+
+class save_and_reraise_exception(object):
+ """Save current exception, run some code and then re-raise.
+
+ In some cases the exception context can be cleared, resulting in None
+ being attempted to be re-raised after an exception handler is run. This
+ can happen when eventlet switches greenthreads or when running an
+ exception handler, code raises and catches an exception. In both
+ cases the exception context will be cleared.
+
+ To work around this, we save the exception state, run handler code, and
+ then re-raise the original exception. If another exception occurs, the
+ saved exception is logged and the new exception is re-raised.
+
+ In some cases the caller may not want to re-raise the exception, and
+ for those circumstances this context provides a reraise flag that
+ can be used to suppress the exception. For example::
+
+ except Exception:
+ with save_and_reraise_exception() as ctxt:
+ decide_if_need_reraise()
+ if not should_be_reraised:
+ ctxt.reraise = False
+ """
+ def __init__(self):
+ self.reraise = True
+
+ def __enter__(self):
+ self.type_, self.value, self.tb, = sys.exc_info()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if exc_type is not None:
+ logging.error(_('Original exception being dropped: %s'),
+ traceback.format_exception(self.type_,
+ self.value,
+ self.tb))
+ return False
+ if self.reraise:
+ six.reraise(self.type_, self.value, self.tb)
+
+
+def forever_retry_uncaught_exceptions(infunc):
+ def inner_func(*args, **kwargs):
+ last_log_time = 0
+ last_exc_message = None
+ exc_count = 0
+ while True:
+ try:
+ return infunc(*args, **kwargs)
+ except Exception as exc:
+ this_exc_message = six.u(str(exc))
+ if this_exc_message == last_exc_message:
+ exc_count += 1
+ else:
+ exc_count = 1
+ # Do not log any more frequently than once a minute unless
+ # the exception message changes
+ cur_time = int(time.time())
+ if (cur_time - last_log_time > 60 or
+ this_exc_message != last_exc_message):
+ logging.exception(
+ _('Unexpected exception occurred %d time(s)... '
+ 'retrying.') % exc_count)
+ last_log_time = cur_time
+ last_exc_message = this_exc_message
+ exc_count = 0
+ # This should be a very rare event. In case it isn't, do
+ # a sleep.
+ time.sleep(1)
+ return inner_func
diff --git a/pool/shard009/Python/0085968_http_challenge.py b/pool/shard009/Python/0085968_http_challenge.py
new file mode 100644
index 0000000000000000000000000000000000000000..577952c61919a4f0fd7a7b3eba80cf2e9da613e2
--- /dev/null
+++ b/pool/shard009/Python/0085968_http_challenge.py
@@ -0,0 +1,116 @@
+#---------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+#---------------------------------------------------------------------------------------------
+# pylint: skip-file
+# flake8: noqa
+try:
+ import urllib.parse as parse
+except ImportError:
+ import urlparse as parse # pylint: disable=import-error
+
+
+class HttpChallenge(object):
+
+ def __init__(self, request_uri, challenge, response_headers=None):
+ """ Parses an HTTP WWW-Authentication Bearer challenge from a server. """
+ self.source_authority = self._validate_request_uri(request_uri)
+ self.source_uri = request_uri
+ self._parameters = {}
+
+ # get the scheme of the challenge and remove from the challenge string
+ trimmed_challenge = self._validate_challenge(challenge)
+ split_challenge = trimmed_challenge.split(' ', 1)
+ self.scheme = split_challenge[0]
+ trimmed_challenge = split_challenge[1]
+
+ # split trimmed challenge into comma-separated name=value pairs. Values are expected
+ # to be surrounded by quotes which are stripped here.
+ for item in trimmed_challenge.split(','):
+ # process name=value pairs
+ comps = item.split('=')
+ if len(comps) == 2:
+ key = comps[0].strip(' "')
+ value = comps[1].strip(' "')
+ if key:
+ self._parameters[key] = value
+
+ # minimum set of parameters
+ if not self._parameters:
+ raise ValueError('Invalid challenge parameters')
+
+ # must specify authorization or authorization_uri
+ if 'authorization' not in self._parameters and 'authorization_uri' not in self._parameters:
+ raise ValueError('Invalid challenge parameters')
+
+ # if the response headers were supplied
+ if response_headers:
+ # get the message signing key and message key encryption key from the headers
+ self.server_signature_key = response_headers.get('x-ms-message-signing-key', None)
+ self.server_encryption_key = response_headers.get('x-ms-message-encryption-key', None)
+
+ def is_bearer_challenge(self):
+ """ Tests whether the HttpChallenge a Bearer challenge.
+ rtype: bool """
+ if not self.scheme:
+ return False
+
+ return self.scheme.lower() == 'bearer'
+
+ def is_pop_challenge(self):
+ """ Tests whether the HttpChallenge is a proof of possession challenge.
+ rtype: bool """
+ if not self.scheme:
+ return False
+
+ return self.scheme.lower() == 'pop'
+
+ def get_value(self, key):
+ return self._parameters.get(key)
+
+ def get_authorization_server(self):
+ """ Returns the URI for the authorization server if present, otherwise empty string. """
+ value = ''
+ for key in ['authorization_uri', 'authorization']:
+ value = self.get_value(key) or ''
+ if value:
+ break
+ return value
+
+ def get_resource(self):
+ """ Returns the resource if present, otherwise empty string. """
+ return self.get_value('resource') or ''
+
+ def get_scope(self):
+ """ Returns the scope if present, otherwise empty string. """
+ return self.get_value('scope') or ''
+
+ def supports_pop(self):
+ """ Returns True if challenge supports pop token auth else False """
+ return self._parameters.get('supportspop', '').lower() == 'true'
+
+ def supports_message_protection(self):
+ """ Returns True if challenge vault supports message protection """
+ return self.supports_pop() and self.server_encryption_key and self.server_signature_key
+
+ def _validate_challenge(self, challenge):
+ """ Verifies that the challenge is a valid auth challenge and returns the key=value pairs. """
+ if not challenge:
+ raise ValueError('Challenge cannot be empty')
+
+ return challenge.strip()
+
+ # pylint: disable=no-self-use
+ def _validate_request_uri(self, uri):
+ """ Extracts the host authority from the given URI. """
+ if not uri:
+ raise ValueError('request_uri cannot be empty')
+
+ uri = parse.urlparse(uri)
+ if not uri.netloc:
+ raise ValueError('request_uri must be an absolute URI')
+
+ if uri.scheme.lower() not in ['http', 'https']:
+ raise ValueError('request_uri must be HTTP or HTTPS')
+
+ return uri.netloc
diff --git a/pool/shard009/Python/0085971_init__.py b/pool/shard009/Python/0085971_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2011536ea4dc1c355df49d88b6608bbf06f57839
--- /dev/null
+++ b/pool/shard009/Python/0085971_init__.py
@@ -0,0 +1,44 @@
+# Copyright 2018 Samsung Electronics
+# 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.
+
+from oslo_config import cfg
+from vitrage.common.constants import DatasourceOpts as DSOpts
+from vitrage.common.constants import UpdateMethod
+
+TROVE_CLUSTER_DATASOURCE = 'trove.cluster'
+
+OPTS = [
+ cfg.StrOpt(DSOpts.TRANSFORMER,
+ default='vitrage.datasources.trove.cluster.transformer.'
+ 'TroveClusterTransformer',
+ help='Trove transformer class path.',
+ required=True),
+ cfg.StrOpt(DSOpts.DRIVER,
+ default='vitrage.datasources.trove.cluster.driver.'
+ 'TroveClusterDriver',
+ help='Trove driver class path.',
+ required=True),
+ cfg.StrOpt(DSOpts.UPDATE_METHOD,
+ default=UpdateMethod.PULL,
+ help='None: updates only via Vitrage periodic snapshots.'
+ 'Pull: updates periodically.'
+ 'Push: updates by getting notifications from the'
+ ' datasource itself.',
+ required=True),
+ cfg.IntOpt(DSOpts.CHANGES_INTERVAL,
+ default=30,
+ min=10,
+ help='Interval in seconds between checking changes in Trove'
+ 'cluster datasource.')]
diff --git a/pool/shard009/Python/0085975_error_module.py b/pool/shard009/Python/0085975_error_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f1537017611f549c8d6623037325b05a7971139
--- /dev/null
+++ b/pool/shard009/Python/0085975_error_module.py
@@ -0,0 +1,183 @@
+"""
+Modules that get shown to the users when an error has occured while
+loading or rendering other modules
+"""
+
+import hashlib
+import logging
+import json
+import sys
+
+from lxml import etree
+from xmodule.x_module import XModule
+from xmodule.editing_module import JSONEditingDescriptor
+from xmodule.errortracker import exc_info_to_str
+from xmodule.modulestore import Location
+from xblock.core import String, Scope
+
+
+log = logging.getLogger(__name__)
+
+# NOTE: This is not the most beautiful design in the world, but there's no good
+# way to tell if the module is being used in a staff context or not. Errors that get discovered
+# at course load time are turned into ErrorDescriptor objects, and automatically hidden from students.
+# Unfortunately, we can also have errors when loading modules mid-request, and then we need to decide
+# what to show, and the logic for that belongs in the LMS (e.g. in get_module), so the error handler
+# decides whether to create a staff or not-staff module.
+
+
+class ErrorFields(object):
+ """
+ XBlock fields used by the ErrorModules
+ """
+ contents = String(scope=Scope.content)
+ error_msg = String(scope=Scope.content)
+ display_name = String(scope=Scope.settings)
+
+
+class ErrorModule(ErrorFields, XModule):
+ """
+ Module that gets shown to staff when there has been an error while
+ loading or rendering other modules
+ """
+
+ def get_html(self):
+ '''Show an error to staff.
+ TODO (vshnayder): proper style, divs, etc.
+ '''
+ # staff get to see all the details
+ return self.system.render_template('module-error.html', {
+ 'staff_access': True,
+ 'data': self.contents,
+ 'error': self.error_msg,
+ })
+
+
+class NonStaffErrorModule(ErrorFields, XModule):
+ """
+ Module that gets shown to students when there has been an error while
+ loading or rendering other modules
+ """
+ def get_html(self):
+ '''Show an error to a student.
+ TODO (vshnayder): proper style, divs, etc.
+ '''
+ # staff get to see all the details
+ return self.system.render_template('module-error.html', {
+ 'staff_access': False,
+ 'data': "",
+ 'error': "",
+ })
+
+
+class ErrorDescriptor(ErrorFields, JSONEditingDescriptor):
+ """
+ Module that provides a raw editing view of broken xml.
+ """
+ module_class = ErrorModule
+
+ @classmethod
+ def _construct(cls, system, contents, error_msg, location):
+
+ if location.name is None:
+ location = location._replace(
+ category='error',
+ # Pick a unique url_name -- the sha1 hash of the contents.
+ # NOTE: We could try to pull out the url_name of the errored descriptor,
+ # but url_names aren't guaranteed to be unique between descriptor types,
+ # and ErrorDescriptor can wrap any type. When the wrapped module is fixed,
+ # it will be written out with the original url_name.
+ name=hashlib.sha1(contents).hexdigest()
+ )
+
+ # real metadata stays in the content, but add a display name
+ model_data = {
+ 'error_msg': str(error_msg),
+ 'contents': contents,
+ 'display_name': 'Error: ' + location.name
+ }
+ return cls(
+ system,
+ location,
+ model_data,
+ )
+
+ def get_context(self):
+ return {
+ 'module': self,
+ 'data': self.contents,
+ }
+
+ @classmethod
+ def from_json(cls, json_data, system, error_msg='Error not available'):
+ return cls._construct(
+ system,
+ json.dumps(json_data, indent=4),
+ error_msg,
+ location=Location(json_data['location']),
+ )
+
+ @classmethod
+ def from_descriptor(cls, descriptor, error_msg='Error not available'):
+ return cls._construct(
+ descriptor.system,
+ str(descriptor),
+ error_msg,
+ location=descriptor.location,
+ )
+
+ @classmethod
+ def from_xml(cls, xml_data, system, org=None, course=None,
+ error_msg='Error not available'):
+ '''Create an instance of this descriptor from the supplied data.
+
+ Does not require that xml_data be parseable--just stores it and exports
+ as-is if not.
+
+ Takes an extra, optional, parameter--the error that caused an
+ issue. (should be a string, or convert usefully into one).
+ '''
+
+ try:
+ # If this is already an error tag, don't want to re-wrap it.
+ xml_obj = etree.fromstring(xml_data)
+ if xml_obj.tag == 'error':
+ xml_data = xml_obj.text
+ error_node = xml_obj.find('error_msg')
+ if error_node is not None:
+ error_msg = error_node.text
+ else:
+ error_msg = 'Error not available'
+
+ except etree.XMLSyntaxError:
+ # Save the error to display later--overrides other problems
+ error_msg = exc_info_to_str(sys.exc_info())
+
+ return cls._construct(system, xml_data, error_msg, location=Location('i4x', org, course, None, None))
+
+ def export_to_xml(self, resource_fs):
+ '''
+ If the definition data is invalid xml, export it wrapped in an "error"
+ tag. If it is valid, export without the wrapper.
+
+ NOTE: There may still be problems with the valid xml--it could be
+ missing required attributes, could have the wrong tags, refer to missing
+ files, etc. That would just get re-wrapped on import.
+ '''
+ try:
+ xml = etree.fromstring(self.contents)
+ return etree.tostring(xml, encoding='unicode')
+ except etree.XMLSyntaxError:
+ # still not valid.
+ root = etree.Element('error')
+ root.text = self.contents
+ err_node = etree.SubElement(root, 'error_msg')
+ err_node.text = self.error_msg
+ return etree.tostring(root, encoding='unicode')
+
+
+class NonStaffErrorDescriptor(ErrorDescriptor):
+ """
+ Module that provides non-staff error messages.
+ """
+ module_class = NonStaffErrorModule
diff --git a/pool/shard009/Python/0085978_spoolme.py b/pool/shard009/Python/0085978_spoolme.py
new file mode 100644
index 0000000000000000000000000000000000000000..95ea8c3271ad645c65e3ed70e8a46b9472f0424b
--- /dev/null
+++ b/pool/shard009/Python/0085978_spoolme.py
@@ -0,0 +1,19 @@
+import uwsgi
+import time
+
+def slow_task(args):
+ time.sleep(10)
+ return uwsgi.SPOOL_OK
+
+uwsgi.spooler = slow_task
+
+
+
+def application(env, start_response):
+
+ name = uwsgi.spool({'Hello':'World', 'I am a':'long running task'})
+ print("spooled as %s" % name)
+
+ start_response('200 Ok', [('Content-Type','text/plain'),('uWSGI-Status', 'spooled')])
+
+ return "task spooled"
diff --git a/pool/shard009/Python/0085983_test_client.py b/pool/shard009/Python/0085983_test_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..eeb3a90f397196d62d14485c4c4c507594e81c9e
--- /dev/null
+++ b/pool/shard009/Python/0085983_test_client.py
@@ -0,0 +1,127 @@
+import json
+from unittest import mock
+
+import httpretty
+import requests.exceptions
+from testfixtures import log_capture
+
+from analyticsclient.client import Client
+from analyticsclient.constants import data_formats, http_methods
+from analyticsclient.exceptions import ClientError, TimeoutError # pylint: disable=redefined-builtin
+from analyticsclient.tests import ClientTestCase
+
+
+class ClientTests(ClientTestCase):
+ def setUp(self):
+ super().setUp()
+ httpretty.enable()
+ self.test_endpoint = 'test'
+ self.test_url = self.get_api_url(self.test_endpoint)
+
+ def tearDown(self):
+ httpretty.disable()
+ httpretty.reset()
+
+ def test_date_format(self):
+ self.assertEqual(Client.DATE_FORMAT, '%Y-%m-%d')
+ self.assertEqual(Client('').DATE_FORMAT, '%Y-%m-%d')
+
+ def test_has_resource(self):
+ httpretty.register_uri(httpretty.GET, self.test_url, body='')
+ self.assertEqual(self.client.has_resource(self.test_endpoint), True)
+
+ def test_missing_resource(self):
+ httpretty.register_uri(httpretty.GET, self.test_url, body='', status=404)
+ self.assertEqual(self.client.has_resource(self.test_endpoint), False)
+
+ def test_failed_authentication(self):
+ client = Client(base_url=self.api_url, auth_token='atoken')
+ httpretty.register_uri(httpretty.GET, self.test_url, body='', status=401)
+
+ self.assertEqual(client.has_resource(self.test_endpoint), False)
+ self.assertEqual(httpretty.last_request().headers['Authorization'], 'Token atoken')
+
+ def test_get(self):
+ data = {'foo': 'bar'}
+ httpretty.register_uri(httpretty.GET, self.test_url, body=json.dumps(data))
+ self.assertEqual(self.client.get(self.test_endpoint), data)
+
+ def test_post(self):
+ data = {'foo': 'bar'}
+ httpretty.register_uri(httpretty.POST, self.test_url, body=json.dumps(data))
+ self.assertEqual(self.client.request(http_methods.POST, self.test_endpoint), data)
+
+ def test_get_invalid_response_body(self):
+ """ Verify that client raises a ClientError if the response body cannot be properly parsed. """
+
+ data = {'foo': 'bar'}
+ httpretty.register_uri(httpretty.GET, self.test_url, body=json.dumps(data)[:6])
+ with self.assertRaises(ClientError):
+ self.client.get(self.test_endpoint)
+
+ def test_strip_trailing_slash(self):
+ url = 'http://example.com'
+ client = Client(url)
+ self.assertEqual(client.base_url, url)
+
+ url_with_slash = 'http://example.com/'
+ client = Client(url_with_slash)
+ self.assertEqual(client.base_url, url)
+
+ # pylint: disable=protected-access
+ @log_capture()
+ @mock.patch('requests.get', side_effect=requests.exceptions.Timeout)
+ def test_request_timeout(self, mock_get, lc):
+ url = self.test_url
+ timeout = None
+ headers = {'Accept': 'application/json'}
+
+ self.assertRaises(
+ TimeoutError,
+ self.client._request,
+ http_methods.GET,
+ self.test_endpoint,
+ timeout=timeout
+ )
+ msg = f'Response from {self.test_endpoint} exceeded timeout of {self.client.timeout}s.'
+ lc.check(('analyticsclient.client', 'ERROR', msg))
+ lc.clear()
+ mock_get.assert_called_once_with(url, headers=headers, timeout=self.client.timeout, params={})
+ mock_get.reset_mock()
+
+ timeout = 10
+ self.assertRaises(
+ TimeoutError,
+ self.client._request,
+ http_methods.GET,
+ self.test_endpoint,
+ timeout=timeout
+ )
+ mock_get.assert_called_once_with(url, headers=headers, timeout=timeout, params={})
+ msg = f'Response from {self.test_endpoint} exceeded timeout of {timeout}s.'
+ lc.check(('analyticsclient.client', 'ERROR', msg))
+
+ def test_request_format(self):
+ httpretty.register_uri(httpretty.GET, self.test_url, body='{}')
+
+ response = self.client.get(self.test_endpoint)
+ self.assertEqual(httpretty.last_request().headers['Accept'], 'application/json')
+ self.assertDictEqual(response, {})
+
+ httpretty.register_uri(httpretty.GET, self.test_url, body='not-json')
+ response = self.client.get(self.test_endpoint, data_format=data_formats.CSV)
+ self.assertEqual(httpretty.last_request().headers['Accept'], 'text/csv')
+ self.assertEqual(response, 'not-json')
+
+ httpretty.register_uri(httpretty.GET, self.test_url, body='{}')
+ response = self.client.get(self.test_endpoint, data_format=data_formats.JSON)
+ self.assertEqual(httpretty.last_request().headers['Accept'], 'application/json')
+ self.assertDictEqual(response, {})
+
+ def test_unsupported_method(self):
+ self.assertRaises(
+ ValueError,
+ self.client._request,
+ http_methods.PATCH,
+ self.test_endpoint
+ )
diff --git a/pool/shard009/Python/0085986_FromLayeredToSingleTexture.py b/pool/shard009/Python/0085986_FromLayeredToSingleTexture.py
new file mode 100644
index 0000000000000000000000000000000000000000..88efc753ac9797c4b257d8479182b03d1c25df0e
--- /dev/null
+++ b/pool/shard009/Python/0085986_FromLayeredToSingleTexture.py
@@ -0,0 +1,38 @@
+
+#################################################################
+#
+# Script for removing layered textures for diffuse channel (export fbx issue)
+#
+# Author: Sergey Solohin (Neill3d) 2013, e-mail to: s@neill3d.com
+# www.neill3d.com
+#
+# Github repo - https://github.com/Neill3d/MoPlugs
+# Licensed under BSD 3-clause
+# https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
+#
+#################################################################
+
+from pyfbsdk import *
+
+gSystem = FBSystem()
+
+
+def UpdateMaterial(mat):
+ #
+ if mat:
+ lTexture = mat.GetTexture(FBMaterialTextureType.kFBMaterialTextureDiffuse)
+ if lTexture and isinstance(lTexture, FBLayeredTexture):
+ if len(lTexture.Layers) > 0:
+ mat.SetTexture(lTexture.Layers[0], FBMaterialTextureType.kFBMaterialTextureDiffuse)
+ #
+ #
+
+l = FBModelList()
+FBGetSelectedModels(l)
+
+for obj in l:
+ for mat in obj.Materials:
+ UpdateMaterial(mat)
+
+ for t in obj.Textures:
+ UpdateTexture(t)
diff --git a/pool/shard009/Python/0085989_recordset_cleanup.py b/pool/shard009/Python/0085989_recordset_cleanup.py
new file mode 100644
index 0000000000000000000000000000000000000000..1264262ae33629f8a6612e9c7fe9a0986ac8860c
--- /dev/null
+++ b/pool/shard009/Python/0085989_recordset_cleanup.py
@@ -0,0 +1,69 @@
+from __future__ import division, absolute_import, print_function
+import sys
+
+from idb.postgres_backend import apidbpool
+from idb import stats
+import datetime
+
+
+def post_delete_stats(rsid):
+ summary = {
+ "recordset_id": rsid,
+ "harvest_date": datetime.datetime.now().isoformat(),
+ "records_count": 0,
+ "records_create": 0,
+ "records_update": 0,
+ "records_delete": 0,
+ "mediarecords_count": 0,
+ "mediarecords_create": 0,
+ "mediarecords_update": 0,
+ "mediarecords_delete": 0,
+ "deleted": True,
+ "commited": True,
+ }
+ stats.index(doc_type="digest", body=summary)
+
+
+def post_all_deleted_rs():
+ deleted_query = {
+ "query": {
+ "filtered": {
+ "filter": {
+ "term": {
+ "deleted": True
+ }
+ }
+ }
+ },
+ "size": 10000
+ }
+
+ deleted_recordsets = set()
+ rsp = stats.search(doc_type="digest", body=deleted_query)
+ for rs in rsp["hits"]["hits"]:
+ deleted_recordsets.add(rs["_source"]["recordset_id"])
+
+ print("{} recordsets already marked as deleted in stats.".format(
+ len(deleted_recordsets)))
+
+ count = 0
+ with apidbpool.cursor() as cursor:
+ cursor.execute("SELECT id FROM uuids WHERE type='recordset' and deleted=true")
+
+ for r in cursor:
+ if r["id"] not in deleted_recordsets:
+ count += 1
+ print("Deleting {}.".format(r["id"]))
+ post_delete_stats(r["id"])
+
+ print("{} recordsets deleted from stats.".format(count))
+
+
+def main():
+ if len(sys.argv) > 1:
+ post_delete_stats(sys.argv[1])
+ else:
+ post_all_deleted_rs()
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0086003_conftest.py b/pool/shard009/Python/0086003_conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..852030d219a388bf9c2c452a61e9a3d6180a4ddb
--- /dev/null
+++ b/pool/shard009/Python/0086003_conftest.py
@@ -0,0 +1,42 @@
+#
+# Copyright 2016 The BigDL 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 pytest
+sc = None
+ray_ctx = None
+
+
+@pytest.fixture(autouse=True, scope='function')
+def automl_fixture():
+ from bigdl.dllib.nncontext import init_spark_on_local
+ from bigdl.orca.ray import RayContext
+ sc = init_spark_on_local(cores=4, spark_log_level="INFO")
+ ray_ctx = RayContext(sc=sc, object_store_memory="1g")
+ ray_ctx.init()
+ yield
+ ray_ctx.stop()
+ sc.stop()
+
+
+# @pytest.fixture()
+# def setUpModule():
+# sc = init_spark_on_local(cores=4, spark_log_level="INFO")
+# ray_ctx = RayContext(sc=sc)
+# ray_ctx.init()
+#
+#
+# def tearDownModule():
+# ray_ctx.stop()
+# sc.stop()
diff --git a/pool/shard009/Python/0086005_boston_housing.py b/pool/shard009/Python/0086005_boston_housing.py
new file mode 100644
index 0000000000000000000000000000000000000000..52009e626d4896430f5df7ef4d7fa94264d7a97b
--- /dev/null
+++ b/pool/shard009/Python/0086005_boston_housing.py
@@ -0,0 +1,82 @@
+#
+# Copyright 2018 Analytics Zoo 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.
+#
+
+# Source url of dataset is from boston_housing.py from Keras Open Source Project
+#
+# The MIT License (MIT)
+#
+# 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.
+
+
+import numpy as np
+
+from bigdl.dataset import base
+
+
+def load_data(path='boston_housing.npz', dest_dir='/tmp/.zoo/dataset', test_split=0.2):
+ """Loads the Boston Housing dataset, the source url of download
+ is copied from keras.datasets
+ # Arguments
+ dest_dir: where to cache the data (relative to `~/.zoo/dataset`).
+ nb_words: number of words to keep, the words are already indexed by frequency
+ so that the less frequent words would be abandoned
+ oov_char: index to pad the abandoned words, if None, one abandoned word
+ would be taken place with its next word and total length -= 1
+ test_split: the ratio to split part of dataset to test data,
+ the remained data would be train data
+
+ # Returns
+ Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
+ """
+
+ path = base.maybe_download(path,
+ dest_dir,
+ 'https://s3.amazonaws.com/keras-datasets/boston_housing.npz')
+
+ with np.load(path) as f:
+ x = f['x']
+ y = f['y']
+
+ shuffle_by_seed([x, y])
+ split_index = int(len(x) * (1 - test_split))
+
+ x_train, y_train = x[:split_index], y[:split_index]
+
+ x_test, y_test = x[split_index:], y[split_index:]
+
+ return (x_train, y_train), (x_test, y_test)
+
+
+def shuffle_by_seed(arr_list, seed=0):
+ for arr in arr_list:
+ np.random.seed(seed)
+ np.random.shuffle(arr)
diff --git a/pool/shard009/Python/0086013_test_inputs.py b/pool/shard009/Python/0086013_test_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e9677fc7c166529a14d8e84a09bf0a188f21c1b
--- /dev/null
+++ b/pool/shard009/Python/0086013_test_inputs.py
@@ -0,0 +1,86 @@
+# encoding: utf-8
+
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+from django.test import TestCase
+
+from haystack import connections, inputs
+
+
+class InputTestCase(TestCase):
+ def setUp(self):
+ super(InputTestCase, self).setUp()
+ self.query_obj = connections['default'].get_query()
+
+ def test_raw_init(self):
+ raw = inputs.Raw('hello OR there, :you')
+ self.assertEqual(raw.query_string, 'hello OR there, :you')
+ self.assertEqual(raw.kwargs, {})
+ self.assertEqual(raw.post_process, False)
+
+ raw = inputs.Raw('hello OR there, :you', test='really')
+ self.assertEqual(raw.query_string, 'hello OR there, :you')
+ self.assertEqual(raw.kwargs, {'test': 'really'})
+ self.assertEqual(raw.post_process, False)
+
+ def test_raw_prepare(self):
+ raw = inputs.Raw('hello OR there, :you')
+ self.assertEqual(raw.prepare(self.query_obj), 'hello OR there, :you')
+
+ def test_clean_init(self):
+ clean = inputs.Clean('hello OR there, :you')
+ self.assertEqual(clean.query_string, 'hello OR there, :you')
+ self.assertEqual(clean.post_process, True)
+
+ def test_clean_prepare(self):
+ clean = inputs.Clean('hello OR there, :you')
+ self.assertEqual(clean.prepare(self.query_obj), 'hello OR there, :you')
+
+ def test_exact_init(self):
+ exact = inputs.Exact('hello OR there, :you')
+ self.assertEqual(exact.query_string, 'hello OR there, :you')
+ self.assertEqual(exact.post_process, True)
+
+ def test_exact_prepare(self):
+ exact = inputs.Exact('hello OR there, :you')
+ self.assertEqual(exact.prepare(self.query_obj), u'"hello OR there, :you"')
+
+ # Incorrect, but the backend doesn't implement much of anything useful.
+ exact = inputs.Exact('hello OR there, :you', clean=True)
+ self.assertEqual(exact.prepare(self.query_obj), u'"hello OR there, :you"')
+
+ def test_not_init(self):
+ not_it = inputs.Not('hello OR there, :you')
+ self.assertEqual(not_it.query_string, 'hello OR there, :you')
+ self.assertEqual(not_it.post_process, True)
+
+ def test_not_prepare(self):
+ not_it = inputs.Not('hello OR there, :you')
+ self.assertEqual(not_it.prepare(self.query_obj), u'NOT (hello OR there, :you)')
+
+ def test_autoquery_init(self):
+ autoquery = inputs.AutoQuery('panic -don\'t "froody dude"')
+ self.assertEqual(autoquery.query_string, 'panic -don\'t "froody dude"')
+ self.assertEqual(autoquery.post_process, False)
+
+ def test_autoquery_prepare(self):
+ autoquery = inputs.AutoQuery('panic -don\'t "froody dude"')
+ self.assertEqual(autoquery.prepare(self.query_obj), u'panic NOT don\'t "froody dude"')
+
+ def test_altparser_init(self):
+ altparser = inputs.AltParser('dismax')
+ self.assertEqual(altparser.parser_name, 'dismax')
+ self.assertEqual(altparser.query_string, '')
+ self.assertEqual(altparser.kwargs, {})
+ self.assertEqual(altparser.post_process, False)
+
+ altparser = inputs.AltParser('dismax', 'douglas adams', qf='author', mm=1)
+ self.assertEqual(altparser.parser_name, 'dismax')
+ self.assertEqual(altparser.query_string, 'douglas adams')
+ self.assertEqual(altparser.kwargs, {'mm': 1, 'qf': 'author'})
+ self.assertEqual(altparser.post_process, False)
+
+ def test_altparser_prepare(self):
+ altparser = inputs.AltParser('dismax', 'douglas adams', qf='author', mm=1)
+ # Not supported on that backend.
+ self.assertEqual(altparser.prepare(self.query_obj), '')
diff --git a/pool/shard009/Python/0086018_export_data.py b/pool/shard009/Python/0086018_export_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab33854ad244e06bbc388ed75d4b5d771d033533
--- /dev/null
+++ b/pool/shard009/Python/0086018_export_data.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python
+
+import dbhash
+import sys
+import fnmatch
+import cPickle as cp
+import sqlite3
+import time
+
+def run_insert_query_by_day(conn, key, value, day):
+ print "Command Construction"
+ for val in value:
+ test_time = time.strftime('%Y-%m-%d',time.gmtime(int(key[1])))
+ if test_time != day:
+ return
+ time_val = time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(int(key[1])))
+# try:
+ cmd = "INSERT into traceroute (deviceid,eventstamp,srcip,dstip,toolid,hop,ip,rtt) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')"%(key[0],time_val,key[2],key[3],key[4],val[0],val[1],val[2]);
+ #print cmd
+ conn.execute(cmd)
+# except:
+# print "Couldn't run %s\n"%(cmd)
+# continue
+ return
+
+def run_insert_query(conn, key, value):
+ print "Command Construction"
+ for val in value:
+ time_val = time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(int(key[1])))
+ cmd = "INSERT into traceroute (deviceid,eventstamp,srcip,dstip,toolid,hop,ip,rtt) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')"%(key[0],time_val,key[2],key[3],key[4],val[0],val[1],val[2]);
+ conn.execute(cmd)
+ return
+
+def export_day(day, conn):
+ db = dbhash.open("traceroutes--2014-01.db", "r")
+
+ for keys in db.keys():
+ key = cp.loads(keys)
+ value = cp.loads(db[keys])
+ retVal = run_insert_query_by_day(conn, key, value, day)
+ # if there is an error or we have gone past the correct day,
+ # then break out
+ # if retVal == False:
+ # break
+
+ conn.commit()
+ db.close()
+
+def export_all(conn):
+ db = dbhash.open("traceroutes--2014-01.db", "r")
+ numAdded = 0
+
+ for keys in db.keys():
+ key = cp.loads(keys)
+ value = cp.loads(db[keys])
+ retVal = run_insert_query(conn, key, value)
+ numAdded += 1
+ if numAdded > 100:
+ conn.commit()
+ numAdded = 0
+
+ conn.commit()
+ db.close()
+
+def create_table(conn):
+ create_table_query = ("CREATE table traceroute (deviceid text, eventstamp text, "
+ "srcip text, dstip text, toolid text, hop integer, ip text, rtt real)")
+ conn.execute(create_table_query)
+ conn.commit()
+
+def split_data_into_diff_tables(conn, filestub):
+ """Split the data into tables of 10 routers each so that we can
+ compute the prevalence and persistence in parallel
+
+ """
+ get_data = ("SELECT * from traceroute WHERE deviceid = ?")
+ get_routers = ("SELECT distinct deviceid from traceroute")
+ insert_data = ("INSERT into traceroute (deviceid,eventstamp,srcip,dstip,toolid,hop,ip,rtt) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
+ cursor = conn.cursor()
+ cursor.execute(get_routers)
+ fileNum = 0
+ dbName = filestub + str(fileNum) + ".db"
+ storeDB = sqlite3.connect(dbName)
+ create_table(storeDB)
+ store = storeDB.cursor()
+ routers = cursor.fetchall()
+ numUncommitted = 0
+ numRouters = 0
+ for (router,) in routers:
+ cursor.execute(get_data,(router,))
+ for entry in cursor.fetchall():
+ store.execute(insert_data, entry)
+ numUncommitted += 1
+ if numUncommitted > 100:
+ storeDB.commit()
+ numUncommitted = 0
+ numRouters += 1
+ print "Finished {} routers".format(numRouters)
+ storeDB.close()
+ fileNum += 1
+ dbName = filestub + str(fileNum) + ".db"
+ storeDB = sqlite3.connect(dbName)
+ create_table(storeDB)
+ store = storeDB.cursor()
+
+if __name__ == "__main__":
+ conn = sqlite3.connect('sqlite-traceroute-data.db')
+# create_table(conn)
+# export_day('2014-01-01', conn)
+# export_all(conn)
+# conn.commit()
+ split_data_into_diff_tables(conn, "monthly-data-split-")
+ conn.close()
diff --git a/pool/shard009/Python/0086021_cypher_record_test.py b/pool/shard009/Python/0086021_cypher_record_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b9607df5bd1476e330e68c78a3d68520183d35b
--- /dev/null
+++ b/pool/shard009/Python/0086021_cypher_record_test.py
@@ -0,0 +1,60 @@
+#/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright 2011-2014, Nigel Small
+#
+# 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 sys
+
+from py2neo.cypher.core import RecordProducer
+
+
+def test_record_field_access(graph):
+ statement = "CREATE (a {name:'Alice',age:33}) RETURN a,a.name as name,a.age as age"
+ for record in graph.cypher.stream(statement):
+ alice = record.values[0]
+ assert record.values[1] == alice.properties["name"]
+ assert record.values[2] == alice.properties["age"]
+ assert record.get("name") == alice.properties["name"]
+ assert record.get("age") == alice.properties["age"]
+
+
+def test_record_representation(graph):
+ statement = "CREATE (a {name:'Alice',age:33}) RETURN a,a.name,a.age"
+ for record in graph.cypher.stream(statement):
+ alice_id = record.values[0]._id
+ if sys.version_info >= (3,):
+ assert repr(record) == ("Record(columns=('a', 'a.name', 'a.age'), "
+ "values=((n%s {age:33,name:\"Alice\"}), "
+ "'Alice', 33))" % alice_id)
+ else:
+ assert repr(record) == ("Record(columns=(u'a', u'a.name', u'a.age'), "
+ "values=((n%s {age:33,name:\"Alice\"}), "
+ "u'Alice', 33))" % alice_id)
+
+
+def test_producer_representation():
+ producer = RecordProducer(["apple", "banana", "carrot"])
+ assert repr(producer) == "RecordProducer(columns=('apple', 'banana', 'carrot'))"
+
+
+def test_producer_length():
+ producer = RecordProducer(["apple", "banana", "carrot"])
+ assert len(producer) == 3
+
+
+def test_producer_column_indexes():
+ producer = RecordProducer(["apple", "banana", "carrot"])
+ assert producer.column_indexes == {"apple": 0, "banana": 1, "carrot": 2}
diff --git a/pool/shard009/Python/0086025_struct.py b/pool/shard009/Python/0086025_struct.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9da6e6c1c8aa7505e2dccb0473335da2979bab2
--- /dev/null
+++ b/pool/shard009/Python/0086025_struct.py
@@ -0,0 +1,72 @@
+from __future__ import absolute_import
+
+from io import BytesIO
+
+from kafka.protocol.abstract import AbstractType
+from kafka.protocol.types import Schema
+
+from kafka.util import WeakMethod
+
+
+class Struct(AbstractType):
+ SCHEMA = Schema()
+
+ def __init__(self, *args, **kwargs):
+ if len(args) == len(self.SCHEMA.fields):
+ for i, name in enumerate(self.SCHEMA.names):
+ self.__dict__[name] = args[i]
+ elif len(args) > 0:
+ raise ValueError('Args must be empty or mirror schema')
+ else:
+ for name in self.SCHEMA.names:
+ self.__dict__[name] = kwargs.pop(name, None)
+ if kwargs:
+ raise ValueError('Keyword(s) not in schema %s: %s'
+ % (list(self.SCHEMA.names),
+ ', '.join(kwargs.keys())))
+
+ # overloading encode() to support both class and instance
+ # Without WeakMethod() this creates circular ref, which
+ # causes instances to "leak" to garbage
+ self.encode = WeakMethod(self._encode_self)
+
+
+ @classmethod
+ def encode(cls, item): # pylint: disable=E0202
+ bits = []
+ for i, field in enumerate(cls.SCHEMA.fields):
+ bits.append(field.encode(item[i]))
+ return b''.join(bits)
+
+ def _encode_self(self):
+ return self.SCHEMA.encode(
+ [self.__dict__[name] for name in self.SCHEMA.names]
+ )
+
+ @classmethod
+ def decode(cls, data):
+ if isinstance(data, bytes):
+ data = BytesIO(data)
+ return cls(*[field.decode(data) for field in cls.SCHEMA.fields])
+
+ def get_item(self, name):
+ if name not in self.SCHEMA.names:
+ raise KeyError("%s is not in the schema" % name)
+ return self.__dict__[name]
+
+ def __repr__(self):
+ key_vals = []
+ for name, field in zip(self.SCHEMA.names, self.SCHEMA.fields):
+ key_vals.append('%s=%s' % (name, field.repr(self.__dict__[name])))
+ return self.__class__.__name__ + '(' + ', '.join(key_vals) + ')'
+
+ def __hash__(self):
+ return hash(self.encode())
+
+ def __eq__(self, other):
+ if self.SCHEMA != other.SCHEMA:
+ return False
+ for attr in self.SCHEMA.names:
+ if self.__dict__[attr] != other.__dict__[attr]:
+ return False
+ return True
diff --git a/pool/shard009/Python/0086026_joomoowebsites.py b/pool/shard009/Python/0086026_joomoowebsites.py
new file mode 100644
index 0000000000000000000000000000000000000000..efd66ce2839e7c15dd24fc35ed1e1f92b1986cd6
--- /dev/null
+++ b/pool/shard009/Python/0086026_joomoowebsites.py
@@ -0,0 +1,120 @@
+""" Ye olde hello world sanity check, using only the base template.
+
+Purpose: ensure we can process the request to render a simple template
+Author: Tom W. Hartung
+Date: Winter, 2017
+Copyright: (c) 2017 Tom W. Hartung, Groja.com, and JooMoo Websites LLC.
+Reference:
+ Chapter 3 of the "Flask Web Development" book (M.Grinberg 2014)
+Usage:
+ bin/hello-run.sh
+"""
+
+from flask import Flask, render_template
+from flask_bootstrap import Bootstrap
+
+app = Flask(__name__)
+Bootstrap(app)
+
+
+@app.route('/')
+@app.route('/home')
+def home():
+
+ """ Render the home.html template """
+
+ return render_template('home.html', home_active='is-active')
+
+
+@app.route('/about')
+def about():
+
+ """ Render the about.html template """
+
+ #include_deleted_blah_blah = True
+ include_deleted_blah_blah = False
+
+ return render_template(
+ 'about.html',
+ about_active='is-active',
+ include_deleted_blah_blah=include_deleted_blah_blah
+ )
+
+
+@app.route('/blog')
+def blog():
+
+ """ Render the blog.html template """
+
+ return render_template('blog.html', blog_active='is-active')
+
+
+@app.route('/portfolio')
+def portfolio():
+
+ """ Render the portfolio.html template """
+
+ return render_template('portfolio.html', portfolio_active='is-active')
+
+
+@app.route("/legal/")
+def legal(legal_page):
+
+ """ Display the requested legal page, defaulting to the terms_of_service """
+
+ if legal_page == 'privacy_policy':
+ template_name = 'legal/privacy_policy.html'
+ elif legal_page == 'terms_of_service':
+ template_name = 'legal/terms_of_service.html'
+ elif legal_page == 'affiliate_marketing_disclosure':
+ template_name = 'legal/affiliate_marketing_disclosure.html'
+ else:
+ template_name = 'legal/terms_of_service.html'
+
+ return render_template(template_name, legal_active='is-active')
+
+
+@app.route('/index')
+def index():
+
+ """ Render the index.html template """
+
+ return render_template('index.html')
+
+
+@app.route('/v')
+def versions():
+ """ Show the versions.html template to see what versions we are using """
+
+ import platform
+ python_version = platform.python_version()
+ import flask
+ flask_version = flask.__version__
+
+ template_name = 'versions.html'
+ return render_template(
+ template_name,
+ python_version=python_version,
+ flask_version=flask_version
+ )
+
+
+@app.errorhandler(404)
+def page_not_found(e):
+
+ """
+ Handle 404 errors by showing the 404.html template
+ Found this code here:
+ http://flask.pocoo.org/docs/0.12/patterns/errorpages/
+ """
+
+ return render_template('404.html'), 404
+
+
+# =============================================================================
+
+#
+# Run the app!
+#
+if __name__ == '__main__':
+ app.run(debug=True)
diff --git a/pool/shard009/Python/0086050_average_groups.py b/pool/shard009/Python/0086050_average_groups.py
new file mode 100644
index 0000000000000000000000000000000000000000..30396e4f0c9ec65812dbe2a9dd304777f7c94f76
--- /dev/null
+++ b/pool/shard009/Python/0086050_average_groups.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+import sys
+import os.path as op
+import csv
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+from analyses.logs import read_logs
+from groups import read_group_info, map_group_names, get_datasets_of_group
+
+def save_fig(fig, filename, suffixes):
+ if isinstance(suffixes, type('')):
+ suffixes = [suffixes]
+
+ for suffix in suffixes:
+ fig.savefig(filename + suffix, dpi=300)
+
+args = sys.argv[1:]
+
+same_shapes = len(args) == 2
+
+if same_shapes:
+ loc_range = [50, 150]
+
+else:
+ loc_range = [0, 180]
+
+dirname, logname = op.split(args[0])
+log = read_logs(dirname, logname)[0]
+
+prefix = op.splitext(logname)[0]
+
+all_params = np.array(log.get_value('params'))
+all_dir_bases = np.array([ii.dir_base for ii in log.items])
+
+all_chi_p = np.array(log.get_value('chisquare(e) p-value'))
+all_aic = np.array(log.get_value('aic'))
+all_bic = np.array(log.get_value('bic'))
+
+group_info = read_group_info()
+gmap = map_group_names(group_info)
+
+group_names = ['age_group', 'pig_group', 'segment']
+
+suffix = ['.png', '.pdf']
+
+rows = []
+for group_name in group_names:
+ print group_name
+ for val in np.unique(group_info[group_name]):
+ dir_bases = get_datasets_of_group(group_info, group_name, val)
+ ix = np.array([ii for ii in range(all_params.shape[0])
+ if log.items[ii].dir_base in dir_bases])
+ print ' ', val, len(dir_bases), len(ix)
+
+ if not len(ix): continue
+
+ params = all_params[ix]
+ dir_bases = all_dir_bases[ix]
+
+ chi_p = all_chi_p[ix]
+ aic = all_aic[ix]
+ bic = all_bic[ix]
+
+ locs = params[:, :2, 0]
+ shapes = params[:, :2, 1]
+ probs = params[:, :2, 2]
+
+ if same_shapes:
+ assert((shapes[:, 0] == shapes[:, 1]).all())
+ assert((probs[:, 0] == probs[:, 1]).all())
+
+ # Sort by locations.
+ ic = locs.argsort(axis=1)
+ ir = np.arange(len(ix))[:, None]
+ locs = locs[ir, ic]
+
+ if not same_shapes:
+ shapes = shapes[ir, ic]
+ probs = probs[ir, ic]
+
+ for ir, dir_base in enumerate(dir_bases):
+ rows.append([group_name, val, dir_base,
+ chi_p[ir], aic[ir], bic[ir]] + locs[ir].tolist()
+ + [shapes[ir, 0], probs[ir, 0]])
+
+ fig = plt.figure(1)
+ ax0 = plt.subplot2grid((1, 4 + 2 * (not same_shapes)),
+ (0, 0), colspan=2)
+ ax0.boxplot([locs[:, 0], locs[:, 1]])
+
+ if same_shapes:
+ ax1 = plt.subplot2grid((1, 4), (0, 2), colspan=1)
+ ax2 = plt.subplot2grid((1, 4), (0, 3), colspan=1)
+
+ ax1.boxplot([shapes[:, 0]])
+ ax2.boxplot([probs[:, 0]])
+
+ else:
+ ax1 = plt.subplot2grid((1, 6), (0, 2), colspan=2)
+ ax2 = plt.subplot2grid((1, 6), (0, 4), colspan=2)
+
+ ax1.boxplot([shapes[:, 0], shapes[:, 1]])
+ ax2.boxplot([probs[:, 0], probs[:, 1]])
+
+ ax0.set_ylim(*loc_range)
+ ax1.set_ylim(0, 10)
+ ax2.set_ylim(0, 1)
+
+ ax0.set_ylabel(r'$\mu$')
+ ax1.set_ylabel(r'$\kappa$')
+ ax2.set_ylabel('prob.')
+
+ plt.tight_layout(pad=0.5)
+
+ esuffix = '%s_%s' % (group_name, val)
+ save_fig(fig, op.join(dirname, prefix + '_group_' + esuffix), suffix)
+ plt.close(fig)
+
+with open(op.join(dirname, 'groups.csv'), 'w') as fd:
+ fd.write('group name, group value, dataset, chisquare(e) p-value,'
+ ' aic, bic, mu0, mu1, kappa, prob\n')
+
+ writer = csv.writer(fd)
+ for row in rows:
+ writer.writerow(row)
diff --git a/pool/shard009/Python/0086060_oonibackend.py b/pool/shard009/Python/0086060_oonibackend.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6654b859ed4b7942bf08e9498800cd03784bbc0
--- /dev/null
+++ b/pool/shard009/Python/0086060_oonibackend.py
@@ -0,0 +1,74 @@
+# ooni backend
+# ************
+#
+# This is the backend system responsible for running certain services that are
+# useful for censorship detection.
+#
+# In here we start all the test helpers that are required by ooniprobe and
+# start the report collector
+
+from twisted.application import internet
+from twisted.internet import reactor
+from twisted.application import internet, service
+from twisted.application.service import Application
+from twisted.names import dns
+
+from cyclone import web
+
+from oonib.testhelpers import dns_helpers, ssl_helpers
+from oonib.testhelpers import http_helpers, tcp_helpers
+
+from oonib import log
+
+from oonib.config import config
+
+if config.main.uid and config.main.gid:
+ application = service.Application('oonibackend', uid=config.main.uid,
+ gid=config.main.gid)
+else:
+ application = service.Application('oonibackend')
+
+serviceCollection = service.IServiceCollection(application)
+
+if config.helpers['ssl'].port:
+ print "Starting SSL helper on %s" % config.helpers['ssl'].port
+ ssl_helper = internet.SSLServer(int(config.helpers['ssl'].port),
+ http_helpers.HTTPReturnJSONHeadersHelper(),
+ ssl_helpers.SSLContext(config))
+ ssl_helper.setServiceParent(serviceCollection)
+
+# Start the DNS Server related services
+if config.helpers['dns'].tcp_port:
+ print "Starting TCP DNS Helper on %s" % config.helpers['dns'].tcp_port
+ tcp_dns_helper = internet.TCPServer(int(config.helpers['dns'].tcp_port),
+ dns_helpers.DNSTestHelper())
+ tcp_dns_helper.setServiceParent(serviceCollection)
+
+if config.helpers['dns'].udp_port:
+ print "Starting UDP DNS Helper on %s" % config.helpers['dns'].udp_port
+ udp_dns_factory = dns.DNSDatagramProtocol(dns_helpers.DNSTestHelper())
+ udp_dns_helper = internet.UDPServer(int(config.helpers['dns'].udp_port),
+ udp_dns_factory)
+ udp_dns_helper.setServiceParent(serviceCollection)
+
+# XXX this needs to be ported
+# Start the OONI daphn3 backend
+if config.helpers['daphn3'].port:
+ print "Starting Daphn3 helper on %s" % config.helpers['daphn3'].port
+ daphn3_helper = internet.TCPServer(int(config.helpers['daphn3'].port),
+ tcp_helpers.Daphn3Server())
+ daphn3_helper.setServiceParent(serviceCollection)
+
+
+if config.helpers['tcp-echo'].port:
+ print "Starting TCP echo helper on %s" % config.helpers['tcp-echo'].port
+ tcp_echo_helper = internet.TCPServer(int(config.helpers['tcp-echo'].port),
+ tcp_helpers.TCPEchoHelper())
+ tcp_echo_helper.setServiceParent(serviceCollection)
+
+if config.helpers['http-return-json-headers'].port:
+ print "Starting HTTP return request helper on %s" % config.helpers['http-return-json-headers'].port
+ http_return_request_helper = internet.TCPServer(
+ int(config.helpers['http-return-json-headers'].port),
+ http_helpers.HTTPReturnJSONHeadersHelper())
+ http_return_request_helper.setServiceParent(serviceCollection)
diff --git a/pool/shard009/Python/0086061_validate_json_format.py b/pool/shard009/Python/0086061_validate_json_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d63117f957ce0c6d707bc7f602750161a79eeee
--- /dev/null
+++ b/pool/shard009/Python/0086061_validate_json_format.py
@@ -0,0 +1,231 @@
+"""
+Validate JSON format.
+
+Licensed under MIT
+Copyright (c) 2012-2015 Isaac Muse
+"""
+import re
+import codecs
+import json
+
+RE_LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE)
+RE_COMMENT = re.compile(
+ r'''(?x)
+ (?P
+ /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments
+ | [ \t]*//(?:[^\r\n])* # single line comments
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quotes
+ | .[^/"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+RE_TRAILING_COMMA = re.compile(
+ r'''(?x)
+ (
+ (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\]) # bracket
+ )
+ | (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\}) # bracket
+ )
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quoted string
+ | .[^,"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+RE_LINE_INDENT_TAB = re.compile(r'^(?:(\t+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$')
+RE_LINE_INDENT_SPACE = re.compile(r'^(?:((?: {4})+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$')
+RE_TRAILING_SPACES = re.compile(r'^.*?[ \t]+\r?\n?$')
+RE_COMMENT_END = re.compile(r'\*/')
+PATTERN_COMMENT_INDENT_SPACE = r'^(%s *?[^\t\r\n][^\r\n]*)?\r?\n$'
+PATTERN_COMMENT_INDENT_TAB = r'^(%s[ \t]*[^ \t\r\n][^\r\n]*)?\r?\n$'
+
+
+E_MALFORMED = "E0"
+E_COMMENTS = "E1"
+E_COMMA = "E2"
+W_NL_START = "W1"
+W_NL_END = "W2"
+W_INDENT = "W3"
+W_TRAILING_SPACE = "W4"
+W_COMMENT_INDENT = "W5"
+
+
+VIOLATION_MSG = {
+ E_MALFORMED: 'JSON content is malformed.',
+ E_COMMENTS: 'Comments are not part of the JSON spec.',
+ E_COMMA: 'Dangling comma found.',
+ W_NL_START: 'Unnecessary newlines at the start of file.',
+ W_NL_END: 'Missing a new line at the end of the file.',
+ W_INDENT: 'Indentation Error.',
+ W_TRAILING_SPACE: 'Trailing whitespace.',
+ W_COMMENT_INDENT: 'Comment Indentation Error.'
+}
+
+
+class CheckJsonFormat(object):
+ """
+ Test JSON for format irregularities.
+
+ - Trailing spaces.
+ - Inconsistent indentation.
+ - New lines at end of file.
+ - Unnecessary newlines at start of file.
+ - Trailing commas.
+ - Malformed JSON.
+ """
+
+ def __init__(self, use_tabs=False, allow_comments=False):
+ """Setup the settings."""
+
+ self.use_tabs = use_tabs
+ self.allow_comments = allow_comments
+ self.fail = False
+
+ def index_lines(self, text):
+ """Index the char range of each line."""
+
+ self.line_range = []
+ count = 1
+ last = 0
+ for m in re.finditer('\n', text):
+ self.line_range.append((last, m.end(0) - 1, count))
+ last = m.end(0)
+ count += 1
+
+ def get_line(self, pt):
+ """Get the line from char index."""
+
+ line = None
+ for r in self.line_range:
+ if pt >= r[0] and pt <= r[1]:
+ line = r[2]
+ break
+ return line
+
+ def check_comments(self, text):
+ """
+ Check for JavaScript comments.
+
+ Log them and strip them out so we can continue.
+ """
+
+ def remove_comments(group):
+ return ''.join([x[0] for x in RE_LINE_PRESERVE.findall(group)])
+
+ def evaluate(m):
+ text = ''
+ g = m.groupdict()
+ if g["code"] is None:
+ if not self.allow_comments:
+ self.log_failure(E_COMMENTS, self.get_line(m.start(0)))
+ text = remove_comments(g["comments"])
+ else:
+ text = g["code"]
+ return text
+
+ content = ''.join(map(lambda m: evaluate(m), RE_COMMENT.finditer(text)))
+ return content
+
+ def check_dangling_commas(self, text):
+ """
+ Check for dangling commas.
+
+ Log them and strip them out so we can continue.
+ """
+
+ def check_comma(g, m, line):
+ # ,] -> ] or ,} -> }
+ self.log_failure(E_COMMA, line)
+ if g["square_comma"] is not None:
+ return g["square_ws"] + g["square_bracket"]
+ else:
+ return g["curly_ws"] + g["curly_bracket"]
+
+ def evaluate(m):
+ g = m.groupdict()
+ return check_comma(g, m, self.get_line(m.start(0))) if g["code"] is None else g["code"]
+
+ return ''.join(map(lambda m: evaluate(m), RE_TRAILING_COMMA.finditer(text)))
+
+ def log_failure(self, code, line=None):
+ """
+ Log failure.
+
+ Log failure code, line number (if available) and message.
+ """
+
+ if line:
+ print("%s: Line %d - %s" % (code, line, VIOLATION_MSG[code]))
+ else:
+ print("%s: %s" % (code, VIOLATION_MSG[code]))
+ self.fail = True
+
+ def check_format(self, file_name):
+ """Initiate the check."""
+
+ self.fail = False
+ comment_align = None
+ with codecs.open(file_name, encoding='utf-8') as f:
+ count = 1
+ for line in f:
+ indent_match = (RE_LINE_INDENT_TAB if self.use_tabs else RE_LINE_INDENT_SPACE).match(line)
+ end_comment = (
+ (comment_align is not None or (indent_match and indent_match.group(2))) and
+ RE_COMMENT_END.search(line)
+ )
+ # Don't allow empty lines at file start.
+ if count == 1 and line.strip() == '':
+ self.log_failure(W_NL_START, count)
+ # Line must end in new line
+ if not line.endswith('\n'):
+ self.log_failure(W_NL_END, count)
+ # Trailing spaces
+ if RE_TRAILING_SPACES.match(line):
+ self.log_failure(W_TRAILING_SPACE, count)
+ # Handle block comment content indentation
+ if comment_align is not None:
+ if comment_align.match(line) is None:
+ self.log_failure(W_COMMENT_INDENT, count)
+ if end_comment:
+ comment_align = None
+ # Handle general indentation
+ elif indent_match is None:
+ self.log_failure(W_INDENT, count)
+ # Enter into block comment
+ elif comment_align is None and indent_match.group(2):
+ alignment = indent_match.group(1) if indent_match.group(1) is not None else ""
+ if not end_comment:
+ comment_align = re.compile(
+ (PATTERN_COMMENT_INDENT_TAB if self.use_tabs else PATTERN_COMMENT_INDENT_SPACE) % alignment
+ )
+ count += 1
+ f.seek(0)
+ text = f.read()
+
+ self.index_lines(text)
+ text = self.check_comments(text)
+ self.index_lines(text)
+ text = self.check_dangling_commas(text)
+ try:
+ json.loads(text)
+ except Exception as e:
+ self.log_failure(E_MALFORMED)
+ print(e)
+ return self.fail
+
+
+if __name__ == "__main__":
+ import sys
+ cjf = CheckJsonFormat(False, True)
+ cjf.check_format(sys.argv[1])
diff --git a/pool/shard009/Python/0086073_fixture_tables.py b/pool/shard009/Python/0086073_fixture_tables.py
new file mode 100644
index 0000000000000000000000000000000000000000..7865e90b19126859f20b98188933b61d7a773c9c
--- /dev/null
+++ b/pool/shard009/Python/0086073_fixture_tables.py
@@ -0,0 +1,155 @@
+"""A copy of Django 1.3.0's stock loaddata.py, adapted so that, instead of
+loading any data, it returns the tables referenced by a set of fixtures so we
+can truncate them (and no others) quickly after we're finished with them."""
+
+import os
+import gzip
+import zipfile
+from itertools import product
+
+from django.conf import settings
+from django.core import serializers
+from django.db import router, DEFAULT_DB_ALIAS
+from django.db.models import get_apps
+
+try:
+ import bz2
+ has_bz2 = True
+except ImportError:
+ has_bz2 = False
+
+
+def tables_used_by_fixtures(fixture_labels, using=DEFAULT_DB_ALIAS):
+ """Act like Django's stock loaddata command, but, instead of loading data,
+ return an iterable of the names of the tables into which data would be
+ loaded."""
+ # Keep a count of the installed objects and fixtures
+ fixture_count = 0
+ loaded_object_count = 0
+ fixture_object_count = 0
+ tables = set()
+
+ class SingleZipReader(zipfile.ZipFile):
+ def __init__(self, *args, **kwargs):
+ zipfile.ZipFile.__init__(self, *args, **kwargs)
+ if settings.DEBUG:
+ assert len(self.namelist()) == 1, "Zip-compressed fixtures must contain only one file."
+ def read(self):
+ return zipfile.ZipFile.read(self, self.namelist()[0])
+
+ compression_types = {
+ None: file,
+ 'gz': gzip.GzipFile,
+ 'zip': SingleZipReader
+ }
+ if has_bz2:
+ compression_types['bz2'] = bz2.BZ2File
+
+ app_module_paths = []
+ for app in get_apps():
+ if hasattr(app, '__path__'):
+ # It's a 'models/' subpackage
+ for path in app.__path__:
+ app_module_paths.append(path)
+ else:
+ # It's a models.py module
+ app_module_paths.append(app.__file__)
+
+ app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
+ for fixture_label in fixture_labels:
+ parts = fixture_label.split('.')
+
+ if len(parts) > 1 and parts[-1] in compression_types:
+ compression_formats = [parts[-1]]
+ parts = parts[:-1]
+ else:
+ compression_formats = list(compression_types.keys())
+
+ if len(parts) == 1:
+ fixture_name = parts[0]
+ formats = serializers.get_public_serializer_formats()
+ else:
+ fixture_name, format = '.'.join(parts[:-1]), parts[-1]
+ if format in serializers.get_public_serializer_formats():
+ formats = [format]
+ else:
+ formats = []
+
+ if not formats:
+ # stderr.write(style.ERROR("Problem installing fixture '%s': %s is
+ # not a known serialization format.\n" % (fixture_name, format)))
+ return set()
+
+ if os.path.isabs(fixture_name):
+ fixture_dirs = [fixture_name]
+ else:
+ fixture_dirs = app_fixtures + list(settings.FIXTURE_DIRS) + ['']
+
+ for fixture_dir in fixture_dirs:
+ # stdout.write("Checking %s for fixtures...\n" %
+ # humanize(fixture_dir))
+
+ label_found = False
+ for combo in product([using, None], formats, compression_formats):
+ database, format, compression_format = combo
+ file_name = '.'.join(
+ p for p in [
+ fixture_name, database, format, compression_format
+ ]
+ if p
+ )
+
+ # stdout.write("Trying %s for %s fixture '%s'...\n" % \
+ # (humanize(fixture_dir), file_name, fixture_name))
+ full_path = os.path.join(fixture_dir, file_name)
+ open_method = compression_types[compression_format]
+ try:
+ fixture = open_method(full_path, 'r')
+ if label_found:
+ fixture.close()
+ # stderr.write(style.ERROR("Multiple fixtures named
+ # '%s' in %s. Aborting.\n" % (fixture_name,
+ # humanize(fixture_dir))))
+ return set()
+ else:
+ fixture_count += 1
+ objects_in_fixture = 0
+ loaded_objects_in_fixture = 0
+ # stdout.write("Installing %s fixture '%s' from %s.\n"
+ # % (format, fixture_name, humanize(fixture_dir)))
+ try:
+ objects = serializers.deserialize(format, fixture, using=using)
+ for obj in objects:
+ objects_in_fixture += 1
+ if router.allow_syncdb(using, obj.object.__class__):
+ loaded_objects_in_fixture += 1
+ tables.add(
+ obj.object.__class__._meta.db_table)
+ loaded_object_count += loaded_objects_in_fixture
+ fixture_object_count += objects_in_fixture
+ label_found = True
+ except (SystemExit, KeyboardInterrupt):
+ raise
+ except Exception:
+ fixture.close()
+ # stderr.write( style.ERROR("Problem installing
+ # fixture '%s': %s\n" % (full_path, ''.join(tra
+ # ceback.format_exception(sys.exc_type,
+ # sys.exc_value, sys.exc_traceback)))))
+ return set()
+ fixture.close()
+
+ # If the fixture we loaded contains 0 objects, assume that an
+ # error was encountered during fixture loading.
+ if objects_in_fixture == 0:
+ # stderr.write( style.ERROR("No fixture data found
+ # for '%s'. (File format may be invalid.)\n" %
+ # (fixture_name)))
+ return set()
+
+ except Exception:
+ # stdout.write("No %s fixture '%s' in %s.\n" % \ (format,
+ # fixture_name, humanize(fixture_dir)))
+ pass
+
+ return tables
diff --git a/pool/shard009/Python/0086075_cmakefile_editor.py b/pool/shard009/Python/0086075_cmakefile_editor.py
new file mode 100644
index 0000000000000000000000000000000000000000..d57c650c5e98018ceca83fdbbf9008ad906b178f
--- /dev/null
+++ b/pool/shard009/Python/0086075_cmakefile_editor.py
@@ -0,0 +1,143 @@
+#
+# Copyright 2013 Free Software Foundation, Inc.
+#
+# This file is part of GNU Radio
+#
+# GNU Radio 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, or (at your option)
+# any later version.
+#
+# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#
+""" Edit CMakeLists.txt files """
+
+import re
+
+class CMakeFileEditor(object):
+ """A tool for editing CMakeLists.txt files. """
+ def __init__(self, filename, separator='\n ', indent=' '):
+ self.filename = filename
+ self.cfile = open(filename, 'r').read()
+ self.separator = separator
+ self.indent = indent
+
+ def append_value(self, entry, value, to_ignore_start='', to_ignore_end=''):
+ """ Add a value to an entry. """
+ regexp = re.compile('(%s\(%s[^()]*?)\s*?(\s?%s)\)' % (entry, to_ignore_start, to_ignore_end),
+ re.MULTILINE)
+ substi = r'\1' + self.separator + value + r'\2)'
+ (self.cfile, nsubs) = regexp.subn(substi, self.cfile, count=1)
+ return nsubs
+
+ def remove_value(self, entry, value, to_ignore_start='', to_ignore_end=''):
+ """
+ Remove a value from an entry.
+ Example: You want to remove file.cc from this list() entry:
+ list(SOURCES
+ file.cc
+ other_file.cc
+ )
+
+ Then run:
+ >>> C.remove_value('list', 'file.cc', 'SOURCES')
+
+ Returns the number of occurences of entry in the current file
+ that were removed.
+ """
+ # In the case of the example above, these are cases we need to catch:
+ # - list(file.cc ...
+ # entry is right after the value parentheses, no whitespace. Can only happen
+ # when to_ignore_start is empty.
+ # - list(... file.cc)
+ # Other entries come first, then entry is preceded by whitespace.
+ # - list(SOURCES ... file.cc) # whitespace!
+ # When to_ignore_start is not empty, entry must always be preceded by whitespace.
+ if len(to_ignore_start) == 0:
+ regexp = r'^\s*({entry}\((?:[^()]*?\s+|)){value}\s*([^()]*{to_ignore_end}\s*\)){to_ignore_start}'
+ else:
+ regexp = r'^\s*({entry}\(\s*{to_ignore_start}[^()]*?\s+){value}\s*([^()]*{to_ignore_end}\s*\))'
+ regexp = regexp.format(
+ entry=entry,
+ to_ignore_start=to_ignore_start,
+ value=value,
+ to_ignore_end=to_ignore_end,
+ )
+ regexp = re.compile(regexp, re.MULTILINE)
+ (self.cfile, nsubs) = re.subn(regexp, r'\1\2', self.cfile, count=1)
+ return nsubs
+
+ def delete_entry(self, entry, value_pattern=''):
+ """Remove an entry from the current buffer."""
+ regexp = '%s\s*\([^()]*%s[^()]*\)[^\n]*\n' % (entry, value_pattern)
+ regexp = re.compile(regexp, re.MULTILINE)
+ (self.cfile, nsubs) = re.subn(regexp, '', self.cfile, count=1)
+ return nsubs
+
+ def write(self):
+ """ Write the changes back to the file. """
+ open(self.filename, 'w').write(self.cfile)
+
+ def remove_double_newlines(self):
+ """Simply clear double newlines from the file buffer."""
+ self.cfile = re.compile('\n\n\n+', re.MULTILINE).sub('\n\n', self.cfile)
+
+ def find_filenames_match(self, regex):
+ """ Find the filenames that match a certain regex
+ on lines that aren't comments """
+ filenames = []
+ reg = re.compile(regex)
+ fname_re = re.compile('[a-zA-Z]\w+\.\w{1,5}$')
+ for line in self.cfile.splitlines():
+ if len(line.strip()) == 0 or line.strip()[0] == '#':
+ continue
+ for word in re.split('[ /)(\t\n\r\f\v]', line):
+ if fname_re.match(word) and reg.search(word):
+ filenames.append(word)
+ return filenames
+
+ def disable_file(self, fname):
+ """ Comment out a file.
+ Example:
+ add_library(
+ file1.cc
+ )
+
+ Here, file1.cc becomes #file1.cc with disable_file('file1.cc').
+ """
+ starts_line = False
+ for line in self.cfile.splitlines():
+ if len(line.strip()) == 0 or line.strip()[0] == '#':
+ continue
+ if re.search(r'\b'+fname+r'\b', line):
+ if re.match(fname, line.lstrip()):
+ starts_line = True
+ break
+ comment_out_re = r'#\1' + '\n' + self.indent
+ if not starts_line:
+ comment_out_re = r'\n' + self.indent + comment_out_re
+ (self.cfile, nsubs) = re.subn(r'(\b'+fname+r'\b)\s*', comment_out_re, self.cfile)
+ if nsubs == 0:
+ print "Warning: A replacement failed when commenting out %s. Check the CMakeFile.txt manually." % fname
+ elif nsubs > 1:
+ print "Warning: Replaced %s %d times (instead of once). Check the CMakeFile.txt manually." % (fname, nsubs)
+
+ def comment_out_lines(self, pattern, comment_str='#'):
+ """ Comments out all lines that match with pattern """
+ for line in self.cfile.splitlines():
+ if re.search(pattern, line):
+ self.cfile = self.cfile.replace(line, comment_str+line)
+
+ def check_for_glob(self, globstr):
+ """ Returns true if a glob as in globstr is found in the cmake file """
+ glob_re = r'GLOB\s[a-z_]+\s"%s"' % globstr.replace('*', '\*')
+ return re.search(glob_re, self.cfile, flags=re.MULTILINE|re.IGNORECASE) is not None
+
diff --git a/pool/shard009/Python/0086077_query.py b/pool/shard009/Python/0086077_query.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0b704946a7683c6c88c34b5d88cf366e294140d
--- /dev/null
+++ b/pool/shard009/Python/0086077_query.py
@@ -0,0 +1,162 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of Invenio.
+# Copyright (C) 2016 CERN.
+#
+# Invenio 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.
+#
+# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
+# 59 Temple Place, Suite 330, Boston, MA 02D111-1307, USA.
+
+"""Query parser."""
+
+import six
+from elasticsearch_dsl import Q
+from flask import current_app
+from invenio_search import RecordsSearch, current_search_client
+from werkzeug.utils import cached_property, import_string
+
+from . import current_oaiserver
+
+
+def query_string_parser(search_pattern):
+ """Elasticsearch query string parser."""
+ if not hasattr(current_oaiserver, 'query_parser'):
+ query_parser = current_app.config['OAISERVER_QUERY_PARSER']
+ if isinstance(query_parser, six.string_types):
+ query_parser = import_string(query_parser)
+ current_oaiserver.query_parser = query_parser
+ return current_oaiserver.query_parser('query_string', query=search_pattern)
+
+
+class OAIServerSearch(RecordsSearch):
+ """Define default filter for quering OAI server."""
+
+ class Meta:
+ """Configuration for OAI server search."""
+
+ default_filter = Q('exists', field='_oai.id')
+
+
+def get_affected_records(spec=None, search_pattern=None):
+ """Get list of affected records.
+
+ :param spec: The record spec.
+ :param search_pattern: The search pattern.
+ :returns: An iterator to lazily find results.
+ """
+ # spec pattern query
+ # ---------- ---------- -------
+ # None None None
+ # None Y Y
+ # X None X
+ # X '' X
+ # X Y X OR Y
+
+ if spec is None and search_pattern is None:
+ raise StopIteration
+
+ queries = []
+
+ if spec is not None:
+ queries.append(Q('match', **{'_oai.sets': spec}))
+
+ if search_pattern:
+ queries.append(query_string_parser(search_pattern=search_pattern))
+
+ search = OAIServerSearch(
+ index=current_app.config['OAISERVER_RECORD_INDEX'],
+ ).query(Q('bool', should=queries))
+
+ for result in search.scan():
+ yield result.meta.id
+
+
+def get_records(**kwargs):
+ """Get records paginated."""
+ page_ = kwargs.get('resumptionToken', {}).get('page', 1)
+ size_ = current_app.config['OAISERVER_PAGE_SIZE']
+ scroll = current_app.config['OAISERVER_RESUMPTION_TOKEN_EXPIRE_TIME']
+ scroll_id = kwargs.get('resumptionToken', {}).get('scroll_id')
+
+ if scroll_id is None:
+ search = OAIServerSearch(
+ index=current_app.config['OAISERVER_RECORD_INDEX'],
+ ).params(
+ scroll='{0}s'.format(scroll),
+ ).extra(
+ version=True,
+ )[(page_-1)*size_:page_*size_]
+
+ if 'set' in kwargs:
+ search = search.query('match', **{'_oai.sets': kwargs['set']})
+
+ time_range = {}
+ if 'from_' in kwargs:
+ time_range['gte'] = kwargs['from_']
+ if 'until' in kwargs:
+ time_range['lte'] = kwargs['until']
+ if time_range:
+ search = search.filter('range', **{'_updated': time_range})
+
+ response = search.execute().to_dict()
+ else:
+ response = current_search_client.scroll(
+ scroll_id=scroll_id,
+ scroll='{0}s'.format(scroll),
+ )
+
+ class Pagination(object):
+ """Dummy pagination class."""
+
+ page = page_
+ per_page = size_
+
+ def __init__(self, response):
+ """Initilize pagination."""
+ self.response = response
+ self.total = response['hits']['total']
+ self._scroll_id = response.get('_scroll_id')
+
+ # clean descriptor on last page
+ if not self.has_next:
+ current_search_client.clear_scroll(
+ scroll_id=self._scroll_id
+ )
+ self._scroll_id = None
+
+ @cached_property
+ def has_next(self):
+ """Return True if there is next page."""
+ return self.page * self.per_page <= self.total
+
+ @cached_property
+ def next_num(self):
+ """Return next page number."""
+ return self.page + 1 if self.has_next else None
+
+ @property
+ def items(self):
+ """Return iterator."""
+ from datetime import datetime
+ for result in self.response['hits']['hits']:
+ if '_oai' in result['_source']:
+ yield {
+ 'id': result['_id'],
+ 'json': result,
+ 'updated': datetime.strptime(
+ result['_source']['_updated'][:19],
+ '%Y-%m-%dT%H:%M:%S'
+ ),
+ }
+
+ return Pagination(response)
diff --git a/pool/shard009/Python/0086081_systemhost.py b/pool/shard009/Python/0086081_systemhost.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b4439ee4785bdc220ee72333179268499ad12a3
--- /dev/null
+++ b/pool/shard009/Python/0086081_systemhost.py
@@ -0,0 +1,45 @@
+# Copyright (c) 2011 Google Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import os
+import platform
+import sys
+
+from webkitpy.common.system import environment, executive, filesystem, platforminfo, user, workspace
+
+
+class SystemHost(object):
+ def __init__(self):
+ self.executive = executive.Executive()
+ self.filesystem = filesystem.FileSystem()
+ self.user = user.User()
+ self.platform = platforminfo.PlatformInfo(sys, platform, self.executive)
+ self.workspace = workspace.Workspace(self.filesystem, self.executive)
+
+ def copy_current_environment(self):
+ return environment.Environment(os.environ.copy())
diff --git a/pool/shard009/Python/0086092_morocco_set_notdata_value.py b/pool/shard009/Python/0086092_morocco_set_notdata_value.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3ea3c4a52ba75a20489e40b45f4540e8a0a7610
--- /dev/null
+++ b/pool/shard009/Python/0086092_morocco_set_notdata_value.py
@@ -0,0 +1,34 @@
+import os
+import glob
+from pgeo.utils.filesystem import get_filename
+import shutil
+import subprocess
+
+def process(input_folder, output_folder):
+
+ # create the folder
+ if os.path.isdir(output_folder):
+ shutil.rmtree(output_folder)
+ os.mkdir(output_folder)
+
+ try:
+ input_files = glob.glob(input_folder +"/*.tif")
+ for input_file in input_files:
+ output_filename = output_folder + "/" + get_filename(input_file) + ".tif"
+ #gdal_calc.py -A wheat_seasonal_act_biomprod_doukkala_mask.tif -B asd --outfile=processed.tif --calc="B*A" --NoDataValue=0
+ cmd = 'gdalwarp ' + input_file + ' ' + output_filename
+ print cmd
+ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
+ output, error = process.communicate()
+ print output
+ print error
+
+ except Exception, e:
+ print e
+ pass
+
+
+input_folder = "/home/vortex/Desktop/LAYERS/MOROCCO_MICHELA/to_publish/3857/meteo/ndvi/original_different_size_with_precipitation"
+output_folder = input_folder + "clipped"
+
+process(input_folder, output_folder)
\ No newline at end of file
diff --git a/pool/shard009/Python/0086099_heterodyne_scan.py b/pool/shard009/Python/0086099_heterodyne_scan.py
new file mode 100644
index 0000000000000000000000000000000000000000..d796eb60f1108bce20d2a69173e4b9cbc8a7a544
--- /dev/null
+++ b/pool/shard009/Python/0086099_heterodyne_scan.py
@@ -0,0 +1,52 @@
+import numpy as np
+import time
+import kid_readout.roach.heterodyne
+import kid_readout.utils.sweeps
+
+import kid_readout.utils.data_file
+
+import kid_readout.equipment.hittite_controller
+
+hc = kid_readout.equipment.hittite_controller.hittiteController(addr='192.168.0.200')
+
+hc.set_freq(12.95833e9)
+hc.on()
+hc.set_power(0)
+
+
+
+
+ri = kid_readout.roach.heterodyne.RoachHeterodyne(adc_valon='/dev/ttyUSB0')
+
+ri.initialize()#use_config=False)
+ri.iq_delay = 0
+
+ri.set_dac_atten(30)
+ri.set_fft_gain(4)
+
+nsamp = 2**16
+step = 1
+nstep = 128
+#f0binned = np.round(f0s * nsamp / 512.0) * 512.0 / nsamp
+offset_bins = np.arange(-(nstep), (nstep)) * step
+
+offsets = offset_bins * 512.0 / nsamp
+
+ri.set_modulation_output(7)
+
+ri.set_lo(1250.)
+frq = kid_readout.utils.sweeps.prepare_sweep(ri,np.arange(1,129)*7/4.+ri.lo_frequency,offsets,nsamp=nsamp)
+
+tic = time.time()
+for lo in 1010+190*np.arange(0,6):
+ print "lo:",lo
+ df = kid_readout.utils.data_file.DataFile(suffix='scan_lo_%.1f_MHz_mmw_modulated_7_7_turns' % lo)
+ df.nc.mmw_atten_turns = (7.,7.)
+ ri.set_lo(lo)
+ df.log_hw_state(ri)
+ df.log_adc_snap(ri)
+ swp = kid_readout.utils.sweeps.do_prepared_sweep(ri,nchan_per_step=32,reads_per_step=2)
+ df.add_sweep(swp)
+ df.close()
+ print "elapsed:", (time.time()-tic)/60.0,'minutes'
+
diff --git a/pool/shard009/Python/0086100_twitter_streamer.py b/pool/shard009/Python/0086100_twitter_streamer.py
new file mode 100644
index 0000000000000000000000000000000000000000..89de1335fa28aebea979c3e7bd8da0a701097393
--- /dev/null
+++ b/pool/shard009/Python/0086100_twitter_streamer.py
@@ -0,0 +1,90 @@
+from twython import TwythonStreamer
+from urllib import request
+import base64
+import os
+import subprocess
+"""
+скрипт слушает ленту пользователя, переданного через credentials.py,
+печатает в консоль дату и текст твита и результат обработки медиа.
+Обработка медиа заключается в том, что, если медиа есть,
+создаётся каталог с именем id твита, туда кладутся картинки с названиями,
+равными base64 от url источника картинки(так для каждой картинки),
+создаётся подкаталог с названием равным base64 от url прикреплённой к твиту ссылки,
+туда выкачивается полный вариант страницы, со структурой каталогов, соответствующей пути к странице в url
+(и так для каждой ссылки в твите).
+"""
+
+
+class SaverStreamer(TwythonStreamer):
+
+ def on_success(self, data):
+ if 'text' in data:
+ handleNewTweet(data)
+
+ def on_error(self, status_code, data):
+ print(status_code, data)
+
+try:
+ import Credentials
+except Exception:
+ Credentials = None
+
+printed_keys = ['created_at', 'text']
+
+
+def handleNewTweet(tweetData):
+
+ for key in printed_keys:
+ print(key, ': ', tweetData[key])
+ print('')
+ if 'entities' in tweetData:
+ entities = tweetData['entities']
+ tweetId = str(tweetData['id'])
+ if 'urls' in entities:
+ if len(entities['urls']) > 0:
+ print('Urls:')
+ for url_entry in entities['urls']:
+ url = url_entry['expanded_url']
+ try:
+ subprocess.call(['wget', '-q', '-p', '-k', '-P', tweetId + '/' +
+ base64.b64encode(bytes(url, "utf-8")).decode("ascii") + '/', url])
+ print('Url downloaded: ', url)
+ except:
+ print('Cannot download url: ', url)
+
+ if 'media' in entities:
+ if len(entities['media']) > 0:
+ print('Media:')
+ for media in entities['media']:
+ if media['type'] == 'photo':
+ media_url = media['media_url_https']
+ try:
+ if not os.path.exists(tweetId):
+ os.makedirs(tweetId)
+ request.urlretrieve(media_url,
+ tweetId + '/' +
+ base64.b64encode(
+ bytes(media_url, "utf-8")).decode("ascii")
+ + os.path.splitext(media_url)[-1])
+ print('Image downloaded: ', media_url)
+ except:
+ print('Cannot download: ', media_url)
+ print('\n\n')
+
+
+APP_KEY = ''
+APP_SECRET = ''
+OAUTH_TOKEN = ''
+OAUTH_TOKEN_SECRET = ''
+
+if Credentials is not None:
+ APP_KEY = Credentials.APP_KEY
+ APP_SECRET = Credentials.APP_SECRET
+ OAUTH_TOKEN = Credentials.OAUTH_TOKEN
+ OAUTH_TOKEN_SECRET = Credentials.OAUTH_TOKEN_SECRET
+
+ stream = SaverStreamer(
+ APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
+ stream.user(**{'with': 'user'})
+else:
+ print('No credentials – no tweets')
diff --git a/pool/shard009/Python/0086102_sqs.py b/pool/shard009/Python/0086102_sqs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c899d5d37004bfc638776d105a0d0c67bd54f132
--- /dev/null
+++ b/pool/shard009/Python/0086102_sqs.py
@@ -0,0 +1,204 @@
+import time
+import base64
+import pickle
+import asyncio
+import functools
+import aiobotocore
+from types import FunctionType
+from typing import Callable, Optional, Any, Union
+from .worker import BatchWorker
+from . import utils
+
+
+class SQSWriter:
+ service_name = "sqs"
+ MAX_RETRY = 10
+ sleep_base = 0.3
+
+ def __init__(
+ self,
+ queue_name: str,
+ region_name: Optional[str] = None,
+ encode_func: Optional[Callable] = None,
+ *,
+ worker_params: Optional[dict] = None,
+ client_params: Optional[dict] = None,
+ ):
+ self.session = aiobotocore.get_session()
+ self.queue_name = queue_name
+ self.is_fifo = queue_name.endswith(".fifo")
+ self.encode_func = encode_func or (
+ lambda o: base64.b64encode(pickle.dumps(o, 2)).decode("ascii")
+ )
+ self.client_params = client_params or {}
+ self.client_params["region_name"] = region_name
+ self.QueueUrl = None
+ self.lock = asyncio.Lock()
+ worker_params = worker_params or {}
+ worker_params.setdefault("name", "SQSWorker")
+ self.worker = BatchWorker(self.write_batch, **worker_params)
+
+ def __repr__(self):
+ return (
+ f"<{self.__class__.__name__}: "
+ f"queue={self.queue_name}, worker={self.worker!r}>"
+ )
+
+ def create_client(self):
+ return self.session.create_client(self.service_name, **self.client_params)
+
+ async def _get_queue_url(self) -> str:
+ if self.QueueUrl is None:
+ async with self.lock:
+ if self.QueueUrl is None:
+ async with self.create_client() as client:
+ resp = await client.get_queue_url(QueueName=self.queue_name)
+ self.QueueUrl = resp["QueueUrl"]
+ return self.QueueUrl
+
+ async def stop(self) -> None:
+ timestamp = time.time()
+ await self.worker.stop()
+ cost = time.time() - timestamp
+ await utils.info(f"{self!r} stopped in {cost:.1f} seconds")
+
+ def _encode(self, obj: Any) -> str:
+ return self.encode_func(obj)
+
+ async def write_one(
+ self,
+ record: Any,
+ delay_seconds: int = 0,
+ deduplication_id: Optional[str] = None,
+ group_id: Optional[str] = None,
+ queued: bool = False,
+ **attributes,
+ ):
+ message = {
+ "record": record,
+ "delay_seconds": delay_seconds,
+ "attributes": attributes,
+ "params": {},
+ }
+ if self.is_fifo:
+ if deduplication_id:
+ message["params"]["MessageDeduplicationId"] = deduplication_id
+ if group_id:
+ message["params"]["MessageGroupId"] = group_id
+ if queued:
+ await self.worker.put(message)
+ return
+ queue_url = await self._get_queue_url()
+ async with self.create_client() as client:
+ return await client.send_message(
+ QueueUrl=queue_url,
+ MessageBody=self._encode(record),
+ DelaySeconds=delay_seconds,
+ MessageAttributes=attributes,
+ **message["params"],
+ )
+
+ async def write_batch(self, obj_list: list) -> None:
+ Entries = [
+ {
+ "Id": str(i),
+ "MessageBody": self._encode(message["record"]),
+ "DelaySeconds": message["delay_seconds"],
+ "MessageAttributes": message["attributes"],
+ **message["params"],
+ }
+ for i, message in enumerate(obj_list)
+ ]
+ queue_url = await self._get_queue_url()
+ n = 0
+ async with self.create_client() as client:
+ while n < self.MAX_RETRY:
+ if n > 0:
+ await asyncio.sleep(self.sleep_base * (2 ** n))
+ try:
+ resp = await client.send_message_batch(
+ QueueUrl=queue_url, Entries=Entries
+ )
+ except Exception as e:
+ await utils.handle_exc(e)
+ n += 1
+ if n >= self.MAX_RETRY:
+ raise
+ continue
+ if "Failed" not in resp:
+ return
+ failed_ids = set(
+ d["Id"] for d in resp["Failed"] if not d["SenderFault"]
+ )
+ await utils.info(f"Send failed {n}: {failed_ids}, {resp['Failed']}")
+ Entries = [entry for entry in Entries if entry["Id"] in failed_ids]
+ n += 1
+ else:
+ raise Exception("write_batch error: SQS send_message_batch failed")
+
+ def async_rpc(
+ self,
+ func: Union[FunctionType, str, None] = None,
+ *,
+ delay_seconds: int = 0,
+ deduplication_id: Optional[str] = None,
+ group_id: Optional[str] = None,
+ queued: bool = True,
+ **attributes,
+ ) -> FunctionType:
+ if func is None:
+ return functools.partial(
+ self.async_rpc,
+ delay_seconds=delay_seconds,
+ deduplication_id=deduplication_id,
+ group_id=group_id,
+ queued=queued,
+ **attributes,
+ )
+ if type(func) == str:
+
+ async def async_func(*args, **kw):
+ record = {"fpath": func, "args": args, "kw": kw}
+ await self.write_one(
+ record,
+ delay_seconds=delay_seconds,
+ deduplication_id=deduplication_id,
+ group_id=group_id,
+ queued=queued,
+ **attributes,
+ )
+
+ else:
+
+ @functools.wraps(func)
+ async def async_func(*args, **kw):
+ fpath = func.__module__ + "." + func.__name__
+ record = {"fpath": fpath, "args": args, "kw": kw}
+ await self.write_one(
+ record,
+ delay_seconds=delay_seconds,
+ deduplication_id=deduplication_id,
+ group_id=group_id,
+ queued=queued,
+ **attributes,
+ )
+
+ return async_func
+
+
+class StringAttribute(dict):
+ def __init__(self, value: str):
+ self["DataType"] = "String"
+ self["StringValue"] = str(value)
+
+
+class BinaryAttribute(dict):
+ def __init__(self, value: bytes):
+ self["DataType"] = "Binary"
+ self["BinaryValue"] = bytes(value)
+
+
+class NumberAttribute(dict):
+ def __init__(self, value: str):
+ self["DataType"] = "Number"
+ self["StringValue"] = str(value)
diff --git a/pool/shard009/Python/0086104_tvtk_segmentation.py b/pool/shard009/Python/0086104_tvtk_segmentation.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f8d2cacf8b0cee7990d1449a7da609cb5ceecff
--- /dev/null
+++ b/pool/shard009/Python/0086104_tvtk_segmentation.py
@@ -0,0 +1,146 @@
+"""
+Using VTK to assemble a pipeline for segmenting MRI images. This example
+shows how to insert well-controled custom VTK filters in Mayavi.
+
+This example downloads an MRI scan, turns it into a 3D numpy array,
+applies a segmentation procedure made of VTK filters to extract the
+gray-matter/white-matter boundary.
+
+The segmentation algorithm used here is very naive and should, of course,
+not be used as an example of segmentation.
+
+"""
+
+### Download the data, if not already on disk ##################################
+import os
+if not os.path.exists('MRbrain.tar.gz'):
+ # Download the data
+ import urllib
+ print "Downloading data, Please Wait (7.8MB)"
+ opener = urllib.urlopen(
+ 'http://graphics.stanford.edu/data/voldata/MRbrain.tar.gz')
+ open('MRbrain.tar.gz', 'wb').write(opener.read())
+
+# Extract the data
+import tarfile
+tar_file = tarfile.open('MRbrain.tar.gz')
+try:
+ os.mkdir('mri_data')
+except:
+ pass
+tar_file.extractall('mri_data')
+tar_file.close()
+
+
+### Read the data in a numpy 3D array ##########################################
+import numpy as np
+data = np.array([np.fromfile(os.path.join('mri_data', 'MRbrain.%i' % i),
+ dtype='>u2') for i in range(1, 110)])
+data.shape = (109, 256, 256)
+data = data.T
+
+################################################################################
+# Heuristic for finding the threshold for the brain
+
+# Exctract the percentile 20 and 80 (without using
+# scipy.stats.scoreatpercentile)
+sorted_data = np.sort(data.ravel())
+l = len(sorted_data)
+lower_thr = sorted_data[0.2*l]
+upper_thr = sorted_data[0.8*l]
+
+# The white matter boundary: find the densest part of the upper half
+# of histogram, and take a value 10% higher, to cut _in_ the white matter
+hist, bins = np.histogram(data[data > np.mean(data)], bins=50)
+brain_thr_idx = np.argmax(hist)
+brain_thr = bins[brain_thr_idx + 4]
+
+del hist, bins, brain_thr_idx
+
+# Display the data #############################################################
+from mayavi import mlab
+from tvtk.api import tvtk
+
+fig = mlab.figure(bgcolor=(0, 0, 0), size=(400, 500))
+# to speed things up
+fig.scene.disable_render = True
+
+src = mlab.pipeline.scalar_field(data)
+# Our data is not equally spaced in all directions:
+src.spacing = [1, 1, 1.5]
+src.update_image_data = True
+
+#----------------------------------------------------------------------
+# Brain extraction pipeline
+
+# In the following, we create a Mayavi pipeline that strongly
+# relies on VTK filters. For this, we make heavy use of the
+# mlab.pipeline.user_defined function, to include VTK filters in
+# the Mayavi pipeline.
+
+# Apply image-based filters to clean up noise
+thresh_filter = tvtk.ImageThreshold()
+thresh_filter.threshold_between(lower_thr, upper_thr)
+thresh = mlab.pipeline.user_defined(src, filter=thresh_filter)
+
+median_filter = tvtk.ImageMedian3D()
+median_filter.set_kernel_size(3, 3, 3)
+median = mlab.pipeline.user_defined(thresh, filter=median_filter)
+
+diffuse_filter = tvtk.ImageAnisotropicDiffusion3D(
+ diffusion_factor=1.0,
+ diffusion_threshold=100.0,
+ number_of_iterations=5, )
+
+diffuse = mlab.pipeline.user_defined(median, filter=diffuse_filter)
+
+# Extract brain surface
+contour = mlab.pipeline.contour(diffuse, )
+contour.filter.contours = [brain_thr, ]
+
+# Apply mesh filter to clean up the mesh (decimation and smoothing)
+dec = mlab.pipeline.decimate_pro(contour)
+dec.filter.feature_angle = 60.
+dec.filter.target_reduction = 0.7
+
+smooth_ = tvtk.SmoothPolyDataFilter(
+ number_of_iterations=10,
+ relaxation_factor=0.1,
+ feature_angle=60,
+ feature_edge_smoothing=False,
+ boundary_smoothing=False,
+ convergence=0.,
+ )
+smooth = mlab.pipeline.user_defined(dec, filter=smooth_)
+
+# Get the largest connected region
+connect_ = tvtk.PolyDataConnectivityFilter(extraction_mode=4)
+connect = mlab.pipeline.user_defined(smooth, filter=connect_)
+
+# Compute normals for shading the surface
+compute_normals = mlab.pipeline.poly_data_normals(connect)
+compute_normals.filter.feature_angle = 80
+
+surf = mlab.pipeline.surface(compute_normals,
+ color=(0.9, 0.72, 0.62))
+
+#----------------------------------------------------------------------
+# Display a cut plane of the raw data
+ipw = mlab.pipeline.image_plane_widget(src, colormap='bone',
+ plane_orientation='z_axes',
+ slice_index=55)
+
+mlab.view(-165, 32, 350, [143, 133, 73])
+mlab.roll(180)
+
+fig.scene.disable_render = False
+
+#----------------------------------------------------------------------
+# To make the link between the Mayavi pipeline and the much more
+# complex VTK pipeline, we display both:
+mlab.show_pipeline(rich_view=False)
+from tvtk.pipeline.browser import PipelineBrowser
+browser = PipelineBrowser(fig.scene)
+browser.show()
+
+mlab.show()
diff --git a/pool/shard009/Python/0086107_simple_coroutines.py b/pool/shard009/Python/0086107_simple_coroutines.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e6e38b38127f8fec005b1d290c9222b4f15c2c9
--- /dev/null
+++ b/pool/shard009/Python/0086107_simple_coroutines.py
@@ -0,0 +1,20 @@
+""" Simple mutually-recursive coroutines with asyncio. Note that these recursive calls
+continue to grow the stack (and will eventually hit the maximum recursion depth
+exception if too many recursive calls are made. """
+
+import asyncio
+
+@asyncio.coroutine
+def a(n):
+ print("A: {}".format(n))
+ if n > 10: return n
+ else: yield from b(n+1)
+
+@asyncio.coroutine
+def b(n):
+ print("B: {}".format(n))
+ yield from a(n+1)
+
+loop = asyncio.get_event_loop()
+loop.run_until_complete(a(0))
+
diff --git a/pool/shard009/Python/0086113_init__.py b/pool/shard009/Python/0086113_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..564c8c2519f9e1014ca28a4f3e33b5951165cdc5
--- /dev/null
+++ b/pool/shard009/Python/0086113_init__.py
@@ -0,0 +1,67 @@
+from unittest import TestCase
+import os
+import signal
+import shutil
+import textwrap
+import time
+import supervise_web.core
+from mock import Mock
+from subprocess import Popen, PIPE
+from supervise_web.svio import svstat
+
+
+class BaseTestCase(TestCase):
+ def setUp(self):
+ # create an empty test directory
+ self.test_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tmp')
+ supervise_web.core._service_dir = Mock(return_value=self.test_dir)
+ if os.path.exists(self.test_dir):
+ shutil.rmtree(self.test_dir)
+ os.mkdir(self.test_dir)
+ self.supervise_procs = {}
+
+ def tearDown(self):
+ # shut down all test daemons and stop their supervise processes
+ for num, supervise_proc in self.supervise_procs.items():
+ daemon_pid = svstat(self._daemon_dir(num))['daemon_pid']
+ supervise_proc.terminate()
+ # only kill daemon if still alive (and not killed by some test)
+ if os.path.exists('/proc/%d' % daemon_pid):
+ os.kill(daemon_pid, signal.SIGTERM)
+
+ def _daemon_dir(self, num):
+ return os.path.join(self.test_dir, 'test_daemon_%d' % num)
+
+ def _daemon_supervise_dir(self, num):
+ return os.path.join(self._daemon_dir(num), 'supervise')
+
+ def _daemon_run_file(self, num):
+ return os.path.join(self._daemon_dir(num), 'run')
+
+ def _create_test_daemon(self, num, sleep_interval=0.2):
+ self._create_daemon_config(num, textwrap.dedent("""
+ #!/usr/bin/python
+ import datetime
+ import time
+ while True:
+ time.sleep(%f)
+ """ % sleep_interval)[1:])
+ # start a new supervise process for this daemon
+ supervise_proc = Popen(['supervise', self._daemon_dir(num)], stdin=PIPE, stderr=PIPE)
+ max_wait = 2 # wait for at most 2 seconds for the supervise process to start
+ while max_wait > 0:
+ if svstat(self._daemon_dir(num))['alive']:
+ break
+ max_wait -= 0.1
+ time.sleep(0.1)
+ else:
+ raise Exception('Supervise process did not start properly for test daemon <%d>' % num)
+ self.supervise_procs[num] = supervise_proc
+
+ def _create_daemon_config(self, num, daemon_code):
+ if os.path.exists(self._daemon_dir(num)):
+ raise Exception('Daemon path <%s> already exists' % self._daemon_dir(num))
+ os.mkdir(self._daemon_dir(num))
+ with open(self._daemon_run_file(num), 'w') as f:
+ f.write(daemon_code)
+ os.chmod(self._daemon_run_file(num), 0700)
diff --git a/pool/shard009/Python/0086119_nightly_gc_debug.py b/pool/shard009/Python/0086119_nightly_gc_debug.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b95211dc2a2b5d71c66728fbb076bb4b29a62da
--- /dev/null
+++ b/pool/shard009/Python/0086119_nightly_gc_debug.py
@@ -0,0 +1,61 @@
+###############################################################################
+# Define everything needed to build nightly Julia for gc debugging
+###############################################################################
+
+gc_debug_nightly_scheduler = Nightly(name="Julia GC Debug Build", builderNames=["nightly_gc_debug-x86", "nightly_gc_debug-x64"], hour=[3], branch="master", onlyIfChanged=True)
+c['schedulers'].append(gc_debug_nightly_scheduler)
+
+julia_gc_debug_factory = BuildFactory()
+julia_gc_debug_factory.useProgress = True
+julia_gc_debug_factory.addSteps([
+ # Clone julia
+ Git(
+ name="Julia checkout",
+ repourl=Property('repository', default='git://github.com/JuliaLang/julia.git'),
+ mode='incremental',
+ method='clean',
+ submodules=True,
+ clobberOnFailure=True,
+ progress=True
+ ),
+ # Fetch so that remote branches get updated as well.
+ ShellCommand(
+ name="git fetch",
+ command=["git", "fetch"],
+ flunkOnFailure=False
+ ),
+
+ # Add our particular configuration to flags
+ SetPropertyFromCommand(
+ name="Add configuration to flags",
+ command=["echo", Interpolate("%(prop:flags)s WITH_GC_DEBUG_ENV=1")],
+ property="flags"
+ ),
+
+ # make clean first, and nuke llvm
+ ShellCommand(
+ name="make cleanall",
+ command=["/bin/bash", "-c", Interpolate("make %(prop:flags)s cleanall")]
+ ),
+
+ # Make!
+ ShellCommand(
+ name="make",
+ command=["/bin/bash", "-c", Interpolate("make %(prop:flags)s")],
+ haltOnFailure = True
+ ),
+
+ # Test!
+ ShellCommand(
+ name="make testall",
+ command=["/bin/bash", "-c", Interpolate("make %(prop:flags)s testall")]
+ )
+])
+
+for arch in ["x86", "x64"]:
+ c['builders'].append(BuilderConfig(
+ name="nightly_gc_debug-%s"%(arch),
+ slavenames=["ubuntu14.04-%s"%(arch)],
+ category="Nightlies",
+ factory=julia_gc_debug_factory
+ ))
diff --git a/pool/shard009/Python/0086120_log_files.py b/pool/shard009/Python/0086120_log_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..f35fdfd03f286209ef26a37ac545f86636b5011f
--- /dev/null
+++ b/pool/shard009/Python/0086120_log_files.py
@@ -0,0 +1,24 @@
+from logging.handlers import RotatingFileHandler
+import logging
+import os
+
+
+def set_logger():
+
+ log_path = os.path.join(os.getcwd(), "Logs")
+ file_name = "news.log"
+ size_50MB = 50000000
+ if not os.path.exists(log_path):
+ try:
+ os.makedirs(log_path)
+ except:
+ pass
+ full_path = os.path.join(log_path, file_name)
+ logging.basicConfig(format='%(filename)s : %(asctime)s %(levelname)s %(message)s', datefmt="%Y-%m-%d %H:%M")
+ logger = logging.getLogger()
+ logger.setLevel(logging.DEBUG)
+ handler = RotatingFileHandler(full_path, maxBytes=size_50MB, backupCount=5)
+ logger.addHandler(handler)
+ formatter = logging.Formatter(fmt='%(filename)s : %(asctime)s %(levelname)s %(message)s', datefmt="%Y-%m-%d %H:%M")
+ handler.setFormatter(formatter)
+ handler.setLevel(logging.DEBUG)
diff --git a/pool/shard009/Python/0086122_test_pycontw2016.py b/pool/shard009/Python/0086122_test_pycontw2016.py
new file mode 100644
index 0000000000000000000000000000000000000000..b025835402ef1c3f74702f9b23b83b7f916fdf90
--- /dev/null
+++ b/pool/shard009/Python/0086122_test_pycontw2016.py
@@ -0,0 +1,87 @@
+import re
+
+import pytest
+
+from django.conf import settings
+from django.contrib.auth import get_user_model
+from django.core import mail, signing
+from django.test import override_settings
+
+
+pytestmark = pytest.mark.skipif(
+ settings.CONFERENCE_DEFAULT_SLUG != 'pycontw-2016',
+ reason='Not current conference',
+)
+
+
+User = get_user_model()
+
+
+def test_schedule(client, parser, schedule):
+ r = client.get('/en-us/events/schedule/')
+ body = parser.parse(r)
+
+ # Make sure every cross-page intra-site link is good.
+ link_tags = body.cssselect('a[href^="/"]')
+ assert len(link_tags) != 0
+ for tag in link_tags:
+ assert client.get(tag.get('href'), follow=True).status_code == 200
+
+
+@pytest.mark.django_db
+@override_settings( # Make sure we don't really send an email.
+ SECRET_KEY='Footage order-flow long-chain hydrocarbons hacker',
+ EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
+ DEFAULT_FROM_EMAIL='dev@pycon.tw',
+)
+def test_signup_post(client, parser):
+ """Check the verification email has correct format.
+ """
+ client.post('/en-us/accounts/signup/', {
+ 'email': 'user@user.me',
+ 'password1': '7K50M',
+ 'password2': '7K50M',
+ }, follow=True)
+
+ user = User.objects.get(email='user@user.me')
+ email = mail.outbox[0]
+
+ # The message does contain the activation link
+ message_has_verification_link = re.search(
+ r'^\s*http://testserver/en-us/accounts/verify/(?P[-:\w]+)/$',
+ email.body.strip(),
+ re.MULTILINE
+ )
+ # The message hints the email in use
+ message_has_account_email = user.email in email.body
+
+ assert message_has_verification_link, email.body.strip()
+ assert message_has_account_email, email.body.strip()
+ assert user.email == signing.loads(
+ message_has_verification_link.group('key'),
+ salt='Footage order-flow long-chain hydrocarbons hacker',
+ )
+ assert not email.alternatives
+
+
+@pytest.mark.usefixtures('bare_user')
+def test_signup_duplicate(client, parser):
+ response = client.post('/en-us/accounts/signup/', {
+ 'email': 'user@user.me',
+ 'password1': '7K50M',
+ 'password2': '7K50M',
+ })
+
+ body = parser.parse(response)
+ errored_blocks = body.cssselect('.has-error')
+ assert [e.get('id') for e in errored_blocks] == ['div_id_email']
+ assert [
+ parser.arrange(e)
+ for e in errored_blocks[0].cssselect('.help-block')
+ ] == [
+ parser.arrange(
+ ''
+ 'A user with that email already exists.'
+ '
'
+ )
+ ]
diff --git a/pool/shard009/Python/0086124_sensor.py b/pool/shard009/Python/0086124_sensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbac046d62ef970b16197d637dc5dcb5872b4a23
--- /dev/null
+++ b/pool/shard009/Python/0086124_sensor.py
@@ -0,0 +1,173 @@
+"""Support for hydrological data from the Fed. Office for the Environment."""
+from datetime import timedelta
+import logging
+
+import voluptuous as vol
+
+from homeassistant.components.sensor import PLATFORM_SCHEMA
+from homeassistant.const import ATTR_ATTRIBUTION, CONF_MONITORED_CONDITIONS
+import homeassistant.helpers.config_validation as cv
+from homeassistant.helpers.entity import Entity
+from homeassistant.util import Throttle
+
+_LOGGER = logging.getLogger(__name__)
+
+ATTRIBUTION = "Data provided by the Swiss Federal Office for the " "Environment FOEN"
+
+ATTR_DELTA_24H = "delta-24h"
+ATTR_MAX_1H = "max-1h"
+ATTR_MAX_24H = "max-24h"
+ATTR_MEAN_1H = "mean-1h"
+ATTR_MEAN_24H = "mean-24h"
+ATTR_MIN_1H = "min-1h"
+ATTR_MIN_24H = "min-24h"
+ATTR_PREVIOUS_24H = "previous-24h"
+ATTR_STATION = "station"
+ATTR_STATION_UPDATE = "station_update"
+ATTR_WATER_BODY = "water_body"
+ATTR_WATER_BODY_TYPE = "water_body_type"
+
+CONF_STATION = "station"
+
+MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
+
+SENSOR_DISCHARGE = "discharge"
+SENSOR_LEVEL = "level"
+SENSOR_TEMPERATURE = "temperature"
+
+CONDITIONS = {
+ SENSOR_DISCHARGE: "mdi:waves",
+ SENSOR_LEVEL: "mdi:zodiac-aquarius",
+ SENSOR_TEMPERATURE: "mdi:oil-temperature",
+}
+
+CONDITION_DETAILS = [
+ ATTR_DELTA_24H,
+ ATTR_MAX_1H,
+ ATTR_MAX_24H,
+ ATTR_MEAN_1H,
+ ATTR_MEAN_24H,
+ ATTR_MIN_1H,
+ ATTR_MIN_24H,
+ ATTR_PREVIOUS_24H,
+]
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
+ {
+ vol.Required(CONF_STATION): vol.Coerce(int),
+ vol.Optional(CONF_MONITORED_CONDITIONS, default=[SENSOR_TEMPERATURE]): vol.All(
+ cv.ensure_list, [vol.In(CONDITIONS)]
+ ),
+ }
+)
+
+
+def setup_platform(hass, config, add_entities, discovery_info=None):
+ """Set up the Swiss hydrological sensor."""
+ station = config.get(CONF_STATION)
+ monitored_conditions = config.get(CONF_MONITORED_CONDITIONS)
+
+ hydro_data = HydrologicalData(station)
+ hydro_data.update()
+
+ if hydro_data.data is None:
+ _LOGGER.error("The station doesn't exists: %s", station)
+ return
+
+ entities = []
+
+ for condition in monitored_conditions:
+ entities.append(SwissHydrologicalDataSensor(hydro_data, station, condition))
+
+ add_entities(entities, True)
+
+
+class SwissHydrologicalDataSensor(Entity):
+ """Implementation of a Swiss hydrological sensor."""
+
+ def __init__(self, hydro_data, station, condition):
+ """Initialize the Swiss hydrological sensor."""
+ self.hydro_data = hydro_data
+ self._condition = condition
+ self._data = self._state = self._unit_of_measurement = None
+ self._icon = CONDITIONS[condition]
+ self._station = station
+
+ @property
+ def name(self):
+ """Return the name of the sensor."""
+ return "{0} {1}".format(self._data["water-body-name"], self._condition)
+
+ @property
+ def unique_id(self) -> str:
+ """Return a unique, friendly identifier for this entity."""
+ return "{0}_{1}".format(self._station, self._condition)
+
+ @property
+ def unit_of_measurement(self):
+ """Return the unit of measurement of this entity, if any."""
+ if self._state is not None:
+ return self.hydro_data.data["parameters"][self._condition]["unit"]
+ return None
+
+ @property
+ def state(self):
+ """Return the state of the sensor."""
+ if isinstance(self._state, (int, float)):
+ return round(self._state, 2)
+ return None
+
+ @property
+ def device_state_attributes(self):
+ """Return the device state attributes."""
+ attrs = {}
+
+ if not self._data:
+ attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
+ return attrs
+
+ attrs[ATTR_WATER_BODY_TYPE] = self._data["water-body-type"]
+ attrs[ATTR_STATION] = self._data["name"]
+ attrs[ATTR_STATION_UPDATE] = self._data["parameters"][self._condition][
+ "datetime"
+ ]
+ attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
+
+ for entry in CONDITION_DETAILS:
+ attrs[entry.replace("-", "_")] = self._data["parameters"][self._condition][
+ entry
+ ]
+
+ return attrs
+
+ @property
+ def icon(self):
+ """Icon to use in the frontend."""
+ return self._icon
+
+ def update(self):
+ """Get the latest data and update the state."""
+ self.hydro_data.update()
+ self._data = self.hydro_data.data
+
+ if self._data is None:
+ self._state = None
+ else:
+ self._state = self._data["parameters"][self._condition]["value"]
+
+
+class HydrologicalData:
+ """The Class for handling the data retrieval."""
+
+ def __init__(self, station):
+ """Initialize the data object."""
+ self.station = station
+ self.data = None
+
+ @Throttle(MIN_TIME_BETWEEN_UPDATES)
+ def update(self):
+ """Get the latest data."""
+ from swisshydrodata import SwissHydroData
+
+ shd = SwissHydroData()
+ self.data = shd.get_station(self.station)
diff --git a/pool/shard009/Python/0086128_config.py b/pool/shard009/Python/0086128_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfff0a985028ba94ba110f0fb87cb2e7f89831bc
--- /dev/null
+++ b/pool/shard009/Python/0086128_config.py
@@ -0,0 +1,204 @@
+import json
+import os.path
+import subprocess
+import yaml
+
+brokenlist = list()
+
+
+class YAMLConfig(object):
+ _config_values = {}
+
+ def __init__(self, filename, default_keys={}, strict_mode=False):
+ self.filename = filename
+ self.default_keys = default_keys
+ self.strict_mode = strict_mode
+ self._load_config()
+
+ def _load_config(self):
+ if not os.path.exists(self.filename):
+ self._make_default_config()
+ else:
+ f = open(self.filename, 'r')
+ self._config_values = yaml.load(f)
+ f.close()
+ self._validate_config()
+ print("[Config] Config %s loaded!" % self.filename)
+
+ def _save_config(self):
+ f = open(self.filename, "w")
+ yaml.dump(self._config_values, f, indent=1)
+ f.close()
+
+ def _make_default_config(self):
+ try:
+ os.makedirs(os.path.dirname(self.filename))
+ except Exception as e:
+ print("Error making folder %s because %s" % (os.path.dirname(self.filename), e))
+ pass
+ f = open(self.filename, "w")
+ yaml.dump(self.default_keys, f, indent=1)
+ f.close()
+ print("[Config] Default config for %s created." % self.filename)
+ self._load_config()
+
+ def _validate_config(self):
+ for key, value in self.default_keys.items():
+ if key not in self._config_values:
+ self._config_values[key] = value
+ print("[Config] Added new default %s for config %s" % (key, self.filename))
+ if self.strict_mode:
+ for key in self._config_values.keys():
+ if key not in self.default_keys:
+ del self._config_values[key]
+ print("[Config] Deleted invlid key %s for config %s" % (key, self.filename))
+ else:
+ if self._config_values[key] is None:
+ self._config_values[key] = self.default_keys[key]
+ print("[Config] Resetting invalid key type for %s in config %s." % (key, self.filename))
+ self._save_config()
+
+ def _get_key(self, key):
+ if key not in self._config_values:
+ raise KeyError
+ if str(type(self._config_values[key])) == "":
+ return self._config_values[key].encode('utf-8')
+ else:
+ return self._config_values[key]
+
+ def set_key(self, key, value):
+ self._config_values[key] = value
+ self._save_config()
+
+ def key_exists(self, key):
+ if key in self._config_values:
+ return True
+ else:
+ return False
+
+ def __getitem__(self, item):
+ return self._get_key(item)
+
+ def __setitem__(self, key, value):
+ self.set_key(key, value)
+
+
+banList = []
+
+globalConfig = YAMLConfig(
+ "cfg/pso2proxy.config.yml",
+ {
+ 'myIpAddr': "0.0.0.0",
+ 'bindIp': "0.0.0.0",
+ 'blockNameMode': 1,
+ 'noisy': False,
+ 'admins': [],
+ 'enabledShips': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+ 'commandPrefix': '!'
+ },
+ True
+)
+
+blockNames = {}
+ShipLabel = {}
+
+proxy_ver = subprocess.Popen(["git", "describe", "--always"], stdout=subprocess.PIPE).communicate()[0].rstrip("\n")
+
+
+def is_admin(sega_id):
+ if sega_id in globalConfig['admins']:
+ return True
+ else:
+ return False
+
+
+def load_block_names():
+ global blockNames
+ if globalConfig['blockNameMode'] == 0:
+ return "[ShipProxy] Blocks are not renamed"
+ if os.path.exists("cfg/blocknames.resources.json"):
+ f = open("cfg/blocknames.resources.json", 'r')
+ try:
+ blockNames = json.load(f, encoding='utf-8')
+ f.close()
+ return ("[ShipProxy] %s Block names loaded!" % len(blockNames))
+ except ValueError:
+ f.close()
+ return ("[ShipProxy] Failed to load blockname file")
+
+ else:
+ return "[ShipProxy] BlockName file does not exists"
+
+
+load_block_names()
+
+
+def load_ship_names():
+ global ShipLabel
+ ShipLabel.clear() # Clear list
+
+ ShipLabel["Console"] = "Console"
+
+ if os.path.exists("cfg/shipslabel.resources.json"):
+ f = open("cfg/shipslabel.resources.json", 'r')
+ try:
+ for key, val in json.load(f, encoding='utf-8').items():
+ ShipLabel[key] = val.encode("utf8", 'ignore')
+ f.close()
+ return ("[GlobalChat] %s ship labels names loaded!" % len(ShipLabel))
+ except ValueError:
+ f.close()
+ return ("[GlobalChat] Failed to load ship labels!")
+ else:
+ return "[GlobalChat] shipslabel file does not exists"
+
+
+load_ship_names()
+
+
+def load_bans():
+ global banList
+ if not os.path.exists('cfg/pso2proxy.bans.json'):
+ f = open('cfg/pso2proxy.bans.json', 'w')
+ f.write(json.dumps(banList))
+ f.close()
+ f = open('cfg/pso2proxy.bans.json', 'r')
+ bans = f.read()
+ f.close()
+ banList = json.loads(bans)
+ return ("[Bans] %i bans loaded!" % len(bans))
+
+
+def save_bans():
+ global banList
+ f = open('cfg/pso2proxy.bans.json', 'w')
+ f.write(json.dumps(banList))
+ f.close()
+ print("[Bans] %i bans saved!" % len(banList))
+
+
+def is_segaid_banned(segaid):
+ global banList
+ for ban in banList:
+ if 'segaId' in ban:
+ if ban['segaId'] == segaid:
+ return True
+ return False
+
+
+def is_player_id_banned(player_id):
+ global banList
+ for ban in banList:
+ if 'playerId' in ban:
+ if int(ban['playerId']) == player_id:
+ return True
+ return False
+
+
+load_bans()
+
+myIpAddress = globalConfig['myIpAddr']
+bindIp = globalConfig['bindIp']
+blockNameMode = globalConfig['blockNameMode']
+noisy = globalConfig['noisy']
+admins = globalConfig['admins']
diff --git a/pool/shard009/Python/0086129_run.py b/pool/shard009/Python/0086129_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e6f05cbffa6701308d303b2d3055bebdf4d3865
--- /dev/null
+++ b/pool/shard009/Python/0086129_run.py
@@ -0,0 +1,41 @@
+import sys, os
+
+def cleanBuild(output):
+ print "Cleaning previous build..."
+ import shutil
+ if not os.path.exists("build"):
+ os.mkdir("build")
+ if os.path.exists("build"):
+ shutil.rmtree("build")
+
+def compileLinux(output):
+ name = output.split(".")[0]
+ os.system("rlwrap sml run.sml " + output)
+ print "PLANG Compiler running ..."
+ os.system("llc " + "build/" + name + ".ll -o build/" + name + ".s")
+ os.system("gcc " + "build/" + name + ".s" + " -o " + name)
+ print "==== Compile Success! ===="
+
+def compileWin(output):
+ os.system("sml run.sml %s" % output)
+ print "PLANG Compiler running ..."
+ os.system("llc build\\{0}.ll -o build\\{0}.s &&\"C:\mingw\\bin\\gcc.exe\" build\{0}.s -o {0}".format(output[:output.rfind(".plg")]))
+ print "==== Compile Success! ===="
+
+def compileOSX(output):
+ print "Unimplemented in Mac OS X"
+ pass
+
+if __name__ == "__main__":
+ filename = sys.argv[1]
+ cleanBuild(filename)
+ os.makedirs(os.path.join("build", os.path.dirname(filename)))
+ if "win" in sys.platform:
+ compileWin(filename)
+ elif "darwin" in sys.platform:
+ compileOSX(filename)
+ elif "linux" in sys.platform:
+ compileLinux(filename)
+ else:
+ print "What are you"
+ pass
diff --git a/pool/shard009/Python/0086130_Jask_test.py b/pool/shard009/Python/0086130_Jask_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e9481ffdd7cc29307362762e04d8b9ef8312ba1
--- /dev/null
+++ b/pool/shard009/Python/0086130_Jask_test.py
@@ -0,0 +1,28 @@
+import demistomock as demisto
+
+DATE_WITHOUT_MS = '2019-05-03T03:01:54'
+DATE_WITH_MS = '2019-05-03T03:02:54.123'
+
+
+def init_integration(mocker):
+ mocker.patch.object(demisto, 'params', return_value={
+ 'URL': 'mock.com'
+ })
+
+
+def test_fetch_incidents(mocker):
+ init_integration(mocker)
+ import Jask
+ from Jask import fetch_incidents
+ mocker.patch.object(Jask, 'req', return_value={
+ 'objects': [
+ {
+ 'timestamp': DATE_WITHOUT_MS
+ },
+ {
+ 'timestamp': DATE_WITH_MS
+ }
+ ]
+ })
+ # asserts there are no exceptions
+ assert(fetch_incidents() is None)
diff --git a/pool/shard009/Python/0086131_leave_allocation.py b/pool/shard009/Python/0086131_leave_allocation.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cffa4c5b1eb2023c1781509453691d663d8aa1d
--- /dev/null
+++ b/pool/shard009/Python/0086131_leave_allocation.py
@@ -0,0 +1,160 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe.utils import flt, date_diff, formatdate
+from frappe import _
+from frappe.model.document import Document
+from erpnext.hr.utils import set_employee_name, get_leave_period
+from erpnext.hr.doctype.leave_application.leave_application import get_approved_leaves_for_period
+
+class OverlapError(frappe.ValidationError): pass
+class BackDatedAllocationError(frappe.ValidationError): pass
+class OverAllocationError(frappe.ValidationError): pass
+class LessAllocationError(frappe.ValidationError): pass
+class ValueMultiplierError(frappe.ValidationError): pass
+
+class LeaveAllocation(Document):
+ def validate(self):
+ self.validate_period()
+ self.validate_new_leaves_allocated_value()
+ self.validate_allocation_overlap()
+ self.validate_back_dated_allocation()
+ self.set_total_leaves_allocated()
+ self.validate_total_leaves_allocated()
+ self.validate_lwp()
+ set_employee_name(self)
+ self.validate_leave_allocation_days()
+
+ def validate_leave_allocation_days(self):
+ company = frappe.db.get_value("Employee", self.employee, "company")
+ leave_period = get_leave_period(self.from_date, self.to_date, company)
+ max_leaves_allowed = frappe.db.get_value("Leave Type", self.leave_type, "max_leaves_allowed")
+ if max_leaves_allowed > 0:
+ leave_allocated = 0
+ if leave_period:
+ leave_allocated = get_leave_allocation_for_period(self.employee, self.leave_type, leave_period[0].from_date, leave_period[0].to_date)
+ leave_allocated += self.new_leaves_allocated
+ if leave_allocated > max_leaves_allowed:
+ frappe.throw(_("Total allocated leaves are more days than maximum allocation of {0} leave type for employee {1} in the period")\
+ .format(self.leave_type, self.employee))
+
+ def on_update_after_submit(self):
+ self.validate_new_leaves_allocated_value()
+ self.set_total_leaves_allocated()
+
+ frappe.db.set(self,'carry_forwarded_leaves', flt(self.carry_forwarded_leaves))
+ frappe.db.set(self,'total_leaves_allocated',flt(self.total_leaves_allocated))
+
+ self.validate_against_leave_applications()
+
+ def validate_period(self):
+ if date_diff(self.to_date, self.from_date) <= 0:
+ frappe.throw(_("To date cannot be before from date"))
+
+ def validate_lwp(self):
+ if frappe.db.get_value("Leave Type", self.leave_type, "is_lwp"):
+ frappe.throw(_("Leave Type {0} cannot be allocated since it is leave without pay").format(self.leave_type))
+
+ def validate_new_leaves_allocated_value(self):
+ """validate that leave allocation is in multiples of 0.5"""
+ if flt(self.new_leaves_allocated) % 0.5:
+ frappe.throw(_("Leaves must be allocated in multiples of 0.5"), ValueMultiplierError)
+
+ def validate_allocation_overlap(self):
+ leave_allocation = frappe.db.sql("""
+ select name from `tabLeave Allocation`
+ where employee=%s and leave_type=%s and docstatus=1
+ and to_date >= %s and from_date <= %s""",
+ (self.employee, self.leave_type, self.from_date, self.to_date))
+
+ if leave_allocation:
+ frappe.msgprint(_("{0} already allocated for Employee {1} for period {2} to {3}")
+ .format(self.leave_type, self.employee, formatdate(self.from_date), formatdate(self.to_date)))
+
+ frappe.throw(_('Reference') + ': {0}'
+ .format(leave_allocation[0][0]), OverlapError)
+
+ def validate_back_dated_allocation(self):
+ future_allocation = frappe.db.sql("""select name, from_date from `tabLeave Allocation`
+ where employee=%s and leave_type=%s and docstatus=1 and from_date > %s
+ and carry_forward=1""", (self.employee, self.leave_type, self.to_date), as_dict=1)
+
+ if future_allocation:
+ frappe.throw(_("Leave cannot be allocated before {0}, as leave balance has already been carry-forwarded in the future leave allocation record {1}")
+ .format(formatdate(future_allocation[0].from_date), future_allocation[0].name),
+ BackDatedAllocationError)
+
+ def set_total_leaves_allocated(self):
+ self.carry_forwarded_leaves = get_carry_forwarded_leaves(self.employee,
+ self.leave_type, self.from_date, self.carry_forward)
+
+ self.total_leaves_allocated = flt(self.carry_forwarded_leaves) + flt(self.new_leaves_allocated)
+
+ if not self.total_leaves_allocated and not frappe.db.get_value("Leave Type", self.leave_type, "is_earned_leave"):
+ frappe.throw(_("Total leaves allocated is mandatory for Leave Type {0}".format(self.leave_type)))
+
+ def validate_total_leaves_allocated(self):
+ # Adding a day to include To Date in the difference
+ date_difference = date_diff(self.to_date, self.from_date) + 1
+ if date_difference < self.total_leaves_allocated:
+ frappe.throw(_("Total allocated leaves are more than days in the period"), OverAllocationError)
+
+ def validate_against_leave_applications(self):
+ leaves_taken = get_approved_leaves_for_period(self.employee, self.leave_type,
+ self.from_date, self.to_date)
+
+ if flt(leaves_taken) > flt(self.total_leaves_allocated):
+ if frappe.db.get_value("Leave Type", self.leave_type, "allow_negative"):
+ frappe.msgprint(_("Note: Total allocated leaves {0} shouldn't be less than already approved leaves {1} for the period").format(self.total_leaves_allocated, leaves_taken))
+ else:
+ frappe.throw(_("Total allocated leaves {0} cannot be less than already approved leaves {1} for the period").format(self.total_leaves_allocated, leaves_taken), LessAllocationError)
+
+def get_leave_allocation_for_period(employee, leave_type, from_date, to_date):
+ leave_allocated = 0
+ leave_allocations = frappe.db.sql("""
+ select employee, leave_type, from_date, to_date, total_leaves_allocated
+ from `tabLeave Allocation`
+ where employee=%(employee)s and leave_type=%(leave_type)s
+ and docstatus=1
+ and (from_date between %(from_date)s and %(to_date)s
+ or to_date between %(from_date)s and %(to_date)s
+ or (from_date < %(from_date)s and to_date > %(to_date)s))
+ """, {
+ "from_date": from_date,
+ "to_date": to_date,
+ "employee": employee,
+ "leave_type": leave_type
+ }, as_dict=1)
+
+ if leave_allocations:
+ for leave_alloc in leave_allocations:
+ leave_allocated += leave_alloc.total_leaves_allocated
+
+ return leave_allocated
+
+@frappe.whitelist()
+def get_carry_forwarded_leaves(employee, leave_type, date, carry_forward=None):
+ carry_forwarded_leaves = 0
+
+ if carry_forward:
+ validate_carry_forward(leave_type)
+
+ previous_allocation = frappe.db.sql("""
+ select name, from_date, to_date, total_leaves_allocated
+ from `tabLeave Allocation`
+ where employee=%s and leave_type=%s and docstatus=1 and to_date < %s
+ order by to_date desc limit 1
+ """, (employee, leave_type, date), as_dict=1)
+ if previous_allocation:
+ leaves_taken = get_approved_leaves_for_period(employee, leave_type,
+ previous_allocation[0].from_date, previous_allocation[0].to_date)
+
+ carry_forwarded_leaves = flt(previous_allocation[0].total_leaves_allocated) - flt(leaves_taken)
+
+ return carry_forwarded_leaves
+
+def validate_carry_forward(leave_type):
+ if not frappe.db.get_value("Leave Type", leave_type, "is_carry_forward"):
+ frappe.throw(_("Leave Type {0} cannot be carry-forwarded").format(leave_type))
diff --git a/pool/shard009/Python/0086134_views.py b/pool/shard009/Python/0086134_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..1221a059b45d17d884c2e912e16bb093674c1484
--- /dev/null
+++ b/pool/shard009/Python/0086134_views.py
@@ -0,0 +1,50 @@
+"""Handle the rendering of the energy scoreboard widget."""
+import datetime
+
+from apps.managers.challenge_mgr import challenge_mgr
+from apps.managers.resource_mgr import resource_mgr
+from apps.widgets.resource_goal import resource_goal
+
+
+def supply(request, page_name):
+ """Supply the view_objects content."""
+ _ = request
+ _ = page_name
+ return {}
+
+
+def resource_supply(request, resource, page_name):
+ """Supply the view_objects content.
+ :return: team, goals_scoreboard, resource_round_ranks"""
+
+ user = request.user
+ team = user.profile.team
+ round_resource_ranks = {}
+ round_group_resource_ranks = {}
+ round_resource_goal_ranks = {}
+
+ today = datetime.datetime.today()
+
+ rounds = challenge_mgr.get_all_round_info()["rounds"]
+ for key in rounds.keys():
+ if rounds[key]["start"] <= today and\
+ (rounds[key]["display_scoreboard"] or page_name == "status"):
+ round_resource_ranks[key] = resource_mgr.resource_ranks(resource, key)
+ round_group_resource_ranks[key] = resource_mgr.group_resource_ranks(resource, key)
+ round_resource_goal_ranks[key] = resource_goal.resource_goal_ranks(resource, key)
+
+ """
+ round_resource_ranks["Overall"] = resource_mgr.resource_ranks(resource, "Overall")
+ round_group_resource_ranks["Overall"] = resource_mgr.group_resource_ranks(resource, "Overall")
+ round_resource_goal_ranks["Overall"] = resource_goal.resource_goal_ranks(resource, "Overall")
+ """
+
+ resource_setting = resource_mgr.get_resource_setting(resource)
+ return {
+ "profile": user.profile,
+ "team": team,
+ "resource": resource_setting,
+ "round_resource_goal_ranks": round_resource_goal_ranks,
+ "round_resource_ranks": round_resource_ranks,
+ "round_group_resource_ranks": round_group_resource_ranks,
+ }
diff --git a/pool/shard009/Python/0086147_sreclient_pristine.py b/pool/shard009/Python/0086147_sreclient_pristine.py
new file mode 100644
index 0000000000000000000000000000000000000000..2df69638fb75d1253aa8f6b20dc0130c3a239952
--- /dev/null
+++ b/pool/shard009/Python/0086147_sreclient_pristine.py
@@ -0,0 +1,107 @@
+from piston_mini_client import (PistonAPI, returns_json)
+from piston_mini_client.validators import (
+ validate,
+ validate_integer,
+ validate_pattern,
+ oauth_protected,
+)
+
+# These are factored out as constants for if you need to work against a
+# server that doesn't support both schemes (like http-only dev servers)
+PUBLIC_API_SCHEME = 'http'
+AUTHENTICATED_API_SCHEME = 'https'
+
+
+class SoftwareCenterRecommenderAPI(PistonAPI):
+ default_service_root = 'http://localhost:8000/api/1.0'
+
+ @returns_json
+ def server_status(self):
+ return self._get('server-status/', scheme=PUBLIC_API_SCHEME)
+
+ @oauth_protected
+ @returns_json
+ def profile(self, pkgnames):
+ """Return True if a profile has already been uploaded."""
+ return self._get('profile/', scheme=AUTHENTICATED_API_SCHEME)
+
+ @oauth_protected
+ @returns_json
+ def submit_profile(self, data):
+ return self._post('profile/', data=data,
+ scheme=AUTHENTICATED_API_SCHEME)
+
+ @returns_json
+ def submit_anon_profile(self, uuid, installed_packages, extra):
+ data = {
+ 'installed_packages': installed_packages,
+ 'extra': extra,
+ }
+ return self._post('profile/%s/' % uuid, data=data,
+ scheme=PUBLIC_API_SCHEME)
+
+ @oauth_protected
+ @validate_pattern('uuid', r'[\dabcdef]{32}')
+ @returns_json
+ def recommend_me(self, uuid):
+ """Fetch personalized (authenticated) recommendations.
+
+ We still need to submit an UUID to link to the anon profile if
+ it was submitted.
+ """
+ return self._get('recommend_me/%s/' % uuid,
+ scheme=AUTHENTICATED_API_SCHEME)
+
+ @validate_pattern('uuid', r'[\dabcdef]{32}')
+ def anon_recommend_me(self, uuid):
+ return self._get('recommend_me/%s/' % uuid,
+ scheme=AUTHENTICATED_API_SCHEME)
+
+ @validate_pattern('pkgname', '[^/]+')
+ @returns_json
+ def recommend_app(self, pkgname):
+ return self._get('recommend_app/%s/' % pkgname,
+ scheme=PUBLIC_API_SCHEME)
+
+ @returns_json
+ def recommend_all_apps(self):
+ return self._get('recommend_all_apps/', scheme=PUBLIC_API_SCHEME)
+
+ @returns_json
+ def recommend_top(self):
+ return self._get('recommend_top/', scheme=PUBLIC_API_SCHEME)
+
+ @oauth_protected
+ @validate_pattern('rid', '\w+')
+ @validate_integer('feedback')
+ @returns_json
+ def feedback(self, rid, feedback):
+ data = {
+ 'feedback': feedback,
+ 'rid': rid,
+ }
+ return self._post('feedback/', data=data,
+ scheme=AUTHENTICATED_API_SCHEME)
+
+ @oauth_protected
+ @validate_pattern('pkgname', '[^/]+')
+ @validate_pattern('action', '\w{3,20}')
+ @returns_json
+ def implicit_feedback(self, pkgname, action):
+ data = {
+ 'package_name': pkgname,
+ 'action': action,
+ }
+ return self._post('implicit_feedback/', data=data,
+ scheme=AUTHENTICATED_API_SCHEME)
+
+ @oauth_protected
+ @returns_json
+ @validate('remove', bool)
+ def remove_app(self, appname, remove):
+ data = {
+ 'app': appname,
+ 'remove': remove,
+ }
+ return self._post('remove_app/', data=data,
+ scheme=AUTHENTICATED_API_SCHEME)
diff --git a/pool/shard009/Python/0086163_dist_cmd_stress.py b/pool/shard009/Python/0086163_dist_cmd_stress.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf016fdc0e510a1c8f68db834ae9f30a70df5f87
--- /dev/null
+++ b/pool/shard009/Python/0086163_dist_cmd_stress.py
@@ -0,0 +1,47 @@
+# Copyright (c) 2013 Matej Laitl
+# Distributed under the terms of the GNU General Public License v2 or any
+# later version of the license, at your option.
+
+"""
+A custom command for distutils to facilitate stress-testing of PyBayes
+"""
+
+from distutils.cmd import Command
+from distutils.errors import DistutilsExecError
+import distutils.log as log
+from os.path import abspath, dirname, join
+import sys
+import unittest
+
+
+class stress(Command):
+ """Stress-test PyBayes in the build directory"""
+
+ description = 'run stress-suite of PyBayes within build directory'
+ user_options = []
+
+ def initialize_options(self):
+ self.build_lib = None
+
+ def finalize_options(self):
+ self.set_undefined_options('build', ('build_lib', 'build_lib'))
+
+ def run(self):
+ self.run_command('build') # build if not alredy run
+ orig_path = sys.path[:]
+ try:
+ tests_path = abspath(self.build_lib)
+ sys.path.insert(0, tests_path)
+ import pybayes.stresses
+ if dirname(pybayes.stresses.__file__) != join(tests_path, 'pybayes', 'stresses'):
+ raise Exception("Expected that imported pybayes.stresses would be from "
+ + "{0}, but it was from {1} instead".format(tests_path,
+ dirname(pybayes.tests.__file__)))
+ suite = unittest.TestLoader().loadTestsFromModule(pybayes.stresses)
+ result = unittest.TextTestRunner(verbosity=self.verbose).run(suite)
+ if not result.wasSuccessful():
+ raise Exception("There were test failures")
+ except Exception as e:
+ raise DistutilsExecError(e)
+ finally:
+ sys.path = orig_path
diff --git a/pool/shard009/Python/0086167_LCSM.py b/pool/shard009/Python/0086167_LCSM.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ed817cd68d913745082d331c7bb1143e7f16a5d
--- /dev/null
+++ b/pool/shard009/Python/0086167_LCSM.py
@@ -0,0 +1,37 @@
+def parse(fasta):
+ f = open(fasta, 'r')
+ rawdna = ""
+ for line in f:
+ rawdna += line
+ #Split file into fragments
+ fragments = rawdna.split('\n')
+
+ #Move fragments into separate array
+ dnafrag = []
+ for i in range(len(fragments)):
+ if i % 2 != 0:
+ dnafrag.append(fragments[i])
+ return dnafrag
+
+def parse_fasta(filename):
+ f = open(filename)
+ sequences = {}
+ for line in f:
+ if line.startswith('>'):
+ name = line[1:].rstrip('\n')
+ sequences[name] = ''
+ else:
+ sequences[name] = sequences[name] + line.rstrip('\n')
+ return sequences.values()
+
+def long_substr(data):
+ substr = ''
+ if len(data) > 1 and len(data[0]) > 0:
+ for i in range(len(data[0])):
+ for j in range(len(data[0])-i+1):
+ if j > len(substr) and all(data[0][i:i+j] in x for x in data):
+ substr = data[0][i:i+j]
+ return substr
+
+#Test
+print long_substr(parse_fasta('rosalind_lcsm.txt'))
\ No newline at end of file
diff --git a/pool/shard009/Python/0086171_mcpacket.py b/pool/shard009/Python/0086171_mcpacket.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5cc98fc45e4f4671adac8f9771a16f5241b2117
--- /dev/null
+++ b/pool/shard009/Python/0086171_mcpacket.py
@@ -0,0 +1,112 @@
+try:
+ basestring
+except NameError:
+ basestring = str
+
+import copy
+import logging
+import zlib
+from time import gmtime, strftime
+
+from spock import utils
+from spock.mcp import datautils, mcdata
+from spock.mcp.mcdata import MC_VARINT
+from spock.mcp.mcpacket_extensions import hashed_extensions
+
+
+logger = logging.getLogger('spock')
+
+
+class PacketDecodeFailure(Exception):
+ def __init__(self, packet, pbuff, underflow=False):
+ self.packet = packet
+ self.pbuff = pbuff
+ self.underflow = underflow
+
+
+class Packet(object):
+ def __init__(self,
+ ident=[mcdata.HANDSHAKE_STATE, mcdata.CLIENT_TO_SERVER, 0x00],
+ data=None
+ ):
+ if isinstance(ident, basestring):
+ ident = mcdata.packet_str2ident[ident]
+ self.__ident = list(ident)
+ # Quick hack to fake default ident
+ if len(self.__ident) == 2:
+ self.__ident.append(0x00)
+ self.ident = tuple(self.__ident)
+ self.str_ident = mcdata.packet_ident2str[self.ident]
+ self.data = data if data else {}
+
+ def clone(self):
+ return Packet(self.ident, copy.deepcopy(self.data))
+
+ def new_ident(self, ident):
+ self.__init__(ident, self.data)
+
+ def decode(self, bbuff, proto_comp_state):
+ self.data = {}
+ packet_length = datautils.unpack(MC_VARINT, bbuff)
+ packet_data = bbuff.recv(packet_length)
+ pbuff = utils.BoundBuffer(packet_data)
+ if proto_comp_state == mcdata.PROTO_COMP_ON:
+ body_length = datautils.unpack(MC_VARINT, pbuff)
+ if body_length > 0:
+ body_data = zlib.decompress(pbuff.flush(), zlib.MAX_WBITS)
+ pbuff.write(body_data)
+ pbuff.save()
+
+ try:
+ # Ident
+ self.__ident[2] = datautils.unpack(MC_VARINT, pbuff)
+ self.ident = tuple(self.__ident)
+ self.str_ident = mcdata.packet_ident2str[self.ident]
+ # Payload
+ for dtype, name in mcdata.hashed_structs[self.ident]:
+ self.data[name] = datautils.unpack(dtype, pbuff)
+ # Extension
+ if self.ident in hashed_extensions:
+ hashed_extensions[self.ident].decode_extra(self, pbuff)
+ if len(pbuff) > 0:
+ raise PacketDecodeFailure(self, pbuff)
+ except utils.BufferUnderflowException:
+ raise PacketDecodeFailure(self, pbuff, True)
+ return self
+
+ def encode(self, proto_comp_state, proto_comp_threshold, comp_level=6):
+ # Ident
+ o = datautils.pack(MC_VARINT, self.ident[2])
+ # Payload
+ for dtype, name in mcdata.hashed_structs[self.ident]:
+ o += datautils.pack(dtype, self.data[name])
+ # Extension
+ if self.ident in hashed_extensions:
+ o += hashed_extensions[self.ident].encode_extra(self)
+
+ if proto_comp_state == mcdata.PROTO_COMP_ON:
+ uncompressed_len = len(o)
+ if uncompressed_len < proto_comp_threshold:
+ header = datautils.pack(MC_VARINT, uncompressed_len + 1)
+ header += datautils.pack(MC_VARINT, 0)
+ elif uncompressed_len >= proto_comp_threshold:
+ o = zlib.compress(o, comp_level)
+ ulen_varint = datautils.pack(MC_VARINT, uncompressed_len)
+ header = datautils.pack(MC_VARINT,
+ uncompressed_len + len(ulen_varint))
+ header += ulen_varint
+ return header + o
+ elif proto_comp_state == mcdata.PROTO_COMP_OFF:
+ return datautils.pack(MC_VARINT, len(o)) + o
+ else:
+ return None
+
+ def __repr__(self):
+ s = ('<<<', '>>>')[self.ident[1]]
+ f = "[%s] %s (0x%02X, 0x%02X): %-" + str(
+ max([len(i) for i in mcdata.hashed_names.values()]) + 1) + "s%s"
+ return f % (
+ strftime("%H:%M:%S", gmtime()), s, self.ident[0], self.ident[2],
+ mcdata.hashed_names[self.ident],
+ str(self.data)
+ )
diff --git a/pool/shard009/Python/0086178_gae_http_server.py b/pool/shard009/Python/0086178_gae_http_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ec52f64d8605f3ef6189512ac87d1390ed73bf2
--- /dev/null
+++ b/pool/shard009/Python/0086178_gae_http_server.py
@@ -0,0 +1,126 @@
+"""
+RESTx: Sane, simple and effective data publishing and integration.
+
+Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either 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 .
+
+"""
+
+"""
+Provide an abstraction layer for a concrete HTTP server implementation.
+
+This allows the rest of our code to be written without server specifics
+being spread all over the place. That way, we can always change the
+concrete HttpServer implementation later on.
+
+"""
+
+# Python imports
+import sys
+import StringIO
+import traceback
+
+# GAE imports
+from google.appengine.ext.webapp.util import run_wsgi_app
+
+# RESTx imports
+import restx.settings as settings
+from restx.httpabstraction.python_http_server import PythonHttpRequest
+
+from restx.logger import *
+
+from restx.httpabstraction.base_server import BaseHttpServer
+
+#
+# Note: We are not defining out own Request class here, since we
+# can just use the request class used for Python.
+#
+
+class _HttpHandler(object):
+ """
+ Since this is something specific to the particular server,
+ this class is not part of the official http-abstraction-API.
+
+ """
+ def __init__(self, request_handler):
+ self.request_handler = request_handler
+
+ def handle(self, environ, start_response):
+ try:
+ start_time = datetime.datetime.now()
+ req = PythonHttpRequest(environ, start_response)
+ msg = "%s : %s : %s" % (req.getRequestProtocol(),
+ req.getRequestMethod(),
+ req.getRequestURI())
+ #log(msg, facility=LOGF_ACCESS_LOG)
+ code, response_body, headers = self.request_handler.handle(req)
+ for name, value in headers.items():
+ req.setResponseHeader(name, value)
+ req.setResponse(code, response_body)
+ req.sendResponse()
+ req.close()
+ end_time = datetime.datetime.now()
+ td = end_time-start_time
+ request_ms = td.seconds*1000 + td.microseconds//1000
+ log("%s : %sms : %s : %s" % (msg, request_ms, code, len(response_body)),
+ start_time = start_time, facility=LOGF_ACCESS_LOG)
+ except Exception, e:
+ sys.stderr.write(traceback.format_exc())
+ raise e
+ """
+ #sys.exit(1)
+ """
+
+
+# ----------------------------------------------------
+
+request_handler = None
+
+def _app_method(environ, start_response):
+ global request_handler
+ handler = _HttpHandler(request_handler)
+ handler.handle(environ, start_response)
+ return ""
+
+
+class GaeHttpServer(BaseHttpServer):
+ """
+ Wrapper class around a concrete HTTP server implementation.
+
+ """
+
+ __native_server = None
+
+ def __init__(self, port, req_handler):
+ """
+ Initialize and start an HTTP server.
+
+ Uses the built-in simple HTTP server implementation that
+ comes with Python.
+
+ @param port: The port on which the server should listen.
+ @type port: int
+
+ @param request_handler: The request handler class from our generic code.
+ @type request_handler: Any class with a 'handle()' method that can take a
+ RestxHttpRequest. In our case, this is normally the
+ RequestDispatcher class.
+
+ """
+ global request_handler
+ request_handler = req_handler
+ log("Listening for HTTP requests...")
+ run_wsgi_app(_app_method)
+
diff --git a/pool/shard009/Python/0086181_clusters_scaling.py b/pool/shard009/Python/0086181_clusters_scaling.py
new file mode 100644
index 0000000000000000000000000000000000000000..50e3139cdfc9b24997b6641c818aa54e8e0413aa
--- /dev/null
+++ b/pool/shard009/Python/0086181_clusters_scaling.py
@@ -0,0 +1,87 @@
+# Copyright (c) 2013 Mirantis Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, 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 copy
+
+import savanna.exceptions as ex
+import savanna.plugins.base as plugin_base
+import savanna.service.api as api
+import savanna.service.validations.base as b
+import savanna.service.validations.cluster_templates as cl_t
+
+
+def _build_node_groups_schema():
+ schema = copy.deepcopy(cl_t.CLUSTER_TEMPLATE_SCHEMA)
+ return schema['properties']['node_groups']
+
+
+CLUSTER_SCALING_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "resize_node_groups": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ },
+ "count": {
+ "type": "integer",
+ "minimum": 0,
+ },
+ },
+ "additionalProperties": False,
+ "required": [
+ "name",
+ "count",
+ ]
+ },
+ "minItems": 1
+ },
+ "add_node_groups": _build_node_groups_schema(),
+ },
+ "additionalProperties": False,
+ "anyOf": [
+ {
+ "required": ["resize_node_groups"]
+ },
+ {
+ "required": ["add_node_groups"]
+ }
+ ]
+
+}
+
+
+def check_cluster_scaling(data, cluster_id, **kwargs):
+ cluster = api.get_cluster(id=cluster_id)
+ if not (plugin_base.PLUGINS.is_plugin_implements(cluster.plugin_name,
+ 'scale_cluster') and (
+ plugin_base.PLUGINS.is_plugin_implements(cluster.plugin_name,
+ 'decommission_nodes'))):
+ raise ex.InvalidException(
+ "Requested plugin '%s' doesn't support cluster scaling feature"
+ % cluster.plugin_name)
+
+ if cluster.status != 'Active':
+ raise ex.InvalidException("Cluster cannot be scaled not in 'Active' "
+ "status. Cluster status: " + cluster.status)
+
+ if data.get("resize_node_groups"):
+ b.check_resize(cluster, data['resize_node_groups'])
+
+ if data.get("add_node_groups"):
+ b.check_add_node_groups(cluster, data['add_node_groups'])
diff --git a/pool/shard009/Python/0086183_operation_log.py b/pool/shard009/Python/0086183_operation_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..30dde20871b26b84375c7d9e3ac4e77982d32d31
--- /dev/null
+++ b/pool/shard009/Python/0086183_operation_log.py
@@ -0,0 +1,193 @@
+# Copyright 2016 NEC Corporation.
+#
+# 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 json
+import logging
+import re
+
+from django.conf import settings
+from django.contrib import messages as django_messages
+from django.core.exceptions import MiddlewareNotUsed
+
+import six.moves.urllib.parse as urlparse
+
+LOG = logging.getLogger(__name__)
+
+
+class OperationLogMiddleware(object):
+ """Middleware to output operation log.
+
+ This log can includes information below:
+
+ - ``domain name``
+ - ``domain id``
+ - ``project name``
+ - ``project id``
+ - ``user name``
+ - ``user id``
+ - ``request scheme``
+ - ``referer url``
+ - ``request url``
+ - ``message``
+ - ``method``
+ - ``http status``
+ - ``request parameters``
+
+ and log format is defined OPERATION_LOG_OPTIONS.
+ """
+
+ @property
+ def OPERATION_LOG(self):
+ # In order to allow to access from mock in test cases.
+ return self._logger
+
+ def __init__(self, get_response):
+ if not getattr(settings, "OPERATION_LOG_ENABLED", False):
+ raise MiddlewareNotUsed
+
+ self.get_response = get_response
+
+ # set configurations
+ _log_option = getattr(settings, "OPERATION_LOG_OPTIONS", {})
+ _available_methods = ['POST', 'GET', 'PUT', 'DELETE']
+ _methods = _log_option.get("target_methods", ['POST'])
+ self._default_format = (
+ "[%(client_ip)s] [%(domain_name)s]"
+ " [%(domain_id)s] [%(project_name)s]"
+ " [%(project_id)s] [%(user_name)s] [%(user_id)s]"
+ " [%(request_scheme)s] [%(referer_url)s] [%(request_url)s]"
+ " [%(message)s] [%(method)s] [%(http_status)s] [%(param)s]")
+ _default_ignored_urls = ['/js/', '/static/', '^/api/']
+ _default_mask_fields = ['password', 'current_password',
+ 'new_password', 'confirm_password']
+ self.target_methods = [x for x in _methods if x in _available_methods]
+ self.mask_fields = _log_option.get("mask_fields", _default_mask_fields)
+ self.format = _log_option.get("format", self._default_format)
+ self._logger = logging.getLogger('horizon.operation_log')
+
+ ignored_urls = _log_option.get("ignore_urls", _default_ignored_urls)
+ self._ignored_urls = [re.compile(url) for url in ignored_urls]
+
+ def __call__(self, request):
+ response = self.get_response(request)
+ response = self._process_response(request, response)
+ return response
+
+ def _process_response(self, request, response):
+ """Log user operation."""
+ log_format = self._get_log_format(request)
+ if not log_format:
+ return response
+
+ params = self._get_parameters_from_request(request)
+ # log a message displayed to user
+ messages = django_messages.get_messages(request)
+ result_message = None
+ if messages:
+ result_message = ', '.join('%s: %s' % (message.tags, message)
+ for message in messages)
+ elif 'action' in request.POST:
+ result_message = request.POST['action']
+ params['message'] = result_message
+ params['http_status'] = response.status_code
+
+ self.OPERATION_LOG.info(log_format, params)
+
+ return response
+
+ def process_exception(self, request, exception):
+ """Log error info when exception occurred."""
+ log_format = self._get_log_format(request)
+ if log_format is None:
+ return
+
+ params = self._get_parameters_from_request(request, True)
+ params['message'] = exception
+ params['http_status'] = '-'
+
+ self.OPERATION_LOG.info(log_format, params)
+
+ def _get_log_format(self, request):
+ """Return operation log format."""
+ user = getattr(request, 'user', None)
+ if not user:
+ return
+ if not request.user.is_authenticated:
+ return
+ method = request.method.upper()
+ if not (method in self.target_methods):
+ return
+ request_url = urlparse.unquote(request.path)
+ for rule in self._ignored_urls:
+ if rule.search(request_url):
+ return
+ return self.format
+
+ def _get_parameters_from_request(self, request, exception=False):
+ """Get parameters to log in OPERATION_LOG."""
+ user = request.user
+ referer_url = None
+ try:
+ referer_dic = urlparse.urlsplit(
+ urlparse.unquote(request.META.get('HTTP_REFERER')))
+ referer_url = referer_dic[2]
+ if referer_dic[3]:
+ referer_url += "?" + referer_dic[3]
+ if isinstance(referer_url, str):
+ referer_url = referer_url.decode('utf-8')
+ except Exception:
+ pass
+ request_url = urlparse.unquote(request.path)
+ if request.META['QUERY_STRING']:
+ request_url += '?' + request.META['QUERY_STRING']
+ return {
+ 'client_ip': request.META.get('REMOTE_ADDR', None),
+ 'domain_name': getattr(user, 'domain_name', None),
+ 'domain_id': getattr(user, 'domain_id', None),
+ 'project_name': getattr(user, 'project_name', None),
+ 'project_id': getattr(user, 'project_id', None),
+ 'user_name': getattr(user, 'username', None),
+ 'user_id': request.session.get('user_id', None),
+ 'request_scheme': request.scheme,
+ 'referer_url': referer_url,
+ 'request_url': request_url,
+ 'method': request.method if not exception else None,
+ 'param': self._get_request_param(request),
+ }
+
+ def _get_request_param(self, request):
+ """Change POST data to JSON string and mask data."""
+ params = {}
+ try:
+ params = request.POST.copy()
+ if not params:
+ params = json.loads(request.body)
+ except Exception:
+ pass
+ for key in params:
+ # replace a value to a masked characters
+ if key in self.mask_fields:
+ params[key] = '*' * 8
+
+ # when a file uploaded (E.g create image)
+ files = request.FILES.values()
+ if list(files):
+ filenames = ', '.join(
+ [up_file.name for up_file in files])
+ params['file_name'] = filenames
+
+ try:
+ return json.dumps(params, ensure_ascii=False)
+ except Exception:
+ return 'Unserializable Object'
diff --git a/pool/shard009/Python/0086188_profile_step.py b/pool/shard009/Python/0086188_profile_step.py
new file mode 100644
index 0000000000000000000000000000000000000000..318383624bcf5d5b2b75190d3b6ab7f9a32b72ad
--- /dev/null
+++ b/pool/shard009/Python/0086188_profile_step.py
@@ -0,0 +1,30 @@
+from behave import *
+import time
+from page_actions import *
+from page_objects import *
+
+email = 'ureport@webpro.com'
+password = 'password'
+
+@when(u'I login to u-report')
+def step_impl(context):
+ login_to_web_pro(context, email, password)
+ time.sleep(1)
+
+@when(u'I go to the profile page')
+def step_impl(context):
+ time.sleep(2)
+ go_to_profile_page(context)
+
+@when(u'I deactivate my account')
+def step_impl(context):
+ deactivate_profile(context.browser)
+ time.sleep(2)
+ assert sorry_to_go_notification_present(context.browser), 'sorry_to_see_you_go not found'
+
+
+@then(u'I shall not be able to login')
+def step_impl(context):
+ login_to_web_pro(context, email, password)
+ time.sleep(1)
+ assert no_user_notification_present(context.browser, email), 'No registered user notification not found'
diff --git a/pool/shard009/Python/0086193_web-scraper.py b/pool/shard009/Python/0086193_web-scraper.py
new file mode 100644
index 0000000000000000000000000000000000000000..887b60bd40e19396163c1b6c39d9d6157ea0d2b7
--- /dev/null
+++ b/pool/shard009/Python/0086193_web-scraper.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+
+import re
+try:
+ from urllib.request import urlopen
+except ImportError:
+ from urllib2 import urlopen
+
+import sqlite3
+from vtfunc import TableFunction
+
+
+class Scraper(TableFunction):
+ params = ['url']
+ columns = ['href', 'description']
+ name = 'scraper'
+
+ def initialize(self, url):
+ self._iter = re.finditer(
+ ']+?href="([^\"]+?)"[^\>]*?>([^\<]+?)',
+ urlopen(url).read().decode('utf-8'))
+
+ def iterate(self, idx):
+ return next(self._iter).groups()
+
+
+conn = sqlite3.connect(':memory:')
+
+# Register the module with the connection.
+Scraper.register(conn)
+
+# Scrape the HackerNews front-page and query for the 3 links with the longest
+# descriptions.
+cursor = conn.execute(
+ 'SELECT * FROM scraper(?) '
+ 'ORDER BY length(description) DESC LIMIT 3;',
+ ('https://news.ycombinator.com',))
+for href, desc in cursor.fetchall():
+ print(desc, ':', href)
+
+
+# Create a separate table that stores a list of URLs we need to scrape. Since
+# this is a relational database, we can feed the url-list to our table-function
+# quite easily.
+conn.execute('CREATE TABLE url_list (url TEXT PRIMARY KEY);')
+conn.execute('INSERT INTO url_list (url) VALUES (?), (?), (?);', (
+ 'http://docs.peewee-orm.com/en/latest/',
+ 'http://github.com/coleifer',
+ 'https://news.ycombinator.com'))
+
+query = conn.execute('SELECT s.url, href, description FROM '
+ 'url_list AS s, scraper(s.url)')
+for url, href, description in query:
+ print(url, ' -- ', description, ':', href)
diff --git a/pool/shard009/Python/0086197_test_kernel.py b/pool/shard009/Python/0086197_test_kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..da13b521956d8da1556f0aa45365e1f9f222a88e
--- /dev/null
+++ b/pool/shard009/Python/0086197_test_kernel.py
@@ -0,0 +1,27 @@
+import pytest
+from srv.salt._modules import kernel
+from mock import patch, MagicMock
+
+def test_boot_image():
+ data = 'BOOT_IMAGE=/boot/vmlinuz-4.1.12-1-default'
+ result = kernel._boot_image(data)
+ assert result == '/boot/vmlinuz-4.1.12-1-default'
+
+@patch('os.path.isfile')
+def test_query_command_succeeds(mock_isfile):
+ mock_isfile.return_value = True
+ result = kernel._query_command("afile")
+ assert result == ['/bin/rpm', '-qf', 'afile']
+
+@patch('os.path.isfile')
+def test_query_command_fails(mock_isfile):
+ mock_isfile.return_value = False
+ result = kernel._query_command("afile")
+ assert result == None
+
+@patch('os.path.isfile')
+def test_query_command_fails_with_no_file(mock_isfile):
+ mock_isfile.return_value = True
+ result = kernel._query_command("")
+ assert result == None
+
diff --git a/pool/shard009/Python/0086200_DeleteScriptAction.py b/pool/shard009/Python/0086200_DeleteScriptAction.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5c3b040d42f1ebc9c8db3cce88eed3d2a909a90
--- /dev/null
+++ b/pool/shard009/Python/0086200_DeleteScriptAction.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+
+"""
+***************************************************************************
+ DeleteScriptAction.py
+ ---------------------
+ Date : August 2012
+ Copyright : (C) 2012 by Victor Olaya
+ Email : volayaf at gmail dot com
+***************************************************************************
+* *
+* This program is free software; you can redistribute it and/or modify *
+* it under the terms of the GNU General Public License as published by *
+* the Free Software Foundation; either version 2 of the License, or *
+* (at your option) any later version. *
+* *
+***************************************************************************
+"""
+
+__author__ = 'Victor Olaya'
+__date__ = 'August 2012'
+__copyright__ = '(C) 2012, Victor Olaya'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+import os
+
+from PyQt4.QtGui import *
+
+from processing.gui.ContextAction import ContextAction
+
+from processing.algs.r.RAlgorithm import RAlgorithm
+from processing.script.ScriptAlgorithm import ScriptAlgorithm
+
+
+class DeleteScriptAction(ContextAction):
+
+ SCRIPT_PYTHON = 0
+ SCRIPT_R = 1
+
+ def __init__(self, scriptType):
+ self.name = 'Delete script'
+ self.scriptType = scriptType
+
+ def isEnabled(self):
+ if self.scriptType == self.SCRIPT_PYTHON:
+ return isinstance(self.alg, ScriptAlgorithm) and self.alg.allowEdit
+ elif self.scriptType == self.SCRIPT_R:
+ return isinstance(self.alg, RAlgorithm)
+
+ def execute(self, alg):
+ reply = QMessageBox.question(None, 'Confirmation',
+ 'Are you sure you want to delete this script?',
+ QMessageBox.Yes | QMessageBox.No,
+ QMessageBox.No)
+ if reply == QMessageBox.Yes:
+ os.remove(self.alg.descriptionFile)
+ if self.scriptType == self.SCRIPT_PYTHON:
+ self.toolbox.updateProvider('script')
+ elif self.scriptType == self.SCRIPT_R:
+ self.toolbox.updateProvider('r')
diff --git a/pool/shard009/Python/0086203_range.py b/pool/shard009/Python/0086203_range.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ea7749c6f8d3ada2980ac99f9a53ec3a40796a4
--- /dev/null
+++ b/pool/shard009/Python/0086203_range.py
@@ -0,0 +1,31 @@
+"""
+File Name: Ch2_Ex7.py
+Developer: Justin A. Shores
+Date Last Modified: 09/02/2014
+Description: Consider range(a, b) are the following statements true or false
+ value of a is included in the range
+ value of b is included in the range
+ The answer should be a-true and b-false but here is a program that
+ proves it!
+"""
+
+# set range values
+val_a = 1
+val_b = 2
+
+# boolean values for true false statements
+bool_a = False
+bool_b = False
+
+# cycle range
+for x in range(val_a, val_b):
+ if x == val_a:
+ bool_a = True
+
+ if x == val_b:
+ bool_b = True
+
+# print statements as true or false
+print("Statements and Answers:")
+print("The value of 'a' is included in the range is: " + str(bool_a))
+print("The value of 'b' is included in the range is: " + str(bool_b))
diff --git a/pool/shard009/Python/0086204_system_email.py b/pool/shard009/Python/0086204_system_email.py
new file mode 100644
index 0000000000000000000000000000000000000000..68a3dd55c6e53947d2733d7fbb4427e2f3fd96fb
--- /dev/null
+++ b/pool/shard009/Python/0086204_system_email.py
@@ -0,0 +1,174 @@
+# -*- coding: utf-8 -*-
+##
+## This file is part of Invenio.
+## Copyright (C) 2009, 2010, 2011, 2013, 2014 CERN.
+##
+## Invenio 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.
+##
+## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
+## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+"""
+Provide a "ticket" interface with Email.
+This is a subclass of BibCatalogSystem
+"""
+
+
+import datetime
+from time import mktime
+import invenio.legacy.webuser
+from invenio.utils.shell import escape_shell_arg
+from invenio.legacy.bibcatalog.system import BibCatalogSystem
+from invenio.ext.email import send_email
+from invenio.ext.logging import register_exception
+
+EMAIL_SUBMIT_CONFIGURED = False
+import invenio.config
+if hasattr(invenio.config, 'CFG_BIBCATALOG_SYSTEM') and invenio.config.CFG_BIBCATALOG_SYSTEM == "EMAIL":
+ if hasattr(invenio.config, 'CFG_BIBCATALOG_SYSTEM_EMAIL_ADDRESS'):
+ EMAIL_SUBMIT_CONFIGURED = True
+ FROM_ADDRESS = invenio.config.CFG_SITE_SUPPORT_EMAIL
+ TO_ADDRESS = invenio.config.CFG_BIBCATALOG_SYSTEM_EMAIL_ADDRESS
+
+
+class BibCatalogSystemEmail(BibCatalogSystem):
+ #BIBCATALOG_RT_SERVER = "" #construct this by http://user:password@RT_URL
+
+ def check_system(self, uid=None):
+ """return an error string if there are problems"""
+
+ ret = ''
+ if not EMAIL_SUBMIT_CONFIGURED:
+ ret = "Please configure bibcatalog email sending in CFG_BIBCATALOG_SYSTEM and CFG_BIBCATALOG_SYSTEM_EMAIL_ADDRESS"
+ return ret
+
+ def ticket_search(self, uid, recordid=-1, subject="", text="", creator="", owner="", \
+ date_from="", date_until="", status="", priority="", queue=""):
+ """Not implemented."""
+
+ raise NotImplementedError
+
+ def ticket_submit(self, uid=None, subject="", recordid=-1, text="", queue="", priority="", owner="", requestor=""):
+ """creates a ticket. Returns ticket_id on success, otherwise None"""
+
+ if not EMAIL_SUBMIT_CONFIGURED:
+ register_exception(stream='warning',
+ subject='bibcatalog email not configured',
+ prefix="please configure bibcatalog email sending in CFG_BIBCATALOG_SYSTEM and CFG_BIBCATALOG_SYSTEM_EMAIL_ADDRESS")
+
+ ticket_id = self._get_ticket_id()
+ priorityset = ""
+ queueset = ""
+ requestorset = ""
+ ownerset = ""
+ recidset = " cf-recordID: %s\n" % recordid
+ textset = ""
+ subjectset = ""
+ if subject:
+ subjectset = 'ticket #%s - %s' % (ticket_id, subject)
+ if priority:
+ priorityset = " priority: %s\n" % priority
+ if queue:
+ queueset = " queue: %s\n" % queue
+ if requestor:
+ requestorset = " requestor: %s\n" % requestor
+ if owner:
+ ownerprefs = invenio.legacy.webuser.get_user_preferences(owner)
+ if "bibcatalog_username" in ownerprefs:
+ owner = ownerprefs["bibcatalog_username"]
+ ownerset = " owner: %s\n" % owner
+
+ textset += ownerset + requestorset + recidset + queueset + priorityset + '\n'
+
+ textset += text + '\n'
+
+ ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, content=textset)
+ if ok:
+ return ticket_id
+ return None
+
+ def ticket_comment(self, uid, ticketid, comment):
+ """ Comment on ticket with given ticketid"""
+
+ subjectset = 'ticket #' + ticketid + ' - Comment ...'
+ textset = '...\n\n*Comment on ticket #' + ticketid + '\nComment:' + comment
+ ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset)
+ if ok:
+ return 1
+ return 0
+
+
+ def ticket_assign(self, uid, ticketid, to_user):
+ """ Re-assign existing ticket with given ticketid to user to_user"""
+
+ subjectset = 'ticket #' + ticketid + ' - Re-assign ...'
+ textset = '...\n\n*Please re-assigning ticket #' + ticketid + ' to ' + to_user
+ ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset)
+ if ok:
+ return 1
+ return 0
+
+ def ticket_set_attribute(self, uid, ticketid, attribute, new_value):
+ """ Request to set attribute to new value on ticket with given ticketid"""
+
+ subjectset = 'ticket #' + ticketid + ' - Attribute Update ...'
+ textset = '...\n\n*Please modify attribute:' + attribute + ' to:' + new_value + ' on ticket:' + ticketid
+ ok = send_email(fromaddr=FROM_ADDRESS, toaddr=TO_ADDRESS, subject=subjectset, header='Hello,\n\n', content=textset)
+ if ok:
+ return 1
+ return 0
+
+ def ticket_get_attribute(self, uid, ticketid, attribute):
+ """Not implemented."""
+
+ raise NotImplementedError
+
+ def ticket_get_info(self, uid, ticketid, attributes = None):
+ """Not implemented."""
+
+ raise NotImplementedError
+
+ def _str_base(self, num, base, numerals = '0123456789abcdefghijklmnopqrstuvwxyz'):
+ """ Convert number to base (2 to 36) """
+
+ if base < 2 or base > len(numerals):
+ raise ValueError("str_base: base must be between 2 and %i" % len(numerals))
+
+ if num == 0:
+ return '0'
+
+ if num < 0:
+ sign = '-'
+ num = -num
+ else:
+ sign = ''
+
+ result = ''
+ while num:
+ result = numerals[num % (base)] + result
+ num //= base
+
+ return sign + result
+
+
+ def _get_ticket_id(self):
+ """ Return timestamp in seconds since the Epoch converted to base36 """
+
+ now = datetime.datetime.now()
+ t = mktime(now.timetuple())+1e-6*now.microsecond
+
+ t_str = str("%.6f" % t)
+ t1, t2 = t_str.split('.')
+ t_str = t1 + t2
+
+ #return base64.encodestring(t_str).strip()
+ return self._str_base(int(t_str), 36)
diff --git a/pool/shard009/Python/0086206_setup.py b/pool/shard009/Python/0086206_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d4d31bb59e4b1059d0d15c96f5b619a4efedda0
--- /dev/null
+++ b/pool/shard009/Python/0086206_setup.py
@@ -0,0 +1,73 @@
+"""
+Based entirely on Django's own ``setup.py``.
+"""
+import os
+from distutils.command.install import INSTALL_SCHEMES
+from distutils.core import setup
+import setuptools
+
+def fullsplit(path, result=None):
+ """
+ Split a pathname into components (the opposite of os.path.join) in a
+ platform-neutral way.
+ """
+ if result is None:
+ result = []
+ head, tail = os.path.split(path)
+ if head == '':
+ return [tail] + result
+ if head == path:
+ return result
+ return fullsplit(head, [tail] + result)
+
+# Tell distutils to put the data_files in platform-specific installation
+# locations. See here for an explanation:
+# http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb
+for scheme in INSTALL_SCHEMES.values():
+ scheme['data'] = scheme['purelib']
+
+# Compile the list of packages available, because distutils doesn't have
+# an easy way to do this.
+packages, data_files = [], []
+root_dir = os.path.dirname(__file__)
+fts_dir = os.path.join(root_dir, 'fts')
+pieces = fullsplit(root_dir)
+if pieces[-1] == '':
+ len_root_dir = len(pieces) - 1
+else:
+ len_root_dir = len(pieces)
+
+for dirpath, dirnames, filenames in os.walk(fts_dir):
+ # Ignore dirnames that start with '.'
+ for i, dirname in enumerate(dirnames):
+ if dirname.startswith('.'): del dirnames[i]
+ if '__init__.py' in filenames:
+ packages.append('.'.join(fullsplit(dirpath)[len_root_dir:]))
+ elif filenames:
+ data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])
+
+# Dynamically calculate the version based on fts.VERSION
+version_tuple = (0, 1, 'pre')
+if version_tuple[2] is not None:
+ version = "%d.%d_%s" % version_tuple
+else:
+ version = "%d.%d" % version_tuple[:2]
+
+setup(
+ name = 'fts',
+ version = version,
+ description = 'Deneric Full Text Search engine for Django',
+ author = 'German M. Bravo',
+ author_email = 'german.mb@gmail.com',
+ url = 'http://code.google.com/p/django-fts/',
+ packages = packages,
+ data_files = data_files,
+ classifiers = ['Development Status :: 1 - Beta',
+ 'Environment :: Web Environment',
+ 'Framework :: Django',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: BSD License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Utilities'],
+)
diff --git a/pool/shard009/Python/0086207_urls.py b/pool/shard009/Python/0086207_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..c13afd64a2fed5f6464203c1c452ee3dbfcc6876
--- /dev/null
+++ b/pool/shard009/Python/0086207_urls.py
@@ -0,0 +1,14 @@
+import views
+from django.conf.urls import url
+
+
+urlpatterns = [
+ url(r'customer/(\d*)', views.CustomerDetail.as_view()),
+ url(r'customer', views.CustomerList.as_view()),
+ url(r'delivery_information/(\d*)', views.DeliveryInformationDetail.as_view()),
+ url(r'delivery_information', views.DeliveryInformationList.as_view()),
+ url(r'complaint/(\d*)', views.ComplaintDetail.as_view()),
+ url(r'complaint', views.ComplaintList.as_view()),
+ url(r'order/(\d*)', views.OrderDetail.as_view()),
+ url(r'order', views.OrderList.as_view()),
+]
diff --git a/pool/shard009/Python/0086212_init__.py b/pool/shard009/Python/0086212_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad405fe4a10ad24fe3336d0c48b73668cfef6f2
--- /dev/null
+++ b/pool/shard009/Python/0086212_init__.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""
+ logbook.testsuite
+ ~~~~~~~~~~~~~~~~~
+
+ The logbook testsuite.
+
+ :copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
+ :license: BSD, see LICENSE for more details.
+"""
+import sys
+
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+
+import logbook
+
+_skipped_modules = []
+_missing = object()
+_func_ident = lambda f: f
+_func_none = lambda f: None
+
+
+class LogbookTestSuite(unittest.TestSuite):
+
+ def run(self, result):
+ try:
+ return unittest.TestSuite.run(self, result)
+ finally:
+ sys.stderr.write('\n')
+ for mod in _skipped_modules:
+ msg = '*** Failed to import %s, tests skipped.\n' % mod
+ sys.stderr.write(msg)
+
+
+class LogbookTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self.log = logbook.Logger('testlogger')
+
+
+def make_fake_mail_handler(**kwargs):
+ class FakeMailHandler(logbook.MailHandler):
+ mails = []
+
+ def get_connection(self):
+ return self
+
+ def close_connection(self, con):
+ pass
+
+ def sendmail(self, fromaddr, recipients, mail):
+ self.mails.append((fromaddr, recipients, mail))
+
+ kwargs.setdefault('level', logbook.ERROR)
+ return FakeMailHandler('foo@example.com', ['bar@example.com'], **kwargs)
+
+
+def skip_if(condition):
+ if condition:
+ return _func_ident
+ else:
+ return _func_none
+
+
+def require(name):
+ if name in _skipped_modules:
+ return _func_none
+ try:
+ __import__(name)
+ except ImportError:
+ _skipped_modules.append(name)
+ return _func_none
+ return _func_ident
+
+
+def missing(name):
+ def decorate(f):
+ def wrapper(*args, **kwargs):
+ old = sys.modules.get(name, _missing)
+ sys.modules[name] = None
+ try:
+ f(*args, **kwargs)
+ finally:
+ if old is _missing:
+ del sys.modules[name]
+ else:
+ sys.modules[name] = old
+ return wrapper
+ return decorate
diff --git a/pool/shard009/Python/0086215_screen.py b/pool/shard009/Python/0086215_screen.py
new file mode 100644
index 0000000000000000000000000000000000000000..da5ed1e44a183b9b8a7ca826ac34d63ddbf0c86b
--- /dev/null
+++ b/pool/shard009/Python/0086215_screen.py
@@ -0,0 +1,251 @@
+"""
+
+This file is part of XDEMO
+
+Copyright(c)
+https://github.com/warp1337/xdemo
+
+This file may be licensed under the terms of the
+GNU Lesser General Public License Version 3 (the ``LGPL''),
+or (at your option) any later version.
+
+Software distributed under the License is distributed
+on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
+express or implied. See the LGPL for the specific language
+governing rights and limitations.
+
+You should have received a copy of the LGPL along with this
+program. If not, go to http://www.gnu.org/licenses/lgpl.html
+or write to the Free Software Foundation, Inc.,
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+The development of this software was supported by the
+Excellence Cluster EXC 277 Cognitive Interaction Technology.
+The Excellence Cluster EXC 277 is a grant of the Deutsche
+Forschungsgemeinschaft (DFG) in the context of the German
+Excellence Initiative.
+
+Authors: Florian Lier
+@techfak.uni-bielefeld.de
+
+This file was part of: https://github.com/Christophe31/screenutils
+and has been altered by the author. Thanks for this great Screen class!
+
+"""
+
+# STD
+import os
+import sys
+try:
+ from commands import getoutput
+except:
+ from subprocess import getoutput
+from os import system
+from time import sleep
+from os.path import getsize
+from threading import Thread
+
+# SELF
+from xdemo.utilities.operatingsystem import is_file
+from xdemo.screenutils.errors import ScreenNotFoundError
+from xdemo.utilities.operatingsystem import get_operating_system
+
+
+def tailf(file_):
+ """Each value is content added to the log file since last value return"""
+ last_size = getsize(file_)
+ while True:
+ cur_size = getsize(file_)
+ if (cur_size != last_size):
+ f = open(file_, 'r')
+ f.seek(last_size if cur_size > last_size else 0)
+ text = f.read()
+ f.close()
+ last_size = cur_size
+ yield text
+ else:
+ yield ""
+
+
+def list_screens():
+ """List all the existing screens and build a Screen instance for each
+ """
+ list_cmd = "screen -ls"
+ return [
+ Screen(".".join(l.split(".")[1:]).split("\t")[0])
+ for l in getoutput(list_cmd).split('\n')
+ if "\t" in l and ".".join(l.split(".")[1:]).split("\t")[0]
+ ]
+
+
+class Screen(object):
+ """Represents a gnu-screen object::
+
+ >>> s=Screen("screenName", initialize=True)
+ >>> s.name
+ 'screenName'
+ >>> s.exists
+ True
+ >>> s.state
+ >>> s.send_commands("man -k keyboard")
+ >>> s.kill()
+ >>> s.exists
+ False
+ """
+
+ def __init__(self, name, _info_dict, log):
+ self.name = name
+ self.log = log
+ self._id = None
+ self._status = None
+ self.logs = None
+ self._logfilename = None
+ self.info_dict = _info_dict
+ self.os_system = get_operating_system()
+ self.runtimeenvironment = None
+
+ @property
+ def id(self):
+ """return the identifier of the screen as string"""
+ if not self._id:
+ self._set_screen_infos()
+ return self._id
+
+ @property
+ def status(self):
+ """return the status of the screen as string"""
+ self._set_screen_infos()
+ return self._status
+
+ @property
+ def exists(self):
+ """Tell if the screen session exists or not."""
+ # Parse the screen -ls call, to find if the screen exists or not.
+ # " 28062.G.Terminal (Detached)"
+ lines = getoutput("screen -ls").split('\n')
+ if self.name in [".".join(l.split(".")[1:]).split("\t")[0] for l in lines if self.name in l]:
+ return self.name
+ else:
+ return None
+
+ def enable_logs(self, filename=None):
+ if filename is None:
+ filename = self.name
+ self._screen_commands("logfile " + filename, "log on ")
+ self._screen_commands("logfile flush 0")
+ self._logfilename = filename
+ open(filename, 'w+')
+ self.logs = tailf(filename)
+
+ def disable_logs(self, remove_logfile=False):
+ self._screen_commands("log off")
+ if remove_logfile:
+ system('rm ' + self._logfilename)
+ self.logs = None
+
+ def initialize(self, _environment=None):
+ """initialize a screen, if does not exists yet"""
+ if _environment is None:
+ self.log.error("[screen] no environment file provided")
+ sys.exit(1)
+
+ # Double check existence
+ if is_file(_environment):
+ pass
+ else:
+ self.log.error("[screen] '%s' not found" % _environment)
+ sys.exit(1)
+
+ self.runtimeenvironment = _environment
+
+ if not self.exists:
+ self._id = None
+ # Detach the screen once attached, on a new tread.
+ # Thread(target=self._delayed_detach).start()
+ # Detach immediately
+ # support Unicode (-U),
+ # attach to a new/existing named screen (-R).
+ self.log.info("[screen] '%s' in env %s" % (self.name, os.path.basename(self.runtimeenvironment)))
+ source_cmd = ". %s && " % self.runtimeenvironment
+ system(source_cmd + 'stdbuf -oL' + ' screen -U -dmS ' + self.name)
+
+ def interrupt(self):
+ """Insert CTRL+C in the screen session"""
+ self._screen_commands("eval \"stuff \\003\"")
+
+ def kill(self):
+ """Kill the screen applications then close the screen"""
+ self._screen_commands('quit')
+
+ def detach(self):
+ """detach the screen"""
+ self._check_exists()
+ system("screen -d " + self.id)
+
+ def send_commands(self, *commands):
+ """send commands to the active gnu-screen"""
+ self._check_exists()
+ for command in commands:
+ self._screen_commands('stuff "' + command + '" ',
+ 'eval "stuff \\015"')
+
+ def add_user_access(self, unix_user_name):
+ """allow to share your session with an other unix user"""
+ self._screen_commands('multiuser on', 'acladd ' + unix_user_name)
+
+ def _screen_commands(self, *commands):
+ """allow to insert generic screen specific commands
+ a glossary of the existing screen command in `man screen`"""
+ self._check_exists()
+ for command in commands:
+ # Runtime Environment has been set in the initialize step
+ final_cmd = 'screen -x ' + self.id + ' -X ' + command
+ system(final_cmd)
+ sleep(0.05)
+
+ def clean_log(self):
+ clean_log = "echo '' > %s" % self._logfilename.strip()
+ system(clean_log)
+
+ def _check_exists(self, message="Error code: 404."):
+ """check whereas the screen exist. if not, raise an exception"""
+ session = self.exists
+ if session is not None:
+ pass
+ # raise ScreenNotFoundError(message, self.name)
+ else:
+ self.log.error("[screen] '%s' could not be found" % self.name)
+
+ def _set_screen_infos(self):
+ """set the screen information related parameters"""
+ if self.exists:
+ line = ""
+ for l in getoutput("screen -ls").split("\n"):
+ if (
+ self.name in l and
+ self.name == ".".join(
+ l.split('\t')[1].split('.')[1:]) in l):
+ line = l
+ if not line:
+ # raise ScreenNotFoundError("While getting info.", self.name)
+ self.log.error("[screen] '%s' could not be found", self.name)
+ self._status = None
+ return self._status
+ infos = line.split('\t')[1:]
+ self._id = infos[0].split('.')[0]
+ if len(infos) == 3:
+ self._date = infos[1][1:-1]
+ self._status = infos[2][1:-1]
+ else:
+ self._status = infos[1][1:-1]
+ else:
+ self.log.error("[screen] '%s' does not exist", self.name)
+ self._status = None
+ return self._status
+
+ def _delayed_detach(self):
+ sleep(0.1)
+ self.detach()
+
+ def __repr__(self):
+ return "<%s '%s'>" % (self.__class__.__name__, self.name)
diff --git a/pool/shard009/Python/0086217_echo-server.py b/pool/shard009/Python/0086217_echo-server.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b865b5fc615396c904b95c53904bb3cb6e51603
--- /dev/null
+++ b/pool/shard009/Python/0086217_echo-server.py
@@ -0,0 +1,64 @@
+import time
+from time import strftime, gmtime
+import math
+import datetime
+import paho.mqtt.client as mqtt
+
+buffer = ""
+v1, v2 = True, True
+d1, d2, d3 = 0.0, 0.0, 0.0
+inc = 0.0
+tim = 1
+
+def getd1():
+ return str(d1)
+
+def getd2():
+ return str(d2)
+
+def getd3():
+ return str(d3)
+
+def getv1():
+ return str(v1)
+
+def getv2():
+ return str(v2)
+
+def gettime():
+ return strftime("%a, %d %b %Y %H:%M:%S", gmtime())
+
+def packmessage():
+ ret = str("{ \"time\": \"" + gettime() + "\", \"d1\": " + getd1() + ", \"d2\": " + getd2() + ", \"d3\": " + getd3() + ", \"v1\": \"" + getv1() + "\", \"v2\": \"" + getv2() + "\" }").encode()
+ return ret
+
+def update(d1, d2, d3, v1, v2, inc):
+
+ #t = datetime.datetime.now().timetuple()[5]
+ t = inc
+ d1 = str(round((math.sin(t) + 1)*400, 2))
+ d2 = str(round((math.cos(t) + 1)*400, 2))
+ d3 = str(round((math.tan(t) + 1)*400, 2))
+
+ if(float(d3) >= 1000):
+ d3 = 0.0
+ v1 = False
+ v2 = False
+ else:
+ v1 = True
+ v2 = True
+
+ return d1, d2, d3, v1, v2
+
+##INIT CLIENT
+client = mqtt.Client()
+client.connect("localhost")
+
+while True:
+
+ d1, d2, d3, v1, v2 = update(d1, d2, d3, v1, v2, inc)
+ inc += 0.1
+ buffer = packmessage()
+ print(buffer)
+ client.publish("dev/test", buffer)
+ time.sleep(0.25)
diff --git a/pool/shard009/Python/0086218_reprojectDB.py b/pool/shard009/Python/0086218_reprojectDB.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a8bb98d72f3db7c87f8649aff15bad3cff3459
--- /dev/null
+++ b/pool/shard009/Python/0086218_reprojectDB.py
@@ -0,0 +1,73 @@
+import arcpy
+import sys
+from os.path import join
+
+arcpy.env.geographicTransformations = 'NAD_1983_to_WGS_1984_5'
+
+try:
+ base_folder = sys.argv[1]
+except:
+ base_folder = raw_input('base folder: ')
+
+print('creating new database')
+new_db = base_folder + 'QueryLayers_NEW.gdb'
+old_db = base_folder + 'QueryLayers.gdb'
+new_ref_db = base_folder + 'ReferenceData_NEW.gdb'
+old_ref_db = base_folder + 'ReferenceData.gdb'
+if arcpy.Exists(new_db):
+ arcpy.Delete_management(new_db)
+arcpy.CreateFileGDB_management(base_folder, 'QueryLayers_NEW.gdb')
+if arcpy.Exists(new_ref_db):
+ arcpy.Delete_management(new_ref_db)
+arcpy.CreateFileGDB_management(base_folder, 'ReferenceData_NEW.gdb')
+
+relationship_class_names = set([])
+arcpy.env.workspace = old_db
+print('FEATURE CLASSES')
+for fc in arcpy.ListFeatureClasses():
+ print(fc)
+
+ arcpy.Project_management(fc, join(new_db, fc), arcpy.SpatialReference(3857))
+ relationship_class_names.update(arcpy.Describe(fc).relationshipClassNames)
+
+print('TABLES')
+for tbl in arcpy.ListTables():
+ print(tbl)
+
+ arcpy.CopyRows_management(tbl, join(new_db, tbl))
+ relationship_class_names.update(arcpy.Describe(tbl).relationshipClassNames)
+
+print('RELATIONSHIP CLASSES')
+card_lu = {'OneToOne': 'ONE_TO_ONE',
+ 'OneToMany': 'ONE_TO_MANY',
+ 'ManyToMany': 'MANY_TO_MANY'}
+arcpy.env.workspace = new_db
+for rc in relationship_class_names:
+ print(rc)
+
+ rc_desc = arcpy.Describe(join(old_db, rc))
+
+ keys = {}
+ for k in rc_desc.originClassKeys:
+ keys[k[1]] = k[0]
+ if len(rc_desc.destinationClassKeys) > 0:
+ print('DESTINATION KEYS!!!')
+ arcpy.CreateRelationshipClass_management(join(new_db, rc_desc.originClassNames[0]),
+ join(new_db, rc_desc.destinationClassNames[0]),
+ rc,
+ 'SIMPLE',
+ rc_desc.forwardPathLabel,
+ rc_desc.backwardPathLabel,
+ rc_desc.notification.upper(),
+ card_lu[rc_desc.cardinality],
+ 'NONE',
+ keys['OriginPrimary'],
+ keys['OriginForeign'])
+
+print('REFERENCE DATA')
+arcpy.env.workspace = old_ref_db
+for r in new_ref_db:
+ print(r)
+ arcpy.Project_management(r, join(new_ref_db, fc), arcpy.SpatialReference(3857))
+
+print('done')
diff --git a/pool/shard009/Python/0086219_test_cli_init.py b/pool/shard009/Python/0086219_test_cli_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc91747205a0c1de1fd9790c4db664125d6a2d60
--- /dev/null
+++ b/pool/shard009/Python/0086219_test_cli_init.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+from tempfile import gettempdir
+
+from mock import patch
+import ruamel.yaml
+
+from chanjo.testutils import FakeZipFile, fake_urlretrieve
+
+
+def test_init_demo(tmpdir, invoke_cli):
+ # GIVEN empty directory
+ assert tmpdir.listdir() == []
+ # WHEN setting up demo on CLI
+ target_dir = tmpdir.join('chanjo-demo')
+ target_path = str(target_dir)
+ result = invoke_cli(['init', '--demo', target_path])
+ # THEN is should work and place 4 demo files + 1 sqlite db + 1 config
+ assert result.exit_code == 0
+ assert len(target_dir.listdir()) == (4 + 1 + 1)
+
+
+@patch('urllib.request.urlretrieve', fake_urlretrieve)
+@patch('zipfile.ZipFile', FakeZipFile)
+@patch('click.confirm', lambda param: True)
+def test_init_bootstrap(tmpdir, invoke_cli):
+ # GIVEN empty dir
+ assert tmpdir.listdir() == []
+ # WHEN boostrapping chanjo
+ result = invoke_cli(['init', str(tmpdir)])
+ # THEN it should place 2 + 1 (BED, DB, config) files in the target dir
+ assert result.exit_code == 0
+ assert len(tmpdir.listdir()) == 3
+
+
+@patch('click.confirm', lambda param: False)
+@patch('click.prompt', lambda param: "{}/cov.sqlite3".format(gettempdir()))
+def test_init_no_bootstrap(tmpdir, invoke_cli):
+ # GIVEN ...
+ # WHEN opting out of bootstrap
+ result = invoke_cli(['init', str(tmpdir)])
+ # THEN it should work with custom database URI
+ assert result.exit_code == 0
+ conf_path = tmpdir.join('chanjo.yaml')
+ with open(str(conf_path), 'r') as handle:
+ data = ruamel.yaml.safe_load(handle)
+ assert 'coverage.sqlite3' in data['database']
diff --git a/pool/shard009/Python/0086224_freeform_layout_wdg.py b/pool/shard009/Python/0086224_freeform_layout_wdg.py
new file mode 100644
index 0000000000000000000000000000000000000000..894bcea9d070a509fa567e84bfbefa5251ccf54f
--- /dev/null
+++ b/pool/shard009/Python/0086224_freeform_layout_wdg.py
@@ -0,0 +1,274 @@
+###########################################################
+#
+# Copyright (c) 2009, Southpaw Technology
+# All Rights Reserved
+#
+# PROPRIETARY INFORMATION. This software is proprietary to
+# Southpaw Technology, and is not to be reproduced, transmitted,
+# or disclosed in any way without written permission.
+#
+#
+#
+__all__ = ["FreeFormLayoutWdg"]
+
+from pyasm.common import Common, jsonloads
+from pyasm.search import Search, SearchKey
+from pyasm.web import DivWdg, Table, WebContainer
+from pyasm.widget import WidgetConfig
+
+from tactic.ui.common import BaseRefreshWdg
+from tactic.ui.widget import ActionButtonWdg
+
+import random
+
+
+
+class FreeFormLayoutWdg(BaseRefreshWdg):
+
+ ARGS_KEYS = {
+ 'search_type': {
+ 'description': 'Search Type for Free Form layout',
+ 'type': 'TextWdg',
+ 'order': 1,
+ 'category': 'Options'
+ },
+ 'view': {
+ 'description': 'Freeform view',
+ 'type': 'TextWdg',
+ 'order': 1,
+ 'category': 'Options'
+ },
+ 'css': {
+ 'description': 'Top level style',
+ 'type': 'TextAreaWdg',
+ 'order': 2,
+ 'category': 'Options'
+ },
+ }
+
+
+
+
+
+ def get_input_value(my, name):
+ value = my.kwargs.get(name)
+ if value == None:
+ web = WebContainer.get_web()
+ value = web.get_form_value(name)
+
+ return value
+
+
+
+ def get_default_background(my):
+ return DivWdg().get_color("background")
+
+
+
+ def get_display(my):
+
+ category = "FreeformWdg"
+ view = my.get_input_value("view")
+
+ sobject = my.get_input_value("sobject")
+ if not sobject and my.sobjects:
+ sobject = my.sobjects[0]
+ if not view:
+ view = 'freeform'
+
+ if sobject:
+ search_key = sobject.get_search_key()
+ search_type = sobject.get_base_search_type()
+
+ else:
+ search_key = my.get_input_value("search_key")
+ search_type = my.get_input_value("search_type")
+
+ if sobject:
+ pass
+ elif search_key:
+ sobject = Search.get_by_search_key(search_key)
+ elif search_type:
+ search = Search(search_type)
+ search.add_limit(1)
+ sobject = search.get_sobject()
+ else:
+ sobject = None
+
+
+ top = DivWdg()
+ top.add_class("spt_freeform_top")
+
+
+ search = Search("config/widget_config")
+ search.add_filter("search_type", search_type)
+ search.add_filter("view", view)
+ config_sobj = search.get_sobject()
+ if config_sobj:
+ config_xml = config_sobj.get_value("config")
+ else:
+ config_xml = ""
+
+ if not config_xml:
+ top.add("No definition found")
+ return top
+
+ config = WidgetConfig.get(view=view, xml=config_xml)
+ view_attrs = config.get_view_attributes()
+
+
+ bgcolor = view_attrs.get("bgcolor")
+ if not bgcolor:
+ bgcolor = my.get_default_background()
+
+ if bgcolor:
+ top.add_style("background", bgcolor)
+
+
+ # draw the layout
+ freeform_layout = my.get_canvas_display(search_type, view, config, sobject)
+ top.add(freeform_layout)
+
+ return top
+
+
+ def get_canvas_display(my, search_type, view, config, sobject):
+
+ top = DivWdg()
+ top.add_class("spt_freeform_layout_top")
+ my.set_as_panel(top)
+ #top.add_color("background", "background")
+ #top.add_color("color", "color")
+ #top.add_style("height: 100%")
+ #top.add_style("width: 100%")
+ #border_color = top.get_color("border")
+ #top.add_border()
+
+ css = my.kwargs.get("css")
+ if css:
+ css = jsonloads(css)
+ for name, value in css.items():
+ top.add_style(name, value)
+
+
+ # define canvas
+ canvas = top
+ canvas.add_class("spt_freeform_canvas")
+ canvas.add_style("position: relative")
+ canvas.add_style("overflow: hidden")
+
+ my.kwargs['view'] = view
+
+
+ element_names = config.get_element_names()
+ view_attrs = config.get_view_attributes()
+
+ canvas_height = view_attrs.get("height")
+ if not canvas_height:
+ canvas_height = '400px'
+ canvas.add_style("height: %s" % canvas_height)
+
+ canvas_width = view_attrs.get("width")
+ if not canvas_width:
+ canvas_width = '400px'
+ canvas.add_style("width: %s" % canvas_width)
+
+ for element_name in element_names:
+
+ widget_div = DivWdg()
+ canvas.add(widget_div)
+ widget_div.add_style("position: absolute")
+ widget_div.add_style("vertical-align: top")
+
+ widget_div.add_class("SPT_ELEMENT_SELECT")
+
+
+ el_attrs = config.get_element_attributes(element_name)
+ height = el_attrs.get("height")
+ if height:
+ widget_div.add_style("height: %s" % height)
+
+ width = el_attrs.get("width")
+ if width:
+ widget_div.add_style("width: %s" % width)
+
+ display_handler = config.get_display_handler(element_name)
+ display_options = config.get_display_options(element_name)
+ widget_div.add_attr("spt_display_handler", display_handler)
+
+ try:
+ widget = config.get_display_widget(element_name)
+ except:
+ continue
+ widget.set_sobject(sobject)
+ widget_div.add_attr("spt_element_name", element_name)
+ widget_div.add_class("spt_element")
+
+ #widget_div.add(widget)
+
+ try:
+ widget_div.add(widget.get_buffer_display())
+ except:
+ widget_div.add("Error")
+ raise
+
+ try:
+ is_resizable = widget.is_resizable()
+ except:
+ is_resizable = False
+ if is_resizable:
+ widget.add_style("width: 100%")
+ widget.add_style("height: 100%")
+ widget.add_style("overflow: hidden")
+
+
+ xpos = el_attrs.get("xpos")
+ if not xpos:
+ xpos = '100px'
+ widget_div.add_style("left: %s" % xpos)
+
+ ypos = el_attrs.get("ypos")
+ if not ypos:
+ ypos = '100px'
+ widget_div.add_style("top: %s" % ypos)
+
+
+ return top
+
+
+__all__.append("FreeFormElementWdg")
+from tactic.ui.common import BaseTableElementWdg
+class FreeFormElementWdg(BaseTableElementWdg):
+
+ ARGS_KEYS = {
+ 'view': {
+ 'description': 'Freeform view',
+ 'type': 'TextWdg',
+ 'order': 1,
+ 'category': 'Options'
+ },
+ }
+
+
+ def preprocess(my):
+ my.layout = FreeFormLayoutWdg(**my.kwargs)
+
+ def is_editable(my):
+ return False
+
+ def get_display(my):
+
+ sobject = my.get_current_sobject()
+ my.layout.set_sobject(sobject)
+
+ top = my.top
+ top.add(my.layout.get_buffer_display())
+
+ return top
+
+
+
+
+
+
+
diff --git a/pool/shard009/Python/0086233_test_regex.py b/pool/shard009/Python/0086233_test_regex.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c34864e35c30f440a9eb87e83b340a378225b19
--- /dev/null
+++ b/pool/shard009/Python/0086233_test_regex.py
@@ -0,0 +1,36 @@
+import pytest
+from transcode import regex
+
+LINES_TEXT = '''Hear are
+some lines. These
+lines span 3 lines
+
+This is paragraph 2,
+it spends 2 lines.
+
+Paragraph 3 is a line line'''
+
+URLS = [
+ 'http://foobarbaz.com/?search=findme',
+ 'https://user:password@example.com:8000/some-path_here?foo=bar&spam=eggs#hash'
+]
+
+URL_TEXT = '''Within this text block there should be 2 urls.
+
+Here is the first one, very simple: {}
+
+And here is the second, more complex one, {}, within the sentence.'''.format(*URLS)
+
+class TestRegex:
+
+ def test_multiline_splitter(self):
+ result = regex.multiline_splitter(LINES_TEXT)
+ assert len(result) == 3
+
+ def test_urls(self):
+ results = list(regex.url_re.finditer(URL_TEXT))
+ assert len(results) == 2
+ assert results[0].group() == URLS[0]
+ assert results[1].group() == URLS[1]
+
+
diff --git a/pool/shard009/Python/0086235_sock.py b/pool/shard009/Python/0086235_sock.py
new file mode 100644
index 0000000000000000000000000000000000000000..b82da86bcc577031b89d77bc91062ec1240a551a
--- /dev/null
+++ b/pool/shard009/Python/0086235_sock.py
@@ -0,0 +1,55 @@
+#coding=utf-8
+
+import os
+import socket
+
+ALL_INTERFACE = '0.0.0.0'
+
+def create_sockets(binds, unix_sock, backlog):
+ """create listen sockets
+
+ :Parameters:
+ - `backlog`: listen queue max length
+ """
+ listeners = []
+ if "OPEN_FD" in os.environ:
+ fds = os.environ.pop("OPEN_FD").split(',')
+ if binds:
+ for i in range(len(binds)):
+ listeners.append(_create_socket(binds[i], backlog, fds[i]))
+
+ if unix_sock:
+ listeners.append( _create_socket(unix_sock, backlog, socket.AF_UNIX, fds[-1]))
+
+ return listeners
+
+ if binds:
+ """
+ if ALL_INTERFACE in binds:
+ listeners.append(_create_socket((ALL_INTERFACE, port), backlog)) # bind all interface
+ else:
+ """
+ for bind in binds:
+ listeners.append(_create_socket(bind, backlog))
+
+ if unix_sock:
+ sock = _create_socket(unix_sock, backlog, socket.AF_UNIX)
+ listeners.append(sock)
+
+ return listeners
+
+def _create_socket(addr, backlog, socket_family=socket.AF_INET, fd=None):
+ if fd:
+ sock = socket.fromfd(fd, socket_family, socket.SOCK_STREAM)
+ else:
+ sock = socket.socket(socket_family, socket.SOCK_STREAM)
+ set_socket_options(sock)
+ sock.bind(addr)
+ sock.listen(backlog)
+ return sock
+
+def set_socket_options(sock):
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ #if sock.family == sock.AF_INET:
+ # sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ sock.setblocking(0)
diff --git a/pool/shard009/Python/0086236_apiurls.py b/pool/shard009/Python/0086236_apiurls.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cb927a59171b54292e6efe047b5f2759e37c246
--- /dev/null
+++ b/pool/shard009/Python/0086236_apiurls.py
@@ -0,0 +1,17 @@
+from django.conf.urls import url, include
+from rest_framework.urlpatterns import format_suffix_patterns
+import restviews
+
+urlpatterns = [
+ url(
+ r'',
+ include([
+ url(r'^$', restviews.ShipList.as_view()),
+ url(r'^(?P[0-9]+)/$', restviews.ShipDetail.as_view()),
+ ])
+ )
+]
+
+urlpatterns = format_suffix_patterns(urlpatterns)
+
+# EOF
diff --git a/pool/shard009/Python/0086237_test-2.py b/pool/shard009/Python/0086237_test-2.py
new file mode 100644
index 0000000000000000000000000000000000000000..240cca7d6cb31e6986c4f24e10acef674849ae48
--- /dev/null
+++ b/pool/shard009/Python/0086237_test-2.py
@@ -0,0 +1,14 @@
+# a small 2-node example, just a producer and consumer
+
+import os
+import stat
+import sys
+
+print("Executing python script.")
+
+file = open('test-2.sh','w')
+file.write('#!/bin/sh\n')
+#file.write('echo "Executing binary for 2" >'+sys.argv[-1][8:-1]+'\n')
+file.write('echo "Executing binary for 2" >'+sys.argv[-1]+'\n')
+file.close()
+os.chmod('test-2.sh', stat.S_IRWXU)
diff --git a/pool/shard009/Python/0086238_http_transport.py b/pool/shard009/Python/0086238_http_transport.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8553060f9bd0f9b85db61e2181e14afc83fdd1f
--- /dev/null
+++ b/pool/shard009/Python/0086238_http_transport.py
@@ -0,0 +1,223 @@
+from twisted.web.resource import Resource
+from twisted.web.server import Request, Session, NOT_DONE_YET
+from twisted.internet import defer
+from twisted.python.failure import Failure
+import hashlib
+import json
+import string
+
+import helpers
+import semaphore
+#from storage import Storage
+from protocol import Protocol, RequestCounter
+from event_handler import GenericEventHandler
+import settings
+
+import logger
+log = logger.get_logger('http_transport')
+
+class Transport(object):
+ def __init__(self, session_id, lock):
+ self.buffer = []
+ self.session_id = session_id
+ self.lock = lock
+ self.push_url = None # None or full URL for HTTP Push
+ self.peer = None
+
+ # For compatibility with generic transport, not used in HTTP transport
+ self.disconnecting = False
+
+ def getPeer(self):
+ return self.peer
+
+ def write(self, data):
+ if len(self.buffer) >= settings.HTTP_BUFFER_LIMIT:
+ # Drop first (oldest) item in buffer
+ # if buffer crossed allowed limit.
+ # This isn't totally exact, because one record in buffer
+ # can teoretically contains more than one message (divided by \n),
+ # but current server implementation don't store responses in this way,
+ # so counting exact number of messages will lead to unnecessary overhead.
+ self.buffer.pop(0)
+
+ self.buffer.append(data)
+
+ if not self.lock.is_locked() and self.push_url:
+ # Push the buffer to callback URL
+ # TODO: Buffer responses and perform callbgitacks in batches
+ self.push_buffer()
+
+ def push_buffer(self):
+ '''Push the content of the buffer into callback URL'''
+ if not self.push_url:
+ return
+
+ # FIXME: Don't expect any response
+ helpers.get_page(self.push_url, method='POST',
+ headers={"content-type": "application/stratum",
+ "x-session-id": self.session_id},
+ payload=self.fetch_buffer())
+
+ def fetch_buffer(self):
+ ret = ''.join(self.buffer)
+ self.buffer = []
+ return ret
+
+ def set_push_url(self, url):
+ self.push_url = url
+
+def monkeypatch_method(cls):
+ '''Perform monkey patch for given class.'''
+ def decorator(func):
+ setattr(cls, func.__name__, func)
+ return func
+ return decorator
+
+@monkeypatch_method(Request)
+def getSession(self, sessionInterface=None, cookie_prefix='TWISTEDSESSION'):
+ '''Monkey patch for Request object, providing backward-compatible
+ getSession method which can handle custom cookie as a session ID
+ (which is necessary for following Stratum protocol specs).
+ Unfortunately twisted developers rejected named-cookie feature,
+ which is pressing me into this ugly solution...
+
+ TODO: Especially this would deserve some unit test to be sure it doesn't break
+ in future twisted versions.
+ '''
+ # Session management
+ if not self.session:
+ cookiename = string.join([cookie_prefix] + self.sitepath, "_")
+ sessionCookie = self.getCookie(cookiename)
+ if sessionCookie:
+ try:
+ self.session = self.site.getSession(sessionCookie)
+ except KeyError:
+ pass
+ # if it still hasn't been set, fix it up.
+ if not self.session:
+ self.session = self.site.makeSession()
+ self.addCookie(cookiename, self.session.uid, path='/')
+ self.session.touch()
+ if sessionInterface:
+ return self.session.getComponent(sessionInterface)
+ return self.session
+
+class HttpSession(Session):
+ sessionTimeout = settings.HTTP_SESSION_TIMEOUT
+
+ def __init__(self, *args, **kwargs):
+ Session.__init__(self, *args, **kwargs)
+ #self.storage = Storage()
+
+ # Reference to connection object (Protocol instance)
+ self.protocol = None
+
+ # Synchronizing object for avoiding race condition on session
+ self.lock = semaphore.Semaphore(1)
+
+ # Output buffering
+ self.transport = Transport(self.uid, self.lock)
+
+ # Setup cleanup method on session expiration
+ self.notifyOnExpire(lambda: HttpSession.on_expire(self))
+
+ @classmethod
+ def on_expire(cls, sess_obj):
+ # FIXME: Close protocol connection
+ print "EXPIRING SESSION", sess_obj
+
+ if sess_obj.protocol:
+ sess_obj.protocol.connectionLost(Failure(Exception("HTTP session closed")))
+
+ sess_obj.protocol = None
+
+class Root(Resource):
+ isLeaf = True
+
+ def __init__(self, debug=False, signing_key=None, signing_id=None,
+ event_handler=GenericEventHandler):
+ Resource.__init__(self)
+ self.signing_key = signing_key
+ self.signing_id = signing_id
+ self.debug = debug # This class acts as a 'factory', debug is used by Protocol
+ self.event_handler = event_handler
+
+ def render_GET(self, request):
+ if not settings.BROWSER_ENABLE:
+ return "Welcome to %s server. Use HTTP POST to talk with the server." % settings.USER_AGENT
+
+ # TODO: Web browser
+ return "Web browser not implemented yet"
+
+ def render_OPTIONS(self, request):
+ session = request.getSession(cookie_prefix='STRATUM_SESSION')
+
+ request.setHeader('server', settings.USER_AGENT)
+ request.setHeader('x-session-timeout', session.sessionTimeout)
+ request.setHeader('access-control-allow-origin', '*') # Allow access from any other domain
+ request.setHeader('access-control-allow-methods', 'POST, OPTIONS')
+ request.setHeader('access-control-allow-headers', 'Content-Type')
+ return ''
+
+ def render_POST(self, request):
+ session = request.getSession(cookie_prefix='STRATUM_SESSION')
+
+ l = session.lock.acquire()
+ l.addCallback(self._perform_request, request, session)
+ return NOT_DONE_YET
+
+ def _perform_request(self, _, request, session):
+ request.setHeader('content-type', 'application/stratum')
+ request.setHeader('server', settings.USER_AGENT)
+ request.setHeader('x-session-timeout', session.sessionTimeout)
+ request.setHeader('access-control-allow-origin', '*') # Allow access from any other domain
+
+ # Update client's IP address
+ session.transport.peer = request.getHost()
+
+ # Although it isn't intuitive at all, request.getHeader reads request headers,
+ # but request.setHeader (few lines above) writes response headers...
+ if 'application/stratum' not in request.getHeader('content-type'):
+ session.transport.write("%s\n" % json.dumps({'id': None, 'result': None, 'error': (-1, "Content-type must be 'application/stratum'. See http://stratum.bitcoin.cz for more info.", "")}))
+ self._finish(None, request, session.transport, session.lock)
+ return
+
+ if not session.protocol:
+ # Build a "protocol connection"
+ proto = Protocol()
+ proto.transport = session.transport
+ proto.factory = self
+ proto.connectionMade()
+ session.protocol = proto
+ else:
+ proto = session.protocol
+
+ # Update callback URL if presented
+ callback_url = request.getHeader('x-callback-url')
+ if callback_url != None:
+ if callback_url == '':
+ # Blank value of callback URL switches HTTP Push back to HTTP Poll
+ session.transport.push_url = None
+ else:
+ session.transport.push_url = callback_url
+
+ data = request.content.read()
+ if data:
+ counter = RequestCounter()
+ counter.on_finish.addCallback(self._finish, request, session.transport, session.lock)
+ proto.dataReceived(data, request_counter=counter)
+ else:
+ # Ping message (empty request) of HTTP Polling
+ self._finish(None, request, session.transport, session.lock)
+
+
+ @classmethod
+ def _finish(cls, _, request, transport, lock):
+ # First parameter is callback result; not used here
+ data = transport.fetch_buffer()
+ request.setHeader('content-length', len(data))
+ request.setHeader('content-md5', hashlib.md5(data).hexdigest())
+ request.setHeader('x-content-sha256', hashlib.sha256(data).hexdigest())
+ request.write(data)
+ request.finish()
+ lock.release()
diff --git a/pool/shard009/Python/0086251_test_availability_zones.py b/pool/shard009/Python/0086251_test_availability_zones.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bc6db58bcaf9bea8ed0a545432caa1147b0196f
--- /dev/null
+++ b/pool/shard009/Python/0086251_test_availability_zones.py
@@ -0,0 +1,157 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2013 Netease Corporation
+# 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 availability zones
+"""
+
+from oslo.config import cfg
+
+from nova import availability_zones as az
+from nova import context
+from nova import db
+from nova import test
+
+CONF = cfg.CONF
+CONF.import_opt('internal_service_availability_zone',
+ 'nova.availability_zones')
+CONF.import_opt('default_availability_zone',
+ 'nova.availability_zones')
+
+
+class AvailabilityZoneTestCases(test.TestCase):
+ """Test case for aggregate based availability zone."""
+
+ def setUp(self):
+ super(AvailabilityZoneTestCases, self).setUp()
+ self.host = 'me'
+ self.availability_zone = 'nova-test'
+ self.default_az = CONF.default_availability_zone
+ self.default_in_az = CONF.internal_service_availability_zone
+ self.context = context.get_admin_context()
+ self.agg = self._create_az('az_agg', self.availability_zone)
+
+ def tearDown(self):
+ db.aggregate_delete(self.context, self.agg['id'])
+ super(AvailabilityZoneTestCases, self).tearDown()
+
+ def _create_az(self, agg_name, az_name):
+ agg_meta = {'name': agg_name}
+ agg = db.aggregate_create(self.context, agg_meta)
+
+ metadata = {'availability_zone': az_name}
+ db.aggregate_metadata_add(self.context, agg['id'], metadata)
+
+ return agg
+
+ def _create_service_with_topic(self, topic, host, disabled=False):
+ values = {
+ 'binary': 'bin',
+ 'host': host,
+ 'topic': topic,
+ 'disabled': disabled,
+ }
+ return db.service_create(self.context, values)
+
+ def _destroy_service(self, service):
+ return db.service_destroy(self.context, service['id'])
+
+ def _add_to_aggregate(self, service, aggregate):
+ return db.aggregate_host_add(self.context,
+ aggregate['id'], service['host'])
+
+ def _delete_from_aggregate(self, service, aggregate):
+ return db.aggregate_host_delete(self.context,
+ self.aggregate['id'], service['host'])
+
+ def test_set_availability_zone_compute_service(self):
+ """Test for compute service get right availability zone."""
+ service = self._create_service_with_topic('compute', self.host)
+ services = db.service_get_all(self.context)
+
+ # The service is not add into aggregate, so confirm it is default
+ # availability zone.
+ new_service = az.set_availability_zones(self.context, services)[0]
+ self.assertEquals(new_service['availability_zone'],
+ self.default_az)
+
+ # The service is added into aggregate, confirm return the aggregate
+ # availability zone.
+ self._add_to_aggregate(service, self.agg)
+ new_service = az.set_availability_zones(self.context, services)[0]
+ self.assertEquals(new_service['availability_zone'],
+ self.availability_zone)
+
+ self._destroy_service(service)
+
+ def test_set_availability_zone_not_compute_service(self):
+ """Test not compute service get right availability zone."""
+ service = self._create_service_with_topic('network', self.host)
+ services = db.service_get_all(self.context)
+ new_service = az.set_availability_zones(self.context, services)[0]
+ self.assertEquals(new_service['availability_zone'],
+ self.default_in_az)
+ self._destroy_service(service)
+
+ def test_get_host_availability_zone(self):
+ """Test get right availability zone by given host."""
+ self.assertEquals(self.default_az,
+ az.get_host_availability_zone(self.context, self.host))
+
+ service = self._create_service_with_topic('compute', self.host)
+ self._add_to_aggregate(service, self.agg)
+
+ self.assertEquals(self.availability_zone,
+ az.get_host_availability_zone(self.context, self.host))
+
+ def test_get_availability_zones(self):
+ """Test get_availability_zones."""
+
+ # get_availability_zones returns two lists, zones with at least one
+ # enabled services, and zones with no enabled services.
+ # Use the following test data:
+ #
+ # zone host enabled
+ # nova-test host1 Yes
+ # nova-test host2 No
+ # nova-test2 host3 Yes
+ # nova-test3 host4 No
+ # host5 No
+
+ agg2 = self._create_az('agg-az2', 'nova-test2')
+ agg3 = self._create_az('agg-az3', 'nova-test3')
+
+ service1 = self._create_service_with_topic('compute', 'host1',
+ disabled=False)
+ service2 = self._create_service_with_topic('compute', 'host2',
+ disabled=True)
+ service3 = self._create_service_with_topic('compute', 'host3',
+ disabled=False)
+ service4 = self._create_service_with_topic('compute', 'host4',
+ disabled=True)
+ service5 = self._create_service_with_topic('compute', 'host5',
+ disabled=True)
+
+ self._add_to_aggregate(service1, self.agg)
+ self._add_to_aggregate(service2, self.agg)
+ self._add_to_aggregate(service3, agg2)
+ self._add_to_aggregate(service4, agg3)
+
+ zones, not_zones = az.get_availability_zones(self.context)
+
+ self.assertEquals(zones, ['nova-test', 'nova-test2'])
+ self.assertEquals(not_zones, ['nova-test3', 'nova'])
diff --git a/pool/shard009/Python/0086256_init__.py b/pool/shard009/Python/0086256_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..03640d97de9acd4c93026e9be0b22bed49d9ee01
--- /dev/null
+++ b/pool/shard009/Python/0086256_init__.py
@@ -0,0 +1,69 @@
+# ----------------------------------------------------------------------------
+# Copyright (C) 2013-2014 Huynh Vi Lam
+#
+# This file is part of pimucha.
+#
+# 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 logging
+
+logger = logging.getLogger()
+
+
+NETControllers = {}
+
+try:
+ from .netcontrollers import NATIR
+ NETControllers.update({'NATIR':NATIR})
+except Exception as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
+
+try:
+ from .netcontrollers import NCM11
+ NETControllers.update({'LCM11':NCM11})
+ NETControllers.update({'NCM11':NCM11})
+ NETControllers.update({'PCM11':NCM11})
+except Exception as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
+
+try:
+ from .netcontrollers import NCM15
+ NETControllers.update({'LCM15':NCM15})
+ NETControllers.update({'NCM15':NCM15})
+ NETControllers.update({'PCM15':NCM15})
+except Exception as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
+
+try:
+ from .netcontrollers import NRFXCOM
+ NETControllers.update({'NRFXCOM':NRFXCOM})
+except ImportError as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
+
+try:
+ from .netcontrollers import NRFXTRX
+ NETControllers.update({'LRFXTRX':NRFXTRX})
+ NETControllers.update({'NRFXTRX':NRFXTRX})
+ NETControllers.update({'PRFXTRX':NRFXTRX})
+except ImportError as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
+
+try:
+ from .netcontrollers import NTSDUO
+ NETControllers.update({'LTSDUO':NTSDUO})
+ NETControllers.update({'NTSDUO':NTSDUO})
+ NETControllers.update({'PTSDUO':NTSDUO})
+except ImportError as e:
+ logger.debug("%s : %s", repr(e.__class__), str(e))
diff --git a/pool/shard009/Python/0086257_test_telnetlib.py b/pool/shard009/Python/0086257_test_telnetlib.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae6222f6ce7759ed2e4cb475b37967de68e1d3f
--- /dev/null
+++ b/pool/shard009/Python/0086257_test_telnetlib.py
@@ -0,0 +1,79 @@
+import socket
+import threading
+import telnetlib
+import time
+
+from unittest import TestCase
+from test import support
+
+HOST = support.HOST
+
+def server(evt, serv):
+ serv.listen(5)
+ evt.set()
+ try:
+ conn, addr = serv.accept()
+ except socket.timeout:
+ pass
+ finally:
+ serv.close()
+ evt.set()
+
+class GeneralTests(TestCase):
+
+ def setUp(self):
+ self.evt = threading.Event()
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.sock.settimeout(3)
+ self.port = support.bind_port(self.sock)
+ threading.Thread(target=server, args=(self.evt,self.sock)).start()
+ self.evt.wait()
+ self.evt.clear()
+ time.sleep(.1)
+
+ def tearDown(self):
+ self.evt.wait()
+
+ def testBasic(self):
+ # connects
+ telnet = telnetlib.Telnet(HOST, self.port)
+ telnet.sock.close()
+
+ def testTimeoutDefault(self):
+ self.assertTrue(socket.getdefaulttimeout() is None)
+ socket.setdefaulttimeout(30)
+ try:
+ telnet = telnetlib.Telnet("localhost", self.port)
+ finally:
+ socket.setdefaulttimeout(None)
+ self.assertEqual(telnet.sock.gettimeout(), 30)
+ telnet.sock.close()
+
+ def testTimeoutNone(self):
+ # None, having other default
+ self.assertTrue(socket.getdefaulttimeout() is None)
+ socket.setdefaulttimeout(30)
+ try:
+ telnet = telnetlib.Telnet(HOST, self.port, timeout=None)
+ finally:
+ socket.setdefaulttimeout(None)
+ self.assertTrue(telnet.sock.gettimeout() is None)
+ telnet.sock.close()
+
+ def testTimeoutValue(self):
+ telnet = telnetlib.Telnet("localhost", self.port, timeout=30)
+ self.assertEqual(telnet.sock.gettimeout(), 30)
+ telnet.sock.close()
+
+ def testTimeoutOpen(self):
+ telnet = telnetlib.Telnet()
+ telnet.open("localhost", self.port, timeout=30)
+ self.assertEqual(telnet.sock.gettimeout(), 30)
+ telnet.sock.close()
+
+
+def test_main(verbose=None):
+ support.run_unittest(GeneralTests)
+
+if __name__ == '__main__':
+ test_main()
diff --git a/pool/shard009/Python/0086261_test_vm_ha_level.py b/pool/shard009/Python/0086261_test_vm_ha_level.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa556b117d9b76d8821a87024a0a4fed2c7e9e0a
--- /dev/null
+++ b/pool/shard009/Python/0086261_test_vm_ha_level.py
@@ -0,0 +1,35 @@
+# -*- coding:utf-8 -*-
+
+import zstackwoodpecker.test_util as test_util
+import zstackwoodpecker.test_lib as test_lib
+
+vm = test_lib.lib_get_specific_stub('e2e_mini/vm', 'vm')
+
+vm_ops = None
+vm_name = 'vm-' + vm.get_time_postfix()
+
+def test():
+ global vm_ops
+ vm_ops = vm.VM()
+ vm_ops.create_vm(name=vm_name)
+ vm_ops.set_ha_level(vm_name=vm_name, ha=True)
+ vm_ops.set_ha_level(vm_name=vm_name, ha=False)
+ vm_ops.set_ha_level(vm_name=vm_name, ha=True, details_page=True)
+ vm_ops.set_ha_level(vm_name=vm_name, ha=False, details_page=True)
+ vm_ops.check_browser_console_log()
+ test_util.test_pass('Set VM HA Level Successful')
+
+
+def env_recover():
+ global vm_ops
+ vm_ops.expunge_vm(vm_name)
+ vm_ops.close()
+
+#Will be called only if exception happens in test().
+def error_cleanup():
+ global vm_ops
+ try:
+ vm_ops.expunge_vm(vm_name)
+ vm_ops.close()
+ except:
+ pass
diff --git a/pool/shard009/Python/0086262_CatalogueSelectUI.py b/pool/shard009/Python/0086262_CatalogueSelectUI.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5aedde395d9846525dae2a43cc34a901c8b56be
--- /dev/null
+++ b/pool/shard009/Python/0086262_CatalogueSelectUI.py
@@ -0,0 +1,83 @@
+##########################################################################
+#
+# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above
+# copyright notice, this list of conditions and the following
+# disclaimer.
+#
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with
+# the distribution.
+#
+# * Neither the name of John Haddon nor the names of
+# any other contributors to this software may be used to endorse or
+# promote products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+##########################################################################
+import IECore
+import Gaffer
+import GafferImage
+
+def __imageNames( plug ) :
+ node = plug.node()
+ imagePlug = node["in"]
+
+ while imagePlug is not None and not isinstance( imagePlug.node(), GafferImage.Catalogue ) :
+ imagePlug = imagePlug.getInput()
+
+ if imagePlug is None :
+ return []
+
+ return imagePlug.node()["images"].keys()
+
+def __imagePresetNames( plug ) :
+
+ return IECore.StringVectorData( [ "Selected" ] + __imageNames( plug ) )
+
+def __imagePresetValues( plug ) :
+
+ return IECore.StringVectorData( [ "" ] + __imageNames( plug ) )
+
+Gaffer.Metadata.registerNode(
+
+ GafferImage.CatalogueSelect,
+
+ "description",
+ "Finds an image in a directly connected Catalogue by name.",
+
+ plugs = {
+
+ "imageName" : [
+
+ "description",
+ "The name of the image to extract.",
+
+ "presetNames", __imagePresetNames,
+ "presetValues", __imagePresetValues,
+ # Don't promote presets so they are still computed dynamically for
+ # the promoted plug rather than being baked.
+ "presetNames:promotable", False,
+ "presetValues:promotable", False,
+
+ ]
+ }
+)
diff --git a/pool/shard009/Python/0086263_openload.py b/pool/shard009/Python/0086263_openload.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f16089cbcac3d11b1c6c062605c1f9997eac9d1
--- /dev/null
+++ b/pool/shard009/Python/0086263_openload.py
@@ -0,0 +1,110 @@
+# -*- coding: utf-8 -*-
+"""
+openload.io urlresolver plugin
+Copyright (C) 2015 tknorris
+
+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 os
+import json
+from lib import helpers
+from urlresolver import common
+from urlresolver.common import i18n
+from urlresolver.resolver import UrlResolver, ResolverError
+
+logger = common.log_utils.Logger.get_logger(__name__)
+logger.disable()
+
+API_BASE_URL = 'https://api.openload.co/1'
+INFO_URL = API_BASE_URL + '/streaming/info'
+GET_URL = API_BASE_URL + '/streaming/get?file={media_id}'
+FILE_URL = API_BASE_URL + '/file/info?file={media_id}'
+
+class OpenLoadResolver(UrlResolver):
+ name = "openload"
+ domains = ["openload.io", "openload.co", "oload.tv", "oload.stream", "oload.win", "oload.download", "oload.info", "oload.icu", "oload.fun", "openload.pw"]
+ pattern = '(?://|\.)(o(?:pen)??load\.(?:io|co|tv|stream|win|download|info|icu|fun|pw))/(?:embed|f)/([0-9a-zA-Z-_]+)'
+
+ def __init__(self):
+ self.net = common.Net()
+
+ def get_media_url(self, host, media_id):
+ try:
+ if not self.__file_exists(media_id):
+ raise ResolverError('File Not Available')
+
+ video_url = self.__check_auth(media_id)
+ if not video_url:
+ video_url = self.__auth_ip(media_id)
+ except ResolverError:
+ raise
+
+ if video_url:
+ headers = {'User-Agent': common.RAND_UA}
+ video_url = video_url + helpers.append_headers(headers)
+ return video_url
+ else:
+ raise ResolverError(i18n('no_ol_auth'))
+
+ def get_url(self, host, media_id):
+ return 'http://openload.co/embed/%s' % (media_id)
+
+ def __file_exists(self, media_id):
+ js_data = self.__get_json(FILE_URL.format(media_id=media_id))
+ return js_data.get('result', {}).get(media_id, {}).get('status') == 200
+
+ def __auth_ip(self, media_id):
+ js_data = self.__get_json(INFO_URL)
+ pair_url = js_data.get('result', {}).get('auth_url', '')
+ if pair_url:
+ pair_url = pair_url.replace('\/', '/')
+ header = i18n('ol_auth_header')
+ line1 = i18n('auth_required')
+ line2 = i18n('visit_link')
+ line3 = i18n('click_pair').decode('utf-8') % (pair_url)
+ with common.kodi.CountdownDialog(header, line1, line2, line3) as cd:
+ return cd.start(self.__check_auth, [media_id])
+
+ def __check_auth(self, media_id):
+ try:
+ js_data = self.__get_json(GET_URL.format(media_id=media_id))
+ except ResolverError as e:
+ status, msg = e
+ if status == 403:
+ return
+ else:
+ raise ResolverError(msg)
+
+ return js_data.get('result', {}).get('url')
+
+ def __get_json(self, url):
+ result = self.net.http_GET(url).content
+ common.logger.log(result)
+ js_result = json.loads(result)
+ if js_result['status'] != 200:
+ raise ResolverError(js_result['status'], js_result['msg'])
+ return js_result
+
+ @classmethod
+ def get_settings_xml(cls):
+ xml = super(cls, cls).get_settings_xml()
+ xml.append('' % (cls.__name__, i18n('auto_update')))
+ xml.append('' % (cls.__name__, i18n('update_url')))
+ xml.append('' % (cls.__name__, i18n('decrypt_key')))
+ xml.append('' % (cls.__name__))
+ return xml
+
+ @classmethod
+ def isPopup(self):
+ return True
diff --git a/pool/shard009/Python/0086266_text.py b/pool/shard009/Python/0086266_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bac3f21fd3604a91ec1834ccaa1da8a0ca6fa50
--- /dev/null
+++ b/pool/shard009/Python/0086266_text.py
@@ -0,0 +1,252 @@
+''' Classes that represent text or sequences of text. '''
+
+import re
+from urllib.request import urlopen
+
+import pandas as pd
+
+from pliers.support.decorators import requires_nltk_corpus
+from pliers.utils import attempt_to_import, verify_dependencies
+from .base import Stim
+
+pysrt = attempt_to_import('pysrt')
+
+
+class TextStim(Stim):
+
+ ''' Any simple text stimulus--most commonly a single word.
+
+ Args:
+ filename (str): Path to input file, if one exists.
+ text (str): Text value to store. If none is provided, value is read
+ from filename.
+ onset (float): Optional onset of the text presentation (in secs) with
+ respect to some more general context or timeline the user wishes
+ to keep track of.
+ duration (float): Optional duration of the TextStim, in seconds.
+ order (int): Optional sequential index of the TextStim within some
+ broader context.
+ url (str): Optional url to read contents from.
+ '''
+
+ _default_file_extension = '.txt'
+
+ def __init__(self, filename=None, text=None, onset=None, duration=None,
+ order=None, url=None):
+ if filename is not None and text is None:
+ text = open(filename).read()
+ if url is not None:
+ text = urlopen(url).read()
+ self.text = text
+ name = 'text[%s]' % text[:40] # Truncate at 40 chars
+ super().__init__(filename, onset, duration, order,
+ name=name, url=url)
+
+ @property
+ def data(self):
+ return self.text
+
+ def save(self, path):
+ with open(path, 'w') as f:
+ f.write(self.text)
+
+
+class ComplexTextStim(Stim):
+
+ ''' A collection of text stims (e.g., a story), typically ordered and with
+ onsets and/or durations associated with each element.
+
+ Args:
+ filename (str): The filename to read from. Must be tab-delimited text.
+ Files must always contain a column containing the text of each
+ stimulus in the collection. Optionally, additional columns can be
+ included that contain duration and onset information. If a header
+ row is present in the file, valid columns must be labeled as
+ 'text', 'onset', and 'duration' where available (though only text
+ is mandatory). If no header is present in the file, the columns
+ argument will be used to infer the indices of the key columns.
+ onset (float): Optional onset of the ComplexTextStim relative to some
+ more general context.
+ duration (float): Optional duration of the ComplexTextStim withing some
+ more general context.
+ columns (str): Optional specification of column order. An abbreviated
+ string denoting the column position of text, onset, and duration
+ in the file. Use t for text, o for onset, d for duration. For
+ example, passing 'ot' indicates that the first column contains
+ the onsets and the second contains the text. E.g., passing 'tod'
+ indicates that the first three columns contain text, onset, and
+ duration information, respectively. Note that if the input file
+ contains a header row, the columns argument will be ignored.
+ default_duration (float): the duration to assign to any text elements
+ in the collection that do not have an explicit value provided
+ in the input file.
+ elements (list): An optional list of TextStims that comprise the
+ ComplexTextStim. If both the filename and elements arguments are
+ passed, the TextStims in elements will be appended to the ones
+ extracted from the file.
+ text (str): Optional multi-token string to convert to a
+ ComplexTextStim.
+ unit (str): The unit of segmentation. Either 'word' or 'sentence'.
+ Ignored if text is None.
+ tokenizer: Optional tokenizer to use if initializing from text. If
+ passed, will override the default nltk tokenizers. If a string is
+ passed, it is interpreted as a capturing regex and passed to
+ re.findall(). Otherwise, must be an object that implements a
+ tokenize() method and returns a list of tokens. Ignored if text is
+ None.
+ language (str): The language to use; passed to nltk. Only used if
+ tokenizer is None. Defaults to English. Ignored if text is None.
+ '''
+
+ _default_file_extension = '.txt'
+
+ def __init__(self, filename=None, onset=None, duration=None, columns=None,
+ default_duration=None, elements=None, text=None, unit='word',
+ tokenizer=None, language='english'):
+
+ if filename is None and elements is None and text is None:
+ raise ValueError("At least one of the 'filename', 'elements', or "
+ "text arguments must be specified.")
+
+ super().__init__(filename, onset, duration)
+
+ self._elements = []
+
+ if filename is not None:
+ if filename.endswith('srt'):
+ self._from_srt(filename)
+ else:
+ self._from_file(filename, columns, default_duration)
+
+ if elements is not None:
+ self._elements.extend(elements)
+
+ if text is not None:
+ self._from_text(text, unit, tokenizer, language)
+
+ @property
+ def elements(self):
+ return [f for f in self]
+
+ def _from_file(self, filename, columns, default_duration):
+ tod_names = {'t': 'text', 'o': 'onset', 'd': 'duration'}
+
+ first_row = open(filename).readline().strip().split('\t')
+ if len(set(first_row) & set(tod_names.values())):
+ col_names = None
+ else:
+ col_names = [tod_names[x] for x in columns]
+
+ data = pd.read_csv(filename, sep='\t', names=col_names)
+
+ for i, r in data.iterrows():
+ if 'onset' not in r:
+ elem = TextStim(r['text'], order=i)
+ else:
+ duration = r.get('duration', None)
+ if duration is None:
+ duration = default_duration
+ elem = TextStim(filename, r['text'], r['onset'], duration)
+ self._elements.append(elem)
+
+ def save(self, path):
+ if path.endswith('srt'):
+ verify_dependencies(['pysrt'])
+ from pysrt import SubRipFile, SubRipItem
+ from datetime import time
+
+ out = SubRipFile()
+ for elem in self._elements:
+ start = time(*self._to_tup(elem.onset))
+ end = time(*self._to_tup(elem.onset + elem.duration))
+ out.append(SubRipItem(0, start, end, elem.text))
+ out.save(path)
+ else:
+ with open(path, 'w') as f:
+ f.write('onset\ttext\tduration\n')
+ for elem in self._elements:
+ f.write('{}\t{}\t{}\n'.format(elem.onset,
+ elem.text,
+ elem.duration))
+
+ def _from_srt(self, filename):
+ verify_dependencies(['pysrt'])
+
+ data = pysrt.open(filename)
+ list_ = [[] for _ in data]
+ for i, row in enumerate(data):
+ start = tuple(row.start)
+ start_time = self._to_sec(start)
+
+ end_ = tuple(row.end)
+ duration = self._to_sec(end_) - start_time
+
+ line = re.sub(r'\s+', ' ', row.text)
+ list_[i] = [line, start_time, duration]
+
+ # Convert to pandas DataFrame
+ df = pd.DataFrame(columns=["text", "onset", "duration"], data=list_)
+
+ for i, r in df.iterrows():
+ elem = TextStim(filename, text=r['text'], onset=r['onset'],
+ duration=r['duration'], order=i)
+ self._elements.append(elem)
+
+ def __iter__(self):
+ """ Iterate text elements. """
+ for elem in self._elements:
+ offset = 0.0 if self.onset is None else self.onset
+ # Calculate element onset relative to this stimulus
+ rel_onset = offset if elem.onset is None else offset + elem.onset
+ yield TextStim(elem.filename, elem.text, rel_onset, elem.duration,
+ elem.order)
+
+ def _to_tup(self, sec):
+ hours = int(sec / 3600)
+ sec = sec % 3600
+ mins = int(sec / 60)
+ sec = sec % 60
+ secs = int(sec)
+ microsecs = int((sec - secs) * 1000000)
+ return hours, mins, secs, microsecs
+
+ def _to_sec(self, tup):
+ hours, mins, secs, msecs = tup
+ total_msecs = (hours * 60 * 60 * 1000) + (mins * 60 * 1000) + \
+ (secs * 1000) + msecs
+ total_secs = total_msecs / 1000.
+ return total_secs
+
+ def _from_text(self, text, unit, tokenizer, language):
+
+ if tokenizer is not None:
+ if isinstance(tokenizer, str):
+ tokens = re.findall(tokenizer, text)
+ else:
+ tokens = tokenizer.tokenize(text)
+ else:
+ import nltk
+
+ @requires_nltk_corpus
+ def tokenize_text(text):
+ if unit == 'word':
+ return nltk.word_tokenize(text, language)
+ elif unit.startswith('sent'):
+ return nltk.sent_tokenize(text, language)
+ else:
+ raise ValueError(
+ "unit must be either 'word' or 'sentence'")
+
+ tokens = tokenize_text(text)
+
+ for i, t in enumerate(tokens):
+ self._elements.append(TextStim(text=t, onset=None, duration=None,
+ order=i))
+
+ @property
+ def data(self):
+ return ' '.join([e.text for e in self._elements])
+
+ def __hash__(self):
+ return hash(
+ (self.data, self.onset, self.duration, self.order, self.history))
diff --git a/pool/shard009/Python/0086271_pid_kettle.py b/pool/shard009/Python/0086271_pid_kettle.py
new file mode 100644
index 0000000000000000000000000000000000000000..1acfb221c8dba9eea46fc686f8e4d0c33b2bd78f
--- /dev/null
+++ b/pool/shard009/Python/0086271_pid_kettle.py
@@ -0,0 +1,76 @@
+# coding=utf-8
+import math
+
+# From
+# https://github.com/hirschmann/pid-autotune
+
+
+class Kettle(object):
+ """
+ A simulated brewing kettle.
+
+ Args:
+ diameter (float): Kettle diameter in centimeters.
+ volume (float): Content volume in liters.
+ temp (float): Initial content temperature in degree celsius.
+ density (float): Content density.
+ """
+ # specific heat capacity of water: c = 4.182 kJ / kg * K
+ SPECIFIC_HEAT_CAP_WATER = 4.182
+
+ # thermal conductivity of steel: lambda = 15 W / m * K
+ THERMAL_CONDUCTIVITY_STEEL = 15
+
+ def __init__(self, diameter, volume, temp, density=1):
+ self._mass = volume * density
+ self._temp = temp
+ radius = diameter / 2
+
+ # height in cm
+ height = (volume * 1000) / (math.pi * math.pow(radius, 2))
+
+ # surface in m^2
+ self._surface = (2 * math.pi * math.pow(radius, 2) + 2 * math.pi * radius * height) / 10000
+
+ @property
+ def temperature(self):
+ """Get the content's temperature."""
+ return self._temp
+
+ def heat(self, power, duration, efficiency=0.98):
+ """
+ Heat the kettle's content.
+
+ Args:
+ power (float): The power in kW.
+ duration (float): The duration in seconds.
+ efficiency (float): The efficiency as number between 0 and 1.
+ """
+ self._temp += self._get_delta_t(power * efficiency, duration)
+ return self._temp
+
+ def cool(self, duration, ambient_temp, heat_loss_factor=1):
+ """
+ Make the content lose heat.
+
+ Args:
+ duration (float): The duration in seconds.
+ ambient_temp (float): The ambient temperature in degree celsius.
+ heat_loss_factor (float): Increase or decrease the heat loss by a
+ specified factor.
+ """
+ # Q = k_w * A * (T_kettle - T_ambient)
+ # P = Q / t
+ power = ((Kettle.THERMAL_CONDUCTIVITY_STEEL * self._surface
+ * (self._temp - ambient_temp)) / duration)
+
+ # W to kW
+ power /= 1000
+ self._temp -= self._get_delta_t(power, duration) * heat_loss_factor
+ return self._temp
+
+ def _get_delta_t(self, power, duration):
+ # P = Q / t
+ # Q = c * m * delta T
+ # => delta(T) = (P * t) / (c * m)
+ return (power * duration) / (Kettle.SPECIFIC_HEAT_CAP_WATER * self._mass)
diff --git a/pool/shard009/Python/0086275_urls.py b/pool/shard009/Python/0086275_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee5c9165f2dda910c3965e2be4ca090d81ee307f
--- /dev/null
+++ b/pool/shard009/Python/0086275_urls.py
@@ -0,0 +1,22 @@
+from django.conf import settings
+from django.conf.urls import url, include
+from django.contrib import admin
+
+from events.views import IndexView
+from userprofiles.views import SetTimezone
+
+urlpatterns = [
+ url(r'^$', IndexView.as_view(), name='index'),
+ url(r'^set/timezone/', SetTimezone.as_view(), name='set_timezone'),
+ url(r'^event/(?P[\d]+)/', include('events.urls.event')),
+ url(r'^events/', include('events.urls.events')),
+ url(r'^accounts/', include('allauth.urls')),
+ url(r'^profile/(?P[\w@.+-]{1,150})/', include('userprofiles.urls')),
+ url(r'^admin/', admin.site.urls),
+]
+
+if settings.DEBUG:
+ import debug_toolbar
+ urlpatterns = [
+ url(r'^__debug__/', include(debug_toolbar.urls)),
+ ] + urlpatterns
diff --git a/pool/shard009/Python/0086282_util.py b/pool/shard009/Python/0086282_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f54dec8fe1966ef5bc1c16ab1edc3b7bfe09d5a
--- /dev/null
+++ b/pool/shard009/Python/0086282_util.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+# -*- mode: python; coding: utf-8 -*-
+
+
+from iter_space import *
+
+
+def dump2files(nodes_ids_set, ips_set, nodes_info_list):
+ """
+ Helper function, for writing data to files
+ """
+ if nodes_ids_set:
+ to_file(nodes_ids_set, "nodes_ids", "a")
+ if ips_set:
+ to_file(ips_set, "nodes_ips", "a")
+ if nodes_info_list:
+ to_file(nodes_info_list, "nodes_info", "a")
+
+
+def address_list2address_set(address_list):
+ """
+ Helper function for parsing and converting address list to addres set
+ """
+ address_set = set()
+ for address in address_list:
+ address = address.split("/")[2]
+ address_set.add(address)
+ return address_set
+
diff --git a/pool/shard009/Python/0086283_destroy.py b/pool/shard009/Python/0086283_destroy.py
new file mode 100644
index 0000000000000000000000000000000000000000..5289ce0fe0681c0d7922ebebef93f72887ceb8bd
--- /dev/null
+++ b/pool/shard009/Python/0086283_destroy.py
@@ -0,0 +1,32 @@
+# Copyright 2015 Isotoma Limited
+#
+# 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 touchdown.core.goals import Goal, register
+from touchdown.goals.action import ActionGoalMixin
+
+
+class Destroy(ActionGoalMixin, Goal):
+
+ """ Tear down this infrastructure """
+
+ name = "destroy"
+ execute_in_reverse = True
+
+ def get_plan_class(self, resource):
+ if "never-destroy" not in resource.ensure:
+ return resource.meta.get_plan("destroy") or resource.meta.get_plan("describe") or resource.meta.get_plan("null")
+ return resource.meta.get_plan("describe") or resource.meta.get_plan("null")
+
+
+register(Destroy)
diff --git a/pool/shard009/Python/0086285_setup.py b/pool/shard009/Python/0086285_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..35ec41ab6f4d0b29ec993a92365918b069247b90
--- /dev/null
+++ b/pool/shard009/Python/0086285_setup.py
@@ -0,0 +1,48 @@
+import os
+import sys
+
+# pylint: disable-msg=F0401
+
+from setuptools import setup, find_packages
+
+here = os.path.dirname(os.path.realpath(__file__))
+sys.path.insert(0, os.path.normpath(os.path.join(here,
+ 'openmdao',
+ 'examples',
+ 'expected_improvement')))
+import releaseinfo
+
+version = releaseinfo.__version__
+
+setup(name='openmdao.examples.expected_improvement',
+ version=version,
+ description="OpenMDAO examples - Problems using Expected Improvement (EI) adaptive sampling methods",
+ long_description="""\
+ """,
+ classifiers=[
+ 'Development Status :: 2 - Pre-Alpha',
+ 'Intended Audience :: Science/Research',
+ 'License :: OSI Approved',
+ 'Natural Language :: English',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python :: 2.7',
+ 'Topic :: Scientific/Engineering',
+ ],
+ keywords='optimization multidisciplinary multi-disciplinary analysis',
+ author='',
+ author_email='',
+ url='http://openmdao.org',
+ license='Apache License, Version 2.0',
+ namespace_packages=["openmdao", "openmdao.examples"],
+ packages=find_packages(), # ['openmdao','openmdao.examples'],
+ include_package_data=True,
+ test_suite='nose.collector',
+ zip_safe=False,
+ install_requires=[
+ 'setuptools',
+ 'openmdao.lib',
+ ],
+ entry_points="""
+ # -*- Entry points: -*-
+ """
+ )
diff --git a/pool/shard009/Python/0086291_secret_data_reader.py b/pool/shard009/Python/0086291_secret_data_reader.py
new file mode 100644
index 0000000000000000000000000000000000000000..d094674d630cbbfbe960ed2a0b3e4ed101f85345
--- /dev/null
+++ b/pool/shard009/Python/0086291_secret_data_reader.py
@@ -0,0 +1,29 @@
+# coding=utf-8
+
+"""
+This module, secret_data_reader.py, will read in data from the appropriate location.
+"""
+
+from sys import platform as _platform
+
+if _platform == "linux" or _platform == "linux2":
+ file_path = '/home/dev_usr/.secrets'
+else:
+ file_path = '/Users/utarsuno/.secrets'
+
+d = {}
+
+
+def get_secret_dictionary_value(key):
+ """Return the secret dictionary.
+ :param key: The key to get a value from.
+ :return: A dictionary of keys and values.
+ """
+ global d
+ global file_path
+ if len(d) == 0:
+ with open(file_path) as f:
+ for l in f:
+ (k, v) = l.split()
+ d[k] = v
+ return d[key]
diff --git a/pool/shard009/Python/0086293_crawler.py b/pool/shard009/Python/0086293_crawler.py
new file mode 100644
index 0000000000000000000000000000000000000000..baba5c576487aa8156ba80111d8ffe334e5ccbb6
--- /dev/null
+++ b/pool/shard009/Python/0086293_crawler.py
@@ -0,0 +1,170 @@
+# -*- coding: utf-8 -*-
+
+"""
+Simple async crawler/callback queue based on gevent.
+
+Based on Jason Morion's gevent+httplib2 crawler at
+https://gist.github.com/996120
+"""
+
+import traceback
+import logging
+import httplib2
+
+import gevent
+from gevent import queue, event, pool
+
+logger = logging.getLogger(__name__)
+
+
+USER_AGENT = "PRAP-MXI"
+
+
+class Job(object):
+ """Encapsulation of a job to put in the job queue. Contains at least
+ a URL, but can also have custom headers or entirely custom meta
+ information. The response object and data are tacked onto this object,
+ which is then returned to the scraper for processing."""
+ default_headers = {
+ 'Accept': 'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;',
+ 'Accept-Encoding': 'gzip,deflate',
+ 'Cache-Control': 'max-age=0',
+ }
+ def __init__(self, url, headers=None, meta=None, method='GET'):
+ self.__url = url
+ self.method = method
+ self.headers = dict(self.default_headers)
+ self.headers.update(headers or {})
+ self.headers['User-Agent'] = USER_AGENT
+ self.meta = meta
+
+ def __hash__(self):
+ return hash(self.url)
+
+ def __cmp__(self, other):
+ return cmp(hash(self), hash(other))
+
+ def __repr__(self):
+ return '' % (
+ self.url,
+ 'done: %d' % len(self.data) if hasattr(self, 'data') else 'pending',
+ )
+
+ url = property(lambda self: self.__url)
+
+
+class Crawler(object):
+ """Simple crawler based on gcrawler, but with a rolling inq that can be
+ added to. The crawler is done when the workers have no more jobs and
+ there are no more urls in the queue."""
+ seen_jobs = set()
+
+ def __init__(self, spider, timeout=2, worker_count=4, pipeline_size=100):
+ self.spider = spider
+ self.spider.crawler = self
+ self.timeout = timeout
+ self.count = worker_count
+ self.inq = queue.Queue(0)
+ self.outq = queue.Queue(pipeline_size)
+ self.jobq = queue.Queue()
+ self.pool = pool.Pool(worker_count)
+ self.worker_finished = event.Event()
+
+ for job in getattr(self.spider, 'jobs', []):
+ self.add_job(job)
+
+ self.cache = '.cache'
+
+ def start(self):
+ """Start the crawler. Starts the scheduler and pipeline first, then
+ adds jobs to the pool and waits for the scheduler and pipeline to
+ finish. The scheduler itself shuts down the pool and waits on that,
+ so it's not required to watch the pool."""
+ # add the spider's jobs first
+ for url in self.spider.urls:
+ self.add_job(url)
+ # start the scheduler & the pipeline
+ self.scheduler_greenlet = gevent.spawn(self.scheduler)
+ self.pipeline_greenlet = gevent.spawn(self.pipeline)
+ self.scheduler_greenlet.join()
+
+ def add_job(self, job, **kwargs):
+ """Add a job to the queue. The job argument can either be a Job object
+ or a url with keyword arguments to be passed to the Job constructor."""
+ if isinstance(job, basestring):
+ job = Job(job, **kwargs)
+ # do not visit previously viewed urls
+ if job in self.seen_jobs:
+ return
+ self.jobq.put(job)
+
+ def scheduler(self):
+ """A simple job scheduler. Presuming it's started after there is at
+ least one job, it feeds jobs to the job queue to a synchronous worker
+ job queue one at a time. When the worker queue fills up, the
+ scheduler will block on the put() operation. When job queue is empty,
+ the scheduler will wait for the workers to finish. If the job queue
+ is empty and no workers are active, the pool's stopped."""
+ logger = logging.getLogger(__name__ + '.scheduler')
+ while True:
+ # join dead greenlets
+ for greenlet in list(self.pool):
+ if greenlet.dead:
+ self.pool.discard(greenlet)
+ try:
+ logger.debug("Fetching job from job queue.")
+ job = self.jobq.get_nowait()
+ except queue.Empty:
+ logger.debug("No jobs remaining.")
+ if self.pool.free_count() != self.pool.size:
+ logger.debug("%d workers remaining, waiting..." % (self.pool.size - self.pool.free_count()))
+ self.worker_finished.wait()
+ self.worker_finished.clear()
+ continue
+ else:
+ logger.debug("No workers left, shutting down.")
+ return self.shutdown()
+ self.pool.spawn(self.worker, job)
+
+ def shutdown(self):
+ """Shutdown the crawler after the pool has finished."""
+ self.pool.join()
+ self.outq.put(StopIteration)
+ self.pipeline_greenlet.join()
+ return True
+
+
+ def worker(self, job, logger=logging.getLogger(__name__ + '.worker')):
+ """A simple worker that fetches urls based on jobs and puts the
+ ammended jobs on the outq for processing in the pipeline thread.
+ After each job is fetched, but before the worker sets the finished
+ event, the spider's preprocess method will be called on the job. This
+ is its opportunity to add urls to the job queue. Heavy processing
+ should be done via the pipeline in postprocess."""
+ logger.debug("starting: %r" % job)
+ # you need to create a new Http instance per greenlet, see ticket:
+ # http://code.google.com/p/httplib2/issues/detail?id=5
+ h = httplib2.Http(self.cache)
+ try:
+ job.response, job.data = h.request(job.url, method=job.method, headers=job.headers)
+ self.spider.preprocess(job)
+ except Exception, e:
+ logger.error("Preprocessing error:\n%s" % traceback.format_exc())
+ self.outq.put(job)
+ self.worker_finished.set()
+ logger.debug("finished: %r" % job)
+ raise gevent.GreenletExit('success')
+
+ def pipeline(self):
+ """A post-processing pipeline greenlet which keeps post-processing from
+ interfering with network wait parallelization of the worker pool."""
+ logger = logging.getLogger(__name__ + '.pipeline')
+ for job in self.outq:
+ try:
+ self.spider.postprocess(job)
+ except:
+ logger.error("error:\n%s" % traceback.format_exc())
+ logger.debug("finished processing.")
+
+def run(spider, **kwargs):
+ Crawler(spider, **kwargs).start()
diff --git a/pool/shard009/Python/0086295_security_group_network_interface.py b/pool/shard009/Python/0086295_security_group_network_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8e471837a0117d9d0ad1051750481a1a1699883
--- /dev/null
+++ b/pool/shard009/Python/0086295_security_group_network_interface.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for
+# license information.
+#
+# Code generated by Microsoft (R) AutoRest Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is
+# regenerated.
+# --------------------------------------------------------------------------
+
+from msrest.serialization import Model
+
+
+class SecurityGroupNetworkInterface(Model):
+ """Network interface and all its associated security rules.
+
+ :param id: ID of the network interface.
+ :type id: str
+ :param security_rule_associations:
+ :type security_rule_associations:
+ ~azure.mgmt.network.v2017_03_01.models.SecurityRuleAssociations
+ """
+
+ _attribute_map = {
+ 'id': {'key': 'id', 'type': 'str'},
+ 'security_rule_associations': {'key': 'securityRuleAssociations', 'type': 'SecurityRuleAssociations'},
+ }
+
+ def __init__(self, **kwargs):
+ super(SecurityGroupNetworkInterface, self).__init__(**kwargs)
+ self.id = kwargs.get('id', None)
+ self.security_rule_associations = kwargs.get('security_rule_associations', None)
diff --git a/pool/shard009/Python/0086302_trait_errors.py b/pool/shard009/Python/0086302_trait_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd46b5ebfda9d5c3bd85c6bf2ce0ec1520b5d00d
--- /dev/null
+++ b/pool/shard009/Python/0086302_trait_errors.py
@@ -0,0 +1,125 @@
+#------------------------------------------------------------------------------
+#
+# Copyright (c) 2005, Enthought, Inc.
+# All rights reserved.
+#
+# This software is provided without warranty under the terms of the BSD
+# license included in enthought/LICENSE.txt and may be redistributed only
+# under the conditions described in the aforementioned license. The license
+# is also available online at http://www.enthought.com/licenses/BSD.txt
+#
+# Thanks for using Enthought open source!
+#
+# Author: David C. Morrill
+# Date: 06/21/2002
+#
+#------------------------------------------------------------------------------
+
+""" Defines the standard exceptions raised by the Traits package.
+"""
+
+#-------------------------------------------------------------------------------
+# Imports:
+#-------------------------------------------------------------------------------
+
+from __future__ import absolute_import
+
+import sys
+
+from .trait_base import class_of
+
+from . import _py2to3
+
+#-------------------------------------------------------------------------------
+# Utilities
+#-------------------------------------------------------------------------------
+
+
+def repr_type(obj):
+ """ Return a string representation of a value and its type for readable
+ error messages.
+ """
+ the_type = _py2to3.type_w_old_style(obj)
+ msg = '%r %r' % (obj, the_type)
+ return msg
+
+#-------------------------------------------------------------------------------
+# 'TraitError' class:
+#-------------------------------------------------------------------------------
+
+class TraitError ( Exception ):
+
+ def __init__ ( self, args = None, name = None, info = None, value = None ):
+ if name is None:
+ # If the given args is not a tuple then assume that the user intended
+ # it to be the single item in a one-element tuple.
+ if not isinstance(args, tuple):
+ args = args,
+ self.args = args
+ else:
+ # Save the information, in case the 'args' object is not the correct
+ # one, and we need to regenerate the message later:
+ self.name = name
+ self.info = info
+ self.value = value
+ self.desc = None
+ self.prefix = 'The'
+ self.set_desc( None, args )
+
+ def set_desc ( self, desc, object = None ):
+ if hasattr( self, 'desc' ):
+ if desc is not None:
+ self.desc = desc
+ if object is not None:
+ self.object = object
+ self.set_args()
+
+ def set_prefix ( self, prefix ):
+ if hasattr( self, 'prefix' ):
+ self.prefix = prefix
+ self.set_args()
+
+ def set_args ( self ):
+ if self.desc is None:
+ extra = ''
+ else:
+ extra = ' specifies %s and' % self.desc
+ obj = getattr( self, 'object', None )
+
+ # Note: self.args must be a tuple so be sure to leave the trailing
+ # commas.
+ the_type = _py2to3.type_w_old_style(self.value)
+ if obj is not None:
+ self.args = ("%s '%s' trait of %s instance%s must be %s, "
+ "but a value of %s was specified." % (
+ self.prefix, self.name, class_of(obj), extra,
+ self.info, repr_type(self.value))),
+ else:
+ self.args = ("%s '%s' trait%s must be %s, but a value of %s was "
+ "specified." % (self.prefix, self.name, extra,
+ self.info, repr_type(self.value))),
+
+#-------------------------------------------------------------------------------
+# 'TraitNotificationError' class:
+#-------------------------------------------------------------------------------
+
+class TraitNotificationError ( Exception ):
+
+ pass
+
+#-------------------------------------------------------------------------------
+# 'DelegationError' class:
+#-------------------------------------------------------------------------------
+
+class DelegationError ( TraitError ):
+
+ def __init__ ( self, args ):
+ # .args must be a tuple.
+ self.args = args,
+
+#-------------------------------------------------------------------------------
+# Export the defined exceptions to the C-base traits module:
+#-------------------------------------------------------------------------------
+
+from . import ctraits
+ctraits._exceptions( TraitError, DelegationError )
diff --git a/pool/shard009/Python/0086306_user_base.py b/pool/shard009/Python/0086306_user_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f738bb8a05ac2cbc7ac18ff471a04ea0c034be5f
--- /dev/null
+++ b/pool/shard009/Python/0086306_user_base.py
@@ -0,0 +1,34 @@
+import sys, glob
+from bft2f_pb2 import *
+sys.path.append('gen-py')
+from auth_service import Auth_Service
+from auth_service.ttypes import *
+
+from thrift import Thrift
+from thrift.transport import TSocket
+from thrift.transport import TTransport
+from thrift.protocol import TBinaryProtocol
+
+USER_PORT = 9090
+ETC_HOSTS_FILE_NAME="bft2f_etc_hosts"
+
+def get_host_ip(host_name):
+ with open(ETC_HOSTS_FILE_NAME, "r+") as f:
+ for l in f.readlines():
+ name, ip = l.split("\t")
+ if host_name == name:
+ return ip
+
+
+def get_client(client_id='c0'):
+ client_ip = get_host_ip(client_id)
+ transport = TSocket.TSocket(client_ip, USER_PORT)
+ transport.setTimeout(20000)
+ transport = TTransport.TBufferedTransport(transport)
+ protocol = TBinaryProtocol.TBinaryProtocol(transport)
+ client = Auth_Service.Client(protocol)
+ transport.open()
+
+ return client, transport
+
+
diff --git a/pool/shard009/Python/0086307_sqlite.py b/pool/shard009/Python/0086307_sqlite.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8198b79651a7253d514825cafa7df61e481dbda
--- /dev/null
+++ b/pool/shard009/Python/0086307_sqlite.py
@@ -0,0 +1,102 @@
+import sqlite3
+
+import sqlm.resultset
+
+class Statement:
+ def __init__(self, connection, stmt):
+ cursor = connection.cursor()
+
+ self.bindnames = []
+ self.bindparams = {}
+
+ self.cursor = cursor
+ self.stmt = stmt
+
+ def __getitem__(self, bindname):
+ # let it fail as this is *not* supported on SQLite
+ return self.cursor.bindparams[bindname.upper()].getvalue()
+
+ def execute(self, **bindparams):
+ for var, value in bindparams.items():
+ self.bindparams[var.upper()] = value
+
+ self.cursor.execute(self.stmt, self.bindparams)
+
+ return sqlm.resultset.ResultSet(self.cursor)
+
+class SQLiteDialect:
+ """Abstraction layer arround the SQLite3 driver.
+ """
+
+ driver = "sqlite3"
+
+ # ------------------------------------------------------------------
+ # Cursor-related abstraction layer
+ # ------------------------------------------------------------------
+ def prepare(self, connection, stmt):
+ """Prepare a statement.
+
+ Returns a Statement instance suitable
+ to execute the statement.
+ """
+ return Statement(connection, stmt)
+
+ def connect(self, db=None, **kwargs):
+ return sqlite3.connect(db)
+
+
+
+ # ------------------------------------------------------------------
+ # Statements builder functions
+ # ------------------------------------------------------------------
+
+ def makeCreateTable(self, tbl, columns, rows):
+ """Generate a `CREATE TABLE` statement"""
+
+ lines = []
+ lines.append('CREATE TABLE "{}" ('.format(tbl))
+
+ m = []
+ for name, typ, prec, scale in columns:
+ if scale:
+ prec = '({},{})'.format(prec,scale)
+ elif prec:
+ prec = '({})'.format(prec)
+ else:
+ prec=''
+
+ m.append(' "{}" {}{}'.format(name, typ, prec))
+
+ lines.append(",\n".join(m))
+ lines.append(")")
+
+ return "\n".join(lines)
+
+ def makeInserts(self, tbl, columns, rows):
+ """Generate a multi-rows `INSERT` statement"""
+
+ lines = []
+ lines.append("INSERT ALL")
+
+ stmt = ' INTO "{}" ({})'.format(
+ tbl,
+ ", ".join(['"'+name+'"' for name, *_ in columns])
+ )
+
+ fmt = ' VALUES ({})'.format(
+ ", ".join(["{}" if t in ('NUMBER') else "'{}'"
+ for n, t, *_ in columns])
+ )
+
+ print(stmt)
+ print(fmt)
+
+ for row in rows:
+ lines.append(stmt)
+ lines.append(fmt.format(*row))
+
+
+ lines.append("SELECT * FROM DUAL")
+
+ return "\n".join(lines)
+
diff --git a/pool/shard009/Python/0086308_socket_client.py b/pool/shard009/Python/0086308_socket_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0333d0fb74b48716bfa7729210d96d76e72a520
--- /dev/null
+++ b/pool/shard009/Python/0086308_socket_client.py
@@ -0,0 +1,186 @@
+from __future__ import print_function
+from __future__ import unicode_literals
+from __future__ import division
+from __future__ import absolute_import
+from builtins import super
+from builtins import str
+from future import standard_library
+standard_library.install_aliases()
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+__license__ = """
+ Copyright (c) 2015 Pontus Sköldström, Bertrand Pechenot
+
+ This file is part of libdd, the DoubleDecker hierarchical
+ messaging system DoubleDecker is free software; you can
+ redistribute it and/or modify it under the terms of the GNU Lesser
+ General Public License (LGPL) version 2.1 as published by the Free
+ Software Foundation.
+
+ As a special exception, the Authors give you permission to link this
+ library with independent modules to produce an executable,
+ regardless of the license terms of these independent modules, and to
+ copy and distribute the resulting executable under terms of your
+ choice, provided that you also meet, for each linked independent
+ module, the terms and conditions of the license of that module. An
+ independent module is a module which is not derived from or based on
+ this library. If you modify this library, you must extend this
+ exception to your version of the library. DoubleDecker 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 program. If not,
+ see .
+"""
+
+import argparse
+import logging
+import socket
+import socketserver
+import threading
+import zmq
+from doubledecker.clientSafe import ClientSafe
+
+# Inherit ClientSafe and implement the abstract classes
+# ClientSafe does encryption and authentication using ECC (libsodium/nacl)
+
+
+class MonitoringDataHandler(socketserver.BaseRequestHandler):
+
+ def setup(self):
+ context = zmq.Context.instance()
+ self.socket = context.socket(zmq.REQ)
+ self.socket.connect('inproc://handlers')
+
+ def handle(self):
+ data = self.request.recv(1024).strip()
+ self.socket.send(data)
+
+
+class RateMonServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
+ pass
+
+class SecureCli(ClientSafe):
+ # callback called automatically everytime a point to point is sent at
+ # destination to the current client
+ def on_data(self, src, msg):
+ print("DATA from {0!s}: {1!s}".format(str(src), str(msg)))
+ if len(msg) < 2:
+ logging.error("Message received but contains only two frames")
+ return
+
+ cmd_ = msg.pop(0)
+ if 'config' == cmd_:
+ json_ = msg.pop(0)
+ print(json_)
+ elif 'pause' == cmd_:
+ self.tcp_client.connect(('127.0.0.1', 54736))
+ self.tcp_client.sendmsg({'pause': True})
+ self.tcp_client.close()
+
+ # callback called upon registration of the client with its broker
+ def on_reg(self):
+ print("The client is now connected")
+
+ # callback called when the client detects that the heartbeating with
+ # its broker has failed, it can happen if the broker is terminated/crash
+ # or if the link is broken
+ def on_discon(self):
+ print("The client got disconnected")
+
+ # callback called when the client receives an error message
+ def on_error(self, code, msg):
+ print("ERROR n#{0:d} : {1!s}".format(code, msg))
+
+ # callback called when the client receives a message on a topic he
+ # subscribed to previously
+ def on_pub(self, src, topic, msg):
+ print("PUB {0!s} from {1!s}: {2!s}".format(str(topic), str(src), str(msg)))
+
+ def start(self):
+ self.b = True
+
+ context = zmq.Context.instance()
+ self.handlers = context.socket(zmq.REP)
+ self.handlers.bind('inproc://handlers')
+
+ self.handlersThread = threading.Thread(
+ target=self.results_sender)
+
+ self.tcp_server = RateMonServer(('127.0.0.1', 9999),
+ MonitoringDataHandler)
+ self.tcp_server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.tcp_server.daemon = True
+ self.serverThread = threading.Thread(
+ target=self.tcp_server.serve_forever)
+
+ self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+ self.serverThread.start()
+ self.handlersThread.start()
+ super(SecureCli).start()
+
+ def shutdown(self):
+ self.serverThread.join()
+ self.handlersThread.join()
+ self.tcp_server.shutdown()
+ self.tcp_server.server_close()
+ super(SecureCli).shutdown()
+
+ def results_sender(self):
+ while True:
+ results = self.handlers.recv()
+ print(results)
+
+ # we inject the message received on the socket into the DD
+ self.sendmsg('agg', results)
+ self.handlers.send(b'')
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description="Generic message client")
+ parser.add_argument('name', help="Identity of this client")
+ parser.add_argument( 'customer', help="Name of the customer to get the keys (i.e. 'a' for the customer-a.json file)")
+ parser.add_argument(
+ '-d',
+ "--dealer",
+ help='URL to connect DEALER socket to, "tcp://1.2.3.4:5555"',
+ nargs='?',
+ default='tcp://127.0.0.1:5555')
+ parser.add_argument(
+ '-f',
+ "--logfile",
+ help='File to write logs to',
+ nargs='?',
+ default=None)
+ parser.add_argument(
+ '-l',
+ "--loglevel",
+ help='Set loglevel (DEBUG, INFO, WARNING, ERROR, CRITICAL)',
+ nargs='?',
+ default="INFO")
+ parser.add_argument(
+ '-k',
+ "--keyfile",
+ help='File containing the encryption/authentication keys)',
+ nargs='?',
+ required=True)
+
+ args = parser.parse_args()
+
+ numeric_level = getattr(logging, args.loglevel.upper(), None)
+ if not isinstance(numeric_level, int):
+ raise ValueError('Invalid log level: {0!s}'.format(args.loglevel))
+
+ logging.basicConfig(format='%(levelname)s:%(message)s', filename=args.logfile, level=numeric_level)
+
+ logging.info("Safe client")
+ genclient = SecureCli(name=args.name,
+ dealerurl=args.dealer,
+ customer=args.customer,
+ keyfile=args.keyfile)
+
+ logging.info("Starting DoubleDecker example client")
+ logging.info("See ddclient.py for how to send/recive and publish/subscribe")
+ genclient.start()
diff --git a/pool/shard009/Python/0086312_proxy.py b/pool/shard009/Python/0086312_proxy.py
new file mode 100644
index 0000000000000000000000000000000000000000..6632bded6b0cbc1be199f962c49c24179a3d69c7
--- /dev/null
+++ b/pool/shard009/Python/0086312_proxy.py
@@ -0,0 +1,122 @@
+import bson
+import bson.errors
+import superdesk
+
+from flask import abort, request, json
+from superdesk.utc import utcnow
+from superdesk.utils import ListCursor
+from apps.search_providers.registry import registered_search_providers
+from apps.io.search_ingest import SearchIngestService
+from superdesk.metadata.item import get_schema
+from superdesk.users.services import current_user_has_item_privilege
+
+
+PROXY_ENDPOINT = "search_providers_proxy"
+
+
+class SearchProviderProxyResource(superdesk.Resource):
+ schema = {
+ "guid": {"type": "string", "required": True},
+ "desk": superdesk.Resource.rel("desks", False, nullable=True),
+ "repo": superdesk.Resource.rel("search_providers", False, nullable=True),
+ "stage": superdesk.Resource.rel("stages", False, nullable=True),
+ "fetch_endpoint": {"type": "string", "readonly": True},
+ "search_provider": {"type": "string", "readonly": True},
+ "_fetchable": {"type": "boolean", "readonly": True},
+ }
+ schema.update(get_schema())
+
+ resource_methods = ["GET", "POST"]
+ privileges = {"POST": "archive"}
+
+
+class SearchProviderProxyService(SearchIngestService):
+ """Search Provider Proxy.
+
+ It will forward requests to specific SearchProvider instance.
+
+ Old implementations will get forwarded to its service.
+ """
+
+ def get_provider(self, provider_id=None, req=None):
+ if not provider_id:
+ provider_id = req.args.get("repo") if req else request.args.get("repo")
+ if provider_id is None:
+ abort(400)
+ try:
+ bson.ObjectId(provider_id)
+ except bson.errors.InvalidId:
+ return provider_id
+ provider = superdesk.get_resource_service("search_providers").find_one(req=None, _id=provider_id)
+ if not provider:
+ abort(400)
+ if provider.get("is_closed"):
+ abort(400)
+ if not current_user_has_item_privilege("search_providers", provider):
+ abort(403)
+ return provider
+
+ def _get_service(self, provider):
+ if isinstance(provider, str):
+ return provider if "," not in provider and provider else "search"
+ provider_data = registered_search_providers[provider["search_provider"]]
+ try:
+ return provider_data["endpoint"]
+ except KeyError:
+ return provider_data["class"](provider)
+
+ def get(self, req, lookup):
+ """Search using provider."""
+ provider = self.get_provider(req=req)
+ service = self._get_service(provider)
+ if isinstance(service, str):
+ return superdesk.get_resource_service(service).get(req, lookup)
+ query = self._get_query(req)
+ params = json.loads(req.args["params"]) if req.args.get("params") else {}
+ try:
+ items = service.find(query, params)
+ except TypeError: # BC
+ items = service.find(query)
+ if isinstance(items, list):
+ items = ListCursor(items)
+ for item in items:
+ self._set_item_defaults(item, provider)
+ return items
+
+ def create(self, docs, **kwargs):
+ """Archive items from provider."""
+ provider = self.get_provider()
+ service = self._get_service(provider)
+ if isinstance(service, str):
+ return superdesk.get_resource_service(service).create(docs, **kwargs)
+ return super().create(docs, **kwargs)
+
+ def fetch(self, guid):
+ """Fetch single item from provider to archive it."""
+ provider = self.get_provider()
+ service = self._get_service(provider)
+ if isinstance(service, str):
+ return superdesk.get_resource_service(service).fetch(guid)
+ item = service.fetch(guid)
+ self._set_item_defaults(item, provider)
+ return item
+
+ def fetch_rendition(self, rendition, item):
+ """Fetch binary from provider."""
+ provider = self.get_provider(provider_id=item.get("ingest_provider"))
+ service = self._get_service(provider)
+ if isinstance(service, str):
+ return superdesk.get_resource_service(service).fetch_rendition(self, rendition)
+ return service.fetch_file(rendition.get("href"), rendition=rendition, item=item)
+
+ def _set_item_defaults(self, item, provider):
+ """Add default values to external items."""
+ now = utcnow()
+ item.setdefault("_id", item.get("guid") or bson.ObjectId())
+ item.setdefault("_type", "externalsource")
+ item.setdefault("type", "picture")
+ item.setdefault("pubstatus", "usable")
+ item.setdefault("firstcreated", now)
+ item.setdefault("versioncreated", now)
+ item.setdefault("fetch_endpoint", PROXY_ENDPOINT)
+ item.setdefault("ingest_provider", str(provider["_id"]))
diff --git a/pool/shard009/Python/0086313_update.py b/pool/shard009/Python/0086313_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a4414ea6c867d263afd40120960d3aacd3ed5b4
--- /dev/null
+++ b/pool/shard009/Python/0086313_update.py
@@ -0,0 +1,201 @@
+from bika.lims.jsonapi import set_fields_from_request
+from plone.jsonapi.core import router
+from plone.jsonapi.core.interfaces import IRouteProvider
+from zExceptions import BadRequest
+from zope import interface
+import json
+import transaction
+
+
+class Update(object):
+ interface.implements(IRouteProvider)
+
+ def initialize(self, context, request):
+ pass
+
+ @property
+ def routes(self):
+ return (
+ ("/update", "update", self.update, dict(methods=['GET', 'POST'])),
+ ("/update_many", "update_many", self.update_many, dict(methods=['GET', 'POST'])),
+ )
+
+ def update(self, context, request):
+ """/@@API/update: Update existing object values
+
+ Required parameters:
+
+ - obj_path: path to the object, relative to plone site root.
+ - fields: json value, dict: key:value = fieldname:value.
+
+ {
+ runtime: Function running time.
+ error: true or string(message) if error. false if no error.
+ success: true or string(message) if success. false if no success.
+ :
+ ...
+ }
+
+ So.
+
+ >>> portal = layer['portal']
+ >>> portal_url = portal.absolute_url()
+ >>> from plone.app.testing import SITE_OWNER_NAME
+ >>> from plone.app.testing import SITE_OWNER_PASSWORD
+
+ Update a client's existing address:
+
+ >>> browser = layer['getBrowser'](portal, loggedIn=True, username=SITE_OWNER_NAME, password=SITE_OWNER_PASSWORD)
+ >>> browser.open(portal_url+"/@@API/update?", "&".join([
+ ... "obj_path=/clients/client-1",
+ ... "title=Test",
+ ... "PostalAddress={'address': '1 Wendy Way', 'city': 'Johannesburg', 'zip': '9000', 'state': 'Gauteng', 'district': '', 'country':'South Africa'}"
+ ... ]))
+ >>> browser.contents
+ '{..."success": true...}'
+
+ quickly check that it saved:
+
+ >>> browser = layer['getBrowser'](portal, loggedIn=True, username=SITE_OWNER_NAME, password=SITE_OWNER_PASSWORD)
+ >>> browser.open(portal_url+"/@@API/read?", "&".join([
+ ... "id=client-1",
+ ... "include_fields=PostalAddress",
+ ... ]))
+ >>> browser.contents
+ '{...1 Wendy Way...}'
+
+ Try the same with a nonsense fieldname:
+
+ >>> browser = layer['getBrowser'](portal, loggedIn=True, username=SITE_OWNER_NAME, password=SITE_OWNER_PASSWORD)
+ >>> browser.open(portal_url+"/@@API/update?", "&".join([
+ ... "obj_path=/clients/client-1",
+ ... "Thing=Fish",
+ ... ]))
+ >>> browser.contents
+ '{...The following request fields were not used: ...Thing...}'
+
+ Setting the value of a RefereceField to "" or None (null) should not cause
+ an error; setting an empty value should clear the field
+
+ >>> browser = layer['getBrowser'](portal, loggedIn=True, username=SITE_OWNER_NAME, password=SITE_OWNER_PASSWORD)
+ >>> browser.open(portal_url+"/@@API/update?", "&".join([
+ ... "obj_path=/clients/client-1",
+ ... 'DefaultCategories=',
+ ... ]))
+ >>> browser.contents
+ '{..."success": true...}'
+
+ """
+ savepoint = transaction.savepoint()
+ self.context = context
+ self.request = request
+ self.unused = [x for x in self.request.form.keys()]
+ self.used("form.submitted")
+ self.used("__ac_name")
+ self.used("__ac_password")
+ ret = {
+ "url": router.url_for("update", force_external=True),
+ "success": False,
+ "error": True,
+ }
+ # always require obj_path
+ self.require("obj_path")
+ obj_path = self.request['obj_path']
+ self.used("obj_path")
+
+ site_path = request['PATH_INFO'].replace("/@@API/update", "")
+ obj = context.restrictedTraverse(str(site_path + obj_path))
+
+ try:
+ fields = set_fields_from_request(obj, request)
+ for field in fields:
+ self.used(field)
+ except:
+ savepoint.rollback()
+ raise
+
+ ret['success'] = True
+ ret['error'] = False
+
+ if self.unused:
+ raise BadRequest("The following request fields were not used: %s. Request aborted." % self.unused)
+
+ return ret
+
+
+ def require(self, fieldname, allow_blank=False):
+ """fieldname is required"""
+ if self.request.form and fieldname not in self.request.form.keys():
+ raise Exception("Required field not found in request: %s" % fieldname)
+ if self.request.form and (not self.request.form[fieldname] or allow_blank):
+ raise Exception("Required field %s may not have blank value")
+
+
+ def used(self, fieldname):
+ """fieldname is used, remove from list of unused fields"""
+ if fieldname in self.unused:
+ self.unused.remove(fieldname)
+
+
+ def update_many(self, context, request):
+ """/@@API/update_many: Update existing object values
+
+ This is a wrapper around the update method, allowing multiple updates
+ to be combined into a single request.
+
+ required parameters:
+
+ - input_values: A json-encoded dictionary.
+ Each key is an obj_path, and each value is a dictionary
+ containing key/value pairs to be set on the object.
+
+ Return value:
+
+ {
+ runtime: Function running time.
+ error: true or string(message) if error. false if no error.
+ success: true or string(message) if success. false if no success.
+ updates: return values from update
+ }
+ """
+ self.context = context
+ self.request = request
+ self.unused = [x for x in self.request.form.keys()]
+ self.used("form.submitted")
+ self.used("__ac_name")
+ self.used("__ac_password")
+ ret = {
+ "url": router.url_for("update_many", force_external=True),
+ "success": False,
+ "error": True,
+ "updates": [],
+ }
+
+ input_values = json.loads(request.get('input_values', '[]'))
+ if not input_values:
+ raise BadRequest("missing input_values")
+ site_path = request['PATH_INFO'].replace("/@@API/update_many", "")
+
+ for obj_path, i in input_values.items():
+ savepoint = transaction.savepoint()
+ if not obj_path.startswith("/"):
+ obj_path = "/" + obj_path
+ if obj_path.startswith(site_path):
+ obj_path = obj_path[len(site_path):]
+ obj = context.restrictedTraverse(str(site_path + obj_path))
+ this_ret = {
+ "url": router.url_for("update_many", force_external=True),
+ "success": False,
+ "error": True,
+ }
+ try:
+ set_fields_from_request(obj, i)
+ except:
+ savepoint.rollback()
+ raise
+ this_ret['success'] = True
+ this_ret['error'] = False
+ ret['updates'].append(this_ret)
+ ret['success'] = True
+ ret['error'] = False
+ return ret
diff --git a/pool/shard009/Python/0086315_test_log.py b/pool/shard009/Python/0086315_test_log.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f23492b97d0222f28f31b64b7dba70879ab8547
--- /dev/null
+++ b/pool/shard009/Python/0086315_test_log.py
@@ -0,0 +1,59 @@
+import unittest2
+from zounds.util import simple_in_memory_settings
+import featureflow as ff
+from .preprocess import Log, PreprocessingPipeline
+import numpy as np
+
+
+class LogTests(unittest2.TestCase):
+ def get_model(self):
+ @simple_in_memory_settings
+ class Model(ff.BaseModel):
+ log = ff.PickleFeature(
+ Log,
+ store=False)
+
+ pipeline = ff.PickleFeature(
+ PreprocessingPipeline,
+ needs=(log,),
+ store=True)
+
+ training = np.random.random_sample((10, 3))
+ _id = Model.process(log=training)
+ return Model(_id)
+
+ def test_forward_transform_preserves_sign_large_values(self):
+ model = self.get_model()
+ inp = (np.random.random_sample((100, 3)) * 1000) - 500
+ s1 = np.sign(inp)
+ result = model.pipeline.transform(inp)
+ s2 = np.sign(result.data)
+ self.assertTrue(np.all(s1 == s2))
+
+ def test_forward_transform_preserves_sign(self):
+ model = self.get_model()
+ inp = np.random.random_sample((100, 3)) - 0.5
+ s1 = np.sign(inp)
+ result = model.pipeline.transform(inp)
+ s2 = np.sign(result.data)
+ self.assertTrue(np.all(s1 == s2))
+
+ def test_backward_transform_reconstructs_data_large_values(self):
+ model = self.get_model()
+ inp = (np.random.random_sample((100, 3)) * 1000) - 500
+ result = model.pipeline.transform(inp)
+ inverted = result.inverse_transform()
+ np.testing.assert_allclose(inp, inverted)
+
+ def test_backward_transform_reconstructs_data(self):
+ model = self.get_model()
+ inp = np.random.random_sample((100, 3)) - 0.5
+ result = model.pipeline.transform(inp)
+ inverted = result.inverse_transform()
+ np.testing.assert_allclose(inp, inverted)
+
+ def test_pipeline_requires_no_inversion_data(self):
+ model = self.get_model()
+ inp = (np.random.random_sample((100, 3)) * 1000) - 500
+ result = model.pipeline.transform(inp)
+ self.assertFalse(result.inversion_data[0])
diff --git a/pool/shard009/Python/0086316_setup.py b/pool/shard009/Python/0086316_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c614aebbd0bfe08f761df42528cf1d3bb03810
--- /dev/null
+++ b/pool/shard009/Python/0086316_setup.py
@@ -0,0 +1,47 @@
+#!/usr/bin/python
+#
+
+from distutils.core import setup
+from distutils.version import LooseVersion
+import os
+
+def is_package(path):
+ return (
+ os.path.isdir(path) and
+ os.path.isfile(os.path.join(path, '__init__.py'))
+ )
+
+def find_packages(path, base="" ):
+ """ Find all packages in path """
+ packages = {}
+ for item in os.listdir(path):
+ dir = os.path.join(path, item)
+ if os.path.isdir(dir):
+ if base:
+ module_name = "%(base)s.%(item)s" % vars()
+ else:
+ module_name = item
+ if is_package( dir ):
+ packages[module_name] = dir
+ packages.update(find_packages(dir, module_name))
+ return packages
+
+
+packages = find_packages(".")
+package_names = packages.keys()
+
+setup(name = "guild-kamaelia",
+ version = "0.0.2",
+ description = "Kamaelia partial-compatibility layer for guild",
+ url='http://www.sparkslabs.com/michael/',
+ author='Michael Sparks (sparkslabs)',
+ author_email="sparks.m@gmail.com",
+ license='Apache Software License',
+
+ packages = package_names,
+ package_dir = packages,
+ package_data={'': ['templates/*']},
+ long_description = """
+Kamaelia partial-compatibility layer for guild
+"""
+ )
diff --git a/pool/shard009/Python/0086317_TransferClient.py b/pool/shard009/Python/0086317_TransferClient.py
new file mode 100644
index 0000000000000000000000000000000000000000..64a928c47a5208971f0b3eb181d9221498d72c33
--- /dev/null
+++ b/pool/shard009/Python/0086317_TransferClient.py
@@ -0,0 +1,215 @@
+""" This is for transfers what RPCClient is for RPC calls
+"""
+import os
+
+from DIRAC import S_OK, S_ERROR
+from DIRAC.Core.Utilities import File
+from DIRAC.Core.DISET.private.BaseClient import BaseClient
+from DIRAC.Core.DISET.private.FileHelper import FileHelper
+
+
+class TransferClient(BaseClient):
+ def _sendTransferHeader(self, actionName, fileInfo):
+ """
+ Send the header of the transfer
+
+ :type actionName: string
+ :param actionName: Action to execute
+ :type fileInfo: tuple
+ :param fileInfo: Information of the target file/bulk
+ :return: S_OK/S_ERROR
+ """
+ retVal = self._connect()
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ # FFC -> File from Client
+ retVal = self._proposeAction(transport, ("FileTransfer", actionName))
+ if not retVal["OK"]:
+ return retVal
+ # We need to convert to list
+ retVal = transport.sendData(S_OK(list(fileInfo)))
+ if not retVal["OK"]:
+ return retVal
+ retVal = transport.receiveData()
+ if not retVal["OK"]:
+ return retVal
+ return S_OK((trid, transport))
+ except Exception as e:
+ self._disconnect(trid)
+ return S_ERROR("Cound not request transfer: %s" % str(e))
+
+ def sendFile(self, filename, fileId, token=""):
+ """
+ Send a file to server
+
+ :type filename: string / file descriptor / file object
+ :param filename: File to send to server
+ :type fileId: any
+ :param fileId: Identification of the file being sent
+ :type token: string
+ :param token: Optional token for the file
+ :return: S_OK/S_ERROR
+ """
+ fileHelper = FileHelper()
+ if "NoCheckSum" in token:
+ fileHelper.disableCheckSum()
+ retVal = fileHelper.getFileDescriptor(filename, "r")
+ if not retVal["OK"]:
+ return retVal
+ fd = retVal["Value"]
+ retVal = self._sendTransferHeader("FromClient", (fileId, token, File.getSize(filename)))
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ fileHelper.setTransport(transport)
+ retVal = fileHelper.FDToNetwork(fd)
+ if not retVal["OK"]:
+ return retVal
+ retVal = transport.receiveData()
+ return retVal
+ finally:
+ self._disconnect(trid)
+
+ def receiveFile(self, filename, fileId, token=""):
+ """
+ Receive a file from the server
+
+ :type filename: string / file descriptor / file object
+ :param filename: File to receive from server
+ :type fileId: any
+ :param fileId: Identification of the file being received
+ :type token: string
+ :param token: Optional token for the file
+ :return: S_OK/S_ERROR
+ """
+ fileHelper = FileHelper()
+ if "NoCheckSum" in token:
+ fileHelper.disableCheckSum()
+ retVal = fileHelper.getDataSink(filename)
+ if not retVal["OK"]:
+ return retVal
+ dS = retVal["Value"]
+ closeAfterUse = retVal["closeAfterUse"]
+ retVal = self._sendTransferHeader("ToClient", (fileId, token))
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ fileHelper.setTransport(transport)
+ retVal = fileHelper.networkToDataSink(dS)
+ if not retVal["OK"]:
+ return retVal
+ retVal = transport.receiveData()
+ if closeAfterUse:
+ dS.close()
+ return retVal
+ finally:
+ self._disconnect(trid)
+
+ def __checkFileList(self, fileList):
+ bogusEntries = []
+ for entry in fileList:
+ if not os.path.exists(entry):
+ bogusEntries.append(entry)
+ return bogusEntries
+
+ def sendBulk(self, fileList, bulkId, token="", compress=True, bulkSize=-1, onthefly=True):
+ """
+ Send a bulk of files to server
+
+ :type fileList: list of ( string / file descriptor / file object )
+ :param fileList: Files to send to server
+ :type bulkId: any
+ :param bulkId: Identification of the files being sent
+ :type token: string
+ :param token: Token for the bulk
+ :type compress: boolean
+ :param compress: Enable compression for the bulk. By default its True
+ :type bulkSize: integer
+ :param bulkSize: Optional size of the bulk
+ :return: S_OK/S_ERROR
+ """
+ bogusEntries = self.__checkFileList(fileList)
+ if bogusEntries:
+ return S_ERROR("Some files or directories don't exist :\n\t%s" % "\n\t".join(bogusEntries))
+ if compress:
+ bulkId = "%s.tar.bz2" % bulkId
+ else:
+ bulkId = "%s.tar" % bulkId
+ retVal = self._sendTransferHeader("BulkFromClient", (bulkId, token, bulkSize))
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ fileHelper = FileHelper(transport)
+ retVal = fileHelper.bulkToNetwork(fileList, compress, onthefly)
+ if not retVal["OK"]:
+ return retVal
+ retVal = transport.receiveData()
+ return retVal
+ finally:
+ self._disconnect(trid)
+
+ def receiveBulk(self, destDir, bulkId, token="", compress=True):
+ """
+ Receive a bulk of files from server
+
+ :type destDir: list of ( string / file descriptor / file object )
+ :param destDir: Files to receive from server
+ :type bulkId: any
+ :param bulkId: Identification of the files being received
+ :type token: string
+ :param token: Token for the bulk
+ :type compress: boolean
+ :param compress: Enable compression for the bulk. By default its True
+ :return: S_OK/S_ERROR
+ """
+ if not os.path.isdir(destDir):
+ return S_ERROR("%s is not a directory for bulk receival" % destDir)
+ if compress:
+ bulkId = "%s.tar.bz2" % bulkId
+ else:
+ bulkId = "%s.tar" % bulkId
+ retVal = self._sendTransferHeader("BulkToClient", (bulkId, token))
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ fileHelper = FileHelper(transport)
+ retVal = fileHelper.networkToBulk(destDir, compress)
+ if not retVal["OK"]:
+ return retVal
+ retVal = transport.receiveData()
+ return retVal
+ finally:
+ self._disconnect(trid)
+
+ def listBulk(self, bulkId, token="", compress=True):
+ """
+ List the contents of a bulk
+
+ :type bulkId: any
+ :param bulkId: Identification of the bulk to list
+ :type token: string
+ :param token: Token for the bulk
+ :type compress: boolean
+ :param compress: Enable compression for the bulk. By default its True
+ :return: S_OK/S_ERROR
+ """
+ if compress:
+ bulkId = "%s.tar.bz2" % bulkId
+ else:
+ bulkId = "%s.tar" % bulkId
+ trid = None
+ retVal = self._sendTransferHeader("ListBulk", (bulkId, token))
+ if not retVal["OK"]:
+ return retVal
+ trid, transport = retVal["Value"]
+ try:
+ response = transport.receiveData(1048576)
+ return response
+ finally:
+ self._disconnect(trid)
diff --git a/pool/shard009/Python/0086330_test_multireddit.py b/pool/shard009/Python/0086330_test_multireddit.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b537ac8efdb999768b630cf1f1fcda0b1974786
--- /dev/null
+++ b/pool/shard009/Python/0086330_test_multireddit.py
@@ -0,0 +1,81 @@
+"""Tests for Multireddit class."""
+
+from __future__ import print_function, unicode_literals
+from praw import errors, objects
+from .helper import PRAWTest, betamax
+
+
+class MultiredditTest(PRAWTest):
+
+ def betamax_init(self):
+ self.r.login(self.un, self.un_pswd, disable_warning=True)
+
+ def test_multireddit_representations(self):
+ multi = objects.Multireddit(self.r, author='Foo', name='Bar')
+ self.assertEqual("Multireddit(author='Foo', name='Bar')", repr(multi))
+ self.assertEqual('Bar', str(multi))
+
+ @betamax()
+ def test_add_and_remove_subreddit(self):
+ multi = self.r.user.get_multireddits()[0]
+ self.assertTrue(self.sr in (x.display_name for x in multi.subreddits))
+ multi.remove_subreddit(self.sr)
+ multi.refresh()
+
+ self.assertFalse(self.sr in (x.display_name for x in multi.subreddits))
+ multi.add_subreddit(self.sr)
+ multi.refresh()
+ self.assertTrue(self.sr in (x.display_name for x in multi.subreddits))
+
+ @betamax()
+ def test_create_and_delete_multireddit(self):
+ name = 'PRAW_{0}'.format(self.r.modhash)[:15]
+ multi = self.r.create_multireddit(name)
+ self.assertEqual(name.lower(), multi.name.lower())
+ self.assertEqual([], multi.subreddits)
+
+ multi.delete()
+ self.assertRaises(errors.NotFound, multi.refresh)
+
+ @betamax()
+ def test_copy_multireddit(self):
+ name = 'praw_{0}'.format(self.r.modhash)[:15]
+ multi = self.r.user.get_multireddits()[0]
+ new_multi = multi.copy(name)
+ self.assertNotEqual(multi.name, new_multi.name)
+ self.assertEqual(multi.path, new_multi.copied_from)
+ self.assertEqual(name, new_multi.name)
+ self.assertEqual(multi.subreddits, new_multi.subreddits)
+
+ @betamax()
+ def test_edit_multireddit(self):
+ name = 'PRAW_{0}'.format(self.r.modhash)[:15]
+ multi = self.r.user.get_multireddits()[0]
+ self.assertNotEqual(name, multi.description_md)
+ self.assertEqual(name, multi.edit(description_md=name).description_md)
+ self.assertEqual(name, multi.refresh().description_md)
+
+ @betamax()
+ def test_get_my_multis(self):
+ multi = self.r.get_my_multireddits()[0]
+ self.assertEqual('publicempty', multi.display_name)
+ self.assertEqual([], multi.subreddits)
+
+ @betamax()
+ def test_get_multireddit(self):
+ multi = self.r.user.get_multireddit('publicempty')
+ self.assertEqual('/user/{0}/m/{1}'.format(self.un, 'publicempty'),
+ multi.path)
+
+ @betamax()
+ def test_multireddit_get_new(self):
+ multi = self.r.user.get_multireddit('publicempty')
+ self.assertEqual([], list(multi.get_new()))
+
+ @betamax()
+ def test_rename_multireddit(self):
+ name = 'renamed_{0}'.format(self.r.modhash)[:15]
+ multi = self.r.user.get_multireddits()[0]
+ self.assertNotEqual(name, multi.name)
+ self.assertEqual(name, multi.rename(name).name)
+ self.assertEqual(name, multi.refresh().name)
diff --git a/pool/shard009/Python/0086331_0035_auto_20150202_0937.py b/pool/shard009/Python/0086331_0035_auto_20150202_0937.py
new file mode 100644
index 0000000000000000000000000000000000000000..055a0981370e4cec75036c91edf03f8e5d6c3ebd
--- /dev/null
+++ b/pool/shard009/Python/0086331_0035_auto_20150202_0937.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+import datetime
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('rules', '0034_auto_20150111_2200'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='category',
+ name='created_date',
+ field=models.DateTimeField(default=datetime.datetime(2015, 2, 2, 9, 37, 12, 518274), verbose_name=b'date created'),
+ preserve_default=True,
+ ),
+ migrations.AlterField(
+ model_name='sourceatversion',
+ name='updated_date',
+ field=models.DateTimeField(default=datetime.datetime(2015, 2, 2, 9, 37, 12, 517591), verbose_name=b'date updated', blank=True),
+ preserve_default=True,
+ ),
+ migrations.AlterField(
+ model_name='sourceupdate',
+ name='created_date',
+ field=models.DateTimeField(default=datetime.datetime(2015, 2, 2, 9, 37, 12, 517921), verbose_name=b'date of update', blank=True),
+ preserve_default=True,
+ ),
+ ]
diff --git a/pool/shard009/Python/0086332_users_test.py b/pool/shard009/Python/0086332_users_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cae6d4c08f4450e51e6c9bf4ab1d3e84579d8d9
--- /dev/null
+++ b/pool/shard009/Python/0086332_users_test.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python
+
+# pylint: disable=unused-import,g-bad-import-order
+from grr.lib import server_plugins
+# pylint: enable=unused-import,g-bad-import-order
+
+from grr.lib import aff4
+from grr.lib import rdfvalue
+from grr.lib import test_lib
+
+
+class UsersTest(test_lib.GRRBaseTest):
+
+ def setUp(self):
+ super(UsersTest, self).setUp()
+
+ self.user = aff4.FACTORY.Create("aff4:/users/foo",
+ aff4_type="GRRUser",
+ mode="rw",
+ token=self.token)
+ self.user.Flush()
+
+ def testNoNotificationIsReturnedIfItWasNotSet(self):
+ self.assertFalse(self.user.GetPendingGlobalNotifications())
+
+ def testNotificationIsReturnedWhenItIsSet(self):
+ with aff4.FACTORY.Create(aff4.GlobalNotificationStorage.DEFAULT_PATH,
+ aff4_type="GlobalNotificationStorage", mode="rw",
+ token=self.token) as storage:
+ storage.AddNotification(rdfvalue.GlobalNotification(
+ type=rdfvalue.GlobalNotification.Type.ERROR, header="foo",
+ content="bar", link="http://www.google.com"))
+
+ notifications = self.user.GetPendingGlobalNotifications()
+ self.assertTrue(notifications)
+ self.assertEqual(len(notifications), 1)
+ self.assertEqual(notifications[0].header, "foo")
+ self.assertEqual(notifications[0].content, "bar")
+
+ def testNotificationIsNotReturnedWhenItExpires(self):
+ with test_lib.FakeTime(100):
+ with aff4.FACTORY.Create(aff4.GlobalNotificationStorage.DEFAULT_PATH,
+ aff4_type="GlobalNotificationStorage", mode="rw",
+ token=self.token) as storage:
+ storage.AddNotification(rdfvalue.GlobalNotification(
+ type=rdfvalue.GlobalNotification.Type.ERROR, header="foo",
+ content="bar", duration=rdfvalue.Duration("1h"),))
+
+ with test_lib.FakeTime(101):
+ notifications = self.user.GetPendingGlobalNotifications()
+ self.assertTrue(notifications)
+
+ with test_lib.FakeTime(100 + 3600 + 1):
+ notifications = self.user.GetPendingGlobalNotifications()
+ self.assertFalse(notifications)
diff --git a/pool/shard009/Python/0086338_attributes.py b/pool/shard009/Python/0086338_attributes.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8e0e136fb5693e0a37ecea854a2da5830e9cad3
--- /dev/null
+++ b/pool/shard009/Python/0086338_attributes.py
@@ -0,0 +1,156 @@
+"""
+Entity attributes.
+
+This file is part of the everest project.
+See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
+
+Created on Dec 2, 2011.
+"""
+from everest.constants import RESOURCE_ATTRIBUTE_KINDS
+from everest.entities.interfaces import IEntity
+from everest.entities.utils import get_entity_class
+from functools import wraps
+from pyramid.compat import itervalues_
+from zope.interface import implementedBy as implemented_by # pylint: disable=E0611,F0401
+
+__docformat__ = 'reStructuredText en'
+__all__ = ['get_domain_class_attribute_iterator',
+ 'get_domain_class_attribute',
+ 'get_domain_class_attribute_iterator',
+ 'get_domain_class_attribute_names',
+ 'get_domain_class_attributes',
+ 'get_domain_class_relationship_attribute_iterator',
+ 'get_domain_class_member_attribute_iterator',
+ 'get_domain_class_terminal_attribute_iterator',
+ 'is_domain_class_collection_attribute',
+ 'is_domain_class_domain_attribute',
+ 'is_domain_class_member_attribute',
+ 'is_domain_class_terminal_attribute',
+ ]
+
+
+def _arg_to_entity_class(func):
+ @wraps(func)
+ def wrap(ent, *args):
+ if isinstance(ent, type) and IEntity in implemented_by(ent):
+ ent_cls = ent
+ else:
+ ent_cls = get_entity_class(ent)
+ return func(ent_cls, *args)
+ return wrap
+
+
+def is_domain_class_terminal_attribute(ent, attr_name):
+ """
+ Checks if the given attribute name is a terminal attribute of the given
+ registered resource.
+ """
+ attr = get_domain_class_attribute(ent, attr_name)
+ return attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL
+
+
+def is_domain_class_member_attribute(ent, attr_name):
+ """
+ Checks if the given attribute name is a entity attribute of the given
+ registered resource.
+ """
+ attr = get_domain_class_attribute(ent, attr_name)
+ return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER
+
+
+def is_domain_class_collection_attribute(ent, attr_name):
+ """
+ Checks if the given attribute name is a aggregate attribute of the given
+ registered resource.
+ """
+ attr = get_domain_class_attribute(ent, attr_name)
+ return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION
+
+
+def is_domain_class_domain_attribute(ent, attr_name):
+ """
+ Checks if the given attribute name is a resource attribute (i.e., either
+ a member or a aggregate attribute) of the given registered resource.
+ """
+ attr = get_domain_class_attribute(ent, attr_name)
+ return attr != RESOURCE_ATTRIBUTE_KINDS.TERMINAL
+
+
+@_arg_to_entity_class
+def get_domain_class_attribute_names(ent):
+ """
+ Returns all attribute names of the given registered resource.
+ """
+ return ent.__everest_attributes__.keys()
+
+
+@_arg_to_entity_class
+def get_domain_class_attributes(ent):
+ """
+ Returns a dictionary mapping the attribute names of the given
+ registered resource to :class:`ResourceAttribute` instances.
+ """
+ return ent.__everest_attributes__
+
+
+@_arg_to_entity_class
+def get_domain_class_attribute(ent, name):
+ """
+ Returns the specified attribute from the map of all collected attributes
+ for the given registered resource or `None`, if the attribute could not
+ be found.
+ """
+ return ent.__everest_attributes__.get(name)
+
+
+@_arg_to_entity_class
+def get_domain_class_attribute_iterator(ent):
+ """
+ Returns an iterator over all attributes in the given registered
+ resource.
+ """
+ return itervalues_(ent.__everest_attributes__)
+
+
+@_arg_to_entity_class
+def get_domain_class_terminal_attribute_iterator(ent):
+ """
+ Returns an iterator over all terminal attributes in the given registered
+ resource.
+ """
+ for attr in itervalues_(ent.__everest_attributes__):
+ if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
+ yield attr
+
+
+@_arg_to_entity_class
+def get_domain_class_relationship_attribute_iterator(ent):
+ """
+ Returns an iterator over all terminal attributes in the given registered
+ resource.
+ """
+ for attr in itervalues_(ent.__everest_attributes__):
+ if attr.kind != RESOURCE_ATTRIBUTE_KINDS.TERMINAL:
+ yield attr
+
+
+@_arg_to_entity_class
+def get_domain_class_member_attribute_iterator(ent):
+ """
+ Returns an iterator over all terminal attributes in the given registered
+ resource.
+ """
+ for attr in itervalues_(ent.__everest_attributes__):
+ if attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER:
+ yield attr
+
+
+@_arg_to_entity_class
+def get_domain_class_collection_attribute_iterator(ent):
+ """
+ Returns an iterator over all terminal attributes in the given registered
+ resource.
+ """
+ for attr in itervalues_(ent.__everest_attributes__):
+ if attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
+ yield attr
diff --git a/pool/shard009/Python/0086340_hw_manager.py b/pool/shard009/Python/0086340_hw_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..d121f86ef31c225610388dbf585a98e0813933cc
--- /dev/null
+++ b/pool/shard009/Python/0086340_hw_manager.py
@@ -0,0 +1,55 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2010 United States Government as represented by the
+# Administrator of the National Aeronautics and Space Administration.
+# 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.
+"""
+HW extend volume manager
+"""
+
+
+import time
+import traceback
+
+from oslo.config import cfg
+
+from cinder import context
+from cinder import utils
+from cinder.volume import manager as volume_manager
+from cinder.openstack.common import log as logging
+
+LOG = logging.getLogger(__name__)
+
+
+class Hw_VolumeManager(volume_manager.VolumeManager):
+ """Manages attachable block storage devices."""
+
+ def update_service_capabilities(self, capabilities):
+ """Update the io_workload in capabilities."""
+ try:
+ ctxt = context.get_admin_context()
+ volumes = self.db.volume_get_all_by_host(ctxt, self.host)
+ io_workload = 0
+ for volume in volumes:
+ if volume['status'] in utils.IO_OPS_LIST:
+ io_workload += 1
+ capabilities['io_workload'] = io_workload
+ LOG.debug('Calculate the io_workload result, capabilities: %s' % (capabilities))
+ except Exception:
+ LOG.error('Calculate the io_workload failed, exception: %s' % (traceback.format_exc()))
+ pass
+
+ self.last_capabilities = capabilities
+
diff --git a/pool/shard009/Python/0086346_test_print.py b/pool/shard009/Python/0086346_test_print.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ebe20923beeca28369463a4b2e86ca0ef20efd
--- /dev/null
+++ b/pool/shard009/Python/0086346_test_print.py
@@ -0,0 +1,42 @@
+from confduino.boardlist import print_boards
+from confduino.hwpacklist import print_hwpacks
+from confduino.liblist import print_libraries
+from confduino.mculist import print_mcus
+from confduino.proglist import print_programmers
+from confduino.version import print_version
+from nose.tools import eq_
+from data import TEST_ARDUINO_PATHS
+import os
+
+
+def test_print():
+ for x in TEST_ARDUINO_PATHS:
+ os.environ['ARDUINO_HOME'] = x
+ print ('ARDUINO_HOME=%s' % x)
+
+ print_boards()
+ print_hwpacks()
+ print_libraries()
+ print_mcus()
+ print_programmers()
+ print_version()
+
+
+def test_cli():
+ def check_print(cmd):
+ cmd = 'python -m confduino.%s > /dev/null' % cmd
+ print (cmd)
+ eq_(os.system(cmd), 0)
+
+ for x in TEST_ARDUINO_PATHS:
+ os.environ['ARDUINO_HOME'] = x
+ print ('ARDUINO_HOME=%s' % x)
+
+ check_print('boardlist')
+ check_print('boardlist --verbose')
+ check_print('hwpacklist')
+ check_print('proglist')
+ check_print('proglist --verbose')
+ check_print('boardlist')
+ check_print('liblist')
+ check_print('mculist')
diff --git a/pool/shard009/Python/0086347_01b0cbb9a1a7_.py b/pool/shard009/Python/0086347_01b0cbb9a1a7_.py
new file mode 100644
index 0000000000000000000000000000000000000000..f447a51f1cfea739680875075ad5452528b6bbb0
--- /dev/null
+++ b/pool/shard009/Python/0086347_01b0cbb9a1a7_.py
@@ -0,0 +1,28 @@
+"""empty message
+
+Revision ID: 01b0cbb9a1a7
+Revises: 37e499a6b25
+Create Date: 2016-04-14 10:29:24.710604
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '01b0cbb9a1a7'
+down_revision = '37e499a6b25'
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.add_column('time_place', sa.Column('latitude', sa.Float(), nullable=True))
+ op.add_column('time_place', sa.Column('longitude', sa.Float(), nullable=True))
+ ### end Alembic commands ###
+
+
+def downgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.drop_column('time_place', 'longitude')
+ op.drop_column('time_place', 'latitude')
+ ### end Alembic commands ###
diff --git a/pool/shard009/Python/0086350_init__.py b/pool/shard009/Python/0086350_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a805c934c2ae1b5d3def9ee7db7d108fedfffb4
--- /dev/null
+++ b/pool/shard009/Python/0086350_init__.py
@@ -0,0 +1,60 @@
+import re
+from functools import partial
+
+from pyramid.config import Configurator
+from clldutils.path import Path
+
+from clld.interfaces import IParameter, IMapMarker, IDomainElement, IValue
+from clld.web.adapters.base import adapter_factory
+from clld.web.app import menu_item
+from clld_glottologfamily_plugin.util import LanguageByFamilyMapMarker
+
+# we must make sure custom models are known at database initialization!
+from nts import models
+
+
+class NtsMapMarker(LanguageByFamilyMapMarker):
+ def get_icon(self, ctx, req):
+ """to allow for user-selectable markers, we have to look up a possible custom
+ selection from the url params.
+ """
+ icon = None
+ if IValue.providedBy(ctx):
+ icon = ctx.domainelement.jsondata['icon']
+ elif IDomainElement.providedBy(ctx):
+ icon = ctx.jsondata['icon']
+ if icon:
+ return icon
+ return super(NtsMapMarker, self).get_icon(ctx, req)
+
+
+def main(global_config, **settings):
+ """ This function returns a Pyramid WSGI application.
+ """
+ convert = lambda spec: ''.join(c if i == 0 else c + c for i, c in enumerate(spec))
+ filename_pattern = re.compile('(?P(c|d|s|f|t)[0-9a-f]{3})\.png')
+ icons = {}
+ for fname in sorted(Path(__file__).parent.joinpath('static', 'icons').iterdir()):
+ m = filename_pattern.match(fname.name)
+ if m:
+ icons[m.group('spec')] = convert(m.group('spec'))
+ settings['icons'] = icons
+
+ config = Configurator(settings=settings)
+ config.include('clldmpg')
+ config.include('clld_glottologfamily_plugin')
+ config.registry.registerUtility(NtsMapMarker(), IMapMarker)
+ config.register_menu(
+ ('dataset', partial(menu_item, 'dataset', label='Home')),
+ ('parameters', partial(menu_item, 'parameters', label='Features')),
+ ('languages', partial(menu_item, 'languages')),
+ ('sources', partial(menu_item, 'sources')),
+ ('designers', partial(menu_item, 'contributions', label="Contributors")),
+ )
+ config.register_adapter(adapter_factory(
+ 'parameter/detail_tab.mako',
+ mimetype='application/vnd.clld.tab',
+ send_mimetype="text/plain",
+ extension='tab',
+ name='tab-separated values'), IParameter)
+ return config.make_wsgi_app()
diff --git a/pool/shard009/Python/0086352_shock_cocoon.py b/pool/shard009/Python/0086352_shock_cocoon.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c958b562ae8b9c002bcec6b8f779156e3ccacc7
--- /dev/null
+++ b/pool/shard009/Python/0086352_shock_cocoon.py
@@ -0,0 +1,63 @@
+"""Definitions for the `Shock` class."""
+from math import isnan
+from astrocats.catalog.source import SOURCE
+
+import numpy as np
+
+from mosfit.constants import C_CGS, DAY_CGS, FOUR_PI, KM_CGS, M_SUN_CGS
+from mosfit.modules.engines.engine import Engine
+
+
+# Important: Only define one ``Module`` class per file.
+
+
+class Shock(Engine):
+ """Cooling emission from shock-heated cocoon.
+
+ Follows Piro and Kollmeier 2018.
+
+ Shock heating can be turned off in bns model by setting cos_theta_cocoon=1
+ """
+
+ DIFF_CONST = M_SUN_CGS / (FOUR_PI * C_CGS * KM_CGS)
+
+ _REFERENCES = [
+ {SOURCE.BIBCODE: '2018ApJ...855..103P'}
+ ]
+
+ def process(self, **kwargs):
+ """Process module."""
+ self._times = kwargs[self.key('dense_times')]
+ self._rest_t_explosion = kwargs[self.key('resttexplosion')]
+ self._kappa = kwargs[self.key('kappa')]
+ self._m_ejecta = kwargs[self.key('mejecta')]
+ self._v_ejecta = kwargs[self.key('vejecta')]
+ # Cocoon opening angle- should be between 1 and cos_theta_open
+ # for polar KN ejecta
+ self._cos_theta_cocoon = kwargs[self.key('cos_theta_cocoon')]
+ # Shocked ejecta power law density profile
+ self._s = kwargs[self.key('s')]
+ # Shock breakout timescale in seconds
+ self._t_shock = kwargs[self.key('tshock')]
+ # Radius where material is shocked by relativistic jet:
+ R = C_CGS * self._t_shock
+
+ theta = np.arccos(self._cos_theta_cocoon)
+
+ self._tau_diff = np.sqrt(self.DIFF_CONST * self._kappa *
+ self._m_ejecta / self._v_ejecta) / DAY_CGS
+
+
+ L0 = (theta**2/2)**(1/3) * (self._m_ejecta * M_SUN_CGS *
+ self._v_ejecta * KM_CGS * R / (self._tau_diff * DAY_CGS)**2 )
+
+ ts = [
+ np.inf
+ if self._rest_t_explosion > x else (x - self._rest_t_explosion)
+ for x in self._times
+ ]
+
+ luminosities = [L0 * (t/self._tau_diff)**-(4/(self._s+2)) for t in ts]
+ luminosities = [0.0 if isnan(x) else x for x in luminosities]
+
+ return {self.dense_key('luminosities'): luminosities}
diff --git a/pool/shard009/Python/0086354_column_tests.py b/pool/shard009/Python/0086354_column_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..81eb3385361519f1dc6e891dfd77f0f7f4ee9057
--- /dev/null
+++ b/pool/shard009/Python/0086354_column_tests.py
@@ -0,0 +1,52 @@
+import datetime
+from decimal import Decimal
+import unittest
+
+from ..pyjsongooglechart import (BooleanColumn, StringColumn, NumberColumn,
+ DateColumn, DatetimeColumn, TimeofdayColumn,
+ ChartColumn)
+
+
+
+class ColumnTests(unittest.TestCase):
+ def test_base(self):
+ c = ChartColumn("name", "id", "p")
+ self.assertEqual(c.label, "name")
+ self.assertEqual(c.id, "id")
+ self.assertEqual(c.p, "p")
+
+ values = [("1",), (2, "2")]
+ c.insert_row(values[0][0])
+ c.insert_row(*values[1])
+
+ self.assertEqual(c.values[0], values[0])
+ self.assertEqual(c.values[1], (values[1][0], values[1][1]))
+ self.assertEqual(c.values, values)
+ self.assertEqual(c.values, list(c))
+
+ def test_validators(self):
+ def worker(column, bad, good):
+ self.assertRaises(ValueError, column.insert_row, bad)
+ column.insert_row(good)
+
+ c = BooleanColumn()
+ worker(c, "non-boolean", True)
+
+ c = StringColumn()
+ worker(c, 12, "isastring")
+
+ c = NumberColumn()
+ worker(c, "12.5", 12.5)
+ worker(c, Decimal("12.5"), 12)
+
+ c = DateColumn()
+ worker(c, "12-23-2012", datetime.date(2012, 12, 23))
+ worker(c, datetime.timedelta(), datetime.datetime.now())
+
+ c = DatetimeColumn()
+ worker(c, "12-23-2012", datetime.datetime(2012, 12, 23))
+ worker(c, datetime.date(2012, 12, 23), datetime.datetime.now())
+
+ c = TimeofdayColumn()
+ worker(c, "12-23-2012", datetime.datetime(2012, 12, 23))
+ worker(c, datetime.date(2012, 12, 23), datetime.datetime.now())
diff --git a/pool/shard009/Python/0086355_test_validation.py b/pool/shard009/Python/0086355_test_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ceb30c12b737856887830655c0a8beb5fd898eb
--- /dev/null
+++ b/pool/shard009/Python/0086355_test_validation.py
@@ -0,0 +1,27 @@
+# Copyright (c) 2015 Mirantis Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, 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 testtools
+import yaml
+
+from sahara_tests.scenario import validation
+
+
+class TestValidation(testtools.TestCase):
+ def test_validation(self):
+ with open("sahara_tests/unit/scenario/vanilla2_7_1.yaml",
+ "r") as yaml_file:
+ config = yaml.load(yaml_file)
+ self.assertIsNone(validation.validate(config))
diff --git a/pool/shard009/Python/0086357_go_thrift_gen.py b/pool/shard009/Python/0086357_go_thrift_gen.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d7c498b9ed756e3cda5fc0a7654876114f75b42
--- /dev/null
+++ b/pool/shard009/Python/0086357_go_thrift_gen.py
@@ -0,0 +1,178 @@
+# coding=utf-8
+# Copyright 2014 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 re
+
+from pants.backend.codegen.thrift.lib.thrift import Thrift
+from pants.base.build_environment import get_buildroot
+from pants.base.exceptions import TaskError
+from pants.base.revision import Revision
+from pants.base.workunit import WorkUnitLabel
+from pants.option.custom_types import target_option
+from pants.task.simple_codegen_task import SimpleCodegenTask
+from pants.util.dirutil import safe_mkdir
+from pants.util.memo import memoized_method, memoized_property
+from pants.util.process_handler import subprocess
+from twitter.common.collections import OrderedSet
+
+from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary
+
+
+class GoThriftGen(SimpleCodegenTask):
+
+ @classmethod
+ def register_options(cls, register):
+ super(GoThriftGen, cls).register_options(register)
+
+ register('--strict', default=True, fingerprint=True, type=bool,
+ help='Run thrift compiler with strict warnings.')
+ register('--gen-options', advanced=True, fingerprint=True,
+ help='Use these apache thrift go gen options.')
+ register('--thrift-import', type=str, advanced=True, fingerprint=True,
+ help='Use this thrift-import gen option to thrift.')
+ register('--thrift-import-target', type=target_option, advanced=True,
+ help='Use this thrift import on symbolic defs.')
+ register('--multiple-files-per-target-override', advanced=True, fingerprint=True,
+ help='If set, multiple thrift files will be allowed per target, regardless of '
+ 'thrift version. Otherwise, only versions greater than 0.10.0 will be assumed to '
+ 'support multiple files.')
+
+ @classmethod
+ def subsystem_dependencies(cls):
+ return super(GoThriftGen, cls).subsystem_dependencies() + (Thrift.scoped(cls),)
+
+ @property
+ def _thrift_binary(self):
+ return self._thrift.select(context=self.context)
+
+ @property
+ def _thrift_version(self):
+ return self._thrift.version(context=self.context)
+
+ @memoized_property
+ def _thrift(self):
+ return Thrift.scoped_instance(self)
+
+ @memoized_property
+ def _deps(self):
+ thrift_import_target = self.get_options().thrift_import_target
+ if thrift_import_target is None:
+ raise TaskError('Option thrift_import_target in scope {} must be set.'.format(
+ self.options_scope))
+ thrift_imports = self.context.resolve(thrift_import_target)
+ return thrift_imports
+
+ @memoized_property
+ def _service_deps(self):
+ service_deps = self.get_options().get('service_deps')
+ return list(self.resolve_deps(service_deps)) if service_deps else self._deps
+
+ SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)')
+ NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE)
+
+ def _declares_service(self, source):
+ with open(source) as thrift:
+ return any(line for line in thrift if self.SERVICE_PARSER.search(line))
+
+ def _get_go_namespace(self, source):
+ with open(source) as thrift:
+ namespace = self.NAMESPACE_PARSER.search(thrift.read())
+ if not namespace:
+ raise TaskError('Thrift file {} must contain "namespace go "', source)
+ return namespace.group(1)
+
+ def synthetic_target_extra_dependencies(self, target, target_workdir):
+ for source in target.sources_relative_to_buildroot():
+ if self._declares_service(os.path.join(get_buildroot(), source)):
+ return self._service_deps
+ return self._deps
+
+ def synthetic_target_type(self, target):
+ return GoThriftGenLibrary
+
+ def is_gentarget(self, target):
+ return isinstance(target, GoThriftLibrary)
+
+ @memoized_method
+ def _validate_supports_more_than_one_source(self):
+ # Support for doing the right thing with multiple files landed in
+ # https://issues.apache.org/jira/browse/THRIFT-3776; first available in 0.10.0
+ if self.get_options().multiple_files_per_target_override:
+ return
+ required_version = '0.10.0'
+ if Revision.semver(self._thrift_version) < Revision.semver(required_version):
+ raise TaskError('A single .thrift source file is supported per go_thrift_library with thrift '
+ 'version `{}`: upgrade to at least `{}` to support multiple files.'.format(
+ self._thrift_version, required_version))
+
+ @memoized_property
+ def _thrift_cmd(self):
+ cmd = [self._thrift_binary]
+ thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import)
+ if thrift_import is None:
+ raise TaskError('Option thrift_import in scope {} must be set.'.format(self.options_scope))
+ gen_options = self.get_options().gen_options
+ if gen_options:
+ gen_options += ',' + thrift_import
+ else:
+ gen_options = thrift_import
+ cmd.extend(('--gen', 'go:{}'.format(gen_options)))
+
+ if self.get_options().strict:
+ cmd.append('-strict')
+ if self.get_options().level == 'debug':
+ cmd.append('-verbose')
+ return cmd
+
+ def _generate_thrift(self, target, target_workdir):
+ target_cmd = self._thrift_cmd[:]
+
+ bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt))
+ for base in bases:
+ target_cmd.extend(('-I', base))
+
+ target_cmd.extend(('-o', target_workdir))
+
+ all_sources = list(target.sources_relative_to_buildroot())
+ if len(all_sources) != 1:
+ self._validate_supports_more_than_one_source()
+
+ for source in all_sources:
+ file_cmd = target_cmd + [os.path.join(get_buildroot(), source)]
+ with self.context.new_workunit(name=source,
+ labels=[WorkUnitLabel.TOOL],
+ cmd=' '.join(file_cmd)) as workunit:
+ result = subprocess.call(file_cmd,
+ stdout=workunit.output('stdout'),
+ stderr=workunit.output('stderr'))
+ if result != 0:
+ raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result))
+
+ gen_dir = os.path.join(target_workdir, 'gen-go')
+ src_dir = os.path.join(target_workdir, 'src')
+ safe_mkdir(src_dir)
+ go_dir = os.path.join(target_workdir, 'src', 'go')
+ os.rename(gen_dir, go_dir)
+
+ @classmethod
+ def product_types(cls):
+ return ['go']
+
+ def execute_codegen(self, target, target_workdir):
+ self._generate_thrift(target, target_workdir)
+
+ @property
+ def _copy_target_attributes(self):
+ """Override `_copy_target_attributes` to exclude `provides`."""
+ return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides']
+
+ def synthetic_target_dir(self, target, target_workdir):
+ all_sources = list(target.sources_relative_to_buildroot())
+ source = all_sources[0]
+ namespace = self._get_go_namespace(source)
+ return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep))
diff --git a/pool/shard009/Python/0086364_projects.py b/pool/shard009/Python/0086364_projects.py
new file mode 100644
index 0000000000000000000000000000000000000000..908e60d3f6bdadae2d2287358c5daf515d30a80d
--- /dev/null
+++ b/pool/shard009/Python/0086364_projects.py
@@ -0,0 +1,75 @@
+
+import buildbot
+import jinja2
+import json
+import re
+import subprocess
+import sys
+import twisted
+from twisted.python import log
+from twisted.internet import defer
+from twisted.web.util import Redirect
+from buildbot.status.web.base import ActionResource
+from buildbot.status.web.base import HtmlResource
+from buildbot.status.web.base import path_to_root
+from buildbot.status.web.base import path_to_authzfail
+
+
+class ProjectsResource(HtmlResource):
+ pageTitle = "Project Repos"
+
+ def content(self, request, cxt):
+ cxt.update(dict(buildbot=buildbot.version,
+ twisted=twisted.__version__,
+ jinja=jinja2.__version__,
+ python=sys.version,
+ platform=sys.platform))
+
+ template = request.site.buildbot_service.templates.get_template("projects.html")
+ template.autoescape = True
+ return template.render(**cxt)
+
+class AddProjectResource(ActionResource):
+ @defer.inlineCallbacks
+ def performAction(self, req):
+ authz = self.getAuthz(req)
+ print authz.getUsername(req), authz.authenticated(req)
+ res = yield authz.actionAllowed('forceBuild', req)
+ if not res:
+ defer.returnValue(Redirect(path_to_authzfail(req)))
+ return
+ projects = json.load(open('projects.json'))
+ log.msg('loaded projects.json')
+
+ log.msg(str(req.args.items()))
+ projectname = req.args.get('projectname', [])[0]
+ projectrepo = req.args.get('projectrepo', [])[0]
+ paths = req.args.get('path', [])
+ boardaddr = req.args.get('boardaddr', [])[0]
+ log.msg(str(req.args.get('arches', [])))
+ arches = req.args.get('arches', ['bluesim'])
+ revisions = req.args.get('revision', [])
+ branches = req.args.get('branch', [])
+
+ m = re.match('git://github.com/(.*)/(.*).git', projectrepo)
+ if projectname in projects:
+ msg = 'project ' + projectname + ' already exists'
+ elif not m:
+ msg = 'repo "' + projectrepo + ' must be of the form git://github.com/username/project.git'
+ else:
+ p = {"repo": projectrepo}
+ if arches:
+ p['arches'] = arches
+ if paths and paths[0] != '':
+ p['path'] = paths[0]
+ if revisions and revisions[0] != '':
+ p['revision'] = revisions[0]
+ if branches and branches[0] != '':
+ p['branch'] = branches[0]
+ p['owner'] = authz.getUsername(req)
+ projects[projectname] = p
+ json.dump(projects, open('projects.json', 'w'), indent=4)
+ subprocess.call(["/usr/bin/buildbot", "reconfig", "/scratch/buildbot/master"])
+ msg = 'added project: ' + ' '.join(req.args.get('projectname', '')) + ' url: ' + ' '.join(req.args.get('projectrepo', ''))
+ defer.returnValue((path_to_root(req), msg))
+
diff --git a/pool/shard009/Python/0086366_jlc_20060225.py b/pool/shard009/Python/0086366_jlc_20060225.py
new file mode 100644
index 0000000000000000000000000000000000000000..2464d4970bfb31eef1edce98a2a6e97d7db4a023
--- /dev/null
+++ b/pool/shard009/Python/0086366_jlc_20060225.py
@@ -0,0 +1,33 @@
+# This is in response to bug 1438337
+# ().
+# We have some XPath test cases that provide coverage for the bug, but it's
+# good to have an XSLT test case or two to deal with it as well.
+
+from Xml.Xslt import test_harness
+
+SRC_1 = """\
+"""
+
+SHEET_1 = """\
+
+
+
+
+
+ !
+
+"""
+
+EXPECTED_1 = """
+"""
+
+def Test(tester):
+ source = test_harness.FileInfo(string=SRC_1)
+ sheet = test_harness.FileInfo(string=SHEET_1)
+ test_harness.XsltTest(tester, source, [sheet], EXPECTED_1,
+ title='XPath comparison against empty node-set in an XSLT context')
+
+ return
diff --git a/pool/shard009/Python/0086369_JSY_HRcalc_programfile.py b/pool/shard009/Python/0086369_JSY_HRcalc_programfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..15b57fcc1cae8cd209f7a23f6ba7a5ac005479c4
--- /dev/null
+++ b/pool/shard009/Python/0086369_JSY_HRcalc_programfile.py
@@ -0,0 +1,78 @@
+# where we import our combined function file
+import HR_allfuncs as hr
+import sys
+filename = "ecg_data.csv"
+
+
+def run_hr_func(averaging_time, tachy_limit=100, brachy_limit=60):
+ if hr.columncheck(filename) == 1:
+ pass
+ if hr.datatypecheck(filename) == 1:
+ pass
+ if hr.datapracticality(filename) == 1:
+ pass
+ hr_data = hr.dataextraction(filename)
+
+ time_array = hr.HR_peakdetect(hr_data)
+
+ inst_hrval = hr.instHR(time_array)
+
+ average_hr_val = hr.hr_averaging(averaging_time, time_array)
+
+ tachy_present = hr.tachy(average_hr_val, tachy_limit)
+ brachy_present = hr.brachy(average_hr_val, brachy_limit)
+
+ hr_txt = open("HR_Specs.txt", "w")
+ hr_txt.write("Patient Name: Heart Patient Dude\n")
+ hr_txt.write("Estimated instant heart rate: {:.3f}\n".format(inst_hrval))
+ hr_txt.write("Estimated average heart rate: {:.3f}\n".format(average_hr_val))
+ hr_txt.write("Sign of tachycardia: " + str(tachy_present) + "\n")
+ hr_txt.write("Sign of brachycardia: " + str(brachy_present) + "\n")
+ hr_txt.write("Please note that values were extracted from a fixed sample of data.\n")
+ hr_txt.write("Consult your physician for further information and clarification.\n")
+
+ hr_txt.close()
+
+ # read from the file to command line
+ f = open('HR_Specs.txt')
+ for line in iter(f):
+ print(line)
+ f.close()
+
+# use Sonali's functions to validate data before extraction
+# use Sonali's function to extract data
+# use peak detection function to collect peak times, store in a time array
+# import time array into instant heart rate function, store in a float variable
+# import time array into average heart rate function, store in a float variable
+# import average heart rate value into tachy-,brachycardia function, store in a boolean variable
+
+# basic syntax on opening, and writing to a file
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("Please input an averaging time.")
+ if len(sys.argv) == 2:
+ averaging_time = sys.argv[1]
+ run_hr_func(averaging_time)
+ if len(sys.argv) == 3:
+ averaging_time = sys.argv[1]
+ tachy_limit = sys.argv[2]
+ tachy_limit = complex(tachy_limit)
+ tachy_limit = tachy_limit.real
+ run_hr_func(averaging_time, tachy_limit)
+ if len(sys.argv) == 4:
+ averaging_time = sys.argv[1]
+ tachy_limit = sys.argv[2]
+ tachy_limit = complex(tachy_limit)
+ tachy_limit = tachy_limit.real
+ brachy_limit = sys.argv[3]
+ brachy_limit = complex(brachy_limit)
+ brachy_limit = brachy_limit.real
+ run_hr_func(averaging_time, tachy_limit, brachy_limit)
+ if len(sys.argv) > 4:
+ print("Please view the README.md file for proper usage, you have too many arguments.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard009/Python/0086374_kernel_config.py b/pool/shard009/Python/0086374_kernel_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..06cfc9d7a7af7e0c3fa40ac24262426383855c3d
--- /dev/null
+++ b/pool/shard009/Python/0086374_kernel_config.py
@@ -0,0 +1,140 @@
+# TODO: need a function to get the newest config file older than us from
+# the repo.
+
+import shutil, os
+from autotest.client import utils
+from autotest.client.shared import error, kernel_versions
+
+def apply_overrides(orig_file, changes_file, output_file):
+ override = dict()
+
+ # First suck all the changes into a dictionary.
+ input = file(changes_file, 'r')
+ for line in input.readlines():
+ if line.startswith('CONFIG_'):
+ key = line.split('=')[0]
+ override[key] = line;
+ elif line.startswith('# CONFIG_'):
+ key = line.split(' ')[1]
+ override[key] = line;
+ input.close()
+
+ # Now go through the input file, overriding lines where need be
+ input = file(orig_file, 'r')
+ output = file(output_file, 'w')
+ for line in input.readlines():
+ if line.startswith('CONFIG_'):
+ key = line.split('=')[0]
+ elif line.startswith('# CONFIG_'):
+ key = line.split(' ')[1]
+ else:
+ key = None
+ if key and key in override:
+ output.write(override[key])
+ else:
+ output.write(line)
+ input.close()
+ output.close()
+
+
+def diff_configs(old, new):
+ utils.system('diff -u %s %s > %s' % (old, new, new + '.diff'),
+ ignore_status=True)
+
+
+
+def modules_needed(config):
+ return (utils.grep('CONFIG_MODULES=y', config) and utils.grep('=m', config))
+
+
+def config_by_name(name, set):
+ version = kernel_versions.version_choose_config(name, set[1:])
+ if version:
+ return set[0] + version
+ return None
+
+
+class kernel_config(object):
+ # Build directory must be ready before init'ing config.
+ #
+ # Stages:
+ # 1. Get original config file
+ # 2. Apply overrides
+ # 3. Do 'make oldconfig' to update it to current source code
+ # (gets done implicitly during the process)
+ #
+ # You may specifiy the a defconfig within the tree to build,
+ # or a custom config file you want, or None, to get machine's
+ # default config file from the repo.
+
+ build_dir = '' # the directory we're building in
+ config_dir = '' # local repository for config_file data
+
+ build_config = '' # the config file in the build directory
+ orig_config = '' # the original config file
+ over_config = '' # config file + overrides
+
+
+ def __init__(self, job, build_dir, config_dir, orig_file,
+ overrides, defconfig = False, name = None, make = None):
+ self.build_dir = build_dir
+ self.config_dir = config_dir
+
+ # 1. Get original config file
+ self.build_config = build_dir + '/.config'
+ if (orig_file == '' and not defconfig and not make): # use user default
+ set = job.config_get("kernel.default_config_set")
+ defconf = None
+ if set and name:
+ defconf = config_by_name(name, set)
+ if not defconf:
+ defconf = job.config_get("kernel.default_config")
+ if defconf:
+ orig_file = defconf
+ if (orig_file == '' and not make and defconfig): # use defconfig
+ make = 'defconfig'
+ if (orig_file == '' and make): # use the config command
+ print "kernel_config: using " + make + " to configure kernel"
+ os.chdir(build_dir)
+ make_return = utils.system('make %s > /dev/null' % make)
+ self.config_record(make)
+ if (make_return):
+ raise error.TestError('make % failed' % make)
+ else:
+ print "kernel_config: using " + orig_file + \
+ " to configure kernel"
+ self.orig_config = config_dir + '/config.orig'
+ utils.get_file(orig_file, self.orig_config)
+ self.update_config(self.orig_config, self.orig_config+'.new')
+ diff_configs(self.orig_config, self.orig_config+'.new')
+
+
+ # 2. Apply overrides
+ if overrides:
+ print "kernel_config: using " + overrides + \
+ " to re-configure kernel"
+ self.over_config = config_dir + '/config.over'
+ overrides_local = self.over_config + '.changes'
+ utils.get_file(overrides, overrides_local)
+ apply_overrides(self.build_config, overrides_local, self.over_config)
+ self.update_config(self.over_config, self.over_config+'.new')
+ diff_configs(self.over_config, self.over_config+'.new')
+ else:
+ self.over_config = self.orig_config
+
+
+ def update_config(self, old_config, new_config = 'None'):
+ os.chdir(self.build_dir)
+ shutil.copyfile(old_config, self.build_config)
+ utils.system('yes "" | make oldconfig > /dev/null')
+ if new_config:
+ shutil.copyfile(self.build_config, new_config)
+
+ def config_record(self, name):
+ #Copy the current .config file to the config.[.]
+ i = 1
+ to = self.config_dir + '/config.%s' % name
+ while os.path.exists(to):
+ i += 1
+ to = self.config_dir + '/config.%s.%d' % (name, i)
+ shutil.copyfile(self.build_dir + '/.config', to)
diff --git a/pool/shard009/Python/0086380_0004_auto_20200702_1932.py b/pool/shard009/Python/0086380_0004_auto_20200702_1932.py
new file mode 100644
index 0000000000000000000000000000000000000000..e050326f045a66fd23db82da3f60da8cc3667050
--- /dev/null
+++ b/pool/shard009/Python/0086380_0004_auto_20200702_1932.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11 on 2020-07-02 19:32
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('spotseeker_server', '0003_auto_20181105_2251'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='itemimage',
+ name='image',
+ field=models.ImageField(upload_to='item_images'),
+ ),
+ migrations.AlterField(
+ model_name='spacereview',
+ name='original_review',
+ field=models.CharField(default='', max_length=1000),
+ ),
+ migrations.AlterField(
+ model_name='spacereview',
+ name='review',
+ field=models.CharField(default='', max_length=1000),
+ ),
+ migrations.AlterField(
+ model_name='spotavailablehours',
+ name='day',
+ field=models.CharField(choices=[('m', 'monday'), ('t', 'tuesday'), ('w', 'wednesday'), ('th', 'thursday'), ('f', 'friday'), ('sa', 'saturday'), ('su', 'sunday')], max_length=3),
+ ),
+ migrations.AlterField(
+ model_name='spotimage',
+ name='image',
+ field=models.ImageField(upload_to='space_images'),
+ ),
+ ]
diff --git a/pool/shard009/Python/0086382_22e3d05acdd4_.py b/pool/shard009/Python/0086382_22e3d05acdd4_.py
new file mode 100644
index 0000000000000000000000000000000000000000..957b82bea8dcaef8d963d7abdb1aacb1abae34f5
--- /dev/null
+++ b/pool/shard009/Python/0086382_22e3d05acdd4_.py
@@ -0,0 +1,33 @@
+"""empty message
+
+Revision ID: 22e3d05acdd4
+Revises: 3d7d5ca299fa
+Create Date: 2015-02-06 10:17:29.664468
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '22e3d05acdd4'
+down_revision = '3d7d5ca299fa'
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.create_table('Message',
+ sa.Column('id', sa.Integer(), nullable=False),
+ sa.Column('date', sa.DateTime(), nullable=False),
+ sa.Column('message_text', sa.String(), nullable=False),
+ sa.Column('member_id', sa.Integer(), nullable=True),
+ sa.ForeignKeyConstraint(['member_id'], ['Member.id'], ),
+ sa.PrimaryKeyConstraint('id')
+ )
+ ### end Alembic commands ###
+
+
+def downgrade():
+ ### commands auto generated by Alembic - please adjust! ###
+ op.drop_table('Message')
+ ### end Alembic commands ###
diff --git a/pool/shard009/Python/0086383_cluster.py b/pool/shard009/Python/0086383_cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1d82ce858cb6e51b7191e1c0fc7d87fce408d15
--- /dev/null
+++ b/pool/shard009/Python/0086383_cluster.py
@@ -0,0 +1,163 @@
+import astropy.io.fits as pyfits
+import numpy as np
+import os
+
+# ====================================================================
+
+# Functions for realizing the model:
+
+def beta_model_profile(r, S0, rc, beta):
+ '''
+ The fabled beta model, radial profile S(r)
+ '''
+ return S0 * (1.0 + (r/rc)**2)**(-3.0*beta + 0.5)
+
+def beta_model_image(x, y, x0, y0, S0, rc, beta):
+ '''
+ Here, x and y are arrays ("meshgrids" or "ramps") containing x and y pixel numbers,
+ and the other arguments are galaxy cluster beta model parameters.
+ Returns a surface brightness image of the same shape as x and y.
+ '''
+ return beta_model_profile(np.sqrt((x-x0)**2 + (y-y0)**2), S0, rc, beta)
+
+def model_image(x, y, ex, pb, x0, y0, S0, rc, beta, b):
+ '''
+ Here, x, y, ex and pb are images, all of the same shape, and the other args are
+ cluster model and X-ray background parameters. ex is the (constant) exposure map
+ and pb is the (constant) particle background map.
+ '''
+ return (beta_model_image(x, y, x0, y0, S0, rc, beta) + b) * ex + pb
+
+# ====================================================================
+
+class XrayData:
+
+ def __init__(self):
+ self.pars = np.zeros(6)
+ return
+
+
+ def read_in_data(self):
+ # Download the data if we don't already have it
+ self.targdir = 'a1835_xmm/'
+ os.system('mkdir -p ' + self.targdir)
+ imagefile = 'P0098010101M2U009IMAGE_3000.FTZ'
+ expmapfile = 'P0098010101M2U009EXPMAP3000.FTZ'
+ bkgmapfile = 'P0098010101M2X000BKGMAP3000.FTZ'
+ remotedir = 'http://heasarc.gsfc.nasa.gov/FTP/xmm/data/rev0/0098010101/PPS/'
+ for filename in [imagefile,expmapfile,bkgmapfile]:
+ path = self.targdir + filename
+ url = remotedir + filename
+ if not os.path.isfile(path): # i.e. if the file does not exist already:
+ os.system('wget -nd -O ' + path + ' ' + 'url')
+
+ # Read in the data
+ self.imfits = pyfits.open(self.targdir + imagefile)
+ self.im = self.imfits[0].data
+ self.pbfits = pyfits.open(self.targdir + bkgmapfile)
+ self.pb = self.pbfits[0].data
+ self.exfits = pyfits.open(self.targdir + expmapfile)
+ self.ex = self.exfits[0].data
+
+ return
+
+
+ def set_up_maps(self):
+
+ # Make x and y ramps
+ self.x = np.array([np.arange(self.im.shape[0]) for j in np.arange(self.im.shape[1])])
+ self.y = np.array([[j for i in np.arange(self.im.shape[1])] for j in np.arange(self.im.shape[0])])
+
+ ### mask a list of circular regions covering non-cluster sources
+ maskfile = 'M2ptsrc.txt'
+ mask = np.loadtxt(self.targdir + maskfile)
+ for reg in mask:
+ distance2 = (self.x-(reg[0]-1.0))**2 + (self.y-(reg[1]-1.0))**2
+ self.ex[distance2 <= reg[2]**2] = 0.0
+ # helpful mask image to keep track of which pixels we can ignore
+ self.mask = self.ex * 0.0
+ self.mask[self.ex > 0.0] = 1.0
+
+ return
+
+
+ def set_pars(self,x0,y0,S0,rc,beta,b):
+ self.pars[0] = x0
+ self.pars[1] = y0
+ self.pars[2] = S0
+ self.pars[3] = rc
+ self.pars[4] = beta
+ self.pars[5] = b
+ return
+
+
+ def make_mean_image(self):
+ x0 = self.pars[0]
+ y0 = self.pars[1]
+ S0 = self.pars[2]
+ rc = self.pars[3]
+ beta = self.pars[4]
+ b = self.pars[5]
+ self.mu = model_image(self.x,self.y,self.ex,self.pb,x0,y0,S0,rc,beta,b)
+ return
+
+
+ def make_mock_data(self):
+ self.mock = np.random.poisson(self.mu,self.mu.shape)
+ return
+
+
+ def evaluate_log_prior(self):
+ # Uniform in all parameters...
+ return 0.0
+
+
+ def evaluate_log_likelihood(self):
+ self.make_mean_image()
+ # Return un-normalized Poisson sampling distribution:
+ # log (\mu^N e^{-\mu} / N!) = N log \mu - \mu + constant
+ return np.sum(self.im * np.log(self.mu) - self.mu)
+
+
+ def evaluate_unnormalised_log_posterior(self,x0,y0,S0,rc,beta,b):
+ self.set_pars(x0,y0,S0,rc,beta,b)
+ return self.evaluate_log_likelihood() + self.evaluate_log_prior()
+
+
+
+# ====================================================================
+'''
+
+Adam's routines for input into MCMC:
+
+def lnpost(params, data):
+ # assumes S0 is a free parameter
+ x0 = params[0]
+ y0 = params[1]
+ S0 = params[2]
+ rc = params[3]
+ beta = params[4]
+ bg = params[5]
+ if x0 < 0. or x0 >= data.im.shape[0] or y0 < 0. or y0 > data.im.shape[1] or S0 <= 0. or rc <= 0. or beta <= 0.0:
+ return -np.inf
+ mod = modelImage(data, x0, y0, S0, rc, beta, bg)
+ if np.min(mod) <= 0.0:
+ return -np.inf
+ return np.sum( (-mod + data.im * np.log(mod)) * data.mask )
+
+
+def lnpost2(params, data):
+ # assumes log(S0) is a free parameter
+ x0 = params[0]
+ y0 = params[1]
+ S0 = np.exp(params[2])
+ rc = params[3]
+ beta = params[4]
+ bg = params[5]
+ if x0 < 0. or x0 >= data.im.shape[0] or y0 < 0. or y0 > data.im.shape[1] or S0 <= 0. or rc <= 0. or beta <= 0.0:
+ return -np.inf
+ mod = modelImage(data, x0, y0, S0, rc, beta, bg)
+ if np.min(mod) <= 0.0:
+ return -np.inf
+ return np.sum( (-mod + data.im * np.log(mod)) * data.mask )
+'''
diff --git a/pool/shard009/Python/0086389_test_portbinding_vlan.py b/pool/shard009/Python/0086389_test_portbinding_vlan.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa5fb250e3fe7b42f0cf87fb056c6963fe774fce
--- /dev/null
+++ b/pool/shard009/Python/0086389_test_portbinding_vlan.py
@@ -0,0 +1,135 @@
+# Copyright 2014, Doug Wiegley (dougwig), A10 Networks
+#
+# 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 mock
+from nose.plugins.attrib import attr
+
+from a10_neutron_lbaas.tests.unit import test_base
+
+from a10_neutron_lbaas.plumbing import portbinding_vlan
+
+from neutron.db.models.segment import NetworkSegment
+from neutron.db.models_v2 import Port
+from neutron.plugins.ml2.models import PortBindingLevel
+
+_SUBNET_ID = "mysubnet"
+_PORT_ID = "portid"
+_SEGMENT_ID = "mysegment"
+_VLAN_ID = 2000
+_NETWORK_ID = "mynetwork"
+_LEVEL = 1
+
+
+def raise_(exc):
+ raise exc
+
+
+class FakeModel(object):
+ def __init__(self, **kwargs):
+ self._dict = kwargs
+
+ def __getattr__(self, key):
+ return self._dict.get(key) or raise_(KeyError(key))
+
+
+class FakeSession(object):
+ _model_map = {
+ PortBindingLevel: FakeModel(segment_id=_SEGMENT_ID, level=_LEVEL),
+ NetworkSegment: FakeModel(id=_SEGMENT_ID, segmentation_id=_VLAN_ID),
+ Port: FakeModel(id=_PORT_ID, subnet_id=_SUBNET_ID, network_id=_NETWORK_ID),
+ }
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def query(self, model):
+ self._rval = self._model_map[model]
+ return self
+
+ def filter_by(self, *args, **kwargs):
+ return self
+
+ def first(self):
+ return self._rval
+
+
+class FakeConfig(object):
+ def __init__(self, *args, **kwargs):
+ self._dict = kwargs
+
+ def get(self, key):
+ return self._dict.get(key)
+
+
+@attr(db=True)
+class TestVlanPortBindingPlumbing(test_base.UnitTestBase):
+ version = "v2"
+
+ def setUp(self, *args, **kwargs):
+ super(TestVlanPortBindingPlumbing, self).setUp(*args, **kwargs)
+ self._subnet_id = "mysubnet"
+ self._port_id = "portid"
+ self._segment_id = "mysegment"
+ self._vlan_id = 2000
+ self._network_id = "mynetwork"
+ self._level = 1
+
+ self._binding_level = mock.Mock(level=1, segment_id=self._segment_id)
+ self._segment = mock.Mock(id=self._segment_id, segmentation_id=self._vlan_id)
+ self._build_mocks()
+ self.target = portbinding_vlan.VlanPortBindingPlumbingHooks(self._driver, self._devices)
+
+ def test_select_device(self):
+ a = self.target.select_device("first-token")
+ self.target.select_device("second-token")
+ self.assertEqual(a, self.target.select_device("first-token"))
+
+ def test_after_vip_create(self):
+ self.target.after_vip_create(self.a10_context, self.os_context, self._vip)
+ self._client.vlan.create.assert_called_once_with(_VLAN_ID, mock.ANY, mock.ANY)
+
+ def test_after_vip_create_ve_exists(self):
+ self._client.interface.ve.get.return_value = {"ve": 2}
+ self.target.after_vip_create(self.a10_context, self.os_context, self._vip)
+ self._client.vlan.create.assert_not_called()
+
+ def _build_mocks(self):
+ # a10_context dependencies
+ self._vip = FakeModel(vip_subnet_id="mysubnet",
+ vip_port=FakeModel(id=self._port_id, network_id=self._network_id))
+ self._devices = {"a": {"host": "1.2.3.4", "api_version": "3.0"}}
+ self._driver = mock.Mock()
+ self._client = self._build_client()
+ self._config = FakeConfig(
+ use_database=False,
+ vlan_interfaces={
+ "tagged_trunks": [1, 2],
+ },
+ use_dhcp=False,
+ vlan_binding_level=self._level
+ )
+ self._a10_driver = mock.Mock(config=self._config)
+ self.a10_context = mock.Mock(a10_driver=self._a10_driver, client=self._client)
+ self._session = self._build_session()
+ self.os_context = mock.Mock(session=self._session, tenant_id="tenant")
+
+ def _build_session(self, **kwargs):
+ return FakeSession()
+
+ def _build_client(self):
+ rval = mock.Mock()
+ rval.interface.ve.get_oper.return_value = None
+ rval.interface.ve.get = lambda: {}
+
+ return rval
diff --git a/pool/shard009/Python/0086393_conf.py b/pool/shard009/Python/0086393_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..5648949015467b87a21c9d6c4b35b5ef7eaab066
--- /dev/null
+++ b/pool/shard009/Python/0086393_conf.py
@@ -0,0 +1,60 @@
+"""Sphinx configuration file."""
+import sys
+
+from pkg_resources import get_distribution
+
+project = "pyLanguagetool"
+copyright = "2017, Lukas Winkler"
+release = get_distribution('pylanguagetool').version
+version = '.'.join(release.split('.')[:2])
+
+master_doc = 'index'
+
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.napoleon',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.doctest',
+ 'sphinx.ext.linkcode'
+]
+
+html_theme = 'alabaster'
+html_theme_options = {
+ 'description': 'A python library and CLI for the LanguageTool JSON API.',
+}
+
+templates_path = ['_templates']
+
+latex_engine = 'xelatex'
+latex_elements = {
+ 'papersize': 'a4paper',
+}
+
+intersphinx_mapping = {
+ 'python': ('https://docs.python.org/3', None),
+ "requests": ("https://2.python-requests.org/en/master/", None),
+}
+
+
+def linkcode_resolve(domain, info):
+ def find_source():
+ # try to find the file and line number, based on code from numpy:
+ # https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L286
+ obj = sys.modules[info['module']]
+ for part in info['fullname'].split('.'):
+ obj = getattr(obj, part)
+ import inspect
+ mod = info['module'].replace('.', '/')
+ if mod == "pylanguagetool":
+ mod += "/__init__"
+ fn = mod + ".py"
+ source, lineno = inspect.getsourcelines(obj)
+ return fn, lineno, lineno + len(source) - 1
+
+ if domain != 'py' or not info['module']:
+ return None
+ try:
+ filename = '{}#L{:d}-L{:d}'.format(*find_source())
+ except Exception:
+ filename = info['module'].replace('.', '/') + '.py'
+ return "https://github.com/Findus23/pyLanguagetool/blob/master/{}".format(filename)
diff --git a/pool/shard009/Python/0086397_camera_tracking.py b/pool/shard009/Python/0086397_camera_tracking.py
new file mode 100644
index 0000000000000000000000000000000000000000..74e4e9b514b755499753a6062e106311f64225e0
--- /dev/null
+++ b/pool/shard009/Python/0086397_camera_tracking.py
@@ -0,0 +1,53 @@
+import cv2
+import time
+import argparse
+#importing the neccessery libraries
+
+cv2.ocl.setUseOpenCL(False)
+#disenabling opencl because it causes an error to do with teh background subtraction
+
+ap = argparse.ArgumentParser()
+ap.add_argument("-a", "--min-area", type=int, default=200, help="minimum area")
+args = vars(ap.parse_args())
+#arguement parser with minimum area for it to pick up as motion
+
+cap = cv2.VideoCapture(0)
+#getting the video out from the webcam
+
+fgbg = cv2.createBackgroundSubtractorMOG2()
+#getting the background subtractor ready for use
+
+while (1):
+ ret, frame = cap.read()
+ #starting the loop while reading from the video capture
+
+ fgmask = fgbg.apply(frame)
+ #applying the bakground subtractor
+
+ thresh = fgmask
+ thresh = cv2.GaussianBlur(thresh, (21, 21), 0)
+ thresh = cv2.threshold(thresh, 127, 255, cv2.THRESH_BINARY)[1]
+ thresh = cv2.dilate(thresh, None, iterations=1)
+ #making the image binary and adjusting it for the contouring
+ _, cnts, _= cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
+ #find the contours aroung the edges of the motion
+ for c in cnts:
+ if cv2.contourArea(c) < args["min_area"]:
+ continue
+ #putting the contour area through the arguement parser for minimum area
+ c = max(cnts, key=cv2.contourArea)
+
+ (x, y, w, h) = cv2.boundingRect(c)
+ cv2.rectangle(frame, (x, y), (x+ w, y + h), (0, 0, 255), 2)
+ #draw the rectangle around the object
+
+ cv2.imshow("Feed", frame)
+ #show the image in a new window
+ key = cv2.waitKey(1) & 0xFF
+ if key == ord("s"):
+ break
+ #break the loop
+
+cap.release()
+cv2.destroyAllWindows()
+#stop the windows
diff --git a/pool/shard009/Python/0086399_example.py b/pool/shard009/Python/0086399_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0f9c4852b6d22186e7b69211e98606682909f4d
--- /dev/null
+++ b/pool/shard009/Python/0086399_example.py
@@ -0,0 +1,108 @@
+#!/usr/bin/python
+
+
+# $Id: example.py,v 1.6 2014/11/26 17:25:15 titus Exp $
+
+#
+# SecSign ID Api example in python.
+#
+# (c) 2014 SecSign Technologies Inc.
+#
+
+import time
+from SecSignIDApi import SecSignIDApi
+from SecSignIDApi import AuthSession
+from SecSignIDApi import InputError
+#
+#
+# Example how to retrieve an authentication session, ask its status and withdraw the authentication session.
+#
+#
+
+#
+# Create an instance of SecSignIDApi.
+#
+print("create new instance of SecSignIDApi.")
+secSignIDApi = SecSignIDApi()
+
+#
+# The servicename and address is mandatory. It has to be send to the server.
+# The value of servicename will be shown on the display of the smartphone. The user then can decide whether he accepts the authentication session shown on his mobile phone.
+#
+servicename = "Your Website Login";
+serviceaddress = "http://www.yoursite.com/";
+secsignid = "username";
+
+#
+# Get a auth session for the sepcified SecSign ID
+#
+# If secsignid is null or empty an exception is thrown.
+# If servicename is null or empty an exception is thrown.
+#
+
+try:
+ authSession = secSignIDApi.requestAuthSession(secsignid, servicename, serviceaddress)
+ print("got authSession '" + str(authSession) + "'")
+
+except InputError as e:
+ print("could not get an authentication session for SecSign ID '" + secsignid + "' : " + e.strerror)
+ exit(1)
+
+
+#
+# Get the auth session status
+#
+# If authSession is null or not an instance of AuthSession an exception is thrown
+#
+authSessionState = authSession.NOSTATE
+
+try:
+ authSessionState = secSignIDApi.getAuthSessionState(authSession)
+ print("got auth session state: " + authSessionState);
+except InputError as e:
+ print("could not get status for authentication session '" + str(authSession.authSessionID) + "' : " + e.strerror)
+ exit(1)
+
+
+# If the script shall wait till the user has accepted the auth session or denied it, it has to ask the server frequently
+secondsToWaitUntilNextCheck = 10
+noError = True
+
+while noError and (int(authSessionState) == AuthSession.PENDING or int(authSessionState) == AuthSession.FETCHED):
+ try:
+ authSessionState = secSignIDApi.getAuthSessionState(authSession);
+ print("auth session state: " + authSessionState)
+
+ if int(authSessionState) == AuthSession.PENDING or int(authSessionState) == AuthSession.FETCHED:
+ time.sleep(secondsToWaitUntilNextCheck)
+ except InputError as e:
+ print("could not get auth session status for auth session '" + authSession.authSessionID + "' : " + e.strerror)
+ noError = False;
+
+
+
+
+if int(authSessionState) == authSession.AUTHENTICATED:
+ print("user has accepted the auth session '" + authSession.authSessionID + "'")
+
+ # release auth session to free resources serverside
+ secSignIDApi.releaseAuthSession(authSession)
+ print("auth session '" + authSession.authSessionID + "' was released.")
+
+
+elif int(authSessionState) == authSession.DENIED:
+ print("user has denied the auth session '" + authSession.authSessionID + "'.")
+ authSessionState = secSignIDApi.cancelAuthSession(authSession); # after the auth session is successfully canceled it is not possible to inquire the status again
+ if authSessionState == authSession.CANCELED:
+ print("authentication session successfully cancelled...")
+
+
+else:
+ print("auth session '" + authSession.authSessionID + "' has state " + authSessionState + ".")
+ authSessionState = secSignIDApi.cancelAuthSession(authSession); # after the auth session is successfully canceled it is not possible to inquire the status again
+ if int(authSessionState) == authSession.CANCELED:
+ print("authentication session successfully cancelled...")
+
+
+
+### end
diff --git a/pool/shard009/Python/0086400_fit_isochrones.py b/pool/shard009/Python/0086400_fit_isochrones.py
new file mode 100644
index 0000000000000000000000000000000000000000..23611c442402ac570ec1c784908e9b869b2ce7c5
--- /dev/null
+++ b/pool/shard009/Python/0086400_fit_isochrones.py
@@ -0,0 +1,174 @@
+"""
+Fit isochrones to the stars in the 3 highlighted pairs
+
+"""
+
+# Standard library
+from collections import OrderedDict
+from os import path
+import os
+
+# Third-party
+from astropy.table import Table
+import matplotlib.pyplot as plt
+import numpy as np
+import emcee
+from tqdm import tqdm
+
+# Package
+from comoving_rv.log import logger
+from comoving_rv.db import Session, Base, db_connect
+from comoving_rv.db.model import (Run, Observation, TGASSource, SimbadInfo,
+ GroupToObservations, SpectralLineInfo,
+ SpectralLineMeasurement, RVMeasurement)
+
+from isochrones import StarModel
+# from isochrones.mist import MIST_Isochrone
+# iso = MIST_Isochrone() # interpolation issues with MIST isochrones
+from isochrones.dartmouth import Dartmouth_Isochrone
+iso = Dartmouth_Isochrone()
+
+def main():
+ # TODO: bad, hard-coded...
+ # base_path = '/Volumes/ProjectData/gaia-comoving-followup/'
+ base_path = '../../data/'
+ db_path = path.join(base_path, 'db.sqlite')
+ engine = db_connect(db_path)
+ session = Session()
+
+ chain_path = path.abspath('./isochrone_chains')
+ os.makedirs(chain_path, exist_ok=True)
+
+ # Check out the bottom of "Color-magnitude diagram.ipynb":
+ interesting_group_ids = [1500, 1229, 1515]
+
+ all_photometry = OrderedDict([
+ ('1500-8455', OrderedDict([('J', (6.8379998, 0.021)),
+ ('H', (6.4640002, 0.017000001)),
+ ('K', (6.3369999, 0.017999999)),
+ ('W1', (6.2950001, 0.093000002)),
+ ('W2', (6.2490001, 0.026000001)),
+ ('W3', (6.3330002, 0.015)),
+ ('B', (9.5950003, 0.022)),
+ ('V', (8.5120001, 0.014))])),
+ ('1500-1804', OrderedDict([('J', (6.9039998, 0.041000001)),
+ ('H', (6.8559999, 0.027000001)),
+ ('K', (6.7989998, 0.017000001)),
+ ('W1', (6.803, 0.064999998)),
+ ('W2', (6.7600002, 0.018999999)),
+ ('W3', (6.8270001, 0.016000001)),
+ ('B', (7.4980001, 0.015)),
+ ('V', (7.289, 0.011))])),
+ ('1229-1366', OrderedDict([('J', (6.7290001, 0.024)),
+ ('H', (6.2449999, 0.02)),
+ ('K', (6.1529999, 0.023)),
+ ('W1', (6.1799998, 0.096000001)),
+ ('W2', (6.04, 0.035)),
+ ('W3', (6.132, 0.016000001)),
+ ('B', (9.5539999, 0.021)),
+ ('V', (8.4619999, 0.014))])),
+ ('1229-7470', OrderedDict([('J', (9.1709995, 0.024)),
+ ('H', (8.7959995, 0.026000001)),
+ ('K', (8.7299995, 0.022)),
+ ('W1', (8.6669998, 0.023)),
+ ('W2', (8.7189999, 0.02)),
+ ('W3', (8.6680002, 0.025)),
+ ('B', (11.428, 0.054000001)),
+ ('V', (10.614, 0.039999999))])),
+ ('1515-3584', OrderedDict([('J', (5.363999843597412, 0.024000000208616257)),
+ ('H', (4.965000152587891, 0.035999998450279236)),
+ ('K', (4.815999984741211, 0.032999999821186066)),
+ ('W1', (4.758, 0.215)),
+ ('W2', (4.565, 0.115)),
+ ('W3', (4.771, 0.015)),
+ ('B', (8.347999572753906, 0.01600000075995922)),
+ ('V', (7.182000160217285, 0.009999999776482582))])),
+ ('1515-1834', OrderedDict([('J', (8.855999946594238, 0.024000000208616257)),
+ ('H', (8.29699993133545, 0.020999999716877937)),
+ ('K', (8.178999900817871, 0.017999999225139618)),
+ ('W1', (8.117, 0.022)),
+ ('W2', (8.15, 0.019)),
+ ('W3', (8.065, 0.02)),
+ ('B', (12.309000015258789, 0.11999999731779099)),
+ ('V', (11.069999694824219, 0.054999999701976776))]))
+ ])
+
+ for k in all_photometry:
+ samples_file = path.join(chain_path, '{0}.hdf5'.format(k))
+
+ if path.exists(samples_file):
+ logger.info("skipping {0} - samples exist at {1}"
+ .format(k, samples_file))
+ continue
+
+ phot = all_photometry[k]
+ obs = session.query(Observation).filter(Observation.object == k).one()
+ plx = (obs.tgas_source.parallax, obs.tgas_source.parallax_error)
+
+ # fit an isochrone
+ model = StarModel(iso, use_emcee=True, parallax=plx, **phot)
+ model.set_bounds(mass=(0.01, 20),
+ feh=(-1, 1),
+ distance=(0, 300),
+ AV=(0, 1))
+
+ # initial conditions for emcee walkers
+ nwalkers = 128
+
+ p0 = []
+ m0, age0, feh0 = model.ic.random_points(nwalkers,
+ minmass=0.01, maxmass=10.,
+ minfeh=-1, maxfeh=1)
+ _, max_distance = model.bounds('distance')
+ _, max_AV = model.bounds('AV')
+ d0 = 10**(np.random.uniform(0,np.log10(max_distance),size=nwalkers))
+ AV0 = np.random.uniform(0, max_AV, size=nwalkers)
+ p0 += [m0]
+ p0 += [age0, feh0, d0, AV0]
+
+ p0 = np.array(p0).T
+ npars = p0.shape[1]
+
+ # run emcee
+ ninit = 256
+ nburn = 1024
+ niter = 4096
+
+ logger.debug('Running emcee - initial sampling...')
+ sampler = emcee.EnsembleSampler(nwalkers, npars, model.lnpost)
+ # pos, prob, state = sampler.run_mcmc(p0, ninit)
+
+ for pos, prob, state in tqdm(sampler.sample(p0, iterations=ninit),
+ total=ninit):
+ pass
+
+ # cull the weak walkers
+ best_ix = sampler.flatlnprobability.argmax()
+ best_p0 = (sampler.flatchain[best_ix][None] +
+ np.random.normal(0, 1E-5, size=(nwalkers, npars)))
+
+ sampler.reset()
+ logger.debug('burn-in...')
+ for pos, prob, state in tqdm(sampler.sample(best_p0, iterations=nburn),
+ total=nburn):
+ pass
+ # pos,_,_ = sampler.run_mcmc(best_p0, nburn)
+
+ sampler.reset()
+ logger.debug('sampling...')
+ # _ = sampler.run_mcmc(pos, niter)
+ for pos, prob, state in tqdm(sampler.sample(pos, iterations=niter),
+ total=niter):
+ pass
+
+ model._sampler = sampler
+ model._make_samples(0.08)
+
+ model.samples.to_hdf(samples_file, key='samples')
+ # np.save('isochrone_chains/chain.npy', sampler.chain)
+ logger.debug('...done and saved!')
+
+if __name__ == '__main__':
+ import logging
+ logger.setLevel(logging.DEBUG)
+ main()
diff --git a/pool/shard009/Python/0086404_models.py b/pool/shard009/Python/0086404_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1b169fe6cadbecc242aff838f1fe34cd2090817
--- /dev/null
+++ b/pool/shard009/Python/0086404_models.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+from django.db import models
+from django.contrib.auth.models import User
+
+
+
+# Create your models here.
+class Disciplina(models.Model):
+ id = models.AutoField(primary_key = True, unique = True)
+ nome = models.CharField(max_length=45)
+ label = models.CharField(max_length=45)
+ user = models.ForeignKey(User)
+ def __unicode__(self):
+ return self.label
\ No newline at end of file
diff --git a/pool/shard009/Python/0086407_generics_utils.py b/pool/shard009/Python/0086407_generics_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c1ac8afd189084e8f96a4643ca0e95c3d98894d
--- /dev/null
+++ b/pool/shard009/Python/0086407_generics_utils.py
@@ -0,0 +1,126 @@
+# To change this license header, choose License Headers in Project Properties.
+# To change this template file, choose Tools | Templates
+# and open the template in the editor.
+
+import json
+import re
+from os.path import expanduser
+import os
+import urllib
+import tempfile
+
+import download_utils
+import printer
+
+__author__="UShareSoft"
+
+
+def extract_id(uri):
+ elements = uri.split("/");
+ return elements[len(elements) - 1];
+
+def check_json_syntax(file):
+ try:
+ printer.out("Validating the template file ["+file+"] ...")
+ json_data=open(file)
+ data = json.load(json_data)
+ json_data.close()
+ printer.out("Syntax of template file ["+file+"] is ok", printer.OK)
+ return data
+ except ValueError as e:
+ printer.out("Syntax of template file ["+file+"] FAILED", printer.ERROR)
+ printer.out("JSON parsing error: "+str(e))
+ return
+ except IOError as e:
+ printer.out("File error: "+str(e), printer.ERROR)
+ return
+
+def query_yes_no(question, default="yes"):
+ """Ask a yes/no question via raw_input() and return their answer.
+
+ "question" is a string that is presented to the user.
+ "default" is the presumed answer if the user just hits .
+ It must be "yes" (the default), "no" or None (meaning
+ an answer is required of the user).
+
+ The "answer" return value is one of "yes" or "no".
+ """
+ valid = {"yes":True, "y":True, "ye":True,
+ "no":False, "n":False}
+ if default == None:
+ prompt = " [y/n] "
+ elif default == "yes":
+ prompt = " [Y/n] "
+ elif default == "no":
+ prompt = " [y/N] "
+ else:
+ raise ValueError("invalid default answer: '%s'" % default)
+
+ while True:
+ printer.out(question + prompt)
+ choice = raw_input().lower()
+ if default is not None and choice == '':
+ return valid[default]
+ elif choice in valid:
+ return valid[choice]
+ else:
+ printer.out("Please respond with 'yes' or 'no' "\
+ "(or 'y' or 'n').\n")
+
+
+def remove_special_chars(string):
+ return (re.sub('[-]', '_', string)).lower()
+
+
+
+def order_list_object_by(objects, attribute):
+ if type(attribute) is str:
+ return sorted(objects, key=lambda x: getattr(x, attribute).lower(), reverse=False)
+ return objects
+
+def get_uforge_url_from_ws_url(ws_url):
+ if ws_url[-1:]!='/':
+ return ws_url.rpartition('/')[0]
+ else:
+ return ws_url[:-1].rpartition('/')[0]
+
+def get_home_dir():
+ return expanduser("~")
+
+def get_remote_regex():
+ return (r'^(?:http|ftp)s?://' # http:// or https://
+ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
+ r'localhost|' #localhost...
+ r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
+ r'(?::\d+)?' # optional port
+ r'(?:/?|[/?]\S+)$')
+
+def get_file(uri, dest_file_name=None):
+ try:
+ regexp = re.compile(get_remote_regex(), re.IGNORECASE)
+ if regexp.search(uri) is not None:
+ dlUtils = download_utils.Download(uri, dest_file_name)
+ try:
+ dlUtils.start()
+ except Exception, e:
+ return 2
+ else:
+ dest_file_name, headers = urllib.urlretrieve(uri)
+ return dest_file_name
+ except Exception, e:
+ print("error downloading "+uri+": "+ str(e))
+ return
+
+def remove_URI_forbidden_char(string):
+ chars= ' '
+ return re.sub(chars, '_', string)
+
+def is_superviser_mode(userName):
+ if "\\" in userName:
+ return True
+ else:
+ return False
+
+def get_target_username(userName):
+ if "\\" in userName:
+ return userName.split('\\')[1]
\ No newline at end of file
diff --git a/pool/shard009/Python/0086412_0001_squashed_0004_remove_unused_tags.py b/pool/shard009/Python/0086412_0001_squashed_0004_remove_unused_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..f52d6efc4fc17a4f9d0b2efc8fe53c075e1dfeca
--- /dev/null
+++ b/pool/shard009/Python/0086412_0001_squashed_0004_remove_unused_tags.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('taggit', '0002_auto_20150616_2121'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='IPBan',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('ip', models.GenericIPAddressField()),
+ ('created', models.DateTimeField(default=django.utils.timezone.now, db_index=True)),
+ ('deleted', models.DateTimeField(null=True, blank=True)),
+ ],
+ ),
+ ]
diff --git a/pool/shard009/Python/0086414_location_moves.py b/pool/shard009/Python/0086414_location_moves.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a7d5461bfe48929d5197e2b71a75f6cc9189b38
--- /dev/null
+++ b/pool/shard009/Python/0086414_location_moves.py
@@ -0,0 +1,96 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# Copyright (C) 2014 Pexego All Rights Reserved
+# $Jesús Ventosinos Mayor $
+#
+# 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 import models, fields, api
+
+
+class location_moves(models.TransientModel):
+
+ _name = 'location.moves'
+
+ product_id = fields.Many2one('product.product', 'Product', required=True)
+ qty = fields.Float('Qty', required=True)
+ check_qty = fields.Boolean('Check Qty',
+ default=lambda self: self.env.context.
+ get('manual', False))
+
+ move_type = fields.Selection(
+ [('beach_stock', 'Beach -> Stock'),
+ ('beach_kitchen', 'Beach -> Kitchen'),
+ ('beach_pantry', 'Beach -> Pantry'),
+ ('stock_kitchen', 'Stock -> Kitchen'),
+ ('stock_pantry', 'Stock -> Pantry'),
+ ('pantry_kitchen', 'Pantry -> Kitchen'),
+ ('kitchen_cooked', 'Kitchen -> Cooked'),
+ ('kitchen_nursing', 'Kitchen -> Nursing'),
+ ('stock_nursing', 'Stock -> Nursing'),
+ ('nursing_damaged', 'Nursing -> Damaged'),
+ ('nursing_cooked', 'Nursing -> Cooked'),
+ ('quality_cooked', 'Quality -> Cooked'),
+ ('cooked_quality', 'Cooked -> Quality'),
+ ('cooked_damaged', 'Cooked -> Damaged'),
+ ('marketing_stock', 'Marketing -> Stock'),
+ ('marketing_product', 'Marketing -> Product'),
+ ('stock_marketing', 'Stock -> Marketing'),
+ ('product_stock', 'Product -> Stock'),
+ ('stock_product', 'Stock -> Product'),
+ ('development_stock', 'Development -> Stock'),
+ ('stock_development', 'Stock -> Development'),
+ ('sat_stock', 'SAT -> Stock'),
+ ('stock_sat', 'Stock -> SAT'),
+ ('external_stock', 'External -> Stock'),
+ ('beach_external', 'Beach -> External'),
+ ],
+ 'Move type', required=True)
+
+ @api.one
+ def create_moves(self):
+ loc_obj = self.env['stock.location']
+ types = {
+ 'beach_stock': loc_obj.move_beach_stock,
+ 'beach_kitchen': loc_obj.move_beach_kitchen,
+ 'beach_pantry': loc_obj.move_beach_pantry,
+ 'stock_kitchen': loc_obj.move_stock_kitchen,
+ 'stock_pantry': loc_obj.move_stock_pantry,
+ 'pantry_kitchen': loc_obj.move_pantry_kitchen,
+ 'kitchen_cooked': loc_obj.move_kitchen_cooked,
+ 'kitchen_nursing': loc_obj.move_kitchen_nursing,
+ 'stock_nursing': loc_obj.move_stock_nursing,
+ 'nursing_damaged': loc_obj.move_nursing_damaged,
+ 'nursing_cooked': loc_obj.move_nursing_cooked,
+ 'quality_cooked': loc_obj.move_quality_cooked,
+ 'cooked_damaged': loc_obj.move_cooked_damaged,
+ 'marketing_stock': loc_obj.move_marketing_stock,
+ 'stock_marketing': loc_obj.move_stock_marketing,
+ 'product_stock': loc_obj.move_product_stock,
+ 'stock_product': loc_obj.move_stock_product,
+ 'development_stock': loc_obj.move_development_stock,
+ 'stock_development': loc_obj.move_stock_development,
+ 'sat_stock': loc_obj.move_sat_stock,
+ 'stock_sat': loc_obj.move_stock_sat,
+ 'cooked_quality': loc_obj.move_cooked_quality,
+ 'marketing_product': loc_obj.move_marketing_product,
+ 'external_stock': loc_obj.move_external_stock,
+ 'beach_external': loc_obj.move_beach_external
+ }
+ types[self.move_type](self.product_id.id, self.qty, self.check_qty)
+ return True
diff --git a/pool/shard009/Python/0086418_test_textarea_input.py b/pool/shard009/Python/0086418_test_textarea_input.py
new file mode 100644
index 0000000000000000000000000000000000000000..aab83fea9aac50ff4187b3ce7cf2b7beb33dbf3b
--- /dev/null
+++ b/pool/shard009/Python/0086418_test_textarea_input.py
@@ -0,0 +1,84 @@
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
+#
+# Powered by the Bokeh Development Team.
+#
+# The full license is in the file LICENSE.txt, distributed with this software.
+#-----------------------------------------------------------------------------
+
+#-----------------------------------------------------------------------------
+# Boilerplate
+#-----------------------------------------------------------------------------
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import pytest ; pytest
+from selenium.webdriver.common.keys import Keys
+#-----------------------------------------------------------------------------
+# Imports
+#-----------------------------------------------------------------------------
+
+# Standard library imports
+
+# External imports
+
+# Bokeh imports
+from bokeh.layouts import column
+from bokeh.models import Circle, ColumnDataSource, CustomAction, CustomJS, Plot, Range1d, TextAreaInput
+from bokeh._testing.util.selenium import enter_text_in_element, RECORD
+
+#-----------------------------------------------------------------------------
+# Tests
+#-----------------------------------------------------------------------------
+
+pytest_plugins = (
+ "bokeh._testing.plugins.bokeh",
+)
+
+
+foo = []
+
+
+def modify_doc(doc):
+ source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"]))
+ plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0)
+ plot.add_glyph(source, Circle(x='x', y='y', size=20))
+ code = RECORD("data", "s.data")
+ plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=code)))
+ text_input = TextAreaInput(cols=20, css_classes=["foo"])
+ def cb(attr, old, new):
+ foo.append((old, new))
+ source.data['val'] = [old, new]
+ text_input.on_change('value', cb)
+ doc.add_root(column(text_input, plot))
+
+
+@pytest.mark.integration
+@pytest.mark.selenium
+class Test_TextInput(object):
+
+ def test_displays_text_input(self, bokeh_model_page):
+ text_input = TextAreaInput(css_classes=["foo"])
+ page = bokeh_model_page(text_input)
+ input_div = page.driver.find_element_by_class_name('foo')
+ el = input_div.find_element_by_tag_name("textarea")
+ assert el.tag_name == 'textarea'
+ assert page.has_no_console_errors()
+
+ def test_displays_placeholder(self, bokeh_model_page):
+ text_input = TextAreaInput(placeholder="placeholder", css_classes=["foo"])
+ page = bokeh_model_page(text_input)
+ input_div = page.driver.find_element_by_class_name('foo')
+ el = input_div.find_element_by_tag_name("textarea")
+ assert el.get_attribute('placeholder') == "placeholder"
+ assert page.has_no_console_errors()
+
+ def test_server_on_change_round_trip(self, bokeh_server_page):
+ page = bokeh_server_page(modify_doc)
+
+ el = page.driver.find_element_by_class_name('foo')
+
+ enter_text_in_element(page.driver, el, "val1" + Keys.TAB)
+
+ page.click_custom_action()
+ results = page.results
+ assert results['data']['val'] == ["", "val1"]
diff --git a/pool/shard009/Python/0086419_LiquidCrystalDisplay.py b/pool/shard009/Python/0086419_LiquidCrystalDisplay.py
new file mode 100644
index 0000000000000000000000000000000000000000..47ac3b3fd9eabd2ce220de25e4d59e1c8c91b717
--- /dev/null
+++ b/pool/shard009/Python/0086419_LiquidCrystalDisplay.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+
+import time
+from configparser import ConfigParser
+import RPi.GPIO as GPIO
+from RPLCD import CharLCD, BacklightMode
+
+class LiquidCrystalDisplay(CharLCD):
+ 'Class for a LCD.'
+
+ def __init__(self, pin_rs, pin_rw, pin_e, pins_data, pin_backlight=None, backlight_enabled=False):
+
+ config = ConfigParser(allow_no_value=True)
+ config.read('config.ini')
+
+ super(LiquidCrystalDisplay, self).__init__(
+ pin_rs= pin_rs,
+ pin_rw= pin_rw,
+ pin_e= pin_e,
+ pins_data= pins_data,
+ pin_backlight= pin_backlight,
+ cols= int(config.get('lcdSize', 'LCD_WIDTH')),
+ rows= int(config.get('lcdSize', 'LCD_HEIGHT')),
+ backlight_enabled= backlight_enabled,
+ backlight_mode= BacklightMode.active_high)
+
+ def toggleBacklight(self, state=None):
+ if (state == None):
+ state = not self.backlight_enabled
+
+ if (state):
+ print("Turning LCD backlight on")
+ else:
+ print("Turning LCD backlight off")
+
+ self.backlight_enabled = state
+
+ def displayText(self, text, duration=5):
+ if (text == None):
+ print ("Warning (LiquidCrystalDisplay.displayText): Text parameter is empty")
+ return
+
+ maxCharacters = self.lcd.cols * self.lcd.rows
+
+ self.toggleBacklight(True)
+
+ print("Writing " + text + " to LCD")
+
+ if (len(text) > maxCharacters):
+ print ("Trimming " + text + " to " + text[:maxCharacters])
+ text = text[:maxCharacters]
+
+ self.write_string(text)
+ time.sleep(duration)
+ self.clear()
+
+ self.toggleBacklight(False)
+
+ def displayScrollingText(self, lineOne, lineTwo=None, lineOneDelay=5, lineTwoDelay=2, lineOneResetDelay=2, clearDelay=5, tick=0.2):
+ if (lineOne == None):
+ print ("Warning (LiquidCrystalDisplay.displayScrollingText): LineOne parameter is empty")
+ return
+
+ self.toggleBacklight(True)
+
+ # Determine how many ticks it will take to dislay lineOne
+ lineOneTicks = len(lineOne) - self.lcd.cols + 1 if len(lineOne) > 16 else 1
+
+ # Scroll through lineOne, while keeping a maximum of 16 characters of lineTwo stationary (if it's not None)
+ for i in range(0, lineOneTicks):
+ self.clear()
+ self.writeTextToRow(lineOne[i:i + self.lcd.cols], 0)
+
+ if (lineTwo != None):
+ self.writeTextToRow(lineTwo[0:self.lcd.cols], 1)
+
+ time.sleep(lineOneDelay if i == 0 else tick)
+
+ if (lineTwo != None):
+ time.sleep(lineOneResetDelay)
+
+ # Determine how many ticks it will take to dislay lineTwo
+ lineTwoTicks = len(lineTwo) - self.lcd.cols + 1 if len(lineTwo) > 16 else 1
+
+ # Scroll through lineTwo, while keeping a maximum of 16 characters of lineOne stationary
+ for i in range(0, lineTwoTicks):
+ self.clear()
+ self.writeTextToRow(lineOne[0:self.lcd.cols], 0)
+ self.writeTextToRow(lineTwo[i:i + self.lcd.cols], 1)
+
+ time.sleep(lineTwoDelay if i == 0 else tick)
+
+ time.sleep(clearDelay)
+ self.clear()
+
+ self.toggleBacklight(False)
+
+ def writeTextToRow(self, text, row):
+ if (row > self.lcd.rows - 1):
+ print ("Warning (LiquidCrystalDisplay.writeTextToRow): Row parameter is too high")
+ return
+
+ print("Writing " + text + " to LCD row " + str(row))
+
+ if (len(text) > self.lcd.cols):
+ print ("Trimming " + text + " to " + text[:self.lcd.cols])
+ text = text[:self.lcd.cols]
+
+ self.cursor_pos = (row, 0)
+ self.write_string(text)
diff --git a/pool/shard009/Python/0086423_datazips.py b/pool/shard009/Python/0086423_datazips.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bbc671f1aacfa644c4ece6c68ad9f72982df80c
--- /dev/null
+++ b/pool/shard009/Python/0086423_datazips.py
@@ -0,0 +1,81 @@
+# coding: utf-8
+"""
+@file
+@brief Data mostly for the first and second years.
+"""
+import os
+from pyquickhelper.loghelper import noLOG
+from pyensae.filehelper.decompress_helper import decompress_zip
+
+
+def anyzip(filename, local=True, cache_folder=".", multi=False,
+ fLOG=noLOG, **kwargs):
+ """
+ Any zip.
+
+ @param filename filename
+ @param local local data or web
+ @param cache_folder where to cache the data if downloaded a second time
+ @param fLOG logging function
+ @param multi multiple files
+ @param kwargs downloading arguments
+ @return filename (str)
+ """
+ if local:
+ this = os.path.abspath(os.path.dirname(__file__))
+ this = os.path.join(this, "zips", filename)
+ if not os.path.exists(this):
+ raise FileNotFoundError(this)
+ res = decompress_zip(this, whereTo=cache_folder, fLOG=fLOG)
+ if cache_folder is not None:
+ res = [os.path.join(cache_folder, _) for _ in res]
+ else:
+ import pyensae.datasource
+ this = pyensae.datasource.download_data(
+ filename, whereTo=cache_folder, fLOG=fLOG, **kwargs)
+ if cache_folder is not None:
+ res = [os.path.join(cache_folder, _) for _ in this]
+ else:
+ res = this
+ if isinstance(res, list):
+ return res if multi else res[0]
+ return res
+
+
+def besancon_df(local=True, cache_folder=".", fLOG=noLOG):
+ """
+ Retrieves ``Besancon.df.zip``.
+
+ @param local local data or web
+ @param cache_folder where to cache the data if downloaded a second time
+ @param fLOG logging function
+ @return filename (str)
+ """
+ return anyzip("besancon.df.txt.zip", local=local, cache_folder=cache_folder,
+ fLOG=fLOG, website="xdtd")
+
+
+def added(local=True, cache_folder=".", fLOG=noLOG):
+ """
+ Retrieves ``added.zip``.
+
+ @param local local data or web
+ @param cache_folder where to cache the data if downloaded a second time
+ @param fLOG logging function
+ @return filename (str)
+ """
+ return anyzip("added.zip", local=local, cache_folder=cache_folder, fLOG=fLOG)
+
+
+def deal_flow_espace_vert_2018_2019(local=True, cache_folder=".", fLOG=noLOG):
+ """
+ Retrieves ``deal_flow_espaces_verts_2018_2019.zip``.
+ The sources compiles two files from pages:
+ * `Deal flow des projets verts : projets notifiés et financés en 2018
+ `_
+ * `Deal flow des projets verts - Projets financés en 2019 et investissements envisagés en 2019
+ `_
+ See :ref:`dealflowespacevertrst`.
+ """
+ return anyzip("deal_flow_espaces_verts_2018_2019.zip", local=local,
+ cache_folder=cache_folder, multi=True, fLOG=fLOG)
diff --git a/pool/shard009/Python/0086427_resolve_duplicates.py b/pool/shard009/Python/0086427_resolve_duplicates.py
new file mode 100644
index 0000000000000000000000000000000000000000..a356ce0bdc890c07d287381e75b023388647de1f
--- /dev/null
+++ b/pool/shard009/Python/0086427_resolve_duplicates.py
@@ -0,0 +1,36 @@
+# Copyright (C) 2016 Google Inc.
+# Licensed under http://www.apache.org/licenses/LICENSE-2.0
+
+"""
+Resolve duplicates.
+
+This helper is used by the following migrations:
+
+* ggrc.migrations.verisions.20160223152916_204540106539;
+* ggrc_risk_assessments.migrations.verisions.20151112161029_62f26762d0a.
+
+"""
+
+from sqlalchemy import and_
+from sqlalchemy.orm import aliased
+
+from ggrc import db
+
+
+def resolve_duplicates(model, attr, separator=u"-"):
+ v0, v1 = aliased(model, name="v0"), aliased(model, name="v1")
+ query = db.session.query(v0).join(v1, and_(
+ getattr(v0, attr) == getattr(v1, attr),
+ v0.id > v1.id
+ ))
+ for v in query:
+ i = 1
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ while db.session.query(model).\
+ filter(getattr(model, attr) == nattr).count():
+ i += 1
+ nattr = "{}{}{}".format(getattr(v, attr, model.type), separator, i)
+ setattr(v, attr, nattr)
+ db.session.add(v)
+ db.session.flush()
+ db.session.commit()
diff --git a/pool/shard009/Python/0086431_flask_app.py b/pool/shard009/Python/0086431_flask_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb004f2d823698523fe31e412891ca8c0d19c795
--- /dev/null
+++ b/pool/shard009/Python/0086431_flask_app.py
@@ -0,0 +1,62 @@
+""" twittback main Flask application """
+
+import flask
+
+import twittback.server
+
+
+server = twittback.server.build_server()
+app = server.app
+
+
+@app.errorhandler(404)
+def not_found(error):
+ return server.not_found(), 404
+
+
+@app.route("/")
+def home_timeline():
+ return server.home_timeline()
+
+
+@app.route("/archives")
+def archives():
+ return server.archives()
+
+
+@app.route("/favicon.ico")
+def favicon():
+ return server.favicon()
+
+
+@app.route("/feed.atom")
+def feed():
+ return server.gen_feed()
+
+
+@app.route("/view/tweet/")
+def view_tweet(twitter_id):
+ return server.view_tweet(twitter_id)
+
+
+@app.route("/view/user")
+def view_user():
+ return server.view_user()
+
+
+@app.route("/timeline//")
+def timeline(year, month):
+ return server.timeline(year, month)
+
+
+@app.route("/search")
+def search():
+ pattern = flask.request.args.get("pattern")
+ if pattern:
+ return server.search(pattern)
+ else:
+ return server.search_form()
+
+
+if __name__ == "__main__":
+ app.run(port=server.port)
diff --git a/pool/shard009/Python/0086437_rendering_resource_settings_manager.py b/pool/shard009/Python/0086437_rendering_resource_settings_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..a42b63fd57c33a17594000d269d861fcd93f2ce7
--- /dev/null
+++ b/pool/shard009/Python/0086437_rendering_resource_settings_manager.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# pylint: disable=E1101
+# pylint: disable=W0403
+
+# Copyright (c) 2014-2015, Human Brain Project
+# Cyrille Favreau
+#
+# This file is part of RenderingResourceManager
+#
+#
+# This library is free software; you can redistribute it and/or modify it under
+# the terms of the GNU Lesser General Public License version 3.0 as published
+# by the Free Software Foundation.
+#
+# This library 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 library; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# All rights reserved. Do not distribute without further notice.
+
+"""
+This class is in charge of handling rendering resources config, such as the
+application name, executable name and command line parameters,
+and ensures persistent storage in a database
+"""
+
+from rendering_resource_manager_service.config.models import RenderingResourceSettings
+import rendering_resource_manager_service.utils.custom_logging as log
+import rest_framework.status as http_status
+from django.db import IntegrityError, transaction
+from rest_framework.renderers import JSONRenderer
+import json
+
+
+class RenderingResourceSettingsManager(object):
+ """
+ This class is in charge of handling session and ensures persistent storage in a database
+ """
+
+ @classmethod
+ def create(cls, params):
+ """
+ Creates new rendering resource config
+ :param params Settings for the new rendering resource
+ """
+ try:
+ settings_id = params['id'].lower()
+ settings = RenderingResourceSettings(
+ id=settings_id,
+ command_line=str(params['command_line']),
+ environment_variables=str(params['environment_variables']),
+ modules=str(params['modules']),
+ process_rest_parameters_format=str(params['process_rest_parameters_format']),
+ scheduler_rest_parameters_format=str(params['scheduler_rest_parameters_format']),
+ project=str(params['project']),
+ queue=str(params['queue']),
+ exclusive=params['exclusive'],
+ nb_nodes=params['nb_nodes'],
+ nb_cpus=params['nb_cpus'],
+ nb_gpus=params['nb_gpus'],
+ memory=params['memory'],
+ graceful_exit=params['graceful_exit'],
+ wait_until_running=params['wait_until_running'],
+ name=params['name'],
+ description=params['description']
+ )
+ with transaction.atomic():
+ settings.save(force_insert=True)
+ msg = 'Rendering Resource ' + settings_id + ' successfully configured'
+ response = json.dumps({'contents': msg})
+ return [http_status.HTTP_201_CREATED, response]
+ except IntegrityError as e:
+ log.error(str(e))
+ response = json.dumps({'contents': str(e)})
+ return [http_status.HTTP_409_CONFLICT, response]
+
+ @classmethod
+ def update(cls, params):
+ """
+ Updates some given rendering resource config
+ :param params new config for the rendering resource
+ """
+ try:
+ settings_id = params['id'].lower()
+ settings = RenderingResourceSettings.objects.get(id=settings_id)
+ settings.command_line = params['command_line']
+ settings.environment_variables = params['environment_variables']
+ settings.modules = params['modules']
+ settings.process_rest_parameters_format = params['process_rest_parameters_format']
+ settings.scheduler_rest_parameters_format = params['scheduler_rest_parameters_format']
+ settings.project = params['project']
+ settings.queue = params['queue']
+ settings.exclusive = params['exclusive']
+ settings.nb_nodes = params['nb_nodes']
+ settings.nb_cpus = params['nb_cpus']
+ settings.nb_gpus = params['nb_gpus']
+ settings.memory = params['memory']
+ settings.graceful_exit = params['graceful_exit']
+ settings.wait_until_running = params['wait_until_running']
+ settings.name = params['name']
+ settings.description = params['description']
+ with transaction.atomic():
+ settings.save()
+ return [http_status.HTTP_200_OK, '']
+ except RenderingResourceSettings.DoesNotExist as e:
+ log.error(str(e))
+ return [http_status.HTTP_404_NOT_FOUND, str(e)]
+
+ @classmethod
+ def list(cls, serializer):
+ """
+ Returns a JSON formatted list of active rendering resource config according
+ to a given serializer
+ :param serializer: Serializer used for formatting the list of session
+ """
+ settings = RenderingResourceSettings.objects.all()
+ return [http_status.HTTP_200_OK,
+ JSONRenderer().render(serializer(settings, many=True).data)]
+
+ @staticmethod
+ def get_by_id(settings_id):
+ """
+ Returns the config rendering resource config
+ :param settings_id id of rendering resource or which we want the config
+ """
+ return RenderingResourceSettings.objects.get(id=settings_id)
+
+ @classmethod
+ def delete(cls, settings_id):
+ """
+ Removes some given rendering resource config
+ :param settings_id Identifier of the Rendering resource config to remove
+ """
+ try:
+ settings = RenderingResourceSettings.objects.get(id=settings_id)
+ with transaction.atomic():
+ settings.delete()
+ return [http_status.HTTP_200_OK, 'Settings successfully deleted']
+ except RenderingResourceSettings.DoesNotExist as e:
+ log.error(str(e))
+ return [http_status.HTTP_404_NOT_FOUND, str(e)]
+
+ @staticmethod
+ def format_rest_parameters(string_format, hostname, port, schema, job_id):
+ """
+ Returns a string of rest parameters formatted according to the
+ string_format argument
+ :param string_format Rest parameter string format
+ :param hostname Rest hostname
+ :param port Rest port
+ :param schema Rest schema
+ """
+ response = string_format
+ response = response.replace('${job_id}', str(job_id))
+ response = response.replace('${rest_hostname}', str(hostname))
+ response = response.replace('${rest_port}', str(port))
+ response = response.replace('${rest_schema}', str(schema))
+ return response
+
+ @classmethod
+ def clear(cls):
+ """
+ Clear all config
+ """
+ with transaction.atomic():
+ RenderingResourceSettings.objects.all().delete()
+ return [http_status.HTTP_200_OK, 'Settings cleared']
diff --git a/pool/shard009/Python/0086438_test_read.py b/pool/shard009/Python/0086438_test_read.py
new file mode 100644
index 0000000000000000000000000000000000000000..07ea618520d6f693770e8e237c18212461f619f6
--- /dev/null
+++ b/pool/shard009/Python/0086438_test_read.py
@@ -0,0 +1,79 @@
+import os
+import os.path
+import shutil
+
+import libarchive.public
+import libarchive.constants
+
+_EXPAND_PATH = os.path.join('/tmp', 'libarchive_expand')
+_TEST_READ_ARCHIVE = os.path.join(_EXPAND_PATH, 'read.7z')
+
+# TODO(dustin): Add tests for file and memory pouring.
+
+def _setup():
+ if os.path.exists(_EXPAND_PATH) is True:
+ shutil.rmtree(_EXPAND_PATH)
+
+ os.mkdir(_EXPAND_PATH)
+
+ for entry in libarchive.public.create_file(
+ _TEST_READ_ARCHIVE,
+ libarchive.constants.ARCHIVE_FORMAT_7ZIP,
+ ['/etc/hosts',
+ 'resources/man.conf']):
+ pass
+
+def _teardown():
+ if os.path.exists(_EXPAND_PATH) is True:
+ shutil.rmtree(_EXPAND_PATH)
+
+def test_enumerate_from_file():
+ with libarchive.public.file_enumerator(_TEST_READ_ARCHIVE) as e:
+ for entry in e:
+ pass
+
+test_enumerate_from_file.setUp = _setup
+test_enumerate_from_file.tearDown = _teardown
+
+def test_enumerate_from_memory():
+ with open(_TEST_READ_ARCHIVE, 'rb') as f:
+ buffer_ = f.read()
+ with libarchive.public.memory_enumerator(buffer_) as e:
+ for entry in e:
+ pass
+
+test_enumerate_from_memory.setUp = _setup
+test_enumerate_from_memory.tearDown = _teardown
+
+def _tree_writer(e):
+ for entry in e:
+ rel_filepath = entry.pathname
+ rel_path = os.path.dirname(rel_filepath)
+
+ if rel_path != '':
+ path = os.path.join(_EXPAND_PATH, rel_path)
+
+ if os.path.exists(path) is False:
+ os.makedirs(path)
+
+ filepath = os.path.join(_EXPAND_PATH, entry.pathname)
+
+ with open(filepath, 'wb') as f:
+ for block in entry.get_blocks():
+ f.write(block)
+
+def test_read_from_file():
+ with libarchive.public.file_reader(_TEST_READ_ARCHIVE) as e:
+ _tree_writer(e)
+
+test_read_from_file.setUp = _setup
+test_read_from_file.tearDown = _teardown
+
+def test_read_from_memory():
+ with open(_TEST_READ_ARCHIVE, 'rb') as f:
+ buffer_ = f.read()
+ with libarchive.public.memory_reader(buffer_) as e:
+ _tree_writer(e)
+
+test_read_from_memory.setUp = _setup
+test_read_from_memory.tearDown = _teardown
diff --git a/pool/shard009/Python/0086442_text_stream.py b/pool/shard009/Python/0086442_text_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..070b754d6520800791ac726fe55ac7bcff79cb1e
--- /dev/null
+++ b/pool/shard009/Python/0086442_text_stream.py
@@ -0,0 +1,23 @@
+import os
+from os import environ
+
+from python_anticaptcha import AnticaptchaClient, ImageToTextTask
+
+api_key = environ["KEY"]
+DIR = os.path.dirname(os.path.abspath(__file__))
+IMAGE = "{}/captcha_ms.jpeg".format(DIR)
+EXPECTED_RESULT = "56nn2"
+
+
+def process(path):
+ captcha_fp = open(path, "rb")
+ client = AnticaptchaClient(api_key)
+ task = ImageToTextTask(captcha_fp)
+ job = client.createTaskSmee(task)
+ return job.get_captcha_text()
+
+
+if __name__ == "__main__":
+ print("Image: " + IMAGE)
+ print("Result: " + str(process(IMAGE)))
+ print("Expected: " + str(EXPECTED_RESULT))
diff --git a/pool/shard009/Python/0086452_datehelper.py b/pool/shard009/Python/0086452_datehelper.py
new file mode 100644
index 0000000000000000000000000000000000000000..3373279af46f0f93e4d0df9f8c7218e17ceb842c
--- /dev/null
+++ b/pool/shard009/Python/0086452_datehelper.py
@@ -0,0 +1,166 @@
+#===============================================================================
+# LICENSE XOT-Framework - CC BY-NC-ND
+#===============================================================================
+# This work is licenced under the Creative Commons
+# Attribution-Non-Commercial-No Derivative Works 3.0 Unported License. To view a
+# copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
+# or send a letter to Creative Commons, 171 Second Street, Suite 300,
+# San Francisco, California 94105, USA.
+#===============================================================================
+import datetime
+
+#===============================================================================
+# Make global object available
+#===============================================================================
+# from logger import Logger
+
+
+class DateHelper:
+ """Helper class to parse datenames into numbers"""
+
+ def __init__(self):
+ """No initialisation, just statics"""
+
+ raise NotImplementedError("Just statics")
+
+ @staticmethod
+ def ThisYear():
+ now = datetime.datetime.now()
+ return now.year
+
+ @staticmethod
+ def GetDateForNextDay(day, possibilities=["ma", "di", "wo", "do", "vr", "za", "zo"], tomorrow="Morgen"):
+ """ Gets the date for the next Weekday (default ["ma", "di", "wo", "do", "vr", "za", "zo"]).
+
+ Arguments:
+ day : String - Weekday with that has in index in the "possibilities" parameter
+
+ Keywork Arguments:
+ possibilities : List - List of possible weekdays.
+
+ Returns the date of the next "day".
+
+ """
+
+ date = datetime.datetime.now()
+ dayNow = date.weekday()
+
+ if (day.lower() == tomorrow.lower()):
+ return date + datetime.timedelta(days=1)
+
+ dayOfWeekToFind = possibilities.index(day)
+
+ if dayNow < dayOfWeekToFind:
+ dateToFind = date + datetime.timedelta(days=dayOfWeekToFind - dayNow)
+ else:
+ # Now: Su (6), Need Mo (0)
+ dateToFind = date + datetime.timedelta(days=dayOfWeekToFind + 7 - dayNow)
+
+ return dateToFind
+
+ @staticmethod
+ def GetDateForPreviousDay(day, possibilities=["ma", "di", "wo", "do", "vr", "za", "zo"], yesterday="Gisteren"):
+ """ Gets the date for the previous Weekday (default ["ma", "di", "wo", "do", "vr", "za", "zo"]).
+
+ Arguments:
+ day : String - Weekday with that has in index in the "possibilities" parameter
+
+ Keywork Arguments:
+ possibilities : List - List of possible weekdays.
+
+ Returns the date of the previous "day".
+
+ """
+
+ date = datetime.datetime.now()
+ dayNow = date.weekday()
+
+ if (day.lower() == yesterday.lower()):
+ return date + datetime.timedelta(days=-1)
+
+ dayOfWeekToFind = possibilities.index(day)
+
+ if dayNow >= dayOfWeekToFind:
+ dateToFind = date - datetime.timedelta(days=dayNow - dayOfWeekToFind)
+ else:
+ # Now: Su (6), Need Mo (0)
+ dateToFind = date - datetime.timedelta(days=dayNow + 7 - dayOfWeekToFind)
+
+ return dateToFind
+
+ @staticmethod
+ def GetMonthFromName(month, language, short=None):
+ """Gets the month number from the name.
+
+ Arguments:
+ month : string - Name of the month
+ language : string - Language code (nl, en)
+
+ Keyword Arguments:
+ short : [opt] boolean - indicates the monthnames are short. Default: None
+
+ Returns:
+ the month number. If short = None, both long and short formats are tried
+ with the short first, then the long.
+ if short is True or False, only those options are selected.
+
+ """
+
+ if short is None:
+ try:
+ return DateHelper.__GetMonthFromName(month, language, True)
+ except:
+ return DateHelper.__GetMonthFromName(month, language, False)
+ else:
+ return DateHelper.__GetMonthFromName(month, language, short)
+
+ @staticmethod
+ def __GetMonthFromName(month, language, short=True):
+ """Gets the month number from the name.
+
+ Arguments:
+ month : string - Name of the month
+ language : string - Language code (nl, en)
+
+ Keyword Arguments:
+ short : [opt] boolean - indicates the monthnames are short. Default: True
+
+ Returns:
+ the month number
+
+ """
+
+ if language == "nl" and short:
+ monthLookup = ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
+ elif language == "nl":
+ monthLookup = ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"]
+
+ elif language == "en" and short:
+ monthLookup = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
+ elif language == "en":
+ monthLookup = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
+
+ elif language == "se" and short:
+ monthLookup = ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]
+ elif language == "se":
+ monthLookup = ["januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december"]
+
+ else:
+ error = "Language code '%s' not implemented"
+ raise NotImplementedError(error)
+
+ if monthLookup.count(month.lower()) > 0:
+ monthValue = monthLookup.index(month.lower()) + 1
+ else:
+ error = "Month '%s' not found for language '%s'" % (month, language)
+ raise ValueError(error)
+ return monthValue
+
+if __name__ == "__main__":
+ print "Next"
+ for day in ("ma", "di", "wo", "do", "vr", "za", "zo", "morgen"):
+ print "%s: %s" % (day, DateHelper.GetDateForNextDay(day))
+
+ print "Previous"
+ for day in ("ma", "di", "wo", "do", "vr", "za", "zo", "gisteren"):
+ print "%s: %s" % (day, DateHelper.GetDateForPreviousDay(day))
diff --git a/pool/shard009/Python/0086453_test_transforms.py b/pool/shard009/Python/0086453_test_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..8346612d9b672eed2156fdf29e2043d332ec73d5
--- /dev/null
+++ b/pool/shard009/Python/0086453_test_transforms.py
@@ -0,0 +1,214 @@
+#
+# Copyright 2014 Quantopian, 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 datetime import timedelta
+from functools import wraps
+from itertools import product
+from nose_parameterized import parameterized
+import operator
+import random
+from six import itervalues
+from six.moves import map
+from unittest import TestCase
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from zipline.algorithm import TradingAlgorithm
+import zipline.utils.factory as factory
+from zipline.api import add_transform, get_datetime
+
+
+def handle_data_wrapper(f):
+ @wraps(f)
+ def wrapper(context, data):
+ dt = get_datetime()
+ if dt.date() != context.current_date:
+ context.warmup -= 1
+ context.mins_for_days.append(1)
+ context.current_date = dt.date()
+ else:
+ context.mins_for_days[-1] += 1
+
+ hist = context.history(2, '1d', 'close_price')
+ for n in (1, 2, 3):
+ if n in data:
+ if data[n].dt == dt:
+ context.vol_bars[n].append(data[n].volume)
+ else:
+ context.vol_bars[n].append(0)
+
+ context.price_bars[n].append(data[n].price)
+ else:
+ context.price_bars[n].append(np.nan)
+ context.vol_bars[n].append(0)
+
+ context.last_close_prices[n] = hist[n][0]
+
+ if context.warmup < 0:
+ return f(context, data)
+
+ return wrapper
+
+
+def initialize_with(test_case, tfm_name, days):
+ def initalize(context):
+ context.test_case = test_case
+ context.days = days
+ context.mins_for_days = []
+ context.price_bars = (None, [np.nan], [np.nan], [np.nan])
+ context.vol_bars = (None, [np.nan], [np.nan], [np.nan])
+ if context.days:
+ context.warmup = days + 1
+ else:
+ context.warmup = 2
+
+ context.current_date = None
+
+ context.last_close_prices = [np.nan, np.nan, np.nan, np.nan]
+ add_transform(tfm_name, days)
+
+ return initalize
+
+
+def windows_with_frequencies(*args):
+ args = args or (None,)
+ return product(('daily', 'minute'), args)
+
+
+def with_algo(f):
+ name = f.__name__
+ if not name.startswith('test_'):
+ raise ValueError('This must decorate a test case')
+
+ tfm_name = name[len('test_'):]
+
+ @wraps(f)
+ def wrapper(self, data_frequency, days=None):
+ sim_params, source = self.sim_and_source[data_frequency]
+
+ algo = TradingAlgorithm(
+ initialize=initialize_with(self, tfm_name, days),
+ handle_data=handle_data_wrapper(f),
+ sim_params=sim_params,
+ identifiers=[1, 2, 3]
+ )
+ algo.run(source)
+
+ return wrapper
+
+
+class TransformTestCase(TestCase):
+ """
+ Tests the simple transforms by running them through a zipline.
+ """
+ @classmethod
+ def setUpClass(cls):
+ random.seed(0)
+ cls.sids = (1, 2, 3)
+
+ minute_sim_ps = factory.create_simulation_parameters(
+ num_days=3,
+ sids=cls.sids,
+ data_frequency='minute',
+ emission_rate='minute',
+ )
+ daily_sim_ps = factory.create_simulation_parameters(
+ num_days=30,
+ sids=cls.sids,
+ data_frequency='daily',
+ emission_rate='daily',
+ )
+ cls.sim_and_source = {
+ 'minute': (minute_sim_ps, factory.create_minutely_trade_source(
+ cls.sids,
+ sim_params=minute_sim_ps,
+ )),
+ 'daily': (daily_sim_ps, factory.create_trade_source(
+ cls.sids,
+ trade_time_increment=timedelta(days=1),
+ sim_params=daily_sim_ps,
+ )),
+ }
+
+ def tearDown(self):
+ """
+ Each test consumes a source, we need to rewind it.
+ """
+ for _, source in itervalues(self.sim_and_source):
+ source.rewind()
+
+ @parameterized.expand(windows_with_frequencies(1, 2, 3, 4))
+ @with_algo
+ def test_mavg(context, data):
+ """
+ Tests the mavg transform by manually keeping track of the prices
+ in a naiive way and asserting that our mean is the same.
+ """
+ mins = sum(context.mins_for_days[-context.days:])
+
+ for sid in data:
+ assert_allclose(
+ data[sid].mavg(context.days),
+ np.mean(context.price_bars[sid][-mins:]),
+ )
+
+ @parameterized.expand(windows_with_frequencies(2, 3, 4))
+ @with_algo
+ def test_stddev(context, data):
+ """
+ Tests the stddev transform by manually keeping track of the prices
+ in a naiive way and asserting that our stddev is the same.
+ This accounts for the corrected ddof.
+ """
+ mins = sum(context.mins_for_days[-context.days:])
+
+ for sid in data:
+ assert_allclose(
+ data[sid].stddev(context.days),
+ np.std(context.price_bars[sid][-mins:], ddof=1),
+ )
+
+ @parameterized.expand(windows_with_frequencies(2, 3, 4))
+ @with_algo
+ def test_vwap(context, data):
+ """
+ Tests the vwap transform by manually keeping track of the prices
+ and volumes in a naiive way and asserting that our hand-rolled vwap is
+ the same
+ """
+ mins = sum(context.mins_for_days[-context.days:])
+ for sid in data:
+ prices = context.price_bars[sid][-mins:]
+ vols = context.vol_bars[sid][-mins:]
+ manual_vwap = sum(
+ map(operator.mul, np.nan_to_num(np.array(prices)), vols),
+ ) / sum(vols)
+
+ assert_allclose(
+ data[sid].vwap(context.days),
+ manual_vwap,
+ )
+
+ @parameterized.expand(windows_with_frequencies())
+ @with_algo
+ def test_returns(context, data):
+ for sid in data:
+ last_close = context.last_close_prices[sid]
+ returns = (data[sid].price - last_close) / last_close
+
+ assert_allclose(
+ data[sid].returns(),
+ returns,
+ )
diff --git a/pool/shard009/Python/0086458_postreply.py b/pool/shard009/Python/0086458_postreply.py
new file mode 100644
index 0000000000000000000000000000000000000000..905e07a840df852171e487c81962e55d8e105421
--- /dev/null
+++ b/pool/shard009/Python/0086458_postreply.py
@@ -0,0 +1,23 @@
+
+from google.appengine.ext import db
+from talkyuser import TalkyUser
+from userpost import UserPost
+import utils
+
+
+class PostReply(db.Model):
+ owner = db.ReferenceProperty(reference_class=TalkyUser, collection_name='replies')
+ post = db.ReferenceProperty(reference_class=UserPost, collection_name='replies')
+ dateTime = db.DateTimeProperty(auto_now_add=True)
+ content = db.StringProperty(multiline=True)
+
+ def toInterchangeable(self):
+ interchangeable = {
+ 'id':self.key().id(),
+ 'owner':self.owner.fb_uid,
+ 'content':self.content,
+ 'date_time':utils.dateTimeToInterchangeable(self.dateTime),
+ }
+ return interchangeable
+
+
diff --git a/pool/shard009/Python/0086461_test_power.py b/pool/shard009/Python/0086461_test_power.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b8699a42dca71fd1005b02f6f133b6b905621e1
--- /dev/null
+++ b/pool/shard009/Python/0086461_test_power.py
@@ -0,0 +1,156 @@
+#
+# 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.
+
+"""
+Test class for DRAC Power Driver
+"""
+
+import mock
+
+from ironic.common import exception
+from ironic.common import states
+from ironic.db import api as dbapi
+from ironic.drivers.modules.drac import client as drac_client
+from ironic.drivers.modules.drac import common as drac_common
+from ironic.drivers.modules.drac import power as drac_power
+from ironic.drivers.modules.drac import resource_uris
+from ironic.openstack.common import context
+from ironic.tests import base
+from ironic.tests.db import utils as db_utils
+from ironic.tests.drivers.drac import utils as test_utils
+
+INFO_DICT = db_utils.get_test_drac_info()
+
+
+@mock.patch.object(drac_client, 'pywsman')
+@mock.patch.object(drac_power, 'pywsman')
+class DracPowerInternalMethodsTestCase(base.TestCase):
+
+ def setUp(self):
+ super(DracPowerInternalMethodsTestCase, self).setUp()
+ driver_info = INFO_DICT
+ db_node = db_utils.get_test_node(driver='fake_drac',
+ driver_info=driver_info,
+ instance_uuid='instance_uuid_123')
+ self.dbapi = dbapi.get_instance()
+ self.node = self.dbapi.create_node(db_node)
+
+ def test__get_power_state(self, mock_power_pywsman, mock_client_pywsman):
+ result_xml = test_utils.build_soap_xml([{'EnabledState': '2'}],
+ resource_uris.DCIM_ComputerSystem)
+ mock_xml = test_utils.mock_wsman_root(result_xml)
+ mock_pywsman_client = mock_client_pywsman.Client.return_value
+ mock_pywsman_client.enumerate.return_value = mock_xml
+
+ self.assertEqual(states.POWER_ON,
+ drac_power._get_power_state(self.node))
+
+ mock_pywsman_client.enumerate.assert_called_once_with(mock.ANY,
+ mock.ANY, resource_uris.DCIM_ComputerSystem)
+
+ def test__set_power_state(self, mock_power_pywsman, mock_client_pywsman):
+ result_xml = test_utils.build_soap_xml([{'ReturnValue':
+ drac_common.RET_SUCCESS}],
+ resource_uris.DCIM_ComputerSystem)
+ mock_xml = test_utils.mock_wsman_root(result_xml)
+ mock_pywsman_client = mock_client_pywsman.Client.return_value
+ mock_pywsman_client.invoke.return_value = mock_xml
+
+ mock_pywsman_clientopts = mock_power_pywsman.ClientOptions.return_value
+
+ drac_power._set_power_state(self.node, states.POWER_ON)
+
+ mock_pywsman_clientopts.add_selector.assert_has_calls([
+ mock.call('CreationClassName', 'DCIM_ComputerSystem'),
+ mock.call('Name', 'srv:system')
+ ])
+ mock_pywsman_clientopts.add_property.assert_called_once_with(
+ 'RequestedState', '2')
+
+ mock_pywsman_client.invoke.assert_called_once_with(mock.ANY,
+ resource_uris.DCIM_ComputerSystem, 'RequestStateChange')
+
+ def test__set_power_state_fail(self, mock_power_pywsman,
+ mock_client_pywsman):
+ result_xml = test_utils.build_soap_xml([{'ReturnValue':
+ drac_common.RET_ERROR,
+ 'Message': 'error message'}],
+ resource_uris.DCIM_ComputerSystem)
+
+ mock_xml = test_utils.mock_wsman_root(result_xml)
+ mock_pywsman_client = mock_client_pywsman.Client.return_value
+ mock_pywsman_client.invoke.return_value = mock_xml
+
+ mock_pywsman_clientopts = mock_power_pywsman.ClientOptions.return_value
+
+ self.assertRaises(exception.DracOperationError,
+ drac_power._set_power_state, self.node,
+ states.POWER_ON)
+
+ mock_pywsman_clientopts.add_selector.assert_has_calls([
+ mock.call('CreationClassName', 'DCIM_ComputerSystem'),
+ mock.call('Name', 'srv:system')
+ ])
+ mock_pywsman_clientopts.add_property.assert_called_once_with(
+ 'RequestedState', '2')
+
+ mock_pywsman_client.invoke.assert_called_once_with(mock.ANY,
+ resource_uris.DCIM_ComputerSystem, 'RequestStateChange')
+
+
+class DracPowerTestCase(base.TestCase):
+
+ def setUp(self):
+ super(DracPowerTestCase, self).setUp()
+ driver_info = INFO_DICT
+ db_node = db_utils.get_test_node(driver='fake_drac',
+ driver_info=driver_info,
+ instance_uuid='instance_uuid_123')
+ self.dbapi = dbapi.get_instance()
+ self.node = self.dbapi.create_node(db_node)
+ self.context = context.get_admin_context()
+
+ def test_get_properties(self):
+ expected = drac_common.COMMON_PROPERTIES
+ driver = drac_power.DracPower()
+ self.assertEqual(expected, driver.get_properties())
+
+ @mock.patch.object(drac_power, '_get_power_state')
+ def test_get_power_state(self, mock_get_power_state):
+ mock_get_power_state.return_value = states.POWER_ON
+ driver = drac_power.DracPower()
+ task = mock.Mock()
+ task.node.return_value = self.node
+
+ self.assertEqual(states.POWER_ON, driver.get_power_state(task))
+ mock_get_power_state.assert_called_once_with(task.node)
+
+ @mock.patch.object(drac_power, '_set_power_state')
+ def test_set_power_state(self, mock_set_power_state):
+ driver = drac_power.DracPower()
+ task = mock.Mock()
+ task.node.return_value = self.node
+
+ driver.set_power_state(task, states.POWER_ON)
+ mock_set_power_state.assert_called_once_with(task.node,
+ states.POWER_ON)
+
+ @mock.patch.object(drac_power, '_set_power_state')
+ def test_reboot(self, mock_set_power_state):
+ driver = drac_power.DracPower()
+ task = mock.Mock()
+ task.node.return_value = self.node
+
+ driver.reboot(task)
+ mock_set_power_state.assert_called_once_with(task.node,
+ states.REBOOT)
diff --git a/pool/shard009/Python/0086464_verify.py b/pool/shard009/Python/0086464_verify.py
new file mode 100644
index 0000000000000000000000000000000000000000..ded332e7e4033f17f277f9d308d677242c6ba3a2
--- /dev/null
+++ b/pool/shard009/Python/0086464_verify.py
@@ -0,0 +1,116 @@
+import hashlib
+import os
+import logging
+import pprint
+import time
+import re
+import threading
+
+
+class Verify:
+ def __init__(self, mountPoint, label, talkToServer, objectStore):
+ self._mountPoint = mountPoint
+ self._hashes = self._readLabel(label)
+ self._talkToServer = talkToServer
+ self._objectStore = objectStore
+
+ @classmethod
+ def dropCaches(cls):
+ with open('/proc/sys/vm/drop_caches', "w") as f:
+ f.write("3\n")
+
+ def go(self):
+ logging.info("Starting Verification")
+ queue = list(self._hashes.iteritems())
+ dontMatch = []
+ lastReport = 0
+ threads = []
+ for i in xrange(self._numberOfCPUs()):
+ threads.append(_VerifyThread(queue, dontMatch, self._mountPoint))
+ while len(queue) > 0:
+ time.sleep(0.1)
+ for thread in threads:
+ if thread.exception is not None:
+ raise Exception("A digestion thread died of an exception, verification failed")
+ if time.time() > lastReport + 10:
+ self._report(len(self._hashes) - len(queue), len(self._hashes))
+ lastReport = time.time()
+ for thread in threads:
+ if thread.exception is not None:
+ raise Exception("A digestion thread died of an exception, verification failed")
+ self._report(len(self._hashes), len(self._hashes))
+ if len(dontMatch) > 0:
+ logging.error("VERIFICATION OF DEPLOYED ROOTFS LABEL FAILED")
+ logging.error("%s", pprint.pformat(dontMatch))
+ raise Exception("Verification of deployed rootfs label failed")
+ logging.info("Verification completed successfully")
+
+ def _readLabel(self, label):
+ with open(os.path.join(self._objectStore, "labels", label)) as f:
+ labelHash = f.read().strip()
+ labelFile = os.path.join(objectStore, labelHash[:2], labelHash[2:4], labelHash[4:])
+ return self._parseLabelFile(labelFile)
+
+ def _parseLabelFile(self, filename):
+ BLACKLIST = set(['/etc/lvm/cache/.cache', '/etc/shadow'])
+ result = {}
+ with open(filename) as f:
+ for line in f.readlines():
+ parts = line.strip().split("\t")
+ if parts[2] == "nohash":
+ continue
+ path = '/' + parts[0].strip('"')
+ if path in BLACKLIST:
+ continue
+ result[path] = parts[2]
+ return result
+
+ def _report(self, done, total):
+ percent = 100 * done / total
+ progress = dict(state='verifying', percent=percent, done=done, total=total)
+ logging.info("Verification progress: %s", (progress, ))
+ if self._talkToServer is not None:
+ self._talkToServer.progress(progress)
+
+ def _numberOfCPUs(self):
+ with open("/proc/cpuinfo") as f:
+ content = f.read()
+ result = len(re.findall(r"\nvendor_id\s", content))
+ assert result > 0
+ return result
+
+
+class _VerifyThread(threading.Thread):
+ def __init__(self, queue, dontMatch, mountPoint):
+ self._queue = queue
+ self._dontMatch = dontMatch
+ self._mountPoint = mountPoint
+ self.exception = None
+ threading.Thread.__init__(self)
+ self.daemon = True
+ threading.Thread.start(self)
+
+ def run(self):
+ try:
+ while True:
+ try:
+ path, digest = self._queue.pop()
+ except:
+ return
+ result = self._verify(path, digest)
+ if result is not None:
+ self._dontMatch.append(result)
+ except Exception as e:
+ self.exception = e
+ logging.exception("Verification thread died of exception")
+
+ def _verify(self, path, digest):
+ absolute = os.path.join(self._mountPoint, path.lstrip("/"))
+ if not os.path.isfile(absolute):
+ return path, "notfound"
+ with open(absolute, "rb") as f:
+ content = f.read()
+ computed = hashlib.md5(content).hexdigest()
+ if computed != digest:
+ return path, "digest"
+ return None
diff --git a/pool/shard009/Python/0086473_test_multiple_create.py b/pool/shard009/Python/0086473_test_multiple_create.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcadacefc563e18bb237e5bd4a041c66e3bc49d3
--- /dev/null
+++ b/pool/shard009/Python/0086473_test_multiple_create.py
@@ -0,0 +1,49 @@
+# Copyright 2013 IBM Corp
+# 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.
+
+from tempest.api.compute import base
+from tempest.common import compute
+from tempest.lib import decorators
+
+
+class MultipleCreateTestJSON(base.BaseV2ComputeTest):
+ create_default_network = True
+
+ @decorators.idempotent_id('61e03386-89c3-449c-9bb1-a06f423fd9d1')
+ def test_multiple_create(self):
+ # Creating server with min_count=2, 2 servers will be created.
+ tenant_network = self.get_tenant_network()
+ body, servers = compute.create_test_server(
+ self.os_primary,
+ wait_until='ACTIVE',
+ min_count=2,
+ tenant_network=tenant_network)
+ for server in servers:
+ self.addCleanup(self.servers_client.delete_server, server['id'])
+ # NOTE(maurosr): do status response check and also make sure that
+ # reservation_id is not in the response body when the request send
+ # contains return_reservation_id=False
+ self.assertNotIn('reservation_id', body)
+ self.assertEqual(2, len(servers))
+
+ @decorators.idempotent_id('864777fb-2f1e-44e3-b5b9-3eb6fa84f2f7')
+ def test_multiple_create_with_reservation_return(self):
+ # Creating multiple servers with return_reservation_id=True,
+ # reservation_id will be returned.
+ body = self.create_test_server(wait_until='ACTIVE',
+ min_count=1,
+ max_count=2,
+ return_reservation_id=True)
+ self.assertIn('reservation_id', body)
diff --git a/pool/shard009/Python/0086480_test_stat.py b/pool/shard009/Python/0086480_test_stat.py
new file mode 100644
index 0000000000000000000000000000000000000000..16ce1bc7daad70504fdca38b6612ca43a7c06794
--- /dev/null
+++ b/pool/shard009/Python/0086480_test_stat.py
@@ -0,0 +1,52 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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 unittest
+
+from pyspark.ml.linalg import Vectors
+from pyspark.ml.stat import ChiSquareTest
+from pyspark.sql import DataFrame
+from pyspark.testing.mlutils import SparkSessionTestCase
+
+
+class ChiSquareTestTests(SparkSessionTestCase):
+ def test_chisquaretest(self):
+ data = [
+ [0, Vectors.dense([0, 1, 2])],
+ [1, Vectors.dense([1, 1, 1])],
+ [2, Vectors.dense([2, 1, 0])],
+ ]
+ df = self.spark.createDataFrame(data, ["label", "feat"])
+ res = ChiSquareTest.test(df, "feat", "label")
+ # This line is hitting the collect bug described in #17218, commented for now.
+ # pValues = res.select("degreesOfFreedom").collect())
+ self.assertIsInstance(res, DataFrame)
+ fieldNames = set(field.name for field in res.schema.fields)
+ expectedFields = ["pValues", "degreesOfFreedom", "statistics"]
+ self.assertTrue(all(field in fieldNames for field in expectedFields))
+
+
+if __name__ == "__main__":
+ from pyspark.ml.tests.test_stat import * # noqa: F401
+
+ try:
+ import xmlrunner # type: ignore[import]
+
+ testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2)
+ except ImportError:
+ testRunner = None
+ unittest.main(testRunner=testRunner, verbosity=2)
diff --git a/pool/shard009/Python/0086483_htrace_to_chrome.py b/pool/shard009/Python/0086483_htrace_to_chrome.py
new file mode 100644
index 0000000000000000000000000000000000000000..d82955477aa2664751915023381f903b88fdc559
--- /dev/null
+++ b/pool/shard009/Python/0086483_htrace_to_chrome.py
@@ -0,0 +1,216 @@
+# Copyright (c) 2016-present, Facebook, 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.
+##############################################################################
+
+## @package htrace_to_chrome
+# Module caffe2.contrib.prof.htrace_to_chrome
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import argparse
+import json
+import re
+import sys
+
+display_levels = ["network", "worker", "operator", "kernel"]
+
+
+def stop_display(limit, curr):
+ return display_levels.index(limit) <= display_levels.index(curr)
+
+
+def build_trace_dict(f, start_time, end_time):
+ """Creates a python dictionary that has trace ids as keys and the
+ corresponding trace objects as values.
+
+ Input: python file object that points to a file with traces, written by
+ htrace-c's local file span receiver.
+ The exact format shouldn't concern you if you're using htrace-c correctly.
+ https://github.com/apache/incubator-htrace/blob/master/htrace-c.
+
+ Returns: a tuple (trace_dic, root_list), where trace_dic is a dictionary
+ containing all traces parsed from the input file object, and root_list is a
+ list of traces from trace_dic which have no parents.
+ Each value in trace_dic is in the form of another dictionary with the
+ folowing keys:
+ "begin" : timestamp of trace start time, microseconds
+ "end" : timestamp of trace end time, microseconds
+ "desc" : description of trace
+ "parent" : trace id of parent trace
+ "children": dictionary of child traces, in the same format as trace_dic
+ """
+ trace_dic = {}
+ root_list = []
+ for line in f:
+ h = json.loads(line)
+ if h["e"] < start_time or h["b"] > end_time:
+ continue
+
+ entry = {"begin": h["b"], "end": h["e"], "desc": h["d"]}
+ if "p" not in h or len(h["p"]) == 0:
+ root_list.append(entry)
+ else:
+ entry["parent"] = h["p"][0]
+ trace_dic[h["a"]] = entry
+
+ for k, v in trace_dic.items():
+ if "parent" not in v:
+ continue
+ parent = trace_dic[v["parent"]]
+ if "children" not in parent:
+ parent["children"] = {}
+ parent["children"][k] = v
+
+ return trace_dic, root_list
+
+
+def generate_chrome_trace(root_list, display):
+ """Takes trace objects created by build_trace_dict() and generates a list of
+ python dictionaries that can be written to a file in json format, which in
+ turn can be given to Chrome tracing (chrome://tracing).
+
+ Input: refer to root_list in build_trace_dict()'s return value.
+
+ Output: list of dictionaries that can be directly written to a json file by
+ json.dumps().
+ The dictionary format follows the JSON array format of Chrome tracing.
+ Complete events ("ph": "X") are used to express most traces; such events
+ will appear as horizontal blocks with lengths equal to the trace duration.
+ Instant events ("ph": "i") are used for traces with many occurrencs which
+ may make the trace graph unreadable; such events are shown as thin lines.
+ """
+ ct = []
+ for root_idx, root in enumerate(root_list):
+ # network-level spans
+ ct.append({
+ "name": root["desc"],
+ "ph": "X",
+ "ts": root["begin"],
+ "dur": root["end"] - root["begin"],
+ "pid": root_idx,
+ "tid": root_idx,
+ "args": {
+ "Start timestamp": root["begin"],
+ "End timestamp": root["end"]
+ }
+ })
+
+ for _, v in root["children"].items():
+ # run-scopes and worker-scopes
+ c = {
+ "name": v["desc"],
+ "ph": "X",
+ "ts": v["begin"],
+ "dur": v["end"] - v["begin"],
+ "pid": root_idx,
+ "args": {
+ "Start timestamp": v["begin"],
+ "End timestamp": v["end"]
+ }
+ }
+
+ if "run-scope" in v["desc"]:
+ c["tid"] = root_idx
+ ct.append(c)
+ else:
+ if stop_display(display, "network"):
+ continue
+
+ m = re.search("(?<=worker-scope-)\d+", v["desc"])
+ wid = m.group(0)
+ c["tid"] = wid
+ ct.append(c)
+
+ if stop_display(display, "worker") or "children" not in v:
+ continue
+ for k_op, v_op in v["children"].items():
+ # operator scopes
+ ct.append({
+ "name": v_op["desc"],
+ "ph": "X",
+ "ts": v_op["begin"],
+ "dur": v_op["end"] - v_op["begin"],
+ "pid": root_idx,
+ "tid": wid,
+ "args": {
+ "Start timestamp": v_op["begin"],
+ "End timestamp": v_op["end"]
+ }
+ })
+
+ if stop_display(display, "operator") or "children" not in v_op:
+ continue
+ for idx, (k_gpu_op, v_gpu_op) in \
+ enumerate(sorted(v_op["children"].items(),
+ key=lambda e: e[1]["begin"])):
+ # kernel scopes
+ if idx == 0:
+ ct.append({
+ "name": v_op["desc"] + "-GPU",
+ "ph": "X",
+ "ts": v_gpu_op["begin"],
+ "dur": v_gpu_op["end"] - v_gpu_op["begin"],
+ "pid": root_idx,
+ "tid": wid,
+ "args": {
+ "desc": "NEW OPERATOR",
+ "Start timestamp": v_gpu_op["begin"],
+ "End timestamp": v_gpu_op["end"]
+ }
+ })
+
+ ct.append({
+ "name": v_op["desc"] + "-GPU",
+ "ph": "i",
+ "ts": v_gpu_op["begin"],
+ "pid": root_idx,
+ "tid": wid,
+ "args": {
+ "desc": v_gpu_op["desc"]
+ }
+ })
+
+ return ct
+
+
+def get_argument_parser():
+ parser = argparse.ArgumentParser(
+ description="Format conversion from HTrace to Chrome tracing.")
+ parser.add_argument("htrace_log", type=str, help="input htrace span log file")
+ parser.add_argument("--display",
+ type=str, choices=display_levels, default="operator",
+ help="deepest level of spans to display (default: operator)")
+ parser.add_argument("--start_time", type=int, default=-1,
+ help="do not display spans occuring before this timestamp")
+ parser.add_argument("--end_time", type=int, default=sys.maxsize,
+ help="do not display spans occuring after this timestamp")
+ return parser
+
+
+def main():
+ args = get_argument_parser().parse_args()
+ with open(args.htrace_log, "r") as f:
+ trace_dic, root_list = build_trace_dict(f, args.start_time, args.end_time)
+
+ ct = generate_chrome_trace(root_list, args.display)
+ print("Writing chrome json file to %s.json" % args.htrace_log)
+ print("Now import %s.json in chrome://tracing" % args.htrace_log)
+ with open(args.htrace_log + ".json", "w") as f:
+ f.write(json.dumps(ct))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0086485_units.py b/pool/shard009/Python/0086485_units.py
new file mode 100644
index 0000000000000000000000000000000000000000..4acce46aedfe2d97cdd9dbc641f87e557cebf361
--- /dev/null
+++ b/pool/shard009/Python/0086485_units.py
@@ -0,0 +1,83 @@
+from __future__ import absolute_import
+from __future__ import print_function
+
+from math import pi as PI
+
+class UnitSet(object):
+ def __init__(self, name, common_unit, entries):
+ self.name = name
+ self.common_unit = ''
+ self.entries = entries
+
+ def __contains__(self, unit):
+ return unit in self.entries
+
+ def __getitem__(self, unit):
+ return self.entries[unit]
+
+
+class UnitSetEntry(object):
+ def __init__(self, unit, conv):
+ self.unit = unit
+ self.conv = conv
+
+ def to_common(self, value):
+ return value * self.conv
+
+ def from_common(self, value):
+ return value / self.conv
+
+
+_unitsets = (
+ ('lengths', ('px', (
+ ('px', 1.0),
+ ('cm', 37.79527559), # 1 cm -> 37.79527559 px
+ ('mm', 3.779527559), # 1 mm -> 3.779527559 px
+ ('in', 96.), # 1 in -> 96 px
+ ('pt', 4./3.), # 1 pt -> 1.3333... px
+ ('pc', 16.), # 1 pc -> 16 px
+ ))),
+ ('angles', ('rad', (
+ ('rad', 1.0),
+ ('deg', (2.*PI)/360.),
+ ('grad', (2.*PI)/400.),
+ ('turn', (2.*PI)/1.),
+ ))),
+ ('times', ('s', (
+ ('s', 1.0),
+ ('ms', 1./1000.),
+ ))),
+ ('ems', ('em', (('em', 1.0),))),
+ ('exs', ('ex', (('ex', 1.0),))),
+ ('chs', ('ch', (('ch', 1.0),))),
+ ('rems', ('rem', (('rem', 1.0),))),
+ ('vws', ('vw', (('vw', 1.0),))),
+ ('vhs', ('vh', (('vh', 1.0),))),
+ ('vmins', ('vmin', (('vmin', 1.0),))),
+ ('freqs', ('hz', (
+ ('hz', 1.0),
+ ('khz', 1000.),
+ ))),
+ ('resolutions', ('dppx', (
+ ('dppx', 1.0),
+ ('dpcm', 1./37.79527559),
+ ('dpi', 1./96.),
+ ))),
+)
+
+def _make_unitset(name, unitset):
+ common, unitinfos = unitset
+ entries = dict((unit, UnitSetEntry(unit, conv)) for unit, conv in unitinfos)
+ return UnitSet(name, common, entries)
+
+unitsets = {}
+
+for _name, _unitset in _unitsets:
+ unitsets[_name] = _make_unitset(_name, _unitset)
+
+unitset_lookup = {}
+
+for _unitset in unitsets.itervalues():
+ for _unitname in _unitset.entries:
+ unitset_lookup[_unitname] = _unitset
+
diff --git a/pool/shard009/Python/0086486_cli_server.py b/pool/shard009/Python/0086486_cli_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cfe8b5dd6dd8064e40a1eb20f11a8e6a38f0269
--- /dev/null
+++ b/pool/shard009/Python/0086486_cli_server.py
@@ -0,0 +1,29 @@
+import argparse
+import logging
+
+from gpopup import notifier
+from gpopup.utils import get_app_logger
+
+DEBUG = True
+logger = get_app_logger(debug=DEBUG)
+
+
+def server_parser():
+ parser = argparse.ArgumentParser(description='GPopupServer Server.')
+ parser.add_argument('--force-bind', action='store_true')
+ parser.add_argument('--background', action='store_true')
+ return parser
+
+
+def main(args=None):
+ parser = server_parser()
+ args = parser.parse_args(args=args)
+ logger.debug('force_bind = {}'.format(args.force_bind))
+ serv = notifier.NotifierServer(force_bind=args.force_bind)
+ try:
+ serv.run(background=args.background)
+ except KeyboardInterrupt:
+ print('Got keyboard quit.', flush=True)
+ # http://tldp.org/LDP/abs/html/exitcodes.html
+ return 130
+ return 0
diff --git a/pool/shard009/Python/0086489_MachineWarehouse.py b/pool/shard009/Python/0086489_MachineWarehouse.py
new file mode 100644
index 0000000000000000000000000000000000000000..08d2fed509bb98f1a7db3c213dfd663f2335a7f6
--- /dev/null
+++ b/pool/shard009/Python/0086489_MachineWarehouse.py
@@ -0,0 +1,215 @@
+# Load the required modules
+import os, sys, subprocess, socket, multiprocessing
+from random import shuffle
+from sets import Set
+
+# Import the Machine and DmakeRC class
+from Machine import *
+
+## Helper function for creating machine objects, this is required to be outside
+# of the class to allow the use of running the object creation in parallel
+# @param line A string of comma sperated values containing one line of machine information from server
+# @return A Machine object generated from the given input
+def createMachine(line):
+ if len(line) == 0:
+ return
+ return Machine(*line)
+
+## @class MachineWarehouse
+# Creates and controls the local and worker Machine objects, it mainly provides the
+# getHosts() method that returns the needed DISTCC_HOSTS environmental variable for
+# use with 'make'
+# @see Machine MachineWarehouse::getHosts
+class MachineWarehouse(object):
+
+
+ ## Class constructor
+ #
+ # Optional Arguments:
+ # allow = list - list of ip addresses/hostnames to allow in DISTCC_HOSTS
+ # restrict = list -
+ # allow_off_network = True | {False} - if true, the above restrictions are ignored
+ #
+ # @see DmakeRC
+ def __init__(self, master, **kwargs):
+
+ # Set default values for public/private members
+ self.machines = [] # all machines
+ self.available = [] # machines that are available
+ self.down = [] # machines that are not available
+
+ # Build the master machine
+ self.master = master
+
+
+ ## Return the hosts line and number of jobs (public)
+ # @param kwargs Optional keyword/value pairings
+ # @return DISTCC_HOSTS
+ # @return jobs
+ #
+ # Optional Arguments (used by getHosts() directly):
+ # jobs = - Custom, user-defined jobs number
+ #
+ # Optional Arguments (passed to buildMachines or _buildHosts):
+ # jobs = - Custom, user-defined jobs number
+ # max = True | {False} - Run the maximum no. of threads (passed to _buildHosts)
+ # localhost = - Set the DISTCC_HOSTS localhost value (passed to _buildHosts)
+ # localslots = - Set the DISTCC_HOSTS localslots value (passed to _buildHosts)
+ # Number of jobs that cannot be run remotely that can be run concurrently
+ # on the local machine
+ # localslots_cpp = - Set the DISTCC_HOSTS localslots_cpp value (passed to _buildHosts)
+ # How many preprocessors will run in parallel on the local machine
+ # disable = list() - list of machines to disable
+ # serial = True | {False} - toggle the parallel creation of the Machine objects
+ # hammer = list() - list of machines to set to max
+ #
+ # @see _buildHosts
+ def getHosts(self, host_lines, **kwargs):
+
+ # Get the optional parameters needed by getHosts
+ jobs = kwargs.get("jobs", None)
+
+ # Buld the Machine objects
+ self.buildMachines(host_lines, disable=kwargs.pop('disable', None), serial=kwargs.pop("serial", False), hammer=kwargs.pop('hammer', None))
+
+ # Buld the hosts lines (return distcc_hosts and jobs)
+ return self._buildHosts(**kwargs)
+
+
+ ## Build the remote Machine objects (public)
+ # @param host_lines Raw host line data from server or .dmakerc
+ # @param disable A list of machines to disable
+ #
+ # Reads the list of machines from the host_lines from the server and
+ # build the Machine objects (in parallel)
+ #
+ # Optional Arguments:
+ # serial = True | {False} - toggle the parallel creation of the Machine objects
+ # disable = list() - a list of machines to disables
+ # @see createMachine Machine
+ def buildMachines(self, host_lines, **kwargs):
+
+ # Return if the workers are already built
+ if len(self.available) > 0:
+ return
+
+ # Handle empty host lines
+ if host_lines == None or len(host_lines) == 0:
+ return
+
+ # Get the disable list and hammer list
+ disable = kwargs.pop('disable', None)
+ hammer = kwargs.pop('hammer', None)
+
+ # Create the Machine objects (in parallel)
+ output = []
+ if not kwargs.pop("serial", False):
+ pool = multiprocessing.Pool(processes=self.master.threads)
+ output = pool.map(createMachine, host_lines)
+ pool.close()
+ pool.join()
+
+ # Create the Machine objects serially
+ else:
+ for line in host_lines:
+ output.append(createMachine(line))
+ output[-1].info()
+
+ # Check the disabled list against the address and ip, the user is allowed to
+ # supply partial ip/hostnames so loop through each and test that the substring
+ # is not contained in either
+ for machine in output:
+ if hammer != None:
+ for h in hammer:
+ if machine.available and ((h in machine.address) or (h in machine.hostname) or (h in machine.username)):
+ machine.status = 'hammer'
+ machine.use_threads = machine.threads
+ break
+
+ if disable != None:
+ for d in disable:
+ if (d in machine.address) or (d in machine.hostname) or (d in machine.username):
+ machine.status = 'disabled'
+ machine.available = False
+ break
+
+ # Populate the two lists of machines
+ for machine in output:
+
+ # A list of all machines
+ self.machines.append(machine)
+
+ # Available machines
+ if machine.available:
+ self.available.append(machine)
+
+ # Unavailable machines
+ else:
+ self.down.append(machine)
+
+
+ ## Update the DISTCC_HOSTS enviornmental variable (private)
+ # @param kwargs Optional keyword/value pairings
+ #
+ # Optional Arguments:
+ # max = True | {False} - Run the maximum no. of threads
+ # localhost = - Set the DISTCC_HOSTS localhost value
+ # localslots = - Set the DISTCC_HOSTS localslots value
+ # localslots_cpp = - Set the DISTCC_HOSTS localslots_cpp value
+ # jobs = - Custom, user-defined jobs number
+ def _buildHosts(self, **kwargs):
+
+ # Extract the custom options
+ has_jobs = kwargs.has_key('jobs')
+ use_max = kwargs.pop('max', False)
+ localhost = kwargs.pop('localhost', None)
+ localslots = kwargs.pop('localslots', None)
+ localslots_cpp = kwargs.pop('localslots_cpp', None)
+
+ # Randomize the workers
+ shuffle(self.available)
+
+ # Create the distcc_hosts and jobs output
+ jobs = 0
+ distcc_hosts = ''
+ for machine in self.available:
+ if use_max:
+ distcc_hosts += " " + machine.hostname + '/' + str(machine.threads)
+ jobs += int(machine.threads)
+ elif machine.use_threads != 0:
+ distcc_hosts += " " + machine.hostname + '/' + str(machine.use_threads)
+ jobs += machine.use_threads
+
+ # Get the default or user-defined values for localhost/localslots_cpp/localslots
+ if localhost == None:
+ # If the number of local threads is greater than the number of available remote
+ # jobs utilize the difference for local compiling. Do not allow the use of less
+ # than 2.
+ localhost = max(2, self.master.threads - jobs)
+
+ if localslots == None:
+ localslots = localhost
+
+ if localslots_cpp == None:
+ localslots_cpp = self.master.threads - localhost
+
+ # Create the DISTCC_HOSTS variable
+ if jobs == 0:
+ localhost = self.master.threads
+ distcc_hosts = 'localhost/' + str(int(localhost))
+
+ else:
+ distcc_hosts = '--localslots=' + str(int(localslots)) + ' --localslots_cpp=' + \
+ str(int(localslots_cpp)) + ' localhost/' + str(int(localhost)) + \
+ distcc_hosts
+
+ # Add the local machine to the jobs total
+ jobs += int(localhost)
+
+ # Get the jobs
+ jobs = kwargs.pop('jobs', jobs)
+ if not use_max and jobs > 70 and not has_jobs:
+ jobs = 70
+
+ # Return the values
+ return distcc_hosts, jobs
diff --git a/pool/shard009/Python/0086495_test_couchbase.py b/pool/shard009/Python/0086495_test_couchbase.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4ad10cf49c333d6c60c89e1b5c49e2a16de7339
--- /dev/null
+++ b/pool/shard009/Python/0086495_test_couchbase.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python
+"""
+Unit test for the Couchbase collectd plugin. Meant to be run with pytest.
+"""
+# Copyright (C) 2016 SignalFx, Inc.
+
+import collections
+import mock
+import sys
+import pytest
+
+import sample_responses
+
+
+class MockCollectd(mock.MagicMock):
+ """
+ Mocks the functions and objects provided by the collectd module
+ """
+
+ @staticmethod
+ def log(log_str):
+ print log_str
+
+ debug = log
+ info = log
+ warning = log
+ error = log
+
+
+def mock_api_call(url, opener):
+ """
+ Returns example statistics from the sample_responses module.
+
+ Args:
+ :param url: (str) The URL whose results to mock
+ """
+ key = ''
+ parsed_url = url.split('/')
+
+ if parsed_url[-2] == 'pools' and parsed_url[-1] == 'default':
+ key = 'node'
+
+ if parsed_url[-2] == 'buckets' and parsed_url[-1] == 'default':
+ key = 'bucket'
+
+ if parsed_url[-1] == 'stats':
+ key = 'bucket_stat'
+
+ return getattr(sample_responses, key)
+
+
+sys.modules['collectd'] = MockCollectd()
+import couchbase
+
+ConfigOption = collections.namedtuple('ConfigOption', ['key', 'values'])
+
+fail_mock_config_required_params = mock.Mock()
+fail_mock_config_required_params.children = [
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', (8091,)),
+ ConfigOption('CollectMode', ('default',)),
+ ConfigOption('Interval', (10,)),
+]
+
+fail_mock_config_required_params_for_bucket = mock.Mock()
+fail_mock_config_required_params_for_bucket.children = [
+ ConfigOption('CollectTarget', ('BUCKET',)),
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', ('8091',)),
+ ConfigOption('CollectMode', ('default',)),
+ ConfigOption('Interval', ('10',)),
+]
+
+fail_mock_config_unsupported_collect_target = mock.Mock()
+fail_mock_config_unsupported_collect_target.children = [
+ ConfigOption('CollectTarget', ('OTHER',)),
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', ('8091',)),
+ ConfigOption('CollectMode', ('default',)),
+ ConfigOption('Interval', ('10',)),
+]
+
+mock_config_nodes = mock.Mock()
+mock_config_nodes.children = [
+ ConfigOption('CollectTarget', ('NODE',)),
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', ('8091',)),
+ ConfigOption('CollectMode', ('detailed',)),
+ ConfigOption('Interval', ('10',)),
+ ConfigOption('FieldLength', ('1024',)),
+]
+
+mock_config_bucket = mock.Mock()
+mock_config_bucket.children = [
+ ConfigOption('CollectTarget', ('BUCKET',)),
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', ('8091',)),
+ ConfigOption('Username', ('username',)),
+ ConfigOption('Password', ('password',)),
+ ConfigOption('CollectBucket', ('default',)),
+ ConfigOption('CollectMode', ('detailed',)),
+ ConfigOption('Interval', ('10',)),
+]
+
+mock_config_field_length = mock.Mock()
+mock_config_field_length.children = [
+ ConfigOption('CollectTarget', ('BUCKET',)),
+ ConfigOption('Host', ('localhost',)),
+ ConfigOption('Port', ('8091',)),
+ ConfigOption('Username', ('username',)),
+ ConfigOption('Password', ('password',)),
+ ConfigOption('CollectBucket', ('default',)),
+ ConfigOption('CollectMode', ('detailed',)),
+ ConfigOption('Interval', ('10',)),
+ ConfigOption('FieldLength', ('1024',)),
+]
+
+
+def test_config_node():
+ """
+ Check read params from config
+ """
+
+ couchbase.config(mock_config_nodes)
+ assert couchbase.CONFIGS[0]['plugin_config']['CollectTarget'] == 'NODE'
+ assert couchbase.CONFIGS[0]['plugin_config']['Host'] == 'localhost'
+ assert couchbase.CONFIGS[0]['plugin_config']['Port'] == '8091'
+ assert couchbase.CONFIGS[0]['collect_mode'] == 'detailed'
+ assert couchbase.CONFIGS[0]['interval'] == '10'
+ assert couchbase.CONFIGS[0]['collect_bucket'] is None
+ assert couchbase.CONFIGS[0]['username'] == ''
+ assert couchbase.CONFIGS[0]['password'] == ''
+
+ assert couchbase.CONFIGS[0]['api_urls']['node'] is not None
+
+ couchbase.CONFIGS = []
+
+
+def test_config_bucket():
+ """
+ Check read params from config included bucket configuration
+ """
+
+ couchbase.config(mock_config_bucket)
+ assert couchbase.CONFIGS[0]['plugin_config']['CollectTarget'] == 'BUCKET'
+ assert couchbase.CONFIGS[0]['plugin_config']['Host'] == 'localhost'
+ assert couchbase.CONFIGS[0]['plugin_config']['Port'] == '8091'
+ assert couchbase.CONFIGS[0]['collect_mode'] == 'detailed'
+ assert couchbase.CONFIGS[0]['interval'] == '10'
+ assert couchbase.CONFIGS[0]['collect_bucket'] == 'default'
+ assert couchbase.CONFIGS[0]['username'] == 'username'
+ assert couchbase.CONFIGS[0]['password'] == 'password'
+
+ assert couchbase.CONFIGS[0]['api_urls']['bucket'] is not None
+ assert couchbase.CONFIGS[0]['api_urls']['bucket_stat'] is not None
+ couchbase.CONFIGS = []
+
+
+def test_config_field_length():
+ """
+ Check read params from config included bucket configuration
+ """
+
+ couchbase.config(mock_config_field_length)
+ assert couchbase.CONFIGS[0]['plugin_config']['CollectTarget'] == 'BUCKET'
+ assert couchbase.CONFIGS[0]['plugin_config']['Host'] == 'localhost'
+ assert couchbase.CONFIGS[0]['plugin_config']['Port'] == '8091'
+ assert couchbase.CONFIGS[0]['collect_mode'] == 'detailed'
+ assert couchbase.CONFIGS[0]['interval'] == '10'
+ assert couchbase.CONFIGS[0]['collect_bucket'] == 'default'
+ assert couchbase.CONFIGS[0]['username'] == 'username'
+ assert couchbase.CONFIGS[0]['password'] == 'password'
+
+ assert couchbase.CONFIGS[0]['field_length'] == 1024
+
+ couchbase.CONFIGS = []
+
+
+def test_config_nodes_fail():
+ """
+ Check for exception when required params are not specified
+ """
+ with pytest.raises(ValueError):
+ couchbase.config(fail_mock_config_required_params)
+
+ couchbase.CONFIGS = []
+
+
+def test_config_unsupported_collect_target_fail():
+ """
+ Check for exception when required params are not specified
+ """
+ with pytest.raises(ValueError):
+ couchbase.config(fail_mock_config_unsupported_collect_target)
+
+ couchbase.CONFIGS = []
+
+
+def test_config_bucket_fail():
+ """
+ Check for exception when bucket name param (CollectBucket)
+ are not specified
+ """
+ with pytest.raises(ValueError):
+ couchbase.config(fail_mock_config_required_params_for_bucket)
+
+ couchbase.CONFIGS = []
+
+
+@mock.patch('couchbase._api_call', mock_api_call)
+def test_read():
+ """
+ Tests the read() method of the collectd plugin. This codepath exercises
+ most of the code in the plugin.
+ """
+ couchbase.config(mock_config_nodes)
+ couchbase.config(mock_config_bucket)
+ couchbase.read()
diff --git a/pool/shard009/Python/0086498_mod.py b/pool/shard009/Python/0086498_mod.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ce8b4d416582f251a37837566413260da76f1dd
--- /dev/null
+++ b/pool/shard009/Python/0086498_mod.py
@@ -0,0 +1,133 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2017 Ricequant, 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.
+
+import copy
+
+import numpy as np
+
+from rqalpha.interface import AbstractMod
+from rqalpha.environment import Environment
+from rqalpha.events import EVENT
+
+
+class FuncatAPIMod(AbstractMod):
+ def start_up(self, env, mod_config):
+ try:
+ import funcat
+ except ImportError:
+ print("-" * 50)
+ print(">>> Missing funcat. Please run `pip install funcat`")
+ print("-" * 50)
+ raise
+
+ from funcat.data.backend import DataBackend
+ from funcat.context import set_current_date
+
+ class RQAlphaDataBackend(DataBackend):
+ """
+ 目前仅支持日数据
+ """
+ skip_suspended = False
+
+ def __init__(self):
+ from rqalpha.api import (
+ history_bars,
+ all_instruments,
+ instruments,
+ )
+
+ self.set_current_date = set_current_date
+
+ self.history_bars = history_bars
+ self.all_instruments = all_instruments
+ self.instruments = instruments
+ self.rqalpha_env = Environment.get_instance()
+
+ self.rqalpha_env.event_bus.add_listener(EVENT.PRE_BEFORE_TRADING, self._pre_before_trading)
+ self.rqalpha_env.event_bus.add_listener(EVENT.PRE_BAR, self._pre_handle_bar)
+
+ def _pre_before_trading(self, *args, **kwargs):
+ calendar_date = self.rqalpha_env.calendar_dt.date()
+ self.set_current_date(calendar_date)
+
+ def _pre_handle_bar(self, *args, **kwargs):
+ calendar_date = self.rqalpha_env.calendar_dt.date()
+ self.set_current_date(calendar_date)
+
+ def get_price(self, order_book_id, start, end):
+ """
+ :param order_book_id: e.g. 000002.XSHE
+ :param start: 20160101
+ :param end: 20160201
+ :returns:
+ :rtype: numpy.rec.array
+ """
+ # start = get_date_from_int(start)
+ # end = get_date_from_int(end)
+ # bar_count = (end - start).days
+
+ # TODO: this is slow, make it run faster
+ bar_count = 1000
+ origin_bars = bars = self.history_bars(order_book_id, bar_count, "1d")
+
+ dtype = copy.deepcopy(bars.dtype)
+ names = list(dtype.names)
+ names[0] = "date"
+ dtype.names = names
+ bars = np.array(bars, dtype=dtype)
+
+ bars["date"] = origin_bars["datetime"] / 1000000
+
+ return bars
+
+ def get_order_book_id_list(self):
+ """获取所有的
+ """
+ return sorted(self.all_instruments("CS").order_book_id.tolist())
+
+ def get_trading_dates(self, start, end):
+ """获取所有的交易日
+
+ :param start: 20160101
+ :param end: 20160201
+ """
+ raise NotImplementedError
+
+ def get_start_date(self):
+ """获取回溯开始时间
+ """
+ return str(self.rqalpha_env.config.base.start_date)
+
+ def symbol(self, order_book_id):
+ """获取order_book_id对应的名字
+ :param order_book_id str: 股票代码
+ :returns: 名字
+ :rtype: str
+ """
+ return self.instruments(order_book_id).symbol
+
+ # change funcat data backend to rqalpha
+ funcat.set_data_backend(RQAlphaDataBackend())
+
+ # register funcat api into rqalpha
+ from rqalpha.api.api_base import register_api
+ for name in dir(funcat):
+ obj = getattr(funcat, name)
+ if getattr(obj, "__module__", "").startswith("funcat"):
+ register_api(name, obj)
+
+ def tear_down(self, code, exception=None):
+ pass
diff --git a/pool/shard009/Python/0086507_setup.py b/pool/shard009/Python/0086507_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7223a0597530014b430864bafda22af45ec3631
--- /dev/null
+++ b/pool/shard009/Python/0086507_setup.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+from __future__ import division, print_function, absolute_import
+
+from setuptools import setup
+import os
+
+if os.getenv('READTHEDOCS'):
+ with open('requirements_docs.txt') as f:
+ required = f.read().splitlines()
+else:
+ with open('requirements.txt') as f:
+ required = f.read().splitlines()
+
+CLASSIFIERS = [
+ 'Development Status :: 4 - Beta',
+ 'Intended Audience :: Science/Research',
+ 'License :: OSI Approved :: BSD License',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
+ 'Topic :: Scientific/Engineering',
+]
+
+args = dict(
+ name='autocolorize',
+ version='0.2.1',
+ url="https://github.com/gustavla/autocolorize",
+ description="Automatic colorizaton of grayscale images using Deep Learning.",
+ maintainer='Gustav Larsson',
+ maintainer_email='gustav.m.larsson@gmail.com',
+ install_requires=required,
+ scripts=['scripts/autocolorize'],
+ packages=[
+ 'autocolorize',
+ 'autocolorize.res',
+ ],
+ package_data={'autocolorize.res': ['autocolorize.prototxt.template']},
+ license='BSD',
+ classifiers=CLASSIFIERS,
+)
+
+setup(**args)
diff --git a/pool/shard009/Python/0086509_test_image.py b/pool/shard009/Python/0086509_test_image.py
new file mode 100644
index 0000000000000000000000000000000000000000..b837e2010b0b4f404c3103ca44588638884e6d96
--- /dev/null
+++ b/pool/shard009/Python/0086509_test_image.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+# Standard Library
+from os.path import abspath, dirname, join, normpath
+from unittest import TestCase
+
+# HTML2LaTeX Stuff
+from html2latex.utils.image import get_image_size
+
+CURRENT_DIR = dirname(abspath(__file__))
+IMAGE_FILE_ROOT = normpath(join(CURRENT_DIR, 'images'))
+image_file_path = normpath(join(IMAGE_FILE_ROOT, "india_map.jpg"))
+
+
+class TestUtilsText(TestCase):
+
+ def test_get_image_size(self):
+ self.assertEqual(
+ (501, 557), get_image_size(image_file_path))
diff --git a/pool/shard009/Python/0086511_timers2.py b/pool/shard009/Python/0086511_timers2.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6967d0307825097d4849c73602f347e709dfb52
--- /dev/null
+++ b/pool/shard009/Python/0086511_timers2.py
@@ -0,0 +1,108 @@
+import matplotlib.pyplot
+import scipy
+import colorsys
+import json
+import sys
+import os
+import copy
+
+matplotlib.pyplot.figure(1, figsize=(14,14))
+
+fname = os.path.splitext(os.path.basename(sys.argv[1]))[0]
+
+fin = open(sys.argv[1], "r")
+jin = json.load(fin)
+fin.close()
+
+# 4 timer values are: total, min, max, average
+timer_groups = [
+[
+ "sirius::Global::generate_radial_functions",
+ "sirius::Global::generate_radial_integrals",
+ "sirius::K_set::find_eigen_states",
+ "sirius::Density::generate",
+ "sirius::Potential::generate_effective_potential",
+ "exciting::sym_rho_mag",
+ "exciting::mixer"
+],
+[
+ "sirius::Band::set_fv_h_o",
+ "sirius::Band::solve_fv_evp",
+ "sirius::K_point::generate_fv_states",
+ "sirius::Band::solve_sv",
+ "sirius::K_point::generate_spinor_wave_functions"
+],
+[
+ "sirius::Potential::poisson",
+ "sirius::Potential::xc"
+],
+[
+ "sirius::Reciprocal_lattice::init",
+ "sirius::Step_function::init",
+ "sirius::Unit_cell::get_symmetry",
+ "sirius::Unit_cell::find_nearest_neighbours",
+ "sirius::K_point::initialize",
+ "sirius::Potential::Potential",
+ "sirius::Atom_type::solve_free_atom"
+]
+]
+
+for itg in range(len(timer_groups)):
+
+ timer_names = []
+ timer_values = []
+ total_time = 0.0
+ for timer_name in timer_groups[itg]:
+
+ if timer_name in jin["timers"]:
+
+ tname = timer_name
+
+ # effective potential is generated once before the scf loop
+ # the first timer is reported in percentage
+ if itg == 0:
+ if timer_name == "sirius::Potential::generate_effective_potential":
+ # (total - average) of effective potential / total of iterations
+ t = (jin["timers"][timer_name][0] - jin["timers"][timer_name][3]) / jin["timers"]["exciting::iteration"][0]
+ else:
+ t = jin["timers"][timer_name][0] / jin["timers"]["exciting::iteration"][0]
+ t = t * 100
+ # show average time in legend
+ timer_names.append(tname + " (%6.2f%%, %6.2f sec./call)"%(t, jin["timers"][timer_name][3]))
+ # show total time for intialization routines
+ elif itg == 3:
+ t = jin["timers"][timer_name][0]
+ timer_names.append(tname + " (%6.2f sec.)"%t)
+ # show average time
+ else:
+ t = jin["timers"][timer_name][3]
+ timer_names.append(tname + " (%6.2f sec./call)"%t)
+
+ timer_values.append(t)
+ total_time += t
+
+ print "total time for timer group ", itg, " ", total_time
+
+ plot = matplotlib.pyplot.subplot("41%i"%(itg+1))
+ box = plot.get_position()
+ plot.set_position([box.x0, box.y0, box.width * 0.1, box.height])
+ box = plot.get_position()
+
+ ytics = [0]
+ for i in range(len(timer_values)):
+ ytics.append(ytics[i] + timer_values[i])
+
+ plots = []
+ for i in range(len(timer_values)):
+ rgb = colorsys.hsv_to_rgb(i / float(len(timer_values)), 0.75, 0.95)
+ c = "#%X%X%X"%(rgb[0]*255, rgb[1]*255, rgb[2]*255)
+ plots.append(matplotlib.pyplot.bar(0, timer_values[i], 2, bottom=ytics[i], color=c))
+
+ matplotlib.pyplot.xticks([], ())
+ matplotlib.pyplot.yticks(ytics)
+ matplotlib.pyplot.ylim([0, ytics[len(ytics)-1]])
+
+ matplotlib.pyplot.legend(plots[::-1], timer_names[::-1], bbox_to_anchor=(1.2, 1), loc=2)
+
+matplotlib.pyplot.savefig(fname+".pdf", format="pdf")
+
diff --git a/pool/shard009/Python/0086514_predict.py b/pool/shard009/Python/0086514_predict.py
new file mode 100644
index 0000000000000000000000000000000000000000..6520d8c5c6e92d7c0c7498242fc92630c0c4a0d0
--- /dev/null
+++ b/pool/shard009/Python/0086514_predict.py
@@ -0,0 +1,33 @@
+import configparser
+import os
+
+import pressagio.callback
+import pressagio
+
+SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
+
+# Define and create PresageCallback object
+class DemoCallback(pressagio.callback.Callback):
+ def __init__(self, buffer):
+ super().__init__()
+ self.buffer = buffer
+
+ def past_stream(self):
+ return self.buffer
+
+ def future_stream(self):
+ return ""
+
+
+config_file = os.path.join(SCRIPT_DIR, "example_profile.ini")
+
+
+config = configparser.ConfigParser()
+config.read(config_file)
+
+
+callback = DemoCallback("der Saal war bereits ")
+prsgio = pressagio.Pressagio(callback, config)
+
+predictions = prsgio.predict()
+print(predictions)
diff --git a/pool/shard009/Python/0086515_thread.py b/pool/shard009/Python/0086515_thread.py
new file mode 100644
index 0000000000000000000000000000000000000000..1216510f06846187ec2c36e2c66ddc29c2a13123
--- /dev/null
+++ b/pool/shard009/Python/0086515_thread.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+
+import csv
+import json
+import datetime
+import urllib
+from collections import Counter
+
+import requests
+from bs4 import BeautifulSoup
+
+from .post import Post
+
+
+class TrashException(Exception):
+ pass
+
+
+class AuthException(Exception):
+ pass
+
+
+class LoginException(Exception):
+ pass
+
+
+class NotFoundException(Exception):
+ pass
+
+
+errors = [
+ ((u'Denna tråd har flyttats till "Papperskorgen". '
+ u'Ett delforum för trådar med för låg kvalitet.'),
+ TrashException('Login required for threads in trashcan.')),
+ ((u'du har inte behörighet till den här sidan. '
+ u'Det kan bero på en av flera anledningar:'),
+ AuthException('Your account lacks sufficient permissions.')),
+ ((u'Du är inte inloggad eller också har du inte behörighet'
+ u' att se den här sidan. Det kan bero på en av flera'),
+ LoginException('Login required for this particular thread.')),
+ ((u'Du angav ett ogiltigt Ämne. Om du följde en giltig'
+ u' länk, var vänlig och kontakta den'),
+ NotFoundException('Thread does not exist.')),
+ ((u'Inget Ämne specifierat. Om du följde en giltig'
+ u' länk var vänlig och meddela den'),
+ NotFoundException('Thread does not exist.')),
+]
+
+
+class Thread():
+ """Temp"""
+ def __init__(self, base_url):
+ self.base_url = base_url
+ self.posts = []
+
+ def get(self, requests=requests):
+ r = requests.get(self.base_url)
+ self.start = BeautifulSoup(r.text, 'html.parser')
+
+ for message, thread_exception in errors:
+ if message in self.start.text:
+ raise thread_exception
+
+ self.append_page(self.start)
+ page_count = self._get_page_count(self.start)
+
+ for page in range(2, page_count + 1):
+ slug = 'p{page}'.format(page=str(page))
+ url = ''.join([self.base_url, slug])
+ r = requests.get(url)
+ soup = BeautifulSoup(r.text, 'html.parser')
+ self.append_page(soup)
+
+ def append_page(self, soup):
+ for div in soup.select('#posts > div')[:-1]:
+ self.append_post(div)
+
+ def append_post(self, soup):
+ post = Post(soup)
+ self.posts.append(post)
+
+ def describe(self):
+ counter = Counter([x['user_name'] for x in self.posts])
+ common_authors = counter.most_common(5)
+ return {
+ 'common_authors': common_authors
+ }
+
+ @property
+ def title(self):
+ """Title of thread"""
+ return self.start.title.text[0:-18]
+
+ @property
+ def section(self):
+ navbar = self.start.find('table', {'class': 'forum-navbar'})
+ breadcrumbs = navbar.find('tr', {'valign': 'bottom'}).find_all('a')
+ section = breadcrumbs[-1]
+ return {'id': section['href'][1:], 'name': section.text}
+
+ def _get_page_count(self, soup):
+ """Finds the number of pages for the given thread
+
+ """
+ element = soup.select_one('td.vbmenu_control.smallfont2.delim')
+ if element:
+ page_count = element.text.split(' ')[-1]
+ return int(page_count)
+ return 1
+
+ def to_csv(self, fname):
+ """Saves the posts to a CSV file"""
+ with open(fname, 'w') as csvfile:
+ headers = ['id', 'user_name', 'time', 'content']
+ writer = csv.DictWriter(csvfile, fieldnames=headers)
+ writer.writeheader()
+
+ for p in self.posts:
+ row = {'id': p.id.encode('utf-8'),
+ 'user_name': p.user_name.encode('utf-8'),
+ 'time': p.timestamp.encode('utf-8'),
+ 'content': p.content.encode('utf-8')}
+ writer.writerow(row)
+
+ def to_json(self, fname):
+ """Saves the posts to a JSON file"""
+ out = {
+ 'title': self.title,
+ 'posts': self.posts
+ }
+
+ with open(fname, 'w') as f:
+ f.write(json.dumps(out))
+
+ def __getitem__(self, index):
+ return self.posts[index]
+
+ def __len__(self):
+ return len(self.posts)
+
+ def __repr__(self):
+ return ''.format(self.base_url)
+
+ def __iter__(self):
+ return iter(self.posts)
diff --git a/pool/shard009/Python/0086517_jagli.py b/pool/shard009/Python/0086517_jagli.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b6570bb8d3c35fdcef134305cd26b7af71717db
--- /dev/null
+++ b/pool/shard009/Python/0086517_jagli.py
@@ -0,0 +1,128 @@
+import os
+import argparse
+
+from jaglk import *
+from jaglt import *
+import jaglf
+
+def runOn(tokens, stack):
+ for tok in tokens:
+ if isinstance(tok, JFunc):
+ f = jaglf.FUNCTIONS[tok.v]
+ stack = f(stack)
+ else:
+ stack.push(tok)
+ return stack
+
+def runCode(code):
+ tokens = tokenize(code)
+ s = Stack()
+ return runOn(tokens, s)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="JAGL (Just A Golfing Language) Interpreter")
+ parser.add_argument('filename', help='filename', nargs='?', default=None)
+ parser.add_argument('-v', '--version', action='version', version='%(prog)s Alpha V1.3 Released Jan 2/2015')
+ parser.add_argument('-i', '--inter', action='store_true', help='run the interactive interpreter')
+ parser.add_argument('-c', '--code', help='execute code from the command line')
+ parser.add_argument('-C', '--changelog',action='store_true', help='print changelog')
+ args = parser.parse_args()
+
+ if args.changelog:
+ print """
+ Changelog:
+
+ Version 1.3:
+ Added:
+ 1) Additional functionality was added to 'n' when operating on arrays
+ 2) 'z' - Now performs a zipWith, using a temporary stack
+ 3) 'G' - Now encases the stack in an array
+ 4) Short circuit syntax (see documentation)
+
+ Changed:
+ 1) The conditional value in if and ifelse is now the leftmost argument
+ 2) The conditional drop ('I') is now built into 'f'
+ 3) 'R', when operating with arrays, no longer consumes the array
+ 4) 'k' and 'K' replace 'z' and 'Z' respectively
+ 5) 'q' (min) and 'Q' (max) are now 'm', and 'M' respectively
+ 6) 'I' now functions as 'M' did (isNumeric)
+
+ Removed:
+ 1) 'q' and 'Q' are now obsolete (see Changed #5)
+
+ Version 1.2:
+ Added:
+ 1) 'q' - Push minimum value of array
+ 2) 'Q' - Push maximum value of array
+ 3) 'b' - Push sum of array (more accurately, fold array with the '+'
+ function)
+ 4) 'B' - Push product of array (more accurately, fold array with the '*'
+ function)
+ 5) 'J' - Push sorted array
+
+ Changed:
+ 1) '%' - If used on two arrays, now zips the arrays
+ 2) 'M' (isNumeric), 'N' (isAlphaNumeric), and 'O' (isWhitespace)
+ now work on arrays as well (performing the function to
+ every element in the array and returning the boolean ALL)
+ 3) 'C' - If used on an array, reverses the array
+ 4) 'r' - Now works on single integers
+ 5) The __repr__ method on types now more accurately represents the data
+ encased in them
+ 6) Added __add__ and __mul__ methods on types to accomodate sum and
+ product
+ 7) Changed the output format of '#'
+ 8) Added MUCH better documentation
+
+ Version 1.1:
+ Added:
+ 1) 'z' - Push space character (JNum(32))
+ 2) 'Z' - Push line feed character (JNum(10))
+ 3) 'Y':
+ Arr, Any - Push array of all indexes where an element appears
+ in an array
+
+ 4) Interpreter -C, changelog option
+
+ Changed:
+ 1) Do and While no longer consume the test value to determine whether
+ or not to continue looping
+
+ 2) Fixed dropif; it was dropping if the value was false instead of
+ true
+
+ Removed:
+ 1) Binary number syntax. May add back if actually needed somewhere in
+ the future.
+
+ Version 1.0:
+ Initial release
+"""
+ sys.exit(0)
+
+ try:
+ try:
+ if args.inter:
+ print "JAGL Interpreter Alpha V1.3 - Jan 2/2015"
+ s = Stack()
+ while True:
+ try:
+ s = runOn(tokenize(raw_input(">")), s)
+ except EOFError:
+ break
+ elif args.code:
+ runCode(args.code)
+ elif args.filename:
+ if os.path.isfile(args.filename):
+ with open(args.filename, "r") as f:
+ data = f.read()
+ runCode(data)
+ else:
+ print "Error: File not found"
+ else:
+ print "Usage: jagli.py [-h] [-C] [-i] [-c code] | filename"
+ except Exception as e:
+ Error(e, True)
+ except KeyboardInterrupt:
+ print "Exiting ..."
\ No newline at end of file
diff --git a/pool/shard009/Python/0086518_urls.py b/pool/shard009/Python/0086518_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..39ddd1d7091ef61a88bf61d3e8fcb4e95fee3722
--- /dev/null
+++ b/pool/shard009/Python/0086518_urls.py
@@ -0,0 +1,28 @@
+from django.conf.urls import include, url
+from . import views
+from django.views.generic.dates import ArchiveIndexView
+from blogapp.views import ArticleMonthArchiveView
+from .models import Post
+
+urlpatterns = [
+ url(r'^$', views.index),
+ url(r'^about$', views.about),
+ url(r'^blog$', views.post_list),
+ url(r'^drafts/$', views.post_draft_list, name='post_draft_list'),
+ url(r'^post/(?P[0-9]+)/publish/$', views.post_publish, name='post_publish'),
+ url(r'^post/(?P[0-9]+)/remove/$', views.post_remove, name='post_remove'),
+ url(r'^post/(?P[0-9]+)/$', views.post_detail),
+ url(r'^post/new/$', views.post_new, name='post_new'),
+ url(r'^post/(?P[0-9]+)/edit/$', views.post_edit, name='post_edit'),
+ url(r'^archive/$',
+ ArchiveIndexView.as_view(model=Post, date_field="published_date"),
+ name="post_archive"),
+ # Example: /2012/aug/
+ url(r'^(?P[0-9]{4})/(?P[-\w]+)/$',
+ ArticleMonthArchiveView.as_view(),
+ name="archive_month"),
+ # Example: /2012/08/
+ url(r'^(?P[0-9]{4})/(?P[0-9]+)/$',
+ ArticleMonthArchiveView.as_view(month_format='%m'),
+ name="archive_month_numeric"),
+]
diff --git a/pool/shard009/Python/0086520_azAttrVisalizer.py b/pool/shard009/Python/0086520_azAttrVisalizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0a76137ebb58a7a46f4264eb9d1190c8162f333
--- /dev/null
+++ b/pool/shard009/Python/0086520_azAttrVisalizer.py
@@ -0,0 +1,31 @@
+import maya.cmds as mc
+
+
+def getAttrToGraph():
+ # returns attribute path if one is selected in the channelbox
+ selAttr = mc.channelBox('mainChannelBox', q=1, selectedMainAttributes=1)
+ if selAttr and len(selAttr) == 1:
+ selObj = mc.ls(sl=1)[-1]
+ attrPath = '{}.{}'.format(selObj, selAttr[0])
+ return attrPath
+
+def createVisualizerNodes():
+ # create node tree
+ sGrpFollow = mc.group(n='grp_graphKeys', em=1)
+ sLocGraphThis = mc.spaceLocator(n='loc_pointOnGraph')[0]
+ mc.addAttr(ln='time')
+ mc.addAttr(ln='offsetGraph')
+ mc.parent(sGrpFollow, sLocGraphThis)
+ iStartTime = int(mc.playbackOptions(q=1, min=1))
+ iEndTime = int(mc.playbackOptions(q=1, max=1))
+ # adding keys to mark second marks
+ for t in range(iStartTime, iEndTime, 24):
+ mc.setKeyframe(sGrpFollow, at='translateX', time=[t])
+ # setting up the X offset
+ sExprCmd = '{0}.offsetGraph = {0}.time - `playbackOptions -q -min` + 1'.format(sLocGraphThis)
+ mc.expression(s=sExprCmd, n='expr_visualizerOffset', ae=1)
+ return sLocGraphThis, sGrpFollow
+
+createVisualizerNodes()
+
+
diff --git a/pool/shard009/Python/0086521_calcoohija.py b/pool/shard009/Python/0086521_calcoohija.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fa9a5a2acad0025db20bb08dc7ef2950624641d
--- /dev/null
+++ b/pool/shard009/Python/0086521_calcoohija.py
@@ -0,0 +1,35 @@
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+
+import sys
+
+import calcoo
+
+
+class CalculadoraHija(calcoo.Calculadora):
+ #operacion producto
+ def prod(self, op1, op2):
+ return op1 * op2
+
+ def div(self, op1, op2):
+ #Operacion division
+ try:
+ return op1 / op2
+ except ZeroDivisionError:
+ sys.exit("Division by zero is not allowed")
+
+
+c1 = CalculadoraHija()
+#Añadimos al diccionario las nuevas operaciones
+calcoo.dicc["multiplica"] = c1.prod
+calcoo.dicc["divide"] = c1.div
+
+
+if __name__ == "__main__":
+ operando1 = calcoo.numero(sys.argv[1])
+ operando2 = calcoo.numero(sys.argv[3])
+ try:
+ funcion = calcoo.dicc[sys.argv[2]]
+ except:
+ sys.exit('Operación no válida.')
+ print(calcoo.calculos(funcion, operando1, operando2))
diff --git a/pool/shard009/Python/0086522_check.py b/pool/shard009/Python/0086522_check.py
new file mode 100644
index 0000000000000000000000000000000000000000..88d67b6cffeba5c488550208befef1fad207e8bc
--- /dev/null
+++ b/pool/shard009/Python/0086522_check.py
@@ -0,0 +1,82 @@
+# encoding: UTF-8
+
+from six.moves import range
+from time import time
+from tests.mock import Client
+from tml import Key, Gender
+from tml.translation import TranslationOption
+from tml.application import Application
+from tml.language import Language
+from random import choice, randint
+from tml.dictionary.source import SourceDictionary
+
+
+class Timer(object):
+ """ Timer """
+ def __init__(self):
+ self.start = time()
+ self.times = 1
+
+ def finish(self):
+ self.stop = time()
+ return self
+
+ @property
+ def time(self):
+ return self.stop - self.start
+
+ def call(self, fn, times):
+ self.times = times
+ for i in range(times):
+ fn()
+ return self.finish()
+
+ def per_action(self):
+ return self.time / self.times
+
+
+def test_load_language(app):
+ def load_language():
+ locales = ['ru','en']
+ Language.load_by_locale(app, choice(locales))
+ return load_language
+
+
+
+def main():
+ c = Client.read_all()
+ app = Application.load_default(c)
+ t = Timer().call(test_load_language(app), 100)
+ print('Load language %f' % t.per_action())
+ ru = Language.load_by_locale(app, 'ru')
+ dict = SourceDictionary(language = ru, source = 'index')
+ t = dict.fetch(Key(label = '{actor} give you {count}',
+ description = 'somebody give you few apples',
+ language = ru))
+ def translate():
+ t = dict.fetch(Key(label = '{actor} give you {count}',
+ description = 'somebody give you few apples',
+ language = ru))
+ actors = [{'name':'Анна','gender':'female'}, {'name':'Мария','gender':'female'}, {'name':'Вася','gender':'male'}, {'name':'Артем','gender':'male'}]
+ t.execute({'count': randint(1, 1000), 'actor': choice(actors)}, {})
+
+ t = Timer().call(translate, 1000)
+ t_trans = t.time
+ print 'Translate %f' % t.per_action()
+ def execute():
+ count = randint(1, 100)
+ persons = [Gender.male('Вася'),
+ Gender.female('Маша'),
+ Gender.female('Люся'),
+ Gender.female('Кристина'),
+ Gender.male('Артем'),
+ Gender.other('Артемон'),
+ Gender.male('Коля')]
+ t = TranslationOption('{name||дал, дала, дало} {to::dat} {count} яблоко', ru, {})
+ t.execute({'name': choice(persons), 'to': choice(persons), 'count': count}, {})
+ t = Timer().call(execute, 1000)
+ print('Execute %f' % t.per_action())
+ print('Total %f' % t_trans)
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0086530_memoization.py b/pool/shard009/Python/0086530_memoization.py
new file mode 100644
index 0000000000000000000000000000000000000000..977dee9826e04c4355934e297d666a2c2dbffb92
--- /dev/null
+++ b/pool/shard009/Python/0086530_memoization.py
@@ -0,0 +1,90 @@
+import collections
+import functools
+import contextlib
+import astropy.units as u
+
+_WITH_MEMOIZATION = False
+_CACHE_SIZE = 20
+
+
+@contextlib.contextmanager
+def use_astromodels_memoization(switch, cache_size=_CACHE_SIZE):
+ """
+ Activate/deactivate memoization temporarily
+
+ :param switch: True (memoization on) or False (memoization off)
+ :param cache_size: number of previous evaluation of functions to keep in memory. Default: 100
+ :return:
+ """
+
+ global _WITH_MEMOIZATION
+ global _CACHE_SIZE
+
+ old_status = bool(_WITH_MEMOIZATION)
+ old_cache_size = int(_CACHE_SIZE)
+
+ _WITH_MEMOIZATION = bool(switch)
+ _CACHE_SIZE = int(cache_size)
+
+ yield
+
+ _WITH_MEMOIZATION = old_status
+ _CACHE_SIZE = old_cache_size
+
+
+
+def memoize(method):
+ """
+ A decorator for functions of sources which memoize the results of the last _CACHE_SIZE calls,
+
+ :param method: method to be memoized
+ :return: the decorated method
+ """
+
+ cache = method.cache = collections.OrderedDict()
+
+ # Put these two methods in the local space (faster)
+ _get = cache.get
+ _popitem = cache.popitem
+
+ @functools.wraps(method)
+ def memoizer(instance, x, *args, **kwargs):
+
+ if not _WITH_MEMOIZATION or isinstance(x, u.Quantity):
+
+ # Memoization is not active or using units, do not use memoization
+
+ return method(instance, x, *args, **kwargs)
+
+ # Create a tuple because a tuple is hashable
+
+ unique_id = tuple(float(yy.value) for yy in instance.parameters.values()) + (x.size, x.min(), x.max())
+
+ # Create a unique identifier for this combination of inputs
+
+ key = hash(unique_id)
+
+ # Let's do it this way so we only look into the dictionary once
+
+ result = _get(key)
+
+ if result is not None:
+
+ return result
+
+ else:
+
+ result = method(instance, x, *args, **kwargs)
+
+ cache[key] = result
+
+ if len(cache) > _CACHE_SIZE:
+ # Remove half of the element (but at least 1, even if _CACHE_SIZE=1, which would be pretty idiotic ;-) )
+ [_popitem(False) for i in range(max(_CACHE_SIZE // 2, 1))]
+
+ return result
+
+ # Add the function as a "attribute" so we can access it
+ memoizer.input_object = method
+
+ return memoizer
diff --git a/pool/shard009/Python/0086534_QualitySettingsModel.py b/pool/shard009/Python/0086534_QualitySettingsModel.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d02d27f7263f7f23574cf0e1356e7414111b2df
--- /dev/null
+++ b/pool/shard009/Python/0086534_QualitySettingsModel.py
@@ -0,0 +1,194 @@
+# Copyright (c) 2016 Ultimaker B.V.
+# Cura is released under the terms of the AGPLv3 or higher.
+
+import collections
+
+from PyQt5.QtCore import pyqtProperty, pyqtSignal, Qt
+
+import UM.Application
+import UM.Logger
+import UM.Qt
+import UM.Settings
+
+
+class QualitySettingsModel(UM.Qt.ListModel.ListModel):
+ KeyRole = Qt.UserRole + 1
+ LabelRole = Qt.UserRole + 2
+ UnitRole = Qt.UserRole + 3
+ ProfileValueRole = Qt.UserRole + 4
+ UserValueRole = Qt.UserRole + 5
+ CategoryRole = Qt.UserRole + 6
+
+ def __init__(self, parent = None):
+ super().__init__(parent = parent)
+
+ self._container_registry = UM.Settings.ContainerRegistry.getInstance()
+
+ self._extruder_id = None
+ self._quality = None
+ self._material = None
+
+ self.addRoleName(self.KeyRole, "key")
+ self.addRoleName(self.LabelRole, "label")
+ self.addRoleName(self.UnitRole, "unit")
+ self.addRoleName(self.ProfileValueRole, "profile_value")
+ self.addRoleName(self.UserValueRole, "user_value")
+ self.addRoleName(self.CategoryRole, "category")
+
+ def setExtruderId(self, extruder_id):
+ if extruder_id != self._extruder_id:
+ self._extruder_id = extruder_id
+ self._update()
+ self.extruderIdChanged.emit()
+
+ extruderIdChanged = pyqtSignal()
+ @pyqtProperty(str, fset = setExtruderId, notify = extruderIdChanged)
+ def extruderId(self):
+ return self._extruder_id
+
+ def setQuality(self, quality):
+ if quality != self._quality:
+ self._quality = quality
+ self._update()
+ self.qualityChanged.emit()
+
+ qualityChanged = pyqtSignal()
+ @pyqtProperty(str, fset = setQuality, notify = qualityChanged)
+ def quality(self):
+ return self._quality
+
+ def setMaterial(self, material):
+ if material != self._material:
+ self._material = material
+ self._update()
+ self.materialChanged.emit()
+
+ materialChanged = pyqtSignal()
+ @pyqtProperty(str, fset = setMaterial, notify = materialChanged)
+ def material(self):
+ return self._material
+
+ def _update(self):
+ if not self._quality:
+ return
+
+ items = []
+
+ settings = collections.OrderedDict()
+ definition_container = UM.Application.getInstance().getGlobalContainerStack().getBottom()
+
+ containers = self._container_registry.findInstanceContainers(id = self._quality)
+ if not containers:
+ UM.Logger.log("w", "Could not find a quality container with id %s", self._quality)
+ return
+
+ quality_container = None
+ quality_changes_container = None
+
+ if containers[0].getMetaDataEntry("type") == "quality":
+ quality_container = containers[0]
+ else:
+ quality_changes_container = containers[0]
+
+ criteria = {
+ "type": "quality",
+ "quality_type": quality_changes_container.getMetaDataEntry("quality"),
+ "definition": quality_changes_container.getDefinition().getId()
+ }
+
+ if self._material:
+ criteria["material"] = self._material
+
+ quality_container = self._container_registry.findInstanceContainers(**criteria)
+ if not quality_container:
+ UM.Logger.log("w", "Could not find a quality container matching quality changes %s", quality_changes_container.getId())
+ return
+ quality_container = quality_container[0]
+
+ quality_type = quality_container.getMetaDataEntry("quality_type")
+ definition_id = quality_container.getDefinition().getId()
+
+ criteria = {"type": "quality", "quality_type": quality_type, "definition": definition_id}
+
+ if self._material:
+ criteria["material"] = self._material
+
+ criteria["extruder"] = self._extruder_id
+
+ containers = self._container_registry.findInstanceContainers(**criteria)
+ if not containers:
+ # Try again, this time without extruder
+ new_criteria = criteria.copy()
+ new_criteria.pop("extruder")
+ containers = self._container_registry.findInstanceContainers(**new_criteria)
+
+ if not containers:
+ # Try again, this time without material
+ criteria.pop("material")
+ containers = self._container_registry.findInstanceContainers(**criteria)
+
+ if not containers:
+ # Try again, this time without material or extruder
+ criteria.pop("extruder") # "material" has already been popped
+ containers = self._container_registry.findInstanceContainers(**criteria)
+
+ if not containers:
+ UM.Logger.log("Could not find any quality containers matching the search criteria %s" % str(criteria))
+ return
+
+ if quality_changes_container:
+ criteria = {"type": "quality_changes", "quality": quality_type, "definition": definition_id, "name": quality_changes_container.getName()}
+ if self._extruder_id != "":
+ criteria["extruder"] = self._extruder_id
+ else:
+ criteria["extruder"] = None
+
+ changes = self._container_registry.findInstanceContainers(**criteria)
+ if changes:
+ containers.extend(changes)
+
+ global_container_stack = UM.Application.getInstance().getGlobalContainerStack()
+ is_multi_extrusion = global_container_stack.getProperty("machine_extruder_count", "value") > 1
+
+ current_category = ""
+ for definition in definition_container.findDefinitions():
+ if definition.type == "category":
+ current_category = definition.label
+ continue
+
+ profile_value = None
+ for container in containers:
+ new_value = container.getProperty(definition.key, "value")
+ if new_value is not None:
+ profile_value = new_value
+
+ user_value = None
+ if not self._extruder_id:
+ user_value = global_container_stack.getTop().getProperty(definition.key, "value")
+ else:
+ extruder_stack = self._container_registry.findContainerStacks(id = self._extruder_id)
+ if extruder_stack:
+ user_value = extruder_stack[0].getTop().getProperty(definition.key, "value")
+
+ if profile_value is None and user_value is None:
+ continue
+
+ if is_multi_extrusion:
+ settable_per_extruder = global_container_stack.getProperty(definition.key, "settable_per_extruder")
+ # If a setting is not settable per extruder (global) and we're looking at an extruder tab, don't show this value.
+ if self._extruder_id != "" and not settable_per_extruder:
+ continue
+
+ # If a setting is settable per extruder (not global) and we're looking at global tab, don't show this value.
+ if self._extruder_id == "" and settable_per_extruder:
+ continue
+ items.append({
+ "key": definition.key,
+ "label": definition.label,
+ "unit": definition.unit,
+ "profile_value": "" if profile_value is None else str(profile_value), # it is for display only
+ "user_value": "" if user_value is None else str(user_value),
+ "category": current_category
+ })
+
+ self.setItems(items)
\ No newline at end of file
diff --git a/pool/shard009/Python/0086535_zeroconf.py b/pool/shard009/Python/0086535_zeroconf.py
new file mode 100644
index 0000000000000000000000000000000000000000..895ae4ab790d6c8387a2f1923fcbdadd81afd418
--- /dev/null
+++ b/pool/shard009/Python/0086535_zeroconf.py
@@ -0,0 +1,131 @@
+"""Generate zeroconf file."""
+from collections import OrderedDict, defaultdict
+import json
+from typing import Dict
+
+from .model import Integration, Config
+
+BASE = """
+\"\"\"Automatically generated by hassfest.
+
+To update, run python3 -m script.hassfest
+\"\"\"
+
+
+ZEROCONF = {}
+
+HOMEKIT = {}
+""".strip()
+
+
+def generate_and_validate(integrations: Dict[str, Integration]):
+ """Validate and generate zeroconf data."""
+ service_type_dict = defaultdict(list)
+ homekit_dict = {}
+
+ for domain in sorted(integrations):
+ integration = integrations[domain]
+
+ if not integration.manifest:
+ continue
+
+ service_types = integration.manifest.get('zeroconf', [])
+ homekit = integration.manifest.get('homekit', {})
+ homekit_models = homekit.get('models', [])
+
+ if not service_types and not homekit_models:
+ continue
+
+ try:
+ with open(str(integration.path / "config_flow.py")) as fp:
+ content = fp.read()
+ uses_discovery_flow = 'register_discovery_flow' in content
+
+ if (service_types and not uses_discovery_flow and
+ ' async_step_zeroconf(' not in content):
+ integration.add_error(
+ 'zeroconf', 'Config flow has no async_step_zeroconf')
+ continue
+
+ if (homekit_models and not uses_discovery_flow and
+ ' async_step_homekit(' not in content):
+ integration.add_error(
+ 'zeroconf', 'Config flow has no async_step_homekit')
+ continue
+
+ except FileNotFoundError:
+ integration.add_error(
+ 'zeroconf',
+ 'Zeroconf info in a manifest requires a config flow to exist'
+ )
+ continue
+
+ for service_type in service_types:
+ service_type_dict[service_type].append(domain)
+
+ for model in homekit_models:
+ # We add a space, as we want to test for it to be model + space.
+ model += " "
+
+ if model in homekit_dict:
+ integration.add_error(
+ 'zeroconf',
+ 'Integrations {} and {} have overlapping HomeKit '
+ 'models'.format(domain, homekit_dict[model]))
+ break
+
+ homekit_dict[model] = domain
+
+ # HomeKit models are matched on starting string, make sure none overlap.
+ warned = set()
+ for key in homekit_dict:
+ if key in warned:
+ continue
+
+ # n^2 yoooo
+ for key_2 in homekit_dict:
+ if key == key_2 or key_2 in warned:
+ continue
+
+ if key.startswith(key_2) or key_2.startswith(key):
+ integration.add_error(
+ 'zeroconf',
+ 'Integrations {} and {} have overlapping HomeKit '
+ 'models'.format(homekit_dict[key], homekit_dict[key_2]))
+ warned.add(key)
+ warned.add(key_2)
+ break
+
+ zeroconf = OrderedDict((key, service_type_dict[key])
+ for key in sorted(service_type_dict))
+ homekit = OrderedDict((key, homekit_dict[key])
+ for key in sorted(homekit_dict))
+
+ return BASE.format(
+ json.dumps(zeroconf, indent=4),
+ json.dumps(homekit, indent=4),
+ )
+
+
+def validate(integrations: Dict[str, Integration], config: Config):
+ """Validate zeroconf file."""
+ zeroconf_path = config.root / 'homeassistant/generated/zeroconf.py'
+ config.cache['zeroconf'] = content = generate_and_validate(integrations)
+
+ with open(str(zeroconf_path), 'r') as fp:
+ current = fp.read().strip()
+ if current != content:
+ config.add_error(
+ "zeroconf",
+ "File zeroconf.py is not up to date. "
+ "Run python3 -m script.hassfest",
+ fixable=True
+ )
+ return
+
+
+def generate(integrations: Dict[str, Integration], config: Config):
+ """Generate zeroconf file."""
+ zeroconf_path = config.root / 'homeassistant/generated/zeroconf.py'
+ with open(str(zeroconf_path), 'w') as fp:
+ fp.write(config.cache['zeroconf'] + '\n')
diff --git a/pool/shard009/Python/0086536_test_swagger_api.py b/pool/shard009/Python/0086536_test_swagger_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..826bd24a750c0d35e5a0ae139833a4bd79587d7c
--- /dev/null
+++ b/pool/shard009/Python/0086536_test_swagger_api.py
@@ -0,0 +1,139 @@
+import pprint
+from pymacaron_core.swagger.api import API
+
+
+class Handlers():
+ pass
+
+
+yaml_str = """
+swagger: '2.0'
+info:
+ version: '0.0.1'
+host: some.server.com
+schemes:
+ - http
+produces:
+ - application/json
+paths:
+ /v1/some/path:
+ get:
+ summary: blabla
+ description: blabla
+ parameters:
+ - in: query
+ name: arg1
+ description: foooo
+ required: true
+ type: string
+ - in: query
+ name: arg2
+ description: foooo
+ required: true
+ type: string
+ produces:
+ - application/json
+ x-bind-server: pnt_common.test.default_timeout
+ x-bind-client: do_test
+ x-auth-required: false
+ responses:
+ '200':
+ description: result
+ schema:
+ $ref: '#/definitions/Result'
+
+ /v1/some/more/path:
+ get:
+ description: blabla
+ produces:
+ - application/json
+ x-bind-server: pnt_common.test.default_timeout
+ x-bind-client: do_more_test
+ responses:
+ '200':
+ description: result
+ schema:
+ $ref: '#/definitions/Result'
+
+definitions:
+
+ Result:
+ type: object
+ description: result
+ properties:
+ foo:
+ type: string
+ description: blabla
+ bar:
+ type: string
+ description: bloblo
+
+ Param:
+ type: object
+ description: param
+ properties:
+ arg1:
+ type: string
+ description: blabla
+ arg2:
+ type: string
+ description: bloblo
+
+ Error:
+ type: object
+ description: param
+ properties:
+ code:
+ type: string
+ description: blabla
+ message:
+ type: string
+ description: bloblo
+
+"""
+
+
+def test_api_constructor():
+ api = API('somename', yaml_str=yaml_str)
+ assert api.name == 'somename'
+ assert api.api_spec
+ assert api.client_timeout == 10
+ assert api.error_callback
+ assert not api.is_server
+
+
+def test_api_models():
+ api = API('somename', yaml_str=yaml_str)
+
+ # Check that the models work
+ assert hasattr(api.model, 'Param')
+ assert hasattr(api.model, 'Result')
+ assert hasattr(api.model, 'Error')
+
+ name_to_model = {
+ 'Param': api.model.Param,
+ 'Result': api.model.Result,
+ 'Error': api.model.Error,
+ }
+ for name, model in list(name_to_model.items()):
+ i = model()
+ type_name = type(i).__name__
+ print("type: %s = " % name + pprint.pformat(type(api.model.Param()).__name__))
+ assert type_name == name
+
+ P = api.model.Param(arg1='1')
+ print("p: " + pprint.pformat(P))
+ assert type(P).__name__ == 'Param'
+ assert P.arg1 == '1'
+
+
+def test_api_get_version():
+ api = API('somename', yaml_str=yaml_str)
+ assert api.get_version() == '0.0.1'
+
+
+def test_api_clients():
+ api = API('somename', yaml_str=yaml_str)
+ assert hasattr(api.client, 'do_test')
+ assert hasattr(api.client, 'do_more_test')
+ assert api.client.do_test != api.client.do_more_test
diff --git a/pool/shard009/Python/0086539_Protek506_multimeter_RS232.py b/pool/shard009/Python/0086539_Protek506_multimeter_RS232.py
new file mode 100644
index 0000000000000000000000000000000000000000..46c8637ce14d352f9cfabc5828d861fdbb3d7ac6
--- /dev/null
+++ b/pool/shard009/Python/0086539_Protek506_multimeter_RS232.py
@@ -0,0 +1,81 @@
+#!/usr/bin/python2.7
+# -*- coding: utf-8 -*-
+
+"""
+read serial output from Protek 506 multimeter and save it to file
+
+(C) 2015 x4x georg.la8585@gmx.at
+
+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.
+
+Name: Protek506_multimeter_RS232.py
+Info:
+Thema:
+Date: <2015-05-06 Mittwoch 10:52>
+Version:
+
+the serial port configuration for the Protek506 is 1200,N,7,2.
+Date is sent on sent enter.
+"""
+
+import datetime
+import signal
+import sys
+import serial
+import time
+
+
+# open file
+file = open("Protek_log.txt", "ab")
+
+# open serial
+ser = serial.Serial(
+ port='/dev/ttyUSB0',
+ baudrate=1200,
+ bytesize=7,
+ parity='N',
+ stopbits=2,
+ timeout=None,
+ xonxoff=0,
+ rtscts=0)
+
+
+def signal_handler(signal, frame):
+ """on Cont-C exit"""
+ print 'You pressed Ctrl+C!'
+ file.close()
+ ser.close()
+ sys.exit(0)
+
+# run:
+signal.signal(signal.SIGINT, signal_handler)
+
+if(not ser.isOpen):
+ ser.open()
+print("serial is open")
+counter = 0
+while(ser.isOpen):
+ counter += 1
+ ser.write("\n")
+ data = ser.read(1)
+ data += ser.read(ser.inWaiting())
+ datastr = (str(datetime.datetime.now()) + " " + data)
+ print(datastr)
+ # append to fiel:
+ file.write(datastr + "\n")
+ """
+ if counter > 20: # every cycle
+ file.flush() # force writing to file
+ """
+ time.sleep(1) # sleep 1sec
+
diff --git a/pool/shard009/Python/0086541_auth_provider_homeassistant.py b/pool/shard009/Python/0086541_auth_provider_homeassistant.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ac6f23e2d91e374c636bb6015d587afc144f4e
--- /dev/null
+++ b/pool/shard009/Python/0086541_auth_provider_homeassistant.py
@@ -0,0 +1,178 @@
+"""Offer API to configure the Home Assistant auth provider."""
+import voluptuous as vol
+
+from homeassistant.auth.providers import homeassistant as auth_ha
+from homeassistant.components import websocket_api
+from homeassistant.components.websocket_api import decorators
+from homeassistant.exceptions import Unauthorized
+
+
+async def async_setup(hass):
+ """Enable the Home Assistant views."""
+ hass.components.websocket_api.async_register_command(websocket_create)
+ hass.components.websocket_api.async_register_command(websocket_delete)
+ hass.components.websocket_api.async_register_command(websocket_change_password)
+ hass.components.websocket_api.async_register_command(
+ websocket_admin_change_password
+ )
+ return True
+
+
+@decorators.websocket_command(
+ {
+ vol.Required("type"): "config/auth_provider/homeassistant/create",
+ vol.Required("user_id"): str,
+ vol.Required("username"): str,
+ vol.Required("password"): str,
+ }
+)
+@websocket_api.require_admin
+@websocket_api.async_response
+async def websocket_create(hass, connection, msg):
+ """Create credentials and attach to a user."""
+ provider = auth_ha.async_get_provider(hass)
+ user = await hass.auth.async_get_user(msg["user_id"])
+
+ if user is None:
+ connection.send_error(msg["id"], "not_found", "User not found")
+ return
+
+ if user.system_generated:
+ connection.send_error(
+ msg["id"],
+ "system_generated",
+ "Cannot add credentials to a system generated user.",
+ )
+ return
+
+ try:
+ await provider.async_add_auth(msg["username"], msg["password"])
+ except auth_ha.InvalidUser:
+ connection.send_error(msg["id"], "username_exists", "Username already exists")
+ return
+
+ credentials = await provider.async_get_or_create_credentials(
+ {"username": msg["username"]}
+ )
+ await hass.auth.async_link_user(user, credentials)
+
+ connection.send_result(msg["id"])
+
+
+@decorators.websocket_command(
+ {
+ vol.Required("type"): "config/auth_provider/homeassistant/delete",
+ vol.Required("username"): str,
+ }
+)
+@websocket_api.require_admin
+@websocket_api.async_response
+async def websocket_delete(hass, connection, msg):
+ """Delete username and related credential."""
+ provider = auth_ha.async_get_provider(hass)
+ credentials = await provider.async_get_or_create_credentials(
+ {"username": msg["username"]}
+ )
+
+ # if not new, an existing credential exists.
+ # Removing the credential will also remove the auth.
+ if not credentials.is_new:
+ await hass.auth.async_remove_credentials(credentials)
+
+ connection.send_result(msg["id"])
+ return
+
+ try:
+ await provider.async_remove_auth(msg["username"])
+ except auth_ha.InvalidUser:
+ connection.send_error(
+ msg["id"], "auth_not_found", "Given username was not found."
+ )
+ return
+
+ connection.send_result(msg["id"])
+
+
+@decorators.websocket_command(
+ {
+ vol.Required("type"): "config/auth_provider/homeassistant/change_password",
+ vol.Required("current_password"): str,
+ vol.Required("new_password"): str,
+ }
+)
+@websocket_api.async_response
+async def websocket_change_password(hass, connection, msg):
+ """Change current user password."""
+ user = connection.user
+ if user is None:
+ connection.send_error(msg["id"], "user_not_found", "User not found")
+ return
+
+ provider = auth_ha.async_get_provider(hass)
+ username = None
+ for credential in user.credentials:
+ if credential.auth_provider_type == provider.type:
+ username = credential.data["username"]
+ break
+
+ if username is None:
+ connection.send_error(
+ msg["id"], "credentials_not_found", "Credentials not found"
+ )
+ return
+
+ try:
+ await provider.async_validate_login(username, msg["current_password"])
+ except auth_ha.InvalidAuth:
+ connection.send_error(msg["id"], "invalid_password", "Invalid password")
+ return
+
+ await provider.async_change_password(username, msg["new_password"])
+
+ connection.send_result(msg["id"])
+
+
+@decorators.websocket_command(
+ {
+ vol.Required(
+ "type"
+ ): "config/auth_provider/homeassistant/admin_change_password",
+ vol.Required("user_id"): str,
+ vol.Required("password"): str,
+ }
+)
+@decorators.require_admin
+@decorators.async_response
+async def websocket_admin_change_password(hass, connection, msg):
+ """Change password of any user."""
+ if not connection.user.is_owner:
+ raise Unauthorized(context=connection.context(msg))
+
+ user = await hass.auth.async_get_user(msg["user_id"])
+
+ if user is None:
+ connection.send_error(msg["id"], "user_not_found", "User not found")
+ return
+
+ provider = auth_ha.async_get_provider(hass)
+
+ username = None
+ for credential in user.credentials:
+ if credential.auth_provider_type == provider.type:
+ username = credential.data["username"]
+ break
+
+ if username is None:
+ connection.send_error(
+ msg["id"], "credentials_not_found", "Credentials not found"
+ )
+ return
+
+ try:
+ await provider.async_change_password(username, msg["password"])
+ connection.send_result(msg["id"])
+ except auth_ha.InvalidUser:
+ connection.send_error(
+ msg["id"], "credentials_not_found", "Credentials not found"
+ )
+ return
diff --git a/pool/shard009/Python/0086542_pygame_texture.py b/pool/shard009/Python/0086542_pygame_texture.py
new file mode 100644
index 0000000000000000000000000000000000000000..4152a536d375475705ab09ef912601c3dac2ed29
--- /dev/null
+++ b/pool/shard009/Python/0086542_pygame_texture.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+"""Load a texture from a file using pygame"""
+
+import os
+import VisionEgg
+VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
+
+from VisionEgg.Core import *
+from VisionEgg.FlowControl import Presentation
+from VisionEgg.Textures import *
+import pygame.image
+import OpenGL.GL as gl
+
+filename = os.path.join(VisionEgg.config.VISIONEGG_SYSTEM_DIR,"data","visionegg.bmp")
+pygame_surface = pygame.image.load(filename)
+texture = Texture(pygame_surface)
+
+screen = get_default_screen()
+
+# Create the instance of TextureStimulus
+stimulus = TextureStimulus(texture = texture,
+ position = (screen.size[0]/2.0,screen.size[1]/2.0),
+ anchor = 'center',
+ size = texture.size,
+ mipmaps_enabled = 0,
+ texture_min_filter=gl.GL_LINEAR,
+ shrink_texture_ok=1)
+
+viewport = Viewport(screen=screen,
+ stimuli=[stimulus])
+
+p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport])
+p.go()
diff --git a/pool/shard009/Python/0086543_sample_data.py b/pool/shard009/Python/0086543_sample_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5415d9587f8b2d3646229fc4e8300972204a3d8
--- /dev/null
+++ b/pool/shard009/Python/0086543_sample_data.py
@@ -0,0 +1,122 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+
+import frappe
+from frappe.utils.make_random import add_random_children, get_random
+import frappe.utils
+
+def make_sample_data():
+ """Create a few opportunities, quotes, material requests, issues, todos, projects
+ to help the user get started"""
+
+ selling_items = frappe.get_all("Item", filters = {"is_sales_item": 1})
+ buying_items = frappe.get_all("Item", filters = {"is_purchase_item": 1})
+
+ if selling_items:
+ for i in range(3):
+ make_opportunity(selling_items)
+ make_quote(selling_items)
+
+ make_projects()
+
+ if buying_items:
+ make_material_request(buying_items)
+
+ frappe.db.commit()
+
+def make_opportunity(selling_items):
+ b = frappe.get_doc({
+ "doctype": "Opportunity",
+ "enquiry_from": "Customer",
+ "customer": get_random("Customer"),
+ "enquiry_type": "Sales",
+ "with_items": 1
+ })
+
+ add_random_children(b, "items", rows=len(selling_items), randomize = {
+ "qty": (1, 5),
+ "item_code": ("Item", {"is_sales_item": 1})
+ }, unique="item_code")
+
+ b.insert(ignore_permissions=True)
+
+ b.add_comment("This is a dummy record")
+
+def make_quote(selling_items):
+ qtn = frappe.get_doc({
+ "doctype": "Quotation",
+ "quotation_to": "Customer",
+ "customer": get_random("Customer"),
+ "order_type": "Sales"
+ })
+
+ add_random_children(qtn, "items", rows=len(selling_items), randomize = {
+ "qty": (1, 5),
+ "item_code": ("Item", {"is_sales_item": 1})
+ }, unique="item_code")
+
+ qtn.insert(ignore_permissions=True)
+
+ qtn.add_comment("This is a dummy record")
+
+def make_material_request(buying_items):
+ for i in buying_items:
+ mr = frappe.get_doc({
+ "doctype": "Material Request",
+ "material_request_type": "Purchase",
+ "items": [{
+ "schedule_date": frappe.utils.add_days(frappe.utils.nowdate(), 7),
+ "item_code": i.name,
+ "qty": 10
+ }]
+ })
+ mr.insert()
+ mr.submit()
+
+ mr.add_comment("This is a dummy record")
+
+
+def make_issue():
+ pass
+
+def make_projects():
+ project = frappe.get_doc({
+ "doctype": "Project",
+ "project_name": "BCLOUD Implementation",
+ })
+ current_date = frappe.utils.nowdate()
+ project.set("tasks", [
+ {
+ "title": "Explore BCLOUD",
+ "start_date": frappe.utils.add_days(current_date, 1),
+ "end_date": frappe.utils.add_days(current_date, 2)
+ },
+ {
+ "title": "Run Sales Cycle",
+ "start_date": frappe.utils.add_days(current_date, 2),
+ "end_date": frappe.utils.add_days(current_date, 3)
+ },
+ {
+ "title": "Run Billing Cycle",
+ "start_date": frappe.utils.add_days(current_date, 3),
+ "end_date": frappe.utils.add_days(current_date, 4)
+ },
+ {
+ "title": "Run Purchase Cycle",
+ "start_date": frappe.utils.add_days(current_date, 4),
+ "end_date": frappe.utils.add_days(current_date, 5)
+ },
+ {
+ "title": "Import Data",
+ "start_date": frappe.utils.add_days(current_date, 5),
+ "end_date": frappe.utils.add_days(current_date, 6)
+ },
+ {
+ "title": "Go Live!",
+ "start_date": frappe.utils.add_days(current_date, 6),
+ "end_date": frappe.utils.add_days(current_date, 7)
+ }])
+
+ project.insert(ignore_permissions=True)
diff --git a/pool/shard009/Python/0086551_main.py b/pool/shard009/Python/0086551_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6fde145b4444254e103774322a81bbf4c086345
--- /dev/null
+++ b/pool/shard009/Python/0086551_main.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+# Copyright 2016 LasLabs Inc.
+# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
+
+import json
+from openerp import http
+from openerp.http import request
+from openerp.addons.website.controllers.main import Website
+
+
+import logging
+_logger = logging.getLogger(__name__)
+
+
+class Website(Website):
+
+ @http.route(
+ '/website/data_slider/',
+ type='http',
+ auth='public',
+ methods=['GET'],
+ website=True,
+ )
+ def get_data_slider_data(self, model, **kwargs):
+ # @TODO: Figure out a better way to hand the data to client
+ # @TODO: Security eval on this - should be fine, model perms?
+ # @TODO: Better exception handling (or any at all, really)
+ res = []
+ _logger.debug(kwargs)
+ domain = json.loads(kwargs.get('domain', "[]"))
+ fields = json.loads(kwargs.get('fields', "[]"))
+ limit = kwargs.get('limit', None)
+ if limit:
+ limit = int(limit)
+ for rec_id in request.env[model].search(domain, limit=limit):
+ res.append({
+ k: getattr(rec_id, k, None) for k in fields
+ })
+ return json.dumps(res)
diff --git a/pool/shard009/Python/0086556_BDSimulator_test.py b/pool/shard009/Python/0086556_BDSimulator_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e80a024d0af25096fa2a87919e8ea27b69e22a8
--- /dev/null
+++ b/pool/shard009/Python/0086556_BDSimulator_test.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+
+import unittest
+
+import numpy
+
+import model
+import _gfrd
+import gfrdbase
+import bd
+import logging
+import myrandom
+
+bd.log.setLevel(logging.WARNING)
+
+
+class BDSimulatorTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self.m = model.ParticleModel(1e-5)
+ self.S = model.Species('S', 2e-11, 5e-8)
+ self.A = model.Species('A', 0, 1e-8)
+ self.B = model.Species('B', 2e-11, 5e-9)
+ self.m.add_species_type(self.S)
+ self.m.add_species_type(self.A)
+ self.m.add_species_type(self.B)
+ self.m.set_all_repulsive()
+ self.w = gfrdbase.create_world(self.m, 10)
+ self.nrw = _gfrd.NetworkRulesWrapper(self.m.network_rules)
+ self.s = bd.BDSimulator(self.w, myrandom.rng, self.nrw)
+
+ def tearDown(self):
+ pass
+
+ def test_instantiation(self):
+ self.failIf(self.s == None)
+
+
+ def test_one_particle(self):
+ gfrdbase.place_particle(self.w, self.S, [0.0,0.0,0.0])
+
+ t = self.s.t
+ for i in range(5):
+ self.s.step()
+ self.failIf(t == self.s.t)
+
+ def test_two_particles(self):
+ gfrdbase.place_particle(self.w, self.S, [0.0,0.0,0.0])
+ gfrdbase.place_particle(self.w, self.S, [5e-6,5e-6,5e-6])
+
+ t = self.s.t
+ for i in range(5):
+ self.s.step()
+ self.failIf(t == self.s.t)
+
+ def test_three_particles(self):
+ gfrdbase.place_particle(self.w, self.S, [0.0,0.0,0.0])
+ gfrdbase.place_particle(self.w, self.S, [5e-6,5e-6,5e-6])
+ gfrdbase.place_particle(self.w, self.S, [1e-7,1e-7,1e-7])
+
+ t = self.s.t
+ for i in range(5):
+ self.s.step()
+ self.failIf(t == self.s.t)
+
+ def test_immobile_is_immobile(self):
+ particleA = gfrdbase.place_particle(self.w, self.A, [0.0,0.0,0.0])
+ gfrdbase.place_particle(self.w, self.B, [1.5000001e-8,0.0,0.0])
+
+ initial_position = particleA[1].position
+
+ for i in range(10):
+ self.s.step()
+ #print particleA[1].position
+
+ new_position = particleA[1].position
+ dist = self.w.distance(initial_position, new_position)
+
+ self.failIf(dist != 0, 'initial pos: %s,\tnew pos: %s' %
+ (initial_position, new_position))
+
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pool/shard009/Python/0086559_cfusb.py b/pool/shard009/Python/0086559_cfusb.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e620abf1900ae56e809db4ce89c728831fdb6e5
--- /dev/null
+++ b/pool/shard009/Python/0086559_cfusb.py
@@ -0,0 +1,196 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# || ____ _ __
+# +------+ / __ )(_) /_______________ _____ ___
+# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
+# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
+# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
+#
+# Copyright (C) 2011-2013 Bitcraze AB
+#
+# Crazyflie Nano Quadcopter Client
+#
+# 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.
+
+"""
+USB driver for the Crazyflie.
+"""
+
+import os
+import usb
+import logging
+import sys
+import time
+import array
+import binascii
+
+__author__ = 'Bitcraze AB'
+__all__ = ['CfUsb']
+
+logger = logging.getLogger(__name__)
+
+USB_VID = 0x0483
+USB_PID = 0x5740
+
+try:
+ import usb.core
+
+ pyusb_backend = None
+ if os.name == "nt":
+ import usb.backend.libusb0 as libusb0
+
+ pyusb_backend = libusb0.get_backend()
+ pyusb1 = True
+except:
+ pyusb1 = False
+
+
+def _find_devices():
+ """
+ Returns a list of CrazyRadio devices currently connected to the computer
+ """
+ ret = []
+
+ logger.info("Looking for devices....")
+
+ if pyusb1:
+ for d in usb.core.find(idVendor=USB_VID, idProduct=USB_PID, find_all=1,
+ backend=pyusb_backend):
+ ret.append(d)
+ else:
+ busses = usb.busses()
+ for bus in busses:
+ for device in bus.devices:
+ if device.idVendor == USB_VID:
+ if device.idProduct == USB_PID:
+ ret += [device, ]
+
+ return ret
+
+
+class CfUsb:
+ """ Used for communication with the Crazyradio USB dongle """
+
+ def __init__(self, device=None, devid=0):
+ """ Create object and scan for USB dongle if no device is supplied """
+ self.dev = None
+ self.handle = None
+ self._last_write = 0
+ self._last_read = 0
+
+ if device is None:
+ devices = _find_devices()
+ try:
+ self.dev = devices[devid]
+ except Exception:
+ self.dev = None
+
+ if self.dev:
+ if (pyusb1 is True):
+ self.dev.set_configuration(1)
+ self.handle = self.dev
+ self.version = float(
+ "{0:x}.{1:x}".format(self.dev.bcdDevice >> 8,
+ self.dev.bcdDevice & 0x0FF))
+ else:
+ self.handle = self.dev.open()
+ self.handle.setConfiguration(1)
+ self.handle.claimInterface(0)
+ self.version = float(self.dev.deviceVersion)
+
+ def get_serial(self):
+ return usb.util.get_string(self.dev, 255, self.dev.iSerialNumber)
+
+ def close(self):
+ if (pyusb1 is False):
+ if self.handle:
+ self.handle.releaseInterface()
+ self.handle.reset()
+ else:
+ if self.dev:
+ self.dev.reset()
+
+ self.handle = None
+ self.dev = None
+
+ def scan(self):
+ # TODO: Currently only supports one device
+ if self.dev:
+ return [("usb://0", "")]
+ return []
+
+ def set_crtp_to_usb(self, crtp_to_usb):
+ if crtp_to_usb:
+ _send_vendor_setup(self.handle, 0x01, 0x01, 1, ())
+ else:
+ _send_vendor_setup(self.handle, 0x01, 0x01, 0, ())
+
+ # Data transfers
+ def send_packet(self, dataOut):
+ """ Send a packet and receive the ack from the radio dongle
+ The ack contains information about the packet transmition
+ and a data payload if the ack packet contained any """
+ try:
+ if (pyusb1 is False):
+ count = self.handle.bulkWrite(1, dataOut, 20)
+ else:
+ count = self.handle.write(endpoint=1, data=dataOut, timeout=20)
+ except usb.USBError as e:
+ pass
+
+ def receive_packet(self):
+ dataIn = ()
+ try:
+ if (pyusb1 is False):
+ dataIn = self.handle.bulkRead(0x81, 64, 20)
+ else:
+ dataIn = self.handle.read(0x81, 64, timeout=20)
+ except usb.USBError as e:
+ try:
+ if e.backend_error_code == -7 or e.backend_error_code == -116:
+ # Normal, the read was empty
+ pass
+ else:
+ raise IOError("Crazyflie disconnected")
+ except AttributeError as e:
+ # pyusb < 1.0 doesn't implement getting the underlying error
+ # number and it seems as if it's not possible to detect
+ # if the cable is disconnected. So this detection is not
+ # supported, but the "normal" case will work.
+ pass
+
+ return dataIn
+
+
+# Private utility functions
+def _send_vendor_setup(handle, request, value, index, data):
+ if pyusb1:
+ handle.ctrl_transfer(usb.TYPE_VENDOR, request, wValue=value,
+ wIndex=index, timeout=1000, data_or_wLength=data)
+ else:
+ handle.controlMsg(usb.TYPE_VENDOR, request, data, value=value,
+ index=index, timeout=1000)
+
+
+def _get_vendor_setup(handle, request, value, index, length):
+ if pyusb1:
+ return handle.ctrl_transfer(usb.TYPE_VENDOR | 0x80, request,
+ wValue=value, wIndex=index, timeout=1000,
+ data_or_wLength=length)
+ else:
+ return handle.controlMsg(usb.TYPE_VENDOR | 0x80, request, length,
+ value=value, index=index, timeout=1000)
diff --git a/pool/shard009/Python/0086565_test_dellos10_facts.py b/pool/shard009/Python/0086565_test_dellos10_facts.py
new file mode 100644
index 0000000000000000000000000000000000000000..28a688172737b16b322f90fc95b9cfa2bebc65fd
--- /dev/null
+++ b/pool/shard009/Python/0086565_test_dellos10_facts.py
@@ -0,0 +1,110 @@
+# (c) 2016 Red Hat Inc.
+#
+# (c) 2017 Dell EMC.
+#
+# 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
+
+import json
+
+from units.compat.mock import patch
+from units.modules.utils import set_module_args
+from .dellos10_module import TestDellos10Module, load_fixture
+from ansible.modules.network.dellos10 import dellos10_facts
+
+
+class TestDellos10Facts(TestDellos10Module):
+
+ module = dellos10_facts
+
+ def setUp(self):
+ super(TestDellos10Facts, self).setUp()
+
+ self.mock_run_command = patch(
+ 'ansible.modules.network.dellos10.dellos10_facts.run_commands')
+ self.run_command = self.mock_run_command.start()
+
+ def tearDown(self):
+ super(TestDellos10Facts, self).tearDown()
+
+ self.mock_run_command.stop()
+
+ def load_fixtures(self, commands=None):
+
+ def load_from_file(*args, **kwargs):
+ module, commands = args
+ output = list()
+
+ for item in commands:
+ try:
+ obj = json.loads(item)
+ command = obj['command']
+ except ValueError:
+ command = item
+ if '|' in command:
+ command = str(command).replace('|', '')
+ filename = str(command).replace(' ', '_')
+ filename = filename.replace('/', '7')
+ filename = filename.replace(':', '_colon_')
+ output.append(load_fixture(filename))
+ return output
+
+ self.run_command.side_effect = load_from_file
+
+ def test_dellos10_facts_gather_subset_default(self):
+ set_module_args(dict())
+ result = self.execute_module()
+ ansible_facts = result['ansible_facts']
+ self.assertIn('hardware', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('default', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset'])
+ self.assertEqual('os10', ansible_facts['ansible_net_hostname'])
+ self.assertIn('ethernet1/1/8', ansible_facts['ansible_net_interfaces'].keys())
+ self.assertEqual(7936, ansible_facts['ansible_net_memtotal_mb'])
+ self.assertEqual(5693, ansible_facts['ansible_net_memfree_mb'])
+
+ def test_dellos10_facts_gather_subset_config(self):
+ set_module_args({'gather_subset': 'config'})
+ result = self.execute_module()
+ ansible_facts = result['ansible_facts']
+ self.assertIn('default', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('config', ansible_facts['ansible_net_gather_subset'])
+ self.assertEqual('os10', ansible_facts['ansible_net_hostname'])
+ self.assertIn('ansible_net_config', ansible_facts)
+
+ def test_dellos10_facts_gather_subset_hardware(self):
+ set_module_args({'gather_subset': 'hardware'})
+ result = self.execute_module()
+ ansible_facts = result['ansible_facts']
+ self.assertIn('default', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('hardware', ansible_facts['ansible_net_gather_subset'])
+ self.assertEqual('x86_64', ansible_facts['ansible_net_cpu_arch'])
+ self.assertEqual(7936, ansible_facts['ansible_net_memtotal_mb'])
+ self.assertEqual(5693, ansible_facts['ansible_net_memfree_mb'])
+
+ def test_dellos10_facts_gather_subset_interfaces(self):
+ set_module_args({'gather_subset': 'interfaces'})
+ result = self.execute_module()
+ ansible_facts = result['ansible_facts']
+ self.assertIn('default', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('interfaces', ansible_facts['ansible_net_gather_subset'])
+ self.assertIn('ethernet1/1/8', ansible_facts['ansible_net_interfaces'].keys())
+ self.assertEqual(sorted(['mgmt1/1/1', 'ethernet1/1/4', 'ethernet1/1/2', 'ethernet1/1/3', 'ethernet1/1/1']),
+ sorted(list(ansible_facts['ansible_net_neighbors'].keys())))
+ self.assertIn('ansible_net_interfaces', ansible_facts)
diff --git a/pool/shard009/Python/0086574_test_types.py b/pool/shard009/Python/0086574_test_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..baf9c5b8a315ea9a8bf37b718f8ad00a5e9a5f1a
--- /dev/null
+++ b/pool/shard009/Python/0086574_test_types.py
@@ -0,0 +1,80 @@
+# 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 custom SQLAlchemy types via Ironic DB."""
+
+from oslo_db import exception as db_exc
+
+from ironic.common import utils as ironic_utils
+import ironic.db.sqlalchemy.api as sa_api
+from ironic.db.sqlalchemy import models
+from ironic.tests.db import base
+
+
+class SqlAlchemyCustomTypesTestCase(base.DbTestCase):
+
+ # NOTE(max_lobur): Since it's not straightforward to check this in
+ # isolation these tests use existing db models.
+
+ def test_JSONEncodedDict_default_value(self):
+ # Create chassis w/o extra specified.
+ ch1_id = ironic_utils.generate_uuid()
+ self.dbapi.create_chassis({'uuid': ch1_id})
+ # Get chassis manually to test SA types in isolation from UOM.
+ ch1 = sa_api.model_query(models.Chassis).filter_by(uuid=ch1_id).one()
+ self.assertEqual({}, ch1.extra)
+
+ # Create chassis with extra specified.
+ ch2_id = ironic_utils.generate_uuid()
+ extra = {'foo1': 'test', 'foo2': 'other extra'}
+ self.dbapi.create_chassis({'uuid': ch2_id, 'extra': extra})
+ # Get chassis manually to test SA types in isolation from UOM.
+ ch2 = sa_api.model_query(models.Chassis).filter_by(uuid=ch2_id).one()
+ self.assertEqual(extra, ch2.extra)
+
+ def test_JSONEncodedDict_type_check(self):
+ self.assertRaises(db_exc.DBError,
+ self.dbapi.create_chassis,
+ {'extra':
+ ['this is not a dict']})
+
+ def test_JSONEncodedLict_default_value(self):
+ # Create conductor w/o extra specified.
+ cdr1_id = 321321
+ self.dbapi.register_conductor({'hostname': 'test_host1',
+ 'drivers': None,
+ 'id': cdr1_id})
+ # Get conductor manually to test SA types in isolation from UOM.
+ cdr1 = (sa_api
+ .model_query(models.Conductor)
+ .filter_by(id=cdr1_id)
+ .one())
+ self.assertEqual([], cdr1.drivers)
+
+ # Create conductor with drivers specified.
+ cdr2_id = 623623
+ drivers = ['foo1', 'other driver']
+ self.dbapi.register_conductor({'hostname': 'test_host2',
+ 'drivers': drivers,
+ 'id': cdr2_id})
+ # Get conductor manually to test SA types in isolation from UOM.
+ cdr2 = (sa_api
+ .model_query(models.Conductor)
+ .filter_by(id=cdr2_id)
+ .one())
+ self.assertEqual(drivers, cdr2.drivers)
+
+ def test_JSONEncodedList_type_check(self):
+ self.assertRaises(db_exc.DBError,
+ self.dbapi.register_conductor,
+ {'hostname': 'test_host3',
+ 'drivers': {'this is not a list': 'test'}})
diff --git a/pool/shard009/Python/0086575_test_screen.py b/pool/shard009/Python/0086575_test_screen.py
new file mode 100644
index 0000000000000000000000000000000000000000..294968242e97a2c90cdc1b591370e864d0b5b754
--- /dev/null
+++ b/pool/shard009/Python/0086575_test_screen.py
@@ -0,0 +1,56 @@
+from nose.tools import assert_equal
+from screen import *
+
+class TestScreen:
+ def setUp(self):
+ self.s = Screen(width=18, height=4)
+
+ def test_init_screen(self):
+ assert self.s
+
+ def test_format_single_short_message(self):
+ message = "A short message"
+ output = self.s.message(message)
+ assert_equal(message, output)
+
+ def test_format_single_long_message_to_two_lines(self):
+ message = "This is 16 characters long"
+ output = self.s.message(message)
+ assert_equal("This is 16 charact\ners long", output)
+
+ def test_message_truncates_really_long_line(self):
+ message = """Four score and seven years ago,
+our fathers brought forth on this
+continent, a new nation, conceived
+in liberty and dedicated to the
+proposition that all men are
+created equal.""".replace("\n", "")
+ output = self.s.message(message)
+ expected_output = "\n".join(["Four score and sev",
+ "en years ago, our ",
+ "fathers brought fo",
+ "rth on this contin"])
+ assert_equal(expected_output, output)
+
+ def test_message_can_be_forced_to_be_one_line(self):
+ message = "This is 16 characters long"
+ output = self.s.message(message, single_line=True)
+ assert_equal("This is 16 charact", output)
+
+ def test_multi_message_allows_multiple_messages(self):
+ messages = "this is a test for now".split()
+ output = self.s.multi_message(messages)
+ assert_equal("this\nis\na\ntest", output)
+
+ def test_multi_message_truncates_a_long_line(self):
+ messages = ["Hi", "This is 16 characters long"]
+ output = self.s.multi_message(messages)
+ assert_equal("Hi\nThis is 16 charact", output)
+
+ def test_scroll_message_lists_all_scrolled_messages(self):
+ message = "This is 16 characters long"
+ output = self.s.scroll_message(message)
+
+ assert_equal(len(output), 9)
+ assert_equal(output[0], "This is 16 charact")
+ assert_equal(output[-1], "16 characters long")
diff --git a/pool/shard009/Python/0086576_views.py b/pool/shard009/Python/0086576_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..020510d87b2ec5539047ae3e3056c2479ce49911
--- /dev/null
+++ b/pool/shard009/Python/0086576_views.py
@@ -0,0 +1,17 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+from django.http import HttpResponse
+from django.template.context import Context, RequestContext
+from django.shortcuts import render_to_response, redirect
+from django.conf import settings
+from django.contrib.auth.models import User
+
+def profile(request):
+ if request.method == "POST":
+ x = request.POST.get('username',"blah!!")
+ users = User.objects.get(username=x)
+ username = users[0].password
+ else:
+ username = "blah!!"
+ return render_to_response("example.html", locals(), context_instance = RequestContext(request))
diff --git a/pool/shard009/Python/0086579_api.py b/pool/shard009/Python/0086579_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f2e4122ece929224ba709ae6314495d647cb4a7
--- /dev/null
+++ b/pool/shard009/Python/0086579_api.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+'''
+Netease Music API
+
+Created on 2017-02-19
+@author: Mellcap
+'''
+import requests
+import json
+
+from mellplayer.utils.encrypt_utils import encrypted_request
+from mellplayer.mell_logger import mell_logger
+
+
+class Netease(object):
+
+ def __init__(self):
+ self.playlist_categories = []
+
+ def _request(self, url, method='GET', is_raw=True, data=None):
+ '''
+ 对requests简单封装
+ '''
+ headers = {'appver': '2.0.2', 'Referer': 'http://music.163.com'}
+ if method == 'GET':
+ result = requests.get(url=url, headers=headers)
+ elif method == 'POST' and data:
+ result = requests.post(url=url, data=data, headers=headers)
+ # if request failed, return False
+ if not result.ok:
+ return False
+ result.encoding = 'UTF-8'
+ if is_raw:
+ return json.loads(result.text)
+ return result.text
+
+ def playlist_categories(self):
+ '''
+ 分类歌单
+ http://music.163.com/discover/playlist/
+ '''
+ url = 'http://music.163.com/discover/playlist/'
+ result = self._request(url)
+ return result
+
+ def category_playlists(self, category='流行', offset=0, limit=50, order='hot', total='false'):
+ '''
+ 分类详情
+ http://music.163.com/api/playlist/list?cat=流行&order=hot&offset=0&total=false&limit=50
+ '''
+ url = 'http://music.163.com/api/playlist/list?cat=%s&order=%s&offset=%s&total=%s&limit=%s' % (category, order, offset, total, limit)
+ result = self._request(url)
+ return result
+
+ def playlist_detail(self, playlist_id):
+ '''
+ 歌单详情
+ http://music.163.com/api/playlist/detail?id=xxx
+ '''
+ url = 'http://music.163.com/api/playlist/detail?id=%s' % playlist_id
+ result = self._request(url)
+ return result
+
+
+ def song_detail(self, song_ids):
+ '''
+ 歌曲详情
+ http://music.163.com/api/song/detail?ids=[xxx, xxx]
+ '''
+ url = 'http://music.163.com/api/song/detail?ids=%s' % song_ids
+ result = self._request(url)
+ return result
+
+ def song_detail_new(self, song_ids):
+ url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
+ data = {'ids': song_ids, 'br': 320000, 'csrf_token': ''}
+ data = encrypted_request(data)
+ result = self._request(url, method="POST", data=data)
+ return result
+
+
+ def lyric_detail(self, song_id):
+ '''
+ 歌词详情
+ http://music.163.com/api/song/lyric?os=osx&id=xxx&lv=-1&kv=-1&tv=-1
+ '''
+ url = 'http://music.163.com/api/song/lyric?os=osx&id=%s&lv=-1&kv=-1&tv=-1' % song_id
+ result = self._request(url)
+ return result
+
+
+ def parse_info(self, data, parse_type):
+ '''
+ 解析信息
+ '''
+ res = None
+ if parse_type == 'category_playlists':
+ res = [d['id'] for d in data['playlists']]
+ elif parse_type == 'playlist_detail':
+ tracks = data['result']['tracks']
+ playlist_ids = [t['id'] for t in tracks]
+ playlist_detail = {t['id']: {
+ 'song_id': t['id'],
+ 'song_name': t['name'],
+ 'song_url': t['mp3Url'],
+ 'song_artists': ' & '.join(map(lambda a: a['name'], t['artists']))
+ } for t in tracks}
+ res = (playlist_ids, playlist_detail)
+ elif parse_type == 'lyric_detail':
+ if 'lrc' in data:
+ res = {
+ 'lyric': data['lrc']['lyric']
+ }
+ else:
+ res = {
+ 'lyric': 'no_lyric'
+ }
+ elif parse_type == 'song_detail_new':
+ res = {d['id']: {
+ 'song_url': d['url'],
+ 'song_br': d['br']
+ } for d in data['data']}
+ return res
+
+
diff --git a/pool/shard009/Python/0086587_setup.py b/pool/shard009/Python/0086587_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..12831d03e6638adec9b238b89f19be63ac79d9aa
--- /dev/null
+++ b/pool/shard009/Python/0086587_setup.py
@@ -0,0 +1,19 @@
+from setuptools import setup, find_packages
+
+version = __import__('mailchimp').__version__
+
+setup(
+ name = 'django-mailchimp',
+ version = version,
+ description = 'Mailchimp wrapper for Django, using Mailchimp API 1.3',
+ author = 'Jonas Obrist et al.',
+ url = 'http://github.com/divio/django-mailchimp',
+ packages = find_packages(),
+ zip_safe=False,
+ package_data={
+ 'mailchimp': [
+ 'templates/mailchimp/*.html',
+ 'locale/*/LC_MESSAGES/*',
+ ],
+ },
+)
diff --git a/pool/shard009/Python/0086589_build.py b/pool/shard009/Python/0086589_build.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5d738f5887d8092323ad5f089135cb272279a3e
--- /dev/null
+++ b/pool/shard009/Python/0086589_build.py
@@ -0,0 +1,79 @@
+#
+# This file is part of Mapnik (c++ mapping toolkit)
+#
+# Copyright (C) 2015 Artem Pavlenko
+#
+# Mapnik 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 2.1 of the License, or (at your option) any later version.
+#
+# This library 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 library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+#
+#
+
+Import ('env')
+
+can_build = False
+
+if env.get('BOOST_LIB_VERSION_FROM_HEADER'):
+ boost_version_from_header = int(env['BOOST_LIB_VERSION_FROM_HEADER'].split('_')[1])
+ if boost_version_from_header >= 56:
+ can_build = True
+
+if not can_build:
+ print 'WARNING: skipping building the optional geojson datasource plugin which requires boost >= 1.56'
+else:
+
+ Import ('plugin_base')
+
+ PLUGIN_NAME = 'geojson'
+
+ plugin_env = plugin_base.Clone()
+
+ plugin_sources = Split(
+ """
+ %(PLUGIN_NAME)s_datasource.cpp
+ %(PLUGIN_NAME)s_featureset.cpp
+ %(PLUGIN_NAME)s_index_featureset.cpp
+ %(PLUGIN_NAME)s_memory_index_featureset.cpp
+
+ """ % locals()
+ )
+
+ # Link Library to Dependencies
+ libraries = []
+ libraries.append('mapnik-json')
+
+ if env['PLUGIN_LINKING'] == 'shared':
+ libraries.append('boost_system%s' % env['BOOST_APPEND'])
+ libraries.insert(0,env['MAPNIK_NAME'])
+ libraries.append(env['ICU_LIB_NAME'])
+
+ TARGET = plugin_env.SharedLibrary('../%s' % PLUGIN_NAME,
+ SHLIBPREFIX='',
+ SHLIBSUFFIX='.input',
+ source=plugin_sources,
+ LIBS=libraries)
+
+ # if the plugin links to libmapnik ensure it is built first
+ Depends(TARGET, env.subst('../../../src/%s' % env['MAPNIK_LIB_NAME']))
+ Depends(TARGET, env.subst('../../../src/json/libmapnik-json${LIBSUFFIX}'))
+
+ if 'uninstall' not in COMMAND_LINE_TARGETS:
+ env.Install(env['MAPNIK_INPUT_PLUGINS_DEST'], TARGET)
+ env.Alias('install', env['MAPNIK_INPUT_PLUGINS_DEST'])
+
+ plugin_obj = {
+ 'LIBS': libraries,
+ 'SOURCES': plugin_sources,
+ }
+
+ Return('plugin_obj')
diff --git a/pool/shard009/Python/0086592_test_LPDQ.py b/pool/shard009/Python/0086592_test_LPDQ.py
new file mode 100644
index 0000000000000000000000000000000000000000..977cb5d6325068a9105432f610b6a1804784385d
--- /dev/null
+++ b/pool/shard009/Python/0086592_test_LPDQ.py
@@ -0,0 +1,106 @@
+from pyns.engine import TransmissionMedium
+from pyns.phy import PHYLayer
+from pyns.protocols import LPDQNode, LPDQBaseStation
+import simpy
+from pyns.utility.random_mock import RandomMock
+
+def simpy_LPDQ(env, nodes, bs):
+ # using the example in paper
+ # http://ieeexplore.ieee.org/xpls/icp.jsp?arnumber=7457611
+ # setting up the random seeds
+ nodes[0].random = RandomMock([0, 0, 0])
+ nodes[1].random = RandomMock([0, 0, 2])
+ nodes[2].random = RandomMock([0, 1, 1])
+ nodes[3].random = RandomMock([0, 1, 0])
+ nodes[4].random = RandomMock([1])
+ nodes[5].random = RandomMock([2, 0])
+ nodes[6].random = RandomMock([2, 2])
+
+ for i in range(7):
+ nodes[i].send("", nodes[i].MTU)
+
+ def on_receive(packet):
+ payload = packet.payload
+ id = packet.id
+ if type(payload) == str:
+ if id == 5:
+ assert abs(env.now - 1.8) < 0.1
+ elif id == 6:
+ assert abs(env.now - 3.8) < 0.1
+ elif id == 7:
+ assert abs(env.now - 4.8) < 0.1
+ elif id == 1:
+ assert abs(env.now - 5.8) < 0.1
+ elif id == 2:
+ assert abs(env.now - 6.8) < 0.1
+ elif id == 4:
+ assert abs(env.now - 7.8) < 0.1
+ elif id == 3:
+ assert abs(env.now - 8.8) < 0.1
+
+ bs.on_receive += on_receive
+
+ yield env.timeout(10)
+
+def test_LPDQ():
+ env = simpy.Environment()
+ rates = [30]
+ slot_t = 0.1
+ feedback_t = 0.1
+
+ random_list = range(10)
+
+ t = TransmissionMedium(env)
+ bs = LPDQBaseStation(0, env, 0, 3, rates=rates, jitter_range = 0.0001, feedback_t = feedback_t, slot_t = slot_t)
+ t.add_device(bs)
+ nodes = []
+ TOTAL = 10
+ for i in range(1, TOTAL + 1):
+ node = LPDQNode(i, env, feedback_t = feedback_t, slot_t = slot_t, m=3, rates = rates, guard = 0.01, seed = i, jitter_range = 0.001)
+ t.add_device(node)
+ nodes.append(node)
+ env.process(simpy_LPDQ(env, nodes, bs))
+
+ env.run(until=20)
+
+
+def LPDQ_path_loss(env, node, bs):
+ # the first time it will have a packet lost
+ # it will wait till next frame and try to send it
+
+ def on_receive(packet):
+ payload = packet.payload
+ id = packet.id
+ if type(payload) == str:
+ assert abs(env.now -2.8) < 0.1
+
+ bs.on_receive += on_receive
+
+ node.send("", node.MTU)
+ yield env.timeout(10)
+
+def test_LPDQ_loss():
+ env = simpy.Environment()
+ rates = [30]
+ slot_t = 0.1
+ feedback_t = 0.1
+
+ # need to set up transmission medium for this one to simulate the path loss
+ layer = PHYLayer(120, 10000, 1) # the details doesn't matter as random mock will be used here
+ t = TransmissionMedium(env, layer=layer)
+ bs = LPDQBaseStation(0, env, 0, 3, rates=rates, jitter_range = 0.0001, feedback_t = feedback_t, slot_t = slot_t)
+ t.add_device(bs)
+ bs.random = RandomMock([0])
+
+ node = LPDQNode(1, env, feedback_t = feedback_t, slot_t = slot_t, m=3, rates = rates, guard = 0.01, seed = 1, jitter_range = 0.001)
+ node.random = RandomMock([0, 1, 0])
+
+ t.add_device(node)
+
+ env.process(LPDQ_path_loss(env, node, bs))
+
+ env.run(until=10)
+
+if __name__ == "__main__":
+ test_LPDQ()
+ test_LPDQ_loss()
diff --git a/pool/shard009/Python/0086593_Simple_POST.py b/pool/shard009/Python/0086593_Simple_POST.py
new file mode 100644
index 0000000000000000000000000000000000000000..834d2bf4b08eb5d8849d028a696394c36b5e2711
--- /dev/null
+++ b/pool/shard009/Python/0086593_Simple_POST.py
@@ -0,0 +1,29 @@
+#!/usr/bin/python
+import socket
+import sys
+import time
+import os
+
+# create couple HOST (IP address), PORT
+HOST,PORT = sys.argv[1],80
+# the send request
+request = 'POST /post_test/post_test_2 HTTP/1.1 \r\nContent-Type: text/plain; \r\nContent-Length: 12 \r\n\r\nHello World!'
+correctAck = 'HTTP/1.1 200 OK\\r\\n'
+correctAnswer = 'Hello World!'
+# create the socket
+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+# connection to the server
+sock.connect((HOST,PORT))
+
+sock.send(bytes(request,'UTF-8'))
+
+# receive the server answer
+data = sock.recv(1024)
+
+# close the socket
+sock.close()
+
+if(correctAck in str(data) and correctAnswer in str(data)):
+ sys.exit(os.EX_OK)
+else:
+ sys.exit(os.EX_SOFTWARE)
diff --git a/pool/shard009/Python/0086598_initializers.py b/pool/shard009/Python/0086598_initializers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f88c483e5c92fb2f2b6e7db5d7f8931f51d6b8b2
--- /dev/null
+++ b/pool/shard009/Python/0086598_initializers.py
@@ -0,0 +1,47 @@
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import numpy as np
+import tensorflow as tf
+import math
+
+
+def identity_initializer(scale = 1.0):
+
+ def _initializer(shape, dtype=tf.float32, partition_info=None):
+
+ identity = None
+ normal_fill = tf.truncated_normal(shape, stddev=0.01)
+ if len(shape) == 1:
+ identity = tf.constant(0., dtype=dtype, shape=shape)
+ elif len(shape) == 2 and shape[0] == shape[1]:
+ identity = tf.constant(scale*np.identity(shape[0], dtype))
+ elif len(shape) == 4 and shape[2] == shape[3]:
+ array = np.zeros(shape, dtype=float)
+ cx, cy = shape[0]/2, shape[1]/2
+ for i in range(shape[2]):
+ array[cx, cy, i, i] = 1
+ identity = tf.constant(scale*array, dtype=dtype)
+ else:
+ identity = tf.eye(shape[1], batch_shape=[shape[0]])
+
+ return tf.maximum(identity, normal_fill)
+ return _initializer
+
+
+
+
+def orthogonal_initializer(scale = 1.1):
+ ''' From Lasagne and Keras. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
+ '''
+
+ def _initializer(shape, dtype=tf.float32, partition_info=None):
+ flat_shape = (shape[0], np.prod(shape[1:]))
+ a = np.random.normal(0.0, 1.0, flat_shape)
+ u, _, v = np.linalg.svd(a, full_matrices=False)
+ # pick the one with the correct shape
+ q = u if u.shape == flat_shape else v
+ q = q.reshape(shape) #this needs to be corrected to float32
+ return tf.constant(scale * q[:shape[0], :shape[1]], dtype=tf.float32)
+ return _initializer
\ No newline at end of file
diff --git a/pool/shard009/Python/0086599_test_utils.py b/pool/shard009/Python/0086599_test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..70f89829d9c5fe7c3ccf87ce94210d93a40014c1
--- /dev/null
+++ b/pool/shard009/Python/0086599_test_utils.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+
+import sys
+import os
+import pytest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../src"))
+
+from epicslide import utils
+
+
+def test_get_path_url_relative():
+ u = utils.get_path_url('/plop', relative=True)
+ assert u == '/plop'
diff --git a/pool/shard009/Python/0086603_test_list.py b/pool/shard009/Python/0086603_test_list.py
new file mode 100644
index 0000000000000000000000000000000000000000..295f08679c3eb95187c0d580dcb7a13f76261e92
--- /dev/null
+++ b/pool/shard009/Python/0086603_test_list.py
@@ -0,0 +1,33 @@
+import pytest
+
+import pandas as pd
+from pandas.tests.extension.list.array import (
+ ListArray,
+ ListDtype,
+ make_data,
+)
+
+
+@pytest.fixture
+def dtype():
+ return ListDtype()
+
+
+@pytest.fixture
+def data():
+ """Length-100 ListArray for semantics test."""
+ data = make_data()
+
+ while len(data[0]) == len(data[1]):
+ data = make_data()
+
+ return ListArray(data)
+
+
+def test_to_csv(data):
+ # https://github.com/pandas-dev/pandas/issues/28840
+ # array with list-likes fail when doing astype(str) on the numpy array
+ # which was done in to_native_types
+ df = pd.DataFrame({"a": data})
+ res = df.to_csv()
+ assert str(data[0]) in res
diff --git a/pool/shard009/Python/0086604_c_form.py b/pool/shard009/Python/0086604_c_form.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b64f8100fe07ba65645551886833c6ff684549f
--- /dev/null
+++ b/pool/shard009/Python/0086604_c_form.py
@@ -0,0 +1,70 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe.utils import flt
+from frappe import _
+from frappe.model.document import Document
+
+class CForm(Document):
+ def validate(self):
+ """Validate invoice that c-form is applicable
+ and no other c-form is received for that"""
+
+ for d in self.get('invoices'):
+ if d.invoice_no:
+ inv = frappe.db.sql("""select c_form_applicable, c_form_no from
+ `tabSales Invoice` where name = %s and docstatus = 1""", d.invoice_no)
+
+ if inv and inv[0][0] != 'Yes':
+ frappe.throw(_("C-form is not applicable for Invoice: {0}").format(d.invoice_no))
+
+ elif inv and inv[0][1] and inv[0][1] != self.name:
+ frappe.throw(_("""Invoice {0} is tagged in another C-form: {1}.
+ If you want to change C-form no for this invoice,
+ please remove invoice no from the previous c-form and then try again"""\
+ .format(d.invoice_no, inv[0][1])))
+
+ elif not inv:
+ frappe.throw(_("Row {0}: Invoice {1} is invalid, it might be cancelled / does not exist. \
+ Please enter a valid Invoice".format(d.idx, d.invoice_no)))
+
+ def on_update(self):
+ """ Update C-Form No on invoices"""
+ self.set_total_invoiced_amount()
+
+ def on_submit(self):
+ self.set_cform_in_sales_invoices()
+
+ def before_cancel(self):
+ # remove cform reference
+ frappe.db.sql("""update `tabSales Invoice` set c_form_no=null where c_form_no=%s""", self.name)
+
+ def set_cform_in_sales_invoices(self):
+ inv = [d.invoice_no for d in self.get('invoices')]
+ if inv:
+ frappe.db.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s where name in (%s)""" %
+ ('%s', '%s', ', '.join(['%s'] * len(inv))), tuple([self.name, self.modified] + inv))
+
+ frappe.db.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s
+ where name not in (%s) and ifnull(c_form_no, '') = %s""" %
+ ('%s', ', '.join(['%s']*len(inv)), '%s'), tuple([self.modified] + inv + [self.name]))
+ else:
+ frappe.throw(_("Please enter atleast 1 invoice in the table"))
+
+ def set_total_invoiced_amount(self):
+ total = sum([flt(d.grand_total) for d in self.get('invoices')])
+ frappe.db.set(self, 'total_invoiced_amount', total)
+
+ def get_invoice_details(self, invoice_no):
+ """ Pull details from invoices for referrence """
+ if invoice_no:
+ inv = frappe.db.get_value("Sales Invoice", invoice_no,
+ ["posting_date", "territory", "base_net_total", "base_grand_total"], as_dict=True)
+ return {
+ 'invoice_date' : inv.posting_date,
+ 'territory' : inv.territory,
+ 'net_total' : inv.base_net_total,
+ 'grand_total' : inv.base_grand_total
+ }
diff --git a/pool/shard009/Python/0086606_setup.py b/pool/shard009/Python/0086606_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3bd3887eb98ee0e1c44f34ae6c2df3aa2ab0254
--- /dev/null
+++ b/pool/shard009/Python/0086606_setup.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+
+import os
+import sys
+import ast
+import re
+import subprocess
+from setuptools import find_packages
+import functools
+import fnmatch
+
+
+# get version number
+# avoid importing from package
+version_re = re.compile(r'__version__\s+=\s+(.*)')
+with open('butterflow/version.py', 'rb') as f:
+ version = str(ast.literal_eval(version_re.search(
+ f.read().decode('utf-8')).group(1)))
+
+# directories
+rootdir = os.path.abspath(os.sep)
+topdir = os.path.join(os.path.dirname(os.path.realpath(__file__)))
+pkgdir = os.path.join(topdir, 'butterflow')
+dependsdir = os.path.join(topdir, 'depends')
+
+# are we building a development version?
+building = True
+for x in sys.argv:
+ if x.startswith('build') or x.startswith('develop'):
+ building = False
+is_devbuild = ('dev' in version or 'a' in version) and not building
+
+# make a list with no duplicates
+# does not maintain ordering
+def mklist(*items):
+ s = set([])
+ for x in items:
+ if isinstance(x, list):
+ for y in x:
+ s.add(y)
+ elif x is not None:
+ s.add(x)
+ return list(s)
+
+
+py_ver_X = sys.version_info.major
+py_ver_Y = sys.version_info.minor
+py_ver = '{}.{}'.format(py_ver_X, py_ver_Y)
+
+homebrew_prefix = None
+homebrew_site_pkgs = None
+try:
+ homebrew_prefix = subprocess.Popen(['brew', '--prefix'],
+ stdout=subprocess.PIPE)
+ homebrew_prefix = homebrew_prefix.stdout.read().strip()
+except Exception:
+ # fall back to environment variable if brew command is not found
+ if 'HOMEBREW_PREFIX' in os.environ:
+ homebrew_prefix = os.environ['HOMEBREW_PREFIX']
+if homebrew_prefix is not None:
+ homebrew_site_pkgs = os.path.join(homebrew_prefix, 'lib/python{}/'
+ 'site-packages/'.format(py_ver))
+ # Because some formulae provide python bindings, homebrew builds bindings
+ # against the first python (and python-config) in PATH (check
+ # `which python`).
+ #
+ # Homebrew site-packages should preceed all others on sys.path
+ # if it exists:
+ sys.path.insert(1, homebrew_site_pkgs)
+
+cflags = ['-std=c11'] # c compilation flags
+linkflags = [] # linker flags
+cxxflags = []
+
+is_win = sys.platform.startswith('win')
+is_osx = sys.platform.startswith('darwin')
+is_nix = sys.platform.startswith('linux')
+
+# should we use cxfreeze?
+use_cx_freeze = False
+if is_win and 'build_exe' in sys.argv:
+ try:
+ # cxfreeze extends setuptools and should be imported after it
+ from cx_Freeze import setup, Executable
+ from distutils.core import Extension # cxfreeze builds upon distutils
+ use_cx_freeze = True
+ except ImportError as exc:
+ sys.exit(exc)
+else:
+ from setuptools import setup, Extension, find_packages
+
+# global cflags
+if is_devbuild:
+ cflags.append('-Wall')
+ cflags.append('-g') # turn off debugging symbols for release
+ cflags.extend(['-O0', '-fbuiltin', '-fdiagnostics-show-option'])
+
+# disable warnings that are safe to ignore
+cflags.extend(['-Wno-unused-variable', '-Wno-unused-function'])
+if is_osx:
+ cflags.extend(['-Wno-shorten-64-to-32', '-Wno-overloaded-virtual',
+ '-Wno-#warnings'])
+else:
+ cflags.extend(['-Wno-cpp'])
+
+# set cxxflags, remove c only options
+for x in cflags:
+ if x != '-std=c11' and \
+ x != '-Wstrict-prototypes':
+ cxxflags.append(x)
+
+# global link flags
+if is_nix:
+ linkflags.extend(['-shared', '-Wl,--export-dynamic'])
+elif is_osx:
+ # Don't explicity link against the system python on OSX to prevent
+ # segfaults arising from modules being built with one python (i.e. system
+ # python) and imported from a foreign python (i.e. brewed python).
+ #
+ # See: https://github.com/Homebrew/homebrew/blob/master/share/doc/
+ # homebrew/Common-Issues.md#python-segmentation-fault-11-on-import-
+ # some_python_module
+ #
+ # Building modules with `-undefined dynamic_lookup` instead of an explict
+ # link allows symbols to be resolved at import time. `otool -L .so`
+ # shouldn't mention Python.
+ # See: https://github.com/Homebrew/homebrew-science/pull/1886
+ linkflags.append('-Wl,-undefined,dynamic_lookup')
+ linkflags.extend(['-arch', 'x86_64'])
+
+avinfo_ext = Extension('butterflow.avinfo', extra_compile_args=cflags,
+ extra_link_args=linkflags,
+ libraries=['avcodec', 'avformat', 'avutil'],
+ sources=[os.path.join(pkgdir, 'avinfo.c')],
+ language='c')
+
+# opencl args
+cl_lib = None
+cl_linkflags = None
+if is_osx:
+ cl_linkflags = ['-framework', 'OpenCL']
+else:
+ cl_lib = ['OpenCL']
+
+old_linkflags = linkflags
+if cl_linkflags:
+ linkflags.extend(cl_linkflags)
+
+ocl_ext = Extension('butterflow.ocl', extra_compile_args=cxxflags,
+ extra_link_args=linkflags,
+ libraries=mklist(cl_lib, 'opencv_core', 'opencv_ocl'),
+ sources=[os.path.join(pkgdir, 'ocl.cpp')], language='c++')
+
+linkflags = old_linkflags
+
+# numpy args
+np_includes = None
+if is_osx:
+ if homebrew_prefix is not None:
+ # Homebrew opencv uses a brewed numpy by default but it's possible for
+ # a user to their own or the system one if the --without-brewed-numpy
+ # option is used.
+ #
+ # Note: usually all pythonX.Y packages with headers are placed in
+ # /usr/include/pythonX.Y/ or /usr/local/include/, but
+ # homebrew policy is to put them in site-packages
+ np_includes = os.path.join(homebrew_site_pkgs, 'numpy/core/include')
+ else:
+ # fallback to the system's numpy
+ np_includes = '/System/Library/Frameworks/Python.framework/Versions/'\
+ '{}/Extras/lib/python/numpy/core/include'.format(py_ver)
+
+# opencv-ndarray-conversion args
+nddir = os.path.join(dependsdir, 'opencv-ndarray-conversion')
+nd_includes = os.path.join(nddir, 'include')
+
+motion_ext = Extension('butterflow.motion',
+ extra_compile_args=cxxflags,
+ extra_link_args=linkflags,
+ include_dirs=mklist(nd_includes, np_includes),
+ libraries=['opencv_core', 'opencv_ocl',
+ 'opencv_imgproc'],
+ sources=[os.path.join(pkgdir, 'motion.cpp'),
+ os.path.join(nddir, 'src', 'conversion.cpp')],
+ language='c++')
+
+# shared args
+setup_kwargs = {
+ 'name': 'butterflow',
+ 'packages': find_packages(exclude=['tests']),
+ 'ext_modules': [avinfo_ext, ocl_ext, motion_ext],
+ 'version': version,
+ 'author': 'Duong Pham',
+ 'author_email': 'dthpham@gmail.com',
+ 'url': 'https://github.com/dthpham/butterflow',
+ 'download_url': 'http://srv.dthpham.me/butterflow/butterflow-{}.tar.gz'.
+ format(version),
+ 'description': 'Makes motion interpolated and fluid slow motion videos',
+ 'keywords': ['motion interpolation', 'slow motion', 'slowmo',
+ 'smooth motion'],
+ 'entry_points': {'console_scripts': ['butterflow = butterflow.cli:main']},
+ 'test_suite': 'tests'
+}
+
+setup = functools.partial(setup, **setup_kwargs)
+
+if use_cx_freeze:
+ additional_files = []
+ with open('include_files.txt', 'r') as f:
+ for line in f:
+ line = line.rstrip()
+ if line.startswith('#'):
+ continue
+ elif line.startswith('prefix'):
+ prefix = line.split('=')[1]
+ continue
+ else:
+ pattern = line
+ for file in os.listdir(prefix):
+ if fnmatch.fnmatch(file, pattern):
+ filename = file
+ relpath = os.path.relpath(os.path.join(prefix, filename))
+ additional_files.append((relpath, filename))
+ build_exe_options = {
+ 'packages': ['butterflow'],
+ 'includes': ['numpy.core._methods', 'numpy.lib.format'], # Bug: https://stackoverflow.com/q/41735413
+ 'include_msvcr': True,
+ 'excludes': ['copyreg', 'distutils', 'email', 'future', 'pydoc_data',
+ 'setuptools', 'test', 'tests', 'test', 'Tkinter'],
+ 'include_files': additional_files,
+ # 'replace_paths': [("*", "")],
+ }
+ executables = [
+ Executable(script='butterflow/__main__.py',
+ # initScript=os.path.abspath('butterflow/console.py'),
+ base=None,
+ targetName='butterflow.exe',
+ icon='butterflow.ico',
+ copyright='Copyright (c) 2017 Duong Pham')
+ ]
+ setup(options={'build_exe': build_exe_options}, executables=executables)
+else:
+ setup()
diff --git a/pool/shard009/Python/0086611_message.py b/pool/shard009/Python/0086611_message.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc1b1932b13f55fe39666dd67b2557ed67cebb0
--- /dev/null
+++ b/pool/shard009/Python/0086611_message.py
@@ -0,0 +1,63 @@
+import json
+import contextlib
+
+from . import parsers, tool
+
+
+class MessageWrapper(object):
+ """
+ To provide a more easy-use interface for websocket handler writers.
+ """
+
+ def __init__(self, consumer, content=None):
+
+ # If no content provided, use what consumer holds
+ if content is None:
+ content = json.loads(consumer.message.content['text'])
+
+ try:
+ self.handler_name, self.data = parsers.decode(content)
+ except parsers.WebsocketDataDecodeError as e:
+ self.handler_name, self.data = '__error__', str(e)
+
+ self.user = consumer.message.user
+ self.__consumer = consumer
+ self.__broadcaster = tool.Broadcaster(self.handler_name)
+
+ @property
+ def packed_data(self):
+ """
+ Returns the original version of incoming data.
+ """
+ return parsers.encode(self.handler_name, self.data)
+
+ def reply(self, data):
+ """
+ A shortcut for replying.
+ """
+ wrapped = parsers.encode(self.handler_name, data)
+
+ self.__consumer.send(wrapped)
+
+ def __getattribute__(self, name):
+ """
+ To avoid redundancy, message wrapper simply proxies the methods
+ specified in BROADCAT_FUNCTION_NAMES to its broadcaster.
+ """
+ if name in tool.BROADCAST_FUNCTION_NAMES:
+ return getattr(self.__broadcaster, name)
+
+ return object.__getattribute__(self, name)
+
+ @contextlib.contextmanager
+ def patch_handler_name(self, handler_name):
+ """
+ A context manager to provide convenience for temporary handler name
+ modification.
+ """
+
+ old = self.handler_name
+
+ self.handler_name = self.__broadcaster.handler_name = handler_name
+ yield
+ self.handler_name = self.__broadcaster.handler_name = old
diff --git a/pool/shard009/Python/0086612_init__.py b/pool/shard009/Python/0086612_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1259b8c604db6e2dd8bddef6d0a3bfd2c41e7651
--- /dev/null
+++ b/pool/shard009/Python/0086612_init__.py
@@ -0,0 +1,139 @@
+# -*- coding: utf-8 -*-
+"""Loads helper utility modules and functions."""
+from __future__ import (absolute_import, division, print_function,
+ unicode_literals, with_statement)
+
+import os
+import shutil
+import ssl
+import warnings
+
+import backoff
+
+from watchmaker.utils import urllib
+
+
+def scheme_from_uri(uri):
+ """Return a scheme from a parsed uri."""
+ # Handle case where path does not contain a scheme
+ # i.e. '/abspath/foo' or 'relpath/foo'
+ # Do not test `if parts.scheme` because of how urlparse handles Windows
+ # file paths -- i.e. 'C:\\foo' => scheme = 'c' :(
+ return uri.scheme if '://' in urllib.parse.urlunparse(uri) else 'file'
+
+
+def uri_from_filepath(filepath):
+ """Return a URI compatible with urllib, handling URIs and file paths."""
+ parts = urllib.parse.urlparse(filepath)
+ scheme = scheme_from_uri(parts)
+
+ if scheme != 'file':
+ # Return non-file paths unchanged
+ return filepath
+
+ # Expand relative file paths and convert them to uri-style
+ path = urllib.request.pathname2url(os.path.abspath(os.path.expanduser(
+ ''.join([x for x in [parts.netloc, parts.path] if x]))))
+
+ return urllib.parse.urlunparse((scheme, '', path, '', '', ''))
+
+
+def basename_from_uri(uri):
+ """Return the basename/filename/leaf part of a URI."""
+ # Do not split on '/' and return the last part because that will also
+ # include any query in the uri. Instead, parse the uri.
+ return os.path.basename(urllib.parse.urlparse(uri).path)
+
+
+@backoff.on_exception(backoff.expo, urllib.error.URLError, max_tries=5)
+def urlopen_retry(uri):
+ """Retry urlopen on exception."""
+ kwargs = {}
+ try:
+ # trust the system's default CA certificates
+ # proper way for 2.7.9+ on Linux
+ if uri.startswith("https://"):
+ kwargs['context'] = ssl.create_default_context(
+ ssl.Purpose.SERVER_AUTH
+ )
+ except AttributeError:
+ pass
+
+ # pylint: disable=consider-using-with
+ return urllib.request.urlopen(uri, **kwargs)
+
+
+def copytree(src, dst, force=False, **kwargs):
+ r"""
+ Copy OS directory trees from source to destination.
+
+ Args:
+ src: (:obj:`str`)
+ Source directory tree to be copied.
+ (*Default*: None)
+
+ dst: (:obj:`str`)
+ Destination where directory tree is to be copied.
+ (*Default*: None)
+
+ force: (:obj:`bool`)
+ Whether to delete destination prior to copy.
+ (*Default*: ``False``)
+
+ """
+ if force and os.path.exists(dst):
+ shutil.rmtree(dst)
+
+ shutil.copytree(src, dst, **kwargs)
+
+
+def config_none_deprecate(check_value, log):
+ r"""
+ Warn if variable is the string 'None' rather than Pythonic `None`.
+
+ If it is the string 'None', this warns and returns Pythonic `None`.
+ Otherwise, the variable is returned unchanged.
+
+ Args:
+ check_value: (:obj:`str`)
+ Variable to be checked for string 'None' (case-insenstive).
+
+ log: (:obj:`logging.Logger`)
+ Logger where deprecation warning will be made.
+
+ """
+ value = clean_none(check_value)
+
+ if check_value and value is None:
+ deprecate_msg = (
+ 'Use of "None" (string) as a config value is deprecated. Use '
+ '`null` instead.')
+ log.warn(deprecate_msg)
+ warnings.warn(deprecate_msg, DeprecationWarning)
+
+ return value
+
+
+def clean_none(value):
+ """Convert string 'None' to None."""
+ if str(value).lower() == 'none':
+ return None
+
+ return value
+
+
+def copy_subdirectories(src_dir, dest_dir, log=None):
+ """Copy subdirectories within given src dir into dest dir."""
+ for subdir in next(os.walk(src_dir))[1]:
+ if (
+ not subdir.startswith('.') and
+ not os.path.exists(os.sep.join((dest_dir, subdir)))
+ ):
+ copytree(
+ os.sep.join((src_dir, subdir)),
+ os.sep.join((dest_dir, subdir))
+ )
+ if log:
+ log.info('Copied from %s to %s',
+ os.sep.join((src_dir, subdir)),
+ os.sep.join((dest_dir, subdir)))
diff --git a/pool/shard009/Python/0086613_test_migration_throttling.py b/pool/shard009/Python/0086613_test_migration_throttling.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d983340e1a1fded87220ff32dd006bdadbd17e8
--- /dev/null
+++ b/pool/shard009/Python/0086613_test_migration_throttling.py
@@ -0,0 +1,93 @@
+import fauxfactory
+import pytest
+from widgetastic.widget import NoSuchElementException
+
+from cfme import test_requirements
+from cfme.cloud.provider.openstack import OpenStackProvider
+from cfme.fixtures.provider import rhel69_template
+from cfme.fixtures.provider import rhel7_minimal
+from cfme.fixtures.provider import ubuntu16_template
+from cfme.infrastructure.provider.rhevm import RHEVMProvider
+from cfme.infrastructure.provider.virtualcenter import VMwareProvider
+from cfme.markers.env_markers.provider import ONE_PER_TYPE
+from cfme.markers.env_markers.provider import ONE_PER_VERSION
+from cfme.v2v.migration_settings import MigrationSettings
+
+pytestmark = [
+ test_requirements.v2v,
+ pytest.mark.provider(
+ classes=[OpenStackProvider, RHEVMProvider],
+ selector=ONE_PER_VERSION,
+ required_flags=["v2v"],
+ scope="module"
+ ),
+ pytest.mark.provider(
+ classes=[VMwareProvider],
+ selector=ONE_PER_TYPE,
+ fixture_name="source_provider",
+ required_flags=["v2v"],
+ scope="module",
+ ),
+ pytest.mark.usefixtures("v2v_provider_setup"),
+]
+
+
+@pytest.mark.parametrize(
+ "mapping_data_multiple_vm_obj_single_datastore",
+ [
+ ["nfs", "nfs", [rhel7_minimal, rhel69_template, ubuntu16_template]],
+ ],
+ indirect=True,
+)
+def test_migration_throttling(
+ request, appliance, provider, mapping_data_multiple_vm_obj_single_datastore
+):
+ """
+ Polarion:
+ assignee: sshveta
+ casecomponent: V2V
+ initialEstimate: 1/4h
+ caseimportance: high
+ caseposneg: positive
+ testtype: functional
+ startsin: 5.10
+ """
+ migration_settings = MigrationSettings(appliance)
+ migration_settings.migration_throttling.set_max_migration_per_conv_host("2")
+
+ infrastructure_mapping_collection = appliance.collections.v2v_infra_mappings
+ mapping_data = mapping_data_multiple_vm_obj_single_datastore.infra_mapping_data
+ mapping = infrastructure_mapping_collection.create(**mapping_data)
+
+ migration_plan_collection = appliance.collections.v2v_migration_plans
+ migration_plan = migration_plan_collection.create(
+ name="plan_{}".format(fauxfactory.gen_alphanumeric()),
+ description="desc_{}".format(fauxfactory.gen_alphanumeric()),
+ infra_map=mapping.name,
+ vm_list=mapping_data_multiple_vm_obj_single_datastore.vm_list,
+ )
+ assert migration_plan.wait_for_state("Started")
+ request_details_list = migration_plan.get_plan_vm_list(wait_for_migration=False)
+ vms = request_details_list.read()
+
+ @request.addfinalizer
+ def _cleanup():
+ infrastructure_mapping_collection.delete(mapping)
+ request_details_list.cancel_migration(vm, confirmed=True)
+
+ conversion_host_popup = []
+ host_creds = provider.hosts.all()
+ hosts_dict = {key.name: [] for key in host_creds}
+ # Check if conversion host is shown for each VM
+ for vm in vms:
+ try:
+ popup_text = request_details_list.read_additional_info_popup(vm)
+ if popup_text['Conversion Host'] in hosts_dict:
+ conversion_host_popup.append(popup_text['Conversion Host'])
+ except NoSuchElementException:
+ # conversion host might be empty for throttled vm
+ # until it is waiting for other VM's to finish until BZ 1716283 is fixed.
+ continue
+ for conv_host in conversion_host_popup:
+ # Not more than two VM's can have same conversion host
+ assert (conversion_host_popup.count(conv_host) <= 2)
diff --git a/pool/shard009/Python/0086614_ReformulationForLoopStatements.py b/pool/shard009/Python/0086614_ReformulationForLoopStatements.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c9af7d370ba5978eac3d65a8701797c08de18f2
--- /dev/null
+++ b/pool/shard009/Python/0086614_ReformulationForLoopStatements.py
@@ -0,0 +1,219 @@
+# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
+#
+# Part of "Nuitka", an optimizing Python compiler that is compatible and
+# integrates with CPython, but also works on its own.
+#
+# 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.
+#
+""" Reformulation of for loop statements.
+
+Consult the developer manual for information. TODO: Add ability to sync
+source code comments with developer manual sections.
+
+"""
+
+from nuitka.nodes.AssignNodes import (
+ StatementAssignmentVariable,
+ StatementReleaseVariable,
+)
+from nuitka.nodes.BuiltinIteratorNodes import (
+ ExpressionAsyncIter,
+ ExpressionAsyncNext,
+ ExpressionBuiltinIter1,
+)
+from nuitka.nodes.BuiltinNextNodes import ExpressionBuiltinNext1
+from nuitka.nodes.ComparisonNodes import ExpressionComparisonIs
+from nuitka.nodes.ConditionalNodes import makeStatementConditional
+from nuitka.nodes.ConstantRefNodes import makeConstantRefNode
+from nuitka.nodes.LoopNodes import StatementLoop, StatementLoopBreak
+from nuitka.nodes.StatementNodes import StatementsSequence
+from nuitka.nodes.VariableRefNodes import ExpressionTempVariableRef
+from nuitka.nodes.YieldNodes import ExpressionYieldFromWaitable
+
+from .ReformulationAssignmentStatements import buildAssignmentStatements
+from .ReformulationTryExceptStatements import makeTryExceptSingleHandlerNode
+from .ReformulationTryFinallyStatements import makeTryFinallyStatement
+from .TreeHelpers import (
+ buildNode,
+ buildStatementsNode,
+ makeStatementsSequence,
+ makeStatementsSequenceFromStatements,
+ popBuildContext,
+ pushBuildContext,
+)
+
+
+def _buildForLoopNode(provider, node, sync, source_ref):
+ # The for loop is re-formulated according to developer manual. An iterator
+ # is created, and looped until it gives StopIteration. The else block is
+ # taken if a for loop exits normally, i.e. because of iterator
+ # exhaustion. We do this by introducing an indicator variable.
+
+ # We handle async and sync both here, leading to cases, pylint: disable=too-many-locals
+
+ source = buildNode(provider, node.iter, source_ref)
+
+ # Temporary variables, we need one for the iterator, and one for the current
+ # value.
+ temp_scope = provider.allocateTempScope("for_loop")
+
+ tmp_iter_variable = provider.allocateTempVariable(
+ temp_scope=temp_scope, name="for_iterator"
+ )
+ tmp_value_variable = provider.allocateTempVariable(
+ temp_scope=temp_scope, name="iter_value"
+ )
+
+ else_block = buildStatementsNode(
+ provider=provider,
+ nodes=node.orelse if node.orelse else None,
+ source_ref=source_ref,
+ )
+
+ if else_block is not None:
+ # Indicator variable, will end up with C bool type, and need not be released.
+ tmp_break_indicator = provider.allocateTempVariable(
+ temp_scope=temp_scope, name="break_indicator", temp_type="bool"
+ )
+
+ statements = [
+ StatementAssignmentVariable(
+ variable=tmp_break_indicator,
+ source=makeConstantRefNode(constant=True, source_ref=source_ref),
+ source_ref=source_ref,
+ )
+ ]
+ else:
+ statements = []
+
+ statements.append(StatementLoopBreak(source_ref=source_ref))
+
+ handler_body = makeStatementsSequence(
+ statements=statements, allow_none=False, source_ref=source_ref
+ )
+
+ if sync:
+ next_node = ExpressionBuiltinNext1(
+ value=ExpressionTempVariableRef(
+ variable=tmp_iter_variable, source_ref=source_ref
+ ),
+ source_ref=source_ref,
+ )
+ else:
+ next_node = ExpressionYieldFromWaitable(
+ expression=ExpressionAsyncNext(
+ value=ExpressionTempVariableRef(
+ variable=tmp_iter_variable, source_ref=source_ref
+ ),
+ source_ref=source_ref,
+ ),
+ source_ref=source_ref,
+ )
+
+ statements = (
+ makeTryExceptSingleHandlerNode(
+ tried=StatementAssignmentVariable(
+ variable=tmp_value_variable, source=next_node, source_ref=source_ref
+ ),
+ exception_name="StopIteration" if sync else "StopAsyncIteration",
+ handler_body=handler_body,
+ source_ref=source_ref,
+ ),
+ buildAssignmentStatements(
+ provider=provider,
+ node=node.target,
+ source=ExpressionTempVariableRef(
+ variable=tmp_value_variable, source_ref=source_ref
+ ),
+ source_ref=source_ref,
+ ),
+ )
+
+ pushBuildContext("loop_body")
+ statements += (
+ buildStatementsNode(provider=provider, nodes=node.body, source_ref=source_ref),
+ )
+ popBuildContext()
+
+ loop_body = makeStatementsSequence(
+ statements=statements, allow_none=True, source_ref=source_ref
+ )
+
+ cleanup_statements = [
+ StatementReleaseVariable(variable=tmp_value_variable, source_ref=source_ref),
+ StatementReleaseVariable(variable=tmp_iter_variable, source_ref=source_ref),
+ ]
+
+ if else_block is not None:
+ statements = [
+ StatementAssignmentVariable(
+ variable=tmp_break_indicator,
+ source=makeConstantRefNode(constant=False, source_ref=source_ref),
+ source_ref=source_ref,
+ )
+ ]
+ else:
+ statements = []
+
+ if sync:
+ iter_source = ExpressionBuiltinIter1(
+ value=source, source_ref=source.getSourceReference()
+ )
+ else:
+ iter_source = ExpressionYieldFromWaitable(
+ expression=ExpressionAsyncIter(
+ value=source, source_ref=source.getSourceReference()
+ ),
+ source_ref=source.getSourceReference(),
+ )
+
+ statements += (
+ # First create the iterator and store it.
+ StatementAssignmentVariable(
+ variable=tmp_iter_variable, source=iter_source, source_ref=source_ref
+ ),
+ makeTryFinallyStatement(
+ provider=provider,
+ tried=StatementLoop(loop_body=loop_body, source_ref=source_ref),
+ final=StatementsSequence(
+ statements=cleanup_statements, source_ref=source_ref
+ ),
+ source_ref=source_ref,
+ ),
+ )
+
+ if else_block is not None:
+ statements.append(
+ makeStatementConditional(
+ condition=ExpressionComparisonIs(
+ left=ExpressionTempVariableRef(
+ variable=tmp_break_indicator, source_ref=source_ref
+ ),
+ right=makeConstantRefNode(constant=True, source_ref=source_ref),
+ source_ref=source_ref,
+ ),
+ yes_branch=else_block,
+ no_branch=None,
+ source_ref=source_ref,
+ )
+ )
+
+ return makeStatementsSequenceFromStatements(*statements)
+
+
+def buildForLoopNode(provider, node, source_ref):
+ return _buildForLoopNode(provider, node, True, source_ref)
+
+
+def buildAsyncForLoopNode(provider, node, source_ref):
+ return _buildForLoopNode(provider, node, False, source_ref)
diff --git a/pool/shard009/Python/0086617_gui.py b/pool/shard009/Python/0086617_gui.py
new file mode 100644
index 0000000000000000000000000000000000000000..01ba3081ea9f6d392e90b751f398a90cd4b02b8e
--- /dev/null
+++ b/pool/shard009/Python/0086617_gui.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python
+
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library 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 library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+"""
+GUI creation utilities
+"""
+
+import os
+import unittest
+
+import fluidity.diagnostics.debug as debug
+import fluidity.diagnostics.optimise as optimise
+import fluidity.diagnostics.utils as utils
+
+def GuiDisabledByEnvironment():
+ return "DIAGNOSTICS_GUI_DISABLED" in os.environ and os.environ["DIAGNOSTICS_GUI_DISABLED"]
+
+if not GuiDisabledByEnvironment():
+ try:
+ import gobject
+ except:
+ debug.deprint("Warning: Failed to import gobject module")
+ try:
+ import gtk
+ except:
+ debug.deprint("Warning: Failed to import gtk module")
+
+def DisplayWindow(window):
+ """
+ Launch the GTK main loop to display the supplied window
+ """
+
+ window.connect("destroy", gtk.main_quit)
+ window.show()
+ gtk.main()
+
+ return
+
+def DisplayWidget(widget, width = 640, height = 480, title = None):
+ """
+ Pack the supplied widget in a simple window, and launch the GTK main loop to
+ display it
+ """
+
+ window = WindowWidget(widget, width, height, title)
+ DisplayWindow(window)
+
+ return
+
+def DisplayPlot(plot, withToolbar = True, width = 640, height = 480, title = None):
+ """
+ Generate a widget from the supplied plot, pack the supplied widget in a simple
+ window, and launch the GTK main loop to display it
+ """
+
+ widget = plot.Widget(withToolbar = withToolbar)
+ widget.show_all()
+ DisplayWidget(widget, width = width, height = height, title = title)
+
+ return
+
+def WindowWidget(widget, width = 640, height = 480, title = None):
+ """
+ Pack the supplied widget in a simple window
+ """
+
+ window = gtk.Window()
+ window.set_default_size(width, height)
+ if not title is None:
+ window.set_title(title)
+
+ window.add(widget)
+
+ return window
+
+def ComboBoxFromEntries(entries):
+ """
+ Contruct a combo box from the list of entries
+ """
+
+ comboBox = gtk.combo_box_new_text()
+ for entry in entries:
+ comboBox.append_text(entry)
+
+ return comboBox
+
+def TableFromWidgetsArray(widgets, homogeneous = False):
+ """
+ Construct a table containing the supplied array of widgets
+ (which can be ragged)
+ """
+
+ rows, columns = len(widgets), 0
+ if rows > 0:
+ if utils.CanLen(widgets[0]) and not isinstance(widgets[0], gtk.Widget):
+ columns = len(widgets[0])
+ for subWidget in widgets[1:]:
+ columns = max(columns, len(widgets))
+ else:
+ widgets = [[widget] for widget in widgets]
+ columns = 1
+
+ table = gtk.Table(rows = rows, columns = columns, homogeneous = homogeneous)
+
+ for i in range(rows):
+ for j in range(len(widgets[i])):
+ table.attach(widgets[i][j], j, j + 1, i, i + 1)
+
+ return table
+
+class guiUnittests(unittest.TestCase):
+ def testGtkSupport(self):
+ import gobject
+ import gtk
+
+ return
+
+ def testComboBoxFromEntries(self):
+ self.assertTrue(isinstance(ComboBoxFromEntries([]), gtk.ComboBox))
+
+ return
diff --git a/pool/shard009/Python/0086620_rw.py b/pool/shard009/Python/0086620_rw.py
new file mode 100644
index 0000000000000000000000000000000000000000..05765427632274aafb2ec230e86cdbde4abe944d
--- /dev/null
+++ b/pool/shard009/Python/0086620_rw.py
@@ -0,0 +1,84 @@
+from .identifier import identifier
+from .varint import varuint_decode, varuint_encode, NotEnoughDataException
+from ..exceptions import EncoderException, DecoderException
+
+
+def encode(packet):
+ """Encodes a single packet to a byte string. Returns the byte string."""
+ return _Encoder().encode(packet)
+
+
+def decode(bytes):
+ """Attempts to decode the packet from the set of bytes. If the packet
+ is not known, this function will return None."""
+ return _Decoder().decode(bytes)
+
+
+class _Decoder():
+ """Decodes a single packet off of a byte string."""
+
+ def _read_variunt(self):
+ try:
+ n, read = varuint_decode(self.buffer, self._pos)
+ self._pos = read
+ return n
+ except NotEnoughDataException:
+ raise DecoderException('invalid packet; could not read ID')
+
+ def remaining_bytes(self, meta=True):
+ """
+ Returns the remaining, unread bytes from the buffer.
+ """
+ pos, self._pos = self._pos, len(self.buffer)
+ return self.buffer[pos:]
+
+ def decode(self, bytes):
+ """
+ Decodes the packet off the byte string.
+ """
+
+ self.buffer = bytes
+ self._pos = 0
+
+ Packet = identifier.get_packet_from_id(self._read_variunt())
+
+ # unknown packets will be None from the identifier
+ if Packet is None:
+ return None
+
+ packet = Packet()
+ packet.ParseFromString(self.remaining_bytes())
+ return packet
+
+
+class _Encoder():
+ """
+ The opposite of Decoder, Encoder helps with writing a packet.
+ """
+
+ def __init__(self):
+ self.buffer = bytearray()
+
+ def _write(self, data):
+ if isinstance(data, int):
+ self.buffer.append(data)
+ else:
+ self.buffer.extend(data)
+
+ def _write_variunt(self, number):
+ varuint_encode(self._write, number)
+
+ def encode(self, packet):
+ """
+ Pushes a packet to the writer, encoding it on the internal
+ buffer.
+ """
+
+ id = identifier.get_packet_id(packet)
+ if id is None:
+ raise EncoderException('unknown packet')
+
+ self._write_variunt(id)
+ self._write(packet.SerializeToString())
+
+ return bytes(self.buffer)
diff --git a/pool/shard009/Python/0086621_uninformed_search.py b/pool/shard009/Python/0086621_uninformed_search.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f75ef273c1a38b52445e6acbc4af64189a1a30a
--- /dev/null
+++ b/pool/shard009/Python/0086621_uninformed_search.py
@@ -0,0 +1,41 @@
+
+def bfs(G, s, f):
+ """
+ Breadth-first search
+ :param G: The graph object
+ :param s: The start node
+ :param f: The goal node
+ :return: The explored set
+ """
+ explored, frontier = [], [s]
+
+ while frontier:
+ v = frontier.pop(0)
+ if v == f:
+ pass
+ else:
+ explored.append(v)
+ frontier.extend([w for w in G[v] if w not in explored])
+
+ return explored
+
+
+def dfs(G, s, f):
+ """
+ Depth-first search
+ :param G: The graph object
+ :param s: The start node
+ :param f: The goal node
+ :return: The explored set
+ """
+ explored, frontier = [], [s]
+
+ while frontier:
+ v = frontier.pop()
+ if v == f:
+ pass
+ else:
+ explored.append(v)
+ frontier.extend([w for w in G[v] if w not in explored])
+
+ return explored
\ No newline at end of file
diff --git a/pool/shard009/Python/0086625_refreshrepo.py b/pool/shard009/Python/0086625_refreshrepo.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d0a9dff2bd78334547ec931091ea1f7f11d8a78
--- /dev/null
+++ b/pool/shard009/Python/0086625_refreshrepo.py
@@ -0,0 +1,131 @@
+# -*- coding: utf-8 -*-
+"""Copyright (c) 2012 Sergio Gabriel Teves
+All rights reserved.
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 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 __future__ import with_statement
+import traceback, sys
+
+from django.core.management.base import BaseCommand
+
+from django.contrib.auth.models import User
+from django.conf import settings
+import time
+from optparse import make_option
+from versioncontrol.manager import Manager, LockRepo, POTUpdater
+from versioncontrol.models import BuildCache
+from projects.models import Project
+
+import logging
+logger = logging.getLogger('vertaal.batch')
+
+class Command(BaseCommand):
+ help = 'Refresh Repositories'
+ option_list = BaseCommand.option_list + (
+ make_option('--pot-only',
+ action='store_true',
+ dest='potonly',
+ default=False,
+ help='Get POT cache only'),
+ )
+
+ def handle(self, *args, **options):
+
+ self.stdout.write('Started.\n')
+ logger.info("Start")
+ t_start = time.time()
+
+ potonly = options['potonly']
+
+ BOT_USERNAME = getattr(settings, 'BOT_USERNAME', 'bot')
+ BOT_USER = User.objects.get(username=BOT_USERNAME)
+
+ projects = Project.objects.filter(enabled=True, read_only=False)
+
+ b = None
+ failedProjects = []
+ try:
+ for project in projects:
+ teams = project.teams.all()
+ for release in project.releases.filter(enabled=True, read_only=False):
+ for component in project.components.all():
+
+ try:
+ b = BuildCache.objects.get(component=component, release=release)
+ if b.is_locked:
+ logger.info("%s - %s is locked" % (release, component))
+ break
+ except:
+ b = BuildCache.objects.create(component=component,
+ release=release)
+
+ b.lock()
+
+ try:
+ if not potonly:
+ for team in teams:
+ if project.slug in failedProjects:
+ self.stdout.write("Project %s skipped because previous fails\n" % project.slug)
+ logger.info("Project %s skipped because previous fails" % project.slug)
+ break
+
+ logger.info("Refresh project %s, release %s, component %s, team %s" % (project.name,
+ release.name,
+ component.name,
+ team.language.name))
+ man = Manager(project, release, component, team.language, user=BOT_USER)
+
+ try:
+ logger.debug('Create lock')
+ with LockRepo(project.slug,
+ release.slug,
+ component.slug,
+ team.language.code) as lock:
+ logger.debug('Refresh')
+ man.revert()
+ man.refresh()
+ logger.debug('Process Stats')
+ man.update_stats(False)
+ except Exception, e:
+ failedProjects.append(project.slug)
+ logger.error(e)
+ traceback.print_exc(file=sys.stdout)
+ finally:
+ del man
+
+ if component.potlocation:
+ logger.info("Processing POT")
+ repo = POTUpdater(project, release, component)
+ try:
+ repo.update_stats(True)
+ except Exception, e:
+ logger.error(e)
+ traceback.print_exc(file=sys.stdout)
+ finally:
+ del repo
+ else:
+ logger.debug("POT skipped")
+
+ finally:
+ if b: b.unlock()
+
+ except Exception, e:
+ logger.error(e.args)
+ traceback.print_exc(file=sys.stdout)
+ if b: b.unlock()
+ logger.info("End")
+
+ self.stdout.write('Completed in %d seconds.\n' % int(time.time() - t_start))
diff --git a/pool/shard009/Python/0086633_demo.py b/pool/shard009/Python/0086633_demo.py
new file mode 100644
index 0000000000000000000000000000000000000000..5abaf700b1884342574e6d235757e9dd782252a6
--- /dev/null
+++ b/pool/shard009/Python/0086633_demo.py
@@ -0,0 +1,34 @@
+# -*- coding: UTF-8 -*-
+# Copyright 2014-2019 Rumma & Ko Ltd
+# License: GNU Affero General Public License v3 (see file COPYING for details)
+
+from lino.api import dd, rt, _
+
+from lino.utils.mldbc import babeld
+
+
+def objects():
+ ListType = rt.models.lists.ListType
+ List = rt.models.lists.List
+
+ mailing = babeld(ListType, _("Mailing list"))
+ yield mailing
+
+ discuss = babeld(ListType, _("Discussion group"))
+ yield discuss
+
+ flags = ListType(**dd.str2kw('designation', _("Flags")))
+ yield flags
+
+ yield List(list_type=mailing, **dd.str2kw('designation', _("Announcements")))
+ yield List(list_type=mailing, **dd.str2kw('designation', _("Weekly newsletter")))
+
+ yield List(list_type=discuss, **dd.str2kw('designation', _("General discussion")))
+ yield List(list_type=discuss, **dd.str2kw('designation', _("Beginners forum")))
+ yield List(list_type=discuss, **dd.str2kw('designation', _("Developers forum")))
+
+ yield List(list_type=flags,
+ **dd.str2kw('designation', _("PyCon 2014")))
+ yield List(list_type=flags,
+ **dd.str2kw('designation', _("Free Software Day 2014")))
+ yield List(list_type=flags, **dd.str2kw('designation', _("Schools")))
diff --git a/pool/shard009/Python/0086638_target_kl46z.py b/pool/shard009/Python/0086638_target_kl46z.py
new file mode 100644
index 0000000000000000000000000000000000000000..307299ad54ec90999da8145294cd9741375ed1b2
--- /dev/null
+++ b/pool/shard009/Python/0086638_target_kl46z.py
@@ -0,0 +1,33 @@
+"""
+ mbed CMSIS-DAP debugger
+ Copyright (c) 2006-2013 ARM Limited
+
+ 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 target_kinetis import Kinetis
+from .memory_map import (FlashRegion, RamRegion, MemoryMap)
+import logging
+
+
+class KL46Z(Kinetis):
+
+ memoryMap = MemoryMap(
+ FlashRegion( start=0, length=0x40000, blocksize=0x400, isBootMemory=True),
+ RamRegion( start=0x1fffe000, length=0x8000)
+ )
+
+ def __init__(self, link):
+ super(KL46Z, self).__init__(link, self.memoryMap)
+ self.mdm_idr = 0x001c0020
+
diff --git a/pool/shard009/Python/0086642_feed_parse_extractKrystalgenieWordpressCom.py b/pool/shard009/Python/0086642_feed_parse_extractKrystalgenieWordpressCom.py
new file mode 100644
index 0000000000000000000000000000000000000000..feb9cbca49c247d4e089f706d3c566f02d123780
--- /dev/null
+++ b/pool/shard009/Python/0086642_feed_parse_extractKrystalgenieWordpressCom.py
@@ -0,0 +1,22 @@
+
+def extractKrystalgenieWordpressCom(item):
+ '''
+ Parser for 'krystalgenie.wordpress.com'
+ '''
+
+ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
+ if not (chp or vol) or "preview" in item['title'].lower():
+ return None
+
+ tagmap = [
+ ('PRC', 'PRC', 'translated'),
+ ('Loiterous', 'Loiterous', 'oel'),
+ ]
+
+ for tagname, name, tl_type in tagmap:
+ if tagname in item['tags']:
+ return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
+
+
+ return False
+
\ No newline at end of file
diff --git a/pool/shard009/Python/0086644_AlgorithmExecutor.py b/pool/shard009/Python/0086644_AlgorithmExecutor.py
new file mode 100644
index 0000000000000000000000000000000000000000..61d8acf14162fa92253c9dd2f51b1bf303160e5d
--- /dev/null
+++ b/pool/shard009/Python/0086644_AlgorithmExecutor.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+
+"""
+***************************************************************************
+ AlgorithmExecutor.py
+ ---------------------
+ Date : August 2012
+ Copyright : (C) 2012 by Victor Olaya
+ Email : volayaf at gmail dot com
+***************************************************************************
+* *
+* This program is free software; you can redistribute it and/or modify *
+* it under the terms of the GNU General Public License as published by *
+* the Free Software Foundation; either version 2 of the License, or *
+* (at your option) any later version. *
+* *
+***************************************************************************
+"""
+
+__author__ = 'Victor Olaya'
+__date__ = 'August 2012'
+__copyright__ = '(C) 2012, Victor Olaya'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+import sys
+from copy import deepcopy
+from qgis.PyQt.QtCore import QCoreApplication
+from qgis.core import (QgsFeature,
+ QgsVectorFileWriter,
+ QgsProcessingFeedback,
+ QgsSettings,
+ QgsProcessingUtils,
+ QgsMessageLog,
+ QgsProperty,
+ QgsProcessingException,
+ QgsProcessingParameters,
+ QgsProcessingOutputLayerDefinition)
+from processing.gui.Postprocessing import handleAlgorithmResults
+from processing.tools import dataobjects
+from processing.tools.system import getTempFilename
+
+
+def execute(alg, parameters, context=None, feedback=None):
+ """Executes a given algorithm, showing its progress in the
+ progress object passed along.
+
+ Return true if everything went OK, false if the algorithm
+ could not be completed.
+ """
+
+ if feedback is None:
+ feedback = QgsProcessingFeedback()
+ if context is None:
+ context = dataobjects.createContext(feedback)
+
+ try:
+ results, ok = alg.run(parameters, context, feedback)
+ return ok, results
+ except QgsProcessingException as e:
+ QgsMessageLog.logMessage(str(sys.exc_info()[0]), 'Processing', QgsMessageLog.CRITICAL)
+ if feedback is not None:
+ feedback.reportError(e.msg)
+ return False, {}
+
+
+def executeIterating(alg, parameters, paramToIter, context, feedback):
+ # Generate all single-feature layers
+ settings = QgsSettings()
+ systemEncoding = settings.value('/UI/encoding', 'System')
+
+ parameter_definition = alg.parameterDefinition(paramToIter)
+ if not parameter_definition:
+ return False
+
+ iter_source = QgsProcessingParameters.parameterAsSource(parameter_definition, parameters, context)
+ sink_list = []
+ if iter_source.featureCount() == 0:
+ return False
+
+ total = 100.0 / iter_source.featureCount()
+ for current, feat in enumerate(iter_source.getFeatures()):
+ if feedback.isCanceled():
+ return False
+
+ sink, sink_id = QgsProcessingUtils.createFeatureSink('memory:', context, iter_source.fields(), iter_source.wkbType(), iter_source.sourceCrs())
+ sink_list.append(sink_id)
+ sink.addFeature(feat, QgsFeatureSink.FastInsert)
+ del sink
+
+ feedback.setProgress(int(current * total))
+
+ # store output values to use them later as basenames for all outputs
+ outputs = {}
+ for out in alg.destinationParameterDefinitions():
+ outputs[out.name()] = parameters[out.name()]
+
+ # now run all the algorithms
+ for i, f in enumerate(sink_list):
+ if feedback.isCanceled():
+ return False
+
+ parameters[paramToIter] = f
+ for out in alg.destinationParameterDefinitions():
+ o = outputs[out.name()]
+ parameters[out.name()] = QgsProcessingUtils.generateIteratingDestination(o, i, context)
+ feedback.setProgressText(tr('Executing iteration {0}/{1}...').format(i, len(sink_list)))
+ feedback.setProgress(i * 100 / len(sink_list))
+ ret, results = execute(alg, parameters, context, feedback)
+ if not ret:
+ return False
+
+ handleAlgorithmResults(alg, context, feedback, False)
+ return True
+
+
+def tr(string, context=''):
+ if context == '':
+ context = 'AlgorithmExecutor'
+ return QCoreApplication.translate(context, string)
diff --git a/pool/shard009/Python/0086645_update.py b/pool/shard009/Python/0086645_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..5be57ffccdcf45bb1c9e4b92cb4bc8e075deefa3
--- /dev/null
+++ b/pool/shard009/Python/0086645_update.py
@@ -0,0 +1,174 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you 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 collections import Counter
+from typing import Any, Dict, List, Optional
+
+from flask_appbuilder.models.sqla import Model
+from flask_appbuilder.security.sqla.models import User
+from marshmallow import ValidationError
+
+from superset.commands.base import BaseCommand
+from superset.commands.utils import populate_owners
+from superset.connectors.sqla.models import SqlaTable
+from superset.dao.exceptions import DAOUpdateFailedError
+from superset.datasets.commands.exceptions import (
+ DatabaseChangeValidationError,
+ DatasetColumnNotFoundValidationError,
+ DatasetColumnsDuplicateValidationError,
+ DatasetColumnsExistsValidationError,
+ DatasetExistsValidationError,
+ DatasetForbiddenError,
+ DatasetInvalidError,
+ DatasetMetricsDuplicateValidationError,
+ DatasetMetricsExistsValidationError,
+ DatasetMetricsNotFoundValidationError,
+ DatasetNotFoundError,
+ DatasetUpdateFailedError,
+)
+from superset.datasets.dao import DatasetDAO
+from superset.exceptions import SupersetSecurityException
+from superset.views.base import check_ownership
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateDatasetCommand(BaseCommand):
+ def __init__(
+ self,
+ user: User,
+ model_id: int,
+ data: Dict[str, Any],
+ override_columns: bool = False,
+ ):
+ self._actor = user
+ self._model_id = model_id
+ self._properties = data.copy()
+ self._model: Optional[SqlaTable] = None
+ self.override_columns = override_columns
+
+ def run(self) -> Model:
+ self.validate()
+ if self._model:
+ try:
+ dataset = DatasetDAO.update(
+ model=self._model,
+ properties=self._properties,
+ override_columns=self.override_columns,
+ )
+ return dataset
+ except DAOUpdateFailedError as ex:
+ logger.exception(ex.exception)
+ raise DatasetUpdateFailedError()
+ raise DatasetUpdateFailedError()
+
+ def validate(self) -> None:
+ exceptions: List[ValidationError] = list()
+ owner_ids: Optional[List[int]] = self._properties.get("owners")
+ # Validate/populate model exists
+ self._model = DatasetDAO.find_by_id(self._model_id)
+ if not self._model:
+ raise DatasetNotFoundError()
+ # Check ownership
+ try:
+ check_ownership(self._model)
+ except SupersetSecurityException:
+ raise DatasetForbiddenError()
+
+ database_id = self._properties.get("database", None)
+ table_name = self._properties.get("table_name", None)
+ # Validate uniqueness
+ if not DatasetDAO.validate_update_uniqueness(
+ self._model.database_id, self._model_id, table_name
+ ):
+ exceptions.append(DatasetExistsValidationError(table_name))
+ # Validate/Populate database not allowed to change
+ if database_id and database_id != self._model:
+ exceptions.append(DatabaseChangeValidationError())
+ # Validate/Populate owner
+ try:
+ owners = populate_owners(self._actor, owner_ids)
+ self._properties["owners"] = owners
+ except ValidationError as ex:
+ exceptions.append(ex)
+
+ # Validate columns
+ columns = self._properties.get("columns")
+ if columns:
+ self._validate_columns(columns, exceptions)
+
+ # Validate metrics
+ metrics = self._properties.get("metrics")
+ if metrics:
+ self._validate_metrics(metrics, exceptions)
+
+ if exceptions:
+ exception = DatasetInvalidError()
+ exception.add_list(exceptions)
+ raise exception
+
+ def _validate_columns(
+ self, columns: List[Dict[str, Any]], exceptions: List[ValidationError]
+ ) -> None:
+ # Validate duplicates on data
+ if self._get_duplicates(columns, "column_name"):
+ exceptions.append(DatasetColumnsDuplicateValidationError())
+ else:
+ # validate invalid id's
+ columns_ids: List[int] = [
+ column["id"] for column in columns if "id" in column
+ ]
+ if not DatasetDAO.validate_columns_exist(self._model_id, columns_ids):
+ exceptions.append(DatasetColumnNotFoundValidationError())
+
+ # validate new column names uniqueness
+ if not self.override_columns:
+ columns_names: List[str] = [
+ column["column_name"] for column in columns if "id" not in column
+ ]
+ if not DatasetDAO.validate_columns_uniqueness(
+ self._model_id, columns_names
+ ):
+ exceptions.append(DatasetColumnsExistsValidationError())
+
+ def _validate_metrics(
+ self, metrics: List[Dict[str, Any]], exceptions: List[ValidationError]
+ ) -> None:
+ if self._get_duplicates(metrics, "metric_name"):
+ exceptions.append(DatasetMetricsDuplicateValidationError())
+ else:
+ # validate invalid id's
+ metrics_ids: List[int] = [
+ metric["id"] for metric in metrics if "id" in metric
+ ]
+ if not DatasetDAO.validate_metrics_exist(self._model_id, metrics_ids):
+ exceptions.append(DatasetMetricsNotFoundValidationError())
+ # validate new metric names uniqueness
+ metric_names: List[str] = [
+ metric["metric_name"] for metric in metrics if "id" not in metric
+ ]
+ if not DatasetDAO.validate_metrics_uniqueness(self._model_id, metric_names):
+ exceptions.append(DatasetMetricsExistsValidationError())
+
+ @staticmethod
+ def _get_duplicates(data: List[Dict[str, Any]], key: str) -> List[str]:
+ duplicates = [
+ name
+ for name, count in Counter([item[key] for item in data]).items()
+ if count > 1
+ ]
+ return duplicates
diff --git a/pool/shard009/Python/0086648_views.py b/pool/shard009/Python/0086648_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c25cae4216696b5a19dd34f21c9cfa9fd784d8
--- /dev/null
+++ b/pool/shard009/Python/0086648_views.py
@@ -0,0 +1,149 @@
+from django.contrib.auth.decorators import login_required
+from django.core.urlresolvers import reverse
+from django.shortcuts import render, get_object_or_404, redirect
+from django.http import HttpResponseRedirect
+from django.forms import inlineformset_factory
+from crispy_forms.helper import FormHelper
+from .models import Bucket, Item, Identifier, IdentifierType
+from .forms import ItemForm, IdentifierForm, BucketItemForm, SearchForm
+import logging
+
+
+# @login_required()
+def index(request):
+ buckets = {b: Item.objects.filter(bucket=b) for b in Bucket.objects.all()}
+ identifier_types = {i.id: i.name
+ for i in IdentifierType.objects.all()}
+ identifier_types.update({0: 'Name'})
+
+ # for the new item form
+ item = Item()
+ IdentifierFormSet = inlineformset_factory(
+ Item,
+ Identifier,
+ form=IdentifierForm,
+ fields=('type', 'value'),
+ can_delete=False,
+ extra=0
+ )
+
+ context = {
+ 'bucket_list': buckets,
+ 'identifier_types': identifier_types,
+ 'item_form': ItemForm(instance=item),
+ 'formset': IdentifierFormSet(instance=item),
+ 'search_form': SearchForm()
+ }
+
+ return render(request, 'inventory/index.html', context)
+
+
+# @login_required
+def bucket(request, bucket_id):
+ bucket = get_object_or_404(Bucket, pk=bucket_id)
+ items = Item.objects.filter(bucket=bucket)
+ buckets = Bucket.objects.all().exclude(pk=bucket_id)
+
+ # for the new item form
+ item = Item()
+ item.bucket = bucket
+ IdentifierFormSet = inlineformset_factory(
+ Item,
+ Identifier,
+ form=IdentifierForm,
+ fields=('type', 'value'),
+ can_delete=False,
+ extra=0
+ )
+
+ context = {
+ 'bucket': bucket,
+ 'item_list': items,
+ 'bucket_list': buckets,
+ 'item_form': BucketItemForm(instance=item),
+ 'formset': IdentifierFormSet(instance=item),
+ 'search_form': SearchForm()
+ }
+
+ return render(request, 'inventory/bucket.html', context)
+
+
+def add(request, bucket_id=None):
+ item = ItemForm(request.POST)
+
+ # check item validity, but don't save just yet
+ if item.is_valid():
+ item = item.save(commit=False)
+ else:
+ context = {
+ 'error_text': 'Invalid Item: ' + item.errors.as_json()
+ }
+ return render(request, 'inventory/error.html', context)
+
+ IdentifierForm = inlineformset_factory(
+ Item,
+ Identifier,
+ fields=('type', 'value'),
+ can_delete=False,
+ )
+ identifier = IdentifierForm(request.POST, instance=item)
+
+ # check identifier(s) validity, save item and identifier(s)
+ if identifier.is_valid():
+ item.save()
+ identifier.save()
+ else:
+ context = {
+ 'error_text': 'Invalid Identifier: ' + identifier.errors.as_json(escape_html=False)
+ }
+ return render(request, 'inventory/error.html', context)
+
+ # send user to reasonable view
+ if bucket_id:
+ return redirect('inventory:bucket', bucket_id=bucket_id)
+
+ return redirect('inventory:index')
+
+
+def item(request, item_id):
+ return render(request, 'inventory/item.html')
+
+
+def move(request, item_id, bucket_id):
+ item = get_object_or_404(Item, pk=item_id)
+ bucket = get_object_or_404(Bucket, pk=bucket_id)
+ return_path = request.GET['return']
+
+ # move to new bucket and save
+ old_id = item.bucket.id
+ item.bucket = bucket
+ item.save()
+
+ # send user to reasonable view
+ if 'bucket' in return_path:
+ return redirect('inventory:bucket', bucket_id=old_id)
+
+ return redirect('inventory:index')
+
+
+def search(request):
+ search = SearchForm(request.POST)
+ context = {
+ 'bucket_list': Bucket.objects.all(),
+ 'search_form': search,
+ 'bucket_as_property': True
+ }
+
+ if search.is_valid():
+ # special case: search by name
+ if search.cleaned_data['search_property'] == 0:
+ context['item_list'] = Item.objects.filter(
+ name__contains=search.cleaned_data['search_keyword']
+ )
+ else:
+ context['item_list'] = Item.objects.filter(
+ identifier__type=search.cleaned_data['search_property'],
+ identifier__value=search.cleaned_data['search_keyword']
+ )
+
+ return render(request, 'inventory/search.html', context)
diff --git a/pool/shard009/Python/0086655_url.py b/pool/shard009/Python/0086655_url.py
new file mode 100644
index 0000000000000000000000000000000000000000..657c53815e95e4862a8454fbaf77a6ada355d600
--- /dev/null
+++ b/pool/shard009/Python/0086655_url.py
@@ -0,0 +1,136 @@
+"""
+This module contains general purpose URL functions not found in the standard
+library.
+
+Some of the functions that used to be imported from this module have been moved
+to the w3lib.url module. Always import those from there instead.
+"""
+import posixpath
+import re
+from six.moves.urllib.parse import (ParseResult, urldefrag, urlparse, urlunparse)
+
+# scrapy.utils.url was moved to w3lib.url and import * ensures this
+# move doesn't break old code
+from w3lib.url import *
+from w3lib.url import _safe_chars, _unquotepath
+from scrapy.utils.python import to_unicode
+
+
+def url_is_from_any_domain(url, domains):
+ """Return True if the url belongs to any of the given domains"""
+ host = parse_url(url).netloc.lower()
+ if not host:
+ return False
+ domains = [d.lower() for d in domains]
+ return any((host == d) or (host.endswith('.%s' % d)) for d in domains)
+
+
+def url_is_from_spider(url, spider):
+ """Return True if the url belongs to the given spider"""
+ return url_is_from_any_domain(url,
+ [spider.name] + list(getattr(spider, 'allowed_domains', [])))
+
+
+def url_has_any_extension(url, extensions):
+ return posixpath.splitext(parse_url(url).path)[1].lower() in extensions
+
+
+def parse_url(url, encoding=None):
+ """Return urlparsed url from the given argument (which could be an already
+ parsed url)
+ """
+ if isinstance(url, ParseResult):
+ return url
+ return urlparse(to_unicode(url, encoding))
+
+
+def escape_ajax(url):
+ """
+ Return the crawleable url according to:
+ https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
+
+ >>> escape_ajax("www.example.com/ajax.html#!key=value")
+ 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html?k1=v1&k2=v2#!key=value")
+ 'www.example.com/ajax.html?k1=v1&k2=v2&_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html?#!key=value")
+ 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html#!")
+ 'www.example.com/ajax.html?_escaped_fragment_='
+
+ URLs that are not "AJAX crawlable" (according to Google) returned as-is:
+
+ >>> escape_ajax("www.example.com/ajax.html#key=value")
+ 'www.example.com/ajax.html#key=value'
+ >>> escape_ajax("www.example.com/ajax.html#")
+ 'www.example.com/ajax.html#'
+ >>> escape_ajax("www.example.com/ajax.html")
+ 'www.example.com/ajax.html'
+ """
+ defrag, frag = urldefrag(url)
+ if not frag.startswith('!'):
+ return url
+ return add_or_replace_parameter(defrag, '_escaped_fragment_', frag[1:])
+
+
+def add_http_if_no_scheme(url):
+ """Add http as the default scheme if it is missing from the url."""
+ match = re.match(r"^\w+://", url, flags=re.I)
+ if not match:
+ parts = urlparse(url)
+ scheme = "http:" if parts.netloc else "http://"
+ url = scheme + url
+
+ return url
+
+
+def guess_scheme(url):
+ """Add an URL scheme if missing: file:// for filepath-like input or http:// otherwise."""
+ parts = urlparse(url)
+ if parts.scheme:
+ return url
+ # Note: this does not match Windows filepath
+ if re.match(r'''^ # start with...
+ (
+ \. # ...a single dot,
+ (
+ \. | [^/\.]+ # optionally followed by
+ )? # either a second dot or some characters
+ )? # optional match of ".", ".." or ".blabla"
+ / # at least one "/" for a file path,
+ . # and something after the "/"
+ ''', parts.path, flags=re.VERBOSE):
+ return any_to_uri(url)
+ else:
+ return add_http_if_no_scheme(url)
+
+
+def strip_url(url, strip_credentials=True, strip_default_port=True, origin_only=False, strip_fragment=True):
+
+ """Strip URL string from some of its components:
+
+ - `strip_credentials` removes "user:password@"
+ - `strip_default_port` removes ":80" (resp. ":443", ":21")
+ from http:// (resp. https://, ftp://) URLs
+ - `origin_only` replaces path component with "/", also dropping
+ query and fragment components ; it also strips credentials
+ - `strip_fragment` drops any #fragment component
+ """
+
+ parsed_url = urlparse(url)
+ netloc = parsed_url.netloc
+ if (strip_credentials or origin_only) and (parsed_url.username or parsed_url.password):
+ netloc = netloc.split('@')[-1]
+ if strip_default_port and parsed_url.port:
+ if (parsed_url.scheme, parsed_url.port) in (('http', 80),
+ ('https', 443),
+ ('ftp', 21)):
+ netloc = netloc.replace(':{p.port}'.format(p=parsed_url), '')
+ return urlunparse((
+ parsed_url.scheme,
+ netloc,
+ '/' if origin_only else parsed_url.path,
+ '' if origin_only else parsed_url.params,
+ '' if origin_only else parsed_url.query,
+ '' if strip_fragment else parsed_url.fragment
+ ))
diff --git a/pool/shard009/Python/0086657_Cmos.py b/pool/shard009/Python/0086657_Cmos.py
new file mode 100644
index 0000000000000000000000000000000000000000..266fb8937dfdcf27c6743e029c00a97d5e9568d0
--- /dev/null
+++ b/pool/shard009/Python/0086657_Cmos.py
@@ -0,0 +1,40 @@
+# Copyright (c) 2008 The Regents of The University of Michigan
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met: redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer;
+# redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution;
+# neither the name of the copyright holders nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Authors: Gabe Black
+
+from m5.params import *
+from m5.proxy import *
+from Device import BasicPioDevice
+from X86IntPin import X86IntSourcePin
+
+class Cmos(BasicPioDevice):
+ type = 'Cmos'
+ cxx_class='X86ISA::Cmos'
+ time = Param.Time('01/01/2012',
+ "System time to use ('Now' for actual time)")
+ int_pin = Param.X86IntSourcePin(X86IntSourcePin(),
+ 'Pin to signal RTC alarm interrupts to')
diff --git a/pool/shard009/Python/0086670_main.py b/pool/shard009/Python/0086670_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..1886d63a135dba6d930e14e4a635d6f61f3a2d0f
--- /dev/null
+++ b/pool/shard009/Python/0086670_main.py
@@ -0,0 +1,127 @@
+import pickle
+import numpy as np
+import pandas as pd
+import xgboost as xgb
+import matplotlib.pyplot as plt
+
+from src.functions import read_data, remove_outliers, \
+ calculate_times, calculate_confidence, get_movement, report_best_scores
+from sklearn.metrics import classification_report, confusion_matrix
+from sklearn.model_selection import RandomizedSearchCV, train_test_split
+from sklearn.utils import compute_class_weight
+from sklearn.dummy import DummyClassifier
+
+
+# Load all data files
+user, quiz, time_df, xclick, yclick = read_data()
+questions = time_df.columns.values
+
+##################################################
+# Calculate response times per question
+# (notice Q1 time can't be calculated, as we don't
+# have timestamp for beginning of the test)
+delta_time_df = calculate_times(time_df)
+# Calculate the descriptive stats for response times
+delta_time_df = delta_time_df.apply(remove_outliers)
+delta_time_eda = delta_time_df.describe()
+
+dt_bp_fig = plt.figure()
+delta_time_bp = delta_time_df['time_' + questions].boxplot(fontsize='small')
+dt_bp_fig.savefig('assets/boxplot.png')
+
+shortest_q = delta_time_df['time_' + questions].mean().idxmin()
+print('Shortest question: ' + shortest_q)
+calculate_confidence(delta_time_df[shortest_q])
+
+longest_q = delta_time_df['time_' + questions].mean().idxmax()
+print('Longest question: ' + longest_q)
+calculate_confidence(delta_time_df[longest_q])
+
+# Median
+questions[np.argsort(delta_time_df['time_' + questions].mean())[len(delta_time_df['time_' + questions].mean())//2]]
+
+
+###########################################################
+# Is there a relationship between Q1/Q2 and user behaviour?
+# Which one is better predictor?
+
+quiz.set_index('PartnerUID', inplace=True)
+quiz = quiz.join(user, how='left')
+quiz.set_index('UID', inplace=True)
+
+quiz.pivot_table(index='Q1', columns='Flag', aggfunc='size', fill_value=0)
+quiz.pivot_table(index='Q2', columns='Flag', aggfunc='size', fill_value=0)
+
+quiz.Flag.value_counts()
+
+cramer = quiz.corrwith(quiz.Flag, axis=0, method=cramer_v)
+
+print('Correlation between Q1 and User Behaviour is: ' + str(cramer[0]) + '%')
+print('Correlation between Q2 and User Behaviour is: ' + str(cramer[1]) + '%')
+
+cramer.to_csv('data/cramer.csv')
+
+###########################################################
+# Build a model to predict user behaviour
+
+# Set features as: answers + times + movement
+quiz_encoded = pd.get_dummies(quiz.iloc[:, 0:59], prefix=questions, columns=questions)
+
+quiz_encoded = quiz_encoded.join(quiz.Flag)
+
+quiz_encoded = quiz_encoded.join(delta_time_df, how='left')
+
+dclick = get_movement(xclick, yclick)
+quiz_encoded = quiz_encoded.join(dclick, how='left')
+
+# Clean NaN values
+quiz_encoded.dropna(subset=['Flag', 'time_recorded'], inplace=True)
+quiz_encoded.drop(['time_Q1', 'dclick_Q1'], axis=1, inplace=True)
+
+# Split dataset - _test used as validation set
+X = quiz_encoded.loc[:, quiz_encoded.columns != 'Flag']
+y = quiz_encoded.loc[:, 'Flag']
+X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=123)
+
+# Handle imbalances
+weight_flag = compute_class_weight('balanced', np.unique(y_train), y_train)
+weights = np.ones(quiz_encoded.shape[0], dtype = 'float')
+weights[quiz_encoded.Flag == 'Bad'] = weight_flag[0] - 1
+weights[quiz_encoded.Flag == 'Good'] = weight_flag[1] - 1
+weights[quiz_encoded.Flag == 'Unknown'] = weight_flag[2] - 1
+
+# Baseline model
+baseline = DummyClassifier(strategy="stratified")
+baseline.fit(X_train, y_train)
+y_pred = baseline.predict(X_test)
+print(confusion_matrix(y_test, y_pred))
+print(classification_report(y_test, y_pred))
+
+# Using xgboost as state-of-the-art in classification, and resilient to NaN values
+xgb_model = xgb.XGBClassifier(objective='multi:softprob')
+# xgb_model.fit(X_train, y_train, sample_weight=weights, eval_metric='merror')
+
+# To speed up, reduced number of potential alternative parameters
+params = {
+ "learning_rate": [0.01, 0.05, 0.10, 0.15, 0.30],
+ "gamma": [0, 0.1, 0.2, 0.3, 0.5],
+ "max_depth": [2, 3, 6],
+ "n_estimators": [10, 25, 50, 100]
+}
+
+search = RandomizedSearchCV(xgb_model, param_distributions=params,
+ random_state=123, n_iter=100, cv=5, verbose=2, n_jobs=4,
+ scoring='balanced_accuracy', return_train_score=True)
+
+search.fit(X_train, y_train, sample_weight=weights, eval_metric='merror')
+report_best_scores(search.cv_results_, 1)
+
+best_model = search.best_estimator_
+pickle.dump(best_model, open("assets/best_model.pickle.dat", "wb"))
+
+# Evaluation and feature importance
+xgb.plot_importance(best_model, max_num_features=20)
+
+y_pred = best_model.predict(X_test)
+print(confusion_matrix(y_test, y_pred))
+print(classification_report(y_test, y_pred))
diff --git a/pool/shard009/Python/0086673_init__.py b/pool/shard009/Python/0086673_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9f697948da75d60aff2b2191761cdbb2c72937b
--- /dev/null
+++ b/pool/shard009/Python/0086673_init__.py
@@ -0,0 +1,29 @@
+from DesOptPy.DesOptPy import *
+from DesOptPy.tools import *
+from DesOptPy.plotting import *
+
+# from DesOptPy.FunctionAggregation import *
+
+
+__title__ = 'DESign OPTimization in PYthon'
+__shorttitle__ = 'DesOptPy'
+__version__ = '2.0 development'
+# __all__ = ["DesOpt"]
+__author__ = 'E. J. Wehrle'
+__copyright__ = 'Copyright 2021 E. J. Wehrle'
+__email__ = 'Erich.Wehrle(a)unibz.it'
+__url__ = 'github.com/edub/DesOptPy2'
+# TODO decide on license for new version
+__license__ = 'TBD' # "GNU Lesser General Public License"
+
+
+def PrintDesOptPy():
+ print()
+ print(__title__ + ' - ' + __shorttitle__)
+ print('Version: ' + __version__)
+ print('License: ' + __license__)
+ print('Internet: ' + __url__)
+ print('\n')
+
+
+PrintDesOptPy()
diff --git a/pool/shard009/Python/0086674_traceobjpluginctrl.py b/pool/shard009/Python/0086674_traceobjpluginctrl.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa43cd3fd9c89fa1c19ac93ef06b435067f20b30
--- /dev/null
+++ b/pool/shard009/Python/0086674_traceobjpluginctrl.py
@@ -0,0 +1,203 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# ---------------------------------------------------------------------
+# Copyright (c) 2012 Michael Hull.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# - Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# - Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in
+# the documentation and/or other materials provided with the
+# distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+# ----------------------------------------------------------------------
+
+import operator
+
+from morphforge.units import qty
+from morphforge.traces.tracetypes import TraceFixedDT
+
+
+class TraceOperatorCtrl(object):
+
+ trace_operators_all = {}
+ trace_operators_active = {}
+ trace_operators = [operator.__add__, operator.__sub__,
+ operator.__div__, operator.__mul__,
+ operator.__pow__]
+
+ @classmethod
+ def add_trace_operator_symmetrical_handler(cls, operator_type, lhs_type, rhs_type, operator_func, flag='default', set_as_default=False):
+ assert False
+ cls.add_trace_operator(operator_type=operator_type,
+ lhs_type=lhs_type,
+ rhs_type=rhs_type,
+ operator_func=operator_func,
+ flag=flag,
+ set_as_default=set_as_default)
+ cls.add_trace_operator(operator_type=operator_type,
+ lhs_type=rhs_type,
+ rhs_type=lhs_type,
+ operator_func=operator_func,
+ flag=flag,
+ set_as_default=set_as_default)
+
+ @classmethod
+ def add_trace_operator(cls, operator_type, lhs_type, rhs_type, operator_func, flag='default', set_as_default=False):
+ assert operator_type in cls.trace_operators
+
+ key = (operator_type, lhs_type, rhs_type)
+
+ # Add to the list of all:
+ if not key in cls.trace_operators_all:
+ cls.trace_operators_all[key] = {}
+
+ # Check the flag is not already active:
+ assert not flag in cls.trace_operators_all[key], 'Duplicate key/flag %s %s:' % (flag, key)
+ cls.trace_operators_all[key][flag] = operator_func
+
+ # Set as default if there is no current default, or flag is default:
+ if not key in cls.trace_operators_active or flag == 'default' or set_as_default:
+ cls.trace_operators_active[key] = operator_func, flag
+
+
+ @classmethod
+ def operate(cls, operator_type, lhs, rhs, use_flag=None, **kwargs):
+
+ # Lets map 'int' to 'float for standard ops (not power)'
+ if operator_type in [ operator.__add__, operator.__sub__, operator.__mul__, operator.__div__]:
+ if type(lhs) is int:
+ lhs = float(lhs)
+ if type(rhs) is int:
+ rhs = float(rhs)
+
+
+
+ key = (operator_type, type(lhs), type(rhs))
+
+ # Use the active operation:
+ if not use_flag:
+ assert key in cls.trace_operators_active, 'Trace Operation not defined for: %s' % str(key)
+ opfunctor = cls.trace_operators_active[key][0]
+
+ # Use a custom operation:
+ else:
+ assert key in cls.trace_operators_all
+ assert use_flag in cls.trace_operators_all[key]
+ opfunctor = cls.trace_operators_all[key][use_flag]
+
+ return opfunctor(lhs=lhs, rhs=rhs, **kwargs)
+
+
+
+
+class TraceMethodCtrl(object):
+
+ registered_methods = {}
+
+ # A list of method names that can be used for anytrace
+ # if a specific method is not available for a type of trace
+ fallback_to_fixedtrace_methods = {}
+
+ default_fallback_resolution = qty('0.1:ms')
+
+ @classmethod
+ def register(cls, trace_cls, method_name, method_functor, can_fallback_to_fixed_trace=False, fallback_resolution=None):
+ # print 'Registering method', trace_cls, method_name
+ key = (trace_cls, method_name)
+ assert not key in cls.registered_methods
+ cls.registered_methods[key] = method_functor
+
+ # Can we fallback to fixed_dt traces to use this operation
+ if can_fallback_to_fixed_trace:
+ fallback_resolution = fallback_resolution or cls.default_fallback_resolution
+ assert trace_cls == TraceFixedDT
+ cls.fallback_to_fixedtrace_methods[method_name] = fallback_resolution
+
+ @classmethod
+ def has_method(cls, trace_cls, method_name):
+ if (trace_cls, method_name) in cls.registered_methods:
+ return True
+ if method_name in cls.fallback_to_fixedtrace_methods:
+ return True
+ return False
+
+ @classmethod
+ def get_method(cls, trace_cls, method_name):
+ key = (trace_cls, method_name)
+ if key in cls.registered_methods:
+ return cls.registered_methods[key]
+ # Fallback to FixedDT
+ if method_name in cls.fallback_to_fixedtrace_methods:
+ method = cls.registered_methods[(TraceFixedDT, method_name)]
+ dt = cls.fallback_to_fixedtrace_methods[method_name]
+ return _prepend_conversion_to_fixed_trace_to_function(method, fixed_trace_dt=dt)
+
+ # Error!
+ assert False
+
+
+
+def _prepend_conversion_to_fixed_trace_to_function(func, fixed_trace_dt):
+ from morphforge.traces.methods.MMtrace_conversion import TraceConverter
+
+ def wrapped_func(self, *args, **kwargs):
+ tr_new = TraceConverter.rebase_to_fixed_dt(self, dt=fixed_trace_dt)
+ return func(tr_new, *args, **kwargs)
+
+ return wrapped_func
+
+
+def copy_trace_attrs(tr_old, tr_new, name=None, comment=None, tags=None, add_tags=None):
+ # NewName:
+ if name is not None:
+ if name.startswith('+'):
+ new_name = tr_old.name + name[1:]
+ elif name.endswith('+'):
+ new_name = name[:-1] + tr_old.name
+ else:
+ new_name = name
+ else:
+ new_name = tr_old.name
+
+ # NewComment:
+ if comment is not None:
+ if comment.startswith('+'):
+ new_comment = tr_old.comment + comment[1:]
+ elif comment.endswith('+'):
+ new_comment = comment[:-1] + tr_old.comment
+ else:
+ new_comment = comment
+ else:
+ new_comment = tr_old.comment
+
+ if tags:
+ assert not add_tags
+ new_tags = tags
+ else:
+ new_tags = tr_old.tags + ((add_tags if add_tags else []))
+
+ tr_new.name = new_name
+ tr_new.comment = new_comment
+ tr_new.tags = new_tags
+
+ return tr_new
+
+
diff --git a/pool/shard009/Python/0086675_name2pathway.py b/pool/shard009/Python/0086675_name2pathway.py
new file mode 100644
index 0000000000000000000000000000000000000000..04336662f36b23c3908b5b4ddf92831166105ae1
--- /dev/null
+++ b/pool/shard009/Python/0086675_name2pathway.py
@@ -0,0 +1,116 @@
+__author__ = 'Matteo'
+__doc__ = '''Given a list of gene product names match to a reaction ID and therefore to a pathway from BioCyc.
+KEGG is not free and GO's flatfiles lack names. So BioCyc was chosen, which I like more than KEGG TBH and certainly GO.
+It uses the enzymes.col and gene_association.metacyc flatfiles of metacyc. It has is mostly accurate.
+It matches by words where if the match has longer than half matched words it is chosen.
+I did not use Differ as I don't think that would have made too many false positives.'''
+
+import csv, re
+import numpy
+#from collections import OrderedDict
+N = "\n"
+T = "\t"
+# N="
"
+
+def wordmatching(mylist,refp,ref2p,fout):
+ def make_symname(fp):
+ symball={}
+ for el in csv.reader(open(fp),delimiter=T):
+ if len(el)<7:
+ pass
+ elif el[2] not in symball:
+ symball[el[2]]=el[9]
+ return symball
+
+ def make_namepath(fp):
+ nameball={}
+ for line in open(fp).readlines():
+ if line[0]=='#':
+ continue
+ #UNIQUE-ID NAME REACTION-EQUATION PATHWAYS PATHWAYS PATHWAYS PATHWAYS
+ parts=line.split(T)
+ name=' '.join(munger(parts[1]))
+ paths=set(filter(None,parts[3:6]))
+ if name not in nameball: #new key
+ nameball[name]=paths
+ else: #seen key
+ nameball[name].update(paths)
+ return {k:sorted(nameball[k]) for k in nameball}
+
+
+ def munger(txt):
+ blacklist='transport binding family'.split()
+ blacktype='transport tranport hypo'.split()
+ for black in blacklist:
+ if txt.find(black+' protein')>0:
+ words=['CENSORED', blacktype[blacklist.index(black)]]
+ break
+ else:
+ w=txt.lower().replace('protein',' ').replace('polypeptide',' ').replace('peptide',' ').replace('subunit',' ') #not family
+ w=w.replace('oxo','keto').replace('yl','yl ') #off for now. Numbers?
+ w=re.sub('\-[0-9]\-','',w)
+ #w=w.replace('-','')
+ words=re.sub('[^0-9a-zA-Z]+', ' ',w).split()
+ blacklist='hypothetical putative family symporter transporter channel regulator factor repressor inducer'.split()
+ blacktype='hypo hypo hypo transport transport transport TF TF TF TF'.split()
+ for black in blacklist:#hypos ect will not be matched to a pathway.
+ if black in words:
+ words=['CENSORED', blacktype[blacklist.index(black)]]
+ return set(words)
+
+ def matcher(queries,refs,sym):
+ kwords=sorted(refs.keys(),key=lambda x: len(refs[x]))
+ rpage=[set(k.split()) for k in kwords]
+ score=[]
+ censor=0
+ hit=[['error'] for i in queries] #???
+ for qi,q in enumerate(queries):
+ if len(q)<5:
+ if q[1] in sym:
+ #print(q[1]+' is '+sym[q[1]])
+ q[1]=sym[q[1]]
+ qwords=munger(q[1])
+ if 'CENSORED' in qwords:
+ censor+=censor
+ hit[qi]=sorted(qwords-{'CENSORED'})
+ continue
+ max=0
+ mi=None
+ ms=999
+ for ri,rwords in enumerate(rpage):
+ inter=qwords.intersection(rwords)
+ n=len(inter)
+ s=len(' '.join(inter))
+ if n>max or (n==max and s>ms):
+ max=n
+ mi=ri
+ ms=s
+ score.append(max/len(qwords))
+ if not mi:
+ pass
+ hit[qi]=['unmatched'] #dodgy
+ # print(qwords,'unmatched') #unmatched
+ elif len(qwords) == len(rpage[mi]):
+ hit[qi]=refs[kwords[mi]] #perferct
+ elif max/len(qwords)>0.5:
+ hit[qi]=refs[kwords[mi]] #dodgy
+ else:
+ hit[qi]=['unmatched'] #issue
+ print(numpy.mean(score),score.count(0)/(len(queries)-censor),score.count(1)/(len(queries)-censor))
+ return hit
+ #0.295555237493 0.5176123180763552 0.15228854672010125 #hyphen=''
+ #0.323181296193 0.47880194051887787 0.16199114110947058 #hyphen=' '
+ #0.509206555418 0.11347816916262392 0.16199114110947058 skipping censored
+ #0.54410711962 0.10693946424804894 0.17085003163889476
+ #0.578467839238 0.08437038599451592 0.17274836532377136
+
+ ref=make_namepath(refp)
+ sym=make_symname(ref2p)
+ qry=list(csv.reader(open(mylist),delimiter=T))
+ ht=matcher(qry,ref,sym)
+ w=csv.writer(open(fout,'w'))
+ for i, qe in enumerate(qry):
+ w.writerow(qe+ht[i])
+
+if __name__ == "__main__":
+ wordmatching('name_list 2.2.txt','enzymes.col','gene_association.metacyc','pairings.csv')
diff --git a/pool/shard009/Python/0086686_create_a_spectrogram_16k.py b/pool/shard009/Python/0086686_create_a_spectrogram_16k.py
new file mode 100644
index 0000000000000000000000000000000000000000..c26a1de4b80b467555b1c27c98b95c0376f91279
--- /dev/null
+++ b/pool/shard009/Python/0086686_create_a_spectrogram_16k.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+import os
+import numpy as np
+import math
+import fnmatch
+from my_spectrogram import my_specgram
+from scipy.io import wavfile
+import matplotlib.pylab as plt
+from pylab import rcParams
+
+rcParams['figure.figsize'] = 6, 3
+
+SCRIPT_DIR = os.getcwd()
+INPUT_FOLDER = 'Input_audio_wav_16k/'
+OUTPUT_FOLDER = 'Input_spectrogram_16k/'
+print(os.listdir(INPUT_FOLDER))
+
+wave = input('What file would you like to convert to a spectrogram: ')
+
+def plot_spectrogram(audiopath, plotpath=None, NFFT_window=0.025,
+ noverlap_window=0.023, freq_min=None, freq_max=None,
+ axis='off'):
+ fs, data = wavfile.read(audiopath)
+ data = data / data.max()
+ center = data.mean() * 0.2
+ data = data + np.random.normal(center, abs(center * 0.5), len(data))
+ NFFT = pow(2, int(math.log(int(fs*NFFT_window), 2) + 0.5)) # 25ms window, nearest power of 2
+ noverlap = int(fs*noverlap_window)
+ fc = int(np.sqrt(freq_min*freq_max))
+ # Pxx is the segments x freqs array of instantaneous power, freqs is
+ # the frequency vector, bins are the centers of the time bins in which
+ # the power is computed, and im is the matplotlib.image.AxesImage
+ # instance
+ Pxx, freqs, bins, im = my_specgram(data, NFFT=NFFT, Fs=fs,
+ Fc=fc, detrend=None,
+ window=np.hanning(NFFT),
+ noverlap=noverlap, cmap='Greys',
+ xextent=None,
+ pad_to=None, sides='default',
+ scale_by_freq=None,
+ minfreq=freq_min, maxfreq=freq_max)
+ plt.axis(axis)
+ im.axes.axis('tight')
+ im.axes.get_xaxis().set_visible(False)
+ im.axes.get_yaxis().set_visible(False)
+ if plotpath:
+ plt.savefig(plotpath, bbox_inches='tight',
+ transparent=False, pad_inches=0, dpi=96)
+ else:
+ plt.show()
+ plt.clf()
+
+
+# same as training but no added noise
+def plot_spectrogram_val(audiopath, plotpath=None, NFFT_window=0.025,
+ noverlap_window=0.023, freq_min=None, freq_max=None,
+ axis='off'):
+ fs, data = wavfile.read(audiopath)
+ data = data / data.max()
+ NFFT = pow(2, int(math.log(int(fs*NFFT_window), 2) + 0.5)) # 25ms window, nearest power of 2
+ noverlap = int(fs*noverlap_window)
+ fc = int(np.sqrt(freq_min*freq_max))
+ # Pxx is the segments x freqs array of instantaneous power, freqs is
+ # the frequency vector, bins are the centers of the time bins in which
+ # the power is computed, and im is the matplotlib.image.AxesImage
+ # instance
+ Pxx, freqs, bins, im = my_specgram(data, NFFT=NFFT, Fs=fs,
+ Fc=fc, detrend=None,
+ window=np.hanning(NFFT),
+ noverlap=noverlap, cmap='Greys',
+ xextent=None,
+ pad_to=None, sides='default',
+ scale_by_freq=None,
+ minfreq=freq_min, maxfreq=freq_max)
+ plt.axis(axis)
+ im.axes.axis('tight')
+ im.axes.get_xaxis().set_visible(False)
+ im.axes.get_yaxis().set_visible(False)
+ if plotpath:
+ plt.savefig(plotpath, bbox_inches='tight',
+ transparent=False, pad_inches=0, dpi=96)
+ else:
+ plt.show()
+ plt.clf()
+
+
+# create spectrograms of randomly drawn samples from each language
+def find(pattern, path):
+ result = []
+ for root, dirs, files in os.walk(path):
+ for name in files:
+ if fnmatch.fnmatch(name, pattern):
+ result.append(os.path.join(root, name))
+ return result[0]
+
+
+plot_spectrogram(find(wave, INPUT_FOLDER),
+ plotpath=OUTPUT_FOLDER + str(wave[:-4]) + '.jpeg',
+ NFFT_window=0.025, noverlap_window=0.023,
+ freq_min=0, freq_max=5500)
+print('All done')
diff --git a/pool/shard009/Python/0086692_models.py b/pool/shard009/Python/0086692_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..56906a4fde3a08ad493585ac9a4cc560914ae326
--- /dev/null
+++ b/pool/shard009/Python/0086692_models.py
@@ -0,0 +1,114 @@
+from __future__ import absolute_import
+
+import json
+import pickle
+from datetime import datetime
+
+from django.db import models
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.contenttypes import generic
+from django.utils.translation import ugettext_lazy as _
+from django.core import serializers
+
+#from history.managers import HistoryManager
+from .runtime_data import history_types_dict
+
+
+class HistoryType(models.Model):
+ namespace = models.CharField(max_length=64, verbose_name=_(u'namespace'))
+ name = models.CharField(max_length=64, verbose_name=_(u'name'))
+
+ def __unicode__(self):
+ try:
+ return unicode(history_types_dict[self.namespace][self.name]['label'])
+ except KeyError:
+ return u'obsolete history type: %s - %s' % (self.namespace, self.name)
+
+ @models.permalink
+ def get_absolute_url(self):
+ return ('history_type_list', [self.pk])
+
+ class Meta:
+ ordering = ('namespace', 'name')
+ unique_together = ('namespace', 'name')
+ verbose_name = _(u'history type')
+ verbose_name_plural = _(u'history types')
+
+
+class History(models.Model):
+ datetime = models.DateTimeField(verbose_name=_(u'date time'))
+ content_type = models.ForeignKey(ContentType, blank=True, null=True)
+ object_id = models.PositiveIntegerField(blank=True, null=True)
+ content_object = generic.GenericForeignKey('content_type', 'object_id')
+ history_type = models.ForeignKey(HistoryType, verbose_name=_(u'history type'))
+ dictionary = models.TextField(verbose_name=_(u'dictionary'), blank=True)
+
+ def __unicode__(self):
+ return u'%s - %s - %s' % (self.datetime, self.content_object, self.history_type)
+
+ def save(self, *args, **kwargs):
+ if not self.pk:
+ self.datetime = datetime.now()
+ super(History, self).save(*args, **kwargs)
+
+ def get_label(self):
+ return history_types_dict[self.history_type.namespace][self.history_type.name]['label']
+
+ def get_summary(self):
+ return history_types_dict[self.history_type.namespace][self.history_type.name].get('summary', u'')
+
+ def get_details(self):
+ return history_types_dict[self.history_type.namespace][self.history_type.name].get('details', u'')
+
+ def get_expressions(self):
+ return history_types_dict[self.history_type.namespace][self.history_type.name].get('expressions', {})
+
+ def get_processed_summary(self):
+ return _process_history_text(self, self.get_summary())
+
+ def get_processed_details(self):
+ return _process_history_text(self, self.get_details())
+
+ @models.permalink
+ def get_absolute_url(self):
+ return ('history_view', [self.pk])
+
+ class Meta:
+ ordering = ('-datetime',)
+ verbose_name = _(u'history')
+ verbose_name_plural = _(u'histories')
+
+
+def _process_history_text(history, text):
+ key_values = {
+ 'content_object': history.content_object,
+ 'datetime': history.datetime
+ }
+
+ loaded_dictionary = json.loads(history.dictionary)
+
+ new_dict = {}
+ for key, values in loaded_dictionary.items():
+ value_type = pickle.loads(str(values['type']))
+ if isinstance(value_type, models.base.ModelBase):
+ for deserialized in serializers.deserialize('json', values['value']):
+ new_dict[key] = deserialized.object
+ elif isinstance(value_type, models.query.QuerySet):
+ qs = []
+ for deserialized in serializers.deserialize('json', values['value']):
+ qs.append(deserialized.object)
+ new_dict[key] = qs
+ else:
+ new_dict[key] = json.loads(values['value'])
+
+ key_values.update(new_dict)
+ expressions_dict = {}
+
+ for key, value in history.get_expressions().items():
+ try:
+ expressions_dict[key] = eval(value, key_values.copy())
+ except Exception, e:
+ expressions_dict[key] = e
+
+ key_values.update(expressions_dict)
+ return text % key_values
diff --git a/pool/shard009/Python/0086701_jawa_smuggler.py b/pool/shard009/Python/0086701_jawa_smuggler.py
new file mode 100644
index 0000000000000000000000000000000000000000..86f72619eba658b5f51f89affc86708f92f124c1
--- /dev/null
+++ b/pool/shard009/Python/0086701_jawa_smuggler.py
@@ -0,0 +1,39 @@
+import sys
+from services.spawn import MobileTemplate
+from services.spawn import WeaponTemplate
+from resources.datatables import WeaponType
+from resources.datatables import Difficulty
+from resources.datatables import Options
+from java.util import Vector
+
+
+def addTemplate(core):
+ mobileTemplate = MobileTemplate()
+
+ mobileTemplate.setCreatureName('jawa_protector')
+ mobileTemplate.setLevel(17)
+ mobileTemplate.setDifficulty(Difficulty.NORMAL)
+
+ mobileTemplate.setMinSpawnDistance(4)
+ mobileTemplate.setMaxSpawnDistance(8)
+ mobileTemplate.setDeathblow(False)
+ mobileTemplate.setScale(1)
+ mobileTemplate.setSocialGroup("jawa")
+ mobileTemplate.setAssistRange(0)
+ mobileTemplate.setStalker(True)
+
+ templates = Vector()
+ templates.add('object/mobile/shared_jawa.iff')
+ mobileTemplate.setTemplates(templates)
+
+ weaponTemplates = Vector()
+ weapontemplate = WeaponTemplate('object/weapon/ranged/carbine/shared_carbine_cdef.iff', WeaponType.CARBINE, 1.0, 15, 'energy')
+ weaponTemplates.add(weapontemplate)
+ mobileTemplate.setWeaponTemplateVector(weaponTemplates)
+
+ attacks = Vector()
+ mobileTemplate.setDefaultAttack('rangedShot')
+ mobileTemplate.setAttacks(attacks)
+
+ core.spawnService.addMobileTemplate('jawa_protector', mobileTemplate)
+ return
\ No newline at end of file
diff --git a/pool/shard009/Python/0086702_reports.py b/pool/shard009/Python/0086702_reports.py
new file mode 100644
index 0000000000000000000000000000000000000000..f49681444c06d9be6e1734fa4d8909024c8bafa5
--- /dev/null
+++ b/pool/shard009/Python/0086702_reports.py
@@ -0,0 +1,78 @@
+from .utils import flatten_list, set_default_dates
+
+
+class Column(object):
+ def add_to_report(self, report, key, dictionary):
+ pass
+
+
+class Report(object):
+ """
+ A report was found to be a useful callable for more complicated aggregate reports, in which each
+ column of the report is a complicated query, but can be performed for every row of the
+ table at once. Subclasses of this object can define tabular reports declaratively,
+ by creating Column attributes.
+
+ The main report class builds a dictionary of dictionaries. Each key is a unique identifier, and
+ the dictionary value has the remaining column attributes. Each column is called in the order it was
+ declared, adding its column value to each subdictionary in the main dictionary. The final product
+ is then flattened.
+
+ For instance, suppose we were aggregating stats by Locations. I might declare three columns:
+
+ class MyCityReport(Report):
+ population = PopulationColumn()
+ crime = CrimeColumn()
+ pollution = PollutionColumn()
+
+ each Column knows how to add itself to the report structure following the same convention.
+ So MyCityReport would start with an empty report dictionary, {}.
+ After the call to PopulationColumn's add_to_report() method, the report dictionary might look
+ like this:
+
+ {'nairobi':{'pop':3000000},
+ 'kampala':{'pop':1420200},
+ 'kigali':{'pop':965398}}
+
+ After Crime's add_to_report(), it would be:
+
+ {'nairobi':{'pop':3000000, 'crime':'nairobbery'},
+ 'kampala':{'pop':1420200, 'crime':'lots of carjacking'},
+ 'kigali':{'pop':965398, 'crime':'ok lately'}}
+
+ And so on. After all columns have been given a shot at adding their data, the report finally flattens
+ this list into something that can be used by the generic view in the standard way (i.e., as an iterable
+ that can be sorted, paginated, and selected):
+
+ [{'key':'nairobi','pop':3000000, 'crime':'nairobbery'},
+ {'key':'kampala','pop':1420200, 'crime':'lots of carjacking'},
+ {'key':'kigali','pop':965398, 'crime':'ok lately'}]
+
+ Reports also sort date filtering and drill-down by default, just be sure to set
+ `needs_date` to True when passing a Report object to the generic view, and also set
+ the base_template to be `generic/timeslider_base.html' rather than the standard
+ `generic/base.html`
+ """
+ def __init__(self, request=None, dates=None):
+ datedict = {}
+ set_default_dates(dates, request, datedict)
+
+ self.drill_key = request.POST['drill_key'] if 'drill_key' in request.POST else None
+ self.start_date = datedict['start_date']
+ self.end_date = datedict['end_date']
+ self.report = {} #SortedDict()
+ self.columns = []
+ column_classes = Column.__subclasses__()
+ for attrname in dir(self):
+ val = getattr(self, attrname)
+ if type(val) in column_classes:
+ self.columns.append(attrname)
+ val.add_to_report(self, attrname, self.report)
+
+ self.report = flatten_list(self.report)
+
+ def __iter__(self):
+ return self.report.__iter__()
+
+ def __len__(self):
+ return len(self.report)
diff --git a/pool/shard009/Python/0086704_kindManager.py b/pool/shard009/Python/0086704_kindManager.py
new file mode 100644
index 0000000000000000000000000000000000000000..04be344b97bc0923c7a0a2248252d6a0fa20ec5b
--- /dev/null
+++ b/pool/shard009/Python/0086704_kindManager.py
@@ -0,0 +1,242 @@
+# Copyright 2010-2012 Institut Mines-Telecom
+#
+# 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.
+
+"""
+Created on Jun 12, 2012
+
+@author: Bilel Msekni
+@contact: bilel.msekni@telecom-sudparis.eu
+@author: Houssem Medhioub
+@contact: houssem.medhioub@it-sudparis.eu
+@organization: Institut Mines-Telecom - Telecom SudParis
+@license: Apache License, Version 2.0
+"""
+
+import pyocni.pyocni_tools.config as config
+import pyocni.pyocni_tools.occi_Joker as joker
+import pyocni.pyocni_tools.couchdbdoc_Joker as doc_Joker
+
+import pyocni.pyocni_tools.uuid_Generator as uuid_Generator
+
+try:
+ import simplejson as json
+except ImportError:
+ import json
+
+from pyocni.pyocni_tools.config import return_code
+
+# getting the Logger
+logger = config.logger
+
+class KindManager:
+ """
+
+ Manager for Kind documents on couch database
+
+ """
+
+ def get_filtered_kinds(self, jfilters, db_kinds):
+ """
+ Returns kind documents matching the filter provided
+ Args:
+ @param jfilters: description of the kind document to retrieve
+ @param db_kinds: Kind descriptions that already exist in database
+ @return : OCCI kind description contained inside of the kind document
+ """
+ var = list()
+ #Extract kind descriptions from the dictionary
+ try:
+ for elem in db_kinds:
+ for jfilter in jfilters:
+ ok = joker.filter_occi_description(elem, jfilter)
+ if ok is True:
+ var.append(elem)
+ logger.debug("===== Get_filtered_Kinds: A kind was found =====")
+ break
+ return var, return_code['OK']
+ except Exception as e:
+ logger.error("===== Get_filtered_Kinds: " + e.message + "=====")
+ return "An error has occurred", return_code['Internal Server Error']
+
+
+ def register_kinds(self, descriptions, db_occi_ids, db_occi_locs):
+ """
+ Add new kinds to the database
+ Args:
+ @param descriptions: OCCI kind descriptions
+ @param db_occi_ids: Kind IDs already existing in the database
+ @param db_occi_locs: Kind locations already existing in the database
+ """
+ loc_res = list()
+
+ resp_code = return_code['OK']
+
+ for desc in descriptions:
+ occi_id = joker.get_description_id(desc)
+ ok_k = joker.verify_occi_uniqueness(occi_id, db_occi_ids)
+
+ if ok_k is True:
+ occi_loc = joker.make_category_location(desc)
+ ok_loc = joker.verify_occi_uniqueness(occi_loc, db_occi_locs)
+
+ if ok_loc is True:
+ jData = dict()
+ jData['_id'] = uuid_Generator.get_UUID()
+ jData['OCCI_Location'] = occi_loc
+ jData['OCCI_Description'] = desc
+ jData['OCCI_ID'] = occi_id
+ jData['Type'] = "Kind"
+ jData['Provider'] = {"local": ["dummy"], "remote": []}
+ loc_res.append(jData)
+
+ else:
+ message = "Location conflict, kind will not be created."
+ logger.error("===== Register kind ERROR: " + message + " =====")
+ resp_code = return_code['Conflict']
+ return list(), resp_code
+ else:
+ message = "This kind description already exists in document "
+ logger.error("===== Register kind ERROR: " + message + " =====")
+ resp_code = return_code['Conflict']
+ return list(), resp_code
+
+ return loc_res, resp_code
+
+
+ def update_OCCI_kind_descriptions(self, new_data, db_data):
+ """
+ Updates the OCCI description field of the kind which document OCCI_ID is equal to OCCI_ID contained in data
+ (Should only be done by the creator of the kind document)
+ Args:
+
+ @param new_data: Data containing the OCCI ID of the kind and the new OCCI kind description
+ @param db_data: Categories already contained in the database
+
+ """
+ to_update = list()
+
+ resp_code = return_code['OK']
+
+ for desc in new_data:
+ occi_id = joker.get_description_id(desc)
+ old_doc = joker.extract_doc(occi_id, db_data)
+
+ if old_doc is not None:
+ problems, occi_description = joker.update_occi_category_description(old_doc['OCCI_Description'], desc)
+
+ if problems is True:
+ message = "Kind OCCI description " + occi_id + " has not been totally updated."
+ logger.error("===== Kind OCCI description update:" + message + " =====")
+ return list(), return_code['Bad Request']
+ else:
+ message = "Kind OCCI description " + occi_id + " has been updated successfully"
+ old_doc['OCCI_Description'] = occi_description
+
+ to_update.append(old_doc)
+
+ logger.debug("===== Update kind OCCI description : " + message + " =====")
+
+ else:
+ message = "Kind document " + occi_id + " couldn\'t be found "
+ logger.error("===== Update kind OCCI description : " + message + " =====")
+ return list(), return_code['Not Found']
+
+ return to_update, resp_code
+
+ def update_kind_providers(self, new_data, db_data):
+ """
+ Updates the provider field of the kind which document OCCI_ID is equal to OCCI_ID contained in data
+ (Should only be done by the creator of the kind document)
+ Args:
+
+ @param new_data: Data containing the OCCI ID of the kind and the new kind provider description
+ @param db_data: Categories already contained in the database
+
+ """
+ to_update = list()
+ resp_code = return_code['OK']
+
+ for desc in new_data:
+ occi_id = desc['OCCI_ID']
+ old_doc = joker.extract_doc(occi_id, db_data)
+
+ if old_doc is not None:
+ provider_description, problems = doc_Joker.update_kind_provider(old_doc['Provider'], desc['Provider'])
+
+ if problems is True:
+ message = "Kind provider description " + occi_id + " has not been totally updated."
+ logger.error("===== Kind provider description update " + message + " =====")
+ return list(), return_code['Bad Request']
+ else:
+ message = "Kind provider description " + occi_id + " has been updated successfully"
+ old_doc['Provider'] = provider_description
+
+ to_update.append(old_doc)
+ logger.debug("===== Update kind provider description : " + message + " =====")
+
+ else:
+ message = "Kind document " + occi_id + " couldn\'t be found "
+ logger.error("===== Update kind provider des : " + message + " =====")
+ return list(), return_code['Not Found']
+ return to_update, resp_code
+
+
+ def delete_kind_documents(self, descriptions, db_categories):
+ """
+ Delete kind documents that is related to the scheme + term contained in the description provided
+ Args:
+ @param descriptions: OCCI description of the kind document to delete
+ @param db_categories: Category data already contained in the database
+
+ """
+
+ kind_ref = list()
+ res_code = return_code['OK']
+ #Verify the existence of such kind document
+ for desc in descriptions:
+ occi_id = joker.get_description_id(desc)
+
+ kind_id_rev = joker.verify_exist_occi_id(occi_id, db_categories)
+
+ if kind_id_rev is not None:
+ kind_ref.append(kind_id_rev)
+ event = "Kind document " + occi_id + " is sent for delete "
+ logger.debug("===== Delete_kind_documents : " + event + " =====")
+
+ else:
+ event = "Could not find this kind document " + occi_id
+ logger.error("===== Delete kind : " + event + " ===== ")
+ return list(), return_code['Bad Request']
+
+ return kind_ref, res_code
+
+
+
+ #========================================================================================================================
+ # Independant Functions
+ #========================================================================================================================
+ #
+ # def get_entities_belonging_to_kind(self, occi_id,db_data):
+ # """
+ # Verifies if there are entities of this kind
+ # Args:
+ # @param occi_id: OCCI_ID of the kind
+ # @param db_data: OCCI_IDs of the kind that has entities running
+ # """
+ # try:
+ # db_data.index(occi_id)
+ # except ValueError as e:
+ # logger.debug("Entities belong kind : " + e.message)
+ # return False
+ # return True
\ No newline at end of file
diff --git a/pool/shard009/Python/0086705_jsonToDatabase.py b/pool/shard009/Python/0086705_jsonToDatabase.py
new file mode 100644
index 0000000000000000000000000000000000000000..98ebfcfa91837ccffcacad4c1a6749b953525032
--- /dev/null
+++ b/pool/shard009/Python/0086705_jsonToDatabase.py
@@ -0,0 +1,38 @@
+#-------------------------------------------------------------------------------
+# Name: jsonToDatabase
+# Purpose: decode JSON to Database data
+#
+# Author: Animesh Pandey
+#
+# Created: 05/03/2014
+# Copyright: (c) Animesh Pandey 2014
+#-------------------------------------------------------------------------------
+
+import json
+import sys
+from pprint import pprint
+
+def getDictAttributes(d):
+ for i, j in d.iteritems():
+ if (isinstance(j, dict)):
+ print i
+ getDictAttributes(j)
+ else:
+ pass
+## print "{0} : {1}".format(i, j)
+
+count = 0
+temp = []
+with open('test.json') as f:
+ for l in f:
+ count += 1
+ line = l.strip()
+ json_data = json.loads(line)
+
+ temp.append(line)
+
+## pprint(json_data)
+ getDictAttributes(json_data)
+
+ if count == 1:
+ sys.exit(0)
diff --git a/pool/shard009/Python/0086714_views.py b/pool/shard009/Python/0086714_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..3efb28c097923fc2e28464f9cfafa782800f0a5e
--- /dev/null
+++ b/pool/shard009/Python/0086714_views.py
@@ -0,0 +1,36 @@
+import os
+
+from django.conf import settings
+from django.http import HttpResponse
+from django.views.generic import View
+from knox.auth import TokenAuthentication
+from rest_framework import status
+from rest_framework.generics import GenericAPIView
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+
+
+class IndexView(View):
+ """Render main page."""
+
+ def get(self, request):
+ """Return html for main application page."""
+
+ abspath = open(os.path.join(settings.BASE_DIR, 'static_dist/index.html'), 'r')
+ return HttpResponse(content=abspath.read())
+
+
+class ProtectedDataView(GenericAPIView):
+ """Return protected data main page."""
+
+ authentication_classes = (TokenAuthentication,)
+ permission_classes = (IsAuthenticated,)
+
+ def get(self, request):
+ """Process GET request and return protected data."""
+
+ data = {
+ 'data': 'THIS IS THE PROTECTED STRING FROM SERVER',
+ }
+
+ return Response(data, status=status.HTTP_200_OK)
diff --git a/pool/shard009/Python/0086715_script_interface_object_params.py b/pool/shard009/Python/0086715_script_interface_object_params.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a76b1361e2d761817dd7ccb344eed317458dca
--- /dev/null
+++ b/pool/shard009/Python/0086715_script_interface_object_params.py
@@ -0,0 +1,50 @@
+# Copyright (C) 2010-2018 The ESPResSo project
+#
+# This file is part of ESPResSo.
+#
+# ESPResSo 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.
+#
+# ESPResSo 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 __future__ import division, print_function
+
+import unittest as ut
+
+import espressomd
+
+from espressomd.shapes import Wall, Sphere
+from espressomd.constraints import ShapeBasedConstraint
+
+
+class ScriptInterfaceObjectParams(ut.TestCase):
+
+ """Tests that object parameters are assigned the correct python class"""
+
+ def test(self):
+ c = ShapeBasedConstraint()
+ w = Wall(normal=[-1, 0, 0])
+ c.shape = w
+ # Does the shape parameter return the correct lcass
+ self.assertEqual(c.shape.__class__, Wall)
+ # Do the sciprt object match
+ self.assertEqual(c.shape, w)
+
+ # Different shape
+ c.shape = Sphere(radius=1)
+ # Test class
+ self.assertEqual(c.shape.__class__, Sphere)
+ # Test parameter retrieval
+ self.assertAlmostEqual(c.shape.radius, 1, places=8)
+ with self.assertRaises(ValueError):
+ c.shape = Wall(thisparameterdoesnotexist=0)
+
+if __name__ == "__main__":
+ ut.main()
diff --git a/pool/shard009/Python/0086723_views.py b/pool/shard009/Python/0086723_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab5f60192030d8aed0f55271ff708fa61e70bc2
--- /dev/null
+++ b/pool/shard009/Python/0086723_views.py
@@ -0,0 +1,96 @@
+# Copyright 2012, Nachi Ueno, NTT MCL, 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.core.urlresolvers import reverse
+from django.utils.translation import ugettext_lazy as _
+
+from horizon import exceptions
+from horizon import forms
+from horizon import tabs
+from horizon.utils import memoized
+
+from openstack_dashboard import api
+
+from openstack_dashboard.dashboards.project.routers.ports \
+ import forms as project_forms
+from openstack_dashboard.dashboards.project.routers.ports \
+ import tabs as project_tabs
+
+
+class AddInterfaceView(forms.ModalFormView):
+ form_class = project_forms.AddInterface
+ template_name = 'project/routers/ports/create.html'
+ success_url = 'horizon:project:routers:detail'
+ failure_url = 'horizon:project:routers:detail'
+ page_title = _("Add Interface")
+
+ def get_success_url(self):
+ return reverse(self.success_url,
+ args=(self.kwargs['router_id'],))
+
+ @memoized.memoized_method
+ def get_object(self):
+ try:
+ router_id = self.kwargs["router_id"]
+ return api.neutron.router_get(self.request, router_id)
+ except Exception:
+ redirect = reverse(self.failure_url, args=[router_id])
+ msg = _("Unable to retrieve router.")
+ exceptions.handle(self.request, msg, redirect=redirect)
+
+ def get_context_data(self, **kwargs):
+ context = super(AddInterfaceView, self).get_context_data(**kwargs)
+ context['router'] = self.get_object()
+ return context
+
+ def get_initial(self):
+ router = self.get_object()
+ return {"router_id": self.kwargs['router_id'],
+ "router_name": router.name}
+
+
+class SetGatewayView(forms.ModalFormView):
+ form_class = project_forms.SetGatewayForm
+ template_name = 'project/routers/ports/setgateway.html'
+ success_url = 'horizon:project:routers:index'
+ failure_url = 'horizon:project:routers:index'
+ page_title = _("Set Gateway")
+
+ def get_success_url(self):
+ return reverse(self.success_url)
+
+ @memoized.memoized_method
+ def get_object(self):
+ try:
+ router_id = self.kwargs["router_id"]
+ return api.neutron.router_get(self.request, router_id)
+ except Exception:
+ redirect = reverse(self.failure_url)
+ msg = _("Unable to set gateway.")
+ exceptions.handle(self.request, msg, redirect=redirect)
+
+ def get_context_data(self, **kwargs):
+ context = super(SetGatewayView, self).get_context_data(**kwargs)
+ context['router'] = self.get_object()
+ return context
+
+ def get_initial(self):
+ router = self.get_object()
+ return {"router_id": self.kwargs['router_id'],
+ "router_name": router.name}
+
+
+class DetailView(tabs.TabView):
+ tab_group_class = project_tabs.PortDetailTabs
+ template_name = 'project/networks/ports/detail.html'
diff --git a/pool/shard009/Python/0086731_decode_strings.py b/pool/shard009/Python/0086731_decode_strings.py
new file mode 100644
index 0000000000000000000000000000000000000000..c99fc64e567d8a335c1d496b50f9a8912d1250b7
--- /dev/null
+++ b/pool/shard009/Python/0086731_decode_strings.py
@@ -0,0 +1,78 @@
+"""
+Convert party strings to integers
+"""
+import numpy as np
+
+party_map_str = """
+Centaur 1
+Cosmos 2
+Ebony 3
+Odyssey 4
+Tokugawa 5
+"""
+
+char_party = {}
+char_party_float = {}
+index_party = {}
+for line in party_map_str.strip().split('\n'):
+ ch, index = line.split()
+ char_party_float[ch] = float(index)
+ char_party[ch] = int(index)
+ index_party[float(index)] = ch
+
+
+target_class_str = """
+Centaur 1.,0.,0.,0.,0
+Cosmos 0.,1.,0.,0.,0
+Ebony 0.,0.,1.,0.,0
+Odyssey 0.,0.,0.,1.,0
+Tokugawa 0.,0.,0.,0.,1
+"""
+
+char_target = {}
+index_target = {}
+for line in target_class_str.strip().split('\n'):
+ ch, index = line.split(" ")
+ char_target[ch] = [float(i) for i in index.strip().split(".,")]
+# index_target[index] = ch
+
+"""
+Convert age strings to integers
+"""
+age_map_str = """
+18-24 1
+25-35 2
+36-45 3
+46-55 4
+55+ 5
+"""
+
+char_age = {}
+index_age = {}
+for line in age_map_str.strip().split('\n'):
+ ch, index = line.split()
+ char_age[ch] = float(index)
+ index_age[float(index)] = ch
+
+#print("{}",format(char_age['46-55']))
+"""
+Convert education degrees to integers
+"""
+education_map_str = """
+Primary 1
+Diploma 2
+Degree 3
+Masters 4
+"""
+
+char_education = {}
+index_education = {}
+for line in education_map_str.strip().split('\n'):
+ ch, index = line.split()
+ char_education[ch] = float(index)
+ index_education[float(index)] = ch
+
+
+"""
+Convert ??
+"""
diff --git a/pool/shard009/Python/0086737_pycrunchbase.py b/pool/shard009/Python/0086737_pycrunchbase.py
new file mode 100644
index 0000000000000000000000000000000000000000..88eaa5104ad9126d0b1b0eb588137ea1603c15cb
--- /dev/null
+++ b/pool/shard009/Python/0086737_pycrunchbase.py
@@ -0,0 +1,229 @@
+import requests
+import six
+
+from .resource import (
+ Acquisition,
+ FundingRound,
+ Fund,
+ IPO,
+ Organization,
+ Page,
+ Person,
+ Product,
+)
+
+
+@six.python_2_unicode_compatible
+class CrunchBase(object):
+ """Class that manages talking to CrunchBase API"""
+ BASE_URL = 'https://api.crunchbase.com/v/3/'
+ ORGANIZATIONS_URL = BASE_URL + 'organizations'
+ LOCATIONS_URL = BASE_URL + 'locations'
+ CATEGORIES_URL = BASE_URL + 'categories'
+ PRODUCTS_URL = BASE_URL + 'products'
+
+ def __init__(self, api_key=None):
+ if not api_key:
+ raise ValueError('API key for CrunchBase not supplied')
+ self.api_key = api_key
+
+ def organizations(self, name):
+ """
+ Search for a organization given a name, returns the first
+ :class:`Page` of results
+
+ Returns:
+ Page or None
+ """
+ url = self.ORGANIZATIONS_URL
+ data = self._make_request(url, {'name': name})
+ if not data or data.get('error'):
+ return None
+ return Page(name, data)
+
+ def organization(self, permalink):
+ """Get the details of a organization given a organization's permalink.
+
+ Returns:
+ Organization or None
+ """
+ node_data = self.get_node('organizations', permalink)
+ return Organization(node_data) if node_data else None
+
+ def person(self, permalink):
+ """Helper to maintain backward compatability"""
+ return self.people(permalink)
+
+ def people(self, permalink):
+ """Get the details of a person given a person's permalink
+
+ Returns:
+ Person or None
+ """
+ node_data = self.get_node('people', permalink)
+ return Person(node_data) if node_data else None
+
+ def funding_round(self, uuid):
+ """Get the details of a FundingRound given the uuid.
+
+ Returns
+ FundingRound or None
+ """
+ node_data = self.get_node('funding-rounds', uuid)
+ return FundingRound(node_data) if node_data else None
+
+ def acquisition(self, uuid):
+ """Get the details of a acquisition given a uuid.
+
+ Returns:
+ Acquisition or None
+ """
+ node_data = self.get_node('acquisition', uuid)
+ return Acquisition(node_data) if node_data else None
+
+ def product(self, permalink):
+ """Get the details of a product given a product permalink.
+
+ Returns:
+ Product or None
+ """
+ node_data = self.get_node('product', permalink)
+ return Product(node_data) if node_data else None
+
+ def products(self):
+ """Gets a list of products on CrunchBase"""
+ url = self.PRODUCTS_URL
+ page = self._page('Products', url)
+ return page
+
+ def ipo(self, permalink):
+ """Get the details of an ipo given a ipo uuid.
+
+ Returns:
+ IPO or None
+ """
+ node_data = self.get_node('ipo', permalink)
+ return IPO(node_data) if node_data else None
+
+ def fund(self, permalink):
+ """Get the details of an fundraise given a fundraise uuid.
+
+ Returns:
+ Fund or None
+ """
+ node_data = self.get_node('funds', permalink)
+ return Fund(node_data) if node_data else None
+
+ def fundraise(self, permalink):
+ """Get the details of an fundraise given a fundraise uuid.
+
+ Returns:
+ Fund or None
+ """
+ node_data = self.get_node('funds', permalink)
+ return Fund(node_data) if node_data else None
+
+ def locations(self):
+ """
+ Queries for a list of all active Locations,
+ returns the first :class:`Page` of results.
+
+ Returns:
+ Page or None
+ """
+ url = self.LOCATIONS_URL
+ page = self._page('Locations', url)
+ return page
+
+ def categories(self):
+ """
+ Queries for a list of all active Categories,
+ returns the first :class:`Page` of results.
+
+ Returns:
+ Page or None
+ """
+ url = self.CATEGORIES_URL
+ page = self._page('Categories', url)
+ return page
+
+ def get_node(self, node_type, uuid, params=None):
+ """Get the details of a Node from CrunchBase.
+ The node_type must match that of CrunchBase's, and the uuid
+ is either the {uuid} or {permalink} as stated on their docs.
+
+ Returns:
+ dict: containing the data describing this node with the keys
+ uuid, type, properties, relationships.
+ Or None if there's an error.
+ """
+ node_url = self.BASE_URL + node_type + '/' + uuid
+ data = self._make_request(node_url, params=params)
+ if not data or data.get('error'):
+ return None
+ return data
+
+ def more(self, page):
+ """Given a Page, tries to get more data using the
+ first_page_url or next_page_url given in the response.
+
+ If page happens to be a Relationship, i.e. page.first_page_url
+ is not None, we just call that url to retrieve the first page.
+
+ Returns:
+ None if there is no more page to get, else
+ Relationship with the new data
+ """
+ if page.first_page_url:
+ url_to_call = page.first_page_url
+ return self._page(page.name, url_to_call)
+ elif page.next_page_url:
+ url_to_call = page.next_page_url
+ return self._page(page.name, url_to_call)
+ else:
+ return None
+
+ def _page(self, name, url):
+ """Loads a page for a Node
+
+ Args:
+ name (str): name of page we are getting
+ url (str): url of the page to make the call to
+
+ Returns:
+ page if we can get the data
+ None if we have an error
+ """
+ data = self._make_request(url)
+ if not data or data.get('error'):
+ return None
+ return Page(name, data)
+
+ def _build_url(self, base_url, params=None):
+ """Helper to build urls by appending all queries and the API key.
+ The API key is always the last query parameter."""
+
+ join_char = '&' if '?' in base_url else '?'
+
+ params_string = '&'.join(
+ '%s=%s' % (k, v) for k, v in six.iteritems(params or {}))
+
+ if params_string:
+ params_string += "&user_key=%s" % self.api_key
+ else:
+ params_string = "user_key=%s" % self.api_key
+
+ return base_url + join_char + params_string
+
+ def _make_request(self, url, params=None):
+ """Makes the actual API call to CrunchBase"""
+ final_url = self._build_url(url, params)
+ response = requests.get(final_url)
+ response.raise_for_status()
+ return response.json().get('data')
+
+ def __str__(self):
+ return "pycrunchbase CrunchBase API"
+
+ def __repr__(self):
+ return self.__str__()
diff --git a/pool/shard009/Python/0086739_server.py b/pool/shard009/Python/0086739_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..6df7ee16f90440098386b729221bd847da7238bf
--- /dev/null
+++ b/pool/shard009/Python/0086739_server.py
@@ -0,0 +1,127 @@
+from os.path import join, isfile, abspath
+from xmlrpc.client import Fault
+from xmlrpc.server import SimpleXMLRPCServer
+from xmlrpc.client import ServerProxy
+from urllib.parse import urlparse
+import sys
+
+MAX_HISTORY_LENGTH = 6
+
+UNHANDLED = 100
+ACCESS_DENIED = 200
+
+
+class UnhandleQuery(Fault):
+ def __init__(self, message="Couldn't handle the query"):
+ Fault.__init__(self, UNHANDLED, message)
+
+
+class AccessDenied(Fault):
+ def __init__(self, message="Acces denied"):
+ Fault.__init__(self, ACCESS_DENIED, message)
+
+
+def inside(dir, name):
+ dir = abspath(dir)
+ name = abspath(name)
+ return name.startswith(join(dir, ''))
+
+
+def getPort(url):
+ '在URL中提取端口'
+ name = urlparse(url)[1]
+ parts = name.split(':')
+ return int(parts[-1])
+
+
+class Node:
+ """
+ P2P网络中的节点。
+ """
+
+ def __init__(self, url, dirname, secret):
+ self.url = url
+ self.dirname = dirname
+ self.secret = secret
+ self.known = set()
+
+ def query(self, query, history=[]):
+ """
+ 查询文件,可能会向其他已知节点请求帮助。讲文件作为字符串返回。
+ """
+ print('in function query')
+ try:
+ content = self._handle(query)
+ except:
+
+ history = history + [self.url]
+ print('in funciton query, history : %s' % history)
+ if len(history) >= MAX_HISTORY_LENGTH: raise
+ content = self._broadcast(query, history)
+ return content
+
+ def hello(self, other):
+ """
+ 用于将节点介绍给其他节点。
+ """
+ self.known.add(other)
+ return 0
+
+ def fetch(self, query, secret):
+ """
+ 用于让节点找到文件并且下载。
+ """
+ print(query)
+ print(secret)
+ if secret != self.secret: raise AccessDenied
+ result = self.query(query)
+ print(result)
+ f = open(join(self.dirname, query), 'w')
+ f.write(result)
+ f.close()
+ return 0
+
+ def _start(self):
+ """
+ 内部使用,用于启动XML_RPC服务器。
+ """
+ s = SimpleXMLRPCServer(("", getPort(self.url)))
+ s.register_instance(self)
+ s.serve_forever()
+
+ def _handle(self, query):
+ """
+ 内部使用,用于处理请求。
+ """
+ dir = self.dirname
+ name = join(dir, query)
+ print('in function _handle, file name : %s' % name)
+ if not isfile(name): raise UnhandleQuery
+ if not inside(dir, name): raise AccessDenied
+ return open(name).read()
+
+ def _broadcast(self, query, history):
+ for other in self.known.copy():
+ print('other: %s' % other)
+ if other in history: continue
+ try:
+ s = ServerProxy(other)
+ return s.query(query, history)
+
+ except Fault as f:
+ if f.faultCode == UNHANDLED:
+ pass
+ else:
+ self.known.remove(other)
+ except:
+ self.known.remove(other)
+ raise UnhandleQuery
+
+
+def main():
+ url, directory, secret = sys.argv[1:]
+ n = Node(url, directory, secret)
+ n._start()
+
+
+if __name__ == '__main__': main()
diff --git a/pool/shard009/Python/0086740_test_futures_subscriber.py b/pool/shard009/Python/0086740_test_futures_subscriber.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d41713e6ec85b0d2b61a1d4053f9573cefe4a87
--- /dev/null
+++ b/pool/shard009/Python/0086740_test_futures_subscriber.py
@@ -0,0 +1,65 @@
+# Copyright 2017, Google LLC All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.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 __future__ import absolute_import
+
+import mock
+import pytest
+
+from google.cloud.pubsub_v1.subscriber import futures
+from google.cloud.pubsub_v1.subscriber._protocol import streaming_pull_manager
+
+
+class TestStreamingPullFuture(object):
+ def make_future(self):
+ manager = mock.create_autospec(
+ streaming_pull_manager.StreamingPullManager, instance=True
+ )
+ future = futures.StreamingPullFuture(manager)
+ return future
+
+ def test_default_state(self):
+ future = self.make_future()
+
+ assert future.running()
+ assert not future.done()
+ future._manager.add_close_callback.assert_called_once_with(
+ future._on_close_callback
+ )
+
+ def test__on_close_callback_success(self):
+ future = self.make_future()
+
+ future._on_close_callback(mock.sentinel.manager, None)
+
+ assert future.result() is True
+ assert not future.running()
+
+ def test__on_close_callback_failure(self):
+ future = self.make_future()
+
+ future._on_close_callback(mock.sentinel.manager, ValueError("meep"))
+
+ with pytest.raises(ValueError):
+ future.result()
+
+ assert not future.running()
+
+ def test_cancel(self):
+ future = self.make_future()
+
+ future.cancel()
+
+ future._manager.close.assert_called_once()
+ assert future.cancelled()
diff --git a/pool/shard009/Python/0086754_system.py b/pool/shard009/Python/0086754_system.py
new file mode 100644
index 0000000000000000000000000000000000000000..516405fb35db8b1a1f792aa654e6ccae453e90d7
--- /dev/null
+++ b/pool/shard009/Python/0086754_system.py
@@ -0,0 +1,131 @@
+# -*- coding: utf-8 -*-
+
+"""
+***************************************************************************
+ py
+ ---------------------
+ Date : August 2012
+ Copyright : (C) 2012 by Victor Olaya
+ Email : volayaf at gmail dot com
+***************************************************************************
+* *
+* This program is free software; you can redistribute it and/or modify *
+* it under the terms of the GNU General Public License as published by *
+* the Free Software Foundation; either version 2 of the License, or *
+* (at your option) any later version. *
+* *
+***************************************************************************
+"""
+
+
+__author__ = 'Victor Olaya'
+__date__ = 'August 2012'
+__copyright__ = '(C) 2012, Victor Olaya'
+
+# This will get replaced with a git SHA1 when you do a git archive
+
+__revision__ = '$Format:%H$'
+
+import os
+import time
+import sys
+import uuid
+
+from PyQt4.QtCore import QFileInfo, QDir
+from qgis.core import QgsApplication
+
+numExported = 1
+
+
+def userFolder():
+ userDir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() \
+ + '/processing'
+ if not QDir(userDir).exists():
+ QDir().mkpath(userDir)
+
+ return unicode(QDir.toNativeSeparators(userDir))
+
+
+def isWindows():
+ return os.name == 'nt'
+
+
+def isMac():
+ return sys.platform == 'darwin'
+
+_tempFolderSuffix = unicode(uuid.uuid4()).replace('-', '')
+
+
+def tempFolder():
+ tempDir = os.path.join(unicode(QDir.tempPath()), 'processing' + _tempFolderSuffix)
+ if not QDir(tempDir).exists():
+ QDir().mkpath(tempDir)
+
+ return unicode(os.path.abspath(tempDir))
+
+
+def setTempOutput(out, alg):
+ if hasattr(out, 'directory'):
+ out.value = getTempDirInTempFolder()
+ else:
+ ext = out.getDefaultFileExtension(alg)
+ out.value = getTempFilenameInTempFolder(out.name + '.' + ext)
+
+
+def getTempFilename(ext=None):
+ path = tempFolder()
+ if ext is None:
+ filename = path + os.sep + unicode(time.time()) \
+ + unicode(getNumExportedLayers())
+ else:
+ filename = path + os.sep + unicode(time.time()) \
+ + unicode(getNumExportedLayers()) + '.' + ext
+ return filename
+
+
+def getTempFilenameInTempFolder(basename):
+ """Returns a temporary filename for a given file, putting it into
+ a temp folder but not changing its basename.
+ """
+
+ path = tempFolder()
+ path = os.path.join(path, unicode(uuid.uuid4()).replace('-', ''))
+ mkdir(path)
+ basename = removeInvalidChars(basename)
+ filename = os.path.join(path, basename)
+ return filename
+
+
+def getTempDirInTempFolder():
+ """Returns a temporary directory, putting it into a temp folder.
+ """
+
+ path = tempFolder()
+ path = os.path.join(path, unicode(uuid.uuid4()).replace('-', ''))
+ mkdir(path)
+ return path
+
+
+def removeInvalidChars(string):
+ validChars = \
+ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:.'
+ string = ''.join(c for c in string if c in validChars)
+ return string
+
+
+def getNumExportedLayers():
+ global numExported
+ numExported += 1
+ return numExported
+
+
+def mkdir(newdir):
+ newdir = newdir.strip('\n\r ')
+ if os.path.isdir(newdir):
+ pass
+ else:
+ (head, tail) = os.path.split(newdir)
+ if head and not os.path.isdir(head):
+ mkdir(head)
+ if tail:
+ os.mkdir(newdir)
diff --git a/pool/shard009/Python/0086755_synthese_test.py b/pool/shard009/Python/0086755_synthese_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..65cd494a6a1264d359f4137de572a735eb4ecdab
--- /dev/null
+++ b/pool/shard009/Python/0086755_synthese_test.py
@@ -0,0 +1,176 @@
+# coding=utf-8
+# Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.
+#
+# This file is part of Navitia,
+# the software to build cool stuff with public transport.
+#
+# Hope you'll enjoy and contribute to this project,
+# powered by Canal TP (www.canaltp.fr).
+# Help us simplify mobility and open public transport:
+# a non ending quest to the responsive locomotion way of traveling!
+#
+# LICENCE: 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 .
+#
+# Stay tuned using
+# twitter @navitia
+# IRC #navitia on freenode
+# https://groups.google.com/d/forum/navitia
+# www.navitia.io
+import datetime
+from dateutil.parser import parse
+import mock
+import pytz
+from jormungandr.realtime_schedule.synthese import Synthese
+import validators
+from jormungandr.realtime_schedule.tests.utils import MockRoutePoint, _timestamp
+
+
+def make_url_test():
+ synthese = Synthese(id='tata', timezone='Europe/Paris', service_url='http://bob.com/')
+
+ url = synthese._make_url(MockRoutePoint(route_id='route_tata', line_id='line_toto', stop_id='stop_tutu'))
+
+ # it should be a valid url
+ assert validators.url(url)
+
+ assert url.startswith('http://bob.com/')
+ assert 'SERVICE=tdg' in url
+ assert 'roid=stop_tutu' in url
+ assert 'rn=' not in url # we should not have any limit
+ assert 'date=' not in url # we should not have any custom date
+
+
+def make_url_date_and_count_test():
+ synthese = Synthese(id='tata', timezone='UTC', service_url='http://bob.com/')
+
+ url = synthese._make_url(MockRoutePoint(route_id='route_tata', line_id='line_toto', stop_id='stop_tutu'),
+ count=2, from_dt=_timestamp("12:00"))
+
+ # it should be a valid url
+ assert validators.url(url)
+
+ assert url.startswith('http://bob.com/')
+ assert 'SERVICE=tdg' in url
+ assert 'roid=stop_tutu' in url
+ # we should have the param we provided
+ assert 'rn=2' in url
+ assert 'date=2016-02-07 12:00' in url
+
+
+def make_url_invalid_code_test():
+ """
+ test make_url when RoutePoint does not have a mandatory code
+
+ we should not get any url
+ """
+ synthese = Synthese(id='tata', timezone='Europe/Paris', service_url='http://bob.com/')
+
+ url = synthese._make_url(MockRoutePoint(route_id='route_tata', line_id='line_toto', stop_id=None))
+
+ assert url is None
+
+
+class MockResponse(object):
+ def __init__(self, data, status_code, url, *args, **kwargs):
+ self.content = data
+ self.text = data
+ self.status_code = status_code
+ self.url = url
+
+
+class MockRequests(object):
+
+ def __init__(self, responses):
+ self.responses = responses
+
+ def get(self, url, *args, **kwargs):
+ return MockResponse(self.responses[url][0], self.responses[url][1], url)
+
+
+def mock_good_response():
+ return """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """
+
+
+class MockRequests(object):
+
+ def __init__(self, responses):
+ self.responses = responses
+
+ def get(self, url, *args, **kwargs):
+ return MockResponse(self.responses[url][0], self.responses[url][1], url)
+
+
+def next_passage_for_route_point_test():
+ """
+ test the whole next_passage_for_route_point
+ mock the http call to return a good response, we should get some next_passages
+ """
+ synthese = Synthese(id='tata', timezone='UTC', service_url='http://bob.com/')
+
+ mock_requests = MockRequests({
+ 'http://bob.com/?SERVICE=tdg&roid=stop_tutu':
+ (mock_good_response(), 200)
+ })
+
+ route_point = MockRoutePoint(route_id='route_tata', line_id='line_toto', stop_id='stop_tutu')
+
+ with mock.patch('requests.get', mock_requests.get):
+ passages = synthese.next_passage_for_route_point(route_point)
+
+ assert len(passages) == 3
+
+ assert passages[0].datetime == datetime.datetime(2016, 3, 29, 13, 37, tzinfo=pytz.UTC)
+ assert passages[1].datetime == datetime.datetime(2016, 3, 29, 13, 47, tzinfo=pytz.UTC)
+ assert passages[2].datetime == datetime.datetime(2016, 3, 29, 13, 57, tzinfo=pytz.UTC)
+
+
+def next_passage_for_route_point_failure_test():
+ """
+ test the whole next_passage_for_route_point
+
+ the timeo's response is in error (status = 404), we should get 'None'
+ """
+ synthese = Synthese(id='tata', timezone='UTC', service_url='http://bob.com/')
+
+ mock_requests = MockRequests({
+ 'http://bob.com/?SERVICE=tdg&roid=stop_tutu':
+ (mock_good_response(), 404)
+ })
+
+ route_point = MockRoutePoint(route_id='route_tata', line_id='line_toto', stop_id='stop_tutu')
+
+ with mock.patch('requests.get', mock_requests.get):
+ passages = synthese.next_passage_for_route_point(route_point)
+
+ assert passages is None
+
+def status_test():
+ synthese = Synthese(id='tata', timezone='UTC', service_url='http://bob.com/')
+ status = synthese.status()
+ assert status['id'] == 'tata'
diff --git a/pool/shard009/Python/0086758_sense_test_with_initialstate_integration_and_creeper.py b/pool/shard009/Python/0086758_sense_test_with_initialstate_integration_and_creeper.py
new file mode 100644
index 0000000000000000000000000000000000000000..cee1cf13232d768b49748d2b7ab14cb4a2a73f82
--- /dev/null
+++ b/pool/shard009/Python/0086758_sense_test_with_initialstate_integration_and_creeper.py
@@ -0,0 +1,55 @@
+from sense_hat import SenseHat
+import time
+import sys
+from ISStreamer.Streamer import Streamer
+
+logger = Streamer(bucket_name="Sense Hat Environment Stream", access_key="zLahwAUqKbNKv6YvuT5JuO58EiUOavDa")
+
+sense = SenseHat()
+sense.clear()
+var = 14400
+
+O = (0, 255, 0) # Green
+X = (0, 0, 0) # Black
+
+creeper_pixels = [
+ O, O, O, O, O, O, O, O,
+ O, O, O, O, O, O, O, O,
+ O, X, X, O, O, X, X, O,
+ O, X, X, O, O, X, X, O,
+ O, O, O, X, X, O, O, O,
+ O, O, X, X, X, X, O, O,
+ O, O, X, X, X, X, O, O,
+ O, O, X, O, O, X, O, O
+]
+
+black_pixels = [
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X,
+ X, X, X, X, X, X, X, X
+]
+
+while var > 0:
+ temp = sense.get_temperature()
+ temp = round(temp, 1)
+ logger.log("Teperature C",temp)
+ humidity = sense.get_humidity()
+ humidity = round(humidity, 1)
+ logger.log("Humidity :",humidity)
+ pressure = sense.get_pressure()
+ pressure = round(pressure, 1)
+ logger.log("Pressure:",pressure)
+ var = var -1
+ logger.log("Seconds Until Script Exit",var)
+ sense.set_pixels(creeper_pixels)
+ time.sleep(5)
+ sense.set_pixels(black_pixels)
+ time.sleep(25)
+ sense.clear()
+ if var == 0:
+ sys.exit()
diff --git a/pool/shard009/Python/0086759_gzippeddict.py b/pool/shard009/Python/0086759_gzippeddict.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f264ce84e6b352618cd90ba3d1973131d5de473
--- /dev/null
+++ b/pool/shard009/Python/0086759_gzippeddict.py
@@ -0,0 +1,57 @@
+"""
+sentry.db.models.fields.gzippeddict
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
+:license: BSD, see LICENSE for more details.
+"""
+
+from __future__ import absolute_import, print_function
+
+import logging
+import six
+
+from django.db import models
+from south.modelsinspector import add_introspection_rules
+
+from sentry.utils.compat import pickle
+from sentry.utils.strings import decompress, compress
+
+__all__ = ('GzippedDictField',)
+
+logger = logging.getLogger('sentry.errors')
+
+
+class GzippedDictField(models.TextField):
+ """
+ Slightly different from a JSONField in the sense that the default
+ value is a dictionary.
+ """
+ __metaclass__ = models.SubfieldBase
+
+ def to_python(self, value):
+ if isinstance(value, six.string_types) and value:
+ try:
+ value = pickle.loads(decompress(value))
+ except Exception as e:
+ logger.exception(e)
+ return {}
+ elif not value:
+ return {}
+ return value
+
+ def get_prep_value(self, value):
+ if not value and self.null:
+ # save ourselves some storage
+ return None
+ # enforce unicode strings to guarantee consistency
+ if isinstance(value, str):
+ value = six.text_type(value)
+ return compress(pickle.dumps(value))
+
+ def value_to_string(self, obj):
+ value = self._get_val_from_obj(obj)
+ return self.get_prep_value(value)
+
+
+add_introspection_rules([], ["^sentry\.db\.models\.fields\.gzippeddict\.GzippedDictField"])
diff --git a/pool/shard009/Python/0086761_philosophes.py b/pool/shard009/Python/0086761_philosophes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a44f0348c6847a47306d910aaf6044f60a23eb60
--- /dev/null
+++ b/pool/shard009/Python/0086761_philosophes.py
@@ -0,0 +1,94 @@
+# -*- coding: utf-8 -*-
+
+import threading
+import time
+import random
+
+
+class Philosophe(threading.Thread):
+
+ tempsRepas = 2
+ couverts = None
+
+ def __init__(self, nom):
+ self.nom = nom
+ self.compteur = 0
+ if Philosophe.couverts is None:
+ Philosophe.couverts = threading.Lock()
+ threading.Thread.__init__(self)
+
+ def attendreCouverts(self):
+ while not Philosophe.couverts.acquire(False):
+ self.reflechir()
+ time.sleep(0.2)
+
+ def rendreCouverts(self):
+ Philosophe.couverts.release()
+
+ def reflechir(self):
+ print(self.nom + " réfléchit\n")
+
+ def manger(self):
+ time.sleep(0.5)
+ self.attendreCouverts()
+ self.compteur = self.compteur + 1
+ print(self.nom + " mange son repas " + str(self.compteur) + "\n")
+ time.sleep(Philosophe.tempsRepas)
+ self.rendreCouverts()
+
+ def run(self):
+
+ while self.compteur < 5:
+ self.reflechir()
+ self.manger()
+ time.sleep(0.5)
+
+ print(self.nom + " se retire\n")
+
+
+
+
+
+
+
+
+
+
+
+lsPhi=[]
+
+for i in range(7):
+ lsPhi += [ Philosophe("Philosophe n° {}".format(i))]
+
+
+random.shuffle (lsPhi)
+
+for philo in lsPhi:
+ philo.start()
+
+for philo in lsPhi:
+ philo.join()
+
+print "Fini pour les philosophes!"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pool/shard009/Python/0086764_warnings.py b/pool/shard009/Python/0086764_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7418074ce29877d7772cf9b4cbe8c5978e8a26e
--- /dev/null
+++ b/pool/shard009/Python/0086764_warnings.py
@@ -0,0 +1,43 @@
+# testing/warnings.py
+# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
+#
+#
+# This module is part of SQLAlchemy and is released under
+# the MIT License: http://www.opensource.org/licenses/mit-license.php
+"""NOTE: copied/adapted from SQLAlchemy master for backwards compatibility;
+ this should be removable when Alembic targets SQLAlchemy 0.9.4.
+"""
+
+from __future__ import absolute_import
+
+import warnings
+from sqlalchemy import exc as sa_exc
+import re
+
+
+def setup_filters():
+ """Set global warning behavior for the test suite."""
+
+ warnings.filterwarnings('ignore',
+ category=sa_exc.SAPendingDeprecationWarning)
+ warnings.filterwarnings('error', category=sa_exc.SADeprecationWarning)
+ warnings.filterwarnings('error', category=sa_exc.SAWarning)
+
+
+def assert_warnings(fn, warning_msgs, regex=False):
+ """Assert that each of the given warnings are emitted by fn."""
+
+ from .assertions import eq_
+
+ with warnings.catch_warnings(record=True) as log:
+ # ensure that nothing is going into __warningregistry__
+ warnings.filterwarnings("always")
+
+ result = fn()
+ for warning in log:
+ popwarn = warning_msgs.pop(0)
+ if regex:
+ assert re.match(popwarn, str(warning.message))
+ else:
+ eq_(popwarn, str(warning.message))
+ return result
diff --git a/pool/shard009/Python/0086766_test_rhythmtransform.py b/pool/shard009/Python/0086766_test_rhythmtransform.py
new file mode 100644
index 0000000000000000000000000000000000000000..6602c48c37ae15061f73f5dbd2ef1751f16e936a
--- /dev/null
+++ b/pool/shard009/Python/0086766_test_rhythmtransform.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+
+# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
+#
+# This file is part of Essentia
+#
+# Essentia 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 (FSF), 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 Affero GNU General Public License
+# version 3 along with this program. If not, see http://www.gnu.org/licenses/
+
+
+from essentia_test import *
+import numpy as np
+
+listZeros=[[0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
+ 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
+ 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
+ 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
+ 0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,
+ 0.,0.,0.,0.,0.,0.,0.,0.,0.]]
+
+class TestRhythmTransform(TestCase):
+
+ def testInvalidParam(self):
+ self.assertConfigureFails(RhythmTransform(), {'frameSize': -1})
+ self.assertConfigureFails(RhythmTransform(), {'hopSize': -1})
+
+ def testRegression(self):
+ # Simple regression test, comparing normal behaviour
+ sampleRate = 44100
+ melFrameSize = 8192
+ melHopSize = 1024
+ rtFrameSize = 256
+ rtHopSize = 32
+ audio = MonoLoader(filename = join(testdata.audio_dir, 'recorded', 'techno_loop.wav'),sampleRate=sampleRate)()
+
+ w = Windowing(type='blackmanharris62')
+ spectrum = Spectrum()
+ melbands = MelBands(sampleRate=sampleRate, numberBands=40, lowFrequencyBound=0, highFrequencyBound=sampleRate/2)
+
+ pool = Pool()
+ for frame in FrameGenerator(audio=audio, frameSize=melFrameSize, hopSize=melHopSize, startFromZero=True):
+ pool.add('melbands', melbands(spectrum(w(frame))))
+
+ #print("Mel band frames: %d" % len(pool['melbands']))
+ #print("Rhythm transform frames: %d" % int(len(pool['melbands']) / 32))
+
+ rhythmtransform = RhythmTransform(frameSize=rtFrameSize, hopSize=rtHopSize)
+ rt = rhythmtransform(pool['melbands'])
+
+ # This code stores reference values in a file for later loading.
+ # np.save('rhythmtransform.npy', rt)
+
+ # Reference samples are loaded as expected values
+ expected_rhythmtransform_npy = np.load(join(filedir(), 'rhythmtransform/rhythmtransform.npy'))
+
+ # Loop through all Melframes to regression test each one against the file reference values.
+ index = 0
+ while index.
+#
+
+"""
+URLs for the matrix-synapse module.
+"""
+
+from django.conf.urls import url
+
+from .views import SetupView, ServiceView
+
+urlpatterns = [
+ url(r'^apps/matrixsynapse/setup/$', SetupView.as_view(), name='setup'),
+ url(r'^apps/matrixsynapse/$', ServiceView.as_view(), name='index'),
+]
diff --git a/pool/shard009/Python/0086773_production.py b/pool/shard009/Python/0086773_production.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3446e778ab2196af50230fde6bf17750dbb0866
--- /dev/null
+++ b/pool/shard009/Python/0086773_production.py
@@ -0,0 +1,148 @@
+# -*- coding: utf-8 -*-
+'''
+Production Configurations
+
+- Use djangosecure
+- Use Amazon's S3 for storing static files and uploaded media
+- Use mailgun to send emails
+- Use Redis on Heroku
+
+'''
+from __future__ import absolute_import, unicode_literals
+
+from boto.s3.connection import OrdinaryCallingFormat
+from django.utils import six
+
+
+from .common import * # noqa
+
+# SECRET CONFIGURATION
+# ------------------------------------------------------------------------------
+# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
+# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
+SECRET_KEY = env("DJANGO_SECRET_KEY")
+
+# This ensures that Django will be able to detect a secure connection
+# properly on Heroku.
+SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
+
+# django-secure
+# ------------------------------------------------------------------------------
+INSTALLED_APPS += ("djangosecure", )
+
+SECURITY_MIDDLEWARE = (
+ 'djangosecure.middleware.SecurityMiddleware',
+)
+
+
+# Make sure djangosecure.middleware.SecurityMiddleware is listed first
+MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES
+
+# set this to 60 seconds and then to 518400 when you can prove it works
+SECURE_HSTS_SECONDS = 60
+SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
+ "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
+SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
+SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
+ "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
+SECURE_BROWSER_XSS_FILTER = True
+SESSION_COOKIE_SECURE = False
+SESSION_COOKIE_HTTPONLY = True
+SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
+
+# SITE CONFIGURATION
+# ------------------------------------------------------------------------------
+# Hosts/domain names that are valid for this site
+# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
+ALLOWED_HOSTS = ["*"]
+# END SITE CONFIGURATION
+
+INSTALLED_APPS += ("gunicorn", )
+
+# STORAGE CONFIGURATION
+# ------------------------------------------------------------------------------
+# Uploaded Media Files
+# ------------------------
+# See: http://django-storages.readthedocs.org/en/latest/index.html
+#INSTALLED_APPS += (
+# 'storages',
+#)
+#DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
+#
+#AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
+#AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
+#AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
+#AWS_AUTO_CREATE_BUCKET = True
+#AWS_QUERYSTRING_AUTH = False
+#AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()
+#
+# AWS cache settings, don't change unless you know what you're doing:
+#AWS_EXPIRY = 60 * 60 * 24 * 7
+#
+# TODO See: https://github.com/jschneier/django-storages/issues/47
+# Revert the following and use str after the above-mentioned bug is fixed in
+# either django-storage-redux or boto
+#AWS_HEADERS = {
+# 'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
+# AWS_EXPIRY, AWS_EXPIRY))
+#}
+
+# URL that handles the media served from MEDIA_ROOT, used for managing
+# stored files.
+#MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
+
+# Static Assests
+# ------------------------
+#STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
+
+
+# EMAIL
+# ------------------------------------------------------------------------------
+DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
+ default='forocacao ')
+#EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
+EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')
+#MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY')
+#MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME')
+EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[forocacao] ')
+SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
+EMAIL_HOST = env('DJANGO_EMAIL_HOST', default='localhost')
+EMAIL_PORT = env('DJANGO_EMAIL_PORT', default=25)
+EMAIL_HOST_USER = env('DJANGO_EMAIL_HOST_USER', default='')
+EMAIL_HOST_PASSWORD = env('DJANGO_EMAIL_HOST_PASSWORD', default='')
+EMAIL_USE_TLS = env('DJANGO_EMAIL_USE_TLS', default=False)
+EMAIL_USE_SSL = env('DJANGO_EMAIL_USE_SSL', default=False)
+EMAIL_SSL_CERTFILE = env('DJNAGO_EMAIL_SSL_CERTFILE', default=None)
+
+
+# TEMPLATE CONFIGURATION
+# ------------------------------------------------------------------------------
+# See:
+# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
+TEMPLATES[0]['OPTIONS']['loaders'] = [
+ ('django.template.loaders.cached.Loader', [
+ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),
+]
+
+# DATABASE CONFIGURATION
+# ------------------------------------------------------------------------------
+# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
+DATABASES['default'] = env.db("DATABASE_URL")
+
+# CACHING
+# ------------------------------------------------------------------------------
+# Heroku URL does not pass the DB number, so we parse it in
+CACHES = {
+ "default": {
+ "BACKEND": "django_redis.cache.RedisCache",
+ "LOCATION": "{0}/{1}".format(env.cache_url('REDIS_URL', default="redis://127.0.0.1:6379"), 0),
+ "OPTIONS": {
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
+ "IGNORE_EXCEPTIONS": True, # mimics memcache behavior.
+ # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
+ }
+ }
+}
+
+
+# Your production stuff: Below this line define 3rd party library settings
diff --git a/pool/shard009/Python/0086775_storage_subformat_base_test.py b/pool/shard009/Python/0086775_storage_subformat_base_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..2365d241c86df50f0ca223b53bb5253c9ca8aa06
--- /dev/null
+++ b/pool/shard009/Python/0086775_storage_subformat_base_test.py
@@ -0,0 +1,119 @@
+from mock import patch
+
+import mock
+
+from .test_helper import raises
+
+from kiwi.exceptions import (
+ KiwiFormatSetupError,
+ KiwiResizeRawDiskError
+)
+
+from kiwi.storage.subformat.base import DiskFormatBase
+
+
+class TestDiskFormatBase(object):
+ @patch('platform.machine')
+ def setup(self, mock_machine):
+ mock_machine.return_value = 'x86_64'
+ xml_data = mock.Mock()
+ xml_data.get_name = mock.Mock(
+ return_value='some-disk-image'
+ )
+ self.xml_state = mock.Mock()
+ self.xml_state.xml_data = xml_data
+ self.xml_state.get_image_version = mock.Mock(
+ return_value='1.2.3'
+ )
+ self.disk_format = DiskFormatBase(
+ self.xml_state, 'root_dir', 'target_dir'
+ )
+
+ @raises(NotImplementedError)
+ def test_create_image_format(self):
+ self.disk_format.create_image_format()
+
+ @raises(KiwiFormatSetupError)
+ def test_get_target_file_path_for_format_invalid_format(self):
+ self.disk_format.get_target_file_path_for_format('foo')
+
+ def test_post_init(self):
+ self.disk_format.post_init({'option': 'unhandled'})
+ assert self.disk_format.custom_args == {}
+
+ def test_get_qemu_option_list(self):
+ custom_args = {
+ 'subformat=format': None,
+ 'adapter_type=type': None
+ }
+ assert self.disk_format.get_qemu_option_list(custom_args) == [
+ '-o', 'adapter_type=type', '-o', 'subformat=format'
+ ]
+
+ def test_get_target_file_path_for_format(self):
+ assert self.disk_format.get_target_file_path_for_format('vhd') == \
+ 'target_dir/some-disk-image.x86_64-1.2.3.vhd'
+
+ def test_store_to_result(self):
+ result = mock.Mock()
+ self.disk_format.image_format = 'qcow2'
+ self.disk_format.store_to_result(result)
+ result.add.assert_called_once_with(
+ compress=False,
+ filename='target_dir/some-disk-image.x86_64-1.2.3.qcow2',
+ key='disk_format_image',
+ shasum=True,
+ use_for_bundle=True
+ )
+
+ @raises(KiwiResizeRawDiskError)
+ @patch('os.path.getsize')
+ def test_resize_raw_disk_raises_on_shrink_disk(self, mock_getsize):
+ mock_getsize.return_value = 42
+ self.disk_format.resize_raw_disk(10)
+
+ @patch('os.path.getsize')
+ @patch('kiwi.storage.subformat.base.Command.run')
+ def test_resize_raw_disk(self, mock_command, mock_getsize):
+ mock_getsize.return_value = 42
+ assert self.disk_format.resize_raw_disk(1024) is True
+ mock_command.assert_called_once_with(
+ [
+ 'qemu-img', 'resize',
+ 'target_dir/some-disk-image.x86_64-1.2.3.raw', '1024'
+ ]
+ )
+
+ @patch('os.path.getsize')
+ @patch('kiwi.storage.subformat.base.Command.run')
+ def test_resize_raw_disk_append(self, mock_command, mock_getsize):
+ mock_getsize.return_value = 42
+ assert self.disk_format.resize_raw_disk(1024, append=True) is True
+ mock_command.assert_called_once_with(
+ [
+ 'qemu-img', 'resize',
+ 'target_dir/some-disk-image.x86_64-1.2.3.raw', '+1024'
+ ]
+ )
+
+ @patch('os.path.getsize')
+ def test_resize_raw_disk_same_size(self, mock_getsize):
+ mock_getsize.return_value = 42
+ assert self.disk_format.resize_raw_disk(42) is False
+
+ @patch('os.path.exists')
+ def test_has_raw_disk(self, mock_exists):
+ mock_exists.return_value = True
+ assert self.disk_format.has_raw_disk() is True
+ mock_exists.assert_called_once_with(
+ 'target_dir/some-disk-image.x86_64-1.2.3.raw'
+ )
+
+ @patch('kiwi.storage.subformat.base.Path.wipe')
+ @patch('os.path.exists')
+ def test_destructor(self, mock_exists, mock_wipe):
+ mock_exists.return_value = True
+ self.disk_format.temp_image_dir = 'tmpdir'
+ self.disk_format.__del__()
+ self.disk_format.temp_image_dir = None
+ mock_wipe.assert_called_once_with('tmpdir')
diff --git a/pool/shard009/Python/0086776_play-url.py b/pool/shard009/Python/0086776_play-url.py
new file mode 100644
index 0000000000000000000000000000000000000000..086059742ab009ba1d4076e4d904c39291c8deaf
--- /dev/null
+++ b/pool/shard009/Python/0086776_play-url.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+
+from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
+import urlparse
+import logging
+from xml.dom.minidom import Document
+
+logging.basicConfig(level=logging.DEBUG)
+
+class MegaAwesomePythonServer(BaseHTTPRequestHandler):
+
+ def do_POST(self):
+ length = int(self.headers.getheader('Content-Length'))
+ data = urlparse.parse_qs(self.rfile.read(length))
+
+ logging.debug("from: " + data.get("from")[0])
+ logging.debug("to: " + data.get("to")[0])
+ logging.debug("direction: " + data.get("direction")[0])
+
+ doc = Document()
+ response = doc.createElement('Response')
+ play = doc.createElement('Play')
+ url = doc.createElement('Url')
+ urlString = doc.createTextNode('http://www.example.com/example.wav')
+ url.appendChild(urlString)
+ play.appendChild(url)
+ response.appendChild(play)
+ doc.appendChild(response)
+
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/xml')
+ self.end_headers()
+ self.wfile.write(doc.toxml())
+
+
+server = HTTPServer(('', 3000), MegaAwesomePythonServer)
+server.serve_forever()
diff --git a/pool/shard009/Python/0086777_loading_modifying_writing.py b/pool/shard009/Python/0086777_loading_modifying_writing.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8221f3687350e610687d2b95eb44b8a622f2593
--- /dev/null
+++ b/pool/shard009/Python/0086777_loading_modifying_writing.py
@@ -0,0 +1,61 @@
+"""
+In this example an axon is built, a morphology is loaded, the axon is
+then connected to the loadeed morphology.
+"""
+
+import neuroml
+import neuroml.loaders as loaders
+import neuroml.writers as writers
+
+fn = './test_files/Purk2M9s.nml'
+doc = loaders.NeuroMLLoader.load(fn)
+print("Loaded morphology file from: "+fn)
+
+#get the parent segment:
+parent_segment = doc.cells[0].morphology.segments[0]
+
+parent = neuroml.SegmentParent(segments=parent_segment.id)
+
+#make an axon:
+seg_id = 5000 # need a way to get a unique id from a morphology
+axon_segments = []
+for i in range(10):
+ p = neuroml.Point3DWithDiam(x=parent_segment.distal.x,
+ y=parent_segment.distal.y,
+ z=parent_segment.distal.z,
+ diameter=0.1)
+
+ d = neuroml.Point3DWithDiam(x=parent_segment.distal.x+10,
+ y=parent_segment.distal.y,
+ z=parent_segment.distal.z,
+ diameter=0.1)
+
+ axon_segment = neuroml.Segment(proximal = p,
+ distal = d,
+ parent = parent)
+
+ axon_segment.id = seg_id
+
+ axon_segment.name = 'axon_segment_' + str(axon_segment.id)
+
+ #now reset everything:
+ parent = neuroml.SegmentParent(segments=axon_segment.id)
+ parent_segment = axon_segment
+ seg_id += 1
+
+ axon_segments.append(axon_segment)
+
+doc.cells[0].morphology.segments += axon_segments
+
+nml_file = './tmp/modified_morphology.nml'
+
+writers.NeuroMLWriter.write(doc,nml_file)
+
+print("Saved modified morphology file to: "+nml_file)
+
+
+###### Validate the NeuroML ######
+
+from neuroml.utils import validate_neuroml2
+
+validate_neuroml2(nml_file)
diff --git a/pool/shard009/Python/0086780_plot_colorbars.py b/pool/shard009/Python/0086780_plot_colorbars.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fa016501de001eda166bbce5a200a8f0712373c
--- /dev/null
+++ b/pool/shard009/Python/0086780_plot_colorbars.py
@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) Vispy Development Team. All Rights Reserved.
+# Distributed under the (new) BSD License. See LICENSE.txt for more info.
+"""
+Show use of colorbars in plot
+"""
+import vispy.plot as vp
+
+fig = vp.Fig(size=(600, 500), show=False)
+plotwidget = fig[0, 0]
+
+fig.title = "bollu"
+plotwidget.plot([(x, x**2) for x in range(0, 100)], title="y = x^2")
+plotwidget.colorbar(position="top", cmap="autumn")
+
+if __name__ == '__main__':
+ fig.show(run=True)
diff --git a/pool/shard009/Python/0086781_action.py b/pool/shard009/Python/0086781_action.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9722aaa03a5c409756c0ebc556daec757e0310f
--- /dev/null
+++ b/pool/shard009/Python/0086781_action.py
@@ -0,0 +1,13 @@
+import digitalocean
+from st2actions.runners.pythonrunner import Action
+
+
+class BaseAction(Action):
+
+ def __init__(self, config):
+ super(BaseAction, self).__init__(config)
+ self._token = config['token']
+
+ def do_action(self,cls,action,**kwargs):
+ obj = getattr(digitalocean,cls)(token=self._token)
+ return getattr(obj,action)(**kwargs)
diff --git a/pool/shard009/Python/0086782_baremetal_nodes_client.py b/pool/shard009/Python/0086782_baremetal_nodes_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9a712ee9b7892e27cfc53e982e116b5b94eb01b
--- /dev/null
+++ b/pool/shard009/Python/0086782_baremetal_nodes_client.py
@@ -0,0 +1,42 @@
+# Copyright 2015 NEC Corporation. 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.
+
+from oslo_serialization import jsonutils as json
+from six.moves.urllib import parse as urllib
+
+from tempest.lib.api_schema.response.compute.v2_1 import baremetal_nodes \
+ as schema
+from tempest.lib.common import rest_client
+
+
+class BaremetalNodesClient(rest_client.RestClient):
+ """Tests Baremetal API"""
+
+ def list_baremetal_nodes(self, **params):
+ """List all baremetal nodes."""
+ url = 'os-baremetal-nodes'
+ if params:
+ url += '?%s' % urllib.urlencode(params)
+ resp, body = self.get(url)
+ body = json.loads(body)
+ self.validate_response(schema.list_baremetal_nodes, resp, body)
+ return rest_client.ResponseBody(resp, body)
+
+ def show_baremetal_node(self, baremetal_node_id):
+ """Return the details of a single baremetal node."""
+ url = 'os-baremetal-nodes/%s' % baremetal_node_id
+ resp, body = self.get(url)
+ body = json.loads(body)
+ self.validate_response(schema.get_baremetal_node, resp, body)
+ return rest_client.ResponseBody(resp, body)
diff --git a/pool/shard009/Python/0086785_server.py b/pool/shard009/Python/0086785_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..34dd49b16c028eb8e1041a1c074f0ae62fa8b750
--- /dev/null
+++ b/pool/shard009/Python/0086785_server.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+
+# Copyright 2016 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import argparse
+import os
+import subprocess
+import sys
+import tempfile
+
+LIGHTTPD_CONF = """
+server.document-root = "{root}"
+server.port = {port}
+mimetype.assign = (
+ ".html" => "text/html"
+)
+"""
+
+def run_lighttpd(conf):
+ """Run lighttpd in a subprocess and block until it exits.
+
+ Takes the lighttpd configuration file as a string.
+ """
+ with tempfile.NamedTemporaryFile() as conf_file:
+ conf_file.write(conf)
+ conf_file.file.close()
+ server = subprocess.Popen(['lighttpd', '-D', '-f', conf_file.name])
+ try:
+ server.wait()
+ except KeyboardInterrupt:
+ # Let lighttpd handle the signal.
+ server.wait()
+
+def main():
+ script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
+ data_dir = os.path.join(script_dir, 'data')
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument('-p', '--port', default=3000)
+ args = parser.parse_args()
+
+ conf = LIGHTTPD_CONF.format(port=args.port, root=data_dir)
+ print conf
+ run_lighttpd(conf)
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0086786_Danu.py b/pool/shard009/Python/0086786_Danu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e2366d61a170df911466e2b4c5e0af19db0cd70
--- /dev/null
+++ b/pool/shard009/Python/0086786_Danu.py
@@ -0,0 +1,157 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+# MIT License
+# Copyright (C) 2013-2014 sitic
+
+import pywikibot
+import pywikibot.date
+import time
+
+#what should be snapshoted?
+mainPageTitle = {
+ 'en' : u'Main Page',
+ 'de' : u'Wikipedia:Hauptseite'
+}
+#will be added at the top of the snapshoted page
+archivePageIntro = {
+ 'en' : u'',
+ 'de' : u'{{{{Wikipedia:Hauptseite/Archiv/Vorlage|Tag={day}|Monat={month}|Jahr={year}}}}}\n{{{{bots|denyscript=delinker}}}}\n'
+}
+#where to put the snapshoted page
+archiveTitlePrefix = {
+ 'en' : u'Wikipedia:Main Page history/',
+ 'de' : u'Wikipedia:Hauptseite/Archiv/'
+}
+#script will generate pages archiveTitlePrefix + localize(dateformat)
+dateformat = {
+ 'en' : u'{year} {monthName} {day}',
+ 'de' : u'{day}. {monthName} {year}'
+}
+#where to update the template
+templateTitle = {
+ 'en' : u'Template:Main Page history',
+ 'de' : u'Wikipedia:Hauptseite/Archiv'
+}
+archiveComment = {
+ 'en' : u'Bot: creating snapshot of the current [[Main Page]]',
+ 'de' : u'[[WP:Bot|Bot]]: erstelle Abbild der heutigen [[Wikipedia:Hauptseite|Hauptseite]]'
+}
+newMonthComment = {
+ 'en' : u'Bot: adding links to next month',
+ 'de' : u'[[WP:Bot|Bot]]: Vorbereitung für den nächsten Monat'
+}
+
+class SnapMain():
+ def __init__(self):
+ self.site = pywikibot.Site()
+ self.site.login()
+
+ self.day = time.localtime().tm_mday
+ self.month = time.localtime().tm_mon
+ self.monthName = pywikibot.date.monthName(self.site.language(),
+ self.month)
+ if self.month == 12: # end of the year?
+ self.nextmonthName = pywikibot.date.monthName(self.site.language(),
+ 1)
+ else:
+ self.nextmonthName = pywikibot.date.monthName(self.site.language(),
+ self.month + 1)
+
+ self.year = time.localtime().tm_year
+ self.nextyear = time.localtime().tm_year + 1
+
+ self.snap()
+
+ self.maxDays = pywikibot.date.getNumberOfDaysInMonth(
+ time.localtime().tm_mon)
+ if time.localtime().tm_mday == self.maxDays: #end of the month?
+ pass
+ #self.new_month()
+
+ def format_date(self, day, monthName, year):
+ """
+ return a string with the formated date (e.g. u'31. Dezember 2013')
+ """
+ l_dateformat = pywikibot.translate(self.site, dateformat,
+ fallback=False)
+ return l_dateformat.format(day=day, monthName=monthName, year=year)
+
+ def isleapyear(self, n):
+ if n % 400 == 0:
+ return True
+ if n % 100 == 0:
+ return False
+ if n % 4 == 0:
+ return True
+ else:
+ return False
+
+
+ def snap(self):
+ pywikibot.output(u'creating snapshot for today: ' +
+ self.format_date(self.day, self.monthName, self.year))
+ l_mainPageTitle = pywikibot.translate(self.site, mainPageTitle,
+ fallback=False)
+ l_archiveTitlePrefix = pywikibot.translate(self.site,
+ archiveTitlePrefix, fallback=False)
+ l_archivePageIntro = pywikibot.translate(self.site, archivePageIntro,
+ fallback=False)
+ l_archiveComment = pywikibot.translate(self.site, archiveComment,
+ fallback=False)
+
+ l_archivePageIntro = l_archivePageIntro.format(day=time.strftime('%d'),
+ month=time.strftime('%m'), year=self.year)
+
+ mainPage = pywikibot.Page(self.site, l_mainPageTitle)
+ date = self.format_date(self.day, self.monthName, self.year)
+ archivePage = pywikibot.Page(self.site, l_archiveTitlePrefix + date)
+
+ archivePage.text = pywikibot.textlib.removeLanguageLinks(mainPage.expand_text())
+ archivePage.text = pywikibot.textlib.removeCategoryLinks(archivePage.text)
+ archivePage.text = l_archivePageIntro + archivePage.text
+
+ archivePage.save(comment=l_archiveComment, botflag=True, minor=False, force=True)
+
+ def new_month(self):
+ pywikibot.output(u'new month, updating template')
+ l_archiveTitlePrefix = pywikibot.translate(self.site,
+ archiveTitlePrefix, fallback=False)
+ l_templateTitle = pywikibot.translate(self.site, templateTitle,
+ fallback=False)
+ l_newMonthComment = pywikibot.translate(self.site, newMonthComment,
+ fallback=False)
+
+ templatePage = pywikibot.Page(self.site, l_templateTitle)
+ if time.localtime().tm_mon == 12: # end of the year?
+ newYearTable = u'\n\n\n{{|\n|+ \'\'\'{year}\'\'\'\n|}}'
+ templatePage.text += newYearTable.format(year=self.nextyear)
+
+ self.year = self.nextyear
+ maxDays = 31 #January
+ else:
+ #check for leap year, getNumberOfDaysInMonth() does not do that
+ if self.isleapyear(self.year) and time.localtime().tm_mon == 1:
+ maxDays = 29
+ else:
+ maxDays = pywikibot.date.getNumberOfDaysInMonth(
+ time.localtime().tm_mon + 1)
+
+ if self.format_date(1, self.nextmonthName, self.year) in templatePage.text:
+ #template page is already up to date
+ return
+
+ templatePage.text = templatePage.text[:-1] + u'-\n| ' + self.nextmonthName
+
+ for i in range(1, maxDays + 1):
+ templatePage.text += u'|| [[' + l_archiveTitlePrefix +\
+ self.format_date(i, self.nextmonthName, self.year) +\
+ u'|' + i.__str__() + u']]'
+
+ templatePage.text += u'\n|}'
+ templatePage.save(comment=l_newMonthComment, botflag=True, minor=False)
+
+if __name__ == "__main__":
+ try:
+ SnapMain()
+ finally:
+ pywikibot.stopme()
diff --git a/pool/shard009/Python/0086788_Branch.py b/pool/shard009/Python/0086788_Branch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f045c63414751d3396d6a5b0cf0260e95479de3a
--- /dev/null
+++ b/pool/shard009/Python/0086788_Branch.py
@@ -0,0 +1,43 @@
+"""This file is part of the FLiER Test Suite.
+
+ The FLiER Test Suite 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.
+
+ The FLiER Test Suite 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 the FLiER Test Suite. If not, see
+ .
+
+ Copyright Colin Ponce 2015.
+"""
+
+import numpy as np
+
+class Branch:
+ """A branch represents a transmission line in a power network.
+
+ More generally, it can represent any connection between two network buses
+ that involve non-infinite admittance.
+ """
+ def __init__(self, ID, buses, impedance, line_charging_susc = 0.0,
+ nonunity_tap = False, tap = 1.0+0.0j):
+ self.ID = ID
+ self.buses = buses
+ self.impedance = impedance
+ self.admittance = 1.0 / impedance
+ self.line_charging_susc = line_charging_susc
+ self.nonunity_tap = nonunity_tap
+ self.tap = tap
+
+ self.buses[0].add_branch(self)
+ self.buses[1].add_branch(self)
+
+ def copy(self):
+ return Branch(self.ID, self.buses, self.impedance,
+ self.line_charging_susc, self.nonunity_tap, self.tap)
diff --git a/pool/shard009/Python/0086789_backend-server.py b/pool/shard009/Python/0086789_backend-server.py
new file mode 100644
index 0000000000000000000000000000000000000000..c63fa924ffb6e5e9f7cb9de25342c33956467034
--- /dev/null
+++ b/pool/shard009/Python/0086789_backend-server.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+import SimpleHTTPServer
+import SocketServer
+import base64
+import hmac
+import hashlib
+from requestsigner import AwsV2Auth
+from urlparse import urlparse, parse_qs
+from time import time
+
+KEY = "XXX"
+SECRET = "XXX"
+BUCKET = "XXX"
+HOST = "sos.exo.io"
+
+class TokenRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
+ def do_GET(self):
+ if not "/token/" in self.path:
+ return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
+
+ query = urlparse(self.path).query
+ query_components = parse_qs(query)
+ ct = query_components["contentType"][0]
+
+
+ key = base64.b32encode(hmac.new(str(time()), "1", hashlib.sha512).digest())[0:30]
+ url = 'https://' + HOST + '/' + BUCKET + '/' + key
+ auth = AwsV2Auth(KEY, SECRET)
+ signed_url = auth.pre_sign(url, method='PUT', headers={'Content-Type': ct})
+
+ self.send_response(200)
+ self.send_header('Content-Type','text/plain');
+ self.end_headers()
+ self.wfile.write(signed_url);
+ return
+
+Handler = TokenRequestHandler
+server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)
+
+server.serve_forever()
diff --git a/pool/shard009/Python/0086794_test_system_image_type.py b/pool/shard009/Python/0086794_test_system_image_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..798ce48244cd92047eb6d01a24aa45f0c858bad0
--- /dev/null
+++ b/pool/shard009/Python/0086794_test_system_image_type.py
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+import fauxfactory
+import pytest
+
+from cfme.infrastructure.pxe import SystemImageType
+from utils import error
+from utils.update import update
+
+pytestmark = [pytest.mark.tier(3)]
+
+
+def test_system_image_type_crud():
+ """
+ Tests a System Image Type using CRUD operations.
+ """
+ sys_image_type = SystemImageType(
+ name=fauxfactory.gen_alphanumeric(8),
+ provision_type=SystemImageType.VM_OR_INSTANCE)
+ sys_image_type.create()
+ with update(sys_image_type):
+ sys_image_type.name = sys_image_type.name + "_update"
+ sys_image_type.delete(cancel=False)
+
+
+def test_duplicate_name_error_validation():
+ """
+ Tests a System Image for duplicate name.
+ """
+ sys_image_type = SystemImageType(
+ name=fauxfactory.gen_alphanumeric(8),
+ provision_type=SystemImageType.VM_OR_INSTANCE)
+ sys_image_type.create()
+ with error.expected('Name has already been taken'):
+ sys_image_type.create()
+ sys_image_type.delete(cancel=False)
+
+
+def test_name_required_error_validation():
+ """
+ Tests a System Image with no name.
+ """
+ sys_image_type = SystemImageType(
+ name=None,
+ provision_type=SystemImageType.VM_OR_INSTANCE)
+ with error.expected('Name is required'):
+ sys_image_type.create()
+
+# Commenting the maximum charater validation due to
+# http://cfme-tests.readthedocs.org/guides/gotchas.html#
+# selenium-is-not-clicking-on-the-element-it-says-it-is
+# def test_name_max_character_validation():
+# """
+# Tests a System Image name with max characters.
+# """
+# sys_image_type = SystemImageType(
+# name=fauxfactory.gen_alphanumeric(256),
+# provision_type='Vm')
+# sys_image_type.create()
+# sys_image_type.delete(cancel=False)
diff --git a/pool/shard009/Python/0086802_fsf_replace.py b/pool/shard009/Python/0086802_fsf_replace.py
new file mode 100644
index 0000000000000000000000000000000000000000..707276dd0dfb6b84e92ccd91496e9bc974ce6892
--- /dev/null
+++ b/pool/shard009/Python/0086802_fsf_replace.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python
+# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
+# vi: set ft=python sts=4 ts=4 sw=4 et:
+"""
+encoding.py: basic encoding process
+inputs: subject data, model, parameters
+outputs: either matrix or writes to NIFTI
+"""
+
+#!/usr/bin/env python
+# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
+# vi: set ft=python sts=4 ts=4 sw=4 et:
+# this script represents just throwing pymvpa at the problem. doesn't work great, and I suspect it's
+# because we're using an encoding model.
+"""
+Wrapper for PyMVPA analysis. Implemented as a program to be able to run multiple models quickly.
+
+For troubleshooting and parameter testing an ipynb exists too.
+"""
+# initialize stuff
+import sys
+import os
+
+PROJECTTITLE = ''
+
+def replacetext(template, replacements, output):
+ # replacements = {'###SUB###': sub, '###RUN###': run, ###SCAN###, scan, ###T1###: t1, ###IN###: input, ###OUTPUT###: output}
+ # still need vol though...
+ with open(template, 'r') as infile, open(output, 'w') as outfile:
+ for line in infile:
+ for src, target in replacements.iteritems():
+ line = line.replace(src, target)
+ outfile.write(line)
+ return
+
+
+def parsemapping(filename):
+ # parses filemapping.txt
+ import csv
+ df = {}
+ with open(filename, 'r') as f:
+ readCSV = csv.reader(f, delimiter=',')
+ for row in readCSV:
+ if len(row) > 0:
+ df[row[1]] = row[0]
+ return df
+
+
+def main(argv):
+ import getopt
+ fmap = 'filemapping.txt'
+ template = None
+ sub = None
+ try:
+ # figure out this line
+ opts, args = getopt.getopt(argv, "dwh:m:c:b:r:f",
+ ["sub=", "filename=", "project=", "write"])
+ except getopt.GetoptError:
+ print 'fsf_replace.py -s -f '
+ sys.exit(2)
+ for opt, arg in opts:
+ if opt == '-h':
+ print 'fsf_replace.py -s -f '
+ sys.exit()
+ elif opt in ("-s", "--sub"):
+ sub = arg
+ elif opt in ("-f", "--fmap"):
+ fmap = arg
+ elif opt in ("-t", "--template"):
+ template = arg
+
+ if sub is None or template is None:
+ sys.exit(2)
+
+ if sys.platform == 'darwin':
+ sys.path.append(os.path.join("/Users", "njchiang", "GitHub", "task-fmri-utils"))
+ sys.path.append(os.path.join("/Volumes", "JEFF", "UCLA", PROJECTTITLE, "code"))
+ else:
+ sys.path.append(os.path.join("D:\\", "GitHub", "task-fmri-utils"))
+ sys.path.append(os.path.join("D:\\", "fmri", PROJECTTITLE, "code"))
+ from project_code import projectutils as pu
+ # need a trial_type attribute
+ PATHS, _, _ = pu.initpaths()
+ df = parsemapping(os.path.join(PATHS['root'], 'data', sub, 'behav', fmap))
+ for run, scan in df.iteritems():
+ if 'Run' in run:
+ output = run
+ outfile = os.path.join(PATHS['root'], 'data', sub, 'notes', output + '.fsf')
+ replacements = {'###SUB###': sub, '###RUN###': run, '###SCAN###': scan,
+ '###T1###': df['T1'], '###OUTPUT###': output}
+ replacetext(template, replacements, outfile)
+
+
+if __name__ == "__main__":
+ main(sys.argv[1:])
\ No newline at end of file
diff --git a/pool/shard009/Python/0086806_c2ef4831ef76_user_last_login.py b/pool/shard009/Python/0086806_c2ef4831ef76_user_last_login.py
new file mode 100644
index 0000000000000000000000000000000000000000..02e08f92f0ad18007ffb20da3f5a495f2d2f3509
--- /dev/null
+++ b/pool/shard009/Python/0086806_c2ef4831ef76_user_last_login.py
@@ -0,0 +1,22 @@
+"""user last login
+
+Revision ID: c2ef4831ef76
+Revises: 9be372ec38bc
+Create Date: 2020-02-23 13:36:17.439014
+
+"""
+from alembic import op
+import sqlalchemy as sa
+from docassemble.webapp.database import dbtableprefix
+
+# revision identifiers, used by Alembic.
+revision = 'c2ef4831ef76'
+down_revision = '9be372ec38bc'
+branch_labels = None
+depends_on = None
+
+def upgrade():
+ op.add_column(dbtableprefix + 'user', sa.Column('last_login', sa.DateTime()))
+
+def downgrade():
+ op.drop_column(dbtableprefix + 'user', 'last_login')
diff --git a/pool/shard009/Python/0086813_oscurart_futurism.py b/pool/shard009/Python/0086813_oscurart_futurism.py
new file mode 100644
index 0000000000000000000000000000000000000000..1141d1827f7b05ef83a551378a4ac31d38cf0d5b
--- /dev/null
+++ b/pool/shard009/Python/0086813_oscurart_futurism.py
@@ -0,0 +1,149 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is 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.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+bl_info = {
+ "name": "Futurism",
+ "author": "Oscurart",
+ "version": (1, 2),
+ "blender": (2, 63, 0),
+ "location": "Object > Futurism",
+ "description": "Adds a new Mesh Object",
+ "warning": "",
+ "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"
+ "Scripts/Object/Oscurart_Futurism",
+ "tracker_url": "https://developer.blender.org/T31911",
+ "category": "Add Mesh"}
+
+
+import bpy
+
+def object_osc_futurism (self, context,STEP, HOLD):
+ ACTOBJ=bpy.context.active_object # OBJETO ACTIVO
+ FS=bpy.context.scene.frame_start # FRAME START
+ FE=bpy.context.scene.frame_end # FRAME END
+ OBJLIST=[] # LISTA PARA OBJETOS ????
+ FC=FS # FRAME CURRENT
+ OBJNUMBER=1 # SUFIJO DE NUMERO PARA OBJETOS
+ STEPINC=0 # NUMERO PARA EVALUAR LOS PASOS
+ bpy.context.scene.frame_set(FS) # SETEO EL FRAME CURRENT
+ OBACT = bpy.context.active_object # SETEO EL OBJETO ACTIVO
+
+ ## CREO EMPTY
+ bpy.ops.object.add()
+ bpy.context.active_object.name = "FuturismContainer"
+ EMPTY = bpy.context.active_object
+
+ # SUMO PARAMETERS AL EMPTY
+ EMPTY["FUTURISM_HOLDIN"] = 0
+ EMPTY["FUTURISM_HOLDOUT"] = 0
+
+ bpy.context.scene.objects.active = OBACT # RECUPERO OBJETO ACTIVO
+
+ for OBJETO in range((FE+1)-FS):
+ if STEPINC == STEP:
+ # CREO UN MESH A PARTIR DE OBJETO
+ MESH=ACTOBJ.to_mesh(bpy.context.scene, True, 'PREVIEW')
+ # CREO OBJETO
+ OBJECT=bpy.data.objects.new(ACTOBJ.name[:3]+str(FC), MESH)
+ # CONECTO A LA ESCENA
+ bpy.context.scene.objects.link(OBJECT)
+ # SETEO FRAME CURRENT
+ bpy.context.scene.frame_set(FC)
+ # MARCO EXPRESIONES PARA VIEW
+ OBJECT.driver_add("hide")
+ OBJECT.animation_data.drivers[0].driver.variables.new()
+ OBJECT.animation_data.drivers[0].driver.variables.new()
+ OBJECT.animation_data.drivers[0].driver.variables.new()
+ OBJECT.animation_data.drivers[0].driver.expression= "False if frame >= %s+var_001 and frame <= %s+var_002 else True" % (str(FC),str(FC+HOLD))
+ OBJECT.animation_data.drivers[0].driver.variables[0].targets[0].id_type = 'SCENE'
+ OBJECT.animation_data.drivers[0].driver.variables[0].targets[0].id= bpy.context.scene
+ OBJECT.animation_data.drivers[0].driver.variables[0].targets[0].data_path = "current_frame"
+ OBJECT.animation_data.drivers[0].driver.variables[1].targets[0].id_type = 'OBJECT'
+ OBJECT.animation_data.drivers[0].driver.variables[1].targets[0].id= EMPTY
+ OBJECT.animation_data.drivers[0].driver.variables[1].targets[0].data_path = '["FUTURISM_HOLDIN"]'
+ OBJECT.animation_data.drivers[0].driver.variables[2].targets[0].id_type = 'OBJECT'
+ OBJECT.animation_data.drivers[0].driver.variables[2].targets[0].id= EMPTY
+ OBJECT.animation_data.drivers[0].driver.variables[2].targets[0].data_path = '["FUTURISM_HOLDOUT"]'
+
+ # MARCO EXPRESIONES PARA RENDER
+ OBJECT.driver_add("hide_render")
+ OBJECT.animation_data.drivers[1].driver.variables.new()
+ OBJECT.animation_data.drivers[1].driver.variables.new()
+ OBJECT.animation_data.drivers[1].driver.variables.new()
+ OBJECT.animation_data.drivers[1].driver.expression= "False if frame >= %s+5 and frame <= %s else True" % (str(FC),str(FC+HOLD))
+ OBJECT.animation_data.drivers[1].driver.variables[0].targets[0].id_type = 'SCENE'
+ OBJECT.animation_data.drivers[1].driver.variables[0].targets[0].id= bpy.context.scene
+ OBJECT.animation_data.drivers[1].driver.variables[0].targets[0].data_path = "current_frame"
+ OBJECT.animation_data.drivers[1].driver.variables[1].targets[0].id_type = 'OBJECT'
+ OBJECT.animation_data.drivers[1].driver.variables[1].targets[0].id= EMPTY
+ OBJECT.animation_data.drivers[1].driver.variables[1].targets[0].data_path = '["FUTURISM_HOLDIN"]'
+ OBJECT.animation_data.drivers[1].driver.variables[2].targets[0].id_type = 'OBJECT'
+ OBJECT.animation_data.drivers[1].driver.variables[2].targets[0].id= EMPTY
+ OBJECT.animation_data.drivers[1].driver.variables[2].targets[0].data_path = '["FUTURISM_HOLDOUT"]'
+ # RESETEO STEPINC
+ STEPINC=0
+ # COPIAMOS S R T
+ OBJECT.matrix_world=ACTOBJ.matrix_world
+ #EMPARENTO
+ OBJECT.parent=EMPTY
+ # AVANZO STEP Y FRAME
+ FC+=1
+ STEPINC+=1
+
+# CLASE PARA OPERADOR
+class Oscurart_futurism (bpy.types.Operator):
+ bl_idname = "object.duplicate_futurism"
+ bl_label = "Duplicate Futurism"
+ bl_description = "Duplicate object per frame"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ scale = bpy.props.IntProperty(name='Step',default=1, min=1, max=1000)
+
+ hold = bpy.props.IntProperty(name='Hold', default=0, min=0)
+
+ @classmethod
+ def poll(cls, context):
+ return(bpy.context.active_object.type == "MESH" )
+
+ def execute(self, context):
+ object_osc_futurism(self, context, self.scale, self.hold)
+
+ return {'FINISHED'}
+
+
+# Registration
+
+def add_osc_futurism_button(self, context):
+ self.layout.operator(
+ Oscurart_futurism.bl_idname,
+ text="Futurism",
+ icon="PLUGIN")
+
+
+def register():
+ bpy.utils.register_class(Oscurart_futurism)
+ bpy.types.VIEW3D_MT_object.append(add_osc_futurism_button)
+
+
+def unregister():
+ bpy.utils.unregister_class(Oscurart_futurism)
+ bpy.types.VIEW3D_MT_object.remove(add_osc_futurism_button)
+
+
+if __name__ == '__main__':
+ register()
diff --git a/pool/shard009/Python/0086814_kfold-example.py b/pool/shard009/Python/0086814_kfold-example.py
new file mode 100644
index 0000000000000000000000000000000000000000..579248767f832aed95d09487065c395315779b2e
--- /dev/null
+++ b/pool/shard009/Python/0086814_kfold-example.py
@@ -0,0 +1,13 @@
+from sklearn.cross_validation import KFold
+import numpy as np
+
+X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
+y = np.array([1, 2, 3, 4])
+kf = KFold(4, n_folds=2)
+len(kf)
+print(kf)
+
+for train_index, test_index in kf:
+ print("TRAIN:", train_index, "TEST:", test_index)
+ X_train, X_test = X[train_index], X[test_index]
+ y_train, y_test = y[train_index], y[test_index]
diff --git a/pool/shard009/Python/0086815_generate_audio_samples.py b/pool/shard009/Python/0086815_generate_audio_samples.py
new file mode 100644
index 0000000000000000000000000000000000000000..4dd765b9460b1b5627cbd6c8bd3ffc555f2a1497
--- /dev/null
+++ b/pool/shard009/Python/0086815_generate_audio_samples.py
@@ -0,0 +1,240 @@
+"""
+This generates a single-tone audio clip for instrument classification.
+"""
+
+import argparse
+from music21.chord import Chord
+from music21.duration import Duration
+from music21.instrument import Instrument
+from music21.note import Note, Rest
+from music21.stream import Stream
+from music21.tempo import MetronomeMark
+from music21.volume import Volume
+import numpy as np
+import os
+import pandas as pd
+import soundfile as sf
+
+from midi2audio import FluidSynth
+from instruments import midi_instruments
+
+def make_instrument(id):
+ i = Instrument()
+ i.midiProgram = id
+ return i
+
+def chord_with_volume(chord, volume):
+ chord.volume = Volume(velocityScalar=volume)
+ return chord
+
+def write_midi(stream, output_file):
+ stream.write('midi', output_file)
+
+def generate_single_note(midi_number, midi_instrument=0, volume=1.0, duration=1.0, tempo=120):
+ """
+ Generates a stream containing a single note with given parameters.
+ midi_number - MIDI note number, 0 to 127
+ midi_instrument - MIDI intrument number, 0 to 127
+ duration - floating point number (in quarter note lengths)
+ volume - 0.0 to 1.0
+ tempo - number of quarter notes per minute (eg. 120)
+
+ Note that there's a quarter note rest at the beginning and at the end.
+ """
+ return Stream([
+ MetronomeMark(number=tempo),
+ make_instrument(int(midi_instrument)),
+ chord_with_volume(Chord([
+ Note(midi=int(midi_number), duration=Duration(duration))
+ ]), volume)
+ ])
+
+def generate_separate_notes(note_params_df, output_dir, audio_format='flac'):
+ """
+ Generates a batch of single note samples from the given table of parameters.
+
+ `note_params_df` - a Pandas Dataframe with columns:
+ `midi_number, midi_instrument, volume, duration, tempo`. Their meaning is the same as in generate_single_note.
+ `output_dir` - output directory for the MIDI files
+
+ Each sample goes to a single MIDI file named by the numeric index. Also each synthesized audio sample goes to a
+ """
+ os.makedirs(output_dir, exist_ok=True)
+
+ fs = FluidSynth()
+ for i, row in note_params_df.iterrows():
+ midi_file = '{0}/{1:06d}.midi'.format(output_dir, i)
+ audio_file = '{0}/{1:06d}.{2}'.format(output_dir, i, audio_format)
+
+ print(row, midi_file, audio_file)
+
+ stream = generate_single_note(**row)
+ write_midi(stream, midi_file)
+ fs.midi_to_audio(midi_file, audio_file)
+
+def random_params(n, note_range=None, volume_range=(0.5, 1.0), duration=1.0, tempo=60, seed=None):
+ """
+ Generate note parameters randomly as a DataFrame.
+
+ n - number of samples
+ """
+
+ if seed is not None:
+ np.random.seed(seed)
+
+ instruments = midi_instruments()
+
+ def instrument_range(i):
+ instr = instruments.ix[i]
+ instr_range = np.array([instr['min_pitch'], instr['max_pitch']])
+ if note_range is not None:
+ instr_range = np.clip(instr_range, *note_range)
+ return instr_range
+
+ allowed_instruments = np.hstack([
+ np.arange(0, 8), # piano
+ np.arange(16, 32), # organ, guitar
+ np.arange(40, 48), # strings
+ np.arange(56, 80), # brass, reed, pipe
+ ])
+
+ def random_note_for_instrument(instr):
+ instr_range = instrument_range(instr)
+ return np.random.random_integers(low=instr_range[0], high=instr_range[1], size=1)[0]
+
+ df = pd.DataFrame()
+ df['midi_instrument'] = np.random.choice(allowed_instruments, size=n)
+ df['midi_number'] = df['midi_instrument'].apply(random_note_for_instrument)
+ df['volume'] = np.random.uniform(low=volume_range[0], high=volume_range[1], size=n)
+ # TODO: allow varying duration while maintaining constant audio length
+ df['duration'] = duration
+ df['tempo'] = tempo
+
+ return df
+
+def generate_notes_in_batch(note_params_df, output_dir, audio_format='flac', sample_rate=44100):
+ """
+ Generates a batch of single note samples from the given table of parameters.
+
+ `note_params_df` - a Pandas Dataframe with columns:
+ `midi_number, midi_instrument, volume, duration, tempo`. Their meaning is the same as in generate_single_note.
+ `output_dir` - output directory for the MIDI files
+
+ Each sample goes to a single MIDI file named by the numeric index. Also each synthesized audio sample goes to a
+ """
+ os.makedirs(output_dir, exist_ok=True)
+
+ fs = FluidSynth(sample_rate=sample_rate)
+
+ stream = Stream()
+
+ for i, row in note_params_df.iterrows():
+ stream.append(MetronomeMark(number=row['tempo']))
+ stream.append(make_instrument(int(row['midi_instrument'])))
+ duration = row['duration']
+ stream.append(chord_with_volume(Chord([
+ Note(midi=int(row['midi_number']), duration=Duration(duration))
+ ]), row['volume']))
+ stream.append(Rest(duration=Duration(2 * duration)))
+
+ midi_file = '{0}/all_samples.midi'.format(output_dir)
+ audio_file_stereo = '{0}/all_samples_stereo.{1}'.format(output_dir, audio_format)
+ audio_file = '{0}/all_samples.{1}'.format(output_dir, audio_format)
+ audio_index_file = '{0}/all_samples_index.csv'.format(output_dir)
+
+ # TODO: We currently assume some fixed duration and tempo (1.0, 120)!!!
+ # The parts should be split according to an index.
+ audio_index = make_audio_index(note_params_df, 3.0, 0.5, sample_rate)
+ audio_index.to_csv(audio_index_file)
+
+ write_midi(stream, midi_file)
+
+ fs.midi_to_audio(midi_file, audio_file_stereo)
+
+ convert_to_mono(audio_file_stereo, audio_file)
+ os.remove(audio_file_stereo)
+
+ x, sample_rate = sf.read(audio_file)
+
+ parts = split_audio_to_parts(x, sample_rate, audio_index)
+ store_parts_to_files(parts, sample_rate, output_dir, audio_format)
+
+def convert_to_mono(stereo_file, mono_file):
+ x, sample_rate = sf.read(stereo_file)
+ x_mono = x.mean(axis=1) # convert to mono
+ sf.write(mono_file, x_mono, sample_rate)
+
+def make_audio_index(note_params_df, part_duration, margin_duration, sample_rate):
+ sample_count = len(note_params_df)
+ index = np.arange(sample_count)
+
+ # let's have larger margin to prevent spilling the content
+ # 1 second margin, 1 second note, 1 second margin
+ # then cut the margin down a bit
+
+ part_samples = int(part_duration * sample_rate)
+ margin_samples = int(margin_duration * sample_rate)
+
+ audio_index = pd.DataFrame()
+
+ audio_index['start_samples'] = index * part_samples + margin_samples
+ audio_index['start_time'] = audio_index['start_samples'] / sample_rate
+
+ audio_index['end_samples'] = (index + 1) * part_samples - margin_samples
+ audio_index['end_time'] = audio_index['end_samples'] / sample_rate
+
+ return audio_index
+
+def split_audio_to_parts(x, sample_rate, audio_index):
+ for i, row in audio_index.iterrows():
+ x_part = x[int(row['start_samples']):int(row['end_samples'])]
+ yield x_part
+
+def store_parts_to_files(parts, sample_rate, output_dir, audio_format):
+ """
+ Store the cut samples in separate files for easier human listening.
+ """
+ for i, x_part in enumerate(parts):
+ audio_file = output_dir + '/sample_{0:06d}.{1}'.format(i, audio_format)
+ print(audio_file)
+ sf.write(audio_file, x_part, sample_rate)
+
+def generate_random_samples(args):
+ params_df = random_params(args.count, seed=args.seed)
+ os.makedirs(args.output_dir, exist_ok=True)
+ params_df.to_csv(args.output_dir + '/parameters.csv')
+ # generate_separate_notes(params_df, output_dir, args.audio_format)
+ generate_notes_in_batch(params_df, args.output_dir, args.audio_format)
+
+class SingleToneDataset():
+ """
+ Represents the generated dataset, useful for loading the data for analysis and model training.
+ """
+ def __init__(self, path):
+ self.path = path
+ self.params_file = path + '/parameters.csv'
+ self.params = pd.read_csv(self.params_file, index_col=0)
+ self.audio_index_file = path + '/all_samples_index.csv'
+ self.audio_index = pd.read_csv(self.audio_index_file, index_col=0)
+ self.audio_file = path + '/all_samples.flac'
+ audio, self.sample_rate = sf.read(self.audio_file)
+ self.samples = np.array(list(split_audio_to_parts(audio, self.sample_rate, self.audio_index)))
+
+ def __repr__(self):
+ return ''.format(self.path, self.samples.shape)
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Generate random audio samples.')
+ parser.add_argument('-c', '--count', type=int, help='number of samples')
+ parser.add_argument('-s', '--seed', type=int, help='random seed')
+ parser.add_argument('-o', '--output-dir', type=str, help='output directory')
+ parser.add_argument('-f', '--audio-format', type=str, default='flac', help='audio format (flac, wav)')
+
+ return parser.parse_args()
+
+if __name__ == '__main__':
+ generate_random_samples(parse_args())
+
+# TODO: split into two parts with separate responsibilities:
+# - randomly generate the parameters to a CSV file
+# - synthesize sounds from a given CSV file
diff --git a/pool/shard009/Python/0086818_scheduler_integration_test.py b/pool/shard009/Python/0086818_scheduler_integration_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..1875109e649bc229a5b350c556db67da546298aa
--- /dev/null
+++ b/pool/shard009/Python/0086818_scheduler_integration_test.py
@@ -0,0 +1,40 @@
+# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
+# Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+import os
+from pathlib import Path
+
+from pants.testutil.pants_integration_test import ensure_daemon, run_pants
+from pants.util.contextutil import temporary_dir
+
+
+def test_visualize_to():
+ # Tests usage of the `--native-engine-visualize-to=` option, which triggers background
+ # visualization of the graph. There are unit tests confirming the content of the rendered
+ # results.
+ with temporary_dir(root_dir=os.getcwd()) as destdir:
+ run_pants(
+ [
+ f"--native-engine-visualize-to={destdir}",
+ "--backend-packages=pants.backend.python",
+ "list",
+ "testprojects/src/python/hello/greet",
+ ]
+ ).assert_success()
+ destdir_files = list(Path(destdir).iterdir())
+ assert len(destdir_files) > 0
+
+
+@ensure_daemon
+def test_graceful_termination(use_pantsd: bool) -> None:
+ result = run_pants(
+ [
+ "--backend-packages=['pants.backend.python', 'internal_plugins.rules_for_testing']",
+ "list-and-die-for-testing",
+ "testprojects/src/python/hello/greet",
+ ],
+ use_pantsd=use_pantsd,
+ )
+ result.assert_failure()
+ assert result.stdout == "testprojects/src/python/hello/greet\n"
+ assert result.exit_code == 42
diff --git a/pool/shard009/Python/0086824_models.py b/pool/shard009/Python/0086824_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..4975678c22854eba31302af1de19f0d9c5c43184
--- /dev/null
+++ b/pool/shard009/Python/0086824_models.py
@@ -0,0 +1,41 @@
+from tt_streams.models import Stream, StreamItem
+from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+
+
+class StoryItem(StreamItem):
+ story = models.ForeignKey('Story', related_name='stream_items')
+ title = models.CharField(max_length=250)
+
+ def save(self, *args, **kwargs):
+ self.title = self.story.title
+ return super(StoryItem, self).save(*args, **kwargs)
+
+
+class Story(models.Model):
+ title = models.CharField(max_length=250)
+ body = models.TextField()
+ stream = models.ManyToManyField(Stream, through=StoryItem)
+
+ def __unicode__(self):
+ return self.title
+
+
+class VideoItem(StreamItem):
+ video = models.ForeignKey('Video')
+
+
+class Video(models.Model):
+ title = models.CharField(max_length=250)
+ url = models.URLField()
+ stream = models.ManyToManyField(Stream, through=VideoItem)
+
+ def __unicode__(self):
+ return self.title
+
+
+@receiver(post_save, sender=Story)
+def update_story_item(sender, instance=None, **kwargs):
+ for item in instance.stream_items.all():
+ item.save()
diff --git a/pool/shard009/Python/0086827_parsing_ops.py b/pool/shard009/Python/0086827_parsing_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2701605e641b190852bb9934ce83f7fc3e90ff15
--- /dev/null
+++ b/pool/shard009/Python/0086827_parsing_ops.py
@@ -0,0 +1,150 @@
+# Copyright 2018 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.
+# ==============================================================================
+"""Experimental `dataset` API for parsing example."""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from tensorflow.python.data.ops import dataset_ops
+from tensorflow.python.data.util import nest
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import ops
+from tensorflow.python.framework import sparse_tensor
+from tensorflow.python.ops import gen_dataset_ops
+from tensorflow.python.ops import parsing_ops
+
+
+class _ParseExampleDataset(dataset_ops.Dataset):
+ """A `Dataset` that parses `example` dataset into a `dict` dataset."""
+
+ def __init__(self, input_dataset, features, num_parallel_calls):
+ super(_ParseExampleDataset, self).__init__()
+ self._input_dataset = input_dataset
+ if not all(types == dtypes.string
+ for types in nest.flatten(input_dataset.output_types)):
+ raise TypeError("Input dataset should be a dataset of vectors of strings")
+ self._num_parallel_calls = num_parallel_calls
+ # pylint: disable=protected-access
+ self._features = parsing_ops._prepend_none_dimension(features)
+ # sparse_keys and dense_keys come back sorted here.
+ (sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults,
+ dense_shapes) = parsing_ops._features_to_raw_params(
+ self._features, [
+ parsing_ops.VarLenFeature, parsing_ops.SparseFeature,
+ parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature
+ ])
+ # TODO(b/112859642): Pass sparse_index and sparse_values for SparseFeature.
+ (_, dense_defaults_vec, sparse_keys, sparse_types, dense_keys, dense_shapes,
+ dense_shape_as_shape) = parsing_ops._process_raw_parameters(
+ None, dense_defaults, sparse_keys, sparse_types, dense_keys,
+ dense_types, dense_shapes)
+ # pylint: enable=protected-access
+ self._sparse_keys = sparse_keys
+ self._sparse_types = sparse_types
+ self._dense_keys = dense_keys
+ self._dense_defaults = dense_defaults_vec
+ self._dense_shapes = dense_shapes
+ self._dense_types = dense_types
+ dense_output_shapes = [
+ self._input_dataset.output_shapes.concatenate(shape)
+ for shape in dense_shape_as_shape
+ ]
+ sparse_output_shapes = [
+ self._input_dataset.output_shapes.concatenate([None])
+ for _ in range(len(sparse_keys))
+ ]
+
+ self._output_shapes = dict(
+ zip(self._dense_keys + self._sparse_keys,
+ dense_output_shapes + sparse_output_shapes))
+ self._output_types = dict(
+ zip(self._dense_keys + self._sparse_keys,
+ self._dense_types + self._sparse_types))
+ self._output_classes = dict(
+ zip(self._dense_keys + self._sparse_keys,
+ [ops.Tensor for _ in range(len(self._dense_defaults))] +
+ [sparse_tensor.SparseTensor for _ in range(len(self._sparse_keys))
+ ]))
+
+ def _as_variant_tensor(self):
+ return gen_dataset_ops.parse_example_dataset(
+ self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access
+ self._num_parallel_calls,
+ self._dense_defaults,
+ self._sparse_keys,
+ self._dense_keys,
+ self._sparse_types,
+ self._dense_shapes,
+ **dataset_ops.flat_structure(self))
+
+ @property
+ def output_shapes(self):
+ return self._output_shapes
+
+ @property
+ def output_types(self):
+ return self._output_types
+
+ @property
+ def output_classes(self):
+ return self._output_classes
+
+
+# TODO(b/111553342): add arguments names and example names as well.
+def parse_example_dataset(features, num_parallel_calls=1):
+ """A transformation that parses `Example` protos into a `dict` of tensors.
+
+ Parses a number of serialized `Example` protos given in `serialized`. We refer
+ to `serialized` as a batch with `batch_size` many entries of individual
+ `Example` protos.
+
+ This op parses serialized examples into a dictionary mapping keys to `Tensor`
+ and `SparseTensor` objects. `features` is a dict from keys to `VarLenFeature`,
+ `SparseFeature`, and `FixedLenFeature` objects. Each `VarLenFeature`
+ and `SparseFeature` is mapped to a `SparseTensor`, and each
+ `FixedLenFeature` is mapped to a `Tensor`. See `tf.parse_example` for more
+ details about feature dictionaries.
+
+ Args:
+ features: A `dict` mapping feature keys to `FixedLenFeature`,
+ `VarLenFeature`, and `SparseFeature` values.
+ num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,
+ representing the number of parsing processes to call in parallel.
+
+ Returns:
+ A dataset transformation function, which can be passed to
+ `tf.data.Dataset.apply`.
+
+ Raises:
+ ValueError: if features argument is None.
+ """
+ if features is None:
+ raise ValueError("Missing: features was %s." % features)
+
+ def _apply_fn(dataset):
+ """Function from `Dataset` to `Dataset` that applies the transformation."""
+ out_dataset = _ParseExampleDataset(dataset, features, num_parallel_calls)
+ if any([
+ isinstance(feature, parsing_ops.SparseFeature)
+ for _, feature in features.items()
+ ]):
+ # pylint: disable=protected-access
+ # pylint: disable=g-long-lambda
+ out_dataset = out_dataset.map(
+ lambda x: parsing_ops._construct_sparse_tensors_for_sparse_features(
+ features, x), num_parallel_calls=num_parallel_calls)
+ return out_dataset
+
+ return _apply_fn
diff --git a/pool/shard009/Python/0086832_queries.py b/pool/shard009/Python/0086832_queries.py
new file mode 100644
index 0000000000000000000000000000000000000000..73558950dfdeb7335ed1a06265e10ba48fc323ab
--- /dev/null
+++ b/pool/shard009/Python/0086832_queries.py
@@ -0,0 +1,16 @@
+import graphene
+
+from falmer.auth.types import ClientUser, Permission
+from django.contrib.auth.models import Permission as DjangoPermission
+
+class Query(graphene.ObjectType):
+ viewer = graphene.Field(ClientUser)
+ permissions = graphene.List(Permission)
+
+ def resolve_viewer(self, info):
+ if info.context.user.is_authenticated:
+ return info.context.user
+ return None
+
+ def resolve_permissions(self, info):
+ return DjangoPermission.objects.select_related('content_type').all()
diff --git a/pool/shard009/Python/0086833_test_convert_dtypes.py b/pool/shard009/Python/0086833_test_convert_dtypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..81203b944fa92b21bbd1adccbc6da000f2a6b586
--- /dev/null
+++ b/pool/shard009/Python/0086833_test_convert_dtypes.py
@@ -0,0 +1,228 @@
+from itertools import product
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_interval_dtype
+
+import pandas as pd
+import pandas._testing as tm
+
+# Each test case consists of a tuple with the data and dtype to create the
+# test Series, the default dtype for the expected result (which is valid
+# for most cases), and the specific cases where the result deviates from
+# this default. Those overrides are defined as a dict with (keyword, val) as
+# dictionary key. In case of multiple items, the last override takes precedence.
+
+test_cases = [
+ (
+ # data
+ [1, 2, 3],
+ # original dtype
+ np.dtype("int32"),
+ # default expected dtype
+ "Int32",
+ # exceptions on expected dtype
+ {("convert_integer", False): np.dtype("int32")},
+ ),
+ (
+ [1, 2, 3],
+ np.dtype("int64"),
+ "Int64",
+ {("convert_integer", False): np.dtype("int64")},
+ ),
+ (
+ ["x", "y", "z"],
+ np.dtype("O"),
+ pd.StringDtype(),
+ {("convert_string", False): np.dtype("O")},
+ ),
+ (
+ [True, False, np.nan],
+ np.dtype("O"),
+ pd.BooleanDtype(),
+ {("convert_boolean", False): np.dtype("O")},
+ ),
+ (
+ ["h", "i", np.nan],
+ np.dtype("O"),
+ pd.StringDtype(),
+ {("convert_string", False): np.dtype("O")},
+ ),
+ ( # GH32117
+ ["h", "i", 1],
+ np.dtype("O"),
+ np.dtype("O"),
+ {},
+ ),
+ (
+ [10, np.nan, 20],
+ np.dtype("float"),
+ "Int64",
+ {
+ ("convert_integer", False, "convert_floating", True): "Float64",
+ ("convert_integer", False, "convert_floating", False): np.dtype("float"),
+ },
+ ),
+ (
+ [np.nan, 100.5, 200],
+ np.dtype("float"),
+ "Float64",
+ {("convert_floating", False): np.dtype("float")},
+ ),
+ (
+ [3, 4, 5],
+ "Int8",
+ "Int8",
+ {},
+ ),
+ (
+ [[1, 2], [3, 4], [5]],
+ None,
+ np.dtype("O"),
+ {},
+ ),
+ (
+ [4, 5, 6],
+ np.dtype("uint32"),
+ "UInt32",
+ {("convert_integer", False): np.dtype("uint32")},
+ ),
+ (
+ [-10, 12, 13],
+ np.dtype("i1"),
+ "Int8",
+ {("convert_integer", False): np.dtype("i1")},
+ ),
+ (
+ [1.2, 1.3],
+ np.dtype("float32"),
+ "Float32",
+ {("convert_floating", False): np.dtype("float32")},
+ ),
+ (
+ [1, 2.0],
+ object,
+ "Int64",
+ {
+ ("convert_integer", False): "Float64",
+ ("convert_integer", False, "convert_floating", False): np.dtype("float"),
+ ("infer_objects", False): np.dtype("object"),
+ },
+ ),
+ (
+ [1, 2.5],
+ object,
+ "Float64",
+ {
+ ("convert_floating", False): np.dtype("float"),
+ ("infer_objects", False): np.dtype("object"),
+ },
+ ),
+ (["a", "b"], pd.CategoricalDtype(), pd.CategoricalDtype(), {}),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]),
+ pd.DatetimeTZDtype(tz="UTC"),
+ pd.DatetimeTZDtype(tz="UTC"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]),
+ "datetime64[ns]",
+ np.dtype("datetime64[ns]"),
+ {},
+ ),
+ (
+ pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]),
+ object,
+ np.dtype("datetime64[ns]"),
+ {("infer_objects", False): np.dtype("object")},
+ ),
+ (pd.period_range("1/1/2011", freq="M", periods=3), None, pd.PeriodDtype("M"), {}),
+ (
+ pd.arrays.IntervalArray([pd.Interval(0, 1), pd.Interval(1, 5)]),
+ None,
+ pd.IntervalDtype("int64", "right"),
+ {},
+ ),
+]
+
+
+class TestSeriesConvertDtypes:
+ @pytest.mark.parametrize(
+ "data, maindtype, expected_default, expected_other",
+ test_cases,
+ )
+ @pytest.mark.parametrize("params", product(*[(True, False)] * 5))
+ def test_convert_dtypes(
+ self, data, maindtype, params, expected_default, expected_other
+ ):
+ warn = None
+ if (
+ hasattr(data, "dtype")
+ and data.dtype == "M8[ns]"
+ and isinstance(maindtype, pd.DatetimeTZDtype)
+ ):
+ # this astype is deprecated in favor of tz_localize
+ warn = FutureWarning
+
+ if maindtype is not None:
+ with tm.assert_produces_warning(warn):
+ series = pd.Series(data, dtype=maindtype)
+ else:
+ series = pd.Series(data)
+
+ result = series.convert_dtypes(*params)
+
+ param_names = [
+ "infer_objects",
+ "convert_string",
+ "convert_integer",
+ "convert_boolean",
+ "convert_floating",
+ ]
+ params_dict = dict(zip(param_names, params))
+
+ expected_dtype = expected_default
+ for spec, dtype in expected_other.items():
+ if all(params_dict[key] is val for key, val in zip(spec[::2], spec[1::2])):
+ expected_dtype = dtype
+
+ warn2 = None
+ if (
+ hasattr(data, "dtype")
+ and data.dtype == "M8[ns]"
+ and isinstance(expected_dtype, pd.DatetimeTZDtype)
+ ):
+ # this astype is deprecated in favor of tz_localize
+ warn2 = FutureWarning
+
+ with tm.assert_produces_warning(warn2):
+ expected = pd.Series(data, dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ # Test that it is a copy
+ copy = series.copy(deep=True)
+ if is_interval_dtype(result.dtype) and result.dtype.subtype.kind in ["i", "u"]:
+ msg = "Cannot set float NaN to integer-backed IntervalArray"
+ with pytest.raises(ValueError, match=msg):
+ result[result.notna()] = np.nan
+ else:
+ result[result.notna()] = np.nan
+
+ # Make sure original not changed
+ tm.assert_series_equal(series, copy)
+
+ def test_convert_string_dtype(self, nullable_string_dtype):
+ # https://github.com/pandas-dev/pandas/issues/31731 -> converting columns
+ # that are already string dtype
+ df = pd.DataFrame(
+ {"A": ["a", "b", pd.NA], "B": ["ä", "ö", "ü"]}, dtype=nullable_string_dtype
+ )
+ result = df.convert_dtypes()
+ tm.assert_frame_equal(df, result)
+
+ def test_convert_bool_dtype(self):
+ # GH32287
+ df = pd.DataFrame({"A": pd.array([True])})
+ tm.assert_frame_equal(df, df.convert_dtypes())
diff --git a/pool/shard009/Python/0086838_env.py b/pool/shard009/Python/0086838_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ab1bc57bcb974ace009f60ebd0e53843a014f93
--- /dev/null
+++ b/pool/shard009/Python/0086838_env.py
@@ -0,0 +1,91 @@
+from __future__ import with_statement
+from alembic import context
+from sqlalchemy import engine_from_config, pool, MetaData
+from logging.config import fileConfig
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+fileConfig(config.config_file_name)
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+import os, sys
+sys.path.append(os.getcwd())
+
+
+def combine_metadata(*args):
+ m = MetaData()
+ for metadata in args:
+ for t in metadata.tables.values():
+ t.tometadata(m)
+ return m
+
+from encounter import table, wilderness, biome
+from web import db
+import pc
+import attributes
+target_metadata = combine_metadata(
+ biome.Base.metadata,
+ wilderness.Base.metadata,
+ table.Base.metadata,
+ pc.Base.metadata,
+ attributes.Base.metadata,
+ db.Model.metadata,
+)
+# target_metadata = None
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_offline():
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
+ Calls to context.execute() here emit the given string to the
+ script output.
+
+ """
+ url = config.get_main_option("sqlalchemy.url")
+ context.configure(
+ url=url, target_metadata=target_metadata, literal_binds=True)
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+def run_migrations_online():
+ """Run migrations in 'online' mode.
+
+ In this scenario we need to create an Engine
+ and associate a connection with the context.
+
+ """
+ connectable = engine_from_config(
+ config.get_section(config.config_ini_section),
+ prefix='sqlalchemy.',
+ poolclass=pool.NullPool)
+
+ with connectable.connect() as connection:
+ context.configure(
+ connection=connection,
+ target_metadata=target_metadata
+ )
+
+ with context.begin_transaction():
+ context.run_migrations()
+
+if context.is_offline_mode():
+ run_migrations_offline()
+else:
+ run_migrations_online()
diff --git a/pool/shard009/Python/0086848_render_template.py b/pool/shard009/Python/0086848_render_template.py
new file mode 100644
index 0000000000000000000000000000000000000000..1585adb73ac2da1d675bbaba27026de85e55668e
--- /dev/null
+++ b/pool/shard009/Python/0086848_render_template.py
@@ -0,0 +1,42 @@
+import json
+from jinja2 import Environment, select_autoescape
+from jinja2_s3loader import S3loader
+from tabulate import tabulate
+import aws_lambda
+
+
+def make_table(
+ rows, headers="keys", tablefmt="psql", exclude_keys=None, required_key=None
+):
+ # list of dicts as an input
+ if exclude_keys and isinstance(exclude_keys, (tuple, list)):
+ for idx, _ in enumerate(rows):
+ for key in exclude_keys:
+ if key in rows[idx]:
+ del rows[idx][key]
+ if required_key and isinstance(required_key, str):
+ for idx, _ in enumerate(rows):
+ for key in exclude_keys:
+ if key in rows[idx]:
+ del rows[idx][key]
+
+ return tabulate(rows, headers=headers, tablefmt=tablefmt)
+
+
+def jinja_env(template_dir, s3_bucket):
+ env = Environment(
+ loader=S3loader(bucket=s3_bucket, prefix=template_dir),
+ autoescape=select_autoescape(["html", "xml"]),
+ )
+ env.filters["tabulate"] = make_table
+ return env
+
+
+def render_template(env, template_name, input_args):
+
+ template = env.get_template(template_name)
+ if "json" not in input_args.keys():
+ input_args["json"] = json.dumps(
+ input_args, cls=aws_lambda.PythonObjectEncoder
+ )
+ return template.render(**input_args)
diff --git a/pool/shard009/Python/0086853_event_reader.py b/pool/shard009/Python/0086853_event_reader.py
new file mode 100644
index 0000000000000000000000000000000000000000..85fccc498d2f4c407d68b73eb435e9e4f279be6e
--- /dev/null
+++ b/pool/shard009/Python/0086853_event_reader.py
@@ -0,0 +1,65 @@
+import os
+import sys
+import argparse
+import struct
+from razer_daemon.keyboard import EVENT_MAPPING, TARTARUS_EVENT_MAPPING
+
+EVENT_FORMAT = '@llHHI'
+EVENT_SIZE = struct.calcsize(EVENT_FORMAT)
+
+
+def loop_on_event(event_file, mapping):
+ with open(event_file, 'rb') as open_file:
+
+ while True:
+ payload = open_file.read(EVENT_SIZE)
+
+ ev_type, code, value = struct.unpack(EVENT_FORMAT, payload)[2:]
+
+ if (ev_type == code == 0) or ev_type == 4:
+ continue
+
+ if ev_type == 1:
+ if value == 0:
+ value = 'UP'
+ elif value == 1:
+ value = 'DOWN'
+ else:
+ value = 'REPEAT'
+
+ code = mapping.get(code, code)
+
+ print("Type: EV_KEY, Code: {1}, Value: {2}".format(ev_type, code, value))
+ else:
+ print("Type: {0}, Code: {1}, Value: {2}".format(ev_type, code, value))
+
+
+def parse_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('event_file', metavar='EVENT_FILE', type=str, help="Device event file like \"/dev/input/by-id/usb-Razer_Razer_BlackWidow_Chroma-event-kbd\"")
+ parser.add_argument('--tartarus', action='store_true', help='Use the tartarus event mapping instead')
+
+ return parser.parse_args()
+
+def run():
+ args = parse_args()
+
+ if not os.path.exists(args.event_file):
+ print('Event file does not exist', file=sys.stderr)
+ sys.exit(1)
+
+ if args.tartarus:
+ mapping = TARTARUS_EVENT_MAPPING
+ else:
+ #mapping = EVENT_MAPPING
+ mapping = {}
+
+ print('Starting. Press keys', file=sys.stderr)
+
+ try:
+ loop_on_event(args.event_file, mapping)
+ except KeyboardInterrupt:
+ print("Exiting", file=sys.stderr)
+
+if __name__ == '__main__':
+ run()
\ No newline at end of file
diff --git a/pool/shard009/Python/0086854_user.py b/pool/shard009/Python/0086854_user.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf205f43be24fe5a055c4cf893e7b610d361cf59
--- /dev/null
+++ b/pool/shard009/Python/0086854_user.py
@@ -0,0 +1,91 @@
+# -*- coding: utf-8 -*-
+
+from mini import db, login_manager
+from mini.util import *
+from mini.models.email import Email
+from mini.models.team import Member
+from datetime import datetime
+from flask.ext.login import current_user, login_user, logout_user
+from flask import url_for
+import fnmatch
+
+class User(Member, AnonymousUser):
+ __tablename__ = "user"
+ __mapper_args__ = {'polymorphic_identity': __tablename__}
+
+ id = db.Column(db.Integer, db.ForeignKey("member.id"), primary_key = True)
+ password = db.Column(db.String(128))
+ created = db.Column(db.DateTime)
+
+ status = db.Column(db.Enum("unverified", "normal", "banned"), default="normal")
+ verify_hash = db.Column(db.String(80))
+
+ permissions = db.Column(db.Text)
+ restrictions = db.Column(db.Text)
+
+ location = db.Column(db.String(200))
+ about = db.Column(db.Text)
+
+ activities = db.relationship("Activity", backref="user", lazy="dynamic")
+
+ def __init__(self):
+ self.created = datetime.utcnow()
+
+ def set_password(self, cleartext):
+ self.password = hash_password(cleartext)
+
+ def generate_verify_hash(self):
+ self.verify_hash = random_string(10)
+ return self.verify_hash
+
+ @property
+ def default_email(self):
+ return Email.query.filter_by(user_id=self.id, is_default=True).first()
+
+ @property
+ def gravatar_email(self):
+ return Email.query.filter_by(user_id=self.id, is_gravatar=True).first()
+
+ def get_avatar(self, size=32):
+ return self.gravatar_email.get_avatar(size)
+
+ def has_permission(self, permission):
+ if permission == "login":
+ return True
+
+ if permission == "nologin":
+ return False
+
+ if not self.permissions: return False
+
+ for line in self.permissions.splitlines():
+ if line and fnmatch.fnmatch(permission, line):
+ return True
+
+ # for team in self.teams:
+ # if team.has_permission(permission):
+ # return True
+
+ return False
+
+ def get_display_name(self):
+ return self.name if self.name else self.identifier
+
+ def get_link(self, size=16):
+ return Markup('
{1}'.format(self.get_avatar(size), self.get_display_name(), self.get_url()))
+
+ def get_url(self):
+ return url_for("user", identifier=self.identifier)
+
+ def get_owned_repositories(self):
+ from mini.models import Repository, Permission
+ return Repository.query.join(Permission).filter_by(member_id=self.id, access="admin")
+
+ @staticmethod
+ def get_current():
+ return current_user
+
+# we need this so flask-login can load a user into a session
+@login_manager.user_loader
+def load_user(user_id):
+ return User.query.filter_by(id=int(user_id)).first()
diff --git a/pool/shard009/Python/0086862_Sampling.py b/pool/shard009/Python/0086862_Sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..83ff9efed8c99c35b2cfec2b7a9ce494da50bfd0
--- /dev/null
+++ b/pool/shard009/Python/0086862_Sampling.py
@@ -0,0 +1,78 @@
+import numpy as np
+
+from asap3.Tools.ParameterOptimization.Optimization import ParameterOptimization
+from asap3.Tools.ParameterOptimization.Search import ParameterSearch
+
+class ParameterSampling(ParameterSearch):
+ def __init__(self, elements, calc, initparam, varparam, stdparam, points,
+ quantities, latticeconstants, calc_args=None, debug=False):
+ self.points = points
+ ParameterSearch.__init__(self, elements, calc, initparam, varparam,
+ stdparam, quantities, latticeconstants,
+ calc_args, debug=0)
+
+ def run(self, xtol=5e-4, ftol=2e0, delta=5e-2, dat=None, txt=None):
+ self.nsteps = 0
+ self.numberlist = []
+ self.errorlist = []
+ self.fitparlist = []
+ self.optparlist = []
+ self.optvallist = []
+
+ fitparam_list = []
+ self.sampling(fitparam_list)
+ #print len(fitparam_list)
+ #for pars in fitparam_list[163:175]:
+ # for (k, p) in pars.items():
+ # print k, p
+ # print "-----"
+ #return
+
+ for fitpar in fitparam_list:
+ self.nsteps += 1
+
+ # Run optimization
+ opt = ParameterOptimization(self.elements, self.calc, fitpar,
+ self.varparam, self.values,
+ self.latticeconstants, self.calc_args,
+ debug=self.debug)
+ (error, optpar, optval) = opt.fit(xtol, ftol, delta, txt)
+
+ self.save(error, fitpar, optpar, optval)
+
+ self.write(dat, 'sampling')
+
+ def sampling(self, output, tempparam=None, n=1):
+ # Which parameter should be altered
+ varcount = 0
+ for (key, var) in self.varparam.items():
+ for i, v in enumerate(var):
+ if v:
+ varcount += 1
+ if varcount == n:
+ k = key
+ m = i
+ #print "Varying %s at position %i (%i out of %i)" % (k, m, n, varcount)
+
+ # What is the "standard diviation"
+ if isinstance(self.stdparam[k], list):
+ std = self.stdparam[k][m]
+ else:
+ std = self.stdparam[k]
+
+ # Vary the parameter
+ ps = self.initparam[k][m] * np.linspace(1.0 - std, 1.0 + std, self.points)
+ for p in ps:
+ newparam = {}
+ for key in self.initparam.keys():
+ if tempparam is None:
+ newparam[key] = self.initparam[key][:]
+ else:
+ newparam[key] = tempparam[key][:]
+ newparam[k][m] = p
+ if n < varcount:
+ self.sampling(output, newparam, n+1)
+ else:
+ output.append(newparam)
+
+
diff --git a/pool/shard009/Python/0086863_test_text.py b/pool/shard009/Python/0086863_test_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..d53b0738e6fdd79103cf4a06aa4197805d65caf7
--- /dev/null
+++ b/pool/shard009/Python/0086863_test_text.py
@@ -0,0 +1,46 @@
+import numpy as np
+from numpy.testing import assert_array_equal
+from nose.tools import assert_equal
+from chowmein.text import LabelCountVectorizer
+
+ir = 'information retrieval'.split()
+ml = 'machine learning'.split()
+nlp = 'natural language processing'.split()
+tm = 'text mining'.split()
+
+other = ['---']
+
+docs = [ml + other + ml + nlp,
+ ir + tm + other + tm,
+ ml + other + tm + other,
+ nlp + nlp + nlp + ir + other,
+ [''],
+ other + other + other,
+ ml + ml + ml]
+
+labels = [ml, nlp, tm, ir]
+
+
+def test_label_count_vectorizer():
+ vect = LabelCountVectorizer()
+ d2l_mat = vect.transform(docs, labels)
+ assert_array_equal(d2l_mat.todense(),
+ np.asarray([[0, 2, 1, 0],
+ [1, 0, 0, 2],
+ [0, 1, 0, 1],
+ [1, 0, 3, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 3, 0, 0]], dtype=np.int64))
+
+ assert_equal(vect.index2label_, {0: ir, 1: ml, 2: nlp, 3: tm})
+
+
+def test_label_frequency():
+ vect = LabelCountVectorizer()
+ assert_equal(vect._label_frequency(['a'], ['a', 'a', 'a']), 3)
+ assert_equal(vect._label_frequency(['a', 'a'], ['a', 'a', 'a']), 2)
+ assert_equal(vect._label_frequency(['a'], []), 0)
+ assert_equal(vect._label_frequency(['a'], ['b', 'b', 'b']), 0)
+ assert_equal(vect._label_frequency(['a', 'b', 'a'],
+ ['a', 'b', 'a', 'b', 'a']), 2)
diff --git a/pool/shard009/Python/0086864_p5_findduplication.py b/pool/shard009/Python/0086864_p5_findduplication.py
new file mode 100644
index 0000000000000000000000000000000000000000..fad13aa4db0852cd07c14c9c6c8daad8ab648c7b
--- /dev/null
+++ b/pool/shard009/Python/0086864_p5_findduplication.py
@@ -0,0 +1,104 @@
+
+import pickle
+import math
+import matplotlib.pyplot as plt
+import matplotlib.image as mpimg
+from A1_notmnistdataset import p2_checkimage
+
+class DataExploration:
+ def __init__(self):
+ with open('../A1_notmnistdataset/notMNIST_3.pickle', 'rb') as f:
+ self.dataset = pickle.load(f)
+ self.train_dataset = self.dataset['train_dataset']
+ self.train_labels = self.dataset['train_labels']
+
+ self.valid_dataset = self.dataset['valid_dataset']
+ self.valid_labels = self.dataset['valid_labels']
+
+ self.test_dataset = self.dataset['test_dataset']
+ self.test_labels = self.dataset['test_labels']
+
+ self.train_filepaths = self.dataset['train_filepaths']
+ self.test_filepaths = self.dataset['test_filepaths']
+ self.valid_filepaths = self.dataset['valid_filepaths']
+
+# print('Training:', self.train_dataset.shape, self.train_labels.shape)
+# print('Validation:', self.valid_dataset.shape, self.valid_labels.shape)
+# print('Testing:', self.test_dataset.shape, self.test_labels.shape)
+ return
+ def checkDupwithin(self, images, groupname, image_paths=None):
+ temp_dict = {}
+ dup_dict={}
+ images.flags.writeable = False
+ count = 0
+ for idx, item in enumerate(images):
+ if item.data in temp_dict:
+ count = count + 1
+# print("duplicate {}:{}".format(count, idx))
+ existingId = temp_dict[item.data]
+ if not (existingId in dup_dict):
+ dup_dict[existingId] = []
+ dup_dict[existingId].append(idx)
+ continue
+ temp_dict[item.data] = idx
+ print("{} has {} duplicate items, {} total items".format(groupname, count, images.shape[0]))
+# print(dup_dict) images[dup_dict[25]]
+# di = dup_dict[128]
+# di = dup_dict[1018]
+# self.dispImages(image_paths[di], images[di])
+ return
+ def checkDupBetween(self,datasetA, datasetB,lablesB, A,B, Apaths = None, Bpaths=None):
+ temp_dict = {}
+ dup_dict={}
+ datasetA.flags.writeable = False
+ datasetB.flags.writeable = False
+ count = 0
+ #build up base table for datasetA in temp_dict
+ for idx, item in enumerate(datasetA):
+ if item.data in temp_dict:
+ continue
+ temp_dict[item.data] = idx
+ for idx,img in enumerate(datasetB):
+ if img.data in temp_dict:
+ count = count + 1
+ existingId = temp_dict[img.data]
+ if not (existingId in dup_dict):
+ dup_dict[existingId] = []
+ dup_dict[existingId].append(idx)
+
+ print("{} {} duplicate {}, total count {}, total count {}".format(A, B, count, datasetA.shape[0], datasetB.shape[0]))
+# print(Apaths[16812])
+# print(Bpaths[dup_dict[16812]])
+
+ return
+ def getDiffLableCount(self, dup_table, labelsB):
+ count = 0
+ for key, value in dup_table.iteritems():
+ truelabels = [labelsB[item] for item in value]
+ allthesame = all(truelabels[0] == item for item in truelabels)
+ if not allthesame:
+ count = count + 1
+ print(truelabels)
+ return count
+ def dispImages(self, filepaths, images):
+ ci = p2_checkimage.CheckImage()
+ ci.dispImages_filepath(filepaths, 1)
+ ci.dispImages(images, 2)
+ return
+ def run(self):
+
+
+ self.checkDupwithin(self.train_dataset,'train_dataset', self.train_filepaths)
+ self.checkDupwithin(self.test_dataset,'test_dataset')
+ self.checkDupwithin(self.valid_dataset,'validation_dataset')
+ self.checkDupBetween(self.train_dataset, self.test_dataset,self.test_labels,'train_dataset','test_dataset', self.train_filepaths, self.test_filepaths)
+ self.checkDupBetween(self.train_dataset, self.valid_dataset,self.test_labels,'train_dataset','validation_dataset')
+ self.checkDupBetween(self.valid_dataset, self.test_dataset,self.test_labels,'validation_dataset','test_dataset')
+ plt.show()
+ return
+
+
+
+if __name__ == "__main__":
+ obj= DataExploration()
+ obj.run()
diff --git a/pool/shard009/Python/0086865_init__.py b/pool/shard009/Python/0086865_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2da833e04ee7da1a5b761291c42c51c84af80575
--- /dev/null
+++ b/pool/shard009/Python/0086865_init__.py
@@ -0,0 +1,173 @@
+#!/usr/bin/env python
+#
+# Copyright 2007 Google 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.
+#
+
+"""Serve static files from a zipfile.
+
+This is a solution for apps that want to serve 1000s of small static
+files while staying withing the 1000 file limit.
+
+The simplest use case is driven purely from the handlers section in
+app.yaml, e.g.:
+
+ - url: /images/.*
+ script: $PYTHON_LIB/google/appengine/ext/zipserve
+
+This would invoke a main() within zipserve/__init__.py. This code
+would then take the URL path, and look for a .zip file under the first
+component of the path, in this case "images.zip" in the app's working
+directory. If found, it will then serve any matching paths below that
+from the zip file. In other words, /images/foo/icon.gif would map to
+foo/icon.gif in the zip file images.zip.
+
+You can also customize the behavior by adding a custom line to your
+WSGIApplication() invocation:
+
+ def main():
+ app = webapp.WSGIApplication(
+ [('/', MainPage),
+ ('/static/(.*)', zipserve.make_zip_handler('staticfiles.zip')),
+ ])
+
+You can pass max_age=N to the make_zip_handler() call to override the
+expiration time in seconds, which defaults to 600.
+
+To customize the behavior even more, you can subclass ZipHandler and
+override the get() method, or override it and call ServeFromZipFile()
+directly.
+
+Note that by default, a Cache-control is added that makes these pages
+cacheable even if they require authentication. If this is not what
+you want, override ZipHandler.SetCachingHeaders().
+"""
+
+
+import email.Utils
+import logging
+import mimetypes
+import time
+import zipfile
+
+from google.appengine.ext import webapp
+from google.appengine.ext.webapp import util
+
+
+def make_zip_handler(zipfilename, max_age=None, public=None):
+ """Factory function to construct a custom ZipHandler instance.
+
+ Args:
+ zipfilename: The filename of a zipfile.
+ max_age: Optional expiration time; defaults to ZipHandler.MAX_AGE.
+ public: Optional public flag; defaults to ZipHandler.PUBLIC.
+
+ Returns:
+ A ZipHandler subclass.
+ """
+ class CustomZipHandler(ZipHandler):
+ def get(self, name):
+ self.ServeFromZipFile(self.ZIPFILENAME, name)
+ ZIPFILENAME = zipfilename
+ if max_age is not None:
+ MAX_AGE = max_age
+ if public is not None:
+ PUBLIC = public
+
+ return CustomZipHandler
+
+
+class ZipHandler(webapp.RequestHandler):
+ """Request handler serving static files from zipfiles."""
+
+ zipfile_cache = {}
+
+ def get(self, prefix, name):
+ """GET request handler.
+
+ Typically the arguments are passed from the matching groups in the
+ URL pattern passed to WSGIApplication().
+
+ Args:
+ prefix: The zipfilename without the .zip suffix.
+ name: The name within the zipfile.
+ """
+ self.ServeFromZipFile(prefix + '.zip', name)
+
+ def ServeFromZipFile(self, zipfilename, name):
+ """Helper for the GET request handler.
+
+ This serves the contents of file 'name' from zipfile
+ 'zipfilename', logging a message and returning a 404 response if
+ either the zipfile cannot be opened or the named file cannot be
+ read from it.
+
+ Args:
+ zipfilename: The name of the zipfile.
+ name: The name within the zipfile.
+ """
+ zipfile_object = self.zipfile_cache.get(zipfilename)
+ if zipfile_object is None:
+ try:
+ zipfile_object = zipfile.ZipFile(zipfilename)
+ except (IOError, RuntimeError), err:
+ logging.error('Can\'t open zipfile %s: %s', zipfilename, err)
+ zipfile_object = ''
+ self.zipfile_cache[zipfilename] = zipfile_object
+ if zipfile_object == '':
+ self.error(404)
+ self.response.out.write('Not found')
+ return
+ try:
+ data = zipfile_object.read(name)
+ except (KeyError, RuntimeError), err:
+ self.error(404)
+ self.response.out.write('Not found')
+ return
+ content_type, encoding = mimetypes.guess_type(name)
+ if content_type:
+ self.response.headers['Content-Type'] = content_type
+ self.SetCachingHeaders()
+ self.response.out.write(data)
+
+ MAX_AGE = 600
+
+ PUBLIC = True
+
+ def SetCachingHeaders(self):
+ """Helper to set the caching headers.
+
+ Override this to customize the headers beyond setting MAX_AGE.
+ """
+ max_age = self.MAX_AGE
+ self.response.headers['Expires'] = email.Utils.formatdate(
+ time.time() + max_age, usegmt=True)
+ cache_control = []
+ if self.PUBLIC:
+ cache_control.append('public')
+ cache_control.append('max-age=%d' % max_age)
+ self.response.headers['Cache-Control'] = ', '.join(cache_control)
+
+
+def main():
+ """Main program.
+
+ This is invoked when this package is referenced from app.yaml.
+ """
+ application = webapp.WSGIApplication([('/([^/]+)/(.*)', ZipHandler)])
+ util.run_wsgi_app(application)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0086871_helpers.py b/pool/shard009/Python/0086871_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a445f958be5664cee842284bcd5434207fa33cf
--- /dev/null
+++ b/pool/shard009/Python/0086871_helpers.py
@@ -0,0 +1,233 @@
+import os
+import collections
+import motherbrain.base
+import logging
+
+from motherbrain.base import db as base_db
+from motherbrain.base.conf import get_config
+
+from bson.objectid import ObjectId
+
+from itertools import chain
+
+
+_opts = {
+ 'database': {
+ 'dbname': {'default': 'urlist'},
+ 'dbhost': {'default': 'mongo1'},
+ 'dbport': {'default': 27017, 'type': int},
+ 'dbusr': {'default': ''},
+ 'dbpwd': {'default': ''},
+ }
+}
+
+settings = get_config(_opts)
+db = base_db.get_db(settings)
+
+
+def last_visit(list_hash, current_user_id):
+ data = db.visit_tracker.find_one({'hash': list_hash,
+ 'user_id': current_user_id})
+
+ if not data:
+ return None
+
+ return data.get('last_visit_at')
+
+def full_url(list_id=None, base_url=None):
+ from urlparse import urljoin
+
+ return urljoin(base_url, list_id)
+
+
+def exclude_owner(data, owner_id):
+ return [x for x in data
+ if not owner_id == x]
+
+
+def is_favorited(model_data, current_user_id):
+ favorited_by, contributors = model_data
+
+ if not isinstance(favorited_by, collections.Iterable):
+ return False
+
+ if isinstance(contributors, collections.Iterable):
+ favorited_by = list(chain(favorited_by, contributors))
+
+ if any([True for x in favorited_by
+ if (isinstance(x, dict) and
+ x.get('user_id') == current_user_id)]):
+ return True
+
+ return False
+
+
+def custom_avatar(model_data):
+ user_id, username, profile_image = model_data
+
+ filename = '.'.join([str(user_id), 'png'])
+
+ fullpath = os.path.join('/srv/urlist_media',
+ 'profile_images', filename)
+
+ if not os.path.exists(fullpath):
+ return profile_image
+
+ return '/'.join(['/media', 'profile_images', filename])
+
+
+def working_set(user_id, current_user_id):
+ from motherbrain.models.working_set import Collection
+
+ _is_owner = {'user_id': str(user_id)}
+ _is_contrib = {'contributors.user_id': str(user_id),
+ 'contributors.status': 'accepted'}
+
+ query = {'$or': [_is_owner, _is_contrib]}
+
+ if not str(user_id) == str(current_user_id):
+ query['$and'] = [{'is_secret': False}]
+
+ # Matches list owned by the user, or contributed to.
+ # Private lists are visibles only by owner.
+ user_lists = db.urlists.find(query)
+
+ ws = Collection(list(user_lists))
+
+ return ws()
+
+
+def _lists_left(user_id, lists, bonus, condition, maxnum):
+ if not lists:
+ return maxnum
+
+ if not bonus:
+ bonus = 0
+
+ maxnum += bonus
+
+ num = len([x for x in lists if condition(x) and \
+ x.get('user_id') == str(user_id)])
+
+ return maxnum - num
+
+
+def secret_lists_left(model_data):
+ user_id, lists, bonus = model_data
+
+ condition = lambda x: x.get('is_secret')
+
+ return _lists_left(user_id, lists, bonus, condition, 4)
+
+
+def draft_lists_left(model_data):
+ user_id, lists, bonus = model_data
+ condition = lambda x: x.get('type') == 'draft'
+
+ return _lists_left(user_id, lists, bonus, condition, 6)
+
+
+def relist_amount(model_data):
+ list_hash, url_hash, from_list_hash, from_url_hash = model_data
+
+ target_list_hash = list_hash
+ target_url_hash = url_hash
+
+ if from_list_hash and from_url_hash:
+ target_list_hash = from_list_hash
+ target_url_hash = from_url_hash
+
+ tracker = db.relist_tracker.find_one({'list_hash': target_list_hash,
+ 'url_hash': target_url_hash})
+
+ if not tracker:
+ return 0
+
+ return tracker.get('count')
+
+
+def list_relist_amount(list_hash):
+ relists = db.relist_tracker.find({'list_hash': list_hash})
+
+ if not relists:
+ return 0
+
+ return sum([x.get('count') for x in relists])
+
+
+def get_userdata(user_id, field):
+ oid = ObjectId(user_id)
+
+ user = db.users.find_one({'_id': oid}, [field])
+
+ if not user:
+ return None
+
+ return user.get(field)
+
+
+def get_listdata(hash, field):
+ list_ = db.urlists.find_one({'hash': hash}, [field])
+
+ if not list_:
+ return None
+
+ return list_.get(field)
+
+
+def followed_lists(user_id=None):
+ from motherbrain.models.working_set import Collection
+
+ user_oid = ObjectId(user_id)
+
+ _is_not_contributor = {'contributors.user_id': {'$ne': user_id}}
+ _is_not_owner = {'user_id': {'$ne': user_id}}
+
+ _exclude = dict(_is_not_contributor, **_is_not_owner)
+ _include = {'followers': user_oid}
+
+ _query = dict(_include, **_exclude)
+
+ data = db.urlists.find(_query)
+
+ lists = Collection(list(data))
+
+ return lists()
+
+
+def is_following_me(model_data, current_user_id=None):
+ user_id, xs = model_data
+
+ if not isinstance(xs, list):
+ return False
+
+ if current_user_id == user_id:
+ return True
+
+ return current_user_id in xs
+
+
+def relists(model_data):
+ '''Return an array of Relisted Url model objects.'''
+
+ list_hash, url_hash, from_list_hash, from_url_hash = model_data
+
+ if all([from_list_hash, from_url_hash]):
+ target_list_hash = from_list_hash
+ target_url_hash = from_url_hash
+ else:
+ target_list_hash = list_hash
+ target_url_hash = url_hash
+
+ tracker = db.relist_tracker.find_one({'list_hash': target_list_hash,
+ 'url_hash': target_url_hash})
+
+ if not tracker:
+ return []
+
+ relists = [x for x in tracker.get('relists', [])
+ if not x.get('target_list_hash') == list_hash]
+
+ from motherbrain.models import relisted_url
+
+ return relisted_url.Collection(relists)()
diff --git a/pool/shard009/Python/0086877_pickhalos.py b/pool/shard009/Python/0086877_pickhalos.py
new file mode 100644
index 0000000000000000000000000000000000000000..30b8b3beafedb5093c69674bc893b755ebd52ff5
--- /dev/null
+++ b/pool/shard009/Python/0086877_pickhalos.py
@@ -0,0 +1,179 @@
+"""
+Select a good halo for zoom in
+
+mass = desired mass of the halo (Msun)
+halocat = rockstar halo cat
+snap = ramses snapshop
+output = root of output names
+deltamass = tolerance of mass range (fraction)
+
+"""
+
+def pickhalos(mass=1e12,halocat='halos_0.0.ascii',snap='info_00001.txt',
+ deltamass=0.05,output='pickhalo'):
+
+ import yt
+ import mypython as mp
+ import numpy as np
+
+ #load the simulation
+ sim = yt.load(snap)
+
+ #load rockstar ascii
+ halos=mp.ramses.parserockstar.parserockstar(halocat)
+ nhalos=len(halos['id'])
+
+ #select halos in correct mass range
+
+ #masses in Msun
+ masses=np.array(halos['mvir'])/sim.hubble_constant
+
+ #filter
+ mmin=mass-mass*deltamass
+ mmax=mass+mass*deltamass
+
+ select=np.nonzero((masses >= mmin) & (masses <= mmax))
+ select=select[0]
+ nselect=select.size
+
+ print "Selected ", nselect, " halos with masses [ ", mmin, ",", mmax, " ]"
+
+ #to slice
+ #print halos['mvir'][select]
+
+ #open output
+ outfile=open(output+'_haloinfo.txt','w')
+ outfile.write('#HaloID,Nnearest,MaxM,NearestID\n')
+
+ #now do some stats on the halos
+ for hhh in range(nselect):
+
+ outfile.write(str(halos['id'][select[hhh]])+'\t')
+
+ #find halos within 4Rvir
+ #distance to halo under exam. in comoving Mpc/h
+ radius=(halos['x']-halos['x'][select[hhh]])**2+(halos['y']-halos['y'][select[hhh]])**2+\
+ (halos['z']-halos['z'][select[hhh]])**2
+ radius=np.sqrt(radius)
+
+ #3Rvir in comoving Mpc/h
+ fourrvir=4*halos['rvir'][select[hhh]]*1e-3
+
+ #find nearest
+ nearest=np.nonzero((radius <= fourrvir) & (radius > 0))
+ nearest=nearest[0]
+ outfile.write(str(nearest.size)+'\t')
+
+ #most massive nearest
+ massnear=np.array(halos['mvir'][nearest])/sim.hubble_constant
+ if nearest.size > 0:
+ outfile.write(str(np.max(massnear))+'\t')
+ else:
+ outfile.write('0.0\t')
+
+ #write id nearest
+ outfile.write(','.join([str(x) for x in halos['id'][nearest]])+'\n')
+
+ #close
+ outfile.close()
+
+ #now onto display options
+ plotselecthalos('x',sim,halos,select,output)
+ plotselecthalos('y',sim,halos,select,output)
+ plotselecthalos('z',sim,halos,select,output)
+
+
+#formatter functions to map grid units to box size
+resol=0
+boxsize=0
+def mjrFormatter(x, pos):
+ global resol
+ global boxsize
+ #The two args are the value and tick position
+ off=x/resol*boxsize #phys
+ return "%.1f" % off
+
+
+def plotselecthalos(axis,sim,halos,select,output):
+
+ """
+ Function that plots a projection of the cube with selected halos
+
+ """
+
+ import matplotlib as mpl
+ import yt
+ from yt.visualization.fixed_resolution import FixedResolutionBuffer
+ import matplotlib.pyplot as plt
+ import matplotlib.image as mpimg
+ import numpy as np
+
+
+ #define axis and permutation
+ ax={'x':0,'y':1,'z':2}
+ ax1={'x':'y','y':'z','z':'x'}
+ ax2={'x':'z','y':'x','z':'y'}
+
+ #make a projection by hand along one axis
+ global resol
+ resol=512
+ global boxsize
+ boxsize=(sim.domain_width.in_units('Mpccm/h'))[0].v #comoving Mpc/h
+
+ projx=sim.proj(("deposit","all_density"),ax[axis])
+ image2d = FixedResolutionBuffer(projx, (0.0, 0.999, 0.0, 0.999),(resol,resol))
+
+ #some display stuff
+ fig=plt.figure(1,figsize=(8,8), dpi=300)
+ imgplot = plt.imshow(np.log10(image2d["deposit","all_density"].v),origin='lower')
+ imgplot.set_clim(-3,-1)
+
+ #cbar=plt.colorbar()
+ #cbar.set_label('log Density'+' (g cm$^{-2}$)', rotation=90)
+
+ #loop over the halos and plot them
+ print "Looping over selected ", select.size
+ for hh in range(select.size):
+
+ radius=10*halos['rvir'][select[hh]]*1e-3 #cMpc/h
+
+ circle = plt.Circle((halos[ax1[axis]][select[hh]]*resol/boxsize,
+ halos[ax2[axis]][select[hh]]*resol/boxsize),
+ radius=radius,fc='None', ec='black', linewidth=1)
+ plt.gca().add_patch(circle)
+ plt.gca().text(halos[ax1[axis]][select[hh]]*resol/boxsize-10,
+ halos[ax2[axis]][select[hh]]*resol/boxsize-10,
+ str(halos['id'][select[hh]]),fontsize=8,color='black')
+
+ #map the axis to box size
+ plt.xlabel(ax1[axis]+' (cMpc h$^{-1}$)')
+ plt.ylabel(ax2[axis]+' (cMpc h$^{-1}$)')
+
+ axe1 = plt.gca()
+ axe1.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
+ axe1.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
+
+ plt.savefig(output+"_"+axis+"_proj.ps")
+ fig.clf()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pool/shard009/Python/0086884_init__.py b/pool/shard009/Python/0086884_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..afbe8c55f704799af276adedcfdc0115f6177993
--- /dev/null
+++ b/pool/shard009/Python/0086884_init__.py
@@ -0,0 +1,58 @@
+import sys
+import django
+import django.db
+
+import tsadmuser
+from .base import TSAdmView
+from ..log import TSAdmLogger
+
+logger = TSAdmLogger(__name__)
+
+class HomeView(TSAdmView):
+ template_name = 'tsadm/home.html'
+
+ def __init__(self):
+ logger.debug('HomeView init')
+ super(HomeView, self).__init__()
+
+ def get_context_data(self, **kwargs):
+ logger.debug('get_context_data')
+ context = super(HomeView, self).get_context_data(**kwargs)
+ context['tsadm']['userSites'] = tsadmuser.sitesAll(self.tsadm.user)
+ return context
+
+
+class InfoView(TSAdmView):
+ template_name = 'tsadm/info.html'
+
+ def __init__(self):
+ logger.debug('InfoView init')
+ super(InfoView, self).__init__()
+
+ def _dbconns(self):
+ dbConnections = list()
+ for dbconn in django.db.connections.all():
+ dbinfo = {
+ 'alias': dbconn.alias,
+ 'version': dbconn.Database.version,
+ 'name': dbconn.settings_dict['NAME'],
+ 'vendor': dbconn.vendor,
+ 'vendorVersion': None,
+ }
+ if dbconn.vendor == 'sqlite':
+ dbinfo['vendorVersion'] = dbconn.Database.sqlite_version
+ dbConnections.append(dbinfo)
+ return dbConnections
+
+ def get_context_data(self, **kwargs):
+ logger.debug('get_context_data')
+ context = super(InfoView, self).get_context_data(**kwargs)
+ context['tsadm']['config'] = self.tsadm.cfg.dumps()
+ context['tsadm']['dbConnections'] = self._dbconns()
+ context['python'] = {
+ 'version': '{}.{}.{}'.format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro),
+ }
+ context['django'] = {
+ 'version': django.get_version(),
+ }
+ return context
diff --git a/pool/shard009/Python/0086887_WMovie.py b/pool/shard009/Python/0086887_WMovie.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d790188bb81f39360d204f1406821bc347af520
--- /dev/null
+++ b/pool/shard009/Python/0086887_WMovie.py
@@ -0,0 +1,26 @@
+# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
+
+# WeCase -- This file implemented WMovie, a memory-store based QMovie.
+# Copyright (C) 2013, 2014 The WeCase Developers.
+# License: GPL v3 or later.
+
+
+from PyQt4 import QtCore, QtGui
+
+
+class WMovie(QtGui.QMovie):
+
+ def __init__(self, filepath, parent=None):
+ super().__init__(parent)
+ self._fileName = ""
+
+ data = b""
+ with open(filepath, "rb") as file:
+ self._fileName = file.name
+ data = file.read()
+ self._imageData = QtCore.QBuffer()
+ self._imageData.setData(data)
+ self.setDevice(self._imageData)
+
+ def fileName(self):
+ return self._fileName
diff --git a/pool/shard009/Python/0086889_ManualSanityChecker.py b/pool/shard009/Python/0086889_ManualSanityChecker.py
new file mode 100644
index 0000000000000000000000000000000000000000..463e1d58258b50768ffe44a77fcaeab9f8232be7
--- /dev/null
+++ b/pool/shard009/Python/0086889_ManualSanityChecker.py
@@ -0,0 +1,104 @@
+# Copyright (c) 2011 The Hazelwire Team.
+#
+# This file is part of Hazelwire.
+#
+# Hazelwire 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.
+#
+# Hazelwire 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 Hazelwire. If not, see .
+r"""
+This service listens for manual sanity check requests from the Admin interface.
+It supports both the normal and peer-to-peer sanity checks.
+Send C{CHECK TYPE} to port 9997 on C{localhost} to request a sanity check.
+"""
+import socket, copy, logging
+from DatabaseHandler import DatabaseHandler
+from SanityCheck import checkIP
+import P2PSanityCheck
+
+class ManualSanityCheckerService:
+
+ def __init__(self, host, port, db):
+ """
+ Initialises the service.
+ @type host: string
+ @param host: the IP to listen on.
+ @type port: integer
+ @param port: the port to listen on.
+ @type db: string
+ @param db: path to the SQLite database file.
+ """
+ self.db = DatabaseHandler(db)
+ self.host = host
+ self.port = port
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
+ self.sock.bind((host,port))
+ self.sock.listen(1)
+ self.modules = self.db.getModulePortsAndNames()
+
+ def startServer(self):
+ self.running = True
+ while self.running:
+ conn, addr = self.sock.accept()
+ self.handle(conn, addr)
+ conn.close()
+ self.sock.close()
+
+ def handle(self, conn, addr):
+ """Handles a request"""
+ data = conn.recv(1024).strip('\n')
+ if data.startswith("CHECK TYPE "):
+ self.contestants = self.db.getClientIPs()
+ checktype = data.split(' ')[2]
+ IP = data.split(' ')[3]
+ if checktype == "NORMAL":
+ logging.info("[MANUALNORMAL] Starting check")
+ for module in self.modules:
+ logging.info("Checking module " + module['name'] + "on port " + str(module['port']))
+ result = checkIP(IP, module['port'])[0]
+ if not result['fine']:
+ logging.info("[MANUALNORMAL] Adding " + IP + " with port " + str(result['port']))
+ self.db.addSuspiciousContestant(IP, result['port'],'',module['name'])
+ logging.info("[MANUALNORMAL] Finished check")
+
+ elif checktype == "P2P":
+ logging.info("[MANUALP2P] Starting check")
+ for module in self.modules:
+ logging.info("[MANUALP2P] Checking module " + module['name'] + " on port " + str(module['port']))
+ self.targets = copy.copy(self.contestants)
+ self.targets.remove(IP)
+ p2p = P2PSanityCheck.PeerToPeerSanityChecker(IP,self.targets, module['port'])
+ p2p.checkIP()
+ results = p2p.getResults()
+ for client in results:
+ for result in client['results']:
+ #logging.info("%s reports port %s on %s: fine = %s" % (client['IP'], result['port'], IP, result['fine']))
+ if result['fine'] == 'False':
+ if result['port'] == "":
+ logging.info("[MANUALP2P] Adding " + client['IP'] + " for not running P2PRequestListener")
+ self.db.addSuspiciousContestant(client["IP"], "","", "PeerToPeerRequestListener")
+ else:
+ logging.info("[MANUALP2P] Adding " + IP + " with port " + str(result['port']) + "reported by " + client['IP'])
+ self.db.addSuspiciousContestant(IP, result['port'], client['IP'], module['name'])
+ logging.info("[MANUALP2P] Finished check.")
+
+ elif data == "STOPMANUAL":
+ logging.info("[MANUALSERVICE] Stopping Manual Sanity Check Service...")
+ self.running = False
+
+ def stopServer(self):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect((self.host, self.port))
+ sock.send('STOPMANUAL')
+ sock.close()
+
+
diff --git a/pool/shard009/Python/0086894_sdk.py b/pool/shard009/Python/0086894_sdk.py
new file mode 100644
index 0000000000000000000000000000000000000000..c771cdf2d333e991b85b0f9c89deb6882582cf38
--- /dev/null
+++ b/pool/shard009/Python/0086894_sdk.py
@@ -0,0 +1,153 @@
+# 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.
+
+"""
+SDK Client
+"""
+import sys
+
+import functools
+import openstack
+from openstack import connection
+from openstack import exceptions as sdk_exc
+from oslo_config import cfg
+from oslo_log import log as logging
+from oslo_serialization import jsonutils
+from requests import exceptions as req_exc
+import six
+
+from senlin.common import exception as senlin_exc
+from senlin import version
+
+USER_AGENT = 'senlin'
+exc = sdk_exc
+LOG = logging.getLogger(__name__)
+
+openstack.enable_logging(debug=False, stream=sys.stdout)
+
+
+def parse_exception(ex):
+ """Parse exception code and yield useful information."""
+ code = 500
+
+ LOG.error(six.text_type(ex))
+ if isinstance(ex, sdk_exc.HttpException):
+ # some exceptions don't contain status_code
+ if hasattr(ex, "status_code") and ex.status_code is not None:
+ code = ex.status_code
+ elif hasattr(ex, "http_status") and ex.http_status is not None:
+ code = ex.http_status
+
+ message = six.text_type(ex)
+ data = {}
+ if ex.details is None and ex.response is not None:
+ data = ex.response.json()
+ else:
+ try:
+ data = jsonutils.loads(ex.details)
+ except Exception:
+ # Some exceptions don't have details record or
+ # are not in JSON format
+ pass
+
+ # try dig more into the exception record
+ # usually 'data' has two types of format :
+ # type1: {"forbidden": {"message": "error message", "code": 403}
+ # type2: {"code": 404, "error": { "message": "not found"}}
+ if data:
+ code = data.get('code', code)
+ message = data.get('message', message)
+ error = data.get('error', None)
+ if error:
+ code = data.get('code', code)
+ message = data['error'].get('message', message)
+ else:
+ for value in data.values():
+ code = value.get('code', code)
+ message = value.get('message', message)
+
+ elif isinstance(ex, sdk_exc.SDKException):
+ # Besides HttpException there are some other exceptions like
+ # ResourceTimeout can be raised from SDK, handle them here.
+ message = six.text_type(ex)
+ elif isinstance(ex, req_exc.RequestException):
+ # Exceptions that are not captured by SDK
+ code = ex.errno
+ message = six.text_type(ex)
+ else:
+ # This could be a generic exception or something we don't understand
+ message = six.text_type(ex)
+
+ raise senlin_exc.InternalError(code=code, message=message)
+
+
+def translate_exception(func):
+ """Decorator for exception translation."""
+
+ @functools.wraps(func)
+ def invoke_with_catch(driver, *args, **kwargs):
+ try:
+ return func(driver, *args, **kwargs)
+ except Exception as ex:
+ raise parse_exception(ex)
+
+ return invoke_with_catch
+
+
+def create_connection(params=None):
+ if params is None:
+ params = {}
+
+ if 'token' in params:
+ params['auth_type'] = 'token'
+ params['app_name'] = USER_AGENT
+ params['app_version'] = version.version_info.version_string()
+ params.setdefault('region_name', cfg.CONF.default_region_name)
+ params.setdefault('identity_api_version', '3')
+ params.setdefault('messaging_api_version', '2')
+
+ try:
+ conn = connection.Connection(**params)
+ except Exception as ex:
+ raise parse_exception(ex)
+
+ return conn
+
+
+def authenticate(**kwargs):
+ """Authenticate using openstack sdk based on user credential"""
+
+ conn = create_connection(kwargs)
+ access_info = {
+ 'token': conn.session.get_token(),
+ 'user_id': conn.session.get_user_id(),
+ 'project_id': conn.session.get_project_id()
+ }
+
+ return access_info
+
+
+class FakeResourceObject(object):
+ """Generate a fake SDK resource object based on given dictionary"""
+ def __init__(self, params):
+ for key in params:
+ setattr(self, key, params[key])
+
+ def to_dict(self):
+ """Override this function in subclass to handle special attributes"""
+ data = {}
+ for attr in dir(self):
+ if not attr.startswith('__'):
+ # Exclude built-in attributes of python object
+ data[attr] = getattr(self, attr)
+
+ return data
diff --git a/pool/shard009/Python/0086896_recipe-466330.py b/pool/shard009/Python/0086896_recipe-466330.py
new file mode 100644
index 0000000000000000000000000000000000000000..be73d21c232a0aca1abda452bbef9d4379f726e0
--- /dev/null
+++ b/pool/shard009/Python/0086896_recipe-466330.py
@@ -0,0 +1,62 @@
+def select(pos, seq):
+ """select(pos, seq): find the nth rank ordered element
+ (the least value has rank 0).
+ Note1: it modifies the seq.
+ Note2: this function is useful with Psyco, otherwise .sort is
+ faster until len(seq)>~3e6"""
+ # Version 1.1, Nov 13 2004, from "Numerical Recipes".
+ lo = 0
+ up = len(seq)-1
+ if posup:
+ raise 'Selection out of bounds.'
+ else:
+ while up>=pos and pos>=lo:
+ i = lo
+ j = up
+ tempr = seq[pos]
+ seq[pos] = seq[lo]
+ seq[lo] = tempr
+ # Split in two
+ while i tempr:
+ j -= 1
+ seq[i] = seq[j]
+ while i~3e6
+ import psyco
+except ImportError:
+ pass
+else:
+ psyco.bind(select)
+
+
+if __name__ == '__main__': # Test ----------------------
+ from time import clock
+ import random
+ nrepetiotions = 6
+ print "nrepetiotions=", nrepetiotions
+ print "len(list), average min time select of 1"\
+ "element of list, min time select(list):"
+ for j in xrange(6, 21):
+ n = 2**j
+ v = []
+ for i in range(nrepetiotions):
+ seq = [random.random() for x in xrange(n+1)]
+ nd2 = int(n//2)
+ t1 = clock()
+ select(nd2, seq)
+ t2 = clock()
+ v.append(t2-t1)
+ print "2^"+str(j)+"=", n, round(1000000*min(v)/n, 3), round(min(v), 3)
diff --git a/pool/shard009/Python/0086900_account.py b/pool/shard009/Python/0086900_account.py
new file mode 100644
index 0000000000000000000000000000000000000000..38009bfc282790a3348dacfdadaa1e9684d55e12
--- /dev/null
+++ b/pool/shard009/Python/0086900_account.py
@@ -0,0 +1,24 @@
+__copyright__ = 'Copyright(c) Gordon Elliott 2017'
+
+"""
+"""
+
+from a_tuin.db import TableMap, PagedQuery, InstanceQuery
+
+from glod.model.account import Account, AccountStatus, AccountCollection
+
+from glod.db.db_column_type_map import DB_COLUMN_TYPE_MAP
+from glod.db.constants import SCHEMA_NAME
+
+
+TableMap(Account, SCHEMA_NAME, 'account', DB_COLUMN_TYPE_MAP)
+
+
+class AccountInstanceQuery(InstanceQuery):
+ def __init__(self, session):
+ super().__init__(Account, AccountCollection, session)
+
+
+class AccountQuery(PagedQuery):
+ def __init__(self, session):
+ super().__init__(Account, AccountCollection, session)
diff --git a/pool/shard009/Python/0086902_multi_gpu_test.py b/pool/shard009/Python/0086902_multi_gpu_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b3118a36185c609270fd4e9602b8f80ab1309b3
--- /dev/null
+++ b/pool/shard009/Python/0086902_multi_gpu_test.py
@@ -0,0 +1,52 @@
+# pylint: disable=no-self-use,invalid-name
+from copy import deepcopy
+
+import keras.backend as K
+from deep_qa.common.params import Params
+from deep_qa.models.text_classification import ClassificationModel
+from deep_qa.testing.test_case import DeepQaTestCase
+
+
+class TestMultiGpu(DeepQaTestCase):
+
+ def setUp(self):
+ super(TestMultiGpu, self).setUp()
+ self.write_true_false_model_files()
+ self.args = Params({
+ 'num_gpus': 2,
+ })
+
+ def test_model_can_train_and_load(self):
+ self.ensure_model_trains_and_loads(ClassificationModel, self.args)
+
+ def test_model_can_train_and_load_with_generator(self):
+ args = self.args
+
+ args["data_generator"] = {"dynamic_batching": True, "padding_noise": 0.4}
+ self.ensure_model_trains_and_loads(ClassificationModel, args)
+
+ def test_variables_live_on_cpu(self):
+ model = self.get_model(ClassificationModel, self.args)
+ model.train()
+
+ trainable_variables = model.model.trainable_weights
+ for variable in trainable_variables:
+ # This is an odd quirk of tensorflow - the devices are actually named
+ # slightly differently from their scopes ... (i.e != "/cpu:0")
+ assert variable.device == "/cpu:0" or variable.device == ""
+
+ def test_multi_gpu_shares_variables(self):
+ multi_gpu_model = self.get_model(ClassificationModel, self.args)
+
+ single_gpu_args = deepcopy(self.args)
+ single_gpu_args["num_gpus"] = 1
+ single_gpu_model = self.get_model(ClassificationModel, single_gpu_args)
+
+ multi_gpu_model.train()
+ multi_gpu_variables = [x.name for x in multi_gpu_model.model.trainable_weights]
+
+ K.clear_session()
+ single_gpu_model.train()
+ single_gpu_variables = ["tower_0/" + x.name for x in single_gpu_model.model.trainable_weights]
+
+ assert single_gpu_variables == multi_gpu_variables
diff --git a/pool/shard009/Python/0086903_pm.py b/pool/shard009/Python/0086903_pm.py
new file mode 100644
index 0000000000000000000000000000000000000000..090888c339c528865935efc2200dd67c1f6737be
--- /dev/null
+++ b/pool/shard009/Python/0086903_pm.py
@@ -0,0 +1,14 @@
+from sa_tools import SAObj
+from sa_tools.parsers.pm import PMParser
+
+
+class PM(SAObj):
+ parser = PMParser()
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.url = "http://forums.somethingawful.com/private.php"
+
+ info_gen = self.parser.parse(self._content)
+ self._apply_key_vals(info_gen)
\ No newline at end of file
diff --git a/pool/shard009/Python/0086905_api.py b/pool/shard009/Python/0086905_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d550750a9320cee9293175cf1a90625be661731
--- /dev/null
+++ b/pool/shard009/Python/0086905_api.py
@@ -0,0 +1,171 @@
+from django.conf import settings
+from django.db import connections
+from django.db.models import Count, Q
+
+from rest_framework import viewsets
+from rest_framework.decorators import detail_route
+from rest_framework.response import Response
+from rest_framework_extensions.cache.decorators import cache_response
+from rest_framework_extensions.key_constructor import bits
+from rest_framework_extensions.key_constructor.constructors import DefaultObjectKeyConstructor
+
+from nc.models import Agency, Stop
+from nc.models import SEARCH_TYPE_CHOICES as SEARCH_TYPE_CHOICES_TUPLES
+from nc import serializers
+from tsdata.utils import GroupedData
+
+
+GROUPS = {'A': 'asian',
+ 'B': 'black',
+ 'I': 'native_american',
+ 'U': 'other',
+ 'W': 'white',
+ 'H': 'hispanic'}
+
+PURPOSE_CHOICES = {1: 'Speed Limit Violation',
+ 2: 'Stop Light/Sign Violation',
+ 3: 'Driving While Impaired',
+ 4: 'Safe Movement Violation',
+ 5: 'Vehicle Equipment Violation',
+ 6: 'Vehicle Regulatory Violation',
+ 7: 'Seat Belt Violation',
+ 8: 'Investigation',
+ 9: 'Other Motor Vehicle Violation',
+ 10: 'Checkpoint'}
+
+GROUP_DEFAULTS = {'asian': 0,
+ 'black': 0,
+ 'native_american': 0,
+ 'other': 0,
+ 'white': 0,
+ 'hispanic': 0}
+
+SEARCH_TYPE_CHOICES = dict(SEARCH_TYPE_CHOICES_TUPLES)
+
+
+class QueryKeyConstructor(DefaultObjectKeyConstructor):
+ params_query = bits.QueryParamsKeyBit(['officer'])
+
+
+query_cache_key_func = QueryKeyConstructor()
+
+
+class AgencyViewSet(viewsets.ReadOnlyModelViewSet):
+ queryset = Agency.objects.all()
+ serializer_class = serializers.AgencySerializer
+
+ def query(self, results, group_by, filter_=None):
+ # date trunc on year, respecting NC time zone
+ year_sql, year_params = connections[Stop.objects.db].ops.datetime_trunc_sql(
+ 'year', 'date', settings.NC_TIME_ZONE,
+ )
+ qs = Stop.objects.extra(select={'year': year_sql}, select_params=year_params)
+ # filter down stops by agency only those who were drivers
+ qs = qs.filter(agency=self.get_object(), person__type='D')
+ # filter down by officer if supplied
+ officer = self.request.query_params.get('officer', None)
+ if officer:
+ qs = qs.filter(officer_id=officer)
+ if filter_:
+ qs = qs.filter(filter_)
+ # group by specified fields and order by year
+ qs = qs.values(*group_by).order_by('year')
+ for stop in qs.annotate(count=Count('date')):
+ data = {}
+ if 'year' in group_by:
+ data['year'] = stop['year'].year
+ if 'purpose' in group_by:
+ purpose = PURPOSE_CHOICES.get(stop['purpose'],
+ stop['purpose'])
+ data['purpose'] = purpose
+
+ if 'search__type' in group_by:
+ data['search_type'] = SEARCH_TYPE_CHOICES.get(
+ stop['search__type'],
+ stop['search__type'],
+ )
+
+ if 'person__race' in group_by:
+ # The 'Hispanic' ethnicity option is now being aggreggated into its
+ # own race category, and its count excluded from the other counts.
+ if stop['person__ethnicity'] == 'H':
+ race = GROUPS.get('H', 'H')
+ else:
+ race = GROUPS.get(stop['person__race'],
+ stop['person__race'])
+
+ data.setdefault(race, 0)
+ data[race] += stop['count']
+
+ results.add(**data)
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def stops(self, request, pk=None):
+ results = GroupedData(by='year', defaults=GROUP_DEFAULTS)
+ self.query(results, group_by=('year', 'person__race', 'person__ethnicity'))
+ return Response(results.flatten())
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def stops_by_reason(self, request, pk=None):
+ response = {}
+ # stops
+ results = GroupedData(by=('purpose', 'year'), defaults=GROUP_DEFAULTS)
+ self.query(results, group_by=('purpose', 'year', 'person__race', 'person__ethnicity'))
+ response['stops'] = results.flatten()
+ # searches
+ results = GroupedData(by=('purpose', 'year'), defaults=GROUP_DEFAULTS)
+ self.query(results, group_by=('purpose', 'year', 'person__race', 'person__ethnicity'),
+ filter_=Q(search__isnull=False))
+ response['searches'] = results.flatten()
+ return Response(response)
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def use_of_force(self, request, pk=None):
+ results = GroupedData(by='year', defaults=GROUP_DEFAULTS)
+ q = Q(search__isnull=False) & Q(engage_force='t')
+ self.query(results, group_by=('year', 'person__race', 'person__ethnicity'), filter_=q)
+ return Response(results.flatten())
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def searches(self, request, pk=None):
+ results = GroupedData(by='year', defaults=GROUP_DEFAULTS)
+ q = Q(search__isnull=False)
+ self.query(results, group_by=('year', 'person__race', 'person__ethnicity'), filter_=q)
+ return Response(results.flatten())
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def searches_by_type(self, request, pk=None):
+ results = GroupedData(by=('search_type', 'year'), defaults=GROUP_DEFAULTS)
+ q = Q(search__isnull=False)
+ self.query(
+ results,
+ group_by=(
+ 'search__type',
+ 'year',
+ 'person__race',
+ 'person__ethnicity',
+ ),
+ filter_=q,
+ )
+ return Response(results.flatten())
+
+ @detail_route(methods=['get'])
+ @cache_response(key_func=query_cache_key_func)
+ def contraband_hit_rate(self, request, pk=None):
+ response = {}
+ # searches
+ results = GroupedData(by='year', defaults=GROUP_DEFAULTS)
+ q = Q(search__isnull=False)
+ self.query(results, group_by=('year', 'person__race', 'person__ethnicity'), filter_=q)
+ response['searches'] = results.flatten()
+ # searches
+ results = GroupedData(by='year', defaults=GROUP_DEFAULTS)
+ q = Q(search__contraband__isnull=False)
+ self.query(results, group_by=('year', 'person__race', 'person__ethnicity'), filter_=q)
+ response['contraband'] = results.flatten()
+ return Response(response)
diff --git a/pool/shard009/Python/0086908_ibenc_lsw08_test.py b/pool/shard009/Python/0086908_ibenc_lsw08_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbb5a70858a8f50e1299a17bfec5d12ff02c77ec
--- /dev/null
+++ b/pool/shard009/Python/0086908_ibenc_lsw08_test.py
@@ -0,0 +1,31 @@
+import unittest
+
+from charm.schemes.ibenc.ibenc_lsw08 import IBE_Revoke
+from charm.toolbox.pairinggroup import PairingGroup, GT
+
+debug = False
+
+
+class IBE_RevokeTest(unittest.TestCase):
+ def testIBE_Revoke(self):
+ # scheme designed for symmetric billinear groups
+ grp = PairingGroup('SS512')
+ n = 5 # total # of users
+
+ ibe = IBE_Revoke(grp)
+
+ ID = "user2@email.com"
+ S = ["user1@email.com", "user3@email.com", "user4@email.com"]
+ (mpk, msk) = ibe.setup(n)
+
+ sk = ibe.keygen(mpk, msk, ID)
+ if debug: print("Keygen...\nsk :=", sk)
+
+ M = grp.random(GT)
+
+ ct = ibe.encrypt(mpk, M, S)
+ if debug: print("Ciphertext...\nct :=", ct)
+
+ m = ibe.decrypt(S, ct, sk)
+ assert M == m, "Decryption FAILED!"
+ if debug: print("Successful Decryption!!!")
diff --git a/pool/shard009/Python/0086909_patch_handler.py b/pool/shard009/Python/0086909_patch_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a23d5b0f4609c5a82a9bb6114b2c6540b1be6f5
--- /dev/null
+++ b/pool/shard009/Python/0086909_patch_handler.py
@@ -0,0 +1,221 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
+# License: MIT. See LICENSE
+""" Patch Handler.
+
+This file manages execution of manaully written patches. Patches are script
+that apply changes in database schema or data to accomodate for changes in the
+code.
+
+Ways to specify patches:
+
+1. patches.txt file specifies patches that run before doctype schema
+migration. Each line represents one patch (old format).
+2. patches.txt can alternatively also separate pre and post model sync
+patches by using INI like file format:
+ ```patches.txt
+ [pre_model_sync]
+ app.module.patch1
+ app.module.patch2
+
+
+ [post_model_sync]
+ app.module.patch3
+ ```
+
+ When different sections are specified patches are executed in this order:
+ 1. Run pre_model_sync patches
+ 2. Reload/resync all doctype schema
+ 3. Run post_model_sync patches
+
+ Hence any patch that just needs to modify data but doesn't depend on
+ old schema should be added to post_model_sync section of file.
+
+3. simple python commands can be added by starting line with `execute:`
+`execute:` example: `execute:print("hello world")`
+"""
+
+import configparser
+import time
+from enum import Enum
+from textwrap import dedent, indent
+from typing import List, Optional
+
+import frappe
+
+
+class PatchError(Exception):
+ pass
+
+
+class PatchType(Enum):
+ pre_model_sync = "pre_model_sync"
+ post_model_sync = "post_model_sync"
+
+
+def run_all(skip_failing: bool = False, patch_type: Optional[PatchType] = None) -> None:
+ """run all pending patches"""
+ executed = set(frappe.get_all("Patch Log", fields="patch", pluck="patch"))
+
+ frappe.flags.final_patches = []
+
+ def run_patch(patch):
+ try:
+ if not run_single(patchmodule = patch):
+ print(patch + ': failed: STOPPED')
+ raise PatchError(patch)
+ except Exception:
+ if not skip_failing:
+ raise
+ else:
+ print('Failed to execute patch')
+
+ patches = get_all_patches(patch_type=patch_type)
+
+ for patch in patches:
+ if patch and (patch not in executed):
+ run_patch(patch)
+
+ # patches to be run in the end
+ for patch in frappe.flags.final_patches:
+ patch = patch.replace('finally:', '')
+ run_patch(patch)
+
+def get_all_patches(patch_type: Optional[PatchType] = None) -> List[str]:
+
+ if patch_type and not isinstance(patch_type, PatchType):
+ frappe.throw(f"Unsupported patch type specified: {patch_type}")
+
+ patches = []
+ for app in frappe.get_installed_apps():
+ patches.extend(get_patches_from_app(app, patch_type=patch_type))
+
+ return patches
+
+def get_patches_from_app(app: str, patch_type: Optional[PatchType] = None) -> List[str]:
+ """ Get patches from an app's patches.txt
+
+ patches.txt can be:
+ 1. ini like file with section for different patch_type
+ 2. plain text file with each line representing a patch.
+ """
+
+ patches_txt = frappe.get_pymodule_path(app, "patches.txt")
+
+ try:
+ # Attempt to parse as ini file with pre/post patches
+ # allow_no_value: patches are not key value pairs
+ # delimiters = '\n' to avoid treating default `:` and `=` in execute as k:v delimiter
+ parser = configparser.ConfigParser(allow_no_value=True, delimiters="\n")
+ # preserve case
+ parser.optionxform = str
+ parser.read(patches_txt)
+
+ # empty file
+ if not parser.sections():
+ return []
+
+ if not patch_type:
+ return [patch for patch in parser[PatchType.pre_model_sync.value]] + \
+ [patch for patch in parser[PatchType.post_model_sync.value]]
+
+ if patch_type.value in parser.sections():
+ return [patch for patch in parser[patch_type.value]]
+ else:
+ frappe.throw(frappe._("Patch type {} not found in patches.txt").format(patch_type))
+
+ except configparser.MissingSectionHeaderError:
+ # treat as old format with each line representing a single patch
+ # backward compatbility with old patches.txt format
+ if not patch_type or patch_type == PatchType.pre_model_sync:
+ return frappe.get_file_items(patches_txt)
+
+ return []
+
+def reload_doc(args):
+ import frappe.modules
+ run_single(method = frappe.modules.reload_doc, methodargs = args)
+
+def run_single(patchmodule=None, method=None, methodargs=None, force=False):
+ from frappe import conf
+
+ # don't write txt files
+ conf.developer_mode = 0
+
+ if force or method or not executed(patchmodule):
+ return execute_patch(patchmodule, method, methodargs)
+ else:
+ return True
+
+def execute_patch(patchmodule, method=None, methodargs=None):
+ """execute the patch"""
+ block_user(True)
+
+ if patchmodule.startswith("execute:"):
+ has_patch_file = False
+ patch = patchmodule.split("execute:")[1]
+ docstring = ""
+ else:
+ has_patch_file = True
+ patch = f"{patchmodule.split()[0]}.execute"
+ _patch = frappe.get_attr(patch)
+ docstring = _patch.__doc__ or ""
+
+ if docstring:
+ docstring = "\n" + indent(dedent(docstring), "\t")
+
+ print(f"Executing {patchmodule or methodargs} in {frappe.local.site} ({frappe.db.cur_db_name}){docstring}")
+
+ start_time = time.time()
+ frappe.db.begin()
+ try:
+ if patchmodule:
+ if patchmodule.startswith("finally:"):
+ # run run patch at the end
+ frappe.flags.final_patches.append(patchmodule)
+ else:
+ if has_patch_file:
+ _patch()
+ else:
+ exec(patch, globals())
+ update_patch_log(patchmodule)
+
+ elif method:
+ method(**methodargs)
+
+ except Exception:
+ frappe.db.rollback()
+ raise
+
+ else:
+ frappe.db.commit()
+ end_time = time.time()
+ block_user(False)
+ print(f"Success: Done in {round(end_time - start_time, 3)}s")
+
+ return True
+
+def update_patch_log(patchmodule):
+ """update patch_file in patch log"""
+ frappe.get_doc({"doctype": "Patch Log", "patch": patchmodule}).insert(ignore_permissions=True)
+
+def executed(patchmodule):
+ """return True if is executed"""
+ if patchmodule.startswith('finally:'):
+ # patches are saved without the finally: tag
+ patchmodule = patchmodule.replace('finally:', '')
+ return frappe.db.get_value("Patch Log", {"patch": patchmodule})
+
+def block_user(block, msg=None):
+ """stop/start execution till patch is run"""
+ frappe.local.flags.in_patch = block
+ frappe.db.begin()
+ if not msg:
+ msg = "Patches are being executed in the system. Please try again in a few moments."
+ frappe.db.set_global('__session_status', block and 'stop' or None)
+ frappe.db.set_global('__session_status_message', block and msg or None)
+ frappe.db.commit()
+
+def check_session_stopped():
+ if frappe.db.get_global("__session_status")=='stop':
+ frappe.msgprint(frappe.db.get_global("__session_status_message"))
+ raise frappe.SessionStopped('Session Stopped')
diff --git a/pool/shard009/Python/0086910_formslogic.py b/pool/shard009/Python/0086910_formslogic.py
new file mode 100644
index 0000000000000000000000000000000000000000..424e4c069e63d34ffb5d6a94487851bc3092d433
--- /dev/null
+++ b/pool/shard009/Python/0086910_formslogic.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python
+# vim: ai ts=4 sts=4 et sw=4
+
+from models import *
+from apps.reporters.models import *
+
+
+class FormsLogic:
+ ''' This class holds method stubs and some utilities for
+ dealing with custom forms logic. Others should inherit
+ from this class and inject themselves into the forms app
+ to provide their own custom logic.
+ '''
+
+ def validate(self, *args, **kwargs):
+ ''' Perform any validation logic on the form. This should
+ return False if everything passes, otherwise a list of
+ string representations of validation errors
+ '''
+ pass
+
+
+
+ def actions(self, *args, **kwargs):
+ ''' Any custom actions that need to be defined for the form.
+ This will only get called if validation succeeds. Actions
+ may include responding to the message.
+ '''
+ pass
+
+
+ def _model_from_form(self, message, form_entry, model_class, field_lookups, foreign_key_lookups):
+ ''' Constructs an instance of a model from form data and returns it.
+ model_class is the class of the object to instantiate
+ field_lookups is a dictionary of token values to fields they map to.
+ foreign_key_lookups is a dictionary of class names to columns.
+ Any time a field to be set is a foreign key, the token will be used
+ to lookup an object whose column matches the one passed in.
+ For example, a foreign key to a location can be looked up by
+ location code.
+ In addition to this, this method will set the reporter in the model
+ if the attribute exists in both the model and the message.
+ '''
+ # instantiate the instance from the passed in class.
+ instance = model_class()
+ for token_entry in form_entry.tokenentry_set.all():
+ if field_lookups.has_key(token_entry.token.abbreviation):
+ field_name = field_lookups[token_entry.token.abbreviation]
+ # this is sillyness. this gets the model type from the metadata
+ # and if it's a foreign key then "rel" will be non null
+ foreign_key = instance._meta.get_field_by_name(field_name)[0].rel
+ if foreign_key:
+ # we can't just blindly set it, but we can get the class out
+ fk_class = foreign_key.to
+ # and from there the name
+ fk_name = fk_class._meta.object_name
+ # and from there we look it up in our table
+ field = foreign_key_lookups[fk_name]
+ # get the object instance
+ filters = { field : token_entry.data }
+ try:
+ fk_instance = fk_class.objects.get(**filters)
+ setattr(instance, field_name, fk_instance)
+ except fk_class.DoesNotExist:
+ # ah well, we tried. Is this a real error? It might be, but if this
+ # was a required field then the save() will fail
+ pass
+ else:
+ setattr(instance, field_lookups[token_entry.token.abbreviation], token_entry.data)
+ if hasattr(message, "reporter"):
+ # this won't do anything special if this isn't a django property
+ instance.reporter = message.reporter
+ return instance
+
+
+
diff --git a/pool/shard009/Python/0086912_0001_initial.py b/pool/shard009/Python/0086912_0001_initial.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fc221c24609f93096f301610cb8f3e5593f057a
--- /dev/null
+++ b/pool/shard009/Python/0086912_0001_initial.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.3 on 2017-07-15 15:53
+from __future__ import unicode_literals
+
+import datetime
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+from django.utils.timezone import utc
+import posts.models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Post',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('title', models.CharField(max_length=120)),
+ ('slug', models.SlugField(unique=True)),
+ ('image', models.ImageField(blank=True, height_field='height_field', null=True, upload_to=posts.models.upload_location, width_field='width_field')),
+ ('height_field', models.IntegerField(default=0)),
+ ('width_field', models.IntegerField(default=0)),
+ ('content', models.TextField()),
+ ('draft', models.BooleanField(default=False)),
+ ('publish', models.DateField(default=datetime.datetime(2017, 7, 15, 15, 53, 28, 629019, tzinfo=utc))),
+ ('timestamp', models.DateTimeField(auto_now_add=True)),
+ ('user', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
+ ],
+ ),
+ ]
diff --git a/pool/shard009/Python/0086914_default.py b/pool/shard009/Python/0086914_default.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cf838e88d2062cf338f9cd47cc6558c6a853766
--- /dev/null
+++ b/pool/shard009/Python/0086914_default.py
@@ -0,0 +1,32 @@
+# import the XBMC libraries so we can use the controls and functions of XBMC
+import xbmc, xbmcgui, xbmcaddon
+import os
+
+
+addon = xbmcaddon.Addon()
+addon_name = addon.getAddonInfo('name')
+addon_path = addon.getAddonInfo('path')
+
+__addon__ = xbmcaddon.Addon()
+__addonid__ = __addon__.getAddonInfo('id')
+__cwd__ = __addon__.getAddonInfo('path').decode("utf-8")
+__resource__ = xbmc.translatePath( os.path.join( __cwd__, 'resources', 'lib' ).encode("utf-8") ).decode("utf-8")
+
+sys.path.append(__resource__)
+
+
+if __name__ == '__main__':
+ import gui
+ screensaver_gui = gui.Screensaver(
+ 'alarmclock.xml',
+ addon_path,
+ 'default',
+ )
+
+ player = gui.PlayerMonitor()
+ player.setScreen(screensaver_gui)
+
+ screensaver_gui.doModal()
+ del screensaver_gui
+ del player
+ sys.modules.clear()
diff --git a/pool/shard009/Python/0086917_addon.py b/pool/shard009/Python/0086917_addon.py
new file mode 100644
index 0000000000000000000000000000000000000000..914da9771f497e9b638648c97f3c5b868056ffe0
--- /dev/null
+++ b/pool/shard009/Python/0086917_addon.py
@@ -0,0 +1,141 @@
+# -*- coding: utf-8 -*-
+"""
+ Dabdate - Korea Drama/TV Shows Streaming Service
+"""
+from xbmcswift2 import Plugin, actions
+import xbmcvfs
+import os
+import json
+
+plugin = Plugin()
+_L = plugin.get_string
+
+plugin_path = plugin.addon.getAddonInfo('path')
+lib_path = os.path.join(plugin_path, 'resources', 'lib')
+sys.path.append(lib_path)
+
+vidmap = None
+import dabdate
+vidmap_path = plugin.get_setting('vidmap_path', str)
+print vidmap_path
+if vidmap_path:
+ try:
+ f = xbmcvfs.File(vidmap_path)
+ vidmap = json.load(f)
+ f.close()
+ plugin.log.info("direct play is enabled with "+vidmap_path)
+ except:
+ vidmap = None
+
+qualcode = {
+ '' :'1', # default
+ _L(31000) :'1', # medium
+ _L(31001) :'2', # low
+ _L(31002) :'3', # high
+}
+localcode = {
+ '' :'la', # default
+ _L(31010) :'au', # austrailia
+ _L(31011) :'eu', # europe
+ _L(31012) :'sa', # south america
+ _L(31013) :'la', # US west
+ _L(31014) :'ny', # US east
+ _L(31015) :'sg', # singapore
+}
+
+CookiePath = os.path.join(plugin.storage_path, 'cookie.lwp')
+
+tPrevPage = u"[B]<<%s[/B]" % _L(30200)
+tNextPage = u"[B]%s>>[/B]" % _L(30201)
+
+@plugin.route('/', name='browse_top', options={'url':'/'})
+@plugin.route('/browse/')
+def browse_page(url):
+ quality = qualcode[ plugin.get_setting("quality", unicode) ]
+ localsrv = localcode[ plugin.get_setting("local", unicode) ]
+ direct_play = plugin.get_setting("direct_play", bool)
+ info = dabdate.parseTop( dabdate.root_url+url, quality=quality, localsrv=localsrv )
+ items = []
+ label_download = plugin.get_string(30204)
+ for item in info['video']:
+ title = item['title']
+ vidurl = item['url']
+ if direct_play and vidmap:
+ turl = dabdate.getDirectUrl(vidmap, item['title'], quality, localsrv)
+ if turl:
+ vidurl = turl
+ title = u"[I]%s[/I]"% item['title']
+ if item['free']:
+ title = u"[B]%s[/B]"% item['title']
+ items.append({
+ 'label':title,
+ 'path':plugin.url_for('play_video', url=vidurl),
+ 'thumbnail':item['thumb'],
+ 'context_menu': [
+ (label_download, actions.background(plugin.url_for('download_video', url=vidurl)))
+ ]
+ })
+ # navigation
+ if 'prevpage' in info:
+ items.append({'label':tPrevPage, 'path':plugin.url_for('browse_page', url=info['prevpage'])})
+ if 'nextpage' in info:
+ items.append({'label':tNextPage, 'path':plugin.url_for('browse_page', url=info['nextpage'])})
+ # extra
+ if url == '/':
+ items.append({'label':u"[COLOR FF0000FF]유아프로그램[/COLOR]", 'path':plugin.url_for('browse_page', url="?lang=5")})
+ #items.append({'label':u"[COLOR FF0000FF]그때를 아십니까[/COLOR]", 'path':plugin.url_for('browse_page', url="?lang=7")})
+ #items.append({'label':u"[COLOR FF0000FF]특선 다큐멘터리[/COLOR]", 'path':plugin.url_for('browse_page', url="?lang=6")})
+ morepage = True if 'page=' in url else False
+ return plugin.finish(items, update_listing=morepage)
+
+@plugin.route('/play/')
+def play_video(url):
+ if url.startswith("http://vod"):
+ info = {"title":"Play", "url":url, "useragent":dabdate.PlayerAgent, "cookie":"player_link=OK"}
+ else:
+ info = resolve_video_url(url)
+ vid_url = "{0:s}|User-Agent={1:s}&Cookie={2:s}".format(info['url'], info['useragent'], info['cookie'])
+ # play video immediately
+ plugin.play_video({'label':info['title'], 'path':vid_url, 'info_type':'video', 'is_playable':True})
+ return plugin.finish(None, succeeded=False)
+
+@plugin.route('/download/')
+def download_video(url):
+ if url.startswith("http://vod"):
+ info = {"title":"Play", "url":url}
+ else:
+ info = resolve_video_url(url)
+ wdir = plugin.get_setting('download_dir', unicode)
+ ext = '.mp4'
+ if not xbmcvfs.exists(wdir):
+ return plugin.finish(None, succeeded=False)
+ wpath = wdir + info['title']+ext
+ print 'Download path: '+wpath.encode('utf-8')
+ import urllib2
+ req = urllib2.Request(info['url'])
+ req.add_header('User-Agent', info['useragent'])
+ req.add_header('Cookie', info['cookie'])
+ plugin.notify('Downloading to '+wpath.encode('utf-8'))
+ r = urllib2.urlopen(req)
+ f = xbmcvfs.File(wpath, 'w')
+ while True:
+ buf = r.read(512*1024)
+ if len(buf) == 0:
+ break
+ f.write(buf)
+ r.close()
+ f.close()
+ plugin.notify('Download completed and saved as '+wpath.encode('utf-8'))
+ return plugin.finish(None, succeeded=True)
+
+def resolve_video_url(url):
+ userid = plugin.get_setting('id', str)
+ passwd = plugin.get_setting('pass', str)
+
+ page_url = dabdate.root_url+url
+ return dabdate.getStreamUrl( page_url, userid=userid, passwd=passwd, cookiefile=CookiePath )
+
+if __name__ == "__main__":
+ plugin.run()
+
+# vim:sw=4:sts=4:et
diff --git a/pool/shard009/Python/0086918_socketcapture.py b/pool/shard009/Python/0086918_socketcapture.py
new file mode 100644
index 0000000000000000000000000000000000000000..25fcf68f16ddc4682280db9b015ae892c5f10ffd
--- /dev/null
+++ b/pool/shard009/Python/0086918_socketcapture.py
@@ -0,0 +1,197 @@
+# Copyright 2012 James McCauley
+#
+# This file is part of POX.
+#
+# POX 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.
+#
+# POX 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 POX. If not, see .
+
+from pox.lib.addresses import *
+import pox.lib.packet as pkt
+
+from struct import pack
+import time
+
+from struct import pack
+import time
+
+class SocketWedge (object):
+ def __init__ (self, socket):
+ self._socket = socket
+
+ def send (self, string, *args, **kw):
+ r = self._socket.send(string, *args, **kw)
+ self._send_out(string, r)
+ return r
+
+ def recv (self, bufsize, *args, **kw):
+ r = self._socket.recv(bufsize, *args, **kw)
+ self._recv_out(r)
+ return r
+
+ def __getattr__ (self, n):
+ return getattr(self._socket, n)
+
+
+class PCapWriter (object):
+ def __init__ (self, outstream, socket = None, flush = False,
+ local_addrs = (None,None,None),
+ remote_addrs = (None,None,None)):
+ """
+ outstream is the stream to write the PCAP trace to.
+ Ethernet addresses have to be faked, and it can be convenient to
+ fake IP and TCP addresses as well. Thus, you can specify local_addrs
+ or remote_addrs. These are tuples of (EthAddr, IPAddr, TCPPort).
+ Any item that is None gets a default value.
+ """
+ self._out = outstream
+ self._flush = flush
+
+ if socket is not None:
+ remote = socket.getpeername()
+ local = socket.getsockname()
+ else:
+ remote = ("1.1.1.1",1)
+ local = ("0.0.0.0",0)
+
+ def create_packet (e1,e2,i1,i2,t1,t2):
+ e = pkt.ethernet(
+ src = e1,
+ dst = e2,
+ type = pkt.ethernet.IP_TYPE)
+ i = pkt.ipv4(
+ srcip = i1,
+ dstip = i2,
+ protocol = pkt.ipv4.TCP_PROTOCOL)
+ t = pkt.tcp(
+ srcport = t1,
+ dstport = t2,
+ off = 5,
+ win = 1)
+ t.ACK = True
+ i.payload = t
+ e.payload = i
+ return e
+
+ self._c_to_s = create_packet(
+ local_addrs[0] or EthAddr("\x02" + "\x00" * 5),
+ remote_addrs[0] or EthAddr("\x02" + "\x11" * 5),
+ local_addrs[1] or IPAddr(local[0]),
+ remote_addrs[1] or IPAddr(remote[0]),
+ local_addrs[2] or local[1],
+ remote_addrs[2] or remote[1],
+ )
+
+ self._s_to_c = create_packet(
+ remote_addrs[0] or EthAddr("\x02" + "\x11" * 5),
+ local_addrs[0] or EthAddr("\x02" + "\x00" * 5),
+ remote_addrs[1] or IPAddr(remote[0]),
+ local_addrs[1] or IPAddr(local[0]),
+ remote_addrs[2] or remote[1],
+ local_addrs[2] or local[1],
+ )
+
+ outstream.write(pack("IHHiIII",
+ 0xa1b2c3d4, # Magic
+ 2,4, # Version
+ time.timezone, # TZ offset
+ 0, # Accuracy of timestamps (apparently 0 is OK)
+ 0x7fffFFff, # Snaplen
+ 1 # Ethernet
+ ))
+
+ def write (self, outgoing, buf):
+ if len(buf) == 0: return
+ e = self._c_to_s if outgoing else self._s_to_c
+ e2 = self._c_to_s if not outgoing else self._s_to_c
+ l = len(buf)
+ e.payload.payload.payload = buf
+ buf = e.pack()
+
+ t = time.time()
+ ut = t - int(t)
+ t = int(t)
+ ut = int(ut * 1000000)
+ self._out.write(pack("IIII",
+ t,ut, # Timestamp
+ len(buf), # Saved size
+ len(buf), # Original size
+ ))
+
+ self._out.write(buf)
+ if self._flush: self._out.flush()
+
+ e.next.next.seq += l
+ e2.next.next.ack += l
+
+
+class CaptureSocket (SocketWedge):
+ """
+ Wraps a TCP socket and writes a faked PCAP format trace
+ """
+ def __init__ (self, socket, outstream, close = True,
+ local_addrs = (None,None,None),
+ remote_addrs = (None,None,None)):
+ """
+ socket is the socket to be wrapped.
+ outstream is the stream to write the PCAP trace to.
+ Ethernet addresses have to be faked, and it can be convenient to
+ fake IP and TCP addresses as well. Thus, you can specify local_addrs
+ or remote_addrs. These are tuples of (EthAddr, IPAddr, TCPPort).
+ Any item that is None gets a default value.
+ """
+ super(CaptureSocket, self).__init__(socket)
+ self._close = close
+ self._writer = PCapWriter(outstream, socket=socket,
+ local_addrs=local_addrs,
+ remote_addrs=remote_addrs)
+
+
+ def _recv_out (self, buf):
+ try:
+ self._writer.write(False, buf)
+ except Exception:
+ pass
+
+ def _send_out (self, buf, r):
+ try:
+ self._writer.write(True, buf[:r])
+ except Exception:
+ pass
+
+ def close (self, *args, **kw):
+ if self._close:
+ try:
+ self._writer._out.close()
+ except Exception:
+ pass
+ return self._socket.close(*args, **kw)
+
+
+if __name__ == "__main__":
+ """
+ Test with:
+ nc -v -v -l 9933
+ """
+ import socket
+ sock = socket.create_connection(("127.0.0.1",9933))
+ s = CaptureSocket(sock, file("test.pcap", "w"))
+ while True:
+ d = s.recv(1024)
+ d = d.upper()
+ import sys
+ import time
+ import random
+ time.sleep(random.random() * 1.5)
+ sys.stdout.write(d)
+ s.send(d)
+
diff --git a/pool/shard009/Python/0086922_models.py b/pool/shard009/Python/0086922_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..eef14c080fd885d88ce5788c0f9168a080ce2f28
--- /dev/null
+++ b/pool/shard009/Python/0086922_models.py
@@ -0,0 +1,97 @@
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
+from rest_framework.authtoken.models import Token
+
+
+def get_name(self):
+ return str(self.first_name) + " " + str(self.last_name)
+
+
+User.add_to_class('__str__', get_name)
+
+
+class Department(models.Model):
+ name = models.CharField(max_length=100)
+
+ class Meta:
+ db_table = u'Department'
+ ordering = ['name']
+
+ def __str__(self):
+ return self.name
+
+
+class Client(models.Model):
+ first_name = models.CharField(max_length=100)
+ last_name = models.CharField(max_length=100)
+ email = models.CharField(max_length=100)
+ department = models.ForeignKey(Department,
+ on_delete=models.CASCADE)
+
+ class Meta:
+ db_table = u'Client'
+ ordering = ['last_name']
+
+ def __str__(self):
+ return str(self.last_name) + ", " + str(self.first_name)
+
+
+class Type(models.Model):
+ name = models.CharField(max_length=100)
+
+ class Meta:
+ db_table = u'Type'
+ ordering = ['name']
+
+ def __str__(self):
+ return self.name
+
+
+class Semester(models.Model):
+ name = models.CharField(max_length=100)
+
+ class Meta:
+ db_table = u'Semester'
+ ordering = ['name']
+
+ def __str__(self):
+ return self.name
+
+
+class CurrentSemester(models.Model):
+ semester = models.ForeignKey(Semester, on_delete=models.CASCADE)
+
+ class Meta:
+ db_table = u'CurrentSemester'
+
+ def __str__(self):
+ return str(self.semester)
+
+
+class Project(models.Model):
+ title = models.CharField(max_length=100)
+ description = models.CharField(max_length=500)
+ date = models.DateField(editable=False)
+ type = models.ForeignKey(Type, on_delete=models.CASCADE)
+ walk_in = models.BooleanField(default=False)
+ client = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True)
+ users = models.ManyToManyField(User)
+ semester = models.ForeignKey(Semester, on_delete=models.CASCADE, blank=True, null=True)
+ hours = models.PositiveIntegerField(default=0)
+ completed = models.BooleanField(default=False)
+
+ class Meta:
+ db_table = u'Project'
+ ordering = ['date']
+
+ def __str__(self):
+ return self.title
+
+
+@receiver(post_save, sender=settings.AUTH_USER_MODEL)
+def create_auth_token(sender, instance=None, created=False, **kwargs):
+ if created:
+ Token.objects.create(user=instance)
diff --git a/pool/shard009/Python/0086923_product_manufacturer.py b/pool/shard009/Python/0086923_product_manufacturer.py
new file mode 100644
index 0000000000000000000000000000000000000000..93f4a6f1a8e5e095b2f3f53acb37a71af6910ed1
--- /dev/null
+++ b/pool/shard009/Python/0086923_product_manufacturer.py
@@ -0,0 +1,43 @@
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (C) 2004-2009 Tiny SPRL ().
+#
+# 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 osv import fields, osv
+
+class product_product(osv.osv):
+ _inherit = 'product.product'
+ _columns = {
+ 'manufacturer' : fields.many2one('res.partner', 'Manufacturer'),
+ 'manufacturer_pname' : fields.char('Manufacturer Product Name', size=64),
+ 'manufacturer_pref' : fields.char('Manufacturer Product Code', size=64),
+ 'attribute_ids': fields.one2many('product.manufacturer.attribute', 'product_id', 'Attributes'),
+ }
+product_product()
+
+class product_attribute(osv.osv):
+ _name = "product.manufacturer.attribute"
+ _description = "Product attributes"
+ _columns = {
+ 'name' : fields.char('Attribute', size=64, required=True),
+ 'value' : fields.char('Value', size=64),
+ 'product_id': fields.many2one('product.product', 'Product', ondelete='cascade'),
+ }
+product_attribute()
+
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
\ No newline at end of file
diff --git a/pool/shard009/Python/0086926_optimization_analysis.py b/pool/shard009/Python/0086926_optimization_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d3651809898cdc6cac8bc5684902d2807161b65
--- /dev/null
+++ b/pool/shard009/Python/0086926_optimization_analysis.py
@@ -0,0 +1,68 @@
+import numpy as np
+import pycqed.analysis_v2.base_analysis as ba
+
+
+class OptimizationAnalysis(ba.BaseDataAnalysis):
+ def __init__(self, t_start: str=None, t_stop: str=None,
+ label: str='', data_file_path: str=None,
+ options_dict: dict=None, extract_only: bool=False,
+ do_fitting: bool=True, auto=True):
+ super().__init__(t_start=t_start, t_stop=t_stop,
+ label=label,
+ data_file_path=data_file_path,
+ options_dict=options_dict,
+ extract_only=extract_only, do_fitting=do_fitting)
+ # self.single_timestamp = False
+ self.params_dict = {'xlabel': 'sweep_name',
+ 'xunit': 'sweep_unit',
+ 'xvals': 'sweep_points',
+ 'measurementstring': 'measurementstring',
+ 'value_names': 'value_names',
+ 'value_units': 'value_units',
+ 'measured_values': 'measured_values'}
+
+
+
+ self.numeric_params = []
+ if auto:
+ self.run_analysis()
+
+
+ def prepare_plots(self):
+ # assumes that value names are unique in an experiment
+
+
+ for i, val_name in enumerate(self.raw_data_dict['value_names'][0]):
+ yvals = self.raw_data_dict['measured_data'][val_name][0]
+
+ self.plot_dicts['{}_vs_iteration'.format(val_name)] = {
+ 'plotfn': self.plot_line,
+ 'xvals': np.arange(len(yvals)),
+ 'xlabel': 'Iteration',
+ 'xunit': '#',
+ 'yvals': yvals,
+ 'ylabel': val_name,
+ 'yunit': self.raw_data_dict['value_units'][0][i]}
+
+ legend_title = 'timestamp'
+
+ # for i, val_name in enumerate(self.raw_data_dict['value_names'][0]):
+
+
+ # self.plot_dicts[val_name] = {
+ # 'plotfn': self.plot_line,
+ # 'xvals': xvals,
+ # 'xlabel': self.raw_data_dict['xlabel'][0],
+ # 'xunit': self.raw_data_dict['xunit'][0][0],
+ # 'yvals': yvals,
+ # 'ylabel': val_name,
+ # 'yrange': self.options_dict.get('yrange', None),
+ # 'xrange': self.options_dict.get('xrange', None),
+ # 'yunit': self.raw_data_dict['value_units'][0][i],
+ # 'setlabel': setlabel,
+ # 'legend_title': legend_title,
+ # 'title': (self.raw_data_dict['timestamps'][0]+' - ' +
+ # self.raw_data_dict['timestamps'][-1] + '\n' +
+ # self.raw_data_dict['measurementstring'][0]),
+ # 'do_legend': do_legend,
+ # 'legend_pos': 'upper right'}
\ No newline at end of file
diff --git a/pool/shard009/Python/0086928_crr_operation_results_operations.py b/pool/shard009/Python/0086928_crr_operation_results_operations.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bad83cac11e1e26d4f9cd6fc25474af43c9fc10
--- /dev/null
+++ b/pool/shard009/Python/0086928_crr_operation_results_operations.py
@@ -0,0 +1,130 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) AutoRest Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import functools
+from typing import Any, Callable, Dict, Generic, Optional, TypeVar
+import warnings
+
+from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
+from azure.core.pipeline import PipelineResponse
+from azure.core.pipeline.transport import HttpResponse
+from azure.core.rest import HttpRequest
+from azure.core.tracing.decorator import distributed_trace
+from azure.mgmt.core.exceptions import ARMErrorFormat
+from msrest import Serializer
+
+from .. import models as _models
+from .._vendor import _convert_request, _format_url_section
+T = TypeVar('T')
+ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
+
+_SERIALIZER = Serializer()
+_SERIALIZER.client_side_validation = False
+
+def build_get_request(
+ azure_region: str,
+ subscription_id: str,
+ operation_id: str,
+ **kwargs: Any
+) -> HttpRequest:
+ api_version = "2021-11-15"
+ accept = "application/json"
+ # Construct URL
+ url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupCrrOperationResults/{operationId}')
+ path_format_arguments = {
+ "azureRegion": _SERIALIZER.url("azure_region", azure_region, 'str'),
+ "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'),
+ "operationId": _SERIALIZER.url("operation_id", operation_id, 'str'),
+ }
+
+ url = _format_url_section(url, **path_format_arguments)
+
+ # Construct parameters
+ query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
+ query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
+
+ # Construct headers
+ header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
+ header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
+
+ return HttpRequest(
+ method="GET",
+ url=url,
+ params=query_parameters,
+ headers=header_parameters,
+ **kwargs
+ )
+
+class CrrOperationResultsOperations(object):
+ """CrrOperationResultsOperations operations.
+
+ You should not instantiate this class directly. Instead, you should create a Client instance that
+ instantiates it for you and attaches it as an attribute.
+
+ :ivar models: Alias to model classes used in this operation group.
+ :type models: ~azure.mgmt.recoveryservicesbackup.passivestamp.models
+ :param client: Client for service requests.
+ :param config: Configuration of service client.
+ :param serializer: An object model serializer.
+ :param deserializer: An object model deserializer.
+ """
+
+ models = _models
+
+ def __init__(self, client, config, serializer, deserializer):
+ self._client = client
+ self._serialize = serializer
+ self._deserialize = deserializer
+ self._config = config
+
+ @distributed_trace
+ def get(
+ self,
+ azure_region: str,
+ operation_id: str,
+ **kwargs: Any
+ ) -> None:
+ """get.
+
+ :param azure_region: Azure region to hit Api.
+ :type azure_region: str
+ :param operation_id:
+ :type operation_id: str
+ :keyword callable cls: A custom type or function that will be passed the direct response
+ :return: None, or the result of cls(response)
+ :rtype: None
+ :raises: ~azure.core.exceptions.HttpResponseError
+ """
+ cls = kwargs.pop('cls', None) # type: ClsType[None]
+ error_map = {
+ 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
+ }
+ error_map.update(kwargs.pop('error_map', {}))
+
+
+ request = build_get_request(
+ azure_region=azure_region,
+ subscription_id=self._config.subscription_id,
+ operation_id=operation_id,
+ template_url=self.get.metadata['url'],
+ )
+ request = _convert_request(request)
+ request.url = self._client.format_url(request.url)
+
+ pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
+ response = pipeline_response.http_response
+
+ if response.status_code not in [200, 202]:
+ map_error(status_code=response.status_code, response=response, error_map=error_map)
+ error = self._deserialize.failsafe_deserialize(_models.NewErrorResponse, pipeline_response)
+ raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
+
+ if cls:
+ return cls(pipeline_response, None, {})
+
+ get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupCrrOperationResults/{operationId}'} # type: ignore
+
diff --git a/pool/shard009/Python/0086930_manage_product_type.py b/pool/shard009/Python/0086930_manage_product_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..59b6e46514b554a4cbcc5f2be456e8f49263f3d3
--- /dev/null
+++ b/pool/shard009/Python/0086930_manage_product_type.py
@@ -0,0 +1,125 @@
+# manage the product type table
+# use the SQLite3 and Python 3.5
+
+# import
+import sqlite3
+
+def query(db_name, sql, data):
+ with sqlite3.connect(db_name) as db:
+ cursor = db.cursor()
+ cursor.execute("PRAGMA Foreign_Keys = ON")
+ cursor.execute(sql, data)
+ result = cursor.fetchall()
+ db.commit()
+ return result
+
+def show_all_data(db_name, table_name):
+ "show all the data of table from db"
+ sql = "SELECT * FROM {0}".format(table_name)
+ return query(db_name, sql, ())
+
+def insert_data(db_name, table_name, description):
+ "insert new data"
+ sql = """
+ INSERT INTO {0}(Description)
+ VALUES (?)
+ """.format(table_name)
+ query(db_name, sql,(description,))
+
+def update_data(db_name, table_name, producttypeid, description):
+ "update the product"
+ sql = """
+ UPDATE {0} SET Description=?
+ WHERE ProductTypeID=?
+ """.format(table_name)
+ query(db_name, sql, (description, producttypeid,))
+
+def delete_data(db_name, table_name, producttypeid):
+ "delete the product from the table"
+ sql = "DELETE FROM {0} WHERE ProductTypeID=?".format(table_name)
+ query(db_name, sql, (producttypeid, ))
+
+def print_table(result):
+ "show the data in a table"
+ print("""
+
+ |{0:^5s}|{1:^15s}|
+ """.format("ID",
+ "Description"))
+ for entry in result:
+ producttypeid, description = entry
+ print("""
+ {0:^5d} {1:^15s}
+ """.format(producttypeid,
+ description))
+
+def ask_question(question, legal):
+ "ask the user a question and return the result"
+ while 1:
+ response = int(input(question))
+ if response in legal:
+ return response
+ print("illegal input, please input data within", legal, "\n")
+
+def print_menu():
+ "print the manage menu"
+ print("""
+
+ Manage The Product Type Table:
+
+ 1. show all product type
+ 2. insert new data into product type table
+ 3. update the current product
+ 4. delete order from repository
+ 5. return to parent
+
+ """)
+
+def manage_product_type():
+
+ legal = (1, 2, 3, 4, 5)
+ question = "\tOperation(1,2,3,4,5): "
+
+ db_name = "coffee_shop.db"
+ table_name = "ProductType"
+
+ while 1:
+ print_menu()
+ response = ask_question(question, legal)
+
+ if response == 1:
+ result = show_all_data(db_name, table_name)
+ print_table(result)
+
+ elif response == 2:
+ print("\tAdd new product type: ")
+ description = input("\t\tDescription: ")
+ insert_data(db_name,
+ table_name,
+ description)
+
+ elif response == 3:
+ result = show_all_data(db_name, table_name)
+ print_table(result)
+ producttypeid = int(input("\tinput the product type ID: "))
+ print("\n\tUpdate the product type information: ")
+ description = input("\t\tDescription: ")
+ update_data(db_name,
+ table_name,
+ producttypeid,
+ description)
+
+ elif response == 4:
+ result = show_all_data(db_name, table_name)
+ print_table(result)
+ producttypeid = int(input("\n\tinput the product type id to delete it: "))
+ delete_data(db_name, table_name, producttypeid)
+
+ elif response == 5:
+ break
+
+ else:
+ pass
+
+if __name__ == "__main__":
+ manage_order()
diff --git a/pool/shard009/Python/0086933_metric_specification.py b/pool/shard009/Python/0086933_metric_specification.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6469d454430d6187a445098f5363841414d5ec0
--- /dev/null
+++ b/pool/shard009/Python/0086933_metric_specification.py
@@ -0,0 +1,82 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for
+# license information.
+#
+# Code generated by Microsoft (R) AutoRest Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is
+# regenerated.
+# --------------------------------------------------------------------------
+
+from msrest.serialization import Model
+
+
+class MetricSpecification(Model):
+ """Description of metrics specification.
+
+ :param name: The name of the metric.
+ :type name: str
+ :param display_name: The display name of the metric.
+ :type display_name: str
+ :param display_description: The description of the metric.
+ :type display_description: str
+ :param unit: Units the metric to be displayed in.
+ :type unit: str
+ :param aggregation_type: The aggregation type.
+ :type aggregation_type: str
+ :param availabilities: List of availability.
+ :type availabilities:
+ list[~azure.mgmt.network.v2017_10_01.models.Availability]
+ :param enable_regional_mdm_account: Whether regional MDM account enabled.
+ :type enable_regional_mdm_account: bool
+ :param fill_gap_with_zero: Whether gaps would be filled with zeros.
+ :type fill_gap_with_zero: bool
+ :param metric_filter_pattern: Pattern for the filter of the metric.
+ :type metric_filter_pattern: str
+ :param dimensions: List of dimensions.
+ :type dimensions: list[~azure.mgmt.network.v2017_10_01.models.Dimension]
+ :param is_internal: Whether the metric is internal.
+ :type is_internal: bool
+ :param source_mdm_account: The source MDM account.
+ :type source_mdm_account: str
+ :param source_mdm_namespace: The source MDM namespace.
+ :type source_mdm_namespace: str
+ :param resource_id_dimension_name_override: The resource Id dimension name
+ override.
+ :type resource_id_dimension_name_override: str
+ """
+
+ _attribute_map = {
+ 'name': {'key': 'name', 'type': 'str'},
+ 'display_name': {'key': 'displayName', 'type': 'str'},
+ 'display_description': {'key': 'displayDescription', 'type': 'str'},
+ 'unit': {'key': 'unit', 'type': 'str'},
+ 'aggregation_type': {'key': 'aggregationType', 'type': 'str'},
+ 'availabilities': {'key': 'availabilities', 'type': '[Availability]'},
+ 'enable_regional_mdm_account': {'key': 'enableRegionalMdmAccount', 'type': 'bool'},
+ 'fill_gap_with_zero': {'key': 'fillGapWithZero', 'type': 'bool'},
+ 'metric_filter_pattern': {'key': 'metricFilterPattern', 'type': 'str'},
+ 'dimensions': {'key': 'dimensions', 'type': '[Dimension]'},
+ 'is_internal': {'key': 'isInternal', 'type': 'bool'},
+ 'source_mdm_account': {'key': 'sourceMdmAccount', 'type': 'str'},
+ 'source_mdm_namespace': {'key': 'sourceMdmNamespace', 'type': 'str'},
+ 'resource_id_dimension_name_override': {'key': 'resourceIdDimensionNameOverride', 'type': 'str'},
+ }
+
+ def __init__(self, **kwargs):
+ super(MetricSpecification, self).__init__(**kwargs)
+ self.name = kwargs.get('name', None)
+ self.display_name = kwargs.get('display_name', None)
+ self.display_description = kwargs.get('display_description', None)
+ self.unit = kwargs.get('unit', None)
+ self.aggregation_type = kwargs.get('aggregation_type', None)
+ self.availabilities = kwargs.get('availabilities', None)
+ self.enable_regional_mdm_account = kwargs.get('enable_regional_mdm_account', None)
+ self.fill_gap_with_zero = kwargs.get('fill_gap_with_zero', None)
+ self.metric_filter_pattern = kwargs.get('metric_filter_pattern', None)
+ self.dimensions = kwargs.get('dimensions', None)
+ self.is_internal = kwargs.get('is_internal', None)
+ self.source_mdm_account = kwargs.get('source_mdm_account', None)
+ self.source_mdm_namespace = kwargs.get('source_mdm_namespace', None)
+ self.resource_id_dimension_name_override = kwargs.get('resource_id_dimension_name_override', None)
diff --git a/pool/shard009/Python/0086934_init__.py b/pool/shard009/Python/0086934_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..847b4da768c18019e84d44cc6c611279ab5835dc
--- /dev/null
+++ b/pool/shard009/Python/0086934_init__.py
@@ -0,0 +1,24 @@
+# coding: utf-8
+
+from collections import defaultdict
+
+
+class Node:
+ def __init__(self, value):
+ self.value = value
+ self.left = None
+ self.right = None
+
+
+class Graph:
+ def __init__(self):
+ self.edge = defaultdict(list)
+
+ def __getitem__(self, k):
+ return self.edge[k]
+
+ def add_edge(self, from_node, to_node):
+ self.edge[from_node].append(to_node)
+
+ def remove_edge(self, from_node, to_node):
+ self.edge[from_node].remove(to_node)
diff --git a/pool/shard009/Python/0086936_middleware.py b/pool/shard009/Python/0086936_middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..7338e7daf094728dbfc36ed7d5341265e73b371c
--- /dev/null
+++ b/pool/shard009/Python/0086936_middleware.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+from excalibur.core import PluginsRunner
+from excalibur.exceptions import ConfigurationLoaderError, ExcaliburError
+import logging
+from .decorators import is_excalibur
+from .models import ExcaliburConf
+from .utils import ExcaliburAttack
+from .exceptions import excalibur_exception_handler
+from django.core.exceptions import ObjectDoesNotExist
+
+logger = logging.getLogger(__name__)
+
+
+class ExcaliburMiddleware(object):
+
+ """ The excalibur middleware """
+
+ @is_excalibur
+ def process_response(self, request, response):
+ """
+ use excalibur when optional "project" and "source" params
+ are in the url
+ """
+ try:
+ # get all params for query
+ excalibur = ExcaliburAttack(request, response)
+ # get user
+ user = excalibur.get_request_user()
+
+ if user:
+ try:
+ excconf = ExcaliburConf()
+ except (AttributeError, ObjectDoesNotExist) as e:
+ raise ConfigurationLoaderError(str(e))
+
+ # run plugins
+ plugin_runner = PluginsRunner(
+ excconf.acl_conf.configuration,
+ excconf.sources_conf.configuration,
+ excconf.ressource_conf.configuration,
+ excconf.plugins_module,
+ raw_yaml_content=True,
+ check_signature=False if user.is_superuser else True
+ )
+
+ newdata, errors = excalibur.make_and_run_query(plugin_runner)
+ if not errors:
+ response = excalibur.aggregate_data(newdata)
+ else:
+ response = excalibur.manage_errors(errors)
+
+ except ExcaliburError as e:
+ logger.error(e.message)
+ response = excalibur_exception_handler(e, response)
+
+ return response
diff --git a/pool/shard009/Python/0086942_sync.py b/pool/shard009/Python/0086942_sync.py
new file mode 100644
index 0000000000000000000000000000000000000000..4240919719f2d85cb065667ef104cb0ef0ff9cee
--- /dev/null
+++ b/pool/shard009/Python/0086942_sync.py
@@ -0,0 +1,190 @@
+from trakt.mapper.core.base import Mapper
+
+import logging
+
+log = logging.getLogger(__name__)
+
+
+class SyncMapper(Mapper):
+ @classmethod
+ def process(cls, client, store, items, media, **kwargs):
+ if not media:
+ return ValueError()
+
+ func = getattr(cls, media)
+
+ if not func:
+ raise ValueError('Unknown media type: %r', media)
+
+ return func(client, store, items, **kwargs)
+
+ #
+ # Movie
+ #
+
+ @classmethod
+ def movies(cls, client, store, items, **kwargs):
+ return cls.map_items(client, store, items, cls.movie, **kwargs)
+
+ @classmethod
+ def movie(cls, client, store, item, **kwargs):
+ movie = cls.map_item(client, store, item, 'movie', **kwargs)
+
+ # Update with root info
+ if 'movie' in item:
+ movie._update(item)
+
+ return movie
+
+ #
+ # Show
+ #
+
+ @classmethod
+ def shows(cls, client, store, items, **kwargs):
+ return cls.map_items(client, store, items, cls.show, **kwargs)
+
+ @classmethod
+ def show(cls, client, store, item, **kwargs):
+ show = cls.map_item(client, store, item, 'show', **kwargs)
+
+ # Update with root info
+ if 'show' in item:
+ show._update(item)
+
+ # Process any episodes in the item
+ for i_season in item.get('seasons', []):
+ season_num = i_season.get('number')
+
+ season = cls.show_season(client, show, season_num, **kwargs)
+
+ for i_episode in i_season.get('episodes', []):
+ episode_num = i_episode.get('number')
+
+ cls.show_episode(client, season, episode_num, i_episode, **kwargs)
+
+ return show
+
+ @classmethod
+ def show_season(cls, client, show, season_num, item=None, **kwargs):
+ season = cls.map_item(client, show.seasons, item, 'season', key=season_num, parent=show, **kwargs)
+ season.show = show
+
+ # Update with root info
+ if item and 'season' in item:
+ season._update(item)
+
+ return season
+
+ @classmethod
+ def show_episode(cls, client, season, episode_num, item=None, **kwargs):
+ episode = cls.map_item(client, season.episodes, item, 'episode', key=episode_num, parent=season, **kwargs)
+ episode.show = season.show
+ episode.season = season
+
+ # Update with root info
+ if item and 'episode' in item:
+ episode._update(item)
+
+ return episode
+
+ #
+ # Season
+ #
+
+ @classmethod
+ def seasons(cls, client, store, items, **kwargs):
+ return cls.map_items(client, store, items, cls.season, **kwargs)
+
+ @classmethod
+ def season(cls, client, store, item, **kwargs):
+ i_season = item.get('season', {})
+
+ season_num = i_season.get('number')
+
+ # Build `show`
+ show = cls.show(client, store, item['show'])
+
+ if show is None:
+ # Unable to create show
+ return None
+
+ # Build `season`
+ season = cls.show_season(client, show, season_num, item, **kwargs)
+
+ return season
+
+ #
+ # Episode
+ #
+
+ @classmethod
+ def episodes(cls, client, store, items, **kwargs):
+ return cls.map_items(client, store, items, cls.episode, **kwargs)
+
+ @classmethod
+ def episode(cls, client, store, item, **kwargs):
+ i_episode = item.get('episode', {})
+
+ season_num = i_episode.get('season')
+ episode_num = i_episode.get('number')
+
+ # Build `show`
+ show = cls.show(client, store, item['show'])
+
+ if show is None:
+ # Unable to create show
+ return None
+
+ # Build `season`
+ season = cls.show_season(client, show, season_num, **kwargs)
+
+ # Build `episode`
+ episode = cls.show_episode(client, season, episode_num, item, **kwargs)
+
+ return episode
+
+ #
+ # Helpers
+ #
+
+ @classmethod
+ def map_items(cls, client, store, items, func, **kwargs):
+ if store is None:
+ store = {}
+
+ for item in items:
+ result = func(client, store, item, **kwargs)
+
+ if result is None:
+ log.warn('Unable to map item: %s', item)
+
+ return store
+
+ @classmethod
+ def map_item(cls, client, store, item, media, key=None, parent=None, **kwargs):
+ if item and media in item:
+ i_data = item[media]
+ else:
+ i_data = item
+
+ pk, keys = cls.get_ids(media, i_data, parent=parent)
+
+ if key is not None:
+ pk = key
+
+ if not keys:
+ keys = [pk]
+
+ if pk is None:
+ # Item has no keys
+ return None
+
+ if pk not in store:
+ # Create new item
+ store[pk] = cls.construct(client, media, i_data, keys, **kwargs)
+ else:
+ # Update existing item
+ store[pk]._update(i_data, **kwargs)
+
+ return store[pk]
diff --git a/pool/shard009/Python/0086946_extractParameters.py b/pool/shard009/Python/0086946_extractParameters.py
new file mode 100644
index 0000000000000000000000000000000000000000..2011dca8c54e708f9bc69b3c3a1e122116980977
--- /dev/null
+++ b/pool/shard009/Python/0086946_extractParameters.py
@@ -0,0 +1,111 @@
+import sys
+
+"""
+ Extracts global parameters from a DD4hep model
+ into a python file with a dictionary.
+
+ The parameters have to be spefified in a simple text file (one per line)
+
+ @author F.Gaede, CERN/DESY
+ @version 1.0
+
+"""
+#-----------------------------------------------
+
+#------------------------------------------------
+# read the compact xml file from the command line
+#
+try:
+ compactFile = sys.argv[1]
+ paramFile = sys.argv[2]
+ dictFile = sys.argv[3]
+except IndexError:
+ print " usage: python extractParameters.py compact.xml param_names.txt pyDict.py"
+ print
+ sys.exit(1)
+
+#-----------------------------------------------
+
+import os, time, DDG4
+from DDG4 import OutputLevel as Output
+from SystemOfUnits import *
+
+#-----------------------------------------------
+
+def run():
+
+ kernel = DDG4.Kernel()
+
+ try:
+ install_dir = os.environ['DD4hepINSTALL']
+
+ except (KeyError):
+ print " please set the environment variable DD4hepINSTALL "
+ print " to your DD4hep installation path ! "
+ exit(1)
+
+ kernel.loadGeometry("file:"+ compactFile )
+ lcdd = kernel.detectorDescription()
+ DDG4.importConstants( lcdd )
+
+ #--------
+
+ inf = open( paramFile , 'r' )
+ outf = open( dictFile , 'w' )
+
+ names = readNames( inf )
+
+ writeDictionary( names, outf )
+
+ inf.close()
+ outf.close()
+
+
+#-----------------------------------------------
+
+def readNames( inf ):
+
+ """
+ read ascii file with parameter names
+ """
+ names = []
+
+ for line in inf:
+ cols = line.split()
+ for n in cols:
+ names.append( n )
+
+ return names
+#-----------------------------------------------
+
+
+def writeDictionary( names, of ):
+
+ of.write( '""" \n' )
+ of.write( ' python dictionary with parameters extracted from: ' + compactFile + '\n' )
+ of.write( '""" '+ '\n')
+ of.write( 'values={}'+ '\n')
+
+ for n in names:
+ of.write( 'values["'+n+'"] = ' + str( getattr( DDG4, n ) ) + '\n')
+
+#-----------------------------------------------
+
+
+def printEnvelopeParameters( det ):
+
+ print " ========== ", det , " ================== "
+ for p in dict[ det ]:
+ print " ", p , getattr( DDG4, p )
+
+
+#-----------------------------------------------
+
+if __name__ == "__main__":
+
+ run()
+
+
+
+
+
diff --git a/pool/shard009/Python/0086950_bootstrap_test.py b/pool/shard009/Python/0086950_bootstrap_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3e1abf3e14351af8fd8ca5eaa055be0e125e78b
--- /dev/null
+++ b/pool/shard009/Python/0086950_bootstrap_test.py
@@ -0,0 +1,86 @@
+from unittest import TestCase
+
+import mock
+
+from trading_system import consts
+from trading_system.systems.trailing_orders.factory import TrailingOrdersFactory
+
+
+class ManualInputBootStrapTestCase(TestCase):
+ def setUp(self):
+ self._setup_reversal(1)
+ self._setup_stop_loss(2)
+ self._setup_operational_cost(1)
+ self._setup_profit(1)
+
+ def test_it_setup_buy_operation(self):
+ self._setup_next_operation(consts.OrderSide.BUY)
+ self._setup_start_value(100)
+ bootstrap = TrailingOrdersFactory().make_input_bootstrap()
+ initial_setup = bootstrap.get_initial_setup()
+ self.assertEqual(initial_setup.stop_value, 104.06)
+
+ def test_it_setup_sell_operation(self):
+ self._setup_next_operation(consts.OrderSide.SELL)
+ self._setup_stop_value(100)
+ bootstrap = TrailingOrdersFactory().make_input_bootstrap()
+ initial_setup = bootstrap.get_initial_setup()
+ self.assertEqual(initial_setup.start_value, 96.05)
+
+ def _setup_next_operation(self, next_operation):
+ self.next_operation = mock.MagicMock(return_value=next_operation)
+ next_operation_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_next_operation',
+ self.next_operation
+ )
+ self.addCleanup(next_operation_patcher.stop)
+ next_operation_patcher.start()
+
+ def _setup_start_value(self, value):
+ self.start_value = mock.MagicMock(return_value=value)
+ start_value_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_start_value', self.start_value
+ )
+ self.addCleanup(start_value_patcher.stop)
+ start_value_patcher.start()
+
+ def _setup_stop_value(self, value):
+ self.stop_value = mock.MagicMock(return_value=value)
+ stop_value_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_stop_value', self.stop_value
+ )
+ self.addCleanup(stop_value_patcher.stop)
+ stop_value_patcher.start()
+
+ def _setup_reversal(self, value):
+ self.reversal = mock.MagicMock(return_value=value)
+ reversal_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_trend_reversal', self.reversal
+ )
+ self.addCleanup(reversal_patcher.stop)
+ reversal_patcher.start()
+
+ def _setup_stop_loss(self, value):
+ self.stop_loss = mock.MagicMock(return_value=value)
+ stop_loss_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_stop_loss', self.stop_loss
+ )
+ self.addCleanup(stop_loss_patcher.stop)
+ stop_loss_patcher.start()
+
+ def _setup_operational_cost(self, value):
+ self.operational_cost = mock.MagicMock(return_value=value)
+ operational_cost_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_operational_cost',
+ self.operational_cost
+ )
+ self.addCleanup(operational_cost_patcher.stop)
+ operational_cost_patcher.start()
+
+ def _setup_profit(self, value):
+ self.profit = mock.MagicMock(return_value=value)
+ profit_patcher = mock.patch(
+ 'trading_system.systems.trailing_orders.bootstrap.ManualInputBootstrap._get_profit', self.profit
+ )
+ self.addCleanup(profit_patcher.stop)
+ profit_patcher.start()
diff --git a/pool/shard009/Python/0086953_callback-grid.py b/pool/shard009/Python/0086953_callback-grid.py
new file mode 100644
index 0000000000000000000000000000000000000000..34a6598066469d5861724c6e5204bb1b28e9c6b4
--- /dev/null
+++ b/pool/shard009/Python/0086953_callback-grid.py
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+import tkinter as tk
+
+
+class Board(tk.Tk):
+ def __init__(self, parent=None):
+ tk.Tk.__init__(self,parent)
+ self.rows = 5
+ self.columns = 5
+ self.init_board()
+
+ def init_board(self):
+ for i in range(self.rows):
+ for j in range(self.columns):
+ # cmd = lambda: self.button_callback(i, j)
+ cmd = lambda y=i, x=j: self.button_callback(x, y)
+ b = tk.Button(self, text=str(" "), command=cmd)
+ b.grid(row=i, column=j)
+
+ def button_callback(self, row, col):
+ print(str(row) + " " + str(col))
+
+
+if __name__ == '__main__':
+ Board().mainloop()
diff --git a/pool/shard009/Python/0086955_climate.py b/pool/shard009/Python/0086955_climate.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e9bb86d8fd5e1f891db9b34d869966fd9114057
--- /dev/null
+++ b/pool/shard009/Python/0086955_climate.py
@@ -0,0 +1,199 @@
+"""Climate platform that offers a climate device for the TFIAC protocol."""
+from concurrent import futures
+from datetime import timedelta
+import logging
+
+from pytfiac import Tfiac
+import voluptuous as vol
+
+from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
+from homeassistant.components.climate.const import (
+ FAN_AUTO,
+ FAN_HIGH,
+ FAN_LOW,
+ FAN_MEDIUM,
+ HVAC_MODE_AUTO,
+ HVAC_MODE_COOL,
+ HVAC_MODE_DRY,
+ HVAC_MODE_FAN_ONLY,
+ HVAC_MODE_HEAT,
+ HVAC_MODE_OFF,
+ SUPPORT_FAN_MODE,
+ SUPPORT_SWING_MODE,
+ SUPPORT_TARGET_TEMPERATURE,
+ SWING_BOTH,
+ SWING_HORIZONTAL,
+ SWING_OFF,
+ SWING_VERTICAL,
+)
+from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, TEMP_FAHRENHEIT
+import homeassistant.helpers.config_validation as cv
+
+SCAN_INTERVAL = timedelta(seconds=60)
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string})
+
+_LOGGER = logging.getLogger(__name__)
+
+MIN_TEMP = 61
+MAX_TEMP = 88
+
+HVAC_MAP = {
+ HVAC_MODE_HEAT: "heat",
+ HVAC_MODE_AUTO: "selfFeel",
+ HVAC_MODE_DRY: "dehumi",
+ HVAC_MODE_FAN_ONLY: "fan",
+ HVAC_MODE_COOL: "cool",
+ HVAC_MODE_OFF: "off",
+}
+
+HVAC_MAP_REV = {v: k for k, v in HVAC_MAP.items()}
+
+SUPPORT_FAN = [FAN_AUTO, FAN_HIGH, FAN_MEDIUM, FAN_LOW]
+SUPPORT_SWING = [SWING_OFF, SWING_HORIZONTAL, SWING_VERTICAL, SWING_BOTH]
+
+SUPPORT_FLAGS = SUPPORT_FAN_MODE | SUPPORT_SWING_MODE | SUPPORT_TARGET_TEMPERATURE
+
+CURR_TEMP = "current_temp"
+TARGET_TEMP = "target_temp"
+OPERATION_MODE = "operation"
+FAN_MODE = "fan_mode"
+SWING_MODE = "swing_mode"
+ON_MODE = "is_on"
+
+
+async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
+ """Set up the TFIAC climate device."""
+ tfiac_client = Tfiac(config[CONF_HOST])
+ try:
+ await tfiac_client.update()
+ except futures.TimeoutError:
+ _LOGGER.error("Unable to connect to %s", config[CONF_HOST])
+ return
+ async_add_devices([TfiacClimate(hass, tfiac_client)])
+
+
+class TfiacClimate(ClimateEntity):
+ """TFIAC class."""
+
+ def __init__(self, hass, client):
+ """Init class."""
+ self._client = client
+ self._available = True
+
+ @property
+ def available(self):
+ """Return if the device is available."""
+ return self._available
+
+ async def async_update(self):
+ """Update status via socket polling."""
+ try:
+ await self._client.update()
+ self._available = True
+ except futures.TimeoutError:
+ self._available = False
+
+ @property
+ def supported_features(self):
+ """Return the list of supported features."""
+ return SUPPORT_FLAGS
+
+ @property
+ def min_temp(self):
+ """Return the minimum temperature."""
+ return MIN_TEMP
+
+ @property
+ def max_temp(self):
+ """Return the maximum temperature."""
+ return MAX_TEMP
+
+ @property
+ def name(self):
+ """Return the name of the climate device."""
+ return self._client.name
+
+ @property
+ def target_temperature(self):
+ """Return the temperature we try to reach."""
+ return self._client.status["target_temp"]
+
+ @property
+ def temperature_unit(self):
+ """Return the unit of measurement."""
+ return TEMP_FAHRENHEIT
+
+ @property
+ def current_temperature(self):
+ """Return the current temperature."""
+ return self._client.status["current_temp"]
+
+ @property
+ def hvac_mode(self):
+ """Return hvac operation ie. heat, cool mode.
+
+ Need to be one of HVAC_MODE_*.
+ """
+ if self._client.status[ON_MODE] != "on":
+ return HVAC_MODE_OFF
+
+ state = self._client.status["operation"]
+ return HVAC_MAP_REV.get(state)
+
+ @property
+ def hvac_modes(self):
+ """Return the list of available hvac operation modes.
+
+ Need to be a subset of HVAC_MODES.
+ """
+ return list(HVAC_MAP)
+
+ @property
+ def fan_mode(self):
+ """Return the fan setting."""
+ return self._client.status["fan_mode"].lower()
+
+ @property
+ def fan_modes(self):
+ """Return the list of available fan modes."""
+ return SUPPORT_FAN
+
+ @property
+ def swing_mode(self):
+ """Return the swing setting."""
+ return self._client.status["swing_mode"].lower()
+
+ @property
+ def swing_modes(self):
+ """List of available swing modes."""
+ return SUPPORT_SWING
+
+ async def async_set_temperature(self, **kwargs):
+ """Set new target temperature."""
+ temp = kwargs.get(ATTR_TEMPERATURE)
+ if temp is not None:
+ await self._client.set_state(TARGET_TEMP, temp)
+
+ async def async_set_hvac_mode(self, hvac_mode):
+ """Set new target hvac mode."""
+ if hvac_mode == HVAC_MODE_OFF:
+ await self._client.set_state(ON_MODE, "off")
+ else:
+ await self._client.set_state(OPERATION_MODE, HVAC_MAP[hvac_mode])
+
+ async def async_set_fan_mode(self, fan_mode):
+ """Set new fan mode."""
+ await self._client.set_state(FAN_MODE, fan_mode.capitalize())
+
+ async def async_set_swing_mode(self, swing_mode):
+ """Set new swing mode."""
+ await self._client.set_swing(swing_mode.capitalize())
+
+ async def async_turn_on(self):
+ """Turn device on."""
+ await self._client.set_state(OPERATION_MODE)
+
+ async def async_turn_off(self):
+ """Turn device off."""
+ await self._client.set_state(ON_MODE, "off")
diff --git a/pool/shard009/Python/0086962_PyDC_cli.py b/pool/shard009/Python/0086962_PyDC_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..674b4ae900670e19e2f561b473980f0f954f9225
--- /dev/null
+++ b/pool/shard009/Python/0086962_PyDC_cli.py
@@ -0,0 +1,150 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+"""
+ Python dragon 32 converter - commandline interface
+ ==================================================
+
+ :copyleft: 2013 by Jens Diemer
+ :license: GNU GPL v3 or above, see LICENSE for more details.
+"""
+
+import logging
+import os
+
+from PyDC import TITLE_LINE, VERSION_STRING, analyze, convert
+from PyDC.base_cli import Base_CLI
+from PyDC.configs import Dragon32Config
+
+
+log = logging.getLogger("PyDC")
+
+
+class PyDC_CLI(Base_CLI):
+ LOG_NAME = "PyDC"
+ DESCRIPTION = "Python dragon 32 converter"
+ EPOLOG = TITLE_LINE
+ VERSION = VERSION_STRING
+ LOG_FORMATTER = logging.Formatter("%(message)s") # %(asctime)s %(message)s")
+
+ def __init__(self):
+ super(PyDC_CLI, self).__init__()
+ self.cfg = Dragon32Config()
+
+ self.parser.add_argument("src", help="Source filename (.wav/.cas/.bas)")
+ self.parser.add_argument("--dst",
+ help="Destination filename (.wav/.cas/.bas)"
+ )
+
+ self.parser.add_argument(
+ "--analyze", action="store_true",
+ help=(
+ "Display zeror crossing information in the given wave file."
+ )
+ )
+
+ # For Wave2Bitstream():
+ self.parser.add_argument(
+ "--bit_one_hz", type=int, default=self.cfg.BIT_ONE_HZ,
+ help=(
+ "Frequency of bit '1' in Hz"
+ " (default: %s)"
+ ) % self.cfg.BIT_ONE_HZ
+ )
+ self.parser.add_argument(
+ "--bit_nul_hz", type=int, default=self.cfg.BIT_NUL_HZ,
+ help=(
+ "Frequency of bit '0' in Hz"
+ " (default: %s)"
+ ) % self.cfg.BIT_NUL_HZ
+ )
+
+ self.parser.add_argument(
+ "--hz_variation", type=int, default=self.cfg.HZ_VARIATION,
+ help=(
+ "How much Hz can signal scatter to match 1 or 0 bit ?"
+ " (default: %s)"
+ ) % self.cfg.HZ_VARIATION
+ )
+
+ self.parser.add_argument(
+ "--min_volume_ratio", type=int, default=self.cfg.MIN_VOLUME_RATIO,
+ help="percent volume to ignore sample (default: %s)" % self.cfg.MIN_VOLUME_RATIO
+ )
+ self.parser.add_argument(
+ "--avg_count", type=int, default=self.cfg.AVG_COUNT,
+ help=(
+ "How many samples should be merged into a average value?"
+ " (default: %s)"
+ ) % self.cfg.AVG_COUNT
+ )
+ self.parser.add_argument(
+ "--end_count", type=int, default=self.cfg.END_COUNT,
+ help=(
+ "Sample count that must be pos/neg at once"
+ " (default: %s)"
+ ) % self.cfg.END_COUNT
+ )
+ self.parser.add_argument(
+ "--mid_count", type=int, default=self.cfg.MID_COUNT,
+ help=(
+ "Sample count that can be around null"
+ " (default: %s)"
+ ) % self.cfg.MID_COUNT
+ )
+
+ self.parser.add_argument(
+ "--case_convert", action="store_true",
+ help=(
+ "Convert to uppercase if source is .bas"
+ " and to lowercase if destination is .bas"
+ )
+ )
+
+ def parse_args(self):
+ args = super(PyDC_CLI, self).parse_args()
+
+ self.source_file = args.src
+ print "source file.......: %s" % self.source_file
+
+ if args.dst:
+ self.destination_file = args.dst
+ print "destination file..: %s" % self.destination_file
+
+ return args
+
+ def run(self):
+ self.args = self.parse_args()
+
+ source_filename = os.path.splitext(self.source_file)[0]
+ if self.args.dst:
+ dest_filename = os.path.splitext(self.destination_file)[0]
+ self.logfilename = dest_filename + ".log"
+ else:
+ self.logfilename = source_filename + ".log"
+ log.info("Logfile: %s" % self.logfilename)
+
+ self.setup_logging(self.args) # XXX: setup logging after the logfilename is set!
+
+ self.cfg.BIT_ONE_HZ = self.args.bit_one_hz # Frequency of bit '1' in Hz
+ self.cfg.BIT_NUL_HZ = self.args.bit_nul_hz # Frequency of bit '0' in Hz
+ self.cfg.HZ_VARIATION = self.args.hz_variation # How much Hz can signal scatter to match 1 or 0 bit ?
+
+ self.cfg.MIN_VOLUME_RATIO = self.args.min_volume_ratio # percent volume to ignore sample
+ self.cfg.AVG_COUNT = self.args.avg_count # How many samples should be merged into a average value?
+ self.cfg.END_COUNT = self.args.end_count # Sample count that must be pos/neg at once
+ self.cfg.MID_COUNT = self.args.mid_count # Sample count that can be around null
+
+ self.cfg.case_convert = self.args.case_convert
+
+ if self.args.analyze:
+ analyze(self.source_file, self.cfg)
+ else:
+ convert(self.source_file, self.destination_file, self.cfg)
+
+
+if __name__ == "__main__":
+ cli = PyDC_CLI()
+ cli.run()
+
+ print "\n --- END --- \n"
diff --git a/pool/shard009/Python/0086964_math_domain_special.py b/pool/shard009/Python/0086964_math_domain_special.py
new file mode 100644
index 0000000000000000000000000000000000000000..388920350ec6ad83cd0118b2591d3ac637c07358
--- /dev/null
+++ b/pool/shard009/Python/0086964_math_domain_special.py
@@ -0,0 +1,36 @@
+# Tests domain errors in special math functions
+
+try:
+ import math
+ math.erf
+except (ImportError, AttributeError):
+ print("SKIP")
+ raise SystemExit
+
+inf = float('inf')
+nan = float('nan')
+
+# single argument functions
+for name, f, args in (
+ ('expm1', math.exp, ()),
+ ('log2', math.log2, (-1, 0)),
+ ('log10', math.log10, (-1, 0)),
+ ('sinh', math.sinh, ()),
+ ('cosh', math.cosh, ()),
+ ('tanh', math.tanh, ()),
+ ('asinh', math.asinh, ()),
+ ('acosh', math.acosh, (-1, 0.9, 1)),
+ ('atanh', math.atanh, (-1, 1)),
+ ('erf', math.erf, ()),
+ ('erfc', math.erfc, ()),
+ ('gamma', math.gamma, (-2, -1, 0, 1)),
+ ('lgamma', math.lgamma, (-2, -1, 0, 1)),
+ ):
+ for x in args + (inf, nan):
+ try:
+ ans = f(x)
+ print('%.4f' % ans)
+ except ValueError:
+ print(name, 'ValueError')
+ except OverflowError:
+ print(name, 'OverflowError')
diff --git a/pool/shard009/Python/0086965_maf_limit_to_species.py b/pool/shard009/Python/0086965_maf_limit_to_species.py
new file mode 100644
index 0000000000000000000000000000000000000000..031aabb5c32d8c5ab877466ec986e8237358116d
--- /dev/null
+++ b/pool/shard009/Python/0086965_maf_limit_to_species.py
@@ -0,0 +1,40 @@
+#!/usr/bin/python2.7
+
+"""
+Read a maf file from stdin and write out a new maf with only blocks having all
+of the required in species, after dropping any other species and removing
+columns containing only gaps.
+
+usage: %prog species,species2,... < maf
+"""
+
+import psyco_full
+
+import bx.align.maf
+import copy
+import sys
+
+from itertools import *
+
+def main():
+
+ species = sys.argv[1].split( ',' )
+
+ maf_reader = bx.align.maf.Reader( sys.stdin )
+ maf_writer = bx.align.maf.Writer( sys.stdout )
+
+ for m in maf_reader:
+ new_components = []
+ for comp in m.components:
+ if comp.src.split( '.' )[0] in species:
+ new_components.append( comp )
+ m.components = new_components
+ m.remove_all_gap_columns()
+ if len( m.components ) > 1:
+ maf_writer.write( m )
+
+ maf_reader.close()
+ maf_writer.close()
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard009/Python/0086968_password_hash_fl2003.py b/pool/shard009/Python/0086968_password_hash_fl2003.py
new file mode 100644
index 0000000000000000000000000000000000000000..c412a0676e65d3a204c012ae8f41fb72d1732497
--- /dev/null
+++ b/pool/shard009/Python/0086968_password_hash_fl2003.py
@@ -0,0 +1,199 @@
+# Tests for Tests for source4/dsdb/samdb/ldb_modules/password_hash.c
+#
+# Copyright (C) Catalyst IT Ltd. 2017
+#
+# 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 .
+#
+
+"""
+Tests for source4/dsdb/samdb/ldb_modules/password_hash.c
+
+These tests need to be run in an environment in which
+io->ac->gpg_key_ids == NULL, so that the gpg supplemental credentials
+are not generated. And also need to be in an environment with a
+functional level less than 2008 to ensure the kerberos newer keys are not
+generated
+"""
+
+from samba.tests.password_hash import (
+ PassWordHashTests,
+ get_package,
+ USER_PASS
+)
+from samba.ndr import ndr_unpack
+from samba.dcerpc import drsblobs
+import binascii
+
+
+class PassWordHashFl2003Tests(PassWordHashTests):
+
+ def setUp(self):
+ super(PassWordHashFl2003Tests, self).setUp()
+
+ def test_default_supplementalCredentials(self):
+ self.add_user(options=[("password hash userPassword schemes", "")])
+
+ sc = self.get_supplemental_creds()
+
+ # Check that we got all the expected supplemental credentials
+ # And they are in the expected order.
+ size = len(sc.sub.packages)
+ self.assertEqual(3, size)
+
+ (pos, package) = get_package(sc, "Primary:Kerberos")
+ self.assertEqual(1, pos)
+ self.assertEqual("Primary:Kerberos", package.name)
+
+ (pos, package) = get_package(sc, "Packages")
+ self.assertEqual(2, pos)
+ self.assertEqual("Packages", package.name)
+
+ (pos, package) = get_package(sc, "Primary:WDigest")
+ self.assertEqual(3, pos)
+ self.assertEqual("Primary:WDigest", package.name)
+
+ # Check that the WDigest values are correct.
+ #
+ digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
+ binascii.a2b_hex(package.data))
+ self.check_wdigests(digests)
+
+ def test_userPassword_sha256(self):
+ self.add_user(options=[("password hash userPassword schemes",
+ "CryptSHA256")])
+
+ sc = self.get_supplemental_creds()
+
+ # Check that we got all the expected supplemental credentials
+ # And they are in the expected order.
+ size = len(sc.sub.packages)
+ self.assertEqual(4, size)
+
+ (pos, package) = get_package(sc, "Primary:Kerberos")
+ self.assertEqual(1, pos)
+ self.assertEqual("Primary:Kerberos", package.name)
+
+ (pos, wd_package) = get_package(sc, "Primary:WDigest")
+ self.assertEqual(2, pos)
+ self.assertEqual("Primary:WDigest", wd_package.name)
+
+ (pos, package) = get_package(sc, "Packages")
+ self.assertEqual(3, pos)
+ self.assertEqual("Packages", package.name)
+
+ (pos, up_package) = get_package(sc, "Primary:userPassword")
+ self.assertEqual(4, pos)
+ self.assertEqual("Primary:userPassword", up_package.name)
+
+ # Check that the WDigest values are correct.
+ #
+ digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
+ binascii.a2b_hex(wd_package.data))
+ self.check_wdigests(digests)
+
+ # Check that the userPassword hashes are computed correctly
+ #
+ up = ndr_unpack(drsblobs.package_PrimaryUserPasswordBlob,
+ binascii.a2b_hex(up_package.data))
+
+ self.checkUserPassword(up, [("{CRYPT}", "5", None)])
+ self.checkNtHash(USER_PASS, up.current_nt_hash.hash)
+
+ def test_supplementalCredentials_cleartext(self):
+ self.add_user(clear_text=True,
+ options=[("password hash userPassword schemes", "")])
+
+ sc = self.get_supplemental_creds()
+
+ # Check that we got all the expected supplemental credentials
+ # And they are in the expected order.
+ size = len(sc.sub.packages)
+ self.assertEqual(4, size)
+
+ (pos, package) = get_package(sc, "Primary:Kerberos")
+ self.assertEqual(1, pos)
+ self.assertEqual("Primary:Kerberos", package.name)
+
+ (pos, wd_package) = get_package(sc, "Primary:WDigest")
+ self.assertEqual(2, pos)
+ self.assertEqual("Primary:WDigest", wd_package.name)
+
+ (pos, package) = get_package(sc, "Packages")
+ self.assertEqual(3, pos)
+ self.assertEqual("Packages", package.name)
+
+ (pos, ct_package) = get_package(sc, "Primary:CLEARTEXT")
+ self.assertEqual(4, pos)
+ self.assertEqual("Primary:CLEARTEXT", ct_package.name)
+
+ # Check that the WDigest values are correct.
+ #
+ digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
+ binascii.a2b_hex(wd_package.data))
+ self.check_wdigests(digests)
+
+ # Check the clear text value is correct.
+ ct = ndr_unpack(drsblobs.package_PrimaryCLEARTEXTBlob,
+ binascii.a2b_hex(ct_package.data))
+ self.assertEqual(USER_PASS.encode('utf-16-le'), ct.cleartext)
+
+ def test_userPassword_cleartext_sha512(self):
+ self.add_user(clear_text=True,
+ options=[("password hash userPassword schemes",
+ "CryptSHA512:rounds=10000")])
+
+ sc = self.get_supplemental_creds()
+
+ # Check that we got all the expected supplemental credentials
+ # And they are in the expected order.
+ size = len(sc.sub.packages)
+ self.assertEqual(5, size)
+
+ (pos, package) = get_package(sc, "Primary:Kerberos")
+ self.assertEqual(1, pos)
+ self.assertEqual("Primary:Kerberos", package.name)
+
+ (pos, wd_package) = get_package(sc, "Primary:WDigest")
+ self.assertEqual(2, pos)
+ self.assertEqual("Primary:WDigest", wd_package.name)
+
+ (pos, ct_package) = get_package(sc, "Primary:CLEARTEXT")
+ self.assertEqual(3, pos)
+ self.assertEqual("Primary:CLEARTEXT", ct_package.name)
+
+ (pos, package) = get_package(sc, "Packages")
+ self.assertEqual(4, pos)
+ self.assertEqual("Packages", package.name)
+
+ (pos, up_package) = get_package(sc, "Primary:userPassword")
+ self.assertEqual(5, pos)
+ self.assertEqual("Primary:userPassword", up_package.name)
+
+ # Check that the WDigest values are correct.
+ #
+ digests = ndr_unpack(drsblobs.package_PrimaryWDigestBlob,
+ binascii.a2b_hex(wd_package.data))
+ self.check_wdigests(digests)
+
+ # Check the clear text value is correct.
+ ct = ndr_unpack(drsblobs.package_PrimaryCLEARTEXTBlob,
+ binascii.a2b_hex(ct_package.data))
+ self.assertEqual(USER_PASS.encode('utf-16-le'), ct.cleartext)
+
+ # Check that the userPassword hashes are computed correctly
+ #
+ up = ndr_unpack(drsblobs.package_PrimaryUserPasswordBlob,
+ binascii.a2b_hex(up_package.data))
+ self.checkUserPassword(up, [("{CRYPT}", "6", 10000)])
+ self.checkNtHash(USER_PASS, up.current_nt_hash.hash)
diff --git a/pool/shard009/Python/0086973_unreadmails.py b/pool/shard009/Python/0086973_unreadmails.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7ac697276fd5d20e11c537d7c2bb4f06a1ae82
--- /dev/null
+++ b/pool/shard009/Python/0086973_unreadmails.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) Morris Jobke 2010
+#
+# MailNotify 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.
+#
+# MailNotify 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 .
+
+# python imports
+import indicate
+import subprocess
+# own imports
+
+import logging
+log = logging.getLogger('Log.UnreadMails')
+
+class UnreadMails:
+ def __init__(self, link, prefix='', style=1):
+ log.debug('new UnreadMails ...')
+ self.link = link
+ self.style = style
+ self.prefix = prefix
+ self.mails = []
+ self.mailboxes = {}
+ self.indicators = {}
+
+ def add(self, mails):
+ mailboxes = {}
+ for mail in mails:
+ if mail.mailbox['name'] not in mailboxes:
+ mailboxes[mail.mailbox['name']] = {'count': 0, 'link': mail.mailbox['link']}
+ mailboxes[mail.mailbox['name']]['count'] += 1
+ if mail.subject not in [m.subject for m in self.mails]:
+ log.info('new mail ...')
+ self.mails.append(mail)
+
+ self.mailboxes = mailboxes
+ # cleanup
+ for mail in self.mails:
+ if mail.subject not in [m.subject for m in mails]:
+ self.mails.remove(mail)
+ if self.style == 2:
+ self.indicators[self.prefix + mail.subject].hide()
+ del self.indicators[self.prefix + mail.subject]
+
+ def indicate(self):
+ if self.style == 1:
+ #### STYLE 1 ####
+ for m in self.mailboxes:
+ n = self.prefix + m
+ if n in self.indicators:
+ self.indicators[n].update(str(self.mailboxes[m]['count']))
+ else:
+ i = IndicatorItem(
+ self.mailboxes[m]['link'],
+ n,
+ str(self.mailboxes[m]['count'])
+ )
+ self.indicators[n] = i
+ elif self.style == 2:
+ #### STYLE 2 ####
+ for m in self.mails:
+ n = self.prefix + m.subject
+ if not n in self.indicators:
+ i = IndicatorItem(
+ m.link,
+ n,
+ m.time
+ )
+ self.indicators[n] = i
+
+ def clear(self):
+ for i in self.indicators:
+ self.indicators[i].hide()
+ self.mails = []
+ self.mailboxes = {}
+ self.indicators = {}
+
+class IndicatorItem(indicate.Indicator):
+ def __init__(self, link, subject, timeOrCount):
+ '''
+ indicator for IndicatorItems
+ '''
+ log.debug('new IndicatorItem ...')
+ indicate.Indicator.__init__(self)
+ self.link = link
+ self.set_property('name', subject)
+ if type(timeOrCount) == type(float()):
+ self.set_property_time('time', timeOrCount)
+ elif type(timeOrCount) == type(str()):
+ self.set_property('count', timeOrCount)
+ self.connect('user-display', self.click)
+ self.set_property('draw-attention', 'true')
+ self.show()
+
+ def click(self, server, something):
+ server.set_property('draw-attention', 'false')
+ subprocess.call(['gnome-open', self.link])
+
+ def stress(self):
+ self.set_property('draw-attention', 'true')
+
+ def unstress(self):
+ self.set_property('draw-attention', 'false')
+
+ def update(self, timeOrCount):
+ if type(timeOrCount) == type(float()):
+ self.set_property_time('time', timeOrCount)
+ elif type(timeOrCount) == type(str()):
+ self.set_property('count', timeOrCount)
+ self.set_property('draw-attention', 'true')
+
diff --git a/pool/shard009/Python/0086974_preintegrated_rendering.py b/pool/shard009/Python/0086974_preintegrated_rendering.py
new file mode 100644
index 0000000000000000000000000000000000000000..8aa4c8cd2c69d953be5119e8915a2f73bb8e491b
--- /dev/null
+++ b/pool/shard009/Python/0086974_preintegrated_rendering.py
@@ -0,0 +1,172 @@
+from typing import Optional
+import imageio
+import tensorflow as tf
+import tensorflow_addons as tfa
+
+import nn_utils.math_utils as math_utils
+
+
+class PreintegratedRenderer(tf.keras.layers.Layer):
+ def __init__(self, brdf_integration_map_path: str, **kwargs) -> None:
+ super(PreintegratedRenderer, self).__init__(**kwargs)
+
+ imageio.plugins.freeimage.download()
+
+ brdf_map = imageio.imread(brdf_integration_map_path, format="HDR-FI")
+
+ # Ensure B, H, W, C
+ self.brdf_integration = tf.convert_to_tensor(brdf_map)[
+ None, ...
+ ] # Read HDR data
+
+ @tf.function(experimental_relax_shapes=True)
+ def fresnel_schlick_roughness(self, ndotv, f0, roughness):
+ with tf.name_scope("FresnelSchlickRoughness"):
+ return f0 + (tf.maximum(1.0 - roughness, f0) - f0) * tf.pow(
+ tf.maximum(1.0 - ndotv, 0.0), 5.0
+ )
+
+ @tf.function(experimental_relax_shapes=True)
+ def get_tangent(self, normal, angle):
+ with tf.name_scope("TangentCalculation"):
+ alteredNormal = tf.stack(
+ [-normal[..., -1], normal[..., 0], normal[..., 1]], -1
+ )
+ tangent = math_utils.cross(normal, alteredNormal)
+ bitangent = math_utils.cross(normal, tangent)
+ return math_utils.normalize(
+ tangent * tf.math.sin(angle) + bitangent * tf.math.cos(angle)
+ ) # Just for safety
+
+ @tf.function(experimental_relax_shapes=True)
+ def calculate_reflection_direction(
+ self,
+ view_vector: tf.Tensor,
+ normal: tf.Tensor,
+ camera_pose: Optional[tf.Tensor] = None,
+ ):
+ """Calculates the relfection direction for a the specified view ray
+ and normal. Can also used if a rotating object with a fixed illumination is
+ present. The reflected ray is then also rotated with the inverse camera pose.
+
+ Args:
+ view_vector (tf.Tensor(float32), [batch, 3]): View vector pointing
+ away from the surface.
+ normal (tf.Tensor(float32), [batch, 3]): Normal vector of the surface.
+ camera_pose (Optional[(tf.Tensor(float32), [3, 4])], optional):
+ Defines the camera rotation matrix. If not None the rays are
+ counterrotated. This is used if a capture is done with a rotating
+ object. Defaults to None.
+
+ Returns:
+ reflected_ray (tf.Tensor(float32), [batch, 3]): the reflected ray in
+ outgoing direction.
+ """
+
+ with tf.name_scope("ReflectionDirection"):
+ normal = tf.where(normal == tf.zeros_like(normal), view_vector, normal)
+
+ # Add the rotating object case
+ if camera_pose is not None:
+ with tf.name_scope("RotationCounterAct"):
+ rotation_matrix = tf.linalg.inv(camera_pose[:3, :3])
+
+ view_vector = view_vector[..., None, :] * rotation_matrix
+ view_vector = tf.reduce_sum(view_vector, -1)
+
+ # View vector points away from the surface. For a reflection
+ # The vector should be incoming (so flip) and the direction is
+ # then outgoing
+ reflection_vector = math_utils.reflect(-view_vector, normal)
+
+ return view_vector, reflection_vector
+
+ @tf.function(experimental_relax_shapes=True)
+ def call(
+ self,
+ view_vector: tf.Tensor,
+ normal: tf.Tensor,
+ diffuse_irradiance: tf.Tensor,
+ specular_irradiance: tf.Tensor,
+ diffuse: tf.Tensor,
+ specular: tf.Tensor,
+ roughness: tf.Tensor,
+ ):
+ """Performs the pre-integrated rendering.
+
+ Args:
+ view_vector (tf.Tensor(float32), [batch, 3]): View vector pointing
+ away from the surface.
+ normal (tf.Tensor(float32), [batch, 3]): Normal vector of the
+ surface.
+ diffuse_irradiance (tf.Tensor(float32), [batch, 3]): The diffuse
+ preintegrated irradiance.
+ specular_irradiance (tf.Tensor(float32), [batch, 3]): The specular
+ preintegrated .
+ diffuse (tf.Tensor(float32), [batch, 3]): The diffuse material
+ parameter.
+ specular (tf.Tensor(float32), [batch, 3]): The specular material
+ parameter.
+ roughness (tf.Tensor(float32), [batch, 1]): The roughness material
+ parameter.
+
+ Returns:
+ rendered_rgb (tf.Tensor(float32), [batch, 3]): The rendered result.
+ """
+ with tf.name_scope("CallPrepare"):
+ normal = tf.where(normal == tf.zeros_like(normal), view_vector, normal)
+
+ ndotv = math_utils.dot(normal, view_vector)
+
+ lin_diffuse = math_utils.srgb_to_linear(diffuse)
+ lin_specular = math_utils.srgb_to_linear(specular)
+
+ F = self.fresnel_schlick_roughness(
+ tf.maximum(ndotv, 0.0), lin_specular, roughness
+ )
+ kS = F
+ kD = 1.0 - kS
+
+ with tf.name_scope("Diffuse"):
+ # Evaluate diffuse
+ diffuse = diffuse_irradiance * lin_diffuse
+
+ with tf.name_scope("Specular"):
+ # Evaluate specular
+ # (u,v) is defined as (ndotv, roughness)
+ # (0,1) +---------+ (1, 1)
+ # | | /\
+ # | | roughness |
+ # | |
+ # (0,0) +---------+ (1, 0)
+ # ndotv ->
+
+ # We access in ij coordinates
+ # (i,j)
+ # (0,0) +---------+ (1, 0)
+ # | |
+ # | |
+ # | |
+ # (0,1) +---------+ (1, 1)
+
+ # So the start is top left instead of bottom left:
+ # -> (1-roughness)
+ # Also we swap from x,y indexing to ij
+ envBrdfCoords = tf.concat(
+ [
+ (1 - roughness) * (self.brdf_integration.shape[1] - 1),
+ tf.maximum(ndotv, 0.0) * (self.brdf_integration.shape[2] - 1),
+ ],
+ -1,
+ )
+
+ envBrdf = tfa.image.interpolate_bilinear(
+ self.brdf_integration, envBrdfCoords[None, ...]
+ )[
+ 0
+ ] # Remove fake batch dimension
+ specular = specular_irradiance * (F * envBrdf[..., :1] + envBrdf[..., 1:2])
+
+ # Joined ambient light
+ ambient = kD * diffuse + specular
+ return ambient
diff --git a/pool/shard009/Python/0086977_models.py b/pool/shard009/Python/0086977_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e33ce3b847e8e92c250ed20c89354601037bfbc
--- /dev/null
+++ b/pool/shard009/Python/0086977_models.py
@@ -0,0 +1,30 @@
+from django.db import models
+from django.utils.encoding import python_2_unicode_compatible
+from django.conf import settings
+
+from model_utils.models import TimeStampedModel
+
+
+class Question(TimeStampedModel):
+
+ answer_choices = (
+ (0, "Yes"),
+ (1, "No"),
+ )
+
+ answer_weights = (
+ (1, "A little"),
+ (2, "Somewhat"),
+ (3, "Very")
+ )
+
+ question_types = (
+ (0, "Personality"),
+ (1, "Interest")
+ )
+
+ user = models.ForeignKey(settings.AUTH_USER_MODEL)
+ question = models.CharField(max_length=75)
+ answer = models.IntegerField(choices=answer_choices)
+ answer_weight = models.IntegerField(choices=answer_weights)
+ question_type = models.IntegerField(choices=question_types)
diff --git a/pool/shard009/Python/0086980_config.py b/pool/shard009/Python/0086980_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b88513e79ddf194628cc0b34546dc00e0c0c993
--- /dev/null
+++ b/pool/shard009/Python/0086980_config.py
@@ -0,0 +1,112 @@
+import os
+import yaml
+
+CONFIG_FILE = 'settings.yaml'
+
+
+class Config(object):
+
+ def __init__(self):
+ # get settings from settings.yaml
+ config_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, CONFIG_FILE))
+ with open(config_file_path, 'r') as yml:
+ self.config = yaml.load(yml)
+
+ self.groups = self.get_groups()
+ self.environments = self.get_environments()
+ self.servers = self.get_servers()
+ self.email_settings = self.get_email_settings()
+ self.default_dir = self.get_default_dir()
+ self.repositories = self.get_repositories()
+
+ def get_groups(self):
+ if self.config['ServerGroups'] is None:
+ groups = ['group1']
+ elif not isinstance(self.config['ServerGroups'], list):
+ raise AttributeError(
+ 'ServerGroups in config file must be of type list, {} given'.format(type(self.config['ServerGroups']))
+ )
+ else:
+ groups = self.config["ServerGroups"]
+
+ return groups
+
+ def get_environments(self):
+ if self.config['Environments'] is None:
+ environments = ['default']
+ elif not isinstance(self.config['Environments'], list):
+ raise AttributeError(
+ 'Environments in config file must be of type list, {} given'.format(type(self.config['Environments']))
+ )
+ else:
+ environments = self.config["Environments"]
+
+ return environments
+
+ def get_servers(self):
+ if [self.config['Servers']] is None:
+ raise Exception('No Server Aliases configured. Please specify servers in your config file')
+ elif not isinstance(self.config['Servers'], dict):
+ raise AttributeError(
+ 'Servers in config file must be of type dict, {} given'.format(type(self.config['Servers']))
+ )
+ else:
+ servers = self.config['Servers']
+
+ # TODO: loop through list of servers and validate the individual dicts for correct structure
+
+ return servers
+
+ def get_email_settings(self):
+
+ if self.config['EmailSettings'] is None:
+ email_setttings = {
+ 'email_host': '',
+ 'email_from': '',
+ 'email_to': ''
+ }
+ elif not isinstance(self.config['EmailSettings'], dict):
+ raise AttributeError(
+ 'Email Settings in config file must be of type dict, {} given'.format(type(self.config['EmailSettings']))
+ )
+ else:
+ email_settings = self.config['EmailSettings']
+
+ return email_settings
+
+ def get_default_dir(self):
+
+ if self.config['DefaultDir'] is None:
+ return os.getcwd()
+ else:
+ return self.config['DefaultDir']
+
+ def get_default_merge_dir(self):
+
+ if self.config['MergeDir'] is None:
+ raise AttributeError(
+ 'MergeDir must be set in settings.yml config file'
+ )
+ else:
+ return self.config['MergeDir']
+
+ def get_repositories(self):
+
+ if [self.config['Repositories']] is None:
+ repositories = []
+ elif not isinstance(self.config['Repositories'], list):
+ raise AttributeError(
+ 'Repositories in config file must be of type list, {} given'.format(type(self.config['Repositories']))
+ )
+ else:
+ repositories = self.config['Repositories']
+
+ return repositories
+
+ def get_git_server(self):
+ if self.config['GitServer'] is None:
+ raise AttributeError(
+ 'GitServer must be set in settings.yml config file'
+ )
+ else:
+ return self.config['GitServer']
diff --git a/pool/shard009/Python/0086985_BlacklistKey.py b/pool/shard009/Python/0086985_BlacklistKey.py
new file mode 100644
index 0000000000000000000000000000000000000000..86721e91f125749f8398566bbadf72ce21d0b012
--- /dev/null
+++ b/pool/shard009/Python/0086985_BlacklistKey.py
@@ -0,0 +1,42 @@
+from PLC.Faults import *
+from PLC.Method import Method
+from PLC.Parameter import Parameter, Mixed
+from PLC.Keys import Key, Keys
+from PLC.Auth import Auth
+
+class BlacklistKey(Method):
+ """
+ Blacklists a key, disassociating it and all others identical to it
+ from all accounts and preventing it from ever being added again.
+
+ WARNING: Identical keys associated with other accounts with also
+ be blacklisted.
+
+ Returns 1 if successful, faults otherwise.
+ """
+
+ roles = ['admin']
+
+ accepts = [
+ Auth(),
+ Key.fields['key_id'],
+ ]
+
+ returns = Parameter(int, '1 if successful')
+
+ def call(self, auth, key_id):
+ # Get associated key details
+ keys = Keys(self.api, [key_id])
+ if not keys:
+ raise PLCInvalidArgument("No such key")
+ key = keys[0]
+
+ # N.B.: Can blacklist any key, even foreign ones
+
+ key.blacklist()
+
+ # Logging variables
+ self.event_objects = {'Key': [key['key_id']]}
+ self.message = 'Key %d blacklisted' % key['key_id']
+
+ return 1
diff --git a/pool/shard009/Python/0086986_wsgi.py b/pool/shard009/Python/0086986_wsgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..35395a530f4058abbadfcb9d061efa791ec9a37f
--- /dev/null
+++ b/pool/shard009/Python/0086986_wsgi.py
@@ -0,0 +1,28 @@
+"""
+WSGI config for project.
+
+This module contains the WSGI application used by Django's development server
+and any production WSGI deployments. It should expose a module-level variable
+named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
+this application via the ``WSGI_APPLICATION`` setting.
+
+Usually you will have the standard Django WSGI application here, but it also
+might make sense to replace the whole Django WSGI application with a custom one
+that later delegates to the Django one. For example, you could introduce WSGI
+middleware here, or combine a Django application with an application of another
+framework.
+
+"""
+import os
+from os.path import abspath, dirname
+from sys import path
+
+SITE_ROOT = dirname(dirname(abspath(__file__)))
+path.append(SITE_ROOT)
+
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ulm.settings")
+
+
+from django.core.wsgi import get_wsgi_application
+application = get_wsgi_application()
diff --git a/pool/shard009/Python/0086998_merge_tx_metadata.py b/pool/shard009/Python/0086998_merge_tx_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a05c321200d0849c6ddc78e8dfaffef98790875
--- /dev/null
+++ b/pool/shard009/Python/0086998_merge_tx_metadata.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python2.7
+
+import os, shutil, copy, json
+
+# when executing this test directly include the parent dir in the path
+if (
+ (__name__ == "__main__") and
+ (__package__ is None)
+):
+ os.sys.path.append(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ )
+
+# module to convert data into human readable form
+import lang_grunt
+
+# module containing some general bitcoin-related functions
+import btc_grunt
+
+# set the btc_grunt base dir to the current dir
+btc_grunt.base_dir = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), ""
+)
+btc_grunt.tx_meta_dir = os.path.join(btc_grunt.base_dir, "tx_metadata", "")
+
+txhash1 = "23ab47f962e86d1849fe2e1bdc3e3e5e49373fd8082bbb3792d704eeeaaec40f"
+
+# get the dir and filename for this hash
+(f_dir, f_name, hashend) = btc_grunt.hash2dir_and_filename_and_hashend(txhash1)
+
+# erase the test tx_metadata file if it exists
+if os.path.exists(btc_grunt.tx_meta_dir):
+ shutil.rmtree(btc_grunt.tx_meta_dir)
+
+# write the data to the tx_metadata file
+save_data1 = {
+ "c9c7-3": {
+ "blockfile_num": 3,
+ "block_start_pos": 128407591,
+ "tx_start_pos": 731,
+ "tx_size": 193,
+ "block_height": 142392,
+ "is_coinbase": None,
+ "is_orphan": None,
+ "spending_txs_list": ["d308-0", "3bd9-15"]
+ }
+}
+btc_grunt.save_tx_data_to_disk(txhash1, save_data1)
+
+# merge new data into the tx metadata file
+save_data2 = {
+ "ffff-9": {
+ "blockfile_num": 3,
+ "block_start_pos": 111111111,
+ "tx_start_pos": 777,
+ "tx_size": 193,
+ "block_height": 999999,
+ "is_coinbase": None,
+ "is_orphan": None,
+ "spending_txs_list": [None, None]
+ }
+}
+btc_grunt.save_tx_data_to_disk(txhash1, save_data2)
+txhash2 = "23ab47a450dd4a8ba00f25041813e42dae7e29508d0ec94980344433088b2861"
+save_data3 = {
+ "386d-26": {
+ "blockfile_num": 12,
+ "block_start_pos": 12945601,
+ "tx_start_pos": 15984,
+ "tx_size": 259,
+ "block_height": 183244,
+ "is_coinbase": None,
+ "is_orphan": None,
+ "spending_txs_list": [None, "ad9b-1"]
+ }
+}
+btc_grunt.save_tx_data_to_disk(txhash2, save_data3)
+
+# verify that the file now contains the correct data
+existing_data_csv = btc_grunt.get_tx_metadata_csv(txhash1) # one tx per list item
+existing_data_dict = btc_grunt.tx_metadata_csv2dict(existing_data_csv)
+save_data_combined = copy.deepcopy(save_data1)
+save_data_combined.update(save_data2)
+expected_data_dict = {txhash1: save_data_combined, txhash2: save_data3}
+if existing_data_dict == expected_data_dict:
+ print "pass"
+ # clean up the directories since everything is fine
+ shutil.rmtree(btc_grunt.tx_meta_dir)
+else:
+ # do not clean up the directories, leave for investigation
+ lang_grunt.die("fail. expected: %s but got %s" % (
+ os.linesep.join(
+ l.rstrip() for l in json.dumps(
+ expected_data_dict, sort_keys = True, indent = 4
+ ).splitlines()
+ ),
+ os.linesep.join(
+ l.rstrip() for l in json.dumps(
+ existing_data_dict, sort_keys = True, indent = 4
+ ).splitlines()
+ ),
+ ))
diff --git a/pool/shard009/Python/0087000_DummyPN532.py b/pool/shard009/Python/0087000_DummyPN532.py
new file mode 100644
index 0000000000000000000000000000000000000000..7922e82836f4aa8428bcbdd70d324cb35113c50b
--- /dev/null
+++ b/pool/shard009/Python/0087000_DummyPN532.py
@@ -0,0 +1,22 @@
+class DummyRFID(object):
+
+ class StandInPN532(object):
+ i = 0
+ loop = [
+ bytearray([0xb3,0xff,0x25,0x5d]),
+ bytearray([0xb1,0xff,0x25,0x5d]),
+ bytearray([0xbf,0xff,0x25,0x5d]),
+ ]
+
+ def begin(self):
+ pass
+ def SAM_configuration(self):
+ pass
+ def read_passive_target(self):
+ self.i = self.i + 1
+ if self.i == 3:
+ self.i = 0
+ return self.loop[self.i]
+
+ def PN532(self, cs=11, sclk=22, mosi=11, miso=55):
+ return self.StandInPN532()
diff --git a/pool/shard009/Python/0087002_jarets_mysql_wrapper.py b/pool/shard009/Python/0087002_jarets_mysql_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..915318003d0b74b45be392808bb0f9e55cfd9814
--- /dev/null
+++ b/pool/shard009/Python/0087002_jarets_mysql_wrapper.py
@@ -0,0 +1,153 @@
+"""
+ @Author Jaret Deprin
+
+ @Usage
+ import jarets_mysql_wrapper
+ # All parameters are required even if user/pass are empty
+ c = jarets_mysql_wrapper.Mysql(DBHOST="localhost", DBNAME="test", DBUSER="", DBPASS="")
+
+ # Stage query
+ c.__stage = True
+ Will print queries / values but not execute them.
+
+ # Select statment examples
+ results = c.select(table, columns, where(optional))
+ results = c.select("jdtest", "*")
+ results = c.select("jdtest", "id", "name")
+ results = c.select("jdtest", "id", "name", where="id=2")
+ results = c.select("jdtest", "id", "name", where="state='running' AND bool=True")
+
+ # Insert statement examples
+ # Both keyword arguments and un-named arguments are supported
+ # Use caution with un-named arguments as they could insert valued into incorrect
+ fields if you write the values in the incorrect order.
+ new_row_primarykey = c.insert(table, **column_names=values)
+ new_row_primarykey = c.insert("jdtest", state="stopped", ip="10.1.1.5", name="host5", bool=True)
+ new_row_primarykey = c.insert("jdtest", 6,"host6","running",False,"10.1.1.6")
+
+ # Update statement examples
+ c.update(table, where, **column_names=values)
+ c.update("jdtest", where="id=6", ip="10.1.1.6", bool=False)
+
+ # Delete statement examples
+ c.delete(table, where)
+ c.delete("jdtest", where="id=6")
+
+"""
+
+import MySQLdb
+import MySQLdb.cursors
+
+class Mysql(object):
+ __instance = None
+ __session = None
+ __connection = None
+
+ def __init__(self, *args, **kwargs):
+ self.__host = kwargs.get('hostname')
+ self.__user = kwargs.get('user')
+ self.__password = kwargs.get('password')
+ self.__database = kwargs.get('database')
+ self.__stage = kwargs.get('stage', False)
+
+ self._mysql_conf_char = kwargs.get("encoding", "latin1")
+
+ def __open(self):
+ try:
+ conn = MySQLdb.connect(host=self.__host,
+ user=self.__user,
+ passwd=self.__password,
+ db=self.__database,
+ cursorclass=MySQLdb.cursors.DictCursor,
+ charset=self._mysql_conf_char)
+ self.__connection = conn
+ self.__session = conn.cursor()
+ #self.__connection.autocommit = True
+ except MySQLdb.Error as e:
+ print("MySQL Connection Error [%d]: %s" % (e.args[0], e.args[1]))
+
+ def __close(self):
+ try:
+ self.__session.close()
+ self.__connection.close()
+ except MySQLdb.Error as e:
+ print("MySQL Error Closing [%d]: %s" % (e.args[0], e.args[1]))
+
+ def insert(self, table, *args, **kwargs):
+ values = None
+ query = "INSERT INTO %s" % table
+ if kwargs:
+ keys = kwargs.keys()
+ values = kwargs.values()
+ query += "(" + ",".join(["%s"]*len(keys)) % tuple(keys) + ") VALUES(" + ",".join(["%s"]*len(values)) + ")"
+ elif args:
+ values = args
+ query += " VALUES(" + ",".join(["%s"]*len(values)) + ")"
+ if self.__stage is True:
+ print(query % tuple(values))
+ return True
+ self.__open()
+ try:
+ self.__session.execute(query, values)
+ except MySQLdb.Error as e:
+ print("MySQL Error Closing [%d]: %s" % (e.args[0], e.args[1]))
+ print(query % tuple(values))
+ self.__connection.rollback()
+ last_row = self.__session.lastrowid
+ self.__connection.commit()
+ self.__close()
+ return last_row
+
+ def select(self, table, *args, **kwargs):
+ result = None
+ keys = args
+ query = "SELECT " + ",".join(keys) + " FROM " + table
+ if kwargs.get('where') is not None:
+ query += " WHERE %s" % kwargs['where']
+ self.__open()
+ self.__session.execute(query)
+ result = self.__session.fetchall()
+ self.__connection.commit()
+ self.__close()
+ return result
+
+ def update(self, table, where, **kwargs):
+ values = kwargs.values()
+ update_list = ["" + key + "=%s" for key in kwargs.keys()]
+ query = "UPDATE " + table + " SET " + ",".join(update_list) + " WHERE " + where
+ if self.__stage is True:
+ print(query % tuple(values))
+ return True
+ self.__open()
+ try:
+ self.__session.execute(query, values)
+ except MySQLdb.Error as e:
+ print("MySQL Error Closing [%d]: %s" % (e.args[0], e.args[1]))
+ print(query % tuple(values))
+ self.__connection.rollback()
+ self.__connection.commit()
+ self.__close()
+
+ def delete(self, table, where):
+ query = "DELETE FROM %s WHERE %s" % (table, where)
+ if self.__stage is True:
+ print(query)
+ return True
+ self.__open()
+ try:
+ self.__session.execute(query)
+ except MySQLdb.Error as e:
+ print("MySQL Error Closing [%d]: %s" % (e.args[0], e.args[1]))
+ print(query)
+ self.__connection.rollback()
+ self.__connection.commit()
+ self.__close()
+
+ def call_store_procedure(self, name, *args):
+ result_sp = None
+ self.__open()
+ self.__session.callproc(name, args)
+ self.__connection.commit()
+ result_sp = self.__session.fetchall()
+ self.__close()
+ return result_sp
diff --git a/pool/shard009/Python/0087005_test_row_factories.py b/pool/shard009/Python/0087005_test_row_factories.py
new file mode 100644
index 0000000000000000000000000000000000000000..dea7fb49331f1529441ab0b58d89121a7f525cfb
--- /dev/null
+++ b/pool/shard009/Python/0087005_test_row_factories.py
@@ -0,0 +1,233 @@
+# Copyright DataStax, 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 tests.integration import get_server_versions, use_singledc, PROTOCOL_VERSION, BasicSharedKeyspaceUnitTestCaseWFunctionTable, BasicSharedKeyspaceUnitTestCase, execute_until_pass
+
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest # noqa
+
+from cassandra.cluster import Cluster, ResultSet
+from cassandra.query import tuple_factory, named_tuple_factory, dict_factory, ordered_dict_factory
+from cassandra.util import OrderedDict
+
+
+def setup_module():
+ use_singledc()
+
+
+class NameTupleFactory(BasicSharedKeyspaceUnitTestCase):
+
+ def setUp(self):
+ super(NameTupleFactory, self).setUp()
+ self.session.row_factory = named_tuple_factory
+ ddl = '''
+ CREATE TABLE {0}.{1} (
+ k int PRIMARY KEY,
+ v1 text,
+ v2 text,
+ v3 text)'''.format(self.ks_name, self.function_table_name)
+ self.session.execute(ddl)
+ execute_until_pass(self.session, ddl)
+
+ def test_sanitizing(self):
+ """
+ Test to ensure that same named results are surfaced in the NamedTupleFactory
+
+ Creates a table with a few different text fields. Inserts a few values in that table.
+ It then fetches the values and confirms that despite all be being selected as the same name
+ they are propagated in the result set differently.
+
+ @since 3.3
+ @jira_ticket PYTHON-467
+ @expected_result duplicate named results have unique row names.
+
+ @test_category queries
+ """
+
+ for x in range(5):
+ insert1 = '''
+ INSERT INTO {0}.{1}
+ ( k , v1, v2, v3 )
+ VALUES
+ ( 1 , 'v1{2}', 'v2{2}','v3{2}' )
+ '''.format(self.keyspace_name, self.function_table_name, str(x))
+ self.session.execute(insert1)
+
+ query = "SELECT v1 AS duplicate, v2 AS duplicate, v3 AS duplicate from {0}.{1}".format(self.ks_name, self.function_table_name)
+ rs = self.session.execute(query)
+ row = rs[0]
+ self.assertTrue(hasattr(row, 'duplicate'))
+ self.assertTrue(hasattr(row, 'duplicate_'))
+ self.assertTrue(hasattr(row, 'duplicate__'))
+
+
+class RowFactoryTests(BasicSharedKeyspaceUnitTestCaseWFunctionTable):
+ """
+ Test different row_factories and access code
+ """
+ def setUp(self):
+ super(RowFactoryTests, self).setUp()
+ self.insert1 = '''
+ INSERT INTO {0}.{1}
+ ( k , v )
+ VALUES
+ ( 1 , 1 )
+ '''.format(self.keyspace_name, self.function_table_name)
+
+ self.insert2 = '''
+ INSERT INTO {0}.{1}
+ ( k , v )
+ VALUES
+ ( 2 , 2 )
+ '''.format(self.keyspace_name, self.function_table_name)
+
+ self.select = '''
+ SELECT * FROM {0}.{1}
+ '''.format(self.keyspace_name, self.function_table_name)
+
+ def tearDown(self):
+ self.drop_function_table()
+
+ def test_tuple_factory(self):
+ session = self.session
+ session.row_factory = tuple_factory
+
+ session.execute(self.insert1)
+ session.execute(self.insert2)
+
+ result = session.execute(self.select)
+
+ self.assertIsInstance(result, ResultSet)
+ self.assertIsInstance(result[0], tuple)
+
+ for row in result:
+ self.assertEqual(row[0], row[1])
+
+ self.assertEqual(result[0][0], result[0][1])
+ self.assertEqual(result[0][0], 1)
+ self.assertEqual(result[1][0], result[1][1])
+ self.assertEqual(result[1][0], 2)
+
+ def test_named_tuple_factory(self):
+ session = self.session
+ session.row_factory = named_tuple_factory
+
+ session.execute(self.insert1)
+ session.execute(self.insert2)
+
+ result = session.execute(self.select)
+
+ self.assertIsInstance(result, ResultSet)
+ result = list(result)
+
+ for row in result:
+ self.assertEqual(row.k, row.v)
+
+ self.assertEqual(result[0].k, result[0].v)
+ self.assertEqual(result[0].k, 1)
+ self.assertEqual(result[1].k, result[1].v)
+ self.assertEqual(result[1].k, 2)
+
+ def test_dict_factory(self):
+ session = self.session
+ session.row_factory = dict_factory
+
+ session.execute(self.insert1)
+ session.execute(self.insert2)
+
+ result = session.execute(self.select)
+
+ self.assertIsInstance(result, ResultSet)
+ self.assertIsInstance(result[0], dict)
+
+ for row in result:
+ self.assertEqual(row['k'], row['v'])
+
+ self.assertEqual(result[0]['k'], result[0]['v'])
+ self.assertEqual(result[0]['k'], 1)
+ self.assertEqual(result[1]['k'], result[1]['v'])
+ self.assertEqual(result[1]['k'], 2)
+
+ def test_ordered_dict_factory(self):
+ session = self.session
+ session.row_factory = ordered_dict_factory
+
+ session.execute(self.insert1)
+ session.execute(self.insert2)
+
+ result = session.execute(self.select)
+
+ self.assertIsInstance(result, ResultSet)
+ self.assertIsInstance(result[0], OrderedDict)
+
+ for row in result:
+ self.assertEqual(row['k'], row['v'])
+
+ self.assertEqual(result[0]['k'], result[0]['v'])
+ self.assertEqual(result[0]['k'], 1)
+ self.assertEqual(result[1]['k'], result[1]['v'])
+ self.assertEqual(result[1]['k'], 2)
+
+
+class NamedTupleFactoryAndNumericColNamesTests(unittest.TestCase):
+ """
+ Test for PYTHON-122: Improve Error Handling/Reporting for named_tuple_factory and Numeric Column Names
+ """
+ @classmethod
+ def setup_class(cls):
+ cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION)
+ cls.session = cls.cluster.connect()
+ cls._cass_version, cls._cql_version = get_server_versions()
+ ddl = '''
+ CREATE TABLE test1rf.table_num_col ( key blob PRIMARY KEY, "626972746864617465" blob )
+ WITH COMPACT STORAGE'''
+ cls.session.execute(ddl)
+
+ @classmethod
+ def teardown_class(cls):
+ cls.session.execute("DROP TABLE test1rf.table_num_col")
+ cls.cluster.shutdown()
+
+ def test_no_exception_on_select(self):
+ """
+ no exception on SELECT for numeric column name
+ """
+ try:
+ self.session.execute('SELECT * FROM test1rf.table_num_col')
+ except ValueError as e:
+ self.fail("Unexpected ValueError exception: %s" % e.message)
+
+ def test_can_select_using_alias(self):
+ """
+ can SELECT "" AS aliases
+ """
+ if self._cass_version < (2, 0, 0):
+ raise unittest.SkipTest("Alias in SELECT not supported before 2.0")
+
+ try:
+ self.session.execute('SELECT key, "626972746864617465" AS my_col from test1rf.table_num_col')
+ except ValueError as e:
+ self.fail("Unexpected ValueError exception: %s" % e.message)
+
+ def test_can_select_with_dict_factory(self):
+ """
+ can SELECT numeric column using dict_factory
+ """
+ self.session.row_factory = dict_factory
+ try:
+ self.session.execute('SELECT * FROM test1rf.table_num_col')
+ except ValueError as e:
+ self.fail("Unexpected ValueError exception: %s" % e.message)
diff --git a/pool/shard009/Python/0087008_llff_test.py b/pool/shard009/Python/0087008_llff_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..82797cc31145bbbef40293ab71272d1b325af224
--- /dev/null
+++ b/pool/shard009/Python/0087008_llff_test.py
@@ -0,0 +1,153 @@
+# Copyright 2020 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.
+
+import os
+import numpy as np
+import imageio
+import torch
+import sys
+sys.path.append('../')
+from torch.utils.data import Dataset
+from .data_utils import random_crop, get_nearest_pose_ids
+from .llff_data_utils import load_llff_data, batch_parse_llff_poses
+
+
+class LLFFTestDataset(Dataset):
+ def __init__(self, args, mode, scenes=(), random_crop=True, **kwargs):
+ self.folder_path = os.path.join(args.rootdir, 'data/nerf_llff_data/')
+ self.args = args
+ self.mode = mode # train / test / validation
+ self.num_source_views = args.num_source_views
+ self.random_crop = random_crop
+ self.render_rgb_files = []
+ self.render_intrinsics = []
+ self.render_poses = []
+ self.render_train_set_ids = []
+ self.render_depth_range = []
+
+ self.train_intrinsics = []
+ self.train_poses = []
+ self.train_rgb_files = []
+
+ all_scenes = os.listdir(self.folder_path)
+ if len(scenes) > 0:
+ if isinstance(scenes, str):
+ scenes = [scenes]
+ else:
+ scenes = all_scenes
+
+ print("loading {} for {}".format(scenes, mode))
+ for i, scene in enumerate(scenes):
+ scene_path = os.path.join(self.folder_path, scene)
+ _, poses, bds, render_poses, i_test, rgb_files = load_llff_data(scene_path, load_imgs=False, factor=4)
+ near_depth = np.min(bds)
+ far_depth = np.max(bds)
+ intrinsics, c2w_mats = batch_parse_llff_poses(poses)
+
+ i_test = np.arange(poses.shape[0])[::self.args.llffhold]
+ i_train = np.array([j for j in np.arange(int(poses.shape[0])) if
+ (j not in i_test and j not in i_test)])
+
+ if mode == 'train':
+ i_render = i_train
+ else:
+ i_render = i_test
+
+ self.train_intrinsics.append(intrinsics[i_train])
+ self.train_poses.append(c2w_mats[i_train])
+ self.train_rgb_files.append(np.array(rgb_files)[i_train].tolist())
+ num_render = len(i_render)
+ self.render_rgb_files.extend(np.array(rgb_files)[i_render].tolist())
+ self.render_intrinsics.extend([intrinsics_ for intrinsics_ in intrinsics[i_render]])
+ self.render_poses.extend([c2w_mat for c2w_mat in c2w_mats[i_render]])
+ self.render_depth_range.extend([[near_depth, far_depth]]*num_render)
+ self.render_train_set_ids.extend([i]*num_render)
+
+ def __len__(self):
+ return len(self.render_rgb_files) * 100000 if self.mode == 'train' else len(self.render_rgb_files)
+
+ def __getitem__(self, idx):
+ idx = idx % len(self.render_rgb_files)
+ rgb_file = self.render_rgb_files[idx]
+ rgb = imageio.imread(rgb_file).astype(np.float32) / 255.
+ render_pose = self.render_poses[idx]
+ intrinsics = self.render_intrinsics[idx]
+ depth_range = self.render_depth_range[idx]
+
+ train_set_id = self.render_train_set_ids[idx]
+ train_rgb_files = self.train_rgb_files[train_set_id]
+ train_poses = self.train_poses[train_set_id]
+ train_intrinsics = self.train_intrinsics[train_set_id]
+
+ img_size = rgb.shape[:2]
+ camera = np.concatenate((list(img_size), intrinsics.flatten(),
+ render_pose.flatten())).astype(np.float32)
+
+ if self.mode == 'train':
+ if rgb_file in train_rgb_files:
+ id_render = train_rgb_files.index(rgb_file)
+ else:
+ id_render = -1
+ subsample_factor = np.random.choice(np.arange(1, 4), p=[0.2, 0.45, 0.35])
+ num_select = self.num_source_views + np.random.randint(low=-2, high=2)
+ else:
+ id_render = -1
+ subsample_factor = 1
+ num_select = self.num_source_views
+
+ nearest_pose_ids = get_nearest_pose_ids(render_pose,
+ train_poses,
+ min(self.num_source_views*subsample_factor, 28),
+ tar_id=id_render,
+ angular_dist_method='dist')
+ nearest_pose_ids = np.random.choice(nearest_pose_ids, min(num_select, len(nearest_pose_ids)), replace=False)
+
+ assert id_render not in nearest_pose_ids
+ # occasionally include input image
+ if np.random.choice([0, 1], p=[0.995, 0.005]) and self.mode == 'train':
+ nearest_pose_ids[np.random.choice(len(nearest_pose_ids))] = id_render
+
+ src_rgbs = []
+ src_cameras = []
+ for id in nearest_pose_ids:
+ src_rgb = imageio.imread(train_rgb_files[id]).astype(np.float32) / 255.
+ train_pose = train_poses[id]
+ train_intrinsics_ = train_intrinsics[id]
+
+ src_rgbs.append(src_rgb)
+ img_size = src_rgb.shape[:2]
+ src_camera = np.concatenate((list(img_size), train_intrinsics_.flatten(),
+ train_pose.flatten())).astype(np.float32)
+ src_cameras.append(src_camera)
+
+ src_rgbs = np.stack(src_rgbs, axis=0)
+ src_cameras = np.stack(src_cameras, axis=0)
+ if self.mode == 'train' and self.random_crop:
+ crop_h = np.random.randint(low=250, high=750)
+ crop_h = crop_h + 1 if crop_h % 2 == 1 else crop_h
+ crop_w = int(400 * 600 / crop_h)
+ crop_w = crop_w + 1 if crop_w % 2 == 1 else crop_w
+ rgb, camera, src_rgbs, src_cameras = random_crop(rgb, camera, src_rgbs, src_cameras,
+ (crop_h, crop_w))
+
+ depth_range = torch.tensor([depth_range[0] * 0.9, depth_range[1] * 1.6])
+
+ return {'rgb': torch.from_numpy(rgb[..., :3]),
+ 'camera': torch.from_numpy(camera),
+ 'rgb_path': rgb_file,
+ 'src_rgbs': torch.from_numpy(src_rgbs[..., :3]),
+ 'src_cameras': torch.from_numpy(src_cameras),
+ 'depth_range': depth_range,
+ }
+
diff --git a/pool/shard009/Python/0087015_migration_after_nichotplug.py b/pool/shard009/Python/0087015_migration_after_nichotplug.py
new file mode 100644
index 0000000000000000000000000000000000000000..f08f03506c42f69cb1263ffebfd7306e3a849fd3
--- /dev/null
+++ b/pool/shard009/Python/0087015_migration_after_nichotplug.py
@@ -0,0 +1,104 @@
+import logging
+import time
+from autotest.client.shared import error
+from virttest import utils_test, virt_vm, utils_net
+
+
+@error.context_aware
+def run(test, params, env):
+ """
+ KVM migration test:
+ 1) Get a live VM and clone it.
+ 2) Verify that the source VM supports migration. If it does, proceed with
+ the test.
+ 3) Hotplug a nic.
+ 4) Disable the primary link of guest.
+ 5) Check if new interface gets ip address.
+ 6) Ping guest's new ip from host.
+ 7) Re-enabling the primary link.
+ 8) Send a migration command to the source VM and wait until it's finished.
+ 9) Disable the primary link again.
+ 10) Ping guest's new ip from host.
+ 11) Re-enabling the primary link.
+
+ :param test: kvm test object.
+ :param params: Dictionary with test parameters.
+ :param env: Dictionary with the test environment.
+ """
+
+ def set_link(nic_name, up=False):
+ for nic in vm.virtnet:
+ if nic.nic_name != nic_name:
+ vm.set_link(nic.device_id, up=up)
+
+ vm = env.get_vm(params["main_vm"])
+ vm.verify_alive()
+ timeout = int(params.get("login_timeout", 360))
+ session = vm.wait_for_login(timeout=timeout)
+
+ guest_is_not_windows = (params.get("os_type") != 'windows')
+ run_dhclient = params.get("run_dhclient", "no")
+ mig_timeout = float(params.get("mig_timeout", "3600"))
+ nettype = params.get("nettype", "bridge")
+ netdst = params.get("netdst", "virbr0")
+ mig_protocol = params.get("migration_protocol", "tcp")
+ mig_cancel_delay = int(params.get("mig_cancel") == "yes") * 2
+ pci_model = params.get("pci_model")
+
+ # Modprobe the module if specified in config file
+ module = params.get("modprobe_module")
+ if guest_is_not_windows and module:
+ session.cmd_output("modprobe %s" % module)
+ if session:
+ session.close()
+
+ error.context("Add network devices through monitor cmd", logging.info)
+ nic_name = 'hotadded'
+ nic_info = vm.hotplug_nic(nic_model=pci_model, nic_name=nic_name,
+ netdst=netdst, nettype=nettype,
+ queues=params.get('queues'))
+ nic_mac = nic_info['mac']
+ vm.params['nics'] += " %s" % nic_name
+ vm.params['nic_model_%s' % nic_name] = nic_info['nic_model']
+
+ # Only run dhclient if explicitly set and guest is not running Windows.
+ # Most modern Linux guests run NetworkManager, and thus do not need this.
+ if run_dhclient == "yes" and guest_is_not_windows:
+ session_serial = vm.wait_for_serial_login(timeout=timeout)
+ ifname = utils_net.get_linux_ifname(session, nic_mac)
+ utils_net.restart_guest_network(session_serial, ifname)
+ # Guest need to take quite a long time to set the ip addr, sleep a
+ # while to wait for guest done.
+ time.sleep(60)
+
+ error.context("Disable the primary link of guest", logging.info)
+ set_link(nic_name, up=False)
+
+ error.context("Check if new interface gets ip address", logging.info)
+ try:
+ ip = vm.wait_for_get_address(nic_name)
+ except virt_vm.VMIPAddressMissingError:
+ raise error.TestFail("Could not get or verify ip address of nic")
+ logging.info("Got the ip address of new nic: %s", ip)
+
+ error.context("Ping guest's new ip from host", logging.info)
+ s, o = utils_test.ping(ip, 10, timeout=15)
+ if s != 0:
+ raise error.TestFail("New nic failed ping test with output:\n %s" % o)
+
+ error.context("Re-enabling the primary link", logging.info)
+ set_link(nic_name, up=True)
+
+ error.context("Migrate from source VM to Destination VM", logging.info)
+ vm.migrate(mig_timeout, mig_protocol, mig_cancel_delay)
+
+ error.context("Disable the primary link", logging.info)
+ set_link(nic_name, up=False)
+
+ error.context("Ping guest's new ip from host", logging.info)
+ s, o = utils_test.ping(ip, 10, timeout=15)
+ if s != 0:
+ raise error.TestFail("New nic failed ping test with output:\n %s" % o)
+
+ error.context("Re-enabling the primary link", logging.info)
+ set_link(nic_name, up=True)
diff --git a/pool/shard009/Python/0087022_tdb_util.py b/pool/shard009/Python/0087022_tdb_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..93c83a87910b7bc75fbc77192e6012c93c55c246
--- /dev/null
+++ b/pool/shard009/Python/0087022_tdb_util.py
@@ -0,0 +1,53 @@
+# Unix SMB/CIFS implementation.
+# Copyright (C) Lumir Balhar 2017
+#
+# 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 samba.tests
+from samba import ldb, Ldb
+from samba.tdb_util import tdb_copy
+import os
+
+
+class TDBUtilTests(samba.tests.TestCaseInTempDir):
+
+ def setUp(self):
+ super(TDBUtilTests, self).setUp()
+
+ def test_tdb_copy(self):
+ src_ldb_file = os.path.join(self.tempdir, "source.ldb")
+ dst_ldb_file = os.path.join(self.tempdir, "destination.ldb")
+
+ # Create LDB source file with some content
+ src_ldb = Ldb(src_ldb_file)
+ src_ldb.add({"dn": "f=dc", "b": "bla"})
+
+ # Copy source file to destination file and check return status
+ self.assertIsNone(tdb_copy(src_ldb_file, dst_ldb_file))
+
+ # Load copied file as LDB object
+ dst_ldb = Ldb(dst_ldb_file)
+
+ # Copmare contents of files
+ self.assertEqual(
+ src_ldb.searchone(basedn=ldb.Dn(src_ldb, "f=dc"), attribute="b"),
+ dst_ldb.searchone(basedn=ldb.Dn(dst_ldb, "f=dc"), attribute="b")
+ )
+
+ # Clean up
+ del src_ldb
+ del dst_ldb
+ os.unlink(src_ldb_file)
+ os.unlink(dst_ldb_file)
diff --git a/pool/shard009/Python/0087023_handlers.py b/pool/shard009/Python/0087023_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..702c577768ba5325937b0a48f62b43c152a32ca2
--- /dev/null
+++ b/pool/shard009/Python/0087023_handlers.py
@@ -0,0 +1,59 @@
+""" for now handlers will handle everything.
+ much of this needs to come from the carrier itself.
+"""
+from django.http import HttpRequest
+from parker.message import publish
+from parker.util import smartimport
+
+class Handler(object):
+ default_queue = None
+
+ def __call__(self, **kwargs):
+ for q in self.get_queues(**kwargs):
+ publish(q, self.get_message(**kwargs))
+
+ def get_queues(self, **kwargs):
+ """ this determines what queues a message goes too """
+ return self.default_queue
+
+ def get_message(self, **kwargs):
+ """ this determines the object that will be seriealized into the message """
+ raise NotImplemented
+
+class ModelHandler(Handler):
+
+ def __init__(self, queues, fields=None):
+ self.queues = queues
+ self.fields = fields
+
+ def get_queues(self, **kwargs):
+ return self.queues
+
+ def get_message(self, sender, instance, **kwargs):
+ fields = self.fields or [x.name for x in instance._meta.fields]
+ return dict([[field, getattr(instance, field)] for field in fields])
+
+
+class TastyPieHandler(Handler):
+ def __init__(self, queues, resource):
+ self.queues = queues
+ self.resource = resource
+
+ def get_message(self, sender, instance, **kwargs):
+ """ unfortunately the design of tastypie makes it hard to use it to just serialize objects
+ if you do much with the request in your resource this will break
+ """
+ if isinstance(self.resource, basestring):
+ self.resource = smartimport(self.resource)
+ resource = self.resource()
+ # is this the least disruptive way to to this?
+ def get_obj(**kwargs):
+ return instance
+ self.resource.get_obj = get_obj
+ # if anything tries to use this it will likely fail
+ req = HttpRequest()
+ bundle = resource.build_bundle(obj=instance)
+ bundle = resource.full_dehydrate(bundle)
+ # TODO: should we even support this? it seems likely to be request specific
+ bundle = resource.alter_detail_data_to_serialize(req, bundle)
+ return resource.serialize(req, bundle, 'application/json')
diff --git a/pool/shard009/Python/0087024_views.py b/pool/shard009/Python/0087024_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaf0f747958ecfdb653f5a25c3c5a50fe4ffda9e
--- /dev/null
+++ b/pool/shard009/Python/0087024_views.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import json
+import os
+
+from django.shortcuts import render
+from django.conf.global_settings import MEDIA_ROOT
+
+def index(request):
+ jsonFile = open(os.path.join(MEDIA_ROOT, 'testscript.json'))
+ return render(request, 'situation/index.html', {
+ 'script': json.dumps(json.load(jsonFile))
+ })
\ No newline at end of file
diff --git a/pool/shard009/Python/0087026_getSmackedDataNoNumpy.py b/pool/shard009/Python/0087026_getSmackedDataNoNumpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..f06d73633bd064ea8bee447dcbca87e4c914e922
--- /dev/null
+++ b/pool/shard009/Python/0087026_getSmackedDataNoNumpy.py
@@ -0,0 +1,167 @@
+#! /usr/bin/env python
+'''
+DESCRIPTION:
+Pulls out data from the SMAKCED wiki page
+and parses it into an array that is simple
+to manipulate and output.
+
+DEPENDS:
+BeautifulSoup
+
+TESTED:
+Python 2.5.2
+
+USAGE:
+python getSmackedData.py
+
+HISTORY:
+Created on Mar 26, 2010 (version 0.1)
+Removed NumPy dependency April 2, 2010 (version 0.2)
+
+@version: 0.2
+
+@author: Sami-Matias Niemi
+'''
+import urllib2, csv
+from BeautifulSoup import BeautifulSoup
+
+__author__ = 'Sami-Matias Niemi'
+__version__ = '0.2'
+
+class Smakced():
+ '''
+ A Class related to SMAKCED collaboration wiki page.
+ '''
+ def __init__(self, url, table):
+ '''
+ Constructor
+
+ @param url: url address of the page
+ @param table: name of the table
+ '''
+ self.url = url
+ self.table = table
+ self.address = self.url + self.table
+
+ def getData(self):
+ '''
+ Retrieve data from the SMAKCED web page.
+
+ @return: retrieved raw data
+ '''
+ hand = urllib2.urlopen(self.address)
+ data = hand.readlines()
+ hand.close()
+ return data
+
+ def parseTable(self, data):
+ '''
+ Parses html table data using BeautifulSoup.
+ Note that table number has been hard coded.
+ The SMAKCED wiki page returns several "tables".
+
+ @param data: data that has been retrieved with
+ the getData method
+ @return: array containing table entries
+ '''
+ tablenumber = 3
+ result = []
+ soup = BeautifulSoup(''.join(data))
+ t = soup.findAll('table')
+ table = t[tablenumber]
+ rows = table.findAll('tr')
+ for tr in rows:
+ line = []
+ cols = tr.findAll('td')
+ hdr = tr.findAll('th')
+ for th in hdr:
+ tmp = str(th.find(text = True))
+ x = tmp.replace(' ', '')
+ line.append(x)
+ for td in cols:
+ tmp = str(td.find(text = True))
+ x = tmp.replace(' ', '')
+ line.append(x)
+ result.append(line)
+ return result
+
+ def writeToFile(self, data, output):
+ '''
+ Writes an html page that contains tables to a file
+ in ascii format.
+ Uses BeautifulSoup for parsing tables.
+
+ @note: This method is untested.
+
+ @param data: data that has been retrieved with
+ the getData method
+ @param output: name of the output file
+ '''
+ g = open(output,'w')
+ soup = BeautifulSoup(''.join(data))
+ t = soup.findAll('table')
+ for table in t:
+ g.write('\nNew Table:\n')
+ rows = table.findAll('tr')
+ for tr in rows:
+ cols = tr.findAll('td')
+ hdr = tr.findAll('th')
+ for th in hdr:
+ try:
+ g.write(th.find(text = True))
+ g.write(',')
+ except: pass
+ for td in cols:
+ try:
+ g.write(td.find(text = True))
+ g.write(',')
+ except: pass
+ g.write("\n")
+ g.close()
+
+if __name__ == '__main__':
+ '''
+ Run when the script is run from the command line.
+ '''
+ #table address
+ smackedurl = 'http://smakced.pbworks.com'
+ tableName1 = '/Virgo1'
+
+ #class instance
+ SM1 = Smakced(smackedurl, tableName1)
+ #download data
+ data = SM1.getData()
+ #parse table
+ table = SM1.parseTable(data)
+
+ #data limitations, only objects that are marked
+ #to be observed at NOT2010 i.e. SMN targets
+ maskedData = [line for line in table if line[6] == 'NOT2010']
+ #if wish to have numerical criteria then something like
+ #maskedData = [line for line in table if flaot(line[x]) >= low_limit and float(line[x]) <= high_limit]
+ #should work
+
+ #output my targets to a file
+ output = open('SMNTargets.txt', 'w')
+ dump = csv.writer(output)
+ dump.writerow(table[0])
+ dump.writerows(maskedData)
+ output.close()
+
+ #make NOT TCS compatible object list file
+ output = open('NOTobjectlist.txt', 'w')
+ for line in maskedData:
+ str = 'VCC' + line[0].split()[0] + ' ' + line[8].replace(' ', ':')
+ str += ' ' + line[9].replace(' ', ':')
+ str += ' 2000 0 0 ' + line[13]
+ output.write(str + '\n')
+ output.close()
+
+ #make a file that can be pasted to the visibility plot software
+ output = open('visibility_plot.txt', 'w')
+ for line in maskedData:
+ str = 'VCC' + line[0].split()[0] + ' ' + line[8] + ' ' + line[9]
+ output.write(str + '\n')
+ output.close()
+
+ print 'All done...'
diff --git a/pool/shard009/Python/0087032_schema.py b/pool/shard009/Python/0087032_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..d78f2c0b9af751c0360e4fdfb8a5b83cb0f86ee2
--- /dev/null
+++ b/pool/shard009/Python/0087032_schema.py
@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+
+import os
+import json
+
+
+def get_schema_path():
+ return os.path.dirname(os.path.abspath(__file__))
+
+
+def load_schema(version):
+ filename = os.path.join(
+ get_schema_path(), 'schema_v{0}.json'.format(version))
+ with open(filename, 'r') as fp:
+ return json.load(fp)
+
+
diff --git a/pool/shard009/Python/0087036_xmpp_bridge.py b/pool/shard009/Python/0087036_xmpp_bridge.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6c54c35449b3a467c21af4ebe2b6f0cd1fe98bd
--- /dev/null
+++ b/pool/shard009/Python/0087036_xmpp_bridge.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python3
+########################################################################
+# File name: xmpp_bridge.py
+# This file is part of: aioxmpp
+#
+# LICENSE
+#
+# This program 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 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
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this program. If not, see
+# .
+#
+########################################################################
+import asyncio
+import asyncio.streams
+import os
+import signal
+import sys
+
+import aioxmpp
+
+
+async def stdout_writer():
+ """
+ This is a bit complex, as stdout can be a pipe or a file.
+
+ If it is a file, we cannot use
+ :meth:`asycnio.BaseEventLoop.connect_write_pipe`.
+ """
+ if sys.stdout.seekable():
+ # it’s a file
+ return sys.stdout.buffer.raw
+
+ if os.isatty(sys.stdin.fileno()):
+ # it’s a tty, use fd 0
+ fd_to_use = 0
+ else:
+ fd_to_use = 1
+
+ twrite, pwrite = await loop.connect_write_pipe(
+ asyncio.streams.FlowControlMixin,
+ os.fdopen(fd_to_use, "wb"),
+ )
+
+ swrite = asyncio.StreamWriter(
+ twrite,
+ pwrite,
+ None,
+ loop,
+ )
+
+ return swrite
+
+
+async def main(local, password, peer,
+ strip_newlines, add_newlines):
+ loop = asyncio.get_event_loop()
+ swrite = await stdout_writer()
+
+ sread = asyncio.StreamReader()
+ tread, pread = await loop.connect_read_pipe(
+ lambda: asyncio.StreamReaderProtocol(sread),
+ sys.stdin,
+ )
+
+ client = aioxmpp.Client(
+ local,
+ aioxmpp.make_security_layer(
+ password,
+ )
+ )
+
+ sigint = asyncio.Event()
+ loop.add_signal_handler(signal.SIGINT, sigint.set)
+ loop.add_signal_handler(signal.SIGTERM, sigint.set)
+
+ def recv(message):
+ body = message.body.lookup(
+ [aioxmpp.structs.LanguageRange.fromstr("*")]
+ )
+ if add_newlines:
+ body += "\n"
+ swrite.write(body.encode("utf-8"))
+
+ client.stream.register_message_callback(
+ "chat",
+ peer,
+ recv
+ )
+
+ sigint_future = asyncio.ensure_future(sigint.wait())
+ read_future = asyncio.ensure_future(sread.readline())
+
+ try:
+ async with client.connected() as stream:
+ # we send directed presence to the peer
+ pres = aioxmpp.Presence(
+ type_=aioxmpp.PresenceType.AVAILABLE,
+ to=peer,
+ )
+ await stream.send(pres)
+ while True:
+ done, pending = await asyncio.wait(
+ [
+ sigint_future,
+ read_future,
+ ],
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+
+ if sigint_future in done:
+ break
+
+ if read_future in done:
+ line = read_future.result().decode()
+ if not line:
+ break
+
+ if strip_newlines:
+ line = line.rstrip()
+
+ msg = aioxmpp.Message(
+ type_="chat",
+ to=peer,
+ )
+ msg.body[None] = line
+
+ await stream.send(msg)
+
+ read_future = asyncio.ensure_future(
+ sread.readline()
+ )
+
+ finally:
+ sigint_future.cancel()
+ read_future.cancel()
+
+
+def jid(s):
+ return aioxmpp.JID.fromstr(s)
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ description="""
+ Send lines from stdin to the given peer and print messages received
+ from the peer to stdout.""",
+ epilog="""
+ The password must be set in the XMPP_BRIDGE_PASSWORD environment
+ variable."""
+ )
+
+ parser.add_argument(
+ "--no-strip-newlines",
+ dest="strip_newlines",
+ action="store_false",
+ default=True,
+ help="Disable stripping newlines from stdin"
+ )
+
+ parser.add_argument(
+ "--no-add-newlines",
+ dest="add_newlines",
+ action="store_false",
+ default=True,
+ help="Disable adding newlines to stdout"
+ )
+
+ parser.add_argument(
+ "local",
+ help="JID to bind to",
+ type=jid,
+ )
+ parser.add_argument(
+ "peer",
+ help="JID of the peer to send messages to",
+ type=jid,
+ )
+
+ args = parser.parse_args()
+
+ try:
+ password = os.environ["XMPP_BRIDGE_PASSWORD"]
+ except KeyError:
+ parser.print_help()
+ print("XMPP_BRIDGE_PASSWORD is not set", file=sys.stderr)
+ sys.exit(1)
+
+ loop = asyncio.get_event_loop()
+ loop.run_until_complete(main(
+ args.local, password, args.peer,
+ args.strip_newlines,
+ args.add_newlines,
+ ))
+ loop.close()
diff --git a/pool/shard009/Python/0087038_include.py b/pool/shard009/Python/0087038_include.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc16e274851681f7a9b6edba822658a06d3d2519
--- /dev/null
+++ b/pool/shard009/Python/0087038_include.py
@@ -0,0 +1,13 @@
+import os
+from .resources import Resource
+
+class Include(object):
+ def __init__(self, dest, source, **kwargs):
+ super(Include, self).__init__()
+ self.dest = os.path.abspath(dest)
+ self.source = source
+ self.kwargs = kwargs
+ def to_resource(self):
+ return Resource.get_resource_type_from_string(self.source)(self.source, **self.kwargs)
+ def __repr__(self):
+ return self.source
diff --git a/pool/shard009/Python/0087039_wingman.py b/pool/shard009/Python/0087039_wingman.py
new file mode 100644
index 0000000000000000000000000000000000000000..793d520ba6879b09823f279ede65e2fdc9f5e21f
--- /dev/null
+++ b/pool/shard009/Python/0087039_wingman.py
@@ -0,0 +1,65 @@
+from go_to_adjacent_systems import *
+from go_somewhere_significant import *
+import vsrandom
+import launch
+import faction_ships
+import VS
+import Briefing
+import universe
+import unit
+import Director
+import gettext
+class wingman (Director.Mission):
+ def __init__ (self,price,factionname,numships,difficulty):
+ Director.Mission.__init__(self)
+ self.price=price
+ self.faction=factionname
+ self.you = VS.getPlayer()
+ self.numships=numships
+ self.diff=difficulty
+ self.adjsys=go_somewhere_significant (self.you,0,5000,0)
+ self.wingship = faction_ships.getRandomFighter(factionname)
+ nam = "[%s]" % self.wingship
+ self.adjsys.Print(_("Hello I'm waiting for your arrival at %s") ,self.wingship)
+ VS.IOmessage(1,self.wingship,"all",_("Once you meet me"))
+ VS.IOmessage(2,self.wingship,"all",_("I will obey your commands until our contracts expire."))
+
+ def GenerateWingmen(self):
+ if (self.you):
+ if (self.you.getCredits()>=self.price):
+ self.you.addCredits(-self.price)
+ lead=launch.launch_wave_around_unit(self.you.getFlightgroupName(),
+ self.you.getFactionName(),
+ self.wingship,
+ "default",
+ self.numships,
+ 500,
+ 1000,
+ self.you)
+ VS.IOmessage (0,lead.getName(),"all",_("I am at your service commander. Let us succeed!"))
+ else:
+ lead=launch.launch_wave_around_unit("ForHire",
+ self.faction,
+ self.wingship,
+ "default",
+ self.numships,
+ 500,
+ 1000,
+ self.you)
+ if (self.diff>0):
+ lead.SetTarget(self.you)
+ VS.IOmessage (0,lead.getName(),"all",_("You don't have the agreed money... prepare to DIE!"))
+ else:
+ VS.IOmessage (0,lead.getName(),"all",_("You don't have the money. A fool like you won't last long!"))
+ def Execute (self):
+
+ if (self.adjsys.Execute()):
+ self.GenerateWingmen()
+ VS.terminateMission(1)
+ def initbriefing(self):
+ print("ending briefing")
+ def loopbriefing(self):
+ print("loop briefing")
+ Briefing.terminate();
+ def endbriefing(self):
+ print("ending briefing")
diff --git a/pool/shard009/Python/0087040_cmd_diffdb.py b/pool/shard009/Python/0087040_cmd_diffdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..470b6cacb27987399baf2f800e5f40e945e4c8e1
--- /dev/null
+++ b/pool/shard009/Python/0087040_cmd_diffdb.py
@@ -0,0 +1,99 @@
+# ScatterBackup - A chaotic backup solution
+# Copyright (C) 2016 Ingo Ruhnke
+#
+# 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 argparse
+import os
+import scatterbackup.sbtr
+from scatterbackup.util import sb_init
+from scatterbackup.database import Database
+
+
+def path_excluded(path, excludes):
+ for ex in excludes:
+ if path.startswith(ex):
+ return True
+ return False
+
+
+def diff(db, oldpath, newpath, excludes, verbose=False):
+ oldglob = os.path.join(oldpath, '*')
+ newglob = os.path.join(newpath, '*')
+
+ oldfileinfos = db.get_by_glob(oldglob)
+
+ for oldfileinfo in oldfileinfos:
+ path = os.path.relpath(oldfileinfo.path, oldpath)
+
+ if path_excluded(path, excludes):
+ if verbose:
+ print("excluded {}".format(path))
+ continue
+
+ newfileinfo = db.get_one_by_path(os.path.join(newpath, path))
+ if newfileinfo is None:
+ print("removed {}".format(path))
+ else:
+ if oldfileinfo.blob == newfileinfo.blob:
+ if verbose:
+ print("ok {}".format(path))
+ else:
+ print("modified {}".format(path))
+
+ newfileinfos = db.get_by_glob(newglob)
+ for newfileinfo in newfileinfos:
+ path = os.path.relpath(newfileinfo.path, newpath)
+
+ if path_excluded(path, excludes):
+ if verbose:
+ print("excluded {}".format(path))
+ continue
+
+ oldfileinfo = db.get_one_by_path(os.path.join(oldpath, path))
+
+ if oldfileinfo is None:
+ print("added {}".format(path))
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Compare two .sbtr files')
+ parser.add_argument('OLDPATH', action='store', type=str, nargs=1,
+ help='old subtree')
+ parser.add_argument('NEWPATH', action='store', type=str, nargs=1,
+ help='new subtree')
+ parser.add_argument('-d', '--database', type=str, default=None,
+ help="Store results in database")
+ parser.add_argument('-e', '--exclude', type=str, action='append', default=[],
+ help="Subpath to exclude")
+ parser.add_argument('-v', '--verbose', action='store_true', default=False,
+ help="Be more verbose")
+ parser.add_argument('--debug-sql', action='store_true', default=False,
+ help="Debug SQL queries")
+ return parser.parse_args()
+
+
+def main():
+ sb_init()
+ args = parse_args()
+ db = Database(args.database or scatterbackup.util.make_default_database(), args.debug_sql)
+ diff(db,
+ os.path.abspath(args.OLDPATH[0]),
+ os.path.abspath(args.NEWPATH[0]),
+ [os.path.normpath(p) + "/" for p in args.exclude],
+ args.verbose)
+
+
+# EOF #
diff --git a/pool/shard009/Python/0087044_server.py b/pool/shard009/Python/0087044_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..e63edef52a3e64bfaf354db5b89633743d2e32ca
--- /dev/null
+++ b/pool/shard009/Python/0087044_server.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python
+#
+#
+# Wild Find
+#
+#
+# Copyright 2014 - 2017 Al Brown
+#
+# Wildlife tracking and mapping
+#
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as published by
+# the Free Software Foundation
+#
+# This program is distributed in the hope 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 BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
+from SocketServer import ThreadingMixIn
+import os
+import threading
+
+from wildfind.falconer.utils import get_resource_htdocs
+
+
+PORT = 12015
+
+
+class Server(object):
+ def __init__(self, heatmap):
+ handler = Handler
+ handler.heatmap = heatmap
+ self._server = ThreadedServer(('localhost', PORT), Handler)
+
+ thread = threading.Thread(target=self._server.serve_forever)
+ thread.start()
+
+ def close(self):
+ self._server.shutdown()
+
+
+class ThreadedServer(ThreadingMixIn, HTTPServer):
+ allow_reuse_address = False
+
+
+class Handler(BaseHTTPRequestHandler):
+ heatmap = None
+
+ def do_GET(self):
+ if self.path.startswith('/heatmap.png'):
+ self.send_response(200)
+ self.send_header('Content-type', 'image/png')
+ self.send_header('cache-control', 's-maxage=0 , no-cache')
+ self.end_headers()
+ self.heatmap.seek(0)
+ self.wfile.write(self.heatmap.read())
+ else:
+ path = get_resource_htdocs(self.path.lstrip('/'))
+
+ if os.path.exists(path):
+ self.send_response(200)
+ self.__send_content_type(path)
+ self.end_headers()
+
+ f = open(path, 'rb')
+ self.wfile.write(f.read())
+ f.close()
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, _format, *_args):
+ return
+
+ def __send_content_type(self, path):
+ content = 'text/plain'
+ _root, ext = os.path.splitext(path)
+ if ext == '.css':
+ content = 'text/css'
+ elif ext == '.html':
+ content = 'text/html'
+ elif ext == '.gif':
+ content = 'image/gif'
+ elif ext == '.js':
+ content = 'text/javascript'
+
+ self.send_header('Content-type', content)
+
+
+if __name__ == '__main__':
+ print 'Please run falconer.py'
+ exit(1)
diff --git a/pool/shard009/Python/0087045_markup.py b/pool/shard009/Python/0087045_markup.py
new file mode 100644
index 0000000000000000000000000000000000000000..6423215ed91fc0c3dcde12ff8ecbc8bd6adadc7c
--- /dev/null
+++ b/pool/shard009/Python/0087045_markup.py
@@ -0,0 +1,119 @@
+# -*- coding: utf-8 -*-
+from creoleparser.core import Parser
+from creoleparser.dialects import create_dialect, creole11_base, parse_args
+from creoleparser.elements import PreBlock, Table as BaseTable
+from django.core.urlresolvers import reverse
+from django.utils.safestring import mark_safe
+from genshi import builder, Markup
+from pygments import highlight
+from pygments.formatters import HtmlFormatter
+from pygments.lexers import get_lexer_by_name
+from pygments.styles.autumn import AutumnStyle
+from pygments.util import ClassNotFound
+from lug_people.models import MemberProfile
+
+global_cache = {}
+
+# This includes Markdown-style backticks for inline code.
+INLINE_MARKUP = [
+ ('**','strong'), ('//','em'), (',,','sub'),
+ ('^^','sup'), ('__','u'), ('##','code'),
+ ('`', 'code'), ('--','del'),
+]
+
+def build_interwikis():
+ from django.conf import settings
+ bases, spaces, classes = {}, {}, {}
+ for name, (base, space) in getattr(settings, 'INTERWIKIS', {}).items():
+ bases[name] = base
+ spaces[name] = space
+ classes[name] = lambda page: name + '-link'
+ return bases, spaces, classes
+
+
+def wiki_link_path(link):
+ if link.startswith("~"):
+ # User profile
+ return reverse('profile', args=[MemberProfile.make_username(link[1:])])
+ else:
+ # The only disallowed character is /.
+ # We turn it into - because it's most commonly used in dates.
+ return reverse('wiki_view', kwargs={'title': link.replace('/', '-')})
+
+
+def wiki_link_class(link):
+ if link.startswith("~"):
+ return 'user-link'
+ else:
+ return 'wiki-link'
+
+
+def get_pygments_formatter():
+ if 'formatter' not in global_cache:
+ global_cache['formatter'] = HtmlFormatter(style=AutumnStyle)
+ return global_cache['formatter']
+
+
+class Table(BaseTable):
+ def __init__(self, classes):
+ self.classes = classes
+ super(Table, self).__init__('table', '|')
+
+ def _build(self, mo, element_store, environ):
+ return super(Table, self)._build(mo, element_store, environ) \
+ (class_=self.classes)
+
+
+class CodeBlock(PreBlock):
+ # Code borrowed from Flask Website:
+ # https://github.com/mitsuhiko/flask/blob/website/flask_website/utils.py
+ def __init__(self):
+ super(CodeBlock, self).__init__('pre', ['{{{', '}}}'])
+
+ def _build(self, mo, element_store, environ):
+ lines = self.regexp2.sub(r'\1', mo.group(1)).splitlines()
+ if lines and lines[0].startswith('#!'):
+ try:
+ lexer = get_lexer_by_name(lines.pop(0)[2:].strip())
+ except ClassNotFound:
+ pass
+ else:
+ return Markup(highlight(u'\n'.join(lines), lexer,
+ get_pygments_formatter()))
+ return builder.tag.pre(u'\n'.join(lines))
+
+
+def create_lug_dialect():
+ iw_bases, iw_spaces, iw_classes = build_interwikis()
+
+ dialect = create_dialect(creole11_base,
+ # Markup customizations
+ simple_markup = INLINE_MARKUP,
+ indent_style = '',
+ indent_class = 'quote',
+ no_wiki_monospace = False,
+ # Internal links
+ wiki_links_base_url = "",
+ wiki_links_path_func = wiki_link_path,
+ wiki_links_class_func = wiki_link_class,
+ # Everyone else's links
+ external_links_class = 'external-link',
+ interwiki_links_base_urls = iw_bases,
+ interwiki_links_class_funcs = iw_classes,
+ interwiki_links_space_chars = iw_spaces
+ )
+ dialect.pre = CodeBlock()
+ dialect.table = Table('table table-striped table-bordered')
+ return dialect
+
+
+def get_parser():
+ if 'parser' not in global_cache:
+ global_cache['parser'] = Parser(dialect=create_lug_dialect(),
+ method='html')
+ return global_cache['parser']
+
+
+def render_markup(text):
+ return mark_safe(get_parser().render(text))
+
diff --git a/pool/shard009/Python/0087046_ticket_serv.py b/pool/shard009/Python/0087046_ticket_serv.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c1b40ebce2ce52523b972ceedf48c136e70f769
--- /dev/null
+++ b/pool/shard009/Python/0087046_ticket_serv.py
@@ -0,0 +1,39 @@
+import sys
+
+from restorm.examples.mock.api import TicketApiClient
+
+
+def main(argv):
+ """
+ Start with::
+
+ python -m restorm.examples.mock.library_serv [port or address:port]
+
+ """
+ ip_address = '127.0.0.1'
+ port = 8000
+
+ # This is an example. Your should do argument checking.
+ if len(argv) == 1:
+ ip_address_port = argv[0].split(':', 1)
+ if len(ip_address_port) == 1:
+ port = ip_address_port[0]
+ else:
+ ip_address, port = ip_address_port
+
+ # Create a playground HTTP server that handles requests from the
+ # ``LibraryApiClient``.
+ api = TicketApiClient('http://%s:%s/api/' % (ip_address, port))
+ server = api.create_server(ip_address, int(port))
+
+ print 'Mock ticket webservice is running at http://%s:%s/api/' % (ip_address, port)
+ print 'Quit the server with CTRL-C.'
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print 'Closing server...'
+ server.socket.close()
+
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
diff --git a/pool/shard009/Python/0087049_0034_fix_ipaddress_status_dhcp.py b/pool/shard009/Python/0087049_0034_fix_ipaddress_status_dhcp.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d068df355b6ef1c6539a94deed3205783afe30e
--- /dev/null
+++ b/pool/shard009/Python/0087049_0034_fix_ipaddress_status_dhcp.py
@@ -0,0 +1,20 @@
+from django.db import migrations
+
+
+def ipaddress_status_dhcp_to_slug(apps, schema_editor):
+ IPAddress = apps.get_model('ipam', 'IPAddress')
+ IPAddress.objects.filter(status='5').update(status='dhcp')
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('ipam', '0033_deterministic_ordering'),
+ ]
+
+ operations = [
+ # Fixes a missed integer substitution from #3569; see bug #4027. The original migration has also been fixed.
+ migrations.RunPython(
+ code=ipaddress_status_dhcp_to_slug
+ ),
+ ]
diff --git a/pool/shard009/Python/0087050_edeposit_amqp_antivirusd.py b/pool/shard009/Python/0087050_edeposit_amqp_antivirusd.py
new file mode 100644
index 0000000000000000000000000000000000000000..94c2a75c4feca47ddd26be0425b0211c76038270
--- /dev/null
+++ b/pool/shard009/Python/0087050_edeposit_amqp_antivirusd.py
@@ -0,0 +1,93 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Interpreter version: python 2.7
+#
+# Imports =====================================================================
+"""
+AMQP binding for ClamAV antivirus. See `edeposit.amqp.antivirus
+`_ for details.
+"""
+import os
+import sys
+import os.path
+import argparse
+
+
+from pika.exceptions import ConnectionClosed
+
+from edeposit.amqp.antivirus import *
+from edeposit.amqp.antivirus.structures import *
+
+
+# if the amqp module wasn't yet installed at this system, load it from package
+try:
+ from edeposit.amqp import settings
+except ImportError:
+ sys.path.insert(0, os.path.abspath('../edeposit/'))
+ import amqp
+ sys.modules["edeposit.amqp"] = amqp
+
+
+from edeposit.amqp.amqpdaemon import AMQPDaemon, getConParams
+from edeposit.amqp import settings
+
+
+# Functions & objects =========================================================
+def main(args, stop=False):
+ """
+ Arguments parsing, etc..
+ """
+ daemon = AMQPDaemon(
+ con_param=getConParams(
+ settings.RABBITMQ_ANTIVIRUS_VIRTUALHOST
+ ),
+ queue=settings.RABBITMQ_ANTIVIRUS_INPUT_QUEUE,
+ out_exch=settings.RABBITMQ_ANTIVIRUS_EXCHANGE,
+ out_key=settings.RABBITMQ_ANTIVIRUS_OUTPUT_KEY,
+ react_fn=reactToAMQPMessage,
+ glob=globals() # used in deserializer
+ )
+
+ if not stop and args.foreground: # run at foreground
+ daemon.run()
+ else:
+ daemon.run_daemon() # run as daemon
+
+
+# Main program ================================================================
+if __name__ == '__main__':
+ if len(sys.argv) > 1 and sys.argv[1] == "stop":
+ main(None, stop=True)
+ sys.exit(0)
+
+ parser = argparse.ArgumentParser(
+ usage='%(prog)s start/stop/restart [-f] FN',
+ description="""AMQP daemon for ClamAV antivirus."""
+ )
+ parser.add_argument(
+ "-f",
+ '--foreground',
+ action="store_true",
+ required=False,
+ help="""Run at foreground, not as daemon. If not set, script is will
+ run at background as unix daemon."""
+ )
+ parser.add_argument(
+ "action",
+ metavar="start/stop/restart",
+ type=str,
+ default=None,
+ help="Start/stop/restart the daemon."
+ )
+ args = parser.parse_args()
+
+ try:
+ main(args)
+ except ConnectionClosed as e:
+ sys.stderr.write(
+ e.message + " - is the RabbitMQ queues properly set?\n"
+ )
+ sys.exit(1)
+ except KeyboardInterrupt:
+ pass
diff --git a/pool/shard009/Python/0087053_ImageSweep.py b/pool/shard009/Python/0087053_ImageSweep.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd987cf3e3e78ab37ac54dd12c4fcc47fe41dcac
--- /dev/null
+++ b/pool/shard009/Python/0087053_ImageSweep.py
@@ -0,0 +1,86 @@
+# ----------------------------------------------------------------------
+# Numenta Platform for Intelligent Computing (NuPIC)
+# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and conditions apply:
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero Public License version 3 as
+# published by the Free Software Foundation.
+#
+# 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 Public License for more details.
+#
+# You should have received a copy of the GNU Affero Public License
+# along with this program. If not, see http://www.gnu.org/licenses.
+#
+# http://numenta.org/licenses/
+# ----------------------------------------------------------------------
+
+import os
+
+from nupic.vision.regions.ImageSensorExplorers.BaseExplorer import BaseExplorer
+
+
+class ImageSweep(BaseExplorer):
+
+ """
+ This explorer is like Flash, but it sends a reset signal whenever the
+ directory changes.
+ """
+
+ def next(self, seeking=False):
+ """
+ Go to the next position (next iteration).
+
+ seeking -- Boolean that indicates whether the explorer is calling next()
+ from seek(). If True, the explorer should avoid unnecessary computation
+ that would not affect the seek command. The last call to next() from
+ seek() will be with seeking=False.
+ """
+
+ self.position['reset'] = False
+ prevImage = self.position['image']
+
+ # Iterate through the filters
+ for i in xrange(self.numFilters):
+ self.position['filters'][i] += 1
+ if self.position['filters'][i] < self.numFilterOutputs[i]:
+ if not seeking:
+ # Center the image
+ self.centerImage()
+ return
+ self.position['filters'][i] = 0
+ # Go to the next image
+ self.position['image'] += 1
+ if self.position['image'] == self.numImages:
+ self.position['image'] = 0
+ if not seeking:
+ # Center the image
+ self.centerImage()
+
+ image = self.position['image']
+ if not self.getImageInfo(prevImage)['imagePath'] or \
+ (os.path.split(self.getImageInfo(image)['imagePath'])[0] !=
+ os.path.split(self.getImageInfo(prevImage)['imagePath'])[0]):
+ self.position['reset'] = True
+
+ def getNumIterations(self, image):
+ """
+ Get the number of iterations required to completely explore the input space.
+
+ Explorers that do not wish to support this method should not override it.
+
+ image -- If None, returns the sum of the iterations for all the loaded
+ images. Otherwise, image should be an integer specifying the image for
+ which to calculate iterations.
+
+ ImageSensor takes care of the input validation.
+ """
+
+ if image is not None:
+ return self.numFilteredVersionsPerImage
+ else:
+ return self.numFilteredVersionsPerImage * self.numImages
diff --git a/pool/shard009/Python/0087057_test_category.py b/pool/shard009/Python/0087057_test_category.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fc0b205a3321ab8ba5cf2479b4ed7680922e24b
--- /dev/null
+++ b/pool/shard009/Python/0087057_test_category.py
@@ -0,0 +1,42 @@
+"""
+Category tests
+"""
+from django.test import override_settings
+from django.test import TestCase
+
+from ozpcenter.scripts import sample_data_generator as data_gen
+import ozpcenter.api.category.model_access as model_access
+from ozpcenter import errors
+import ozpcenter.model_access as generic_model_access
+from ozpcenter import models
+
+
+@override_settings(ES_ENABLED=False)
+class CategoryTest(TestCase):
+
+ def setUp(self):
+ """
+ setUp is invoked before each test method
+ """
+ pass
+
+ @classmethod
+ def setUpTestData(cls):
+ """
+ Set up test data for the whole TestCase (only run once for the TestCase)
+ """
+ data_gen.run()
+
+ def test_get_non_existent_category_by_title(self):
+ category = model_access.get_category_by_title('Non Existent Category')
+ self.assertIsNone(category)
+
+ def test_get_non_existent_category_by_title_err(self):
+ self.assertRaises(models.Category.DoesNotExist, model_access.get_category_by_title, 'Not Existent', True)
+
+ def test_get_non_existent_category_by_id(self):
+ category = model_access.get_category_by_id(0)
+ self.assertIsNone(category)
+
+ def test_get_non_existent_category_by_id_err(self):
+ self.assertRaises(models.Category.DoesNotExist, model_access.get_category_by_id, 0, True)
diff --git a/pool/shard009/Python/0087061_introspection_from_schema.py b/pool/shard009/Python/0087061_introspection_from_schema.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0634860077d50a971049df713e99d55d8e0eb7b
--- /dev/null
+++ b/pool/shard009/Python/0087061_introspection_from_schema.py
@@ -0,0 +1,46 @@
+from typing import cast
+
+from ..error import GraphQLError
+from ..language import parse
+from ..type import GraphQLSchema
+from .get_introspection_query import get_introspection_query, IntrospectionQuery
+
+__all__ = ["introspection_from_schema"]
+
+
+def introspection_from_schema(
+ schema: GraphQLSchema,
+ descriptions: bool = True,
+ specified_by_url: bool = True,
+ directive_is_repeatable: bool = True,
+ schema_description: bool = True,
+ input_value_deprecation: bool = True,
+) -> IntrospectionQuery:
+ """Build an IntrospectionQuery from a GraphQLSchema
+
+ IntrospectionQuery is useful for utilities that care about type and field
+ relationships, but do not need to traverse through those relationships.
+
+ This is the inverse of build_client_schema. The primary use case is outside of the
+ server context, for instance when doing schema comparisons.
+ """
+ document = parse(
+ get_introspection_query(
+ descriptions,
+ specified_by_url,
+ directive_is_repeatable,
+ schema_description,
+ input_value_deprecation,
+ )
+ )
+
+ from ..execution.execute import execute_sync, ExecutionResult
+
+ result = execute_sync(schema, document)
+ if not isinstance(result, ExecutionResult): # pragma: no cover
+ raise RuntimeError("Introspection cannot be executed")
+ if result.errors: # pragma: no cover
+ raise result.errors[0]
+ if not result.data: # pragma: no cover
+ raise GraphQLError("Introspection did not return a result")
+ return cast(IntrospectionQuery, result.data)
diff --git a/pool/shard009/Python/0087070_test_node_tagging.py b/pool/shard009/Python/0087070_test_node_tagging.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bde0f2939b3122cec28cd82d708a199e81b13ab
--- /dev/null
+++ b/pool/shard009/Python/0087070_test_node_tagging.py
@@ -0,0 +1,63 @@
+import pytest
+from psqlgraph import PsqlGraphDriver
+
+from gdcdatamodel.models import basic, versioning # noqa
+from test.helpers import create_tables, truncate
+
+
+@pytest.fixture(scope='module')
+def bg():
+ """Fixture for database driver"""
+
+ cfg = {
+ 'host': 'localhost',
+ 'user': 'test',
+ 'password': 'test',
+ 'database': 'dev_models',
+ 'package_namespace': 'basic',
+ }
+
+ g = PsqlGraphDriver(**cfg)
+ create_tables(g.engine, namespace="basic")
+ yield g
+ truncate(g.engine, namespace="basic")
+
+
+@pytest.fixture(scope="module")
+def create_samples(sample_data, bg):
+ with bg.session_scope() as s:
+
+ version_2s = []
+ for node in sample_data:
+ # delay adding version 2
+ if node.node_id in ["a2b2d27a-6523-4ddd-8b2e-e94437a2aa23", "5ffb4b0e-969e-4643-8187-536ce7130e9c"]:
+ version_2s.append(node)
+ continue
+ s.add(node)
+ s.commit()
+ for v2 in version_2s:
+ s.add(v2)
+ yield
+
+ with bg.session_scope():
+ for n in sample_data:
+ bg.node_delete(n.node_id)
+
+
+@pytest.mark.parametrize("node_id, tag, version", [
+ ("be66197b-f6cc-4366-bded-365856ec4f63", "84044bd2-54a4-5837-b83d-f920eb97c18d", 1),
+ ("a2b2d27a-6523-4ddd-8b2e-e94437a2aa23", "84044bd2-54a4-5837-b83d-f920eb97c18d", 2),
+ ("813f97c4-dffc-4f94-b3f6-66a93476a233", "9a81bbad-b525-568c-b85d-d269a8bdc70a", 1),
+ ("6974c692-be47-4cb8-b8d6-9bd815983cd9", "55814b2f-fc23-5bed-9eab-c73c52c105df", 1),
+ ("5ffb4b0e-969e-4643-8187-536ce7130e9c", "55814b2f-fc23-5bed-9eab-c73c52c105df", 2),
+ ("c6a795f6-ee4a-4fcd-bfed-79348e07cd49", "8cc95392-5861-5524-8b98-a85e18d8294c", 1),
+ ("ed9aa864-1e40-4657-9378-7e3dc26551cc", "fddc5826-8853-5c1a-847d-5850d58ccb3e", 1),
+ ("fb69d25b-5c5d-4879-8955-8f2126e57524", "293d5dd3-117c-5a0a-8030-a428fdf2681b", 1),
+])
+def test_1(create_samples, bg, node_id, tag, version):
+
+ with bg.session_scope():
+ node = bg.nodes().get(node_id)
+ assert node.tag == tag
+ assert node.ver == version
+ assert versioning.compute_tag(node) == node.tag
diff --git a/pool/shard009/Python/0087072_views.py b/pool/shard009/Python/0087072_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..672165da3cd877deea499a997e8118fd53c8bd15
--- /dev/null
+++ b/pool/shard009/Python/0087072_views.py
@@ -0,0 +1,154 @@
+from Crypto.PublicKey import RSA
+
+from django.shortcuts import get_object_or_404
+
+from rest_framework import generics
+from rest_framework import status
+from rest_framework.exceptions import PermissionDenied
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.renderers import JSONRenderer
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from extras.api.renderers import FormlessBrowsableAPIRenderer, FreeRADIUSClientsRenderer
+from secrets.filters import SecretFilter
+from secrets.models import Secret, SecretRole, UserKey
+
+from . import serializers
+
+
+ERR_USERKEY_MISSING = "No UserKey found for the current user."
+ERR_USERKEY_INACTIVE = "UserKey has not been activated for decryption."
+ERR_PRIVKEY_INVALID = "Invalid private key."
+
+
+class SecretRoleListView(generics.ListAPIView):
+ """
+ List all secret roles
+ """
+ queryset = SecretRole.objects.all()
+ serializer_class = serializers.SecretRoleSerializer
+ permission_classes = [IsAuthenticated]
+
+
+class SecretRoleDetailView(generics.RetrieveAPIView):
+ """
+ Retrieve a single secret role
+ """
+ queryset = SecretRole.objects.all()
+ serializer_class = serializers.SecretRoleSerializer
+ permission_classes = [IsAuthenticated]
+
+
+class SecretListView(generics.GenericAPIView):
+ """
+ List secrets (filterable). If a private key is POSTed, attempt to decrypt each Secret.
+ """
+ queryset = Secret.objects.select_related('device__primary_ip4', 'device__primary_ip6', 'role')\
+ .prefetch_related('role__users', 'role__groups')
+ serializer_class = serializers.SecretSerializer
+ filter_class = SecretFilter
+ renderer_classes = [FormlessBrowsableAPIRenderer, JSONRenderer, FreeRADIUSClientsRenderer]
+ permission_classes = [IsAuthenticated]
+
+ def get(self, request, private_key=None):
+ queryset = self.filter_queryset(self.get_queryset())
+
+ # Attempt to decrypt each Secret if a private key was provided.
+ if private_key:
+ try:
+ uk = UserKey.objects.get(user=request.user)
+ except UserKey.DoesNotExist:
+ return Response(
+ {'error': ERR_USERKEY_MISSING},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+ if not uk.is_active():
+ return Response(
+ {'error': ERR_USERKEY_INACTIVE},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+ master_key = uk.get_master_key(private_key)
+ if master_key is not None:
+ for s in queryset:
+ if s.decryptable_by(request.user):
+ s.decrypt(master_key)
+ else:
+ return Response(
+ {'error': ERR_PRIVKEY_INVALID},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+
+ serializer = self.get_serializer(queryset, many=True)
+ return Response(serializer.data)
+
+ def post(self, request):
+ return self.get(request, private_key=request.POST.get('private_key'))
+
+
+class SecretDetailView(generics.GenericAPIView):
+ """
+ Retrieve a single Secret. If a private key is POSTed, attempt to decrypt the Secret.
+ """
+ queryset = Secret.objects.select_related('device__primary_ip4', 'device__primary_ip6', 'role')\
+ .prefetch_related('role__users', 'role__groups')
+ serializer_class = serializers.SecretSerializer
+ renderer_classes = [FormlessBrowsableAPIRenderer, JSONRenderer, FreeRADIUSClientsRenderer]
+ permission_classes = [IsAuthenticated]
+
+ def get(self, request, pk, private_key=None):
+ secret = get_object_or_404(Secret, pk=pk)
+
+ # Attempt to decrypt the Secret if a private key was provided.
+ if private_key:
+ try:
+ uk = UserKey.objects.get(user=request.user)
+ except UserKey.DoesNotExist:
+ return Response(
+ {'error': ERR_USERKEY_MISSING},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+ if not uk.is_active():
+ return Response(
+ {'error': ERR_USERKEY_INACTIVE},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+ if not secret.decryptable_by(request.user):
+ raise PermissionDenied(detail="You do not have permission to decrypt this secret.")
+ master_key = uk.get_master_key(private_key)
+ if master_key is None:
+ return Response(
+ {'error': ERR_PRIVKEY_INVALID},
+ status=status.HTTP_400_BAD_REQUEST
+ )
+ secret.decrypt(master_key)
+
+ serializer = self.get_serializer(secret)
+ return Response(serializer.data)
+
+ def post(self, request, pk):
+ return self.get(request, pk, private_key=request.POST.get('private_key'))
+
+
+class RSAKeyGeneratorView(APIView):
+ """
+ Generate a new RSA key pair for a user. Authenticated because it's a ripe avenue for DoS.
+ """
+ permission_classes = [IsAuthenticated]
+
+ def get(self, request):
+
+ # Determine what size key to generate
+ key_size = request.GET.get('key_size', 2048)
+ if key_size not in range(2048, 4097, 256):
+ key_size = 2048
+
+ # Export RSA private and public keys in PEM format
+ key = RSA.generate(key_size)
+ private_key = key.exportKey('PEM')
+ public_key = key.publickey().exportKey('PEM')
+
+ return Response({
+ 'private_key': private_key,
+ 'public_key': public_key,
+ })
diff --git a/pool/shard009/Python/0087077_rearrange_test.py b/pool/shard009/Python/0087077_rearrange_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..59069608f4ad652a5931a2ca3d7b1d12fef705da
--- /dev/null
+++ b/pool/shard009/Python/0087077_rearrange_test.py
@@ -0,0 +1,45 @@
+#!/usr/bin/env python3
+# 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
+#
+# 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 unittest
+
+from rearrange import rearrange_name
+
+class TestRearrange(unittest.TestCase):
+
+ def test_basic(self):
+ testcase = "Lovelace, Ada"
+ expected = "Ada Lovelace"
+ self.assertEqual(rearrange_name(testcase), expected)
+
+ def test_empty(self):
+ testcase = ""
+ expected = ""
+ self.assertEqual(rearrange_name(testcase), expected)
+
+ def test_double_name(self):
+ testcase = "Hopper, Grace M."
+ expected = "Grace M. Hopper"
+ self.assertEqual(rearrange_name(testcase), expected)
+
+ def test_one_name(self):
+ testcase = "Voltaire"
+ expected = "Voltaire"
+ self.assertEqual(rearrange_name(testcase), expected)
+
+# Run the tests
+unittest.main()
+
diff --git a/pool/shard009/Python/0087082_install.py b/pool/shard009/Python/0087082_install.py
new file mode 100644
index 0000000000000000000000000000000000000000..1df6174ca03d0018212f848678c3d603bf0b1d60
--- /dev/null
+++ b/pool/shard009/Python/0087082_install.py
@@ -0,0 +1,30 @@
+## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.
+## Use of this source code is governed by a BSD-style license that can be
+## found in the COPYING file.
+
+""" Install all the projects to the given dest
+"""
+
+import qisys.parsers
+import qisys.sh
+import qipkg.parsers
+
+def configure_parser(parser):
+ """Configure parser for this action"""
+ qipkg.parsers.pml_parser(parser)
+ parser.add_argument("--pkg", action="store_true", dest="pkg",
+ help="Generate and install .pkg files")
+ parser.add_argument("dest")
+ parser.set_defaults(pkg=False)
+
+def do(args):
+ """Main entry point"""
+ pml_builder = qipkg.parsers.get_pml_builder(args)
+ dest = args.dest
+ if args.pkg:
+ qisys.sh.mkdir(dest, recursive=True)
+ packages = pml_builder.package()
+ for package in packages:
+ qisys.sh.install(package, dest)
+ else:
+ pml_builder.install(dest)
diff --git a/pool/shard009/Python/0087094_handlers.py b/pool/shard009/Python/0087094_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b08ad4aa85f38a3d782ab1899bd05eb19c176f6
--- /dev/null
+++ b/pool/shard009/Python/0087094_handlers.py
@@ -0,0 +1,180 @@
+from __future__ import print_function, unicode_literals
+
+import socket
+import sys
+import time
+from functools import wraps
+from .errors import ClientException
+from .helpers import normalize_url
+from requests import Session
+from six import text_type
+from six.moves import cPickle # pylint: disable=F0401
+from threading import Lock
+from timeit import default_timer as timer
+
+
+class RateLimitHandler(object):
+ """The base handler that provides thread-safe rate limiting enforcement.
+
+ While this handler is threadsafe, the Client is not thread safe when the same
+ `Hutoma` instance is being utilized from multiple threads.
+
+ """
+
+ last_call = {} # Stores a two-item list: [lock, previous_call_time]
+ rl_lock = Lock() # lock used for adding items to last_call
+
+ @staticmethod
+ def rate_limit(function):
+ """Return a decorator that enforces API request limit guidelines.
+
+ We are allowed to make a API request every api_request_delay seconds as
+ specified in praw.ini. This value may differ from reddit to reddit. For
+ reddit.com it is 2. Any function decorated with this will be forced to
+ delay _rate_delay seconds from the calling of the last function
+ decorated with this before executing.
+
+ This decorator must be applied to a RateLimitHandler class method or
+ instance method as it assumes `rl_lock` and `last_call` are available.
+
+ """
+ @wraps(function)
+ def wrapped(cls, _rate_domain, _rate_delay, **kwargs):
+ cls.rl_lock.acquire()
+ lock_last = cls.last_call.setdefault(_rate_domain, [Lock(), 0])
+ with lock_last[0]: # Obtain the domain specific lock
+ cls.rl_lock.release()
+ # Sleep if necessary, then perform the request
+ now = timer()
+ delay = lock_last[1] + _rate_delay - now
+ if delay > 0:
+ now += delay
+ time.sleep(delay)
+ lock_last[1] = now
+ return function(cls, **kwargs)
+ return wrapped
+
+ @classmethod
+ def evict(cls, urls): # pylint: disable=W0613
+ """Method utilized to evict entries for the given urls.
+
+ :param urls: An iterable containing normalized urls.
+ :returns: The number of items removed from the cache.
+
+ By default this method returns False as a cache need not be present.
+
+ """
+ return 0
+
+ def __del__(self):
+ """Cleanup the HTTP session."""
+ if self.http:
+ try:
+ self.http.close()
+ except: # Never fail pylint: disable=W0702
+ pass
+
+ def __init__(self):
+ """Establish the HTTP session."""
+ self.http = Session() # Each instance should have its own session
+
+ def request(self, request, proxies, timeout, verify, **_):
+ """Responsible for dispatching the request and returning the result.
+
+ Network level exceptions should be raised and only
+ ``requests.Response`` should be returned.
+
+ :param request: A ``requests.PreparedRequest`` object containing all
+ the data necessary to perform the request.
+ :param proxies: A dictionary of proxy settings to be utilized for the
+ request.
+ :param timeout: Specifies the maximum time that the actual HTTP request
+ can take.
+ :param verify: Specifies if SSL certificates should be validated.
+
+ ``**_`` should be added to the method call to ignore the extra
+ arguments intended for the cache handler.
+
+ """
+ return self.http.send(request, proxies=proxies, timeout=timeout,
+ allow_redirects=False, verify=verify)
+RateLimitHandler.request = RateLimitHandler.rate_limit(RateLimitHandler.request)
+
+
+class DefaultHandler(RateLimitHandler):
+ """Extends the RateLimitHandler to add thread-safe caching support."""
+
+ ca_lock = Lock()
+ cache = {}
+ cache_hit_callback = None
+ timeouts = {}
+
+ @staticmethod
+ def with_cache(function):
+ """Return a decorator that interacts with a handler's cache.
+
+ This decorator must be applied to a DefaultHandler class method or
+ instance method as it assumes `cache`, `ca_lock` and `timeouts` are
+ available.
+
+ """
+ @wraps(function)
+ def wrapped(cls, _cache_key, _cache_ignore, _cache_timeout, **kwargs):
+ def clear_timeouts():
+ """Clear the cache of timed out results."""
+ for key in list(cls.timeouts):
+ if timer() - cls.timeouts[key] > _cache_timeout:
+ del cls.timeouts[key]
+ del cls.cache[key]
+
+ if _cache_ignore:
+ return function(cls, **kwargs)
+ with cls.ca_lock:
+ clear_timeouts()
+ if _cache_key in cls.cache:
+ if cls.cache_hit_callback:
+ cls.cache_hit_callback(_cache_key)
+ return cls.cache[_cache_key]
+ # Releasing the lock before actually making the request allows for
+ # the possibility of more than one thread making the same request
+ # to get through. Without having domain-specific caching (under the
+ # assumption only one request to a domain can be made at a
+ # time), there isn't a better way to handle this.
+ result = function(cls, **kwargs)
+ # The handlers don't call `raise_for_status` so we need to ignore
+ # status codes that will result in an exception that should not be
+ # cached.
+ if result.status_code not in (200, 302):
+ return result
+ with cls.ca_lock:
+ cls.timeouts[_cache_key] = timer()
+ cls.cache[_cache_key] = result
+ return result
+ return wrapped
+
+ @classmethod
+ def clear_cache(cls):
+ """Remove all items from the cache."""
+ with cls.ca_lock:
+ cls.cache = {}
+ cls.timeouts = {}
+
+ @classmethod
+ def evict(cls, urls):
+ """Remove items from cache matching URLs.
+
+ Return the number of items removed.
+
+ """
+ if isinstance(urls, text_type):
+ urls = [urls]
+ urls = set(normalize_url(url) for url in urls)
+ retval = 0
+ with cls.ca_lock:
+ for key in list(cls.cache):
+ if key[0] in urls:
+ retval += 1
+ del cls.cache[key]
+ del cls.timeouts[key]
+ return retval
+DefaultHandler.request = DefaultHandler.with_cache(RateLimitHandler.request)
diff --git a/pool/shard009/Python/0087098_cleanDb.py b/pool/shard009/Python/0087098_cleanDb.py
new file mode 100644
index 0000000000000000000000000000000000000000..b08ed1b8bdbe84648088ce06aef16bafc6c56ed8
--- /dev/null
+++ b/pool/shard009/Python/0087098_cleanDb.py
@@ -0,0 +1,43 @@
+from .seguinus.easyPoS.models import DonneesEntreprise, LigneFacture, PreparationFacture, Produit, LogFacture
+from .seguinus.chambres.models import Client
+from .seguinus.chambres.models import Reservation, TourOperateur, CacheJour
+from .seguinus.easyPoS.models import Facture
+from .seguinus.collectage.models import Employe, Personne
+from datetime import datetime, date, timedelta, time
+from django.contrib.admin.models import LogEntry
+import os
+
+from django.conf import settings
+
+
+def vacuum_db():
+ from django.db import connection
+ cursor = connection.cursor()
+ cursor.execute("VACUUM")
+ connection.close()
+
+
+def vacu():
+ print("Vacuuming database...")
+ before = os.stat(settings.DATABASE_NAME).st_size
+ print("Size before: %s bytes" % before)
+ vacuum_db()
+ after = os.stat(settings.DATABASE_NAME).st_size
+ print("Size after: %s bytes" % after)
+ print("Reclaimed: %s bytes" % (before - after))
+
+
+def delTout(tout):
+ tout.delete()
+
+
+def allege():
+ today = date.today()
+ delTout(Reservation.objects.filter(dateDepart__lt=today))
+ delTout(Facture.objects.filter(etat='C'))
+ delTout(LogFacture.objects.all())
+ delTout(CacheJour.objects.all())
+ delTout(Employe.objects.all())
+ delTout(Personne.objects.all())
+ delTout(LogEntry.objects.all())
+ vacu()
diff --git a/pool/shard009/Python/0087104_test.py b/pool/shard009/Python/0087104_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..59fb602867595483b979ca090d3e14f8b3fdfe4f
--- /dev/null
+++ b/pool/shard009/Python/0087104_test.py
@@ -0,0 +1,57 @@
+from SICP.lisp_parser.lp import parse
+import unittest
+
+class LispParserTest(unittest.TestCase):
+ def test_simple(self):
+ code = """
+ (define (gcd a b)
+ (if (= b 0)
+ a
+ (gcd b (rem a b))))
+ """
+ self.assertEqual(parse(code),
+ ['define', ['gcd', 'a', 'b'],
+ ['if', ['=', 'b', 0],
+ 'a',
+ ['gcd', 'b', ['rem', 'a', 'b']]]]
+ )
+
+ def test_simpler(self):
+ self.assertEqual(parse('3'), 3)
+ self.assertEqual(parse('-3.34'), -3.34)
+ self.assertEqual(parse('"abc"'), '"abc"')
+ self.assertEqual(parse("'a"), ['quote', 'a'])
+
+ def test_string(self):
+ code = """
+ (define (fib n)
+ "Computes nth fibonacci number"
+ (if (< n 2)
+ n
+ (+ (fib (- n 1)) (fib (- n 2)))))
+ """
+ self.assertEqual(parse(code),
+ ['define', ['fib', 'n'],
+ '"Computes nth fibonacci number"',
+ ['if', ['<', 'n', 2],
+ 'n',
+ ['+', ['fib', ['-', 'n', 1]],
+ ['fib', ['-', 'n', 2]]]]]
+ )
+
+ def test_quotes(self):
+ code = """
+ (define his-name ''(kenjin che))
+ """
+ self.assertEqual(parse(code),
+ ['define', 'his-name', ['quote', ['quote', ['kenjin', 'che']]]]
+ )
+
+ def test_dot(self):
+ self.assertEqual(parse("(a . b)"),
+ ['a', ['dot', 'b']])
+
+ with self.assertRaises(ValueError):
+ print(parse("(a . b c)"))
+
+unittest.main()
diff --git a/pool/shard009/Python/0087106_data_fetcher.py b/pool/shard009/Python/0087106_data_fetcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..32db3d65c2d19a9c82d1e226062bba4443c02f52
--- /dev/null
+++ b/pool/shard009/Python/0087106_data_fetcher.py
@@ -0,0 +1,64 @@
+# The MIT License (MIT)
+# Copyright (c) 2017 Massachusetts Institute of Technology
+#
+# Authors: Cody Rude
+# This software has been created in projects supported by the US National
+# Science Foundation and NASA (PI: Pankratius)
+#
+# 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.
+
+
+# Skdaccess imports
+from skdaccess.framework.data_class import DataFetcherStream, ImageWrapper
+from skdaccess.framework.param_class import *
+
+
+# Standard library imports
+from collections import OrderedDict
+
+# 3rd part imports
+from six.moves.urllib.request import urlopen
+from skimage.io import imread
+from astropy.io import fits
+import warnings
+
+class DataFetcher(DataFetcherStream):
+ '''
+ Data Fetcher for the Solar Dynamics Observatory
+ '''
+
+ def __init__(self, ap_paramList):
+ '''
+ Initialize Solar Dynamics Observatory
+
+ @param ap_paramList[url_list]: Autolist of URLS to access
+ '''
+ super(DataFetcher, self).__init__(ap_paramList)
+
+ def output(self):
+ '''
+ Generate data wrapper
+
+ @return data wrapper of SDO data
+ '''
+ url_list = self.ap_paramList[0]()
+
+ metadata, data = self.retrieveOnlineData(url_list)
+
+ return ImageWrapper(data, meta_data = metadata)
+
diff --git a/pool/shard009/Python/0087108_server.py b/pool/shard009/Python/0087108_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e24549bab040900fac18872a5261344d4297615
--- /dev/null
+++ b/pool/shard009/Python/0087108_server.py
@@ -0,0 +1,74 @@
+import tornado.httpserver
+import tornado.ioloop
+import tornado.web
+import tornado.options
+
+from framework.dependency_management.dependency_resolver import BaseComponent
+from framework.interface import urls
+from framework.lib.owtf_process import OWTFProcess
+
+
+class InterfaceServer(OWTFProcess, BaseComponent):
+ def pseudo_run(self):
+ self.get_component("core").disable_console_logging()
+ config = self.get_component("config")
+ db_config = self.get_component("db_config")
+ db = self.get_component("db")
+ application = tornado.web.Application(
+ handlers=urls.get_handlers(),
+ template_path=config.FrameworkConfigGet('INTERFACE_TEMPLATES_DIR'),
+ debug=False,
+ gzip=True,
+ static_path=config.FrameworkConfigGet('STATICFILES_DIR'),
+ compiled_template_cache=False
+ )
+ self.server = tornado.httpserver.HTTPServer(application)
+ try:
+ ui_port = int(config.FrameworkConfigGet("UI_SERVER_PORT"))
+ ui_address = config.FrameworkConfigGet("SERVER_ADDR")
+ self.server.bind(ui_port, address=ui_address)
+ tornado.options.parse_command_line(
+ args=['dummy_arg', '--log_file_prefix=%s' % db_config.Get('UI_SERVER_LOG'), '--logging=info'])
+ self.server.start(0)
+ db.create_session()
+ tornado.ioloop.IOLoop.instance().start()
+ except KeyboardInterrupt:
+ pass
+
+
+class FileServer(BaseComponent):
+
+ def start(self):
+ try:
+ self.worker_manager = self.get_component("worker_manager")
+ self.get_component("core").disable_console_logging()
+ config = self.get_component("config")
+ db = self.get_component("db")
+ self.application = tornado.web.Application(
+ handlers=urls.get_file_server_handlers(),
+ template_path=config.FrameworkConfigGet('INTERFACE_TEMPLATES_DIR'),
+ debug=False,
+ gzip=True
+ )
+ self.application.Core = self.get_component("core")
+ self.server = tornado.httpserver.HTTPServer(self.application)
+ fileserver_port = int(config.FrameworkConfigGet("FILE_SERVER_PORT"))
+ fileserver_addr = config.FrameworkConfigGet("SERVER_ADDR")
+ self.server.bind(fileserver_port, address=fileserver_addr)
+ tornado.options.parse_command_line(
+ args=['dummy_arg', '--log_file_prefix=%s' % db.Config.Get('FILE_SERVER_LOG'), '--logging=info'])
+ self.server.start(1)
+ # 'self.manage_cron' is an instance of class 'tornado.ioloop.PeriodicCallback',
+ # it schedules the given callback to be called periodically.
+ # The callback is called every 2000 milliseconds.
+ self.manager_cron = tornado.ioloop.PeriodicCallback(self.worker_manager.manage_workers, 2000)
+ self.manager_cron.start()
+ tornado.ioloop.IOLoop.instance().start()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ self.clean_up()
+
+ def clean_up(self):
+ """Properly stop any tornado callbacks."""
+ self.manager_cron.stop()
diff --git a/pool/shard009/Python/0087110_util.py b/pool/shard009/Python/0087110_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..b67fe4018641a717b471efed79a3c5afa680515c
--- /dev/null
+++ b/pool/shard009/Python/0087110_util.py
@@ -0,0 +1,22 @@
+import sys
+import os
+
+interactive = True
+
+def error(msg):
+ _write_msg("error: " + msg)
+
+def warning(msg):
+ _write_msg("warning: " + msg)
+
+def info(msg):
+ _write_msg(msg)
+
+def _write_msg(msg):
+ if not interactive:
+ sys.stderr.write(msg + "\n")
+ else:
+ print("I" + msg)
+
+def file_exists(filename):
+ return os.path.isfile(filename)
diff --git a/pool/shard009/Python/0087111_recipe-226409.py b/pool/shard009/Python/0087111_recipe-226409.py
new file mode 100644
index 0000000000000000000000000000000000000000..682b3c210a2c5f4ecb824f737d4069c72c70a44a
--- /dev/null
+++ b/pool/shard009/Python/0087111_recipe-226409.py
@@ -0,0 +1,15 @@
+import os
+import shutil
+
+def lower_names(dir):
+ assert(os.path.isdir(dir))
+ [os.rename( os.path.join( dir, file ),
+ os.path.join( dir, file.lower() ))
+ for file in os.listdir(dir)]
+def get_dir():
+ input = raw_input('Enter Directory Name: ')
+ return input
+
+if __name__ == '__main__':
+ dir = get_dir()
+ lower_names(dir)
diff --git a/pool/shard009/Python/0087119_sysconfig.py b/pool/shard009/Python/0087119_sysconfig.py
new file mode 100644
index 0000000000000000000000000000000000000000..92bda794627fde1648d2c15fed042f7072a6aa10
--- /dev/null
+++ b/pool/shard009/Python/0087119_sysconfig.py
@@ -0,0 +1,63 @@
+"""
+Helper functions for managing certain system actions.
+
+arkOS Core
+(c) 2016 CitizenWeb
+Written by Jacob Cook
+Licensed under GPLv3, see LICENSE.md
+"""
+
+import os
+
+from arkos import signals
+from arkos.utilities import shell
+
+
+def shutdown():
+ """Shutdown the system."""
+ signals.emit("config", "shutdown")
+ shell("shutdown -P now")
+
+
+def reload():
+ """Reload krakend."""
+ signals.emit("config", "reload")
+ shell("systemctl restart krakend")
+
+
+def reboot():
+ """Reboot the system."""
+ signals.emit("config", "shutdown")
+ shell("reboot")
+
+
+def get_hostname():
+ """Get system hostname."""
+ with open("/etc/hostname", "r") as f:
+ return f.read().rstrip("\n")
+
+
+def set_hostname(name):
+ """Set system hostname."""
+ with open("/etc/hostname", "w") as f:
+ f.write(name)
+ signals.emit("config", "hn_changed", name)
+
+
+def get_timezone():
+ """Get current timezone. Returns ``region`` and ``zone`` in dict."""
+ zone = os.path.realpath("/etc/localtime").split("/usr/share/zoneinfo/")[1]
+ zone = zone.split("/")
+ return {"region": zone[0], "zone": zone[1] if len(zone) > 1 else None}
+
+
+def set_timezone(region, zone=None):
+ """Set system timezone."""
+ if zone and zone not in ["GMT", "UTC"]:
+ zonepath = os.path.join("/usr/share/zoneinfo", region, zone)
+ else:
+ zonepath = os.path.join("/usr/share/zoneinfo", region)
+ if os.path.exists("/etc/localtime"):
+ os.remove("/etc/localtime")
+ os.symlink(zonepath, "/etc/localtime")
+ signals.emit("config", "tz_changed", (region, zone))
diff --git a/pool/shard009/Python/0087124_sparse_linalg_onenormest.py b/pool/shard009/Python/0087124_sparse_linalg_onenormest.py
new file mode 100644
index 0000000000000000000000000000000000000000..78d0ba68ea18d7a03dd209054bf4152610e047f9
--- /dev/null
+++ b/pool/shard009/Python/0087124_sparse_linalg_onenormest.py
@@ -0,0 +1,55 @@
+"""Compare the speed of exact one-norm calculation vs. its estimation.
+"""
+from __future__ import division, print_function, absolute_import
+
+import numpy as np
+
+try:
+ import scipy.sparse.linalg
+ import scipy.sparse
+except ImportError:
+ pass
+
+from .common import Benchmark
+
+
+class BenchmarkOneNormEst(Benchmark):
+ params = [
+ [2, 3, 5, 10, 30, 100, 300, 500, 1000, 1e4, 1e5, 1e6],
+ ['exact', 'onenormest']
+ ]
+ param_names = ['n', 'solver']
+
+ def setup(self, n, solver):
+ np.random.seed(1234)
+ nrepeats = 100
+ shape = (n, n)
+
+ if n <= 1000:
+ # Sample the matrices.
+ self.matrices = []
+ for i in range(nrepeats):
+ M = np.random.randn(*shape)
+ self.matrices.append(M)
+ else:
+ if solver == 'exact':
+ raise NotImplementedError()
+
+ max_nnz = 100000
+ nrepeats = 1
+
+ self.matrices = []
+ for i in range(nrepeats):
+ M = scipy.sparse.rand(shape[0], shape[1], min(max_nnz / (shape[0] * shape[1]), 1e-5))
+ self.matrices.append(M)
+
+ def time_onenormest(self, n, solver):
+ if solver == 'exact':
+ # Get the exact values of one-norms of squares.
+ for M in self.matrices:
+ M.dot(M)
+ scipy.sparse.linalg.matfuncs._onenorm(M)
+ elif solver == 'onenormest':
+ # Get the estimates of one-norms of squares.
+ for M in self.matrices:
+ scipy.sparse.linalg.matfuncs._onenormest_matrix_power(M, 2)
diff --git a/pool/shard009/Python/0087126_test.py b/pool/shard009/Python/0087126_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..a27a3333bd1b1fc21460c99fd01d72ee26c3b933
--- /dev/null
+++ b/pool/shard009/Python/0087126_test.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+
+'''Test of IXFR freeze.'''
+
+from dnstest.test import Test
+
+t = Test()
+
+master = t.server("knot")
+slave = t.server("knot")
+zone = t.zone_rnd(1, records=50)
+
+t.link(zone, master, slave)
+
+t.start()
+
+serial_init = master.zone_wait(zone)
+slave.zone_wait(zone)
+
+master.ctl("zone-xfr-freeze", wait=True)
+master.random_ddns(zone, allow_empty=False)
+t.sleep(4)
+
+resp = master.dig(zone[0].name, "AXFR", tries=1)
+resp.check_xfr(rcode="REFUSED")
+
+resp = slave.dig(zone[0].name, "SOA")
+serial = resp.soa_serial()
+if serial != serial_init:
+ set_err("SOA serial mismatch")
+ detail_log("SOA serial mismatch %d != %d" % (serial, serial_init))
+
+master.ctl("zone-xfr-thaw", wait=True)
+master.ctl("zone-notify")
+slave.zone_wait(zone, serial_init)
+t.xfr_diff(master, slave, zone)
+
+t.end()
diff --git a/pool/shard009/Python/0087128_test_middleware.py b/pool/shard009/Python/0087128_test_middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..006d1e8ee0ae71423ccb2f9b6f9ad54cf8924f1d
--- /dev/null
+++ b/pool/shard009/Python/0087128_test_middleware.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, unicode_literals
+import unittest
+from datetime import datetime
+
+from scrapy.exceptions import NotConfigured
+from scrapy.utils.test import get_crawler
+
+from history.middleware import HistoryMiddleware
+
+MANDATORY_SETTINGS = ['HISTORY_S3_BUCKET',
+ 'AWS_ACCESS_KEY_ID',
+ 'AWS_SECRET_ACCESS_KEY']
+
+
+class TestHistoryMiddleware(unittest.TestCase):
+
+ def setUp(self):
+ settings_dict = {k: 'mock setting' for k in MANDATORY_SETTINGS}
+ crawler = get_crawler(settings_dict=settings_dict)
+ self.middleware = HistoryMiddleware(crawler)
+
+ def test_unconfigured_init(self):
+ with self.assertRaises(NotConfigured):
+ self.middleware = HistoryMiddleware(get_crawler())
+
+ def test_parse_booleannd_dt_epoch(self):
+ self.assertTrue(HistoryMiddleware.parse_epoch('True'))
+ self.assertFalse(HistoryMiddleware.parse_epoch('False'))
+ self.assertTrue(HistoryMiddleware.parse_epoch(True))
+ self.assertFalse(HistoryMiddleware.parse_epoch(False))
+
+ some_dt = datetime.now()
+ self.assertEqual(HistoryMiddleware.parse_epoch(some_dt), some_dt)
+
+ def test_parse_human_epoch(self):
+ self.assertIsInstance(self.middleware.parse_epoch('yesterday'), datetime)
diff --git a/pool/shard009/Python/0087129_test_db_models.py b/pool/shard009/Python/0087129_test_db_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..74dc8315da6ee918eed64a418f3704e7cc8f38d7
--- /dev/null
+++ b/pool/shard009/Python/0087129_test_db_models.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2014 Mirantis, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, 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 random import randint
+
+from nailgun.db.sqlalchemy.models import Cluster
+from nailgun.test.base import BaseTestCase
+
+
+class TestDbModels(BaseTestCase):
+
+ def test_cluster_fuel_version_length(self):
+ fuel_version = 'a' * 1024
+ cluster_data = {
+ 'name': 'cluster-api-' + str(randint(0, 1000000)),
+ 'fuel_version': fuel_version,
+ 'release_id': self.env.create_release(api=False).id
+ }
+
+ cluster = Cluster(**cluster_data)
+ self.db.add(cluster)
+ self.db.commit()
diff --git a/pool/shard009/Python/0087130_test_copy.py b/pool/shard009/Python/0087130_test_copy.py
new file mode 100644
index 0000000000000000000000000000000000000000..75f84eff2d8969f25c9f87112f9ecfced8a64ff2
--- /dev/null
+++ b/pool/shard009/Python/0087130_test_copy.py
@@ -0,0 +1,55 @@
+from hc.api.models import Check
+from hc.test import BaseTestCase
+
+
+class CopyCheckTestCase(BaseTestCase):
+ def setUp(self):
+ super().setUp()
+ self.check = Check(project=self.project)
+ self.check.name = "Foo"
+ self.check.slug = "foo"
+ self.check.subject = "success-keyword"
+ self.check.subject_fail = "failure-keyword"
+ self.check.methods = "POST"
+ self.check.manual_resume = True
+ self.check.save()
+
+ self.copy_url = "/checks/%s/copy/" % self.check.code
+
+ def test_it_works(self):
+ self.client.login(username="alice@example.org", password="password")
+ r = self.client.post(self.copy_url, follow=True)
+ self.assertContains(r, "This is a brand new check")
+
+ copy = Check.objects.get(name="Foo (copy)")
+ self.assertEqual(copy.slug, "foo-copy")
+ self.assertEqual(copy.subject, "success-keyword")
+ self.assertEqual(copy.subject_fail, "failure-keyword")
+ self.assertEqual(copy.methods, "POST")
+ self.assertTrue(copy.manual_resume)
+
+ def test_it_obeys_limit(self):
+ self.profile.check_limit = 0
+ self.profile.save()
+
+ self.client.login(username="alice@example.org", password="password")
+ r = self.client.post(self.copy_url)
+ self.assertEqual(r.status_code, 400)
+
+ def test_it_requires_rw_access(self):
+ self.bobs_membership.role = "r"
+ self.bobs_membership.save()
+
+ self.client.login(username="bob@example.org", password="password")
+ r = self.client.post(self.copy_url)
+ self.assertEqual(r.status_code, 403)
+
+ def test_it_handles_long_check_name(self):
+ self.check.name = "A" * 100
+ self.check.save()
+
+ self.client.login(username="alice@example.org", password="password")
+ self.client.post(self.copy_url)
+
+ q = Check.objects.filter(name="A" * 90 + "... (copy)")
+ self.assertTrue(q.exists())
diff --git a/pool/shard009/Python/0087139_model.py b/pool/shard009/Python/0087139_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..9284369e648e7d1b0428706f09e40365d020bd27
--- /dev/null
+++ b/pool/shard009/Python/0087139_model.py
@@ -0,0 +1,19 @@
+import os
+
+path = os.path.dirname(os.path.realpath(__file__))
+sbmlFilePath = os.path.join(path, 'MODEL0913242281.xml')
+
+with open(sbmlFilePath,'r') as f:
+ sbmlString = f.read()
+
+def module_exists(module_name):
+ try:
+ __import__(module_name)
+ except ImportError:
+ return False
+ else:
+ return True
+
+if module_exists('libsbml'):
+ import libsbml
+ sbml = libsbml.readSBMLFromString(sbmlString)
\ No newline at end of file
diff --git a/pool/shard009/Python/0087145_faulty_temporal_memory_shim.py b/pool/shard009/Python/0087145_faulty_temporal_memory_shim.py
new file mode 100644
index 0000000000000000000000000000000000000000..6744d6fe9edea24d98e34a85a81595023ecd1d83
--- /dev/null
+++ b/pool/shard009/Python/0087145_faulty_temporal_memory_shim.py
@@ -0,0 +1,138 @@
+# ----------------------------------------------------------------------
+# Numenta Platform for Intelligent Computing (NuPIC)
+# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and conditions apply:
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero Public License version 3 as
+# published by the Free Software Foundation.
+#
+# 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 Public License for more details.
+#
+# You should have received a copy of the GNU Affero Public License
+# along with this program. If not, see http://www.gnu.org/licenses.
+#
+# http://numenta.org/licenses/
+# ----------------------------------------------------------------------
+
+"""
+A shim for the faulty TP class that transparently implements
+FaultyTemporalMemory,
+
+for use with OPF.
+"""
+
+import numpy
+
+
+from htmresearch.algorithms.faulty_temporal_memory import FaultyTemporalMemory
+from nupic.algorithms.monitor_mixin.temporal_memory_monitor_mixin import (
+ TemporalMemoryMonitorMixin)
+
+class MonitoredFaultyTemporalMemory(TemporalMemoryMonitorMixin,
+ FaultyTemporalMemory): pass
+
+class MonitoredFaultyTPShim(MonitoredFaultyTemporalMemory):
+ """
+ TP => Temporal Memory shim class.
+ """
+ def __init__(self,
+ numberOfCols=500,
+ cellsPerColumn=10,
+ initialPerm=0.11,
+ connectedPerm=0.50,
+ minThreshold=8,
+ newSynapseCount=15,
+ permanenceInc=0.10,
+ permanenceDec=0.10,
+ permanenceMax=1.0,
+ activationThreshold=12,
+ predictedSegmentDecrement=0,
+ maxSegmentsPerCell=255,
+ maxSynapsesPerSegment=255,
+ globalDecay=0.10,
+ maxAge=100000,
+ pamLength=1,
+ verbosity=0,
+ outputType="normal",
+ seed=42):
+ """
+ Translate parameters and initialize member variables specific to `TP.py`.
+ """
+ super(MonitoredFaultyTPShim, self).__init__(
+ columnDimensions=(numberOfCols,),
+ cellsPerColumn=cellsPerColumn,
+ activationThreshold=activationThreshold,
+ initialPermanence=initialPerm,
+ connectedPermanence=connectedPerm,
+ minThreshold=minThreshold,
+ maxNewSynapseCount=newSynapseCount,
+ permanenceIncrement=permanenceInc,
+ permanenceDecrement=permanenceDec,
+ predictedSegmentDecrement=predictedSegmentDecrement,
+ maxSegmentsPerCell=maxSegmentsPerCell,
+ maxSynapsesPerSegment=maxSynapsesPerSegment,
+ seed=seed)
+
+ self.infActiveState = {"t": None}
+
+
+ def compute(self, bottomUpInput, enableLearn, computeInfOutput=None):
+ """
+ (From `TP.py`)
+ Handle one compute, possibly learning.
+
+ @param bottomUpInput The bottom-up input, typically from a spatial pooler
+ @param enableLearn If true, perform learning
+ @param computeInfOutput If None, default behavior is to disable the inference
+ output when enableLearn is on.
+ If true, compute the inference output
+ If false, do not compute the inference output
+ """
+ super(MonitoredFaultyTPShim, self).compute(set(bottomUpInput.nonzero()[0]),
+ learn=enableLearn)
+ numberOfCells = self.numberOfCells()
+
+ activeState = numpy.zeros(numberOfCells)
+ activeState[self.getCellIndices(self.activeCells)] = 1
+ self.infActiveState["t"] = activeState
+
+ output = numpy.zeros(numberOfCells)
+ output[self.getCellIndices(self.predictiveCells | self.activeCells)] = 1
+ return output
+
+
+ def topDownCompute(self, topDownIn=None):
+ """
+ (From `TP.py`)
+ Top-down compute - generate expected input given output of the TP
+
+ @param topDownIn top down input from the level above us
+
+ @returns best estimate of the TP input that would have generated bottomUpOut.
+ """
+ output = numpy.zeros(self.numberOfColumns())
+ columns = [self.columnForCell(idx) for idx in self.predictiveCells]
+ output[columns] = 1
+ return output
+
+
+ def getActiveState(self):
+ activeState = numpy.zeros(self.numberOfCells())
+ activeState[self.getCellIndices(self.activeCells)] = 1
+ return activeState
+
+
+ def getPredictedState(self):
+ predictedState = numpy.zeros(self.numberOfCells())
+ predictedState[self.getCellIndices(self.predictiveCells)] = 1
+ return predictedState
+
+
+ def getLearnActiveStateT(self):
+ state = numpy.zeros([self.numberOfColumns(), self.cellsPerColumn])
+ return state
diff --git a/pool/shard009/Python/0087150_resource_test.py b/pool/shard009/Python/0087150_resource_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..82aef17ff6a6c9e48174114463e7ec1c05562864
--- /dev/null
+++ b/pool/shard009/Python/0087150_resource_test.py
@@ -0,0 +1,93 @@
+# Copyright 2017 Google 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.
+
+"""Tests the GCP Resource base class."""
+
+import mock
+
+from tests.unittest_utils import ForsetiTestCase
+from google.cloud.security.common.gcp_type import errors
+from google.cloud.security.common.gcp_type import resource_util
+from google.cloud.security.common.gcp_type.organization import Organization
+from google.cloud.security.common.gcp_type.project import Project
+from google.cloud.security.common.gcp_type.resource import Resource
+from google.cloud.security.common.gcp_type.resource import ResourceType
+
+
+class ResourceTest(ForsetiTestCase):
+ """Test Resource."""
+
+ def test_create_resource_raises_notimplemented(self):
+ """Test create Resource raises NotImplemented due to abstract method."""
+ my_resource_id = 'resource-id-1'
+ my_resource_name = 'My resource name'
+ Resource.__abstractmethods__ = frozenset()
+ abs_res = Resource(resource_id=my_resource_id,
+ resource_type=ResourceType.PROJECT,
+ name='projects/%s' % my_resource_id,
+ display_name=my_resource_name)
+ with self.assertRaises(NotImplementedError):
+ abs_res.exists()
+
+ def test_get_resource_types_exist(self):
+ """Test that the Resource Types exist."""
+ self.assertEqual(ResourceType.ORGANIZATION,
+ ResourceType.verify('organization'))
+ self.assertEqual(ResourceType.FOLDER,
+ ResourceType.verify('folder'))
+ self.assertEqual(ResourceType.PROJECT,
+ ResourceType.verify('project'))
+ self.assertEqual(ResourceType.GROUP,
+ ResourceType.verify('group'))
+
+ def test_get_invalid_resource_type_does_not_exist(self):
+ """Test fake resource type raises exception."""
+ with self.assertRaises(errors.InvalidResourceTypeError):
+ ResourceType.verify('fake')
+
+
+class ResourceUtilTest(ForsetiTestCase):
+ """Test ResourceUtil."""
+
+ def test_create_resource_is_ok(self):
+ """Test the resource_util.create_resource() creates the types."""
+ expect_org = Organization(12345)
+ actual_org = resource_util.create_resource(
+ 12345, ResourceType.ORGANIZATION)
+ self.assertEqual(expect_org, actual_org)
+ expect_proj = Project('abcd', 54321)
+ actual_proj = resource_util.create_resource(
+ 'abcd', ResourceType.PROJECT, project_number=54321)
+ self.assertEqual(expect_proj, actual_proj)
+ self.assertEqual(expect_proj.project_number, actual_proj.project_number)
+
+ def test_create_nonexist_resource_returns_None(self):
+ """Test that nonexistent resource type creates None."""
+ self.assertIsNone(
+ resource_util.create_resource('fake-id', 'nonexist'))
+
+ def test_plural_is_correct(self):
+ """Test that the resource type is pluralized correctly."""
+ self.assertEqual('Organizations',
+ resource_util.pluralize(ResourceType.ORGANIZATION))
+ self.assertEqual('Projects',
+ resource_util.pluralize(ResourceType.PROJECT))
+
+ def test_plural_nonexist_resource_returns_none(self):
+ """Test that trying to get plural nonexistent resource returns None."""
+ self.assertIsNone(resource_util.pluralize('nonexistent'))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0087154_docker.py b/pool/shard009/Python/0087154_docker.py
new file mode 100644
index 0000000000000000000000000000000000000000..27c6d2c5184efb537d27c47792b9dadb6fb9eca9
--- /dev/null
+++ b/pool/shard009/Python/0087154_docker.py
@@ -0,0 +1,170 @@
+"""
+Challenge template to deploy instances in on-demand containers
+"""
+
+import logging
+import os
+import tarfile
+import tempfile
+import sys
+
+import docker
+
+from hacksport.problem import Challenge
+from shell_manager.util import sanitize_name
+
+logger = logging.getLogger(__name__)
+
+class DockerChallenge(Challenge):
+ """Challenge based on a docker container."""
+ ports = {}
+
+ def __init__(self):
+ """ Connnects to the docker daemon"""
+ # will be used as the tag on the docker image
+ self.problem_name = sanitize_name(self.name)
+ # use an explicit remote docker daemon per the configuration
+ try:
+ tls_config = docker.tls.TLSConfig(
+ ca_cert=self.docker_ca_cert,
+ client_cert=(self.docker_client_cert, self.docker_client_key),
+ verify=True)
+
+ self.client = docker.DockerClient(base_url=self.docker_host, tls=tls_config)
+ self.api_client = docker.APIClient(base_url=self.docker_host, tls=tls_config)
+ logger.debug("Connecting to docker daemon with config")
+
+ # Docker options not set in configuration so use the environment to
+ # configure (could be local or remote)
+ except AttributeError:
+ logger.debug("Connecting to docker daemon with env")
+ self.client = docker.from_env()
+
+ # throws an exception if the server returns an error: docker.errors.APIError
+ self.client.ping()
+
+ def setup(self):
+ # Challenge author should override setup to do additional setup takes
+ # or pass arguments to the build process.
+ self.initialize_docker({})
+
+ def initialize_docker(self, build_args, timeout=600):
+
+ self.image_name = 'challenges:{}'.format(self.problem_name)
+
+ logger.debug("Building docker image: {}".format(self.image_name))
+ img = self._build_docker_image(build_args, timeout)
+ if img is None:
+ raise Exception('Unable to build docker image')
+
+ self.image_digest = img.id
+
+ try:
+ exposed_ports = img.attrs["Config"]["ExposedPorts"].keys()
+ except KeyError:
+ raise Exception("Dockerfile must expose at least 1 port")
+
+ # Ensure all ports are represented and convert to ints, e.g. "5555/tcp"
+ image_ports = [int(p.split("/")[0]) for p in exposed_ports]
+ for p in image_ports:
+ if p not in self.ports:
+ self.ports[p] = Plain("challenge")
+
+ logger.debug("Built image, digest: {}".format(self.image_digest))
+
+ def _build_docker_image(self, build_args, timeout):
+ """
+ Run a docker build
+ Args:
+ build_args: dict of build arguments to pass to `docker build`
+ timeout: how long to allow for the build
+
+ Returns: boolean success
+ """
+
+ try:
+ img, logs = self.client.images.build(
+ path='.',
+ tag=self.image_name,
+ buildargs=build_args,
+ labels={'problem': self.problem_name},
+ timeout=timeout)
+ except docker.errors.BuildError as e:
+ logger.error("Docker Build Error: " + e.msg)
+ logger.debug(e.build_log)
+ return None
+ except docker.errors.APIError as e:
+ logger.error("Docker API Error: " + e.explanation)
+ return None
+
+ return img
+
+ def copy_from_image(self, src):
+ """
+ Copy a file/folder from within a build image to the local filesystem.
+ Can only be run after the challenge image is created with
+ `initialize_docker`.
+ Args:
+ src : path of file or folder within the challenge image
+ """
+
+ cwd = os.getcwd()
+ logger.debug("Copy: {} from container to {}".format(src, cwd))
+ try:
+ cid = self.api_client.create_container(self.image_name)
+ c = self.client.containers.get(cid)
+ strm, stat = c.get_archive(src)
+
+ with tempfile.NamedTemporaryFile('wb+',suffix=".tar") as tf:
+ for chunk in strm:
+ tf.write(chunk)
+ tf.flush()
+ tf.seek(0)
+
+ with tarfile.open(fileobj=tf) as tar:
+ res = tar.extractall()
+
+ self.api_client.remove_container(cid)
+ except Exception:
+ logger.error("Fatal error in copy_from_image", exc_info=True)
+ raise
+
+
+
+# Utility classes to handle templating of ports. Will get formated twice in the
+# following order host, then port (this is why the extra {} in the fmt string)
+class HTTP():
+ def __init__(self, desc, path="", link_text=""):
+ self.desc = desc
+ self.path = path
+ self.link_text = link_text
+
+ def dict(self):
+ url = "http://{host}:{{port}}" + self.path
+ if self.link_text == "":
+ link = "{}".format(url, url)
+ else:
+ link = "{}".format(url, self.link_text)
+ return {"fmt": link, "desc": self.desc}
+
+class Netcat():
+ def __init__(self, desc):
+ self.desc = desc
+
+ def dict(self):
+ return {"fmt": "nc {host} {{port}}", "desc": self.desc}
+
+class Plain():
+ def __init__(self, desc):
+ self.desc = desc
+
+ def dict(self):
+ return {"fmt": "{host}:{{port}}", "desc": self.desc}
+
+class Custom():
+ def __init__(self, fmt, desc):
+ self.desc = desc
+ self.fmt = fmt
+
+ def dict(self):
+ return {"fmt": self.fmt, "desc": self.desc}
diff --git a/pool/shard009/Python/0087156_generate_android_manifest.py b/pool/shard009/Python/0087156_generate_android_manifest.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9061ed89fa87079c38371290501b055b33e604f
--- /dev/null
+++ b/pool/shard009/Python/0087156_generate_android_manifest.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+#
+# Copyright 2015 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+"""Creates an AndroidManifest.xml for an incremental APK.
+
+Given the manifest file for the real APK, generates an AndroidManifest.xml with
+the application class changed to IncrementalApplication.
+"""
+
+import argparse
+import os
+import sys
+from xml.etree import ElementTree
+
+sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir, 'gyp'))
+from util import build_utils
+
+_ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android'
+ElementTree.register_namespace('android', _ANDROID_NAMESPACE)
+
+_INCREMENTAL_APP_NAME = 'org.chromium.incrementalinstall.BootstrapApplication'
+_META_DATA_NAME = 'incremental-install-real-app'
+
+
+def _AddNamespace(name):
+ """Adds the android namespace prefix to the given identifier."""
+ return '{%s}%s' % (_ANDROID_NAMESPACE, name)
+
+def _ParseArgs():
+ parser = argparse.ArgumentParser()
+ build_utils.AddDepfileOption(parser)
+ parser.add_argument('--src-manifest',
+ help='The main manifest of the app',
+ required=True)
+ parser.add_argument('--out-manifest',
+ help='The output manifest',
+ required=True)
+ parser.add_argument('--disable-isolated-processes',
+ help='Changes all android:isolatedProcess to false. '
+ 'This is required on Android M+',
+ action='store_true')
+ return parser.parse_args()
+
+
+def _ProcessManifest(main_manifest, main_manifest_path,
+ disable_isolated_processes):
+ """Returns a transformed AndroidManifest.xml for use with _incremental apks.
+
+ Args:
+ main_manifest: Manifest contents to transform.
+ main_manifest_path: Path to main_manifest (used for error messages).
+ disable_isolated_processes: Whether to set all isolatedProcess attributes to
+ false
+
+ Returns:
+ The transformed AndroidManifest.xml.
+ """
+ if disable_isolated_processes:
+ main_manifest = main_manifest.replace('isolatedProcess="true"',
+ 'isolatedProcess="false"')
+
+ doc = ElementTree.fromstring(main_manifest)
+ app_node = doc.find('application')
+ if app_node is None:
+ raise Exception('Could not find in %s' % main_manifest_path)
+ real_app_class = app_node.get(_AddNamespace('name'))
+ if real_app_class is None:
+ raise Exception('Could not find android:name in in %s' %
+ main_manifest_path)
+ app_node.set(_AddNamespace('name'), _INCREMENTAL_APP_NAME)
+
+ meta_data_node = ElementTree.SubElement(app_node, 'meta-data')
+ meta_data_node.set(_AddNamespace('name'), _META_DATA_NAME)
+ meta_data_node.set(_AddNamespace('value'), real_app_class)
+ return ElementTree.tostring(doc, encoding='UTF-8')
+
+
+def main():
+ options = _ParseArgs()
+ with open(options.src_manifest) as f:
+ main_manifest_data = f.read()
+ new_manifest_data = _ProcessManifest(main_manifest_data, options.src_manifest,
+ options.disable_isolated_processes)
+ with open(options.out_manifest, 'w') as f:
+ f.write(new_manifest_data)
+
+ if options.depfile:
+ build_utils.WriteDepfile(
+ options.depfile,
+ [options.src_manifest] + build_utils.GetPythonDependencies())
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard009/Python/0087162_native_query.py b/pool/shard009/Python/0087162_native_query.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5809acd6c87d5acab636b8dae3bac274040487c
--- /dev/null
+++ b/pool/shard009/Python/0087162_native_query.py
@@ -0,0 +1,23 @@
+'''Autogenerated by xml_generate script, do not edit!'''
+from OpenGL import platform as _p, arrays
+# Code generation uses this
+from OpenGL.raw.EGL import _types as _cs
+# End users want this...
+from OpenGL.raw.EGL._types import *
+from OpenGL.raw.EGL import _errors
+from OpenGL.constant import Constant as _C
+
+import ctypes
+_EXTENSION_NAME = 'EGL_NV_native_query'
+def _f( function ):
+ return _p.createFunction( function,_p.PLATFORM.EGL,'EGL_NV_native_query',error_checker=_errors._error_checker)
+
+@_f
+@_p.types(_cs.EGLBoolean,_cs.EGLDisplay,arrays.GLvoidpArray)
+def eglQueryNativeDisplayNV(dpy,display_id):pass
+@_f
+@_p.types(_cs.EGLBoolean,_cs.EGLDisplay,_cs.EGLSurface,arrays.GLvoidpArray)
+def eglQueryNativePixmapNV(dpy,surf,pixmap):pass
+@_f
+@_p.types(_cs.EGLBoolean,_cs.EGLDisplay,_cs.EGLSurface,arrays.GLvoidpArray)
+def eglQueryNativeWindowNV(dpy,surf,window):pass
diff --git a/pool/shard009/Python/0087163_setup.py b/pool/shard009/Python/0087163_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f61052a48094004931b9fb4f8bb3bfd8ab2bc79
--- /dev/null
+++ b/pool/shard009/Python/0087163_setup.py
@@ -0,0 +1,37 @@
+from distutils.core import setup
+
+import os
+
+def get_build():
+ path = "./.build"
+
+ if os.path.exists(path):
+ fp = open(path, "r")
+ build = eval(fp.read())
+ if os.path.exists("./.increase_build"):
+ build += 1
+ fp.close()
+ else:
+ build = 1
+
+ fp = open(path, "w")
+ fp.write(str(build))
+ fp.close()
+
+ return int(build)
+
+setup(
+ name = "scrobblethis",
+ version = "0.4.%d" %get_build(),
+ description = "Command-line portable player log scrobbler",
+ author = "Amr Hassan ",
+ author_email = "amr.hassan@gmail.com",
+ license = "gpl",
+ url = "https://launchpad.net/scrobblethis",
+ scripts = ["scrobblethis"],
+ packages = ["st"],
+ data_files = [
+ ("/usr/share/man/man1", ("scrobblethis.1.gz",)),
+ ]
+ )
+
diff --git a/pool/shard009/Python/0087165_angular_velocity321.py b/pool/shard009/Python/0087165_angular_velocity321.py
new file mode 100644
index 0000000000000000000000000000000000000000..11daafba652ada9cac625c9720deb05611c75863
--- /dev/null
+++ b/pool/shard009/Python/0087165_angular_velocity321.py
@@ -0,0 +1,112 @@
+from __future__ import print_function
+
+import numpy as np
+from openmdao.api import IndepVarComp, Component, Group, Problem
+
+class AngularVelocity321(Component):
+ """
+ Notes
+ ------
+
+ Evaluates the body frame angular velocity from 321 Euler angles and their derivatives
+ Units are in radians and radians/s
+
+ Params
+ ------
+ Yaw : float
+ Yaw angle (3-axis rotation) of body frame with respect to the inertial NED frame. Default value is 0.0 rad
+ Pitch : float
+ Pitch angle (2-axis rotation) of body fram with respect to the inertial NED frame. Default value is 0.0 rad
+ Roll : float
+ Roll angle (1-axis rotation) of body fram with respect to the inertial NED frame. Default value is 0.0 rad
+ Yaw rate : float
+ Yaw rate of pod body frame. Default value is .01 rad/s
+ Pitch rate : float
+ Pitch rate of pod body frame. Default value is .01 rad/s
+ Roll rate : float
+ Roll rate of pod body frame. Default value is 0.0 rad/s
+
+
+ Returns
+ -------
+
+ Angular velocity : float
+ Returns the body fame angular velocity of the pod in rad/s
+ """
+
+ def __init__(self):
+ super(AngularVelocity321, self).__init__()
+
+ self.add_param('psi', val = 0.0, units = 'rad', desc = 'Pod yaw angle')
+ self.add_param('theta', val = 0.0, units = 'rad', desc = 'Pod pitch angle')
+ self.add_param('phi', val = 0.0, units = 'rad', desc = 'Pod roll angle')
+ self.add_param('psi_dot', val = 0.0, units = 'rad', desc = 'Pod yaw rate')
+ self.add_param('theta_dot', val = 0.0, units = 'rad', desc = 'Pod pitch rate')
+ self.add_param('phi_dot', val = 0.0, units = 'rad', desc = 'Pod roll rate')
+
+ self.add_output('omega_b', val = np.matrix('0.0; 0.0; 0.0'), units = 'rad/s', desc = 'Angular velocity vector')
+
+ def solve_nonlinear(self, p, u, r):
+ """
+ Notes
+ ------
+
+ omega = [[s(psi)*s(theta), c(psi), 0], [c(psi)*s(theta), -s(psi), 0], [c(theta), 0,1]] * [[phi], [theta], [psi]]
+
+ Params
+ ------
+ Yaw : float
+ Yaw angle (3-axis rotation) of body frame with respect to the inertial NED frame. Default value is 0.0 rad
+ Pitch : float
+ Pitch angle (2-axis rotation) of body fram with respect to the inertial NED frame. Default value is 0.0 rad
+ Roll : float
+ Roll angle (1-axis rotation) of body fram with respect to the inertial NED frame. Default value is 0.0 rad
+ Yaw rate : float
+ Yaw rate of pod body frame. Default value is .01 rad/s
+ Pitch rate : float
+ Pitch rate of pod body frame. Default value is .01 rad/s
+ Roll rate : float
+ Roll rate of pod body frame. Default value is 0.0 rad/s
+
+
+ Returns
+ -------
+
+ Angular velocity : float
+ Returns the body fame angular velocity of the pod in rad/s
+ """
+
+ psi = p['psi']
+ theta = p['theta']
+ phi = p['phi']
+ psi_dot = p['psi_dot']
+ theta_dot = p['theta_dot']
+ phi_dot = p['phi_dot']
+
+ B = np.matrix([[-np.sin(theta), 0.0, 1.0], [np.sin(phi)*np.cos(theta), np.cos(phi), 0.0], [np.cos(phi)*np.cos(theta), -np.sin(phi), 0]])
+
+ u['omega_b'] = B * np.matrix([[phi_dot], [theta_dot], [psi_dot]])
+
+
+if __name__ == '__main__':
+ top = Problem()
+ root = top.root = Group()
+
+ params = (
+ ('psi', 0.0, {'units' : 'rad'}),
+ ('theta', 0.0, {'units' : 'rad'}),
+ ('phi', 0.0, {'units' : 'rad'}),
+ ('psi_dot', 0.1, {'units' : 'rad'}),
+ ('theta_dot', 0.1, {'units' : 'rad'}),
+ ('phi_dot', 0.0, {'units' : 'rad'})
+ )
+
+ root.add('input_vars', IndepVarComp(params), promotes = ['psi', 'theta', 'phi', 'psi_dot', 'theta_dot', 'psi_dot'])
+ root.add('p', AngularVelocity321(), promotes = ['psi', 'theta', 'phi', 'psi_dot', 'theta_dot', 'psi_dot', 'omega_b'])
+
+ top.setup()
+ top.run()
+
+ print('Bod frame angular velocity vector = ')
+ print(top['omega_b'])
+
diff --git a/pool/shard009/Python/0087168_reset.py b/pool/shard009/Python/0087168_reset.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c676c756d6f043b21ef9017b3027804e0fe7464
--- /dev/null
+++ b/pool/shard009/Python/0087168_reset.py
@@ -0,0 +1,138 @@
+# ~*~ coding: utf-8 ~*~
+
+from __future__ import unicode_literals
+from django.shortcuts import render
+from django.views.generic import RedirectView
+from django.core.files.storage import default_storage
+from django.shortcuts import reverse, redirect
+from django.utils.translation import ugettext as _
+from django.views.generic.base import TemplateView
+from django.conf import settings
+from django.urls import reverse_lazy
+from formtools.wizard.views import SessionWizardView
+from django.views.generic import FormView
+
+from common.utils import get_object_or_none
+from common.permissions import PermissionsMixin, IsValidUser
+from ...models import User
+from ...utils import (
+ send_reset_password_mail, get_password_check_rules, check_password_rules,
+ send_reset_password_success_mail
+)
+from ... import forms
+
+
+__all__ = [
+ 'UserLoginView', 'UserForgotPasswordSendmailSuccessView',
+ 'UserResetPasswordSuccessView', 'UserResetPasswordSuccessView',
+ 'UserResetPasswordView', 'UserForgotPasswordView', 'UserFirstLoginView',
+]
+
+
+class UserLoginView(RedirectView):
+ url = reverse_lazy('authentication:login')
+ query_string = True
+
+
+class UserForgotPasswordView(FormView):
+ template_name = 'users/forgot_password.html'
+ form_class = forms.UserForgotPasswordForm
+
+ def form_valid(self, form):
+ email = form.cleaned_data['email']
+ user = get_object_or_none(User, email=email)
+ if not user:
+ error = _('Email address invalid, please input again')
+ form.add_error('email', error)
+ return self.form_invalid(form)
+
+ if not user.is_local:
+ error = _(
+ 'The user is from {}, please go to the corresponding system to change the password'
+ ).format(user.get_source_display())
+ form.add_error('email', error)
+ return self.form_invalid(form)
+
+ send_reset_password_mail(user)
+ return redirect('authentication:forgot-password-sendmail-success')
+
+
+class UserForgotPasswordSendmailSuccessView(TemplateView):
+ template_name = 'flash_message_standalone.html'
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'title': _('Send reset password message'),
+ 'messages': _('Send reset password mail success, '
+ 'login your mail box and follow it '),
+ 'redirect_url': reverse('authentication:login'),
+ }
+ kwargs.update(context)
+ return super().get_context_data(**kwargs)
+
+
+class UserResetPasswordSuccessView(TemplateView):
+ template_name = 'flash_message_standalone.html'
+
+ def get_context_data(self, **kwargs):
+ context = {
+ 'title': _('Reset password success'),
+ 'messages': _('Reset password success, return to login page'),
+ 'redirect_url': reverse('authentication:login'),
+ 'auto_redirect': True,
+ }
+ kwargs.update(context)
+ return super().get_context_data(**kwargs)
+
+
+class UserResetPasswordView(FormView):
+ template_name = 'users/reset_password.html'
+ form_class = forms.UserTokenResetPasswordForm
+
+ def get(self, request, *args, **kwargs):
+ context = self.get_context_data(**kwargs)
+ errors = kwargs.get('errors')
+ if errors:
+ context['errors'] = errors
+ return self.render_to_response(context)
+
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+ token = self.request.GET.get('token', '')
+ user = User.validate_reset_password_token(token)
+ if not user:
+ context['errors'] = _('Token invalid or expired')
+ context['token_invalid'] = True
+ check_rules = get_password_check_rules()
+ context['password_check_rules'] = check_rules
+ return context
+
+ def form_valid(self, form):
+ token = self.request.GET.get('token')
+ user = User.validate_reset_password_token(token)
+ if not user:
+ error = _('Token invalid or expired')
+ form.add_error('new_password', error)
+ return self.form_invalid(form)
+
+ if not user.can_update_password():
+ error = _('User auth from {}, go there change password')
+ form.add_error('new_password', error.format(user.get_source_display()))
+ return self.form_invalid(form)
+
+ password = form.cleaned_data['new_password']
+ is_ok = check_password_rules(password)
+ if not is_ok:
+ error = _('* Your password does not meet the requirements')
+ form.add_error('new_password', error)
+ return self.form_invalid(form)
+
+ user.reset_password(password)
+ User.expired_reset_password_token(token)
+ send_reset_password_success_mail(self.request, user)
+ return redirect('authentication:reset-password-success')
+
+
+class UserFirstLoginView(PermissionsMixin, TemplateView):
+ template_name = 'users/first_login.html'
+ permission_classes = [IsValidUser]
diff --git a/pool/shard009/Python/0087169_test_tar_utilities.py b/pool/shard009/Python/0087169_test_tar_utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd7353676cc720cf4defed01a4a3f245ba407ac5
--- /dev/null
+++ b/pool/shard009/Python/0087169_test_tar_utilities.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from nose.tools import ok_
+import os
+from py_utilities.compression.tar_utilities import create_tarball
+import shutil
+import tarfile
+import tempfile
+import unittest
+
+
+class TestTarUtilities(unittest.TestCase):
+
+ def setUp(self):
+ self.cwd = os.path.dirname(os.path.realpath(__file__))
+ self.temp_dir = tempfile.gettempdir()
+ self.temp_tar = os.path.join(self.temp_dir, 'tar_test')
+ self.test_dir = os.path.join(self.cwd, '..', 'data')
+
+ if not os.path.exists(self.temp_tar):
+ os.makedirs(self.temp_tar)
+
+ def tearDown(self):
+ if os.path.exists(self.temp_tar):
+ shutil.rmtree(self.temp_tar)
+
+ def test_create_tarball_gzip(self):
+ f = create_tarball([self.test_dir], 'foobar', self.temp_tar)
+ ok_(os.path.basename(f) != 'foobar.tar.gz')
+ ok_(os.stat(f).st_size > 0)
+ tarball = tarfile.open(f)
+ ok_(len(tarball.getmembers()) > 0)
+
+ def test_create_tarball_gzip_with_no_format_filename_is_itself(self):
+ f = create_tarball([self.test_dir], 'foobarx', self.temp_tar, "")
+ ok_(os.path.basename(f) == 'foobarx.tar.gz')
+ ok_(os.path.basename(f).find('_') == -1)
+
+ def test_create_tarball(self):
+ f = create_tarball([self.test_dir],
+ 'foobar2',
+ self.temp_tar,
+ gzip=False)
+
+ ok_(os.path.basename(f) != 'foobar2.tar')
+ ok_(os.stat(f).st_size > 0)
+ tarball = tarfile.open(f)
+ ok_(len(tarball.getmembers()) > 0)
+
+ def test_create_tarball_with_no_format_filename_is_itself(self):
+ f = create_tarball([self.test_dir], 'foobar2', self.temp_tar, "",
+ gzip=False)
+ ok_(os.path.basename(f) == 'foobar2.tar')
+ ok_(os.path.basename(f).find('_') == -1)
+
+# vim: filetype=python
diff --git a/pool/shard009/Python/0087170_undoredo.py b/pool/shard009/Python/0087170_undoredo.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8bff6784c8a1c0093e52dafc806909fd4b91313
--- /dev/null
+++ b/pool/shard009/Python/0087170_undoredo.py
@@ -0,0 +1,146 @@
+#
+# Gramps - a GTK+/GNOME based genealogy program
+#
+# Copyright (C) 2015 Douglas S. Blank
+#
+# 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.
+#
+#-------------------------------------------------------------------------
+#
+# Standard python modules
+#
+#-------------------------------------------------------------------------
+from abc import ABCMeta, abstractmethod
+import time
+from collections import deque
+
+class DbUndo(metaclass=ABCMeta):
+ """
+ Base class for the Gramps undo/redo manager. Needs to be subclassed
+ for use with a real backend.
+ """
+
+ __slots__ = ('undodb', 'db', 'undo_history_timestamp', 'undoq', 'redoq')
+
+ def __init__(self, db):
+ """
+ Class constructor. Set up main instance variables
+ """
+ self.db = db
+ self.undoq = deque()
+ self.redoq = deque()
+ self.undo_history_timestamp = time.time()
+
+ def clear(self):
+ """
+ Clear the undo/redo list (but not the backing storage)
+ """
+ self.undoq.clear()
+ self.redoq.clear()
+ self.undo_history_timestamp = time.time()
+
+ def __enter__(self, value):
+ """
+ Context manager method to establish the context
+ """
+ self.open(value)
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ """
+ Context manager method to finish the context
+ """
+ if exc_type is None:
+ self.close()
+ return exc_type is None
+
+ @abstractmethod
+ def open(self, value):
+ """
+ Open the backing storage. Needs to be overridden in the derived
+ class.
+ """
+
+ @abstractmethod
+ def close(self):
+ """
+ Close the backing storage. Needs to be overridden in the derived
+ class.
+ """
+
+ @abstractmethod
+ def append(self, value):
+ """
+ Add a new entry on the end. Needs to be overridden in the derived
+ class.
+ """
+
+ @abstractmethod
+ def __getitem__(self, index):
+ """
+ Returns an entry by index number. Needs to be overridden in the
+ derived class.
+ """
+
+ @abstractmethod
+ def __setitem__(self, index, value):
+ """
+ Set an entry to a value. Needs to be overridden in the derived class.
+ """
+
+ @abstractmethod
+ def __len__(self):
+ """
+ Returns the number of entries. Needs to be overridden in the derived
+ class.
+ """
+
+ @abstractmethod
+ def _redo(self, update_history):
+ """
+ """
+
+ @abstractmethod
+ def _undo(self, update_history):
+ """
+ """
+
+ def commit(self, txn, msg):
+ """
+ Commit the transaction to the undo/redo database. "txn" should be
+ an instance of Gramps transaction class
+ """
+ txn.set_description(msg)
+ txn.timestamp = time.time()
+ self.undoq.append(txn)
+
+ def undo(self, update_history=True):
+ """
+ Undo a previously committed transaction
+ """
+ if self.db.readonly or self.undo_count == 0:
+ return False
+ return self._undo(update_history)
+
+ def redo(self, update_history=True):
+ """
+ Redo a previously committed, then undone, transaction
+ """
+ if self.db.readonly or self.redo_count == 0:
+ return False
+ return self._redo(update_history)
+
+ undo_count = property(lambda self:len(self.undoq))
+ redo_count = property(lambda self:len(self.redoq))
diff --git a/pool/shard009/Python/0087173_naming.py b/pool/shard009/Python/0087173_naming.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b78d133f3e2fbf3523ef77acc1bc05d3f540aa
--- /dev/null
+++ b/pool/shard009/Python/0087173_naming.py
@@ -0,0 +1,50 @@
+from inspect import isclass
+
+from inflection import underscore
+
+from microcosm_pubsub.conventions.lifecycle import LifecycleChange
+
+
+def name_for(obj):
+ """
+ Get a name for something.
+
+ Allows overriding of default names using the `__alias__` attribute.
+
+ """
+ if isinstance(obj, str):
+ return underscore(obj)
+
+ cls = obj if isclass(obj) else obj.__class__
+
+ if hasattr(cls, "__alias__"):
+ return underscore(cls.__alias__)
+ else:
+ return underscore(cls.__name__)
+
+
+def make_media_type(resource, lifecycle_change=None, organization=None, public=False):
+ """
+ Generate a canonical media type for a message that announces a lifecycle change to a resource.
+
+ :param resource: the resource (name)
+ :param lifecycle_change: the change that happened to the resource
+ :param organization: the vendor organization to which this resource belongs
+ :param public: whether the resource is meant for public/external consumption
+
+ """
+ if lifecycle_change is None:
+ lifecycle_change = LifecycleChange.Created
+ if organization is None:
+ organization = "globality"
+
+ return "application/vnd.{}.{}.{}.{}".format(
+ # use a vendor specific media type
+ organization,
+ # differentiate messages sent over a pubsub channel from other messages
+ "pubsub" if public else "pubsub._",
+ # qualify the message with the kind of lifecycle change
+ str(lifecycle_change),
+ # specify the resource name
+ name_for(resource),
+ )
diff --git a/pool/shard009/Python/0087174_test_auto_MathsCommand.py b/pool/shard009/Python/0087174_test_auto_MathsCommand.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcd1f0d7724ed9829ec8ae3b5ab3ea11ed3b3768
--- /dev/null
+++ b/pool/shard009/Python/0087174_test_auto_MathsCommand.py
@@ -0,0 +1,51 @@
+# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
+from nipype.testing import assert_equal
+from nipype.interfaces.fsl.maths import MathsCommand
+
+def test_MathsCommand_inputs():
+ input_map = dict(args=dict(argstr='%s',
+ ),
+ environ=dict(nohash=True,
+ usedefault=True,
+ ),
+ ignore_exception=dict(nohash=True,
+ usedefault=True,
+ ),
+ in_file=dict(argstr='%s',
+ mandatory=True,
+ position=2,
+ ),
+ internal_datatype=dict(argstr='-dt %s',
+ position=1,
+ ),
+ nan2zeros=dict(argstr='-nan',
+ position=3,
+ ),
+ out_file=dict(argstr='%s',
+ genfile=True,
+ hash_files=False,
+ position=-2,
+ ),
+ output_datatype=dict(argstr='-odt %s',
+ position=-1,
+ ),
+ output_type=dict(),
+ terminal_output=dict(mandatory=True,
+ nohash=True,
+ ),
+ )
+ inputs = MathsCommand.input_spec()
+
+ for key, metadata in input_map.items():
+ for metakey, value in metadata.items():
+ yield assert_equal, getattr(inputs.traits()[key], metakey), value
+
+def test_MathsCommand_outputs():
+ output_map = dict(out_file=dict(),
+ )
+ outputs = MathsCommand.output_spec()
+
+ for key, metadata in output_map.items():
+ for metakey, value in metadata.items():
+ yield assert_equal, getattr(outputs.traits()[key], metakey), value
+
diff --git a/pool/shard009/Python/0087178_forms.py b/pool/shard009/Python/0087178_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..13e9b178dd962d5e7cf82142396583dd971938b3
--- /dev/null
+++ b/pool/shard009/Python/0087178_forms.py
@@ -0,0 +1,174 @@
+from datetime import datetime, timedelta
+
+from flask import g
+
+from flask.ext.wtf import (Form, TextField, SelectField,
+ BooleanField, TextAreaField, FloatField,
+ PasswordField, validators, Required, EqualTo,
+ ValidationError, DateTimeField, HiddenField)
+from flask.ext.wtf.html5 import (EmailField, TelField)
+from wtforms.ext.sqlalchemy.fields import (QuerySelectField,
+ QuerySelectMultipleField)
+from cfmi.database.newsite import User, Project, Subject, Session, MailingList
+
+from sqlalchemy import (and_, or_)
+
+class UserForm(Form):
+ name = TextField("Name")
+ email = EmailField("Email Address", validators=[validators.required(),
+ validators.email()])
+ phone = TelField("Emergency Contact Phone Number",
+ validators=[validators.required()] )
+ lists = QuerySelectMultipleField("Mailing Lists")
+
+ def __init__(self, *args, **kwargs):
+ print MailingList.query.all()
+ Form.__init__(self, *args, **kwargs)
+ subscribed = MailingList.query.filter(or_(
+ MailingList.restricted==False,
+ MailingList.users.contains(g.user)))
+ self.lists.query = subscribed
+
+class AdminUserForm(UserForm):
+ permission_level = SelectField(
+ "User Permissions",
+ choices=[(0, 'Disabled'), (1, 'Regular User'),
+ (2, 'Advanced User'), (3, 'Administrator')],
+ coerce=int)
+
+ def __init__(self, *args, **kwargs):
+ UserForm.__init__(self, *args, **kwargs)
+ self.lists.query = MailingList.query
+
+class CreateUserForm(AdminUserForm):
+ username = TextField("Username", validators=[validators.required()])
+
+
+class ProjectForm(Form):
+ name = TextAreaField("Project Name")
+ department = TextField("Department")
+ institution = TextField("Institution")
+ address = TextAreaField("Billing Address")
+ phone = TelField("Billing Contact Phone Number",
+ validators=[validators.required()] )
+ email = EmailField("Billing Email Address", validators=[validators.required(),
+ validators.email()])
+ rx_num = TextField("Reference Number (RX, GD, PO)")
+ users = QuerySelectMultipleField("Authorized Users")
+
+ def __init__(self, *args, **kwargs):
+ Form.__init__(self, *args, **kwargs)
+ self.users.query = User.query.filter(User.permission_level!=0).order_by(User.name)
+
+class AdminProjectForm(ProjectForm):
+ is_active = BooleanField("Approved")
+ mri_rate = FloatField("Hourly Rate")
+ pi = QuerySelectField("Principle Investigator")
+
+ def __init__(self, *args, **kwargs):
+ ProjectForm.__init__(self, *args, **kwargs)
+ self.pi.query = User.query.order_by(User.name)
+
+class PasswordForm(Form):
+ old_passwd = PasswordField("Old Password:")
+ new_passwd = PasswordField(
+ "New Password:", [Required(),
+ EqualTo('rep_passwd', message='Passwords must match')] )
+ rep_passwd = PasswordField("Repeat New Password:")
+
+ def validate_new_passwd(form, field):
+ has_upper = False
+ has_lower = False
+ has_digit = False
+ has_special = False
+ for char in field.data:
+ if char.isupper():
+ has_upper = True
+ continue
+ if char.islower():
+ has_lower = True
+ continue
+ if char.isdigit():
+ has_digit = True
+ continue
+ has_special = True
+ if len(field.data) < 8:
+ raise ValidationError('Passwords must contain at least 8 characters')
+ if [has_upper, has_lower, has_digit, has_special].count(True) < 3:
+ print [has_upper, has_lower, has_digit, has_special]
+ raise ValidationError('Passwords must contain 3 character classes')
+
+class SessionForm(Form):
+ id = HiddenField()
+ sched_start = DateTimeField("Scheduled start")
+ sched_end = DateTimeField("Scheduled end")
+ cancelled = BooleanField()
+ project = QuerySelectField("Project", [Required()])
+ subject = QuerySelectField(allow_blank=True)
+
+ def __init__(self, *args, **kwargs):
+ Form.__init__(self, *args, **kwargs)
+ self.project.query = Project.query.order_by(Project.name)
+ if 'obj' in kwargs:
+ self.id.data = kwargs['obj'].id
+ self.subject.query = Subject.query.filter(Subject.project==kwargs['obj'].project)
+ else:
+ self.subject.query = Subject.query
+ self.subject.query = self.subject.query.order_by(Subject.name)
+
+ def validate_sched_start(form, field):
+ if field.data:
+ conflict = Session.query.filter(
+ and_(Session.sched_startfield.data,
+ Session.id!=form.id.data)).first()
+ if conflict:
+ print conflict
+ raise ValidationError(
+ "This time conflicts with another scan ending: {}".format(conflict.sched_end))
+
+ def validate_sched_end(form, field):
+ if field.data:
+ conflict = Session.query.filter(
+ and_(Session.sched_startfield.data,
+ Session.id!=form.id.data)).first()
+
+ if conflict:
+ raise ValidationError(
+ "This time conflicts with another scan starting: {}".format(conflict.sched_start))
+
+
+
+class AdminSessionForm(SessionForm):
+ approved = BooleanField()
+ start = DateTimeField("Actual start time", validators=[validators.optional()])
+ end = DateTimeField("Actual end time", validators=[validators.optional()])
+ notes = TextAreaField()
+
+class MailingListForm(Form):
+ id = HiddenField()
+ name = TextField("Short Name", validators=[validators.required()])
+ description = TextField("Description")
+ public = BooleanField("Public send messages via e-mail?")
+ restricted = BooleanField("Only administrators can add members")
+
+ def __init__(self, *args, **kwargs):
+ Form.__init__(self, *args, **kwargs)
+ if 'obj' in kwargs:
+ self.id.data = kwargs['obj'].id
+
+ def validate_name(form, field):
+ if field.data:
+ if MailingList.query.filter(and_(
+ MailingList.name==field.data,
+ MailingList.id!=form.id.data)).all():
+ raise ValidationError("A mailing list already exists with this name: {}".format(field.data))
+
+
+class UserSelector(Form):
+ user = QuerySelectField("User")
+
+ def __init__(self, *args, **kwargs):
+ Form.__init__(self, *args, **kwargs)
+ self.user.query = User.query.filter(User.permission_level!=0).order_by(User.name)
diff --git a/pool/shard009/Python/0087179_test_include_test.py b/pool/shard009/Python/0087179_test_include_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e321c57142bb10491f27b30df3ffe65e8181860
--- /dev/null
+++ b/pool/shard009/Python/0087179_test_include_test.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+# Copyright 2016 Google Inc. 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.
+
+from absl.testing import parameterized
+from fruit_test_common import *
+
+COMMON_DEFINITIONS = '''
+ '''
+
+FRUIT_PUBLIC_HEADERS = [
+ "component.h",
+ "fruit.h",
+ "fruit_forward_decls.h",
+ "injector.h",
+ "macro.h",
+ "normalized_component.h",
+ "provider.h",
+]
+
+class TestHeaders(parameterized.TestCase):
+ @parameterized.parameters(FRUIT_PUBLIC_HEADERS)
+ def test_header_self_contained(self, HeaderFile):
+ source = '''
+ #include
+ '''
+ expect_success(
+ COMMON_DEFINITIONS,
+ source,
+ locals())
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/pool/shard009/Python/0087192_CompanyAccount.py b/pool/shard009/Python/0087192_CompanyAccount.py
new file mode 100644
index 0000000000000000000000000000000000000000..68b76a321591dbdbdf927751f0c9394bbfe314fb
--- /dev/null
+++ b/pool/shard009/Python/0087192_CompanyAccount.py
@@ -0,0 +1,28 @@
+from google.appengine.ext import ndb
+
+from Company import Company
+from ModelBase import ModelBase
+
+
+class CompanyAccount(ModelBase):
+ company_key = ndb.KeyProperty(kind="Company")
+ user_account_key = ndb.KeyProperty(kind="UserAccount")
+ access_level = ndb.IntegerProperty(default=100)
+
+ def __init__(self, *args, **kwds):
+ super(CompanyAccount, self).__init__(*args, **kwds)
+ self._company = None
+
+ @property
+ def company(self):
+ if self._company is None:
+ self._company = Company.get_by_id(self.company_key.id())
+ return self._company
+
+ @classmethod
+ def create_company_account(cls, company, user_account):
+ company_key = company.key
+ user_account_key = user_account.key
+ new_company_account = CompanyAccount(company_key=company_key, user_account_key=user_account_key)
+ new_company_account.put()
+ return new_company_account
diff --git a/pool/shard009/Python/0087196_0001_initial.py b/pool/shard009/Python/0087196_0001_initial.py
new file mode 100644
index 0000000000000000000000000000000000000000..979542c4f46010fcbefb32f68526d9eccf0c0eb9
--- /dev/null
+++ b/pool/shard009/Python/0087196_0001_initial.py
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Disease',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('name', models.CharField(max_length=200)),
+ ('concept_id', models.CharField(max_length=10)),
+ ('last_mod_date', models.DateTimeField(verbose_name=b'date published')),
+ ],
+ ),
+ migrations.CreateModel(
+ name='Gene',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('name', models.CharField(max_length=200)),
+ ('concept_id', models.CharField(max_length=10)),
+ ('last_mod_date', models.DateTimeField(verbose_name=b'date published')),
+ ],
+ ),
+ ]
diff --git a/pool/shard009/Python/0087197_shodanScan.py b/pool/shard009/Python/0087197_shodanScan.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a5e10d145429b8649f66576775b05761de9d8cb
--- /dev/null
+++ b/pool/shard009/Python/0087197_shodanScan.py
@@ -0,0 +1,18 @@
+# /usr/bin/env python 2.7
+
+import shodan
+
+def scan():
+ try:
+ ShodanKeyString = "API_KEY"
+ ShodanApi = shodan.Shodan(ShodanKeyString)
+ scan_results = ShodanApi.search("apache")
+ for result in scan_results['matches']:
+ print "IP: %s" % result['ip_str']
+ print result['data']
+ print ''
+ except shodan.APIError, e:
+ print "There is an error: %s" % e
+if __name__ == "__main__":
+ scan()
+
diff --git a/pool/shard009/Python/0087199_test_bigip_snat_pool.py b/pool/shard009/Python/0087199_test_bigip_snat_pool.py
new file mode 100644
index 0000000000000000000000000000000000000000..c254072781100cfaf7ae1f76e7b4addd0059e208
--- /dev/null
+++ b/pool/shard009/Python/0087199_test_bigip_snat_pool.py
@@ -0,0 +1,173 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (c) 2017 F5 Networks Inc.
+# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
+
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+import os
+import json
+import sys
+
+from nose.plugins.skip import SkipTest
+if sys.version_info < (2, 7):
+ raise SkipTest("F5 Ansible modules require Python >= 2.7")
+
+from ansible.compat.tests import unittest
+from ansible.compat.tests.mock import Mock
+from ansible.compat.tests.mock import patch
+from ansible.module_utils.basic import AnsibleModule
+
+try:
+ from library.modules.bigip_snat_pool import Parameters
+ from library.modules.bigip_snat_pool import ModuleManager
+ from library.modules.bigip_snat_pool import ArgumentSpec
+ from library.module_utils.network.f5.common import F5ModuleError
+ from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
+ from test.unit.modules.utils import set_module_args
+except ImportError:
+ try:
+ from ansible.modules.network.f5.bigip_snat_pool import Parameters
+ from ansible.modules.network.f5.bigip_snat_pool import ModuleManager
+ from ansible.modules.network.f5.bigip_snat_pool import ArgumentSpec
+ from ansible.module_utils.network.f5.common import F5ModuleError
+ from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
+ from units.modules.utils import set_module_args
+ except ImportError:
+ raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
+
+fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
+fixture_data = {}
+
+
+def load_fixture(name):
+ path = os.path.join(fixture_path, name)
+
+ if path in fixture_data:
+ return fixture_data[path]
+
+ with open(path) as f:
+ data = f.read()
+
+ try:
+ data = json.loads(data)
+ except Exception:
+ pass
+
+ fixture_data[path] = data
+ return data
+
+
+class TestParameters(unittest.TestCase):
+ def test_module_parameters(self):
+ args = dict(
+ name='my-snat-pool',
+ state='present',
+ members=['10.10.10.10', '20.20.20.20'],
+ partition='Common'
+ )
+ p = Parameters(params=args)
+ assert p.name == 'my-snat-pool'
+ assert p.state == 'present'
+ assert len(p.members) == 2
+ assert '/Common/10.10.10.10' in p.members
+ assert '/Common/20.20.20.20' in p.members
+
+ def test_api_parameters(self):
+ args = dict(
+ members=['/Common/10.10.10.10', '/foo/20.20.20.20']
+ )
+ p = Parameters(params=args)
+ assert len(p.members) == 2
+ assert '/Common/10.10.10.10' in p.members
+ assert '/Common/20.20.20.20' in p.members
+
+
+class TestManager(unittest.TestCase):
+
+ def setUp(self):
+ self.spec = ArgumentSpec()
+
+ def test_create_snat_pool(self, *args):
+ set_module_args(dict(
+ name='my-snat-pool',
+ state='present',
+ members=['10.10.10.10', '20.20.20.20'],
+ password='passsword',
+ server='localhost',
+ user='admin'
+ ))
+
+ module = AnsibleModule(
+ argument_spec=self.spec.argument_spec,
+ supports_check_mode=self.spec.supports_check_mode
+ )
+ mm = ModuleManager(module=module)
+
+ # Override methods to force specific logic in the module to happen
+ mm.exists = Mock(side_effect=[False, True])
+ mm.create_on_device = Mock(return_value=True)
+
+ results = mm.exec_module()
+
+ assert results['changed'] is True
+ assert len(results['members']) == 2
+ assert '/Common/10.10.10.10' in results['members']
+ assert '/Common/20.20.20.20' in results['members']
+
+ def test_create_snat_pool_idempotent(self, *args):
+ set_module_args(dict(
+ name='asdasd',
+ state='present',
+ members=['1.1.1.1', '2.2.2.2'],
+ password='passsword',
+ server='localhost',
+ user='admin'
+ ))
+
+ current = Parameters(params=load_fixture('load_ltm_snatpool.json'))
+
+ module = AnsibleModule(
+ argument_spec=self.spec.argument_spec,
+ supports_check_mode=self.spec.supports_check_mode
+ )
+ mm = ModuleManager(module=module)
+
+ # Override methods to force specific logic in the module to happen
+ mm.exists = Mock(side_effect=[True, True])
+ mm.read_current_from_device = Mock(return_value=current)
+
+ results = mm.exec_module()
+
+ assert results['changed'] is False
+
+ def test_update_snat_pool(self, *args):
+ set_module_args(dict(
+ name='asdasd',
+ state='present',
+ members=['30.30.30.30'],
+ password='passsword',
+ server='localhost',
+ user='admin'
+ ))
+
+ current = Parameters(params=load_fixture('load_ltm_snatpool.json'))
+
+ module = AnsibleModule(
+ argument_spec=self.spec.argument_spec,
+ supports_check_mode=self.spec.supports_check_mode
+ )
+ mm = ModuleManager(module=module)
+
+ # Override methods to force specific logic in the module to happen
+ mm.read_current_from_device = Mock(return_value=current)
+ mm.update_on_device = Mock(return_value=True)
+ mm.exists = Mock(return_value=True)
+ mm.create_on_device = Mock(return_value=True)
+
+ results = mm.exec_module()
+
+ assert results['changed'] is True
+ assert len(results['members']) == 1
+ assert '/Common/30.30.30.30' in results['members']
diff --git a/pool/shard009/Python/0087200_recheck_phenotypes.py b/pool/shard009/Python/0087200_recheck_phenotypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..795a430f21d85189319f73e66f7d5fe07802ccf4
--- /dev/null
+++ b/pool/shard009/Python/0087200_recheck_phenotypes.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python
+
+import sys
+import re
+import sql
+import ora_sql
+
+"""
+some constants
+"""
+SPECIES_ID = 1
+DUMMY_CULTURE_ID = 1
+DUMMY_SUBSPECIES_ID = 1
+DUMMY_PLANT_ID = 1
+DUMMY_ENTITY_ID = -12345
+DUMMY_VALUE_ID = -12345
+
+
+def get_program_id(line, program_key = 2):
+ programs = {
+ 'fast score': 1,
+ 'phenotype' : 2,
+ 'bbch' : 3,
+ }
+
+ try:
+ return programs[ line[ program_key ].lower() ]
+ except KeyError:
+ return False
+
+def homogenize_date(date):
+ (year, month, day) = [ int(x) for x in re.split(r'[^0-9]', date) ]
+
+ if day > 999: # switch day and year if they seem to be reversed
+ day,year = year,day
+ elif (year < 2010):
+ # it seems dates are sometimes given as '06-03-11' which is TOTALLY AMbIGUOUS!
+ # anyway, check if all dates are above 2011
+ day,year = year,day
+
+ if year == 11:
+ year = 2011
+
+ return "%d-%02d-%02d" % (year, month, day)
+
+def preprocess_line(line):
+ program_id = get_program_id(line)
+
+ if not program_id:
+ return line
+
+ # program_id: (positions in the scanner files that are ints)
+ ints = {
+ 1: (3, 4, 7), # entity_id, value_id, sample_id, number
+ 2: (3, 4, 8, 10), # sample_id, bbch_id, entity_id, value_id, number
+ 3: (3, 4)
+ }
+
+ for i in ints[ program_id ]:
+ line[ i ] = int(line[i])
+
+ # get the date right
+ date_pos = 6 # for program_id = 2 | 3
+ if program_id == 1: date_pos = 9
+ line[date_pos] = homogenize_date(line[date_pos])
+
+ return line
+
+def progress(s):
+ #sys.stdout.write('\r%s' % s)
+ #sys.stdout.write('%s' % s)
+ #sys.stdout.flush()
+ pass
+
+def format_line(line):
+ program_id = get_program_id(line)
+
+ default = {
+ 'version': line[0],
+ 'object' : line[1],
+ 'program_id': program_id,
+ 'entity_id': DUMMY_ENTITY_ID,
+ 'value_id': DUMMY_VALUE_ID,
+ 'number' : None
+ }
+
+ if program_id == 1:
+ return dict( default.items() + {
+ 'entity_id': line[3],
+ 'value_id': line[4],
+ 'attribute': line[5],
+ 'value': line[6],
+ 'sample_id': line[7],
+ 'number': line[8],
+ 'date': line[9],
+ 'time': line[10]
+ }.items())
+
+ if program_id == 2:
+ return dict(default.items() + {
+ 'sample_id': line[3],
+ 'bbch_id': line[4],
+ 'bbch': line[5],
+ 'date': line[6],
+ 'time': line[7],
+ 'entity_id': line[8],
+ 'entity': line[9],
+ 'value_id': line[10],
+ 'attribute': line[11],
+ 'value': line[12],
+ 'number': line[13]
+ }.items() )
+
+ if program_id == 3:
+ return dict(default.items() + {
+ 'sample_id': line[3],
+ 'bbch_id': line[4],
+ 'bbch': line[5],
+ 'date': line[6],
+ 'time': line[7]
+ }.items() )
+
+ return None
+
+def main(argv):
+ # get all files
+ files = sql.fetch_all(None, None, "SELECT * FROM `raws`")
+
+ for f in files:
+ print("Processing %s" % f['filename'])
+ raw_id = f['id']
+
+ # preprocess
+ lines = []
+ try:
+ line_nr = 0
+ for line in f['data'].split("\r\n"):
+ if len(line) == 0: continue
+ line_nr += 1
+ line = line.rstrip('\r\n')
+ line = re.split(r'\t|;', line)
+ line = preprocess_line(line)
+ lines.append(line)
+ except:
+ print "%d: %s" % (line_nr, line)
+ raise
+
+ # fix!
+ line_nr = 0
+ try:
+ for line in lines:
+ line_nr += 1
+ phenotype = format_line(line) # create a readable program
+
+ # look up the phenotype id based on the line number
+ try:
+ if (phenotype['entity_id'] == 808 and phenotype['value_id'] == 178): continue
+ phenotype_id = sql.fetch_all('phenotype_raws', { 'line_nr': line_nr, 'raw_id': raw_id })[0]['phenotype_id']
+ except:
+ print "%d: %d" % (line_nr, raw_id)
+ raise
+
+ # get the phenotype_%s % (plant, sample, aliquot) id, if any
+ ph_plant = sql.fetch('phenotype_plants', phenotype_id, 'phenotype_id')
+ ph_sample = sql.fetch('phenotype_samples', phenotype_id, 'phenotype_id')
+ ph_aliquot = sql.fetch('phenotype_aliquots', phenotype_id, 'phenotype_id')
+
+ # check where the link should belong and remove the others, if any
+ if ora_sql.is_plant(phenotype['sample_id']) or ora_sql.was_plant(phenotype['sample_id']):
+ if ph_sample != False: print "DELETE FROM `phenotype_samples` WHERE id = %s;" % ph_sample['id']
+ if ph_aliquot != False: print "DELETE FROM `phenotype_aliquots` WHERE id = %s;" % ph_aliquot['id']
+ elif ora_sql.is_sample(phenotype['sample_id']):
+ if ph_aliquot != False: print "DELETE FROM `phenotype_aliquots` WHERE id = %s;" % ph_aliquot['id']
+ if ph_plant != False: print "DELETE FROM `phenotype_plants` WHERE id = %s;" % ph_plant['id']
+ elif ora_sql.is_aliquot(phenotype['sample_id']):
+ if ph_sample != False: print "DELETE FROM `phenotype_samples` WHERE id = %s;" % ph_sample['id']
+ if ph_plant != False: print "DELETE FROM `phenotype_plants` WHERE id = %s;" % ph_plant['id']
+ else:
+ print "%s NOT found!!" % phenotype['sample_id']
+
+ except:
+ progress("%d: %s" % (line_nr, line))
+ raise
+
+ #sql.commit()
+
+if __name__ == '__main__': main(sys.argv[1:])
diff --git a/pool/shard009/Python/0087203_rlu_locomotion_test.py b/pool/shard009/Python/0087203_rlu_locomotion_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6b821774be7cb7cd8ceb77acf53abc4e6411abe
--- /dev/null
+++ b/pool/shard009/Python/0087203_rlu_locomotion_test.py
@@ -0,0 +1,41 @@
+# coding=utf-8
+# Copyright 2022 The TensorFlow Datasets 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.
+
+"""rlu_locomotion dataset."""
+
+import tensorflow_datasets.public_api as tfds
+from tensorflow_datasets.rl_unplugged.rlu_locomotion import rlu_locomotion
+
+
+class RluLocomotionTest(tfds.testing.DatasetBuilderTestCase):
+ """Tests for rlu_locomotion dataset."""
+ DATASET_CLASS = rlu_locomotion.RluLocomotion
+ SPLITS = {
+ 'train': 2, # Number of fake train example
+ }
+
+ SKIP_TF1_GRAPH_MODE = True
+
+ BUILDER_CONFIG_NAMES_TO_TEST = ['humanoid_corridor']
+
+ @classmethod
+ def setUpClass(cls):
+ rlu_locomotion.RluLocomotion._INPUT_FILE_PREFIX = cls.dummy_data
+ rlu_locomotion.RluLocomotion._SHARDS = 1
+ super().setUpClass()
+
+
+if __name__ == '__main__':
+ tfds.testing.test_main()
diff --git a/pool/shard009/Python/0087207_orchestrate_bag.py b/pool/shard009/Python/0087207_orchestrate_bag.py
new file mode 100644
index 0000000000000000000000000000000000000000..a90dc984e3ff5a415990136f8e46b0abc5468ab3
--- /dev/null
+++ b/pool/shard009/Python/0087207_orchestrate_bag.py
@@ -0,0 +1,36 @@
+from ..cluster.service import ClusterService
+from ..cluster_metadata.service import ClusterMetadataService
+from ..gpu_options_validator.service import GpuOptionsValidatorService
+from ..job_runner.service import JobRunnerService
+from ..job_status.service import JobStatusService
+from ..kubectl.service import KubectlService
+from ..kubernetes.service import KubernetesService
+from ..logging.service import LoggingService
+from ..model_packer.service import ModelPackerService
+from ..options_validator.service import OptionsValidatorService
+from ..provider.broker import ProviderBroker
+from ..resource.service import ResourceService
+from ..sigopt.service import SigOptService
+from .bag import ServiceBag
+
+
+class OrchestrateServiceBag(ServiceBag):
+ def _create_services(self):
+ super()._create_services()
+ self.resource_service = ResourceService(self)
+ self.provider_broker = ProviderBroker(self)
+ self.cluster_metadata_service = ClusterMetadataService(self)
+ self.cluster_service = ClusterService(self)
+ self.job_runner_service = JobRunnerService(self)
+ self.job_status_service = JobStatusService(self)
+ self.kubectl_service = KubectlService(self)
+ self.kubernetes_service = KubernetesService(self)
+ self.logging_service = LoggingService(self)
+ self.model_packer_service = ModelPackerService(self)
+ self.options_validator_service = OptionsValidatorService(self)
+ self.gpu_options_validator_service = GpuOptionsValidatorService(self)
+ self.sigopt_service = SigOptService(self)
+
+ def _warmup_services(self):
+ super()._warmup_services()
+ self.kubernetes_service.warmup()
diff --git a/pool/shard009/Python/0087213_config.py b/pool/shard009/Python/0087213_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..38f3865f9f35a585bd379fd94cf8ce121efdd65a
--- /dev/null
+++ b/pool/shard009/Python/0087213_config.py
@@ -0,0 +1,27 @@
+from dynamite.patterns import Singleton
+import addict
+
+class Config(Singleton):
+
+ def __getitem__(self, item):
+ if item not in self.data:
+ self.data[item] = addict.Dict()
+ return self.data[item]
+
+ def __init__(self):
+ self.data = addict.Dict()
+
+ def __iter__(self):
+ return self.data.__iter__()
+
+ def __setitem__(self, key, value):
+ self.data[key] = value
+
+ def __getattr__(self, item):
+ return self[item]
+
+ def get(self, item, default=None):
+ return self.data.get(item, default)
+
+
+dynamite_options = Config()
diff --git a/pool/shard009/Python/0087214_init__.py b/pool/shard009/Python/0087214_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0532c09b4e86bc8c0053aaf3f0c2ff258c0410ad
--- /dev/null
+++ b/pool/shard009/Python/0087214_init__.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of CERN Open Data Portal.
+# Copyright (C) 2017 CERN.
+#
+# CERN Open Data Portal 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.
+#
+# CERN Open Data Portal 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 CERN Open Data Portal; if not, write to the
+# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+# MA 02111-1307, USA.
+#
+# In applying this license, CERN does not
+# waive the privileges and immunities granted to it by virtue of its status
+# as an Intergovernmental Organization or submit itself to any jurisdiction.
+
+"""Record serialization."""
+
+from __future__ import absolute_import, print_function
+
+from .basic_json import BasicJSONSerializer, RecordSchemaV1
+from .schemaorg import CODSchemaorgSerializer
+
+from invenio_records_rest.serializers.response import record_responsify
+
+
+json = BasicJSONSerializer(RecordSchemaV1)
+
+schemaorg_jsonld = CODSchemaorgSerializer(replace_refs=True)
+
+schemaorg_jsonld_response = record_responsify(schemaorg_jsonld,
+ 'application/ld+json')
diff --git a/pool/shard009/Python/0087221_bing.py b/pool/shard009/Python/0087221_bing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3702d50973091daac2962299e50281770da16d78
--- /dev/null
+++ b/pool/shard009/Python/0087221_bing.py
@@ -0,0 +1,96 @@
+from geopy.geocoders import Bing
+from geopy.point import Point
+from test.geocoders.util import BaseTestGeocoder, env
+
+
+class TestUnitBing:
+
+ def test_user_agent_custom(self):
+ geocoder = Bing(
+ api_key='DUMMYKEY1234',
+ user_agent='my_user_agent/1.0'
+ )
+ assert geocoder.headers['User-Agent'] == 'my_user_agent/1.0'
+
+
+class TestBing(BaseTestGeocoder):
+
+ @classmethod
+ def make_geocoder(cls, **kwargs):
+ return Bing(
+ api_key=env['BING_KEY'],
+ **kwargs
+ )
+
+ async def test_geocode(self):
+ await self.geocode_run(
+ {"query": "435 north michigan ave, chicago il 60611 usa"},
+ {"latitude": 41.890, "longitude": -87.624},
+ )
+
+ async def test_unicode_name(self):
+ await self.geocode_run(
+ {"query": "\u043c\u043e\u0441\u043a\u0432\u0430"},
+ {"latitude": 55.756, "longitude": 37.615},
+ )
+
+ async def test_reverse_point(self):
+ await self.reverse_run(
+ {"query": Point(40.753898, -73.985071)},
+ {"latitude": 40.753, "longitude": -73.984},
+ )
+
+ async def test_reverse_with_culture_de(self):
+ res = await self.reverse_run(
+ {"query": Point(40.753898, -73.985071), "culture": "DE"},
+ {},
+ )
+ assert "Vereinigte Staaten von Amerika" in res.address
+
+ async def test_reverse_with_culture_en(self):
+ res = await self.reverse_run(
+ {"query": Point(40.753898, -73.985071), "culture": "EN"},
+ {},
+ )
+ assert "United States" in res.address
+
+ async def test_reverse_with_include_country_code(self):
+ res = await self.reverse_run(
+ {"query": Point(40.753898, -73.985071),
+ "include_country_code": True},
+ {},
+ )
+ assert res.raw["address"].get("countryRegionIso2", 'missing') == 'US'
+
+ async def test_user_location(self):
+ pennsylvania = (40.98327, -74.96064)
+ colorado = (40.160, -87.784)
+
+ pennsylvania_bias = (40.922351, -75.096562)
+ colorado_bias = (39.914231, -105.070104)
+ for expected, bias in ((pennsylvania, pennsylvania_bias),
+ (colorado, colorado_bias)):
+ await self.geocode_run(
+ {"query": "20 Main Street", "user_location": Point(bias)},
+ {"latitude": expected[0], "longitude": expected[1], "delta": 3.0},
+ )
+
+ async def test_optional_params(self):
+ res = await self.geocode_run(
+ {"query": "Badeniho 1, Prague, Czech Republic",
+ "culture": 'cs',
+ "include_neighborhood": True,
+ "include_country_code": True},
+ {},
+ )
+ address = res.raw['address']
+ assert address['neighborhood'] == "Praha 6"
+ assert address['countryRegionIso2'] == "CZ"
+
+ async def test_structured_query(self):
+ res = await self.geocode_run(
+ {"query": {'postalCode': '80020', 'countryRegion': 'United States'}},
+ {},
+ )
+ address = res.raw['address']
+ assert address['locality'] == "Broomfield"
diff --git a/pool/shard009/Python/0087222_custom.py b/pool/shard009/Python/0087222_custom.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccb795d11f851530b77621db0a54428c91ff4e2b
--- /dev/null
+++ b/pool/shard009/Python/0087222_custom.py
@@ -0,0 +1,132 @@
+# --------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# --------------------------------------------------------------------------------------------
+
+from knack.log import get_logger
+from knack.util import CLIError
+
+from azure.cli.core.util import ScopedConfig
+
+from azure.cli.core import telemetry
+
+logger = get_logger(__name__)
+
+
+def _normalize_config_value(value):
+ if value:
+ value = '' if value in ["''", '""'] else value
+ return value
+
+
+def config_set(cmd, key_value=None, local=False):
+ if key_value:
+ with ScopedConfig(cmd.cli_ctx.config, local):
+ telemetry_contents = []
+ for kv in key_value:
+ # core.no_color=true
+ parts = kv.split('=', 1)
+ if len(parts) == 1:
+ raise CLIError('usage error: [section].[name]=[value] ...')
+ key = parts[0]
+ value = parts[1]
+
+ # core.no_color
+ parts = key.split('.', 1)
+ if len(parts) == 1:
+ raise CLIError('usage error: [section].[name]=[value] ...')
+ section = parts[0]
+ name = parts[1]
+
+ cmd.cli_ctx.config.set_value(section, name, _normalize_config_value(value))
+ telemetry_contents.append((key, section, value))
+ telemetry.set_debug_info('ConfigSet', telemetry_contents)
+
+
+def config_get(cmd, key=None, local=False):
+ # No arg. List all sections and all items
+ if not key:
+ with ScopedConfig(cmd.cli_ctx.config, local):
+ sections = cmd.cli_ctx.config.sections()
+ result = {}
+ for section in sections:
+ items = cmd.cli_ctx.config.items(section)
+ result[section] = items
+ return result
+
+ parts = key.split('.', 1)
+ if len(parts) == 1:
+ # Only section is provided
+ section = key
+ name = None
+ else:
+ # section.name
+ section = parts[0]
+ name = parts[1]
+
+ with ScopedConfig(cmd.cli_ctx.config, local):
+ items = cmd.cli_ctx.config.items(section)
+
+ if not name:
+ # Only section
+ return items
+
+ # section.option
+ try:
+ return next(x for x in items if x['name'] == name)
+ except StopIteration:
+ raise CLIError("Configuration '{}' is not set.".format(key))
+
+
+def config_unset(cmd, key=None, local=False):
+ for k in key:
+ # section.name
+ parts = k.split('.', 1)
+
+ if len(parts) == 1:
+ raise CLIError("usage error: [section].[name]")
+
+ section = parts[0]
+ name = parts[1]
+
+ with ScopedConfig(cmd.cli_ctx.config, local):
+ cmd.cli_ctx.config.remove_option(section, name)
+ telemetry.set_debug_info('ConfigUnset', ' '.join(key))
+
+
+def turn_param_persist_on(cmd):
+ if not cmd.cli_ctx.local_context.is_on:
+ cmd.cli_ctx.local_context.turn_on()
+ logger.warning('Parameter persistence is turned on, you can run `az config param-persist off` to turn it off.')
+ else:
+ logger.warning('Parameter persistence is on already.')
+
+
+def turn_param_persist_off(cmd):
+ if cmd.cli_ctx.local_context.is_on:
+ cmd.cli_ctx.local_context.turn_off()
+ logger.warning('Parameter persistence is turned off, you can run `az config param-persist on` to turn it on.')
+ else:
+ logger.warning('Parameter persistence is off already.')
+
+
+def show_param_persist(cmd, name=None):
+ if not name:
+ name = None
+ return cmd.cli_ctx.local_context.get_value(name)
+
+
+def delete_param_persist(cmd, name=None, all=False, yes=False, purge=False, recursive=False): # pylint: disable=redefined-builtin
+ if name:
+ cmd.cli_ctx.local_context.delete(name)
+
+ if all:
+ from azure.cli.core.util import user_confirmation
+ if purge:
+ user_confirmation('You are going to delete parameter persistence file. '
+ 'Are you sure you want to continue this operation ?', yes)
+ cmd.cli_ctx.local_context.delete_file(recursive)
+ else:
+ user_confirmation('You are going to clear all parameter persistence values. '
+ 'Are you sure you want to continue this operation ?', yes)
+ cmd.cli_ctx.local_context.clear(recursive)
diff --git a/pool/shard009/Python/0087226_main.py b/pool/shard009/Python/0087226_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac18396d3b2215fa4c08b462a500dc6c58db54a1
--- /dev/null
+++ b/pool/shard009/Python/0087226_main.py
@@ -0,0 +1,99 @@
+import os
+import sys
+import logging
+from google.appengine.runtime.apiproxy_errors import CapabilityDisabledError
+
+sys.path.insert(1, os.path.join(os.path.abspath('.'), 'lib'))
+
+import json
+from flask import Flask, request
+from flask.ext.restful import Api, Resource, abort
+from models import MessageModel
+
+
+app = Flask(__name__)
+api = Api(app)
+
+
+class Message(Resource):
+ def get(self):
+ message_id = request.values.get('id', None)
+ if message_id is None:
+ abort(400, message="Bad Request. Message 'id' was not provided.")
+ message = MessageModel.get_by_id(int(message_id))
+ if message is None:
+ abort(404, message="Message '%s' was not found." % message_id)
+ return {'message': message.to_dict()}
+
+ def delete(self):
+ message_id = request.values.get('id', None)
+ if message_id is None:
+ abort(400, message="Please provide a message id.")
+ try:
+ id = int(message_id)
+ messages = MessageModel.get_by_id(id)
+ except ValueError:
+ if message_id == 'all':
+ messages = MessageModel.query().fetch(500)
+ else:
+ abort(400, message="Id should be a number.")
+ if messages is None:
+ abort(404, message="Message '%s' was not found." % message_id)
+
+ if type(messages) is list:
+ for message in messages:
+ message.key.delete()
+ else:
+ messages.key.delete()
+ return {'message': "Message '%s' was deleted successfully." % message_id}
+
+ def post(self):
+ ip = request.remote_addr
+ name = request.values.get('name', None)
+ city = request.values.get('city', None)
+ email = request.values.get('email', None)
+ message = request.values.get('message', None)
+ new_message = MessageModel(
+ ip=ip,
+ name=name,
+ city=city,
+ email=email,
+ message=message
+ )
+ try:
+ new_message.put()
+ except CapabilityDisabledError:
+ logging.error(u'App Engine Datastore is currently in read-only mode.')
+ abort(500)
+ return {'id': new_message.key.id()}, 200, {'Access-Control-Allow-Origin': '*'}
+
+
+class MessageList(Resource):
+ def get(self):
+ max = 500
+ query = MessageModel.query().order(-MessageModel.date)
+ messages = query.fetch(max)
+ aaData = []
+ for message in messages:
+ aaData.append({
+ "ip": message.ip,
+ "date": message.date.isoformat(),
+ "name": message.name,
+ "city": message.city,
+ "message": message.message,
+ "email": message.email,
+ "id": message.key.id()
+ })
+ return {'aaData': aaData}
+
+
+class Warmup(Resource):
+ def get(self):
+ return ''
+
+api.add_resource(Message, '/message')
+api.add_resource(MessageList, '/message/list')
+api.add_resource(Warmup, '/_ah/warmup')
+
+if __name__ == '__main__':
+ app.run(debug=True)
\ No newline at end of file
diff --git a/pool/shard009/Python/0087228_vswitch.py b/pool/shard009/Python/0087228_vswitch.py
new file mode 100644
index 0000000000000000000000000000000000000000..166aab8ce0491348acf9c287970c8af3657f98d2
--- /dev/null
+++ b/pool/shard009/Python/0087228_vswitch.py
@@ -0,0 +1,205 @@
+# Copyright 2017,2018 IBM Corp.
+#
+# 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.
+
+"""Handler for the root of the sdk API."""
+
+import json
+
+from zvmconnector import connector
+from zvmsdk import config
+from zvmsdk import log
+from zvmsdk.sdkwsgi.handlers import tokens
+from zvmsdk.sdkwsgi.schemas import vswitch
+from zvmsdk.sdkwsgi import util
+from zvmsdk.sdkwsgi import validation
+from zvmsdk import utils
+
+
+_VSWITCHACTION = None
+CONF = config.CONF
+LOG = log.LOG
+
+
+class VswitchAction(object):
+ def __init__(self):
+ self.client = connector.ZVMConnector(connection_type='socket',
+ ip_addr=CONF.sdkserver.bind_addr,
+ port=CONF.sdkserver.bind_port)
+
+ def list(self):
+ return self.client.send_request('vswitch_get_list')
+
+ @validation.schema(vswitch.create)
+ def create(self, body):
+ vsw = body['vswitch']
+ name = vsw['name']
+
+ rdev = vsw.get('rdev', None)
+ controller = vsw.get('controller', '*')
+ connection = vsw.get('connection', "CONNECT")
+ network_type = vsw.get('network_type', "ETHERNET")
+ router = vsw.get('router', "NONROUTER")
+ vid = vsw.get('vid', "UNAWARE")
+ port_type = vsw.get('port_type', "ACCESS")
+ gvrp = vsw.get('gvrp', "GVRP")
+ queue_mem = vsw.get('queue_mem', 8)
+ native_vid = vsw.get('native_vid', 1)
+ persist = vsw.get('persist', True)
+ persist = util.bool_from_string(persist, strict=True)
+
+ info = self.client.send_request('vswitch_create', name, rdev=rdev,
+ controller=controller,
+ connection=connection,
+ network_type=network_type,
+ router=router, vid=vid,
+ port_type=port_type, gvrp=gvrp,
+ queue_mem=queue_mem,
+ native_vid=native_vid,
+ persist=persist)
+ return info
+
+ def delete(self, name):
+ info = self.client.send_request('vswitch_delete', name)
+ return info
+
+ def query(self, name):
+ info = self.client.send_request('vswitch_query', name)
+ return info
+
+ @validation.schema(vswitch.update)
+ def update(self, name, body):
+ vsw = body['vswitch']
+ # TODO: only allow one param at most once
+
+ if 'grant_userid' in vsw:
+ userid = vsw['grant_userid']
+ info = self.client.send_request('vswitch_grant_user',
+ name, userid)
+ return info
+
+ if 'revoke_userid' in vsw:
+ userid = vsw['revoke_userid']
+ info = self.client.send_request('vswitch_revoke_user',
+ name, userid)
+ return info
+
+ if 'user_vlan_id' in vsw:
+ userid = vsw['user_vlan_id']['userid']
+ vlanid = vsw['user_vlan_id']['vlanid']
+ info = self.client.send_request('vswitch_set_vlan_id_for_user',
+ name, userid, vlanid)
+ return info
+
+
+def get_action():
+ global _VSWITCHACTION
+ if _VSWITCHACTION is None:
+ _VSWITCHACTION = VswitchAction()
+ return _VSWITCHACTION
+
+
+@util.SdkWsgify
+@tokens.validate
+def vswitch_list(req):
+ def _vswitch_list(req):
+ action = get_action()
+ return action.list()
+
+ info = _vswitch_list(req)
+ info_json = json.dumps(info)
+ req.response.body = utils.to_utf8(info_json)
+ req.response.status = util.get_http_code_from_sdk_return(info)
+ req.response.content_type = 'application/json'
+ return req.response
+
+
+@util.SdkWsgify
+@tokens.validate
+def vswitch_create(req):
+
+ def _vswitch_create(req):
+ action = get_action()
+ body = util.extract_json(req.body)
+
+ return action.create(body=body)
+
+ info = _vswitch_create(req)
+
+ info_json = json.dumps(info)
+ req.response.body = utils.to_utf8(info_json)
+ req.response.status = util.get_http_code_from_sdk_return(info,
+ additional_handler=util.handle_already_exists)
+ req.response.content_type = 'application/json'
+ return req.response
+
+
+@util.SdkWsgify
+@tokens.validate
+def vswitch_delete(req):
+
+ def _vswitch_delete(name):
+ action = get_action()
+
+ return action.delete(name)
+
+ name = util.wsgi_path_item(req.environ, 'name')
+ info = _vswitch_delete(name)
+
+ info_json = json.dumps(info)
+ req.response.body = utils.to_utf8(info_json)
+ req.response.status = util.get_http_code_from_sdk_return(info, default=200)
+ req.response.content_type = 'application/json'
+ return req.response
+
+
+@util.SdkWsgify
+@tokens.validate
+def vswitch_update(req):
+
+ def _vswitch_update(name, req):
+ body = util.extract_json(req.body)
+ action = get_action()
+
+ return action.update(name, body=body)
+
+ name = util.wsgi_path_item(req.environ, 'name')
+
+ info = _vswitch_update(name, req)
+
+ info_json = json.dumps(info)
+ req.response.body = utils.to_utf8(info_json)
+ req.response.status = util.get_http_code_from_sdk_return(info,
+ additional_handler=util.handle_not_found)
+ req.response.content_type = 'application/json'
+ return req.response
+
+
+@util.SdkWsgify
+@tokens.validate
+def vswitch_query(req):
+
+ def _vswitch_query(name):
+ action = get_action()
+ return action.query(name)
+
+ name = util.wsgi_path_item(req.environ, 'name')
+
+ info = _vswitch_query(name)
+
+ info_json = json.dumps(info)
+ req.response.body = utils.to_utf8(info_json)
+ req.response.status = util.get_http_code_from_sdk_return(info,
+ additional_handler=util.handle_not_found)
+ req.response.content_type = 'application/json'
+ return req.response
diff --git a/pool/shard009/Python/0087229_process.py b/pool/shard009/Python/0087229_process.py
new file mode 100644
index 0000000000000000000000000000000000000000..114159f4811614c70ebf3f21e42556ad31f4a6b3
--- /dev/null
+++ b/pool/shard009/Python/0087229_process.py
@@ -0,0 +1,52 @@
+
+AUTOCFG_TEMPLATE = r"""
+PROJECT_NAME = "{project_name}"
+OUTPUT_DIRECTORY = {output_dir}
+GENERATE_LATEX = NO
+GENERATE_MAN = NO
+GENERATE_RTF = NO
+CASE_SENSE_NAMES = NO
+INPUT = {input}
+ENABLE_PREPROCESSING = YES
+QUIET = YES
+JAVADOC_AUTOBRIEF = YES
+JAVADOC_AUTOBRIEF = NO
+GENERATE_HTML = NO
+GENERATE_XML = YES
+ALIASES = "rst=\verbatim embed:rst"
+ALIASES += "endrst=\endverbatim"
+""".strip()
+
+class DoxygenProcessHandle(object):
+
+ def __init__(self, path_handler, run_process, write_file):
+
+ self.path_handler = path_handler
+ self.run_process = run_process
+ self.write_file = write_file
+
+ def process(self, auto_project_info, files):
+
+ name = auto_project_info.name()
+ cfgfile = "%s.cfg" % name
+
+ full_paths = map(lambda x: auto_project_info.abs_path_to_source_file(x), files)
+
+ cfg = AUTOCFG_TEMPLATE.format(
+ project_name=name,
+ output_dir=name,
+ input=" ".join(full_paths)
+ )
+
+ build_dir = self.path_handler.join(
+ auto_project_info.build_dir(),
+ "breathe",
+ "doxygen"
+ )
+
+ self.write_file(build_dir, cfgfile, cfg)
+
+ self.run_process(['doxygen', cfgfile], cwd=build_dir)
+
+ return self.path_handler.join(build_dir, name, "xml")
+
diff --git a/pool/shard009/Python/0087230_testmongo.py b/pool/shard009/Python/0087230_testmongo.py
new file mode 100644
index 0000000000000000000000000000000000000000..245b10cad2c34768cafbfa446b003b1ff001c643
--- /dev/null
+++ b/pool/shard009/Python/0087230_testmongo.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+from util.mongo import MongoClient
+import time
+def trantime(t):
+ c = long(time.mktime(time.strptime(t,"%a %b %d %H:%M:%S %Y")))
+ return c
+
+ar = {"43": 1000}
+h = "10.11.12.31"
+p = 27017
+dbname = "zhangyu"
+user = "test"
+passwd = "testpw"
+m = MongoClient(host=h,port=p,dbName=dbname)
+c = m.authenticate(user, passwd)
+if c != True:
+ print "fail"
+con = {
+}
+g = m.get("money", con)
+a = g.distinct("_id")
+print len(a), g.count()
+for gc in g:
+ if gc.get("_id") in ar.keys():
+ print ar[gc.get("_id")]
+
+
+
+btime = trantime("Wed Jul 15 00:00:00 2015")
+etime = trantime("Thu Jul 16 00:00:00 2015")
+
+print btime,etime
+
+
diff --git a/pool/shard009/Python/0087235_train_numeric.py b/pool/shard009/Python/0087235_train_numeric.py
new file mode 100644
index 0000000000000000000000000000000000000000..c081558d63c96c4c5c0c041ff6e0e166df046480
--- /dev/null
+++ b/pool/shard009/Python/0087235_train_numeric.py
@@ -0,0 +1,51 @@
+import warnings
+import numpy as np
+import h5py
+from preprocessing import load_batches_numeric
+from keras.models import load_model
+from keras.utils import np_utils
+from model import *
+
+input_shape = (600, 800, 3) # frame2numpy 를 거친 input 은 [800, 600] 이 아닌 [600, 800] 이다.
+print("Loading Model ...")
+model = get_nvidia_model(input_shape=input_shape)
+# model = load_model('model_checkpoint.h5') # 학습을 진행한 모델이 존재한다면 이 줄을 사용.
+print("Model Loaded. Compiling...")
+sgd = SGD(lr=1e-3, decay=1e-4, momentum=0.9, nesterov=True) # SGD Optimizer 사용
+model.compile(optimizer='adam', loss="mse") # loss function 은 논문을 따라 "mean squared error"
+model.summary()
+
+# loss 기록을 위한 txt 파일
+f = open("loss_nvidia.txt", 'w')
+
+print("Starting Training...")
+batch_count = 0
+try:
+ for i in range(0, 1):
+ print('----------- On Epoch: ' + str(i) + ' ----------')
+ for x_train, y_train, x_test, y_test in load_batches_numeric():
+ # Model input requires numpy array
+ x_train = np.array(x_train)
+ x_test = np.array(x_test)
+
+ # Fit model to batch
+ train_history = model.fit(x_train, y_train, verbose=1, epochs=1, validation_data=(x_test, y_test))
+
+ # batch_count training_loss validation_loss 의 형태로 기록
+ f.write(str(batch_count) + ' ' + str(train_history.history['loss'][0]) + ' ' + str(
+ train_history.history['val_loss'][0]))
+
+ batch_count += 1
+ # Save a checkpoint
+ if (batch_count % 20) == 0:
+ print('Saving checkpoint ' + str(batch_count))
+ model.save('model_checkpoint_numeric_' + str(batch_count) + '.h5')
+ print('Checkpoint saved. Continuing...')
+except Exception as e:
+ print('Excepted with ' + str(e))
+ print('Saving model...')
+ model.save('excepted_model_numeric.h5')
+ print('Model saved.')
+
+# save final model
+model.save('model_numeric.h5')
\ No newline at end of file
diff --git a/pool/shard009/Python/0087236_download_new_filings.py b/pool/shard009/Python/0087236_download_new_filings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dde3ecab7e2df82e008229e0f0f2312469f2020
--- /dev/null
+++ b/pool/shard009/Python/0087236_download_new_filings.py
@@ -0,0 +1,47 @@
+import subprocess
+from time import sleep
+from os import path
+
+from django.core.management.base import BaseCommand, CommandError
+
+from parsing.form_parser import form_parser, ParserMissingError
+from parsing.filing import filing
+from parsing.read_FEC_settings import FILECACHE_DIRECTORY, FEC_DOWNLOAD
+
+from fec_alerts.models import new_filing
+
+
+
+
+class Command(BaseCommand):
+ help = "Download files from FTP. Mark them as having been downloaded."
+ requires_model_validation = False
+
+ def handle(self, *args, **options):
+ new_filings = new_filing.objects.filter(filing_is_downloaded=False, header_is_processed=False).order_by('filing_number')
+ for filing in new_filings:
+ if filing.filing_number < 1015680:
+ continue
+ print "need to handle %s" % (filing.filing_number)
+ location = FEC_DOWNLOAD % (filing.filing_number)
+ local_location = FILECACHE_DIRECTORY + "/" + str(filing.filing_number) + ".fec"
+ cmd = "curl \"%s\" -o %s" % (location, local_location)
+ print "Running command %s" % (cmd)
+ # run it from a curl shell
+ proc = subprocess.Popen(cmd,shell=True)
+ # if it's there when we're done, mark it as downloaded
+
+
+ print "Now sleeping for 1 second"
+ sleep(1)
+
+ # Putting the file check after the 1 second sleep gives better results; sometimes it appears absent if it's not before
+ if path.isfile(local_location):
+ print "File %s is there" % (filing.filing_number)
+ filing.filing_is_downloaded=True
+ filing.save()
+ else:
+ print "MISSING: %s" % (filing.filing_number)
+
+
+
\ No newline at end of file
diff --git a/pool/shard009/Python/0087237_ressl.py b/pool/shard009/Python/0087237_ressl.py
new file mode 100644
index 0000000000000000000000000000000000000000..25bacea2848ea6604a3aa1e4763e116caa3ac7a6
--- /dev/null
+++ b/pool/shard009/Python/0087237_ressl.py
@@ -0,0 +1,25 @@
+import os
+from importd import d
+
+__version__ = '0.2.1'
+
+d(
+ DEBUG='RESSL_DEBUG' in os.environ,
+ INSTALLED_APPS=['djangosecure'],
+ MIDDLEWARE_CLASSES=['djangosecure.middleware.SecurityMiddleware'],
+ SECURE_SSL_REDIRECT=True,
+ SECURE_PROXY_SSL_HEADER=(
+ os.environ.get('RESSL_PROXY_PROTOCOL', 'HTTP_X_FORWARDED_PROTOCOL'),
+ 'https'
+ ),
+ ALLOWED_HOSTS=[
+ host.strip()
+ for host in os.environ.get('RESSL_ALLOWED_HOSTS', '').split(',')
+ ],
+)
+
+# just for gunicorn
+application = d
+
+if __name__ == "__main__":
+ d.main()
diff --git a/pool/shard009/Python/0087245_gpstandbywatch.py b/pool/shard009/Python/0087245_gpstandbywatch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4285b17dd505b29d1e5017ca787aca9fb66b4c8
--- /dev/null
+++ b/pool/shard009/Python/0087245_gpstandbywatch.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python
+# Line too long - pylint: disable=C0301
+# Invalid name - pylint: disable=C0103
+
+"""
+ gpstandbywatch.py
+ Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved.
+
+ Check actual contents and process state of syncmaster
+ in order to properly return accurate information back to
+ gpinitstandby via gpstart.
+"""
+
+import os
+import sys
+import glob
+import time
+
+from gppylib.gplog import setup_tool_logging, get_default_logger
+from gppylib.commands import gp, unix
+
+
+def matching_files(pglogdir, ignore=None, setlimit=False):
+ """
+ Generate a series of file names corresponding to files
+ in 'pglogdir' which are not in the specified 'ignore' map.
+
+ Note that startup.log is always returned if present.
+
+ If 'setlimit' is not false, files whose modification time
+ exceeds the ctime of startup.log will also be ignored.
+ """
+ mlimit = None
+ pattern = os.path.join(pglogdir, 'startup.log')
+ for path in glob.glob(pattern):
+ if setlimit:
+ mlimit = os.stat(path).st_ctime
+ yield path
+
+ pattern = os.path.join(pglogdir, '*.csv')
+ for path in glob.glob(pattern):
+ if ignore is not None and path in ignore:
+ continue
+ if mlimit is not None and os.stat(path).st_mtime >= mlimit:
+ continue
+ yield path
+
+
+def updated_files(pglogdir, ignore, prev):
+ """
+ Generate a series of (time, path) tuples corresponding to files
+ in 'pglogdir' and not in 'ignore' which were also modified
+ after 'prev' (or all files if 'prev' is None).
+ """
+ for path in matching_files(pglogdir, ignore):
+ ts = os.stat(path).st_mtime
+ if prev is None or prev < ts:
+ yield (ts, path)
+
+
+def updated_handles(pglogdir, ignore, prev, handles):
+ """
+ Generate a series of (time, handle) tuples corresponding to files
+ in 'pglogdir' and not in 'ignore' modified after 'prev'
+ (or all files if 'prev' is None).
+ """
+ for ts, path in updated_files(pglogdir, ignore, prev):
+ h = handles.get(path, None)
+ if h is None:
+ h = open(path, 'r')
+ handles[path] = h
+ yield (ts, h)
+
+
+
+class SyncmasterWatcher:
+ """
+ Watch changes to files in the pg_log directory recorded by the gpsyncmaster.
+ """
+
+ def __init__(self, datadir):
+ """
+ Build a map containing the existing contents of the pg_log
+ directory so that we can avoid getting confused by them
+ after we start the syncmaster.
+ """
+ self.datadir = datadir
+ self.pglogdir = os.path.join(self.datadir, 'pg_log')
+
+ # note use of setlimit=True here to prevent any files created
+ # after startup.log from becoming ignored.
+ self.ignore = {}
+ for path in matching_files( self.pglogdir, setlimit=True ):
+ self.ignore[path] = True
+
+ self.handles = {}
+ self.maxlines = 1000
+ self.timelimit = 10
+ self.delay = 0.1
+
+
+ def tail_briefly(self):
+ """
+ Generate lines recently added to log files in the pg_log directory
+ updated after our __init__ constructor was called.
+ """
+ start = time.time() # starting time
+ elapsed = 0 # time elapsed so far
+ count = 0 # number of lines we've seen
+ tp = None
+
+ # until we're out of time or have returned enough lines
+ while elapsed < self.timelimit and count < self.maxlines:
+
+ # for each file modified since we last checked
+ tn = None
+ for ts, h in updated_handles(self.pglogdir, self.ignore, tp, self.handles):
+
+ # track the last file modification time
+ if tn is None or tn < ts:
+ tn = ts
+
+ # yield the new lines to the caller
+ while count < self.maxlines:
+ line = h.readline()
+ if not line:
+ break
+ yield line
+ count += 1
+
+ # update the elapsed time
+ elapsed = time.time() - start
+
+ # if any new lines, update prev and keep checking for more
+ if tn is not None:
+ tp = tn
+ continue
+
+ # if we get here it means none of the files were updated in
+ # our last iteration. sleep a moment before checking for
+ # more updates
+ time.sleep(self.delay)
+
+
+
+ def monitor_logs(self):
+ """
+ Read the syncmaster log files for a few seconds, looking for
+ potential problems.
+
+ Returns 0 if no problems were seen or or 1 if the startup log
+ contained an error or if the gpsyncmaster process exited before
+ we were done watching.
+ """
+ logger.info("Monitoring logs")
+
+ # now scan some of the syncmaster output for a moment
+ for line in self.tail_briefly():
+
+ if line.startswith('Traceback'): # gpsyncmaster traceback recorded
+ logger.warning(line)
+ return 1
+
+ # MPP-13212 - since the syncmaster reports rejected client connections
+ # as 'FATAL' errors, the presence of a 'FATAL' error need not indicate
+ # a problem in the syncmaster so we comment out the following logic:
+ #
+ # if line.find('FATAL') >= 0: # fatal error recorded
+ # logger.warning(line)
+ # return 1
+ #
+ # This is especially important for health monitoring clients which may
+ # rely on the difference between a rejected connection and a TCP failure.
+
+ if line.find('could not bind IPv4 socket') >= 0: # syncmaster used IPv6 by mistake
+ logger.warning(line)
+ return 1
+
+ if line.find('QDSYNC: scan forward') >= 0: # syncmaster appears to be working
+ logger.info(line)
+ break
+
+ logger.info("checking if syncmaster is running")
+ pid = gp.getSyncmasterPID('localhost', self.datadir)
+ if not pid > 0:
+ logger.warning("syncmaster not running")
+ return 1
+
+ # syncmaster is running and there are no obvious errors in the log
+ logger.info("syncmaster appears ok, pid %s" % pid)
+ return 0
+
+
+ def close(self):
+ """
+ Closes all handles to the logs we're watching.
+ """
+ for h in self.handles.values():
+ h.close()
+ self.handles = {}
+
+
+
+if __name__ == '__main__':
+
+ # setup gpAdminLogs logging
+ execname = os.path.split(sys.argv[0])[-1]
+ hostname = unix.getLocalHostname()
+ username = unix.getUserName()
+ setup_tool_logging(execname, hostname, username)
+ logger = get_default_logger()
+
+ # watch syncmaster logs
+ watcher = SyncmasterWatcher( sys.argv[1] )
+ rc = watcher.monitor_logs()
+ watcher.close()
+
+ # report final status
+ logger.info("exiting with %s" % rc)
+ sys.exit( rc )
diff --git a/pool/shard009/Python/0087250_qa_peak_resync_bb.py b/pool/shard009/Python/0087250_qa_peak_resync_bb.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f5d8097cf2cc44f3da1a14136474ba57709a2b3
--- /dev/null
+++ b/pool/shard009/Python/0087250_qa_peak_resync_bb.py
@@ -0,0 +1,41 @@
+#!/usr/bin/env python
+#
+# Copyright 2014 Institute for Theoretical Information Technology,
+# RWTH Aachen University
+# www.ti.rwth-aachen.de
+#
+# This 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, 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this software; see the file COPYING. If not, write to
+# the Free Software Foundation, Inc., 51 Franklin Street,
+# Boston, MA 02110-1301, USA.
+#
+
+from gnuradio import gr, gr_unittest
+import ofdm_swig as ofdm
+
+class qa_peak_resync_bb (gr_unittest.TestCase):
+
+ def setUp (self):
+ self.tb = gr.top_block ()
+
+ def tearDown (self):
+ self.tb = None
+
+ def test_001_t (self):
+ # set up fg
+ self.tb.run ()
+ # check data
+
+
+if __name__ == '__main__':
+ gr_unittest.run(qa_peak_resync_bb, "qa_peak_resync_bb.xml")
diff --git a/pool/shard009/Python/0087252_fabfile.py b/pool/shard009/Python/0087252_fabfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..583e694d970d0aff9a024e58fa9a79aedb34cac7
--- /dev/null
+++ b/pool/shard009/Python/0087252_fabfile.py
@@ -0,0 +1,100 @@
+from fabric.api import *
+import aws, os, glob, time
+from termcolor import colored
+from mako.template import Template
+
+# EC2 hostnames & IPs keep on changing
+env.disable_known_hosts = True
+
+@task
+def check_credentials():
+ """
+ Ensure that AWS API credentials exist
+ """
+ if not aws.has_credentials():
+ access_key_id = prompt('Access Key ID?')
+ secret_access_key = prompt('Secret Access Key?')
+ aws.save_credentials(access_key_id, secret_access_key)
+
+@task
+def make_vpc(vpc_name='midkemia'):
+ """
+ Make VPC - by default the vpc_name is 'midkemia'
+ """
+ check_credentials()
+ bastion_hosts = aws.make_vpc(vpc_name)
+ for host in bastion_hosts:
+ with connection_to_instance(host):
+ setup_puppet_standalone()
+ apply_manifest('bastion_host', host.name, host.user)
+ for host in bastion_hosts:
+ connect_script(host)
+
+@task
+def delete_vpc(vpc_name='midkemia'):
+ """
+ Delete VPC - by default the vpc_name is 'midkemia'
+ """
+ check_credentials()
+ aws.delete_vpc(vpc_name)
+ for path in glob.glob('connect_*'):
+ os.remove(path)
+
+def connect_script(host):
+ filename = 'connect_' + host.name
+ command = 'ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s\n'
+ command = command % (host.keyfile, host.user, host.public_ip)
+
+ with open(filename, 'w') as script:
+ script.write('#!/bin/sh\n')
+ script.write(command)
+
+ os.chmod(filename, 0755)
+ print colored('Connect to [%s] instance using ./%s' % (host.name, filename), 'cyan')
+
+def connection_to_instance(host):
+ wait_for_ssh_connection(host)
+ return settings(host_string=host.public_ip, user=host.user, key_filename=host.keyfile)
+
+def wait_for_ssh_connection(host):
+ with settings(warn_only=True):
+ result = check_ssh(host)
+ while result.failed:
+ print 'Waiting for SSH service ...'
+ time.sleep(5)
+ result = check_ssh(host)
+
+def check_ssh(host):
+ return local('nc -z -v -w 10 %s 22' % host.public_ip)
+
+def setup_puppet_standalone():
+ tarball_name = 'puppet.tar.gz'
+ with settings(warn_only=True):
+ result = run('puppet --version')
+ if result.failed:
+ sudo('apt-get -y update')
+ sudo('apt-get -y upgrade')
+ sudo('apt-get -y install puppet')
+ with settings(warn_only=True):
+ run('rm -rf puppet')
+ local('rm -rf build')
+ local('mkdir build')
+ local('tar czf build/%s puppet/*' % tarball_name)
+ put('build/' + tarball_name, tarball_name)
+ run('tar xzf ' + tarball_name)
+
+def apply_manifest(manifest, hostname, user):
+ variables = {'user': user, 'vpc_host': hostname}
+ input_file = 'puppet/manifests/%s.pp.txt' % manifest
+ output_file = 'build/%s.pp' % manifest
+
+ content = Template(filename=input_file).render(variables=variables)
+ with open(output_file, 'w') as fp:
+ fp.write(content)
+
+ puppet_root = '/home/%s/puppet' % user
+ command = 'puppet apply --modulepath=%s/modules %s/%s.pp'
+
+ sudo('hostname %s.local' % hostname)
+ put(output_file, '%s/%s.pp' % (puppet_root, manifest))
+ sudo(command % (puppet_root, puppet_root, manifest))
diff --git a/pool/shard009/Python/0087254_file.py b/pool/shard009/Python/0087254_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d94e3df0610f5808cc9bef39cf293fa244ed8ac
--- /dev/null
+++ b/pool/shard009/Python/0087254_file.py
@@ -0,0 +1,16 @@
+from w3lib.url import file_uri_to_path
+
+from scrapy.responsetypes import responsetypes
+from scrapy.utils.decorators import defers
+
+
+class FileDownloadHandler:
+ lazy = False
+
+ @defers
+ def download_request(self, request, spider):
+ filepath = file_uri_to_path(request.url)
+ with open(filepath, 'rb') as fo:
+ body = fo.read()
+ respcls = responsetypes.from_args(filename=filepath, body=body)
+ return respcls(url=request.url, body=body)
diff --git a/pool/shard009/Python/0087257_count_squares.py b/pool/shard009/Python/0087257_count_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..037433245d445598498395d1f71c0917fd4a500e
--- /dev/null
+++ b/pool/shard009/Python/0087257_count_squares.py
@@ -0,0 +1,57 @@
+from typing import List
+
+
+class Solution:
+ # Without modifying input
+ def countSquaresV1(self, matrix: List[List[int]]) -> int:
+ ans, rows, cols = 0, len(matrix), len(matrix[0])
+ dp = [[0] * (cols + 1) for _ in range(rows + 1)]
+ for i in range(rows):
+ for j in range(cols):
+ if matrix[i][j] == 1:
+ dp[i + 1][j + 1] = (
+ min(
+ dp[i + 1][j],
+ dp[i][j + 1],
+ dp[i][j],
+ )
+ + 1
+ )
+ ans += dp[i + 1][j + 1]
+ return ans
+
+ # Modifying input to achieve O(1) in space
+ def countSquaresV2(self, matrix: List[List[int]]) -> int:
+ ans, rows, cols = 0, len(matrix), len(matrix[0])
+ for i in range(rows):
+ for j in range(cols):
+ if matrix[i][j] == 1 and i and j:
+ matrix[i][j] = (
+ min(
+ matrix[i - 1][j],
+ matrix[i][j - 1],
+ matrix[i - 1][j - 1],
+ )
+ + 1
+ )
+ ans += matrix[i][j]
+ return ans
+
+
+# TESTS
+for matrix, expected in [
+ ([[0]], 0),
+ ([[1]], 1),
+ ([[1, 0]], 1),
+ ([[1, 0], [1, 1]], 3),
+ ([[1, 1], [1, 1]], 5),
+ ([[1, 0, 1], [1, 1, 0], [1, 1, 0]], 7),
+ ([[1, 1, 1], [1, 1, 1], [1, 1, 1]], 14),
+ ([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]], 15),
+]:
+ sol = Solution()
+ actual1 = sol.countSquaresV1(matrix)
+ actual2 = sol.countSquaresV2(matrix)
+ print("Square submatrices have all ones ->", actual2)
+ assert actual1 == expected
+ assert actual2 == expected
diff --git a/pool/shard009/Python/0087264_config.py b/pool/shard009/Python/0087264_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..912d10f6cce8cfdbd9aa53bb6f951ada227d369a
--- /dev/null
+++ b/pool/shard009/Python/0087264_config.py
@@ -0,0 +1,43 @@
+# -*- coding:utf-8 -*-
+#
+# Copyright (C) 2013 Carlos Jenkins
+#
+# 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 .
+
+"""
+Test script to generate a config file.
+"""
+
+import sys
+sys.path.insert(0, '../server/lib')
+
+import json
+from emlu.config import default_conf
+
+
+if __name__ == '__main__':
+
+ config = default_conf.copy()
+
+ # Append example mount
+ config['mounts'].append(
+ {
+ 'name' : 'user1',
+ 'mp' : '/media/mount1',
+ 'hidden' : False,
+ 'timeout' : -1,
+ }
+ )
+
+ print(json.dumps(config, indent=4))
diff --git a/pool/shard009/Python/0087266_FindQuantBounds.py b/pool/shard009/Python/0087266_FindQuantBounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8eb1ef2be58406263d047004c6155519afd075d
--- /dev/null
+++ b/pool/shard009/Python/0087266_FindQuantBounds.py
@@ -0,0 +1,69 @@
+#
+# Copyright (C) 2001 greg Landrum
+#
+
+
+
+from rdkit.Dbase import DbConnection
+from rdkit.ML.Data import Quantize
+
+
+def runIt(namesAndTypes, dbConnect, nBounds, resCol, typesToDo=['float']):
+ results = map(lambda x: x[0], dbConnect.GetColumns(namesAndTypes[resCol][0]))
+ nPossibleRes = max(results) + 1
+ for cName, cType in namesAndTypes:
+ if cType in typesToDo:
+ dList = map(lambda x: x[0], dbConnect.GetColumns(cName))
+ qDat = Quantize.FindVarMultQuantBounds(dList, nBounds, results, nPossibleRes)
+ print(cName, qDat)
+
+
+def Usage():
+ import sys
+ msg = """
+ Usage: FindQuantBounds [-r res_col -n bounds_per_var -i] dbName tableName
+ Optional Arguments:
+ -r: specify the number of the result column
+ -n: specify the number of bounds to attempt to find for each variable
+ -i: also find vars for integer values
+"""
+ print(msg)
+ sys.exit(-1)
+
+
+if __name__ == '__main__':
+ import sys
+ import getopt
+
+ try:
+ args, extras = getopt.getopt(sys.argv[1:], 'n:r:i')
+ except Exception:
+ Usage()
+
+ if len(extras) != 2:
+ Usage()
+
+ nBounds = 1
+ typesToDo = ['float']
+ includeInts = 0
+ resCol = -1
+ for arg, val in args:
+ if arg == '-i':
+ includeInts = 1
+ typesToDo.append('integer')
+ elif arg == '-n':
+ try:
+ nBounds = int(val)
+ except ValueError:
+ Usage()
+ elif arg == '-r':
+ try:
+ resCol = int(val)
+ except ValueError:
+ Usage()
+
+ dbName = extras[0]
+ tableName = extras[1]
+ dbConnect = DbConnection.DbConnect(dbName, tableName)
+ namesAndTypes = dbConnect.GetColumnNamesAndTypes()
+ runIt(namesAndTypes, dbConnect, nBounds, resCol, typesToDo)
diff --git a/pool/shard009/Python/0087276_bug_46141-mock.py b/pool/shard009/Python/0087276_bug_46141-mock.py
new file mode 100644
index 0000000000000000000000000000000000000000..d694ee71a8490532ca0453ac2fb956ac4d97ae2e
--- /dev/null
+++ b/pool/shard009/Python/0087276_bug_46141-mock.py
@@ -0,0 +1,60 @@
+# LICENSE BEGIN
+#
+# Copyright (c) 2010 Ysj.Ray
+#
+# 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 .
+#
+## LICENSE END
+
+import os, sys
+sys.path.append(os.environ['PYTHON_LIBPATH'])
+
+import mysql.proto as proto
+
+def connect_server(proxy):
+ proxy.response = {
+ 'type' : proxy.MYSQLD_PACKET_RAW,
+ 'packets' : (
+ proto.to_challenge_packet({}),
+ )
+ }
+
+ return proxy.PROXY_SEND_RESULT
+
+def read_query(proxy, packet):
+ if ord(packet[0]) != proxy.COM_QUERY :
+ proxy.response = {
+ 'type' : proxy.MYSQLD_PACKET_OK
+ }
+ return proxy.PROXY_SEND_RESULT
+
+ if packet[1:] == "SELECT 1" :
+ proxy.response = {
+ 'type' : proxy.MYSQLD_PACKET_OK,
+ 'resultset' : {
+ 'fields' : (
+ ( "1", proxy.MYSQL_TYPE_STRING ),
+ ),
+ 'rows' : (
+ ( "1", ),
+ )
+ }
+ }
+ return proxy.PROXY_SEND_RESULT
+ else:
+ proxy.response = {
+ 'type' : proxy.MYSQLD_PACKET_ERR,
+ 'errmsg' : "(bug_41991-mock) >" + packet[1:] + "<"
+ }
+ return proxy.PROXY_SEND_RESULT
diff --git a/pool/shard009/Python/0087279_lirc.py b/pool/shard009/Python/0087279_lirc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac4807b26af5b7c6358ae3af56e6431d23ad2431
--- /dev/null
+++ b/pool/shard009/Python/0087279_lirc.py
@@ -0,0 +1,91 @@
+"""
+LIRC interface to receive signals from a infrared remote control.
+
+For more details about this component, please refer to the documentation at
+https://home-assistant.io/components/lirc/
+"""
+# pylint: disable=import-error
+import threading
+import time
+import logging
+
+import voluptuous as vol
+
+from homeassistant.const import (
+ EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START)
+
+REQUIREMENTS = ['python-lirc==1.2.3']
+
+_LOGGER = logging.getLogger(__name__)
+
+BUTTON_NAME = 'button_name'
+
+DOMAIN = 'lirc'
+
+EVENT_IR_COMMAND_RECEIVED = 'ir_command_received'
+
+ICON = 'mdi:remote'
+
+CONFIG_SCHEMA = vol.Schema({
+ DOMAIN: vol.Schema({}),
+}, extra=vol.ALLOW_EXTRA)
+
+
+def setup(hass, config):
+ """Setup LIRC capability."""
+ import lirc
+
+ # blocking=True gives unexpected behavior (multiple responses for 1 press)
+ # also by not blocking, we allow hass to shut down the thread gracefully
+ # on exit.
+ lirc.init('home-assistant', blocking=False)
+ lirc_interface = LircInterface(hass)
+
+ def _start_lirc(_event):
+ lirc_interface.start()
+
+ def _stop_lirc(_event):
+ lirc_interface.stopped.set()
+
+ hass.bus.listen_once(EVENT_HOMEASSISTANT_START, _start_lirc)
+ hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_lirc)
+
+ return True
+
+
+class LircInterface(threading.Thread):
+ """
+ This interfaces with the lirc daemon to read IR commands.
+
+ When using lirc in blocking mode, sometimes repeated commands get produced
+ in the next read of a command so we use a thread here to just wait
+ around until a non-empty response is obtained from lirc.
+ """
+
+ def __init__(self, hass):
+ """Construct a LIRC interface object."""
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.stopped = threading.Event()
+ self.hass = hass
+
+ def run(self):
+ """Main loop of LIRC interface thread."""
+ import lirc
+ _LOGGER.debug("LIRC interface thread started")
+ while not self.stopped.isSet():
+ try:
+ code = lirc.nextcode() # list; empty if no buttons pressed
+ except lirc.NextCodeError:
+ _LOGGER.warning("Error reading next code from LIRC")
+ code = None
+ # interpret result from python-lirc
+ if code:
+ code = code[0]
+ _LOGGER.info("Got new LIRC code %s", code)
+ self.hass.bus.fire(
+ EVENT_IR_COMMAND_RECEIVED, {BUTTON_NAME: code})
+ else:
+ time.sleep(0.2)
+ lirc.deinit()
+ _LOGGER.debug('LIRC interface thread stopped')
diff --git a/pool/shard009/Python/0087280_quant.2.py b/pool/shard009/Python/0087280_quant.2.py
new file mode 100644
index 0000000000000000000000000000000000000000..2659da475c78fb67e69c65c64773146677fb06e2
--- /dev/null
+++ b/pool/shard009/Python/0087280_quant.2.py
@@ -0,0 +1,12 @@
+
+# Copyright (c) 2015 Microsoft Corporation
+from z3 import *
+set_option(auto_config=True)
+
+f = Function('f', IntSort(), IntSort(), IntSort())
+x, y = Ints('x y')
+f = ForAll([x, y], f(x, y) == 0)
+print f.body()
+v1 = f.body().arg(0).arg(0)
+print v1
+print eq(v1, Var(1, IntSort()))
diff --git a/pool/shard009/Python/0087289_analytic_resource_plan_line_make_purchase_request.py b/pool/shard009/Python/0087289_analytic_resource_plan_line_make_purchase_request.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aba70ef729dcddd5cbdf895abd69c589d51291e
--- /dev/null
+++ b/pool/shard009/Python/0087289_analytic_resource_plan_line_make_purchase_request.py
@@ -0,0 +1,206 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# Copyright (C) 2014 Eficent ()
+#
+#
+# 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.tools.translate import _
+from openerp.osv import fields, orm
+# from openerp import netsvc
+import openerp.addons.decimal_precision as dp
+
+
+class AnalyticResourcePlanLineMakePurchaseRequest(orm.TransientModel):
+ _name = "analytic.resource.plan.line.make.purchase.request"
+ _description = "Resource plan make purchase request"
+
+ _columns = {
+ 'origin': fields.char('Origin', size=32, required=True),
+ 'description': fields.text('Description'),
+ 'item_ids': fields.one2many(
+ 'analytic.resource.plan.line.make.purchase.request.item',
+ 'wiz_id', 'Items'),
+ }
+
+ def _prepare_item(self, cr, uid, line, context=None):
+ return [{
+ 'account_id': line.account_id.id,
+ 'product_id': line.product_id.id,
+ 'product_qty': line.unit_amount,
+ 'product_uom_id': line.product_uom_id.id,
+ 'line_id': line.id,
+ }]
+
+ def default_get(self, cr, uid, fields, context=None):
+ res = super(AnalyticResourcePlanLineMakePurchaseRequest,
+ self).default_get(cr, uid, fields, context=context)
+ res_plan_obj = self.pool['analytic.resource.plan.line']
+ resource_plan_line_ids = context.get('active_ids', [])
+ active_model = context.get('active_model')
+
+ if not resource_plan_line_ids:
+ return res
+ assert active_model == 'analytic.resource.plan.line', \
+ 'Bad context propagation'
+
+ items = []
+ for line in res_plan_obj.browse(cr, uid, resource_plan_line_ids,
+ context=context):
+ items += self._prepare_item(cr, uid, line, context=context)
+ res['item_ids'] = items
+ return res
+
+ def _prepare_purchase_request(self, cr, uid, make_purchase_request,
+ company_id, context=None):
+ data = {
+ 'company_id': company_id,
+ 'origin': make_purchase_request.origin,
+ 'description': make_purchase_request.description,
+ }
+ return data
+
+ def _prepare_purchase_request_line(self, cr, uid, pr_id,
+ make_purchase_request, item,
+ context=None):
+ return {
+ 'request_id': pr_id,
+ 'name': item.product_id.name,
+ 'product_qty': item.product_qty,
+ 'product_id': item.product_id.id,
+ 'product_uom_id': item.product_uom_id.id,
+ 'date_required': item.line_id.date or False,
+ 'analytic_account_id': item.line_id.account_id.id,
+ 'analytic_resource_plan_lines': [(4, item.line_id.id)]
+ }
+
+ def make_purchase_request(self, cr, uid, ids, context=None):
+ if context is None:
+ context = {}
+ res = []
+ make_purchase_request = self.browse(cr, uid, ids[0], context=context)
+ line_plan_obj = self.pool['analytic.resource.plan.line']
+ request_obj = self.pool['purchase.request']
+ request_line_obj = self.pool['purchase.request.line']
+ company_id = False
+ warehouse_id = False
+ request_id = False
+ for item in make_purchase_request.item_ids:
+ line = item.line_id
+ if line.state != 'confirm':
+ raise orm.except_orm(
+ _('Could not create purchase request !'),
+ _('All resource plan lines must be '
+ 'confirmed.'))
+ if item.product_qty < 0.0:
+ raise orm.except_orm(
+ _('Could not create purchase request !'),
+ _('Enter a positive quantity.'))
+
+ line_company_id = line.account_id.company_id \
+ and line.account_id.company_id.id or False
+ if company_id is not False \
+ and line_company_id != company_id:
+ raise orm.except_orm(
+ _('Could not create purchase request !'),
+ _('You have to select lines '
+ 'from the same company.'))
+ else:
+ company_id = line_company_id
+
+ line_warehouse_id = line.account_id.warehouse_id \
+ and line.account_id.warehouse_id.id or False
+ if warehouse_id is not False \
+ and line_warehouse_id != warehouse_id:
+ raise orm.except_orm(
+ _('Could not create purchase request !'),
+ _('You have to select lines '
+ 'from the same warehouse.'))
+ else:
+ warehouse_id = line_warehouse_id
+
+ if request_id is False:
+ request_data = self._prepare_purchase_request(
+ cr, uid, make_purchase_request, company_id,
+ context=context)
+ request_id = request_obj.create(cr, uid, request_data,
+ context=context)
+ request_line_data = self._prepare_purchase_request_line(
+ cr, uid, request_id, make_purchase_request, item,
+ context=context)
+ request_line_id = request_line_obj.create(
+ cr, uid, request_line_data, context=context)
+ values = {
+ 'purchase_request_lines': [(4, request_line_id)]
+ }
+ line_plan_obj.write(cr, uid, [line.id],
+ values, context=context)
+ project_manager_id = line.account_id.user_id and \
+ line.account_id.user_id.partner_id.id or False
+ if project_manager_id:
+ request = request_obj.browse(cr, uid, request_id,
+ context=context)
+ message_follower_ids = [x.id for x in
+ request.message_follower_ids]
+ if project_manager_id not in message_follower_ids:
+ request_obj.write(cr, uid, request_id, {
+ 'message_follower_ids': (4, project_manager_id)})
+ res.append(request_line_id)
+
+ return {
+ 'domain': "[('id','in', ["+','.join(map(str, res))+"])]",
+ 'name': _('Purchase Request Lines'),
+ 'view_type': 'form',
+ 'view_mode': 'tree,form',
+ 'res_model': 'purchase.request.line',
+ 'view_id': False,
+ 'context': False,
+ 'type': 'ir.actions.act_window'
+ }
+
+
+class AnalyticResourcePlanLineMakePurchaseRequestItem(orm.TransientModel):
+ _name = "analytic.resource.plan.line.make.purchase.request.item"
+ _description = "Resource plan make purchase request item"
+
+ _columns = {
+ 'wiz_id': fields.many2one(
+ 'analytic.resource.plan.line.make.purchase.request',
+ 'Wizard', required=True, ondelete='cascade',
+ readonly=True),
+ 'line_id': fields.many2one('analytic.resource.plan.line',
+ 'Resource Plan Line',
+ required=True,
+ readonly=True),
+ 'account_id': fields.related('line_id',
+ 'account_id', type='many2one',
+ relation='account.analytic.account',
+ string='Analytic Account',
+ readonly=True),
+ 'product_id': fields.related('line_id',
+ 'product_id', type='many2one',
+ relation='product.product',
+ string='Product',
+ readonly=True),
+ 'product_qty': fields.float(string='Quantity to request',
+ digits_compute=dp.get_precision(
+ 'Product UoS')),
+ 'product_uom_id': fields.related('line_id',
+ 'product_uom_id', type='many2one',
+ relation='product.uom',
+ string='UoM',
+ readonly=True)
+ }
diff --git a/pool/shard009/Python/0087293_283.py b/pool/shard009/Python/0087293_283.py
new file mode 100644
index 0000000000000000000000000000000000000000..b75d0de996d0164093e2563a0276a807da0bd9f8
--- /dev/null
+++ b/pool/shard009/Python/0087293_283.py
@@ -0,0 +1,17 @@
+class Solution(object):
+ def moveZeroes(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: None Do not return anything, modify nums in-place instead.
+ """
+ count = 0
+ for i in range(len(nums)):
+ if nums[i] == 0:
+ count += 1
+ elif count > 0:
+ nums[i-count] = nums[i]
+ nums[i] = 0
+
+solution = Solution()
+
+print solution.moveZeroes([0,1,0,3,12])
diff --git a/pool/shard009/Python/0087295_sprite_generators_test.py b/pool/shard009/Python/0087295_sprite_generators_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0c1dbf06c9eb199513e314744732824dc04d469
--- /dev/null
+++ b/pool/shard009/Python/0087295_sprite_generators_test.py
@@ -0,0 +1,107 @@
+# Copyright 2019 DeepMind Technologies Limited.
+#
+# 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.
+# ============================================================================
+# python2 python3
+"""Tests for sprite_generators."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from absl.testing import absltest
+from absl.testing import parameterized
+import numpy as np
+from spriteworld import factor_distributions as distribs
+from spriteworld import sprite
+from spriteworld import sprite_generators
+
+_distrib_0 = distribs.Product([
+ distribs.Discrete('x', [0.5]),
+ distribs.Discrete('y', [0.5]),
+ distribs.Discrete('shape', ['square', 'triangle']),
+ distribs.Discrete('c0', [255]),
+ distribs.Discrete('c1', [255]),
+ distribs.Discrete('c2', [255]),
+])
+
+_distrib_1 = distribs.Product([
+ distribs.Discrete('x', [0.5]),
+ distribs.Discrete('y', [0.5]),
+ distribs.Discrete('shape', ['hexagon', 'circle', 'star_5']),
+ distribs.Discrete('c0', [255]),
+ distribs.Discrete('c1', [255]),
+ distribs.Discrete('c2', [255]),
+])
+
+
+class SpriteGeneratorTest(parameterized.TestCase):
+
+ @parameterized.parameters(1, 2, 5)
+ def testGenerateSpritesLengthType(self, num_sprites):
+ g = sprite_generators.generate_sprites(_distrib_0, num_sprites=num_sprites)
+ sprite_list = g()
+ self.assertIsInstance(sprite_list, list)
+ self.assertLen(sprite_list, num_sprites)
+ self.assertIsInstance(sprite_list[0], sprite.Sprite)
+
+ def testGenerateSpritesCallableNum(self):
+ minval = 3
+ maxval = 6
+ num_sprites = np.random.randint(minval, maxval)
+ g = sprite_generators.generate_sprites(_distrib_0, num_sprites=num_sprites)
+ sprite_list = g()
+ self.assertGreaterEqual(len(sprite_list), minval)
+ self.assertLess(len(sprite_list), maxval)
+
+
+class ChainGeneratorsTest(absltest.TestCase):
+
+ def testOutput(self):
+ g_0 = sprite_generators.generate_sprites(_distrib_0, num_sprites=1)
+ g_1 = sprite_generators.generate_sprites(_distrib_1, num_sprites=2)
+ g_chain = sprite_generators.chain_generators(g_0, g_1)
+ sprite_list = g_chain()
+ self.assertIsInstance(sprite_list, list)
+ self.assertLen(sprite_list, 3)
+ self.assertTrue(_distrib_0.contains(sprite_list[0].factors))
+ self.assertTrue(_distrib_1.contains(sprite_list[1].factors))
+ self.assertTrue(_distrib_1.contains(sprite_list[2].factors))
+
+
+class SampleGeneratorTest(absltest.TestCase):
+
+ def testOutput(self):
+ g_0 = sprite_generators.generate_sprites(_distrib_0, num_sprites=1)
+ g_1 = sprite_generators.generate_sprites(_distrib_1, num_sprites=1)
+ g_chain = sprite_generators.sample_generator((g_0, g_1))
+ sprite_list = g_chain()
+ self.assertIsInstance(sprite_list, list)
+ self.assertLen(sprite_list, 1)
+ self.assertNotEqual(
+ _distrib_0.contains(sprite_list[0].factors),
+ _distrib_1.contains(sprite_list[0].factors))
+
+
+class ShuffleTest(absltest.TestCase):
+
+ def testOutput(self):
+ g = sprite_generators.generate_sprites(_distrib_0, num_sprites=5)
+ g_shuffle = sprite_generators.shuffle(g)
+ sprite_list = g_shuffle()
+ self.assertIsInstance(sprite_list, list)
+ self.assertLen(sprite_list, 5)
+
+
+if __name__ == '__main__':
+ absltest.main()
diff --git a/pool/shard009/Python/0087300_forms.py b/pool/shard009/Python/0087300_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..94e0513a7f15b388c25e054e3282d5d59e12b06d
--- /dev/null
+++ b/pool/shard009/Python/0087300_forms.py
@@ -0,0 +1,20 @@
+
+from wtforms import SelectField, StringField, SubmitField, IntegerField,\
+ ValidationError
+from wtforms.validators import Length, DataRequired
+from flask_wtf import FlaskForm
+
+
+charts = [('linear', 'Linear Chart'), ('bar', 'Bar Chart'),
+ ('scatter', 'Scatter Chart')]
+
+
+class TaobaoSearchStatisticForm(FlaskForm):
+ keyword = StringField('Keyword for Search Scenario', validators=[DataRequired(), Length(1, 64)])
+ depth = IntegerField('Depth', validators=[DataRequired()])
+ chart_type = SelectField('Chart Type of Result', choices=charts)
+
+ def validate_depth(self, field):
+ depth = field.data
+ if depth < 1 or depth > 10:
+ raise ValidationError("Depth should be in range of 1 ~ 10")
\ No newline at end of file
diff --git a/pool/shard009/Python/0087302_test2_byref.py b/pool/shard009/Python/0087302_test2_byref.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ad98fd69d4c349506f9184e19d6e01d3cde0f2b
--- /dev/null
+++ b/pool/shard009/Python/0087302_test2_byref.py
@@ -0,0 +1,54 @@
+# Licensed Materials - Property of IBM
+# Copyright IBM Corp. 2016
+import unittest
+import sys
+import itertools
+import os
+import shutil
+
+from streamsx.topology.topology import *
+from streamsx.topology.tester import Tester
+from streamsx.topology.context import ConfigParams
+import streamsx.spl.op as op
+import test_functions
+
+class CheckForEach(object):
+ def __init__(self):
+ self.expected = ['ByRef', 3, 'a', 42]
+ self.count = 0
+
+ def __call__(self, v):
+ if self.expected[self.count] != v:
+ raise AssertionError()
+ self.count += 1
+
+class TestByRef(unittest.TestCase):
+ _multiprocess_can_split_ = True
+
+ def setUp(self):
+ Tester.setup_standalone(self)
+
+ def test_ByRef(self):
+ topo = Topology()
+ s = topo.source(['ByRef', 3, list(('a', 42))])
+ s = s.map(lambda x : x)
+ s = s.flat_map(lambda x : x if isinstance(x, list) else [x])
+ s.for_each(CheckForEach())
+
+ tester = Tester(topo)
+ tester.contents(s, ['ByRef', 3, 'a', 42])
+ tester.test(self.test_ctxtype, self.test_config)
+
+ def test_NotByRef(self):
+ topo = Topology()
+ s = topo.source(['ByRef', 3, list(('a', 42))])
+ f = op.Map('spl.relational::Filter', s)
+ s = f.stream.map(lambda x : x)
+ f = op.Map('spl.relational::Filter', s)
+ s = f.stream.flat_map(lambda x : x if isinstance(x, list) else [x])
+ f = op.Map('spl.relational::Filter', s)
+ f.stream.for_each(CheckForEach())
+
+ tester = Tester(topo)
+ tester.contents(s, ['ByRef', 3, 'a', 42])
+ tester.test(self.test_ctxtype, self.test_config)
diff --git a/pool/shard009/Python/0087304_linter.py b/pool/shard009/Python/0087304_linter.py
new file mode 100644
index 0000000000000000000000000000000000000000..6cf04dfa8ff97612f06f8e71be6958ad64bfdede
--- /dev/null
+++ b/pool/shard009/Python/0087304_linter.py
@@ -0,0 +1,151 @@
+#
+# linter.py
+# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
+#
+# Written by Yanis Lukes
+# Copyright (c) 2014 Yanis Lukes
+#
+# License: MIT
+#
+
+"""This module exports the Csharplint plugin class."""
+
+import sublime
+import shlex
+
+# for completionscommon functions
+import re
+import glob
+import os
+
+from SublimeLinter.lint import Linter, util
+
+class Csharplint(Linter):
+
+ """Provides an interface to csharplint."""
+
+ syntax = ("c#", "unityc#")
+
+ base_cmd = (
+ "gmcs.bat "
+ " *"
+ " -target:library"
+ " -out:/tmp/errorcheck.dll"
+ #" -out:stdout" doesn't work like that
+ #" sdk:3.5" # Unity uses .NET 3.5
+ #" -r:./*.dll" # Recursively add all libraries within the folder of file
+ )
+ regex = (
+ r'^(?P.+\.cs)\((?P\d+),(?P\d+)\): (?:(?Perror)|(?Pwarning)) \w+: (?P.+)'
+ )
+ tempfile_suffix = '.cs'
+ error_stream = util.STREAM_BOTH # errors are on stderr
+ defaults = {
+ '--filter=,': '',
+ }
+ #comment_re = r'\s*/[/*]'
+ inline_settings = None
+ inline_overrides = 'filter'
+
+ executable = None
+ executable_path = ''
+ version_args = '--version'
+ version_re = r'(?P\d+\.\d+\.\d+)'
+ version_requirement = '>= 1.0'
+ multiline = False
+ line_col_base = (1, 1)
+ selectors = {}
+ word_re = None
+
+ def split_match(self, match):
+ """
+ Extract and return values from match.
+
+ We override this method so that the error:
+ No copyright message found.
+ You should have a line: "Copyright [year] " [legal/copyright] [5]
+ that appears on line 0 (converted to -1 because of line_col_base), can be displayed.
+
+ """
+
+ match, line, col, error, warning, message, near = super().split_match(match)
+
+ if line is not None and line == -1 and message:
+ line = 0
+
+ return match, line, col, error, warning, message, near
+
+ def cmd(self):
+ """
+ Return the command line to execute.
+
+ We override this method, so we can add extra flags and include paths
+ based on the 'include_dirs' and 'extra_flags' settings.
+
+ """
+
+ result = self.base_cmd
+
+ extra = []
+ extra = self.get_setting("completesharp_assemblies", [])
+ if len(extra) == 0:
+ return result
+
+ #result += ","
+ result += " -r:"
+
+ newextra = []
+ window = sublime.active_window()
+ for path in extra:
+ newextra.extend(glob.glob(self.expand_path(path, window, False)))
+ extra = newextra
+ cmd = ""
+ q = "\""
+
+ result += ','.join([shlex.quote(newextra) for newextra in extra])
+ #print("Result: $ '" + result + "'")
+ #result += "%s%s%s" % (q, ";;--;;".join(extra), q)
+ #
+ result += " -nostdlib" # Unity has its own
+
+ return result
+
+ # following are copied from completionscommon package:
+ def get_setting(self, key, default=None):
+ try:
+ s = sublime.active_window().active_view().settings()
+ if s.has(key):
+ return s.get(key)
+ except:
+ pass
+ return self.get_view_settings().get(key, default)
+
+ def expand_path(self, value, window=None, checkExists=True):
+ if window == None:
+ # Views can apparently be window less, in most instances getting
+ # the active_window will be the right choice (for example when
+ # previewing a file), but the one instance this is incorrect
+ # is during Sublime Text 2 session restore. Apparently it's
+ # possible for views to be windowless then too and since it's
+ # possible that multiple windows are to be restored, the
+ # "wrong" one for this view might be the active one and thus
+ # ${project_path} will not be expanded correctly.
+ #
+ # This will have to remain a known documented issue unless
+ # someone can think of something that should be done plugin
+ # side to fix this.
+ window = sublime.active_window()
+
+ get_existing_files = \
+ lambda m: [path \
+ for f in window.folders() \
+ for path in [os.path.join(f, m.group('file'))] \
+ if checkExists and os.path.exists(path) or not checkExists
+ ]
+ value = re.sub(r'\${project_path:(?P[^}]+)}', lambda m: len(get_existing_files(m)) > 0 and get_existing_files(m)[0] or m.group('file'), value)
+ value = re.sub(r'\${env:(?P[^}]+)}', lambda m: os.getenv(m.group('variable')) if os.getenv(m.group('variable')) else "%s_NOT_SET" % m.group('variable'), value)
+ value = re.sub(r'\${home}', os.getenv('HOME') if os.getenv('HOME') else "HOME_NOT_SET", value)
+ value = re.sub(r'\${folder:(?P[^}]+)}', lambda m: os.path.dirname(m.group('file')), value)
+ value = value.replace('\\', '/')
+
+ return value
diff --git a/pool/shard009/Python/0087308_views.py b/pool/shard009/Python/0087308_views.py
new file mode 100644
index 0000000000000000000000000000000000000000..174ac14fed6dd057e1972e917ffb44e3bb62a06e
--- /dev/null
+++ b/pool/shard009/Python/0087308_views.py
@@ -0,0 +1,139 @@
+# Copyright 2014 eBay Software Foundation
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless 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 oslo_log import log as logging
+
+from trove.common import cfg
+from trove.common.strategies.cluster import strategy
+from trove.common.views import create_links
+from trove.instance.views import InstanceDetailView
+
+LOG = logging.getLogger(__name__)
+CONF = cfg.CONF
+
+
+class ClusterView(object):
+
+ def __init__(self, cluster, req=None, load_servers=True):
+ self.cluster = cluster
+ self.req = req
+ self.load_servers = load_servers
+
+ def data(self):
+ instances, ip_list = self.build_instances()
+ cluster_dict = {
+ "id": self.cluster.id,
+ "name": self.cluster.name,
+ "task": {"id": self.cluster.task_id,
+ "name": self.cluster.task_name,
+ "description": self.cluster.task_description},
+ "created": self.cluster.created,
+ "updated": self.cluster.updated,
+ "links": self._build_links(),
+ "datastore": {"type": self.cluster.datastore.name,
+ "version": self.cluster.datastore_version.name},
+ "instances": instances
+ }
+ if ip_list:
+ cluster_dict["ip"] = ip_list
+
+ extended_properties = self.get_extended_properties()
+ if extended_properties:
+ cluster_dict["extended_properties"] = extended_properties
+
+ if self.cluster.locality:
+ cluster_dict['locality'] = self.cluster.locality
+ if self.cluster.configuration_id:
+ cluster_dict['configuration'] = self.cluster.configuration_id
+ LOG.debug(cluster_dict)
+ return {"cluster": cluster_dict}
+
+ def _build_links(self):
+ return create_links("clusters", self.req, self.cluster.id)
+
+ def _build_instances(self, ip_to_be_published_for=[],
+ instance_dict_to_be_published_for=[]):
+ instances = []
+ ip_list = []
+ if self.load_servers:
+ cluster_instances = self.cluster.instances
+ else:
+ cluster_instances = self.cluster.instances_without_server
+ for instance in cluster_instances:
+ instance_dict = {
+ "id": instance.id,
+ "name": instance.name,
+ "type": instance.type,
+ "links": create_links("instances", self.req, instance.id)
+ }
+ if instance.shard_id:
+ instance_dict["shard_id"] = instance.shard_id
+ if self.load_servers:
+ instance_dict["status"] = instance.status
+ if CONF.get(instance.datastore_version.manager).volume_support:
+ instance_dict["volume"] = {"size": instance.volume_size}
+ instance_dict["flavor"] = self._build_flavor_info(
+ instance.flavor_id)
+ instance_ips = instance.get_visible_ip_addresses()
+ if self.load_servers and instance_ips:
+ instance_dict["ip"] = instance_ips
+ if instance.type in ip_to_be_published_for:
+ ip_list.extend(instance_ips)
+ if instance.type in instance_dict_to_be_published_for:
+ instances.append(instance_dict)
+ return instances, ip_list
+
+ def build_instances(self):
+ raise NotImplementedError()
+
+ def get_extended_properties(self):
+ return None
+
+ def _build_flavor_info(self, flavor_id):
+ return {
+ "id": flavor_id,
+ "links": create_links("flavors", self.req, flavor_id)
+ }
+
+
+class ClusterInstanceDetailView(InstanceDetailView):
+ def __init__(self, instance, req):
+ super(ClusterInstanceDetailView, self).__init__(instance, req=req)
+
+ def data(self):
+ result = super(ClusterInstanceDetailView, self).data()
+ return result
+
+
+class ClustersView(object):
+ def __init__(self, clusters, req=None):
+ self.clusters = clusters
+ self.req = req
+
+ def data(self):
+ data = []
+ for cluster in self.clusters:
+ data.append(self.data_for_cluster(cluster))
+ return {'clusters': data}
+
+ def data_for_cluster(self, cluster):
+ view = load_view(cluster, req=self.req, load_servers=False)
+ return view.data()['cluster']
+
+
+def load_view(cluster, req, load_servers=True):
+ manager = cluster.datastore_version.manager
+ return strategy.load_api_strategy(manager).cluster_view_class(
+ cluster, req, load_servers)
diff --git a/pool/shard009/Python/0087309_996580ba7f6c_add_device_appname_column.py b/pool/shard009/Python/0087309_996580ba7f6c_add_device_appname_column.py
new file mode 100644
index 0000000000000000000000000000000000000000..23540c7851b33e41382e549463e0275decfe8590
--- /dev/null
+++ b/pool/shard009/Python/0087309_996580ba7f6c_add_device_appname_column.py
@@ -0,0 +1,24 @@
+"""add device appname column
+
+Revision ID: 996580ba7f6c
+Revises: 66bc8df33d36
+Create Date: 2017-07-12 16:19:12.192935
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '996580ba7f6c'
+down_revision = '66bc8df33d36'
+branch_labels = None
+depends_on = None
+
+def upgrade():
+ op.add_column('devices',
+ sa.Column('appname', sa.String(), nullable=True))
+
+
+def downgrade():
+ op.drop_column('devices', 'appname')
diff --git a/pool/shard009/Python/0087311_System.py b/pool/shard009/Python/0087311_System.py
new file mode 100644
index 0000000000000000000000000000000000000000..5427bfc49d6cab506e3bc2098e116713e806b095
--- /dev/null
+++ b/pool/shard009/Python/0087311_System.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+#
+# System.py
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope 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
+
+import logging
+log = logging.getLogger("Thug")
+
+class System:
+ def __init__(self):
+ pass
+
+ def getProperty(self, property):
+ if property == "java.version":
+ javaplugin = log.ThugVulnModules._javaplugin.split('.')
+ last = javaplugin.pop()
+ return '%s_%s' % ('.'.join(javaplugin), last)
+
+ if property == "java.vendor":
+ return 'Sun Microsystems Inc.'
diff --git a/pool/shard009/Python/0087317_rest.py b/pool/shard009/Python/0087317_rest.py
new file mode 100644
index 0000000000000000000000000000000000000000..a358a1f90499308c2577efaaf7e1287c2779c71e
--- /dev/null
+++ b/pool/shard009/Python/0087317_rest.py
@@ -0,0 +1,117 @@
+from flask import Blueprint, jsonify, request
+
+from twitter_feed.core.serializers.tweet_serializer import tweets_to_atom
+from twitter_feed.core.tweet import Tweet
+from twitter_feed.core.tweet_util import match_tweet_replies
+from twitter_feed.twitter.api import TwitterError, TwitterAPI
+
+
+rest_view = Blueprint('rest_view', __name__, url_prefix='/rest')
+rest_view.api = TwitterAPI
+rest_view.config = {}
+
+
+@rest_view.record
+def record_params(setup_state):
+ app = setup_state.app
+ rest_view.config = dict([(key, value) for (key, value) in app.config.items()])
+ if app.config.get('API') == 'mock':
+ from twitter_feed.twitter.api import MockAPI
+ rest_view.api = MockAPI
+
+
+@rest_view.route('/', methods=['GET'], endpoint='home')
+def home_timeline():
+
+ try:
+ api = rest_view.api(rest_view.config.get('API_URL'), rest_view.config.get('API_KEY'), rest_view.config.get('API_SECRET'))
+ tweets = Tweet.tweets_from_list(api.get_user_timeline('petrkotas'))
+ except TwitterError as error:
+ message = {
+ 'status': error.html_error,
+ 'message': error.html_status + ', ' + str(error.twitter_error) + ': ' + error.twitter_status
+ }
+ response = jsonify(message)
+ response.status_code = error.html_error
+
+ return response
+
+ try:
+ feed = tweets_to_atom(tweets, 'Home feed', request.url, request.host_url)
+ response = feed.get_response()
+ except Exception as error:
+ message = {
+ 'status': 500,
+ 'message': str(error)
+ }
+ response = jsonify(message)
+ response.status_code = 500
+
+ return response
+
+
+@rest_view.route('/users/', methods=['GET'], endpoint='user')
+def user_timeline(user):
+
+ try:
+ api = rest_view.api(rest_view.config.get('API_URL'), rest_view.config.get('API_KEY'), rest_view.config.get('API_SECRET'))
+ temp_tweets = Tweet.tweets_from_list(api.get_user_timeline(user))
+ replies = Tweet.tweets_from_list(api.get_user_replies(user))
+ tweets = []
+ for tweet in temp_tweets:
+ tweets.append(tweet)
+ repl = match_tweet_replies(tweet, replies)
+ if repl:
+ tweets.extend(repl)
+ except TwitterError as error:
+ message = {
+ 'status': error.html_error,
+ 'twitter_message': error.twitter_error
+ }
+ response = jsonify(message)
+ response.status_code = error.html_error
+
+ return response
+
+ try:
+ feed = tweets_to_atom(tweets, 'Feed for ' + user, request.url, request.host_url)
+ response = feed.get_response()
+ except Exception as error:
+ message = {
+ 'status': 500,
+ 'message': str(error)
+ }
+ response = jsonify(message)
+ response.status_code = 500
+
+ return response
+
+
+@rest_view.route('/hashtags/', methods=['GET'], endpoint='hashtag')
+def hashtag_timeline(hashtag):
+
+ try:
+ api = rest_view.api(rest_view.config.get('API_URL'), rest_view.config.get('API_KEY'), rest_view.config.get('API_SECRET'))
+ tweets = Tweet.tweets_from_list(api.get_hashtag_timeline(hashtag))
+ except TwitterError as error:
+ message = {
+ 'status': error.html_error,
+ 'twitter_message': error.twitter_error
+ }
+ response = jsonify(message)
+ response.status_code = error.html_error
+
+ return response
+
+ try:
+ feed = tweets_to_atom(tweets, 'Feed for ' + hashtag, request.url, request.host_url)
+ response = feed.get_response()
+ except Exception as error:
+ message = {
+ 'status': 500,
+ 'message': str(error)
+ }
+ response = jsonify(message)
+ response.status_code = 500
+
+ return response
diff --git a/pool/shard009/Python/0087324_test_Quaternion.py b/pool/shard009/Python/0087324_test_Quaternion.py
new file mode 100644
index 0000000000000000000000000000000000000000..05bdeab25582bf29309d5261be2aa77a1c5bf6c3
--- /dev/null
+++ b/pool/shard009/Python/0087324_test_Quaternion.py
@@ -0,0 +1,32 @@
+import unittest
+import numpy as np
+from math import cos, sin
+from pymicro.crystal.microstructure import Orientation
+
+
+class QuaternionTests(unittest.TestCase):
+
+ def setUp(self):
+ print('testing the Quaternion class')
+ self.euler_deg = [343.580, 128.653, 290.986]
+
+ def test_Euler2Quaternion(self):
+ euler_rad = np.radians(self.euler_deg)
+ # compute quaternion using the passive convention
+ q = Orientation.Euler2Quaternion(self.euler_deg, P=-1)
+
+ euler = 0.5 * euler_rad
+ c1 = cos(euler[0])
+ s1 = sin(euler[0])
+ c2 = cos(euler[1])
+ s2 = sin(euler[1])
+ c3 = cos(euler[2])
+ s3 = sin(euler[2])
+ q0 = c1 * c2 * c3 - s1 * c2 * s3
+ q1 = c1 * s2 * c3 + s1 * s2 * s3
+ q2 = -c1 * s2 * s3 + s1 * s2 * c3
+ q3 = c1 * c2 * s3 + s1 * c2 * c3
+ self.assertAlmostEqual(q.q0, q0)
+ self.assertAlmostEqual(q.q1, q1)
+ self.assertAlmostEqual(q.q2, q2)
+ self.assertAlmostEqual(q.q3, q3)
\ No newline at end of file
diff --git a/pool/shard009/Python/0087327_ngram.py b/pool/shard009/Python/0087327_ngram.py
new file mode 100644
index 0000000000000000000000000000000000000000..57c637c13f615b20231f9f107b7c80f9dd8cc88a
--- /dev/null
+++ b/pool/shard009/Python/0087327_ngram.py
@@ -0,0 +1,79 @@
+# encoding: utf-8
+# ******************************************************
+# Author : zzw922cn
+# Last modified: 2017-12-09 11:00
+# Email : zzw922cn@gmail.com
+# Filename : ngram.py
+# Description : ngram model
+# ******************************************************
+
+import numpy as np
+import os
+import operator
+import pickle
+
+def save_obj(name, obj):
+ with open(name + '.pkl', 'wb') as f:
+ pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
+
+class NGram:
+ def __init__(self, rootdir):
+ self.rootdir = rootdir
+
+ def get_corpus(self):
+ corpus = []
+ word_count = {}
+ biword_count = {}
+ bigram = {}
+ bigram['SOS'] = {}
+ trigram = {}
+ for subdir, dirs, files in os.walk(self.rootdir):
+ for f in files:
+ fullFilename = os.path.join(subdir, f)
+ filenameNoSuffix = os.path.splitext(fullFilename)[0]
+ if f.endswith('.label'):
+ with open(fullFilename, 'r') as f:
+ line = f.readline()
+ corpus.append(line)
+ line = line.strip().split(' ')
+ len_sent = range(len(line))
+ for idx in len_sent:
+ word = line[idx]
+ word_count = inc_dict(word_count, word)
+ if not bigram.has_key(word):
+ bigram[word] = {}
+ if idx == 0:
+ bigram['SOS'] = inc_dict(bigram['SOS'], word)
+ elif idx != len(line)-1:
+ bigram[word] = inc_dict(bigram[word], line[idx+1])
+ else:
+ bigram[word] = inc_dict(bigram[word], 'EOS')
+ if idx == 0:
+ tri_key = 'SOS ' + word
+ else:
+ tri_key = line[idx-1]+' '+word
+ if not trigram.has_key(tri_key):
+ trigram[tri_key] = {}
+ if idx == len(line)-1:
+ trigram[tri_key] = inc_dict(trigram[tri_key], 'EOS')
+ else:
+ trigram[tri_key] = inc_dict(trigram[tri_key], line[idx+1])
+
+ return corpus, word_count, bigram, trigram
+
+def inc_dict(dic, key):
+ if not dic.has_key(key):
+ dic[key] = 0
+ dic[key] += 1
+ return dic
+
+
+if __name__ == '__main__':
+ ngram = NGram('/media/pony/Seagate Expansion Drive/学习/语音识别/ASR数据库/LibriSpeech/')
+ corpus, word_count, bigram, trigram = ngram.get_corpus()
+ savedir = '/home/pony/github/data/libri/ngram/'
+ save_obj(savedir+'corpus', corpus)
+ save_obj(savedir+'word_count', word_count)
+ save_obj(savedir+'bigram', bigram)
+ save_obj(savedir+'trigram', trigram)
+ #sorted_word_count = sorted(word_count.items(), key=operator.itemgetter(1), reverse=True)
diff --git a/pool/shard009/Python/0087331_test_client.py b/pool/shard009/Python/0087331_test_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ebf91feec0538cddae3ce45120d69a2d76101de
--- /dev/null
+++ b/pool/shard009/Python/0087331_test_client.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+#
+# test_client.py
+#
+# Copyright (C) 2006-2020 wolfSSL Inc.
+#
+# This file is part of wolfSSL.
+#
+# wolfSSL 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.
+#
+# wolfSSL 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-1335, USA
+#/
+
+# pylint: disable=missing-docstring, invalid-name, import-error
+# pylint: disable=redefined-outer-name
+
+import pytest
+
+HOST = "www.python.org"
+PORT = 443
+CA_CERTS = "certs/ca-digicert-ev.pem"
+
+@pytest.fixture(
+ params=["wrap_socket", "wrap_socket_with_ca",
+ "wrap_socket_from_context", "ssl_socket"])
+def secure_socket(request, ssl_provider, tcp_socket):
+ sock = None
+
+ if request.param == "wrap_socket":
+ sock = ssl_provider.wrap_socket(tcp_socket)
+
+ elif request.param == "wrap_socket_with_ca":
+ sock = ssl_provider.wrap_socket(
+ tcp_socket, cert_reqs=ssl_provider.CERT_REQUIRED, ca_certs=CA_CERTS)
+
+ elif request.param == "wrap_socket_from_context":
+ ctx = ssl_provider.SSLContext(ssl_provider.PROTOCOL_TLSv1_2)
+
+ ctx.verify_mode = ssl_provider.CERT_REQUIRED
+ ctx.load_verify_locations(CA_CERTS)
+
+ sock = ctx.wrap_socket(tcp_socket)
+
+ elif request.param == "ssl_socket":
+ sock = ssl_provider.SSLSocket(
+ tcp_socket, cert_reqs=ssl_provider.CERT_REQUIRED, ca_certs=CA_CERTS)
+
+ if sock:
+ yield sock
+ sock.close()
+
+def test_secure_connection(secure_socket):
+ secure_socket.connect((HOST, PORT))
+
+ secure_socket.write(b"GET / HTTP/1.1\n\n")
+ assert secure_socket.read(4) == b"HTTP"
diff --git a/pool/shard009/Python/0087341_iomediatortest.py b/pool/shard009/Python/0087341_iomediatortest.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c8dc4897ec340fc128edd1d5f218af9d86c1606
--- /dev/null
+++ b/pool/shard009/Python/0087341_iomediatortest.py
@@ -0,0 +1,26 @@
+*/ Beta Untested Code
+
+import unittest
+
+from lib.iomediator import *
+
+class IoMediatorTest(unittest.TestCase):
+
+ def testKeySplitRe(self):
+ result = KEY_SPLIT_RE.split("+y")
+ self.assertEqual(result, ["", "+", "y"])
+
+ result = KEY_SPLIT_RE.split("asdf +y asdf ")
+ self.assertEqual(result, ["asdf ", "+", "y asdf "])
+
+ result = KEY_SPLIT_RE.split("")
+ self.assertEqual(result, ["", "", ""])
+
+ result = KEY_SPLIT_RE.split("+8CDATA+8")
+ self.assertEqual(result, ["+", "8CDATA", "+", "8"])
+
+ result = KEY_SPLIT_RE.split("y")
+ self.assertEqual(result, ["", "", "y"])
+
+ result = KEY_SPLIT_RE.split("TestMore text")
+ self.assertEqual(result, ["Test", "", "More text"])
diff --git a/pool/shard009/Python/0087343_mobile_app.py b/pool/shard009/Python/0087343_mobile_app.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a33439f517e4328eddd7aab8b6a0efd4b9240b
--- /dev/null
+++ b/pool/shard009/Python/0087343_mobile_app.py
@@ -0,0 +1,231 @@
+# -*- coding: utf-8 -*-
+
+# This file is part of Tautulli.
+#
+# Tautulli 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.
+#
+# Tautulli 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 Tautulli. If not, see .
+
+from __future__ import unicode_literals
+from future.builtins import str
+
+import requests
+import threading
+
+import plexpy
+if plexpy.PYTHON2:
+ import database
+ import helpers
+ import logger
+else:
+ from plexpy import database
+ from plexpy import helpers
+ from plexpy import logger
+
+
+_ONESIGNAL_APP_ID = '3b4b666a-d557-4b92-acdf-e2c8c4b95357'
+_ONESIGNAL_DISABLED = 'onesignal-disabled'
+
+TEMP_DEVICE_TOKENS = {}
+
+
+def set_temp_device_token(token=None, remove=False, add=False, success=False):
+ global TEMP_DEVICE_TOKENS
+
+ if token in TEMP_DEVICE_TOKENS and success:
+ if isinstance(TEMP_DEVICE_TOKENS[token], threading.Timer):
+ TEMP_DEVICE_TOKENS[token].cancel()
+ TEMP_DEVICE_TOKENS[token] = True
+
+ elif token in TEMP_DEVICE_TOKENS and remove:
+ if isinstance(TEMP_DEVICE_TOKENS[token], threading.Timer):
+ TEMP_DEVICE_TOKENS[token].cancel()
+ del TEMP_DEVICE_TOKENS[token]
+
+ elif token not in TEMP_DEVICE_TOKENS and add:
+ invalidate_time = 5 * 60 # 5 minutes
+ TEMP_DEVICE_TOKENS[token] = threading.Timer(invalidate_time, set_temp_device_token, args=[token, True])
+ TEMP_DEVICE_TOKENS[token].start()
+ logger._BLACKLIST_WORDS.add(token)
+
+
+def get_temp_device_token(token=None):
+ return TEMP_DEVICE_TOKENS.get(token)
+
+
+def get_mobile_devices(device_id=None, device_token=None):
+ where = where_id = where_token = ''
+ args = []
+
+ if device_id or device_token:
+ where = 'WHERE '
+ if device_id:
+ where_id += 'device_id = ?'
+ args.append(device_id)
+ if device_token:
+ where_token = 'device_token = ?'
+ args.append(device_token)
+ where += ' AND '.join([w for w in [where_id, where_token] if w])
+
+ db = database.MonitorDatabase()
+ result = db.select('SELECT * FROM mobile_devices %s' % where, args=args)
+
+ return result
+
+
+def get_mobile_device_by_token(device_token=None):
+ if not device_token:
+ return None
+
+ return get_mobile_devices(device_token=device_token)
+
+
+def add_mobile_device(device_id=None, device_name=None, device_token=None,
+ platform=None, version=None, friendly_name=None, onesignal_id=None):
+ db = database.MonitorDatabase()
+
+ keys = {'device_id': device_id}
+ values = {'device_name': device_name,
+ 'device_token': device_token,
+ 'platform': platform,
+ 'version': version,
+ 'onesignal_id': onesignal_id}
+
+ if friendly_name:
+ values['friendly_name'] = friendly_name
+
+ try:
+ result = db.upsert(table_name='mobile_devices', key_dict=keys, value_dict=values)
+ blacklist_logger()
+ except Exception as e:
+ logger.warn("Tautulli MobileApp :: Failed to register mobile device in the database: %s." % e)
+ return
+
+ if result == 'insert':
+ logger.info("Tautulli MobileApp :: Registered mobile device '%s' in the database." % device_name)
+ else:
+ logger.info("Tautulli MobileApp :: Re-registered mobile device '%s' in the database." % device_name)
+
+ set_last_seen(device_token=device_token)
+ threading.Thread(target=set_official, args=[device_id, onesignal_id]).start()
+ return True
+
+
+def get_mobile_device_config(mobile_device_id=None):
+ if str(mobile_device_id).isdigit():
+ mobile_device_id = int(mobile_device_id)
+ else:
+ logger.error("Tautulli MobileApp :: Unable to retrieve mobile device config: invalid mobile_device_id %s." % mobile_device_id)
+ return None
+
+ db = database.MonitorDatabase()
+ result = db.select_single('SELECT * FROM mobile_devices WHERE id = ?',
+ args=[mobile_device_id])
+
+ if result['onesignal_id'] == _ONESIGNAL_DISABLED:
+ result['onesignal_id'] = ''
+
+ return result
+
+
+def set_mobile_device_config(mobile_device_id=None, **kwargs):
+ if str(mobile_device_id).isdigit():
+ mobile_device_id = int(mobile_device_id)
+ else:
+ logger.error("Tautulli MobileApp :: Unable to set exisiting mobile device: invalid mobile_device_id %s." % mobile_device_id)
+ return False
+
+ keys = {'id': mobile_device_id}
+ values = {'friendly_name': kwargs.get('friendly_name', '')}
+
+ db = database.MonitorDatabase()
+ try:
+ db.upsert(table_name='mobile_devices', key_dict=keys, value_dict=values)
+ logger.info("Tautulli MobileApp :: Updated mobile device agent: mobile_device_id %s." % mobile_device_id)
+ blacklist_logger()
+ return True
+ except Exception as e:
+ logger.warn("Tautulli MobileApp :: Unable to update mobile device: %s." % e)
+ return False
+
+
+def delete_mobile_device(mobile_device_id=None, device_id=None):
+ db = database.MonitorDatabase()
+
+ if mobile_device_id:
+ logger.debug("Tautulli MobileApp :: Deleting mobile_device_id %s from the database." % mobile_device_id)
+ result = db.action('DELETE FROM mobile_devices WHERE id = ?', args=[mobile_device_id])
+ return True
+ elif device_id:
+ logger.debug("Tautulli MobileApp :: Deleting device_id %s from the database." % device_id)
+ result = db.action('DELETE FROM mobile_devices WHERE device_id = ?', args=[device_id])
+ return True
+ else:
+ return False
+
+
+def set_official(device_id, onesignal_id):
+ db = database.MonitorDatabase()
+ official = validate_onesignal_id(onesignal_id=onesignal_id)
+ platform = 'android' if official > 0 else None
+
+ try:
+ result = db.action('UPDATE mobile_devices '
+ 'SET official = ?, platform = coalesce(platform, ?) '
+ 'WHERE device_id = ?',
+ args=[official, platform, device_id])
+ except Exception as e:
+ logger.warn("Tautulli MobileApp :: Failed to set official flag for device: %s." % e)
+ return
+
+
+def set_last_seen(device_token=None):
+ db = database.MonitorDatabase()
+ last_seen = helpers.timestamp()
+
+ try:
+ result = db.action('UPDATE mobile_devices SET last_seen = ? WHERE device_token = ?',
+ args=[last_seen, device_token])
+ except Exception as e:
+ logger.warn("Tautulli MobileApp :: Failed to set last_seen time for device: %s." % e)
+ return
+
+
+def validate_onesignal_id(onesignal_id):
+ if onesignal_id is None:
+ return 0
+ elif onesignal_id == _ONESIGNAL_DISABLED:
+ return 2
+
+ headers = {'Content-Type': 'application/json'}
+ payload = {'app_id': _ONESIGNAL_APP_ID}
+
+ logger.info("Tautulli MobileApp :: Validating OneSignal ID")
+ try:
+ r = requests.get('https://onesignal.com/api/v1/players/{}'.format(onesignal_id), headers=headers, json=payload)
+ status_code = r.status_code
+ logger.info("Tautulli MobileApp :: OneSignal ID validation returned status code %s", status_code)
+ return int(status_code == 200)
+ except Exception as e:
+ logger.warn("Tautulli MobileApp :: Failed to validate OneSignal ID: %s." % e)
+ return -1
+
+
+def revalidate_onesignal_ids():
+ for device in get_mobile_devices():
+ set_official(device['device_id'], device['onesignal_id'])
+
+
+def blacklist_logger():
+ devices = get_mobile_devices()
+ for d in devices:
+ logger.blacklist_config(d)
diff --git a/pool/shard009/Python/0087346_release.py b/pool/shard009/Python/0087346_release.py
new file mode 100644
index 0000000000000000000000000000000000000000..59ac9122e8b54b4308ec77b97270500ff89ac9a0
--- /dev/null
+++ b/pool/shard009/Python/0087346_release.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python
+
+"""
+Script to fully automate the release process. Requires Python 2.6+
+with sphinx installed and the 'hg' command on the path.
+"""
+
+from __future__ import print_function
+
+import subprocess
+import shutil
+import os
+import sys
+import urllib2
+import getpass
+import collections
+import itertools
+import re
+
+try:
+ import keyring
+except Exception:
+ pass
+
+VERSION = '0.6.49'
+PACKAGE_INDEX = 'https://pypi.python.org/pypi'
+PACKAGE_INDEX = 'https://pypi.python.org/pypi'
+
+def get_next_version():
+ digits = map(int, VERSION.split('.'))
+ digits[-1] += 1
+ return '.'.join(map(str, digits))
+
+NEXT_VERSION = get_next_version()
+
+files_with_versions = ('docs/conf.py', 'setup.py', 'release.py',
+ 'README.txt', 'distribute_setup.py')
+
+def get_repo_name():
+ """
+ Get the repo name from the hgrc default path.
+ """
+ default = subprocess.check_output('hg paths default').strip()
+ parts = default.split('/')
+ if parts[-1] == '':
+ parts.pop()
+ return '/'.join(parts[-2:])
+
+def get_mercurial_creds(system='https://bitbucket.org', username=None):
+ """
+ Return named tuple of username,password in much the same way that
+ Mercurial would (from the keyring).
+ """
+ # todo: consider getting this from .hgrc
+ username = username or getpass.getuser()
+ keyring_username = '@@'.join((username, system))
+ system = 'Mercurial'
+ password = (
+ keyring.get_password(system, keyring_username)
+ if 'keyring' in globals()
+ else None
+ )
+ if not password:
+ password = getpass.getpass()
+ Credential = collections.namedtuple('Credential', 'username password')
+ return Credential(username, password)
+
+def add_milestone_and_version(version=NEXT_VERSION):
+ auth = 'Basic ' + ':'.join(get_mercurial_creds()).encode('base64').strip()
+ headers = {
+ 'Authorization': auth,
+ }
+ base = 'https://api.bitbucket.org'
+ for type in 'milestones', 'versions':
+ url = (base + '/1.0/repositories/{repo}/issues/{type}'
+ .format(repo = get_repo_name(), type=type))
+ req = urllib2.Request(url = url, headers = headers,
+ data='name='+version)
+ try:
+ urllib2.urlopen(req)
+ except urllib2.HTTPError as e:
+ print(e.fp.read())
+
+def bump_versions():
+ list(map(bump_version, files_with_versions))
+
+def bump_version(filename):
+ with open(filename, 'rb') as f:
+ lines = [line.replace(VERSION, NEXT_VERSION) for line in f]
+ with open(filename, 'wb') as f:
+ f.writelines(lines)
+
+def do_release():
+ assert all(map(os.path.exists, files_with_versions)), (
+ "Expected file(s) missing")
+
+ assert has_sphinx(), "You must have Sphinx installed to release"
+
+ res = raw_input('Have you read through the SCM changelog and '
+ 'confirmed the changelog is current for releasing {VERSION}? '
+ .format(**globals()))
+ if not res.lower().startswith('y'):
+ print("Please do that")
+ raise SystemExit(1)
+
+ print("Travis-CI tests: http://travis-ci.org/#!/jaraco/setuptools")
+ res = raw_input('Have you or has someone verified that the tests '
+ 'pass on this revision? ')
+ if not res.lower().startswith('y'):
+ print("Please do that")
+ raise SystemExit(2)
+
+ subprocess.check_call(['hg', 'tag', VERSION])
+
+ subprocess.check_call(['hg', 'update', VERSION])
+
+ linkify('CHANGES.txt', 'CHANGES (links).txt')
+
+ has_docs = build_docs()
+ if os.path.isdir('./dist'):
+ shutil.rmtree('./dist')
+ cmd = [
+ sys.executable, 'setup.py', '-q',
+ 'egg_info', '-RD', '-b', '',
+ 'sdist',
+ 'register', '-r', PACKAGE_INDEX,
+ 'upload', '-r', PACKAGE_INDEX,
+ ]
+ if has_docs:
+ cmd.extend(['upload_docs', '-r', PACKAGE_INDEX])
+ subprocess.check_call(cmd)
+ upload_bootstrap_script()
+
+ # update to the tip for the next operation
+ subprocess.check_call(['hg', 'update'])
+
+ # we just tagged the current version, bump for the next release.
+ bump_versions()
+ subprocess.check_call(['hg', 'ci', '-m',
+ 'Bumped to {NEXT_VERSION} in preparation for next '
+ 'release.'.format(**globals())])
+
+ # push the changes
+ subprocess.check_call(['hg', 'push'])
+
+ add_milestone_and_version()
+
+def has_sphinx():
+ try:
+ devnull = open(os.path.devnull, 'wb')
+ subprocess.Popen(['sphinx-build', '--version'], stdout=devnull,
+ stderr=subprocess.STDOUT).wait()
+ except Exception:
+ return False
+ return True
+
+def build_docs():
+ if not os.path.isdir('docs'):
+ return
+ if os.path.isdir('docs/build'):
+ shutil.rmtree('docs/build')
+ cmd = [
+ 'sphinx-build',
+ '-b', 'html',
+ '-d', 'build/doctrees',
+ '.',
+ 'build/html',
+ ]
+ subprocess.check_call(cmd, cwd='docs')
+ return True
+
+def upload_bootstrap_script():
+ scp_command = 'pscp' if sys.platform.startswith('win') else 'scp'
+ try:
+ subprocess.check_call([scp_command, 'distribute_setup.py',
+ 'pypi@ziade.org:python-distribute.org/'])
+ except:
+ print("Unable to upload bootstrap script. Ask Tarek to do it.")
+
+def linkify(source, dest):
+ with open(source) as source:
+ out = _linkified_text(source.read())
+ with open(dest, 'w') as dest:
+ dest.write(out)
+
+def _linkified(rst_path):
+ "return contents of reStructureText file with linked issue references"
+ rst_file = open(rst_path)
+ rst_content = rst_file.read()
+ rst_file.close()
+
+ return _linkified_text(rst_content)
+
+def _linkified_text(rst_content):
+ # first identify any existing HREFs so they're not changed
+ HREF_pattern = re.compile('`.*?`_', re.MULTILINE | re.DOTALL)
+
+ # split on the HREF pattern, returning the parts to be linkified
+ plain_text_parts = HREF_pattern.split(rst_content)
+ anchors = []
+ linkified_parts = [_linkified_part(part, anchors)
+ for part in plain_text_parts]
+ pairs = itertools.izip_longest(
+ linkified_parts,
+ HREF_pattern.findall(rst_content),
+ fillvalue='',
+ )
+ rst_content = ''.join(flatten(pairs))
+
+ anchors = sorted(anchors)
+
+ bitroot = 'http://bitbucket.org/tarek/distribute'
+ rst_content += "\n"
+ for x in anchors:
+ issue = re.findall(r'\d+', x)[0]
+ rst_content += '.. _`%s`: %s/issue/%s\n' % (x, bitroot, issue)
+ rst_content += "\n"
+ return rst_content
+
+def flatten(listOfLists):
+ "Flatten one level of nesting"
+ return itertools.chain.from_iterable(listOfLists)
+
+
+def _linkified_part(text, anchors):
+ """
+ Linkify a part and collect any anchors generated
+ """
+ revision = re.compile(r'\b(issue\s+#?\d+)\b', re.M | re.I)
+
+ anchors.extend(revision.findall(text)) # ['Issue #43', ...]
+ return revision.sub(r'`\1`_', text)
+
+if __name__ == '__main__':
+ do_release()
diff --git a/pool/shard009/Python/0087348_dispatcher_server.py b/pool/shard009/Python/0087348_dispatcher_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..47674c2e80645c6f05500d53546acb7bee183710
--- /dev/null
+++ b/pool/shard009/Python/0087348_dispatcher_server.py
@@ -0,0 +1,34 @@
+#!/usr/bin/python
+#-*- coding:utf-8 -*-
+
+import sys
+import socket
+import json
+import random
+import struct
+import kive.http.http_server as http_server
+import kive.http.http_protocol as http_protocol
+import kive.config.settings as settings
+from kive.app.app import *
+import kive.status.status as status
+
+
+def on_http_data(fd, http_req):
+ if settings.Debug:
+ print "body:", http_req
+ url = http_req[:http_req.find("\r\n")].split(" ")[1]
+ if settings.Debug:
+ print fd, url
+
+ status.status.msgs += 1
+ status.status.add_remote(fd, url)
+
+ return "", http_protocol.responseData("hello...")
+
+def on_socket_data(fd, data):
+ if not data.endswith("\r\n\r\n"):
+ return data, ""
+ return on_http_data(fd, data)
+
+def on_data(fd, data):
+ return on_socket_data(fd, data)
diff --git a/pool/shard009/Python/0087350_test_api_openstack_v1_views_stacks_view_builder.py b/pool/shard009/Python/0087350_test_api_openstack_v1_views_stacks_view_builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..cbf9048309c115ba728e30c9d512653a5c10dec7
--- /dev/null
+++ b/pool/shard009/Python/0087350_test_api_openstack_v1_views_stacks_view_builder.py
@@ -0,0 +1,180 @@
+#
+# 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 mock
+
+from heat.api.openstack.v1.views import stacks_view
+from heat.common import identifier
+from heat.tests import common
+
+
+class TestFormatStack(common.HeatTestCase):
+ def setUp(self):
+ super(TestFormatStack, self).setUp()
+ self.request = mock.Mock()
+
+ def test_doesnt_include_stack_action(self):
+ stack = {'stack_action': 'CREATE'}
+
+ result = stacks_view.format_stack(self.request, stack)
+ self.assertEqual({}, result)
+
+ def test_merges_stack_action_and_status(self):
+ stack = {'stack_action': 'CREATE',
+ 'stack_status': 'COMPLETE'}
+
+ result = stacks_view.format_stack(self.request, stack)
+ self.assertIn('stack_status', result)
+ self.assertEqual('CREATE_COMPLETE', result['stack_status'])
+
+ def test_include_stack_status_with_no_action(self):
+ stack = {'stack_status': 'COMPLETE'}
+
+ result = stacks_view.format_stack(self.request, stack)
+ self.assertIn('stack_status', result)
+ self.assertEqual('COMPLETE', result['stack_status'])
+
+ @mock.patch.object(stacks_view, 'util')
+ def test_replace_stack_identity_with_id_and_links(self, mock_util):
+ mock_util.make_link.return_value = 'blah'
+ stack = {'stack_identity': {'stack_id': 'foo'}}
+
+ result = stacks_view.format_stack(self.request, stack)
+ self.assertIn('id', result)
+ self.assertNotIn('stack_identity', result)
+ self.assertEqual('foo', result['id'])
+
+ self.assertIn('links', result)
+ self.assertEqual(['blah'], result['links'])
+
+ @mock.patch.object(stacks_view, 'util', new=mock.Mock())
+ def test_doesnt_add_project_by_default(self):
+ stack = {'stack_identity': {'stack_id': 'foo', 'tenant': 'bar'}}
+
+ result = stacks_view.format_stack(self.request, stack, None)
+ self.assertNotIn('project', result)
+
+ @mock.patch.object(stacks_view, 'util', new=mock.Mock())
+ def test_doesnt_add_project_if_tenant_safe(self):
+ stack = {'stack_identity': {'stack_id': 'foo', 'tenant': 'bar'}}
+
+ result = stacks_view.format_stack(self.request, stack,
+ None, tenant_safe=True)
+ self.assertNotIn('project', result)
+
+ @mock.patch.object(stacks_view, 'util', new=mock.Mock())
+ def test_adds_project_if_not_tenant_safe(self):
+ stack = {'stack_identity': {'stack_id': 'foo', 'tenant': 'bar'}}
+
+ result = stacks_view.format_stack(self.request, stack,
+ None, tenant_safe=False)
+ self.assertIn('project', result)
+ self.assertEqual('bar', result['project'])
+
+ def test_includes_all_other_keys(self):
+ stack = {'foo': 'bar'}
+
+ result = stacks_view.format_stack(self.request, stack)
+ self.assertIn('foo', result)
+ self.assertEqual('bar', result['foo'])
+
+ def test_filter_out_all_but_given_keys(self):
+ stack = {
+ 'foo1': 'bar1',
+ 'foo2': 'bar2',
+ 'foo3': 'bar3',
+ }
+
+ result = stacks_view.format_stack(self.request, stack, ['foo2'])
+ self.assertIn('foo2', result)
+ self.assertNotIn('foo1', result)
+ self.assertNotIn('foo3', result)
+
+
+class TestStacksViewBuilder(common.HeatTestCase):
+ def setUp(self):
+ super(TestStacksViewBuilder, self).setUp()
+ self.request = mock.Mock()
+ self.request.params = {}
+ identity = identifier.HeatIdentifier('123456', 'wordpress', '1')
+ self.stack1 = {
+ u'stack_identity': dict(identity),
+ u'updated_time': u'2012-07-09T09:13:11Z',
+ u'template_description': u'blah',
+ u'description': u'blah',
+ u'stack_status_reason': u'Stack successfully created',
+ u'creation_time': u'2012-07-09T09:12:45Z',
+ u'stack_name': identity.stack_name,
+ u'stack_action': u'CREATE',
+ u'stack_status': u'COMPLETE',
+ u'parameters': {'foo': 'bar'},
+ u'outputs': ['key', 'value'],
+ u'notification_topics': [],
+ u'capabilities': [],
+ u'disable_rollback': True,
+ u'timeout_mins': 60,
+ }
+
+ def test_stack_index(self):
+ stacks = [self.stack1]
+ stack_view = stacks_view.collection(self.request, stacks)
+ self.assertIn('stacks', stack_view)
+ self.assertEqual(1, len(stack_view['stacks']))
+
+ @mock.patch.object(stacks_view, 'format_stack')
+ def test_stack_basic_details(self, mock_format_stack):
+ stacks = [self.stack1]
+ expected_keys = stacks_view.basic_keys
+
+ stacks_view.collection(self.request, stacks)
+ mock_format_stack.assert_called_once_with(self.request,
+ self.stack1,
+ expected_keys,
+ mock.ANY)
+
+ @mock.patch.object(stacks_view.views_common, 'get_collection_links')
+ def test_append_collection_links(self, mock_get_collection_links):
+ # If the page is full, assume a next page exists
+ stacks = [self.stack1]
+ mock_get_collection_links.return_value = 'fake links'
+ stack_view = stacks_view.collection(self.request, stacks)
+ self.assertIn('links', stack_view)
+
+ @mock.patch.object(stacks_view.views_common, 'get_collection_links')
+ def test_doesnt_append_collection_links(self, mock_get_collection_links):
+ stacks = [self.stack1]
+ mock_get_collection_links.return_value = None
+ stack_view = stacks_view.collection(self.request, stacks)
+ self.assertNotIn('links', stack_view)
+
+ @mock.patch.object(stacks_view.views_common, 'get_collection_links')
+ def test_append_collection_count(self, mock_get_collection_links):
+ stacks = [self.stack1]
+ count = 1
+ stack_view = stacks_view.collection(self.request, stacks, count)
+ self.assertIn('count', stack_view)
+ self.assertEqual(1, stack_view['count'])
+
+ @mock.patch.object(stacks_view.views_common, 'get_collection_links')
+ def test_doesnt_append_collection_count(self, mock_get_collection_links):
+ stacks = [self.stack1]
+ stack_view = stacks_view.collection(self.request, stacks)
+ self.assertNotIn('count', stack_view)
+
+ @mock.patch.object(stacks_view.views_common, 'get_collection_links')
+ def test_appends_collection_count_of_zero(self, mock_get_collection_links):
+ stacks = [self.stack1]
+ count = 0
+ stack_view = stacks_view.collection(self.request, stacks, count)
+ self.assertIn('count', stack_view)
+ self.assertEqual(0, stack_view['count'])
diff --git a/pool/shard009/Python/0087355_dga.py b/pool/shard009/Python/0087355_dga.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bbfa3eff03da8f20039055aeb0a4bca87202896
--- /dev/null
+++ b/pool/shard009/Python/0087355_dga.py
@@ -0,0 +1,39 @@
+import argparse
+
+def ror32(v, n):
+ return ((v >> n) | (v << (32-n))) & 0xFFFFFFFF
+
+def next_domain(r, c, l, tld):
+ domain = ""
+ for _ in range(l):
+ r = ror32((321167 * r + c) & 0xFFFFFFFF, 16);
+ domain += chr( (r & 0x17FF) % 26 + ord('a') )
+
+ domain += tld
+ print(domain)
+ return r
+
+def dga(version):
+ if version == 1:
+ r = 0xC87C8A78
+ c = -1719405398
+ l = 17
+ tld = '.net'
+ nr = 300
+ elif version == 2:
+ r = 0x851A3E59
+ c = -1916503263
+ l = 10
+ tld = '.com'
+ nr = 300
+ for _ in range(nr):
+ r = next_domain(r, c, l, tld)
+
+if __name__=="__main__":
+ parser = argparse.ArgumentParser(description="DGA of Fobber")
+ parser.add_argument("version", choices=[1,2], type=int)
+ args = parser.parse_args()
+ dga(args.version)
+
+
+
diff --git a/pool/shard009/Python/0087356_bullet.py b/pool/shard009/Python/0087356_bullet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8720c18b9bc8511820ebf355d1feb4ed7fe5470
--- /dev/null
+++ b/pool/shard009/Python/0087356_bullet.py
@@ -0,0 +1,46 @@
+import pygame
+import movable
+import math
+
+
+class Bullet(movable.Movable):
+ def __init__(self, (x, y), (x2, y2), world_width, world_height):
+ movable.Movable.__init__(self, x, y, world_width, world_height)
+ self.mColor = (0, 200, 255)
+ self.mType = 3
+ self.mWorldWidth = world_width
+ self.mWorldheight = world_height
+ self.mColor = (33, 150, 243)
+ self.mGun = 0
+ self.mAngle = 0
+ self.mDeltaX = 0
+ self.mDeltaY = 0
+ self.mGunX = 0
+ self.mGunY = 0
+ self.mKill = 0
+
+ def draw(self, surface):
+ self.mDeltaX = math.cos(math.radians(self.mAngle)) * 10 + self.mGunX
+ self.mDeltaY = math.sin(math.radians(self.mAngle)) * 10 + self.mGunY
+ pygame.draw.line(surface,
+ self.mColor,
+ (self.mGunX, self.mGunY), # point 1
+ (self.mDeltaX, self.mDeltaY), # point 2
+ 1) # width
+
+ def evolve(self):
+ self.mGunX = math.cos(math.radians(self.mAngle)) + self.mGunX
+ self.mGunY = math.sin(math.radians(self.mAngle)) + self.mGunY
+ self.move()
+ self.mKill += 1
+
+ if self.mKill == 10:
+ del self
+
+ def shoot(self, point, angle):
+ self.mAngle = angle
+ self.mGunX = point[0]
+ self.mGunY = point[1]
+ pass
+
+
diff --git a/pool/shard009/Python/0087357_create_stream.py b/pool/shard009/Python/0087357_create_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..01c19b69048140f7b30cfe7a6156ae7cf029dd22
--- /dev/null
+++ b/pool/shard009/Python/0087357_create_stream.py
@@ -0,0 +1,32 @@
+from __future__ import absolute_import
+from __future__ import print_function
+
+from typing import Any
+
+from zerver.lib.actions import create_stream_if_needed
+from zerver.lib.str_utils import force_text
+from zerver.lib.management import ZulipBaseCommand
+
+from argparse import ArgumentParser
+import sys
+
+class Command(ZulipBaseCommand):
+ help = """Create a stream, and subscribe all active users (excluding bots).
+
+This should be used for TESTING only, unless you understand the limitations of
+the command."""
+
+ def add_arguments(self, parser):
+ # type: (ArgumentParser) -> None
+ self.add_realm_args(parser, True, "realm in which to create the stream")
+ parser.add_argument('stream_name', metavar='', type=str,
+ help='name of stream to create')
+
+ def handle(self, *args, **options):
+ # type: (*Any, **str) -> None
+ realm = self.get_realm(options)
+ assert realm is not None # Should be ensured by parser
+
+ encoding = sys.getfilesystemencoding()
+ stream_name = options['stream_name']
+ create_stream_if_needed(realm, force_text(stream_name, encoding))
diff --git a/pool/shard009/Python/0087359_agentNonConforming.py b/pool/shard009/Python/0087359_agentNonConforming.py
new file mode 100644
index 0000000000000000000000000000000000000000..e653b78bdbbf902df8608a571abcfb3b220d0824
--- /dev/null
+++ b/pool/shard009/Python/0087359_agentNonConforming.py
@@ -0,0 +1,123 @@
+#!/usr/bin/python -tt
+
+# An incredibly simple agent. All we do is find the closest enemy tank, drive
+# towards it, and shoot. Note that if friendly fire is allowed, you will very
+# often kill your own tanks with this code.
+
+#################################################################
+# NOTE TO STUDENTS
+# This is a starting point for you. You will need to greatly
+# modify this code if you want to do anything useful. But this
+# should help you to know how to interact with BZRC in order to
+# get the information you need.
+#
+# After starting the bzrflag server, this is one way to start
+# this code:
+# python agent0.py [hostname] [port]
+#
+# Often this translates to something like the following (with the
+# port name being printed out by the bzrflag server):
+# python agent0.py localhost 49857
+#################################################################
+
+import sys
+import math
+import time
+import random
+
+from bzrc import BZRC, Command
+RADIUS = 30
+
+class Agent(object):
+ """Class handles all command and control logic for a teams tanks."""
+
+ def __init__(self, bzrc):
+ self.bzrc = bzrc
+ self.constants = self.bzrc.get_constants()
+ mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff()
+ self.original = [(tank.x,tank.y) for tank in mytanks]
+ self.direction = [(1 if tank.x < 0 else -1,1 if tank.y < 0 else -1) for tank in mytanks]
+ self.goal = [None for tank in mytanks]
+ self.commands = []
+
+ def tick(self, time_diff):
+ """Some time has passed; decide what to do next."""
+ mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff()
+ self.mytanks = mytanks
+ self.flags = flags
+ self.shots = shots
+ self.othertanks = othertanks
+ self.enemies = [tank for tank in othertanks if tank.color !=
+ self.constants['team']]
+
+ self.commands = []
+
+ for tank in mytanks:
+ index = tank.index
+ if self.goal[index] != None and abs(tank.x - self.goal[index][0]) < 10 and abs(tank.y - self.goal[index][1]) < 10:
+ self.goal[index] = None
+
+ if self.goal[index] == None:
+ #starting from this point choose new random circle to move along
+ self.original[index] = (tank.x,tank.y)
+ self.direction[index] = (1 if bool(random.getrandbits(1)) else -1, 1 if bool(random.getrandbits(1)) else -1)
+ self.goal[index] = (min(max(self.direction[index][0] * RADIUS + tank.x,-400),400),min(max(self.direction[index][1] * RADIUS + tank.y,-400),400))
+ # print "%d -> %s" % (index, self.goal[index])
+
+ #tanks will travel in wave pattern
+ self.move_to_position(tank, self.goal[index])
+
+
+ results = self.bzrc.do_commands(self.commands)
+
+ def move_to_position(self, tank, goal):
+ """Set command to move to given coordinates."""
+ #tank is moving along circle with radius RADIUS
+ target_angle = math.atan2(goal[1] - tank.y,
+ goal[0] - tank.x)
+ relative_angle = self.normalize_angle(target_angle - tank.angle)
+ command = Command(tank.index, random.random(), relative_angle, True)
+ self.commands.append(command)
+
+ def normalize_angle(self, angle):
+ """Make any angle be between +/- pi."""
+ angle -= 2 * math.pi * int (angle / (2 * math.pi))
+ if angle <= -math.pi:
+ angle += 2 * math.pi
+ elif angle > math.pi:
+ angle -= 2 * math.pi
+ return angle
+
+
+def main():
+ # Process CLI arguments.
+ try:
+ execname, host, port = sys.argv
+ except ValueError:
+ execname = sys.argv[0]
+ print >>sys.stderr, '%s: incorrect number of arguments' % execname
+ print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0]
+ sys.exit(-1)
+
+ # Connect.
+ #bzrc = BZRC(host, int(port), debug=True)
+ bzrc = BZRC(host, int(port))
+
+ agent = Agent(bzrc)
+
+ prev_time = time.time()
+
+ # Run the agent
+ try:
+ while True:
+ time_diff = time.time() - prev_time
+ agent.tick(time_diff)
+ except KeyboardInterrupt:
+ print "Exiting due to keyboard interrupt."
+ bzrc.close()
+
+
+if __name__ == '__main__':
+ main()
+
+# vim: et sw=4 sts=4
diff --git a/pool/shard009/Python/0087361_plot.py b/pool/shard009/Python/0087361_plot.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cb8cb85da30c284fc6d1add4a64f0ca5807b9aa
--- /dev/null
+++ b/pool/shard009/Python/0087361_plot.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python2.7
+
+import json
+import matplotlib.pyplot as plt
+
+statefile = open('/tmp/pitmon.json')
+readings = json.load(statefile)
+x = []
+y1 = []
+y2 = []
+y2 = []
+y3 = []
+y4 = []
+y5 = []
+l = []
+t = []
+
+idx = 0
+tick = 0
+for reading in readings:
+ x.append(idx)
+ y1.append(reading['COOK_TEMP'])
+ y2.append(reading['FOOD1_TEMP'])
+ y3.append(reading['FOOD2_TEMP'])
+ y4.append(reading['FOOD3_TEMP'])
+ y5.append(reading['OUTPUT_PERCENT'])
+ if idx % 5 == 0:
+ t.append(idx)
+ l.append(reading['TIME'][:5])
+ tick += 1
+ idx += 1
+
+plt.plot(x, y1, "rs", x, y2, "b^", x, y3, "gp", x, y4, "mD", x, y5, "k+--")
+plt.ylabel('Temperature F')
+plt.xticks(t, l)
+plt.show()
diff --git a/pool/shard009/Python/0087364_data_table_widget.py b/pool/shard009/Python/0087364_data_table_widget.py
new file mode 100644
index 0000000000000000000000000000000000000000..1be7781f5a43a89d5f0183a912d29388ab1cfaa3
--- /dev/null
+++ b/pool/shard009/Python/0087364_data_table_widget.py
@@ -0,0 +1,202 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from PyQt4.Qt import *
+from PyQt4 import QtGui
+
+from dysense.core.utility import make_unicode, pretty, limit_decimal_places, format_decimal_places
+
+class DataTableWidget(QWidget):
+
+ def __init__(self, *args):
+ QWidget.__init__(self, *args)
+
+ self.setup_ui()
+
+ # Associate sensor ID with list of metadata for each piece of data it outputs.
+ self.sensor_id_to_data_info = {}
+
+ # Associate row index with sensor ID
+ self.row_index_to_sensor_id = {}
+ self.sensor_id_to_row_index = {}
+
+ # Track which sensors IDs have shown data in table.
+ # key - sensor_id
+ # value - true if have already shown data in table for this sensor.
+ self.sensor_id_to_data_status = {}
+
+ def setup_ui(self):
+
+ self.button_font = QtGui.QFont()
+ self.button_font.setPointSize(12)
+
+ table_font = QtGui.QFont()
+ table_font.setPointSize(11)
+
+ self.central_layout = QVBoxLayout(self)
+
+ self.data_table = QTableWidget()
+ self.data_table.setFont(table_font)
+ self.data_table.setSelectionBehavior(QAbstractItemView.SelectRows)
+ self.data_table.verticalHeader().setVisible(False)
+ self.data_table.cellClicked.connect(self.cell_clicked)
+ self.data_table.cellDoubleClicked.connect(self.cell_double_clicked)
+
+ self.hint_label = QLabel('Hint: Click a row to auto-update column sizes and header names')
+ self.hint_label.setFont(QFont('label_font', pointSize=14))
+ self.hint_label.setAlignment(Qt.AlignCenter)
+
+ self.central_layout.addWidget(self.data_table)
+ self.central_layout.addWidget(self.hint_label)
+
+ def refresh_table(self):
+
+ if len(self.sensor_id_to_data_info) == 0:
+ self.data_table.setColumnCount(0)
+ self.data_table.setRowCount(0)
+ return # no sensors to show in table
+
+ # First alphabetize sensors
+ sorted_sensor_ids = sorted(self.sensor_id_to_data_info.keys())
+
+ # Add one to for Sensor Name column
+ required_columns = max([len(info) for info in self.sensor_id_to_data_info.values()])
+ required_columns += 1
+
+ # Remove all rows so we can re-add everything.
+ self.data_table.setRowCount(0)
+ self.row_index_to_sensor_id = {}
+ self.sensor_id_to_row_index = {}
+
+ self.data_table.setColumnCount(required_columns)
+
+ for row_idx, sensor_id in enumerate(sorted_sensor_ids):
+
+ info = self.sensor_id_to_data_info[sensor_id]
+
+ self.data_table.insertRow(row_idx)
+
+ self.row_index_to_sensor_id[row_idx] = sensor_id
+ self.sensor_id_to_row_index[sensor_id] = row_idx
+
+ for column_idx in range(required_columns):
+ #for column_idx in range(len(info)):
+
+ table_item = QTableWidgetItem()
+ table_item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
+
+ # Works but greys everything out and prevents cells from being selected at all.
+ #item_flags = Qt.ItemFlags()
+ #item_flags = item_flags & (~Qt.ItemIsEditable)
+ #table_item.setFlags(item_flags)
+
+ if column_idx == 0:
+ table_item.setText(sensor_id)
+
+ if column_idx > len(info):
+ # Gray out cells that shouldn't have data.
+ table_item.setBackground(QtGui.QColor(150,150,150))
+
+ self.data_table.setItem(row_idx, column_idx, table_item)
+
+ # Default to showing column headers for first sensor
+ if row_idx == 0:
+ column_headers = self.get_all_column_headers(info)
+ self.data_table.setHorizontalHeaderLabels(column_headers)
+
+ self.data_table.resizeColumnsToContents()
+ # If set to stretch then user can't resize columns.
+ #self.data_table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
+ #self.data_table.horizontalHeader().setStretchLastSection(True)
+
+ def add_sensor(self, sensor_id, sensor_info):
+
+ data_info = sensor_info['metadata']['data']
+
+ self.sensor_id_to_data_info[sensor_id] = data_info
+
+ # Indicate that haven't shown data for this sensor yet.
+ self.sensor_id_to_data_status[sensor_id] = False
+
+ self.refresh_table()
+
+ def remove_sensor(self, sensor_id):
+
+ del self.sensor_id_to_data_info[sensor_id]
+
+ self.refresh_table()
+
+ def cell_clicked(self, row_idx, col_idx):
+
+ # Use row index that was clicked on to find corresponding sensor info.
+ sensor_id = self.row_index_to_sensor_id[row_idx]
+ data_info = self.sensor_id_to_data_info[sensor_id]
+
+ column_headers = self.get_all_column_headers(data_info)
+
+ self.data_table.setHorizontalHeaderLabels(column_headers)
+
+ self.data_table.resizeColumnsToContents()
+
+ def cell_double_clicked(self, row_idx, col_idx):
+ # Treat this as a single click since user shouldn't be able to edit the cell contents.
+ self.cell_clicked(row_idx, col_idx)
+
+ def get_all_column_headers(self, data_info):
+
+ column_headers = self.get_data_column_headers(data_info)
+
+ column_headers.insert(0, 'Sensor Name')
+
+ num_blank_columns = self.data_table.columnCount() - len(column_headers)
+ if num_blank_columns > 0:
+ column_headers += [''] * num_blank_columns
+
+ return column_headers
+
+ def get_data_column_headers(self, data_info):
+
+ data_column_headers = []
+ for data_element in data_info:
+
+ column_name = pretty(data_element['name'])
+
+ try:
+ column_name += '\n({})'.format(data_element['units'])
+ except KeyError:
+ pass # don't include units
+
+ data_column_headers.append(column_name)
+
+ return data_column_headers
+
+ def refresh_sensor_data(self, sensor_id, new_set_of_data):
+
+ row_index = self.sensor_id_to_row_index[sensor_id]
+ data_info = self.sensor_id_to_data_info[sensor_id]
+
+ for i, data_value in enumerate(new_set_of_data):
+
+ # Add one since first column is sensor name.
+ column_index = i + 1
+
+ table_item = self.data_table.item(row_index, column_index)
+ if table_item is None:
+ continue # set of data is larger than expected
+
+ if isinstance(data_value, float):
+ try:
+ desired_decimal_places = data_info[i]['decimal_places']
+ data_value = format_decimal_places(data_value, desired_decimal_places)
+ except KeyError:
+ # Number of decimals not specified so limit at 5.
+ data_value = limit_decimal_places(data_value, 5)
+
+ table_item.setText(make_unicode(data_value))
+
+ if not self.sensor_id_to_data_status[sensor_id]:
+ # First time showing data for this sensor show make sure columns are big enough to show it.
+ self.data_table.resizeColumnsToContents()
+ else:
+ # Remember that we've shown data for this sensor because constantly resizing looks funny.
+ self.sensor_id_to_data_status[sensor_id] = True
diff --git a/pool/shard009/Python/0087365_pruss.py b/pool/shard009/Python/0087365_pruss.py
new file mode 100644
index 0000000000000000000000000000000000000000..30328c26e372a3e996995f30547a0b6f07c63a7d
--- /dev/null
+++ b/pool/shard009/Python/0087365_pruss.py
@@ -0,0 +1,24 @@
+from app.pru import PRU
+import pru0_constants
+import pru1_constants
+import pru_constants
+
+#List available PRUs for the chip
+pru0 = None
+pru1 = None
+
+def get_hash():
+ global pru0, pru1
+
+ if pru0 is None:
+ pru0 = PRU('pru0',pru0_constants,pru_constants)
+
+ if pru1 is None:
+ pru1 = PRU('pru1',pru1_constants,pru_constants)
+
+ return {'pru0': pru0, 'pru1': pru1}
+
+def unmap_memory():
+ global pru0, pru1
+ pru0.unmap_memory()
+ pru1.unmap_memory()
diff --git a/pool/shard009/Python/0087369_user_identity.py b/pool/shard009/Python/0087369_user_identity.py
new file mode 100644
index 0000000000000000000000000000000000000000..98f959cb99ea750c356813f73071b1e5a13e4c33
--- /dev/null
+++ b/pool/shard009/Python/0087369_user_identity.py
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import sqlalchemy as sa
+
+from hyputils.memex.db import Base
+
+
+class UserIdentity(Base):
+ __tablename__ = "user_identity"
+ __table_args__ = (sa.UniqueConstraint("provider", "provider_unique_id"),)
+
+ id = sa.Column(sa.Integer(), autoincrement=True, primary_key=True)
+ provider = sa.Column(sa.UnicodeText(), nullable=False)
+ provider_unique_id = sa.Column(sa.UnicodeText(), nullable=False)
+ user_id = sa.Column(
+ sa.Integer(), sa.ForeignKey("user.id", ondelete="cascade"), nullable=False
+ )
+
+ def __repr__(self):
+ return "{}(provider={!r}, provider_unique_id={!r})".format(
+ self.__class__.__name__, self.provider, self.provider_unique_id
+ )
diff --git a/pool/shard009/Python/0087370_notebook.py b/pool/shard009/Python/0087370_notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3adb515ba47c435fb5b98e15b244ddf818e135
--- /dev/null
+++ b/pool/shard009/Python/0087370_notebook.py
@@ -0,0 +1,111 @@
+"""
+notebook.py
+-------------
+
+Render trimesh.Scene objects in HTML
+and jupyter notebooks using three.js
+"""
+import os
+import base64
+
+# for our template
+from .. import util
+from .. import resources
+
+
+def scene_to_html(scene):
+ """
+ Return HTML that will render the scene using
+ GLTF/GLB encoded to base64 loaded by three.js
+
+ Parameters
+ --------------
+ scene : trimesh.Scene
+ Source geometry
+
+ Returns
+ --------------
+ html : str
+ HTML containing embedded geometry
+ """
+ # fetch HTML template from ZIP archive
+ # it is bundling all of three.js so compression is nice
+ base = util.decompress(
+ resources.get('templates/viewer.zip', decode=False),
+ file_type='zip')['viewer.html.template'].read().decode('utf-8')
+ scene.camera
+ # get export as bytes
+ data = scene.export(file_type='glb')
+ # encode as base64 string
+ encoded = base64.b64encode(data).decode('utf-8')
+ # replace keyword with our scene data
+ result = base.replace('$B64GLTF', encoded)
+
+ return result
+
+
+def scene_to_notebook(scene, height=500, **kwargs):
+ """
+ Convert a scene to HTML containing embedded geometry
+ and a three.js viewer that will display nicely in
+ an IPython/Jupyter notebook.
+
+ Parameters
+ -------------
+ scene : trimesh.Scene
+ Source geometry
+
+ Returns
+ -------------
+ html : IPython.display.HTML
+ Object containing rendered scene
+ """
+ # keep as soft dependency
+ from IPython import display
+
+ # convert scene to a full HTML page
+ as_html = scene_to_html(scene=scene)
+
+ # escape the quotes in the HTML
+ srcdoc = as_html.replace('"', '"')
+ # embed this puppy as the srcdoc attr of an IFframe
+ # I tried this a dozen ways and this is the only one that works
+ # display.IFrame/display.Javascript really, really don't work
+ # note trailing space to avoid IPython's pointless hardcoded warning
+ embedded = display.HTML(' '.join([
+ '']).format(
+ srcdoc=srcdoc,
+ height=height))
+ return embedded
+
+
+def in_notebook():
+ """
+ Check to see if we are in an IPython or Jypyter notebook.
+
+ Returns
+ -----------
+ in_notebook : bool
+ Returns True if we are in a notebook
+ """
+ try:
+ # function returns IPython context, but only in IPython
+ ipy = get_ipython() # NOQA
+ # we only want to render rich output in notebooks
+ # in terminals we definitely do not want to output HTML
+ name = str(ipy.__class__).lower()
+ terminal = 'terminal' in name
+
+ # spyder uses ZMQshell, and can appear to be a notebook
+ spyder = '_' in os.environ and 'spyder' in os.environ['_']
+
+ # assume we are in a notebook if we are not in
+ # a terminal and we haven't been run by spyder
+ notebook = (not terminal) and (not spyder)
+
+ return notebook
+
+ except BaseException:
+ return False
diff --git a/pool/shard009/Python/0087373_TreeParam.py b/pool/shard009/Python/0087373_TreeParam.py
new file mode 100644
index 0000000000000000000000000000000000000000..371d3641e46e1b7d2a6a8038d72600bcdb72ed0f
--- /dev/null
+++ b/pool/shard009/Python/0087373_TreeParam.py
@@ -0,0 +1,119 @@
+from PyQt5 import QtCore
+from PyQt5.QtSql import QSqlDatabase, QSqlQuery
+
+
+class TreeParam(QtCore.QObject):
+ def __init__(self, page):
+ QtCore.QObject.__init__(self, page)
+
+ self.pageId = page.id
+ self.db = page.db
+ if 'treeparam' not in self.db.tables():
+ self.create(self.db)
+
+ self.fields = page.fields
+ self._params = []
+ self._load()
+ if not self._params:
+ allFields = self.fields
+ self._params = [[allFields.category, ], [allFields.country, ],
+ [allFields.period, ],
+ [allFields.denomination, ], [allFields.year, ]]
+
+ def params(self):
+ return self._params
+
+ def clear(self):
+ del self._params[:] # clearing list
+
+ def append(self, fields):
+ if not isinstance(fields, list):
+ fields = [fields, ]
+
+ self._params.append(fields)
+
+ def usedFieldNames(self):
+ names = []
+ for param in self._params:
+ names.extend([field.name for field in param])
+
+ return names
+
+ def fieldNames(self, index):
+ if index >= len(self._params):
+ return None
+
+ names = [field.name for field in self._params[index]]
+ return names
+
+ def isLast(self, index):
+ return index >= (len(self._params) - 1)
+
+ def _load(self):
+ self.clear()
+ count = 0
+
+ query = QSqlQuery(self.db)
+ query.prepare("SELECT COUNT(DISTINCT position) "
+ "FROM treeparam WHERE pageid=?")
+ query.addBindValue(self.pageId)
+ query.exec_()
+ if query.first():
+ count = query.record().value(0)
+
+ if count:
+ for _ in range(count):
+ self._params.append([])
+
+ query = QSqlQuery(self.db)
+ query.prepare("SELECT * FROM treeparam WHERE pageid=?")
+ query.addBindValue(self.pageId)
+ query.exec_()
+
+ while query.next():
+ record = query.record()
+ position = record.value('position')
+ fieldId = record.value('fieldid')
+ self._params[position].append(self.fields.field(fieldId))
+
+ def save(self):
+ self.db.transaction()
+
+ self.remove()
+
+ for position, param in enumerate(self.params()):
+ for field in param:
+ query = QSqlQuery(self.db)
+ query.prepare("INSERT INTO treeparam (pageid, fieldid,"
+ " position) VALUES (?, ?, ?)")
+ query.addBindValue(self.pageId)
+ query.addBindValue(field.id)
+ query.addBindValue(position)
+ query.exec_()
+
+ self.db.commit()
+
+ def remove(self):
+ query = QSqlQuery(self.db)
+ query.prepare("DELETE FROM treeparam WHERE pageid=?")
+ query.addBindValue(self.pageId)
+ query.exec_()
+
+ def __iter__(self):
+ self.index = 0
+ return self
+
+ def __next__(self):
+ if self.index == len(self._params):
+ raise StopIteration
+ self.index = self.index + 1
+ return self._params[self.index - 1]
+
+ @staticmethod
+ def create(db=QSqlDatabase()):
+ sql = """CREATE TABLE treeparam (
+ id INTEGER NOT NULL PRIMARY KEY,
+ pageid INTEGER,
+ fieldid INTEGER,
+ position INTEGER)"""
+ QSqlQuery(sql, db)
diff --git a/pool/shard009/Python/0087381_basic.py b/pool/shard009/Python/0087381_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a8903f89e08325fda847fb0fdd45243333e87bb
--- /dev/null
+++ b/pool/shard009/Python/0087381_basic.py
@@ -0,0 +1,68 @@
+from mock import Mock
+
+import tower
+from tower import QuadrotorPID, Crazyflie
+
+
+# create the mock object
+mockRegion = Mock(name="Region")
+# prepare the spec list
+fooSpec = ["_fooValue", "source", "doFoo"]
+
+# create the mock object
+mockFoo = Mock(spec=fooSpec)
+
+# create the mock object
+mockControlLaw = Mock(name="Control")
+# prepare the spec list
+fooSpec = ["_fooValue", "source", "doFoo"]
+
+# create the mock object
+mockFoo = Mock(spec=fooSpec)
+
+KILL_COMMAND = 'DEATH'
+
+if __name__ == '__main__':
+ #comment
+ manager = tower.WorkflowManager()
+ # todo: I don't know if I like this from a user perspective
+ # instantiate a Tower
+ tower_1 = tower.Tower(mockRegion, mockControlLaw, optitrack_args={'filtering': False})
+ # instantiate a Manager
+
+ # Instantiate Vehicles
+ crazyflie = Crazyflie(QuadrotorPID(), name='Stringer')
+ print(crazyflie.controller)
+ # Add Vehicles to the Tower
+
+ # Add Tower to Manager
+ manager.add_tower(tower_1)
+
+ # Start all Towers managed by Manager
+ for ps in manager.processes.values():
+ ps.start()
+ print("Started {}".format(ps.name))
+
+ command = raw_input('Server Command: ')
+ print("Command was: {}".format(command))
+ if command == 'shutdown':
+ print("Giving the kill command")
+ for process in manager.processes.values():
+ print("Killing {}".format(process.name))
+ process.results_q.put(KILL_COMMAND)
+ print("joining")
+ process.join()
+
+ for thread in manager.threads.values():
+ print(thread)
+ # todo: ask threads to take the poison pill, then join
+ #thread.kill()
+ else:
+ for ps in manager.processes.values():
+ ps.terminate()
+
+
+
+ # add vehicles, and a map to tower
+
+
diff --git a/pool/shard009/Python/0087382_svm.py b/pool/shard009/Python/0087382_svm.py
new file mode 100644
index 0000000000000000000000000000000000000000..57b1af15838564146d2822ef12952449ceed07d0
--- /dev/null
+++ b/pool/shard009/Python/0087382_svm.py
@@ -0,0 +1,83 @@
+#############################################################################
+#
+# Copyright 2012-2016 University of Utah
+#
+# 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 svm
+import os
+from svmutil import *
+from nitro.util.system_utils import *
+from nitro.util.prettyprint import *
+
+class svm_classifier:
+ """Support Vector Machine Classifier"""
+ m_name = "svm"
+ feature_scaling = True
+ m_params = svm.svm_parameter()
+ m_prob = None
+
+ def convert_raw_training_data(self, raw_data):
+ t_data = ""
+ for line in raw_data.split('\n'):
+ if line == "":
+ break
+ x = [l.strip() for l in line.split(':')]
+ t_data += x[0] + " "
+ i = 1
+ for feature in x[1].split():
+ t_data += str(i) + ":" + feature + " "
+ i += 1
+ t_data += "\n"
+ return t_data
+
+ def scale_features(self, variant_name, models_folder):
+ command = "svm-scale -s %s %s > %s" % (models_folder + variant_name + ".range",\
+ variant_name + ".t",\
+ variant_name + ".t.scale")
+ try:
+ result = subprocess.check_output(command, shell=True)
+ except subprocess.CalledProcessError as e:
+ print_error("Scaling Command Failed")
+ quit()
+
+ def generate_model(self, variant_name, models_folder):
+ training_file = variant_name + ".t"
+ if self.feature_scaling:
+ self.scale_features(variant_name, models_folder)
+ training_file += ".scale"
+ (y, x) = svm_read_problem(training_file)
+ self.m_prob = svm.svm_problem(y, x, self.m_params.kernel_type == PRECOMPUTED)
+
+ libsvm_path = os.environ['LIBSVM_PATH']
+ scaled_filename = os.path.abspath(training_file)
+ cp = "python grid.py " + scaled_filename
+ curdir = os.getcwd()
+ os.chdir(libsvm_path + "/tools/")
+ result = call_process(cp)
+ os.chdir(curdir)
+ C,g,rate = [float(l) for l in result.split("\n")[-2].split(" ")]
+
+ print "C: %.8f, gamma: %.8f\n" % (C,g)
+
+ self.m_params.C = C
+ self.m_params.gamma = g
+
+ print "\n-----------------------------"
+ model = svm.svm_train(self.m_prob, self.m_params)
+ print "-----------------------------\n"
+
+ svm_save_model(models_folder + variant_name + ".model", model)
+
diff --git a/pool/shard009/Python/0087386_move_zip_upload.py b/pool/shard009/Python/0087386_move_zip_upload.py
new file mode 100644
index 0000000000000000000000000000000000000000..191008e42f9f68fb9a471fa0e54ba611eed69b10
--- /dev/null
+++ b/pool/shard009/Python/0087386_move_zip_upload.py
@@ -0,0 +1,23 @@
+# coding=utf-8
+'''
+Created on 2013-8-30
+打包上线
+@author: gudh
+'''
+
+import bookauto, bookconfig
+import time, os
+
+if __name__ == '__main__':
+ # 打包上传的数量
+ count = -1
+ zip_path = "D:/ebook_zip/%s/" % time.strftime("%Y%m%d")
+ if os.path.exists(bookconfig.uploadfile):
+ # 如果存在则备份
+ uploadback = os.path.dirname(bookconfig.uploadfile) + "/upback/upload" + time.strftime("%Y%m%d") + ".txt"
+ print "back upload to %s" % uploadback
+ os.rename(bookconfig.uploadfile, uploadback)
+ bookauto.before_deal(count, zip_path)
+ # 打开需要上传的目录
+ print u"请将目录 %s 中的zip文件全部上传到ftp中的 /ebook_zip/路径下,谢谢。" % zip_path
+ os.startfile(zip_path)
diff --git a/pool/shard009/Python/0087397_settings.py b/pool/shard009/Python/0087397_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a5dbd53bd9467c9b43d8fcc7020f4f7e166a2d
--- /dev/null
+++ b/pool/shard009/Python/0087397_settings.py
@@ -0,0 +1,61 @@
+from django.conf import settings
+from django.test.signals import setting_changed
+from rest_framework.settings import APISettings
+
+
+DEFAULTS = {
+ 'USE_SESSION_AUTH': True,
+ 'SECURITY_DEFINITIONS': {
+ 'basic': {
+ 'type': 'basic'
+ }
+ },
+ 'LOGIN_URL': getattr(settings, 'LOGIN_URL', None),
+ 'LOGOUT_URL': getattr(settings, 'LOGOUT_URL', None),
+ 'DOC_EXPANSION': None,
+ 'APIS_SORTER': None,
+ 'OPERATIONS_SORTER': None,
+ 'JSON_EDITOR': False,
+ 'SHOW_REQUEST_HEADERS': False,
+ 'SUPPORTED_SUBMIT_METHODS': [
+ 'get',
+ 'post',
+ 'put',
+ 'delete',
+ 'patch'
+ ],
+ 'VALIDATOR_URL': '',
+}
+
+IMPORT_STRINGS = []
+
+swagger_settings = APISettings(
+ user_settings=getattr(settings, 'SWAGGER_SETTINGS', {}),
+ defaults=DEFAULTS,
+ import_strings=IMPORT_STRINGS
+)
+
+
+def reload_settings(*args, **kwargs): # pragma: no cover
+ """
+ Reloads settings during unit tests if override_settings decorator
+ is used. (Taken from DRF)
+ """
+ # pylint: disable=W0603
+ global swagger_settings
+
+ if kwargs['setting'] == 'LOGIN_URL':
+ swagger_settings.LOGIN_URL = kwargs['value']
+ if kwargs['setting'] == 'LOGOUT_URL':
+ swagger_settings.LOGOUT_URL = kwargs['value']
+ if kwargs['setting'] != 'SWAGGER_SETTINGS':
+ return
+
+ swagger_settings = APISettings(
+ kwargs['value'],
+ DEFAULTS,
+ IMPORT_STRINGS
+ )
+
+
+setting_changed.connect(reload_settings)
diff --git a/pool/shard009/Python/0087399_t_Distributions_draw.py b/pool/shard009/Python/0087399_t_Distributions_draw.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bef569a3e05553e9083bd19c91242bcf96e19c3
--- /dev/null
+++ b/pool/shard009/Python/0087399_t_Distributions_draw.py
@@ -0,0 +1,65 @@
+#! /usr/bin/env python
+
+from openturns import *
+
+TESTPREAMBLE()
+pointNumber = 251
+
+try:
+ dist1D = Normal(2.0, 4.0)
+ dist2D = Normal(NumericalPoint(2, 2.0),
+ NumericalPoint(2, 4.0), CorrelationMatrix(2))
+ distND = Normal(NumericalPoint(5, 2.0),
+ NumericalPoint(5, 4.0), CorrelationMatrix(5))
+ # Check drawing methods for 1D distributions
+ graphPDF = dist1D.drawPDF()
+ graphPDF.draw("DefaultDrawPDF_1D")
+ graphPDF = dist1D.drawPDF(-4.0, 4.0, 101)
+ graphPDF.draw("FullParametersDrawPDF_1D")
+ graphPDF = dist1D.drawPDF(-4.0, 4.0)
+ graphPDF.draw("RangeDrawPDF_1D")
+ graphPDF = dist1D.drawPDF(101)
+ graphPDF.draw("PointNumberDrawPDF_1D")
+ graphCDF = dist1D.drawCDF()
+ graphCDF.draw("DefaultDrawCDF_1D")
+ graphCDF = dist1D.drawCDF(-4.0, 4.0, 101)
+ graphCDF.draw("FullParametersDrawCDF_1D")
+ graphCDF = dist1D.drawCDF(-4.0, 4.0)
+ graphCDF.draw("RangeDrawCDF_1D")
+ graphCDF = dist1D.drawCDF(101)
+ graphCDF.draw("PointNumberDrawCDF_1D")
+ # Check drawing methods for 2D distributions
+ graphPDF = dist2D.drawPDF()
+ graphPDF.draw("DefaultDrawPDF_2D")
+ graphPDF = dist2D.drawPDF([-4.0, -4.0], [4.0, 4.0], [101, 101])
+ graphPDF.draw("FullParametersDrawPDF_2D")
+ graphPDF = dist2D.drawPDF([-4.0, -4.0], [4.0, 4.0])
+ graphPDF.draw("RangeDrawPDF_2D")
+ graphPDF = dist2D.drawPDF([101, 101])
+ graphPDF.draw("PointNumberDrawPDF_2D")
+ graphCDF = dist2D.drawCDF()
+ graphCDF.draw("DefaultDrawCDF_2D")
+ graphCDF = dist2D.drawCDF([-4.0, -4.0], [4.0, 4.0], [101, 101])
+ graphCDF.draw("FullParametersDrawCDF_2D")
+ graphCDF = dist2D.drawCDF([-4.0, -4.0], [4.0, 4.0])
+ graphCDF.draw("RangeDrawCDF_2D")
+ graphCDF = dist2D.drawCDF([101, 101])
+ graphCDF.draw("PointNumberDrawCDF_2D")
+ # Check drawing methods for ND distributions
+ graphPDF = distND.drawMarginal1DPDF(2, -4.0, 4.0, 101)
+ graphPDF.draw("FullParametersDrawMarginal1DPDF_ND")
+ graphPDF = distND.drawMarginal2DPDF(
+ 2, 3, [-4.0, -4.0], [4.0, 4.0], [101, 101])
+ graphPDF.draw("FullParametersDrawMarginal2DPDF_ND")
+ graphCDF = distND.drawMarginal1DCDF(2, -4.0, 4.0, 101)
+ graphCDF.draw("FullParametersDrawMarginal1DCDF_ND")
+ graphCDF = distND.drawMarginal2DCDF(
+ 2, 3, [-4.0, -4.0], [4.0, 4.0], [101, 101])
+ graphCDF.draw("FullParametersDrawMarginal2DCDF_ND")
+ graphQuantile = dist1D.drawQuantile()
+ graphQuantile.draw("DrawQuantile_1D")
+ graphQuantile = dist2D.drawQuantile()
+ graphQuantile.draw("DrawQuantile_2D")
+except:
+ import sys
+ print "t_Distributions_draw.py", sys.exc_type, sys.exc_value
diff --git a/pool/shard009/Python/0087401_client.py b/pool/shard009/Python/0087401_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..73acf9c104a2f3f84633e5b2436bac136944ccbe
--- /dev/null
+++ b/pool/shard009/Python/0087401_client.py
@@ -0,0 +1,217 @@
+# Copyright (c) 2011 Justin Santa Barbara
+#
+# 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 oslo_serialization import jsonutils
+from oslo_utils import netutils
+import requests
+import six.moves.urllib.parse as urlparse
+
+from cinder.i18n import _, _LI
+from cinder.openstack.common import log as logging
+
+
+LOG = logging.getLogger(__name__)
+
+
+class OpenStackApiException(Exception):
+ def __init__(self, message=None, response=None):
+ self.response = response
+ if not message:
+ message = 'Unspecified error'
+
+ if response:
+ message = _('%(message)s\nStatus Code: %(_status)s\n'
+ 'Body: %(_body)s') % {'_status': response.status_code,
+ '_body': response.text}
+
+ super(OpenStackApiException, self).__init__(message)
+
+
+class OpenStackApiAuthenticationException(OpenStackApiException):
+ def __init__(self, response=None, message=None):
+ if not message:
+ message = _("Authentication error")
+ super(OpenStackApiAuthenticationException, self).__init__(message,
+ response)
+
+
+class OpenStackApiAuthorizationException(OpenStackApiException):
+ def __init__(self, response=None, message=None):
+ if not message:
+ message = _("Authorization error")
+ super(OpenStackApiAuthorizationException, self).__init__(message,
+ response)
+
+
+class OpenStackApiNotFoundException(OpenStackApiException):
+ def __init__(self, response=None, message=None):
+ if not message:
+ message = _("Item not found")
+ super(OpenStackApiNotFoundException, self).__init__(message, response)
+
+
+class TestOpenStackClient(object):
+ """Simple OpenStack API Client.
+
+ This is a really basic OpenStack API client that is under our control,
+ so we can make changes / insert hooks for testing
+
+ """
+
+ def __init__(self, auth_user, auth_key, auth_uri):
+ super(TestOpenStackClient, self).__init__()
+ self.auth_result = None
+ self.auth_user = auth_user
+ self.auth_key = auth_key
+ self.auth_uri = auth_uri
+ # default project_id
+ self.project_id = 'openstack'
+
+ def request(self, url, method='GET', body=None, headers=None,
+ ssl_verify=True, stream=False):
+ _headers = {'Content-Type': 'application/json'}
+ _headers.update(headers or {})
+
+ parsed_url = urlparse.urlparse(url)
+ port = parsed_url.port
+ hostname = parsed_url.hostname
+ scheme = parsed_url.scheme
+
+ if netutils.is_valid_ipv6(hostname):
+ hostname = "[%s]" % hostname
+
+ relative_url = parsed_url.path
+ if parsed_url.query:
+ relative_url = relative_url + "?" + parsed_url.query
+ LOG.info(_LI("Doing %(method)s on %(relative_url)s"),
+ {'method': method, 'relative_url': relative_url})
+ if body:
+ LOG.info(_LI("Body: %s") % body)
+
+ if port:
+ _url = "%s://%s:%d%s" % (scheme, hostname, int(port), relative_url)
+ else:
+ _url = "%s://%s%s" % (scheme, hostname, relative_url)
+
+ response = requests.request(method, _url, data=body, headers=_headers,
+ verify=ssl_verify, stream=stream)
+
+ return response
+
+ def _authenticate(self):
+ if self.auth_result:
+ return self.auth_result
+
+ auth_uri = self.auth_uri
+ headers = {'X-Auth-User': self.auth_user,
+ 'X-Auth-Key': self.auth_key,
+ 'X-Auth-Project-Id': self.project_id}
+ response = self.request(auth_uri,
+ headers=headers)
+
+ http_status = response.status_code
+ LOG.debug("%(auth_uri)s => code %(http_status)s",
+ {'auth_uri': auth_uri, 'http_status': http_status})
+
+ if http_status == 401:
+ raise OpenStackApiAuthenticationException(response=response)
+
+ self.auth_result = response.headers
+ return self.auth_result
+
+ def api_request(self, relative_uri, check_response_status=None, **kwargs):
+ auth_result = self._authenticate()
+
+ # NOTE(justinsb): httplib 'helpfully' converts headers to lower case
+ base_uri = auth_result['x-server-management-url']
+
+ full_uri = '%s/%s' % (base_uri, relative_uri)
+
+ headers = kwargs.setdefault('headers', {})
+ headers['X-Auth-Token'] = auth_result['x-auth-token']
+
+ response = self.request(full_uri, **kwargs)
+
+ http_status = response.status_code
+ LOG.debug("%(relative_uri)s => code %(http_status)s",
+ {'relative_uri': relative_uri, 'http_status': http_status})
+
+ if check_response_status:
+ if http_status not in check_response_status:
+ if http_status == 404:
+ raise OpenStackApiNotFoundException(response=response)
+ elif http_status == 401:
+ raise OpenStackApiAuthorizationException(response=response)
+ else:
+ raise OpenStackApiException(
+ message=_("Unexpected status code"),
+ response=response)
+
+ return response
+
+ def _decode_json(self, response):
+ body = response.text
+ LOG.debug("Decoding JSON: %s" % (body))
+ if body:
+ return jsonutils.loads(body)
+ else:
+ return ""
+
+ def api_get(self, relative_uri, **kwargs):
+ kwargs.setdefault('check_response_status', [200])
+ response = self.api_request(relative_uri, **kwargs)
+ return self._decode_json(response)
+
+ def api_post(self, relative_uri, body, **kwargs):
+ kwargs['method'] = 'POST'
+ if body:
+ headers = kwargs.setdefault('headers', {})
+ headers['Content-Type'] = 'application/json'
+ kwargs['body'] = jsonutils.dumps(body)
+
+ kwargs.setdefault('check_response_status', [200, 202])
+ response = self.api_request(relative_uri, **kwargs)
+ return self._decode_json(response)
+
+ def api_put(self, relative_uri, body, **kwargs):
+ kwargs['method'] = 'PUT'
+ if body:
+ headers = kwargs.setdefault('headers', {})
+ headers['Content-Type'] = 'application/json'
+ kwargs['body'] = jsonutils.dumps(body)
+
+ kwargs.setdefault('check_response_status', [200, 202, 204])
+ response = self.api_request(relative_uri, **kwargs)
+ return self._decode_json(response)
+
+ def api_delete(self, relative_uri, **kwargs):
+ kwargs['method'] = 'DELETE'
+ kwargs.setdefault('check_response_status', [200, 202, 204])
+ return self.api_request(relative_uri, **kwargs)
+
+ def get_volume(self, volume_id):
+ return self.api_get('/volumes/%s' % volume_id)['volume']
+
+ def get_volumes(self, detail=True):
+ rel_url = '/volumes/detail' if detail else '/volumes'
+ return self.api_get(rel_url)['volumes']
+
+ def post_volume(self, volume):
+ return self.api_post('/volumes', volume)['volume']
+
+ def delete_volume(self, volume_id):
+ return self.api_delete('/volumes/%s' % volume_id)
+
+ def put_volume(self, volume_id, volume):
+ return self.api_put('/volumes/%s' % volume_id, volume)['volume']
diff --git a/pool/shard009/Python/0087404_constants.py b/pool/shard009/Python/0087404_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa930f591f622d39bfd4f6cfcd0973b7578ddfab
--- /dev/null
+++ b/pool/shard009/Python/0087404_constants.py
@@ -0,0 +1,32 @@
+# Copyright 2020 DeepMind Technologies Limited.
+#
+# 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.
+
+"""Constants for FermiNet."""
+
+import functools
+import jax
+
+from kfac_ferminet_alpha import utils as kfac_utils
+
+
+# Axis name we pmap over.
+PMAP_AXIS_NAME = 'qmc_pmap_axis'
+
+# Shortcut for jax.pmap over PMAP_AXIS_NAME. Prefer this if pmapping any
+# function which does communications or reductions.
+pmap = functools.partial(jax.pmap, axis_name=PMAP_AXIS_NAME)
+
+# Shortcut for kfac utils
+psum = functools.partial(kfac_utils.psum_if_pmap, axis_name=PMAP_AXIS_NAME)
+pmean = functools.partial(kfac_utils.pmean_if_pmap, axis_name=PMAP_AXIS_NAME)
diff --git a/pool/shard009/Python/0087408_test_magic.py b/pool/shard009/Python/0087408_test_magic.py
new file mode 100644
index 0000000000000000000000000000000000000000..b159b1e59418f4d9b4dd7147562065795e099145
--- /dev/null
+++ b/pool/shard009/Python/0087408_test_magic.py
@@ -0,0 +1,90 @@
+import datetime
+
+import pytest
+
+from .. magic import parse_partial, safe_type, from_path, to_path
+
+def test_to_path():
+ assert to_path(('a',)) == ('a',)
+ assert to_path(('a', 3,)) == ('a', '3',)
+
+def test_from_path():
+ assert from_path(('a',)) == ('a',)
+
+parse = to_path
+
+def test_parse_int():
+ assert parse_partial(3) == ('3',)
+ assert parse_partial(123) == ('123',)
+ assert parse(123) == ('123',)
+
+def test_parse_url():
+ o = list(parse_partial('http://thomaslevine.com/!/about?a=b#lala'))
+ e = ['http', 'thomaslevine.com', '!', 'about?a=b#lala']
+ assert o == e
+
+def test_parse_date():
+ o = list(parse_partial(datetime.date(2014, 2, 5)))
+ e = ['2014', '02', '05']
+ assert o == e
+
+def test_parse_datetime():
+ o = parse_partial(datetime.datetime(2014, 2, 5, 11, 18, 30))
+ e = ('2014', '02', '05', '11', '18')
+ assert o == e
+
+def test_parse_none():
+ assert parse_partial(None) == ('',)
+ assert parse(None) == tuple()
+
+testcases = [
+ # iterables
+ (('a','b','c'), ('a', 'b', 'c')),
+ (['foo','bar','baz'], ('foo', 'bar', 'baz')),
+
+ # strings
+ ('def', ('def',)),
+ ('favorite color', ('favorite color',)),
+
+ # paths
+ ('left/middle/right', ('left', 'middle', 'right')),
+ ('backslashes\\also\\delimit', ('backslashes','also','delimit')),
+ ('/home/tlevine/warehouse', ('home', 'tlevine', 'warehouse')),
+ ('C:\\Users\\Documents', ('c', 'Users', 'Documents')),
+
+ # URLs
+ ('http://thomaslevine.com/!?foo=bar', ('http', 'thomaslevine.com', '!?foo=bar')),
+ (['http://thomaslevine.com', 'foo/bar/baz', 'a b'], ('http', 'thomaslevine.com', 'foo', 'bar', 'baz', 'a b')),
+
+ # . and .. are special
+ ('a/b/c/..', ('a','b','c','\\..')),
+ ('a/b/c/.', ('a','b','c','\\.')),
+ ('a\\b\\c\\..', ('a','b','c','\\..')),
+ ('a\\b\\c\\.', ('a','b','c','\\.')),
+
+ # Nones
+ ((None, 'abc'), ('abc',)),
+
+ # Starting with hash
+ ('#9 BAC GIANG CONSTRUCTION JOINT STOCK COMPANY', ('#9 BAC GIANG CONSTRUCTION JOINT STOCK COMPANY',)),
+]
+
+@pytest.mark.parametrize('index,path', testcases)
+def test_parse(index, path):
+ observed = parse(index)
+ assert observed == path
+
+def test_deterministic_order():
+ 'The iterable should have a deterministic order.'
+ failures = [{3,5}, {'a':'apple','b':'banana'}]
+ for thing in failures:
+ assert not safe_type(thing)
+
+ successes = [[3,6], (2,1), 'aoeua']
+ for thing in successes:
+ assert safe_type(thing)
+
+def test_warn_unsafe_type(recwarn):
+ parse({'one','two','three'})
+ w = recwarn.pop(UserWarning)
+ assert issubclass(w.category, UserWarning)
diff --git a/pool/shard009/Python/0087415_context.py b/pool/shard009/Python/0087415_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..f552d778c4e14f0eccb3855b8723b74fcd9c51f1
--- /dev/null
+++ b/pool/shard009/Python/0087415_context.py
@@ -0,0 +1,113 @@
+# -*- coding: utf-8 -*-
+# Copyright 2015-2019 grafana-dashboard-builder contributors
+#
+# 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 __future__ import unicode_literals
+
+import itertools
+import re
+import string
+
+try:
+ basestring
+except NameError:
+ basestring = str
+
+__author__ = 'Jakub Plichta '
+
+
+class Context(object):
+
+ _pattern = re.compile('{.*}')
+
+ def __init__(self, context=None):
+ super(Context, self).__init__()
+ if not context:
+ self._context = None
+ else:
+ self._context = DictDefaultingToPlaceholder(context)
+
+ def expand_placeholders(self, to_expand):
+ """
+
+ :rtype : dict
+ """
+ if not self._context:
+ return to_expand
+
+ if isinstance(to_expand, basestring):
+ (result, to_expand) = self._expand(to_expand)
+ while result != to_expand:
+ (result, to_expand) = self._expand(result)
+ if isinstance(result, basestring):
+ return string.Formatter().vformat(result, (), self._context)
+ else:
+ return result
+ elif isinstance(to_expand, list):
+ return [self.expand_placeholders(value) for value in to_expand]
+ elif isinstance(to_expand, dict):
+ return dict([(key, self.expand_placeholders(value)) for (key, value) in to_expand.items()])
+ else:
+ return to_expand
+
+ def _expand(self, to_expand):
+ if not isinstance(to_expand, basestring):
+ return to_expand, to_expand
+ elif self._pattern.match(to_expand) and to_expand[1:-1] in self._context:
+ return self._context[to_expand[1:-1]], to_expand
+ escaped = to_expand.replace('{{', '{{{{').replace('}}', '}}}}')
+ return string.Formatter().vformat(escaped, (), self._context), to_expand
+
+ def __str__(self):
+ return str(self._context)
+
+ @staticmethod
+ def create_context(data, keys_to_expand=None):
+ return (Context(Context(context).expand_placeholders(context))
+ for context in ContextExpander(keys_to_expand).create_context(None, data))
+
+
+class DictDefaultingToPlaceholder(dict):
+ def __missing__(self, key):
+ return '{' + key + '}'
+
+
+class ContextExpander(object):
+ def __init__(self, keys_to_expand=None):
+ super(ContextExpander, self).__init__()
+ self._keys_to_expand = keys_to_expand if keys_to_expand else []
+
+ def create_context(self, key, value, parent=None):
+ contexts = []
+ if isinstance(value, list):
+ if key in self._keys_to_expand:
+ contexts.append((context for data in value for context in self.create_context(key, data, key)))
+ else:
+ contexts.append(itertools.repeat({key: value}, 1))
+ elif isinstance(value, dict):
+ for (sub_key, sub_value) in value.items():
+ if parent and len(value) == 1:
+ contexts.append(self.create_context(parent, sub_key))
+ contexts.append(self.create_context(sub_key, sub_value))
+ else:
+ contexts.append(itertools.repeat({key: value}, 1))
+ for context in itertools.product(*contexts):
+ result = {}
+ multi = {}
+ for context_part in context:
+ if len(context_part) == 1:
+ result.update(context_part)
+ else:
+ multi.update(context_part)
+ result.update(multi)
+ yield result
diff --git a/pool/shard009/Python/0087418_batcher.py b/pool/shard009/Python/0087418_batcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..950a198ef182d02fa248886e587aad95de5c313d
--- /dev/null
+++ b/pool/shard009/Python/0087418_batcher.py
@@ -0,0 +1,146 @@
+# Copyright 2018 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or 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.
+
+"""User friendly container for Google Cloud Bigtable MutationBatcher."""
+
+
+FLUSH_COUNT = 1000
+MAX_MUTATIONS = 100000
+MAX_ROW_BYTES = 5242880 # 5MB
+
+
+class MaxMutationsError(ValueError):
+ """The number of mutations for bulk request is too big."""
+
+
+class MutationsBatcher(object):
+ """A MutationsBatcher is used in batch cases where the number of mutations
+ is large or unknown. It will store DirectRows in memory until one of the
+ size limits is reached, or an explicit call to flush() is performed. When
+ a flush event occurs, the DirectRows in memory will be sent to Cloud
+ Bigtable. Batching mutations is more efficient than sending individual
+ request.
+
+ This class is not suited for usage in systems where each mutation
+ needs to guaranteed to be sent, since calling mutate may only result in an
+ in-memory change. In a case of a system crash, any DirectRows remaining in
+ memory will not necessarily be sent to the service, even after the
+ completion of the mutate() method.
+
+ TODO: Performance would dramatically improve if this class had the
+ capability of asynchronous, parallel RPCs.
+
+ :type table: class
+ :param table: class:`~google.cloud.bigtable.table.Table`.
+
+ :type flush_count: int
+ :param flush_count: (Optional) Max number of rows to flush. If it
+ reaches the max number of rows it calls finish_batch() to mutate the
+ current row batch. Default is FLUSH_COUNT (1000 rows).
+
+ :type max_row_bytes: int
+ :param max_row_bytes: (Optional) Max number of row mutations size to
+ flush. If it reaches the max number of row mutations size it calls
+ finish_batch() to mutate the current row batch. Default is MAX_ROW_BYTES
+ (5 MB).
+ """
+
+ def __init__(self, table, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES):
+ self.rows = []
+ self.total_mutation_count = 0
+ self.total_size = 0
+ self.table = table
+ self.flush_count = flush_count
+ self.max_row_bytes = max_row_bytes
+
+ def mutate(self, row):
+ """Add a row to the batch. If the current batch meets one of the size
+ limits, the batch is sent synchronously.
+
+ For example:
+
+ .. literalinclude:: snippets.py
+ :start-after: [START bigtable_api_batcher_mutate]
+ :end-before: [END bigtable_api_batcher_mutate]
+ :dedent: 4
+
+ :type row: class
+ :param row: class:`~google.cloud.bigtable.row.DirectRow`.
+
+ :raises: One of the following:
+ * :exc:`~.table._BigtableRetryableError` if any
+ row returned a transient error.
+ * :exc:`RuntimeError` if the number of responses doesn't
+ match the number of rows that were retried
+ * :exc:`.batcher.MaxMutationsError` if any row exceeds max
+ mutations count.
+ """
+ mutation_count = len(row._get_mutations())
+ if mutation_count > MAX_MUTATIONS:
+ raise MaxMutationsError(
+ "The row key {} exceeds the number of mutations {}.".format(
+ row.row_key, mutation_count
+ )
+ )
+
+ if (self.total_mutation_count + mutation_count) >= MAX_MUTATIONS:
+ self.flush()
+
+ self.rows.append(row)
+ self.total_mutation_count += mutation_count
+ self.total_size += row.get_mutations_size()
+
+ if self.total_size >= self.max_row_bytes or len(self.rows) >= self.flush_count:
+ self.flush()
+
+ def mutate_rows(self, rows):
+ """Add a row to the batch. If the current batch meets one of the size
+ limits, the batch is sent synchronously.
+
+ For example:
+
+ .. literalinclude:: snippets.py
+ :start-after: [START bigtable_api_batcher_mutate_rows]
+ :end-before: [END bigtable_api_batcher_mutate_rows]
+ :dedent: 4
+
+ :type rows: list:[`~google.cloud.bigtable.row.DirectRow`]
+ :param rows: list:[`~google.cloud.bigtable.row.DirectRow`].
+
+ :raises: One of the following:
+ * :exc:`~.table._BigtableRetryableError` if any
+ row returned a transient error.
+ * :exc:`RuntimeError` if the number of responses doesn't
+ match the number of rows that were retried
+ * :exc:`.batcher.MaxMutationsError` if any row exceeds max
+ mutations count.
+ """
+ for row in rows:
+ self.mutate(row)
+
+ def flush(self):
+ """Sends the current. batch to Cloud Bigtable.
+ For example:
+
+ .. literalinclude:: snippets.py
+ :start-after: [START bigtable_api_batcher_flush]
+ :end-before: [END bigtable_api_batcher_flush]
+ :dedent: 4
+
+ """
+ if len(self.rows) != 0:
+ self.table.mutate_rows(self.rows)
+ self.total_mutation_count = 0
+ self.total_size = 0
+ self.rows = []
diff --git a/pool/shard009/Python/0087421_ocular.py b/pool/shard009/Python/0087421_ocular.py
new file mode 100644
index 0000000000000000000000000000000000000000..b34b07412549b3f9069abde1b5fcbf4f75377eec
--- /dev/null
+++ b/pool/shard009/Python/0087421_ocular.py
@@ -0,0 +1,118 @@
+"""Ocular motion module to model eye movements."""
+
+import time
+import logging
+import numpy as np
+
+from lumos.context import Context
+from lumos.input import Projector, InputRunner
+from lumos.net import EventLogger
+
+
+class OcularMotionSystem(object):
+ """Base class for all eye movement models."""
+ pass
+
+
+class EmulatedOcularMotionSystem(OcularMotionSystem):
+ """Eye movements emulated by a moving window over input image stream."""
+
+ tag = "OCULAR" # mainly used for logging
+ velocity_factor = 0.9 # per sec; weight that controls how target distance affects velocity
+ max_velocity = 300 # pixels per sec; maximum velocity with which eye can move
+ min_distance = 5 # pixels
+ min_delta_distance = 2 # pixels
+
+ def __init__(self, projector=None, timeNow=0.0):
+ self.logger = logging.getLogger(self.__class__.__name__)
+ self.projector = projector if projector is not None else Projector()
+ self.timeNow = timeNow
+ self.lastMovementTime = self.timeNow
+ self.isMoving = False
+ self.d = np.float32([0.0, 0.0]) # relative distance to move (x, y)
+ self.v = np.float32([0.0, 0.0]) # velocity to move with (x, y)
+ # TODO: Switch to (r, theta) coordinates? (makes more sense, easier to handle magnitudes)
+ self.logEvents = False # log file is created when enabled
+
+ def update(self, timeNow):
+ self.timeNow = timeNow
+ #self.logger.debug("isMoving? %s", self.isMoving) # [verbose]
+ if self.isMoving:
+ d_mag = np.linalg.norm(self.d, ord=2) # distance magnitude
+ #self.logger.debug("d: (%d, %d), mag: %d", self.d[0], self.d[1], d_mag) # [verbose]
+ if d_mag < self.min_distance:
+ self.stop()
+ else:
+ deltaTime = self.timeNow - self.lastMovementTime
+ self.v = self.velocity_factor * self.d # target velocity, depending on distance
+ v_mag = np.linalg.norm(self.v, ord=2) # velocity magnitude
+ if v_mag > self.max_velocity:
+ self.v *= self.max_velocity / v_mag # scaled down velocity to within limits
+ delta = self.v * deltaTime # delta distance to move in this update
+ delta_mag = np.linalg.norm(delta, ord=2) # delta distance magnitude
+ #self.logger.debug("delta: (%d, %d), mag: %d", delta[0], delta[1], delta_mag) # [verbose]
+ if delta_mag < self.min_delta_distance: # no point trying to move otherwise
+ delta *= self.min_delta_distance / delta_mag
+ delta_mag = self.min_delta_distance
+
+ if delta_mag > d_mag:
+ delta = self.d # prevent overshoot
+ self.d.fill(0.0)
+ else:
+ self.d -= delta
+
+ #self.logger.debug("Moving by: %g, %g", delta[0], delta[1]) # [verbose]
+ if not self.projector.shiftFocus(deltaX=int(delta[0]), deltaY=int(delta[1])): # returns False if not movement occurred
+ self.stop()
+
+ self.lastMovementTime = self.timeNow # don't update time otherwise, delta would remain too small
+
+ def move(self, d):
+ self.d = d
+ if self.logEvents:
+ self.eventLogger.log(self.tag, "move\t{}\t{}\t{}".format(self.d[0], self.d[1], self.timeNow))
+ #self.logger.info("Moving to: %d, %d at %.3f", self.d[0], self.d[1], self.timeNow) # [verbose]
+ self.isMoving = True
+ self.lastMovementTime = self.timeNow
+
+ def stop(self):
+ if self.logEvents:
+ self.eventLogger.log(self.tag, "stop\t{}\t{}\t{}".format(self.d[0], self.d[1], self.timeNow))
+ self.d.fill(0.0)
+ self.v.fill(0.0)
+ self.isMoving = False
+ #self.logger.debug("Stopped") # [verbose]
+
+ def reset(self):
+ self.logger.debug("Reset") # [verbose]
+ offset = self.getFocusOffset()
+ self.move(np.int_([-offset[0], -offset[1]])) # move back to center
+
+ def enableEventLogging(self, filename_prefix="ocular-events", rpc_export=False, start_server=False):
+ eventFilename = "logs/{}_{}.log".format(filename_prefix, time.strftime(EventLogger.timestamp_format, time.localtime(time.time())))
+ self.eventLogger = EventLogger(eventFilename, rpc_export=rpc_export, start_server=start_server)
+ self.logEvents = True
+
+ def getFocusPoint(self):
+ return self.projector.focusPoint
+
+ def getFocusOffset(self):
+ return (self.projector.focusPoint[0] - self.projector.screenSize[0] / 2, self.projector.focusPoint[1] - self.projector.screenSize[1] / 2)
+
+ def getVelocity(self):
+ return self.v
+
+
+# Testing
+if __name__ == "__main__":
+ context = Context.createInstance(description="Ocular motion testing")
+ projector = Projector()
+ ocular = EmulatedOcularMotionSystem(projector)
+ runner = InputRunner(projector)
+
+ while runner.update():
+ ocular.update(context.timeNow)
+ if not ocular.isMoving:
+ ocular.move(np.int_([np.random.uniform(-100, 100), np.random.uniform(-100, 100)]))
+
+ runner.cleanUp()
diff --git a/pool/shard009/Python/0087424_makeICs.py b/pool/shard009/Python/0087424_makeICs.py
new file mode 100644
index 0000000000000000000000000000000000000000..322467ccadf8bd9bd9ab9895926a45fa5e87442c
--- /dev/null
+++ b/pool/shard009/Python/0087424_makeICs.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+"""
+Contains functions for generating the dustyshock tube of Price & Laibe 2015
+
+See shock1d() to make a 1D shock tube.
+
+Price & Laibe shocktube params:
+Tube shape: (2)
+Pressure: (1, 1/8)
+Gas Density: (1, 1/8)
+Dust fraction: (0.5, 0.5)
+gamma: 5/3
+
+Created on Fri Feb 24 10:15:21 2017
+
+@author: ibackus
+"""
+
+import cPickle as pickle
+import numpy as np
+import pynbody
+import diskpy
+import testdust
+import os
+
+# Constants
+SimArray = pynbody.array.SimArray
+kB = pynbody.units.k
+defaultParam1d = 'shock_default1d.param'
+userDefault1d = 'shock_user_defaults1d.param'
+_directory = os.path.dirname(os.path.realpath(__file__))
+defaultParam1d = os.path.join(_directory, defaultParam1d)
+userDefault1d = os.path.join(_directory, userDefault1d)
+argsavename = 'icparams.p'
+
+def shock1d(nParticles=2*569, L=2., P=(1, 1./8), rhog=(1, 1./8), dustFrac=0.5,
+ gamma=5./3, inputParamName=None):
+ """
+ Creates SPH ICs for a 1D dusty-shock tube a la Price & Laibe 2015
+ (see their dustyshock, section 4.2).
+
+ Particles are in a line along the z-axis. Note that since ChaNGa uses
+ periodic boundaries (rather than particles in a tube) the shock tube
+ should be twice as long and will actually produce 2 shocks.
+
+ Parameters
+ ----------
+ nParticles: int
+ Approximate number of particles to use. nParticles will be set in the
+ end to best approximate the gas density in each region.
+ L: float
+ Length of the shock tube. (in code units)
+ P: array-like
+ Pressure in the two regions (left and right)
+ rhog: array-like
+ Gas density in the two regions
+ dustFrac: float
+ Dust fraction (between 0 and 1)
+ gamma: float
+ Adiabatic index
+ inputParamName: str
+ (optional) Override the default ChaNGa params. This can also be
+ done by changing the appropriate user default param in this directory.
+
+ Returns
+ -------
+ ICs: SimSnap
+ Pynbody snapshot of the ICs
+ param: dict
+ dict of the runtime params
+ arguments: dict
+ Arguments used when calling this function, including defaults.
+ paramsavename: str
+ Path the param file is saved to
+ """
+ # Keep track of arguments (and save at the end)
+ arguments = locals()
+
+ P = np.asarray(P)
+ rhog = np.asarray(P)
+ L = float(L)
+ gamma = float(gamma)
+
+ # --------------------------------------------
+ # Initialize
+ # --------------------------------------------
+ # Load stuff
+ if inputParamName is not None:
+ param = diskpy.utils.configparser(inputParamName)
+ else:
+ param = testdust.utils.loadDefaultParam(defaultParam1d, userDefault1d)
+# param = diskpy.utils.configparser(inputParamName, 'param')
+ fprefix = param['achOutName']
+ savename = param['achInFile']
+ molecularWeight = SimArray(param['dMeanMolWeight'], 'm_p')
+ units = diskpy.pychanga.units_from_param(param)
+ # Initialize quantities
+ L = SimArray(L, units['l_unit'])
+ P = SimArray(P, units['pres_unit'])
+ rhog = SimArray(rhog, units['rho_unit'])
+ rho = rhog/(1. - dustFrac)
+ # Set-up number of particles to left/right of boundary
+ N = np.array(np.round(nParticles * rho/rho.sum()).astype(int))
+ nParticles = N.sum()
+ # Initialize snapshot
+ f = pynbody.new(gas=nParticles)
+ # Initialize arrays
+ for key in ('temp', 'rho', 'dustFrac'):
+ f[key] = 0.
+ # Set up left/right slices. These select the left/right regions
+ slices = [slice(0, N[0]), slice(N[0], N[0] + N[1])]
+
+ # --------------------------------------------
+ # Setup values
+ # --------------------------------------------
+ # Mass
+ totMass = float((rho * (L/2.)).sum())
+ f['mass'] = totMass/nParticles
+ # Position
+ z = [0.5 * L * testdust.utils.periodicLine(n) for n in N]
+ f['z'][slices[0]] = z[0] - 0.25 * L
+ f['z'][slices[1]] = z[1] + 0.25 * L
+
+ # Temperature
+ T = molecularWeight * P/(rhog * kB)
+ T.convert_units('K')
+
+ # Assign arrays, looping over both sides
+ for i, s in enumerate(slices):
+ f['temp'][s] = T[i]
+ f['rho'][s] = rho[i]
+ f['dustFrac'][s] = dustFrac
+
+ # Other
+ f['eps'] = 10*L/nParticles
+
+ # Setup params
+ testdust.utils.setupParamBounds(param, [float(L)])
+ param['dConstGamma'] = gamma
+
+ # Save
+ f.write(filename=savename, fmt=pynbody.tipsy.TipsySnap)
+ print 'snapshot saved to:', savename
+ paramsavename = fprefix + '.param'
+ diskpy.utils.configsave(param, paramsavename)
+ print '.param file saved to:', paramsavename
+
+ pickle.dump(arguments, open(argsavename, 'w'), 2)
+ print 'arguments dict pickled to:', argsavename
+
+ return f, param, arguments, paramsavename
diff --git a/pool/shard009/Python/0087428_filechooser.py b/pool/shard009/Python/0087428_filechooser.py
new file mode 100644
index 0000000000000000000000000000000000000000..baba74ca6f436b03b169603cb2e8a539035585d0
--- /dev/null
+++ b/pool/shard009/Python/0087428_filechooser.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python
+# cropgui, a graphical front-end for lossless jpeg cropping
+# Copyright (C) 2009 Jeff Epler
+# 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
+PREVIEW_SIZE = 300
+
+import gi
+gi.require_version('Gtk', '3.0')
+from gi.repository import Gtk as gtk
+from gi.repository import GdkPixbuf as GdkPixbuf
+#import gtk.glade
+
+
+import os
+from PIL import Image
+import cropgui_common
+
+def apply_rotation(rotation, image):
+ print("apply_rotation", rotation)
+ if rotation == 3: return image.transpose(Image.ROTATE_180)
+ if rotation == 6: return image.transpose(Image.ROTATE_270)
+ if rotation == 8: return image.transpose(Image.ROTATE_90)
+ return image
+
+HIGH_WATER, LOW_WATER = 25, 5
+image_cache = {}
+def update_preview_cb(file_chooser, preview):
+ file_chooser.set_preview_widget_active(True)
+ filename = file_chooser.get_preview_filename()
+ if not filename or os.path.isdir(filename):
+ preview.set_from_stock(gtk.STOCK_DIRECTORY, gtk.IconSize.LARGE_TOOLBAR)
+ elif filename in image_cache:
+ preview.set_from_pixbuf(image_cache[filename])
+ else:
+ try:
+ i = Image.open(filename)
+ r = cropgui_common.image_rotation(i)
+ i.thumbnail((PREVIEW_SIZE, PREVIEW_SIZE), Image.ANTIALIAS)
+ i = i.convert('RGB')
+ i = apply_rotation(r, i)
+ try:
+ image_data = i.tostring()
+ except:
+ image_data = i.tobytes()
+ pixbuf = GdkPixbuf.Pixbuf.new_from_data(image_data,
+ GdkPixbuf.Colorspace.RGB, 0, 8, i.size[0], i.size[1],
+ i.size[0]*3)
+ preview.set_from_pixbuf(pixbuf)
+ if len(image_cache) > HIGH_WATER:
+ while len(image_cache) > LOW_WATER:
+ image_cache.popitem()
+ image_cache[filename] = pixbuf
+ except IOError as detail:
+ print(detail)
+ preview.set_from_stock(gtk.STOCK_MISSING_IMAGE,
+ gtk.IconSize.LARGE_TOOLBAR)
+ except:
+ preview.set_from_stock(gtk.STOCK_MISSING_IMAGE,
+ gtk.IconSize.LARGE_TOOLBAR)
+ raise
+
+class BaseChooser:
+ def __init__(self, title, parent):
+# Gnome's "attach-modal-dialogs" can be set to false using
+# gnome-tweak-tool in order to enable movable modal dialogs. No idea
+# how to do that app-specifically though.
+ self.dialog = dialog = \
+ gtk.FileChooserDialog(title, parent, self.mode, self.buttons)
+
+ def run(self):
+ self.dialog.show()
+ response = self.dialog.run()
+ self.dialog.hide()
+ if response == gtk.ResponseType.OK:
+ return self.dialog.get_filenames()
+ else:
+ return []
+
+class Chooser(BaseChooser):
+ mode = gtk.FileChooserAction.OPEN
+
+ buttons = (gtk.STOCK_QUIT, gtk.ResponseType.CANCEL,
+ gtk.STOCK_OPEN, gtk.ResponseType.OK)
+
+ def __init__(self, title, parent):
+ BaseChooser.__init__(self, title, parent)
+
+ self.dialog.set_default_response(gtk.ResponseType.OK)
+ self.dialog.set_select_multiple(True)
+
+ preview = gtk.Image()
+ preview.set_size_request(PREVIEW_SIZE, PREVIEW_SIZE)
+
+ self.dialog.set_preview_widget(preview)
+ self.dialog.set_preview_widget_active(True)
+ self.dialog.connect("update-preview", update_preview_cb, preview)
+
+ filter = gtk.FileFilter()
+ filter.set_name("Images")
+ filter.add_mime_type("image/*")
+ filter.add_pattern("*.jpg")
+ filter.add_pattern("*.jpeg")
+ filter.add_pattern("*.JPG")
+ filter.add_pattern("*.JPEG")
+ filter.add_pattern("*.png")
+ filter.add_pattern("*.PNG")
+ filter.add_pattern("*.tif")
+ filter.add_pattern("*.TIF")
+ filter.add_pattern("*.tiff")
+ filter.add_pattern("*.TIFF")
+ filter.add_pattern("*.gif")
+ filter.add_pattern("*.GIF")
+ self.dialog.add_filter(filter)
+
+ filter = gtk.FileFilter()
+ filter.set_name("All files")
+ filter.add_pattern("*")
+ self.dialog.add_filter(filter)
+
+class DirChooser(BaseChooser):
+ mode = gtk.FileChooserAction.SAVE
+ buttons = (gtk.STOCK_CANCEL, gtk.ResponseType.CANCEL,
+ gtk.STOCK_SAVE, gtk.ResponseType.OK)
+
+ def __init__(self, title, parent):
+ BaseChooser.__init__(self, title, parent)
+ self.dialog.set_default_response(gtk.ResponseType.OK)
+ self.dialog.set_do_overwrite_confirmation(True)
+
+ def set_current_name(self, filename):
+ self.dialog.set_current_name(filename)
+
+ def set_title(self, title):
+ self.dialog.set_title(title)
+
+ def set_current_folder(self, directory):
+ self.dialog.set_current_folder(directory)
diff --git a/pool/shard009/Python/0087433_intersect.py b/pool/shard009/Python/0087433_intersect.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd5bb61c111a731715e4566dc25c47295547d6cb
--- /dev/null
+++ b/pool/shard009/Python/0087433_intersect.py
@@ -0,0 +1,84 @@
+#!/usr/bin/python2.4
+#
+# 20,000 Light Years Into Space
+# This game is licensed under GPL v2, and copyright (C) Jack Whitham 2006.
+#
+
+
+# Line intersection algorithm. Thanks to page 113 of
+# Computer Graphics Principles and Practice (2nd. Ed), Foley et al.
+#
+# Note 1: it's not an intersection if the two lines share an endpoint.
+# Note 2: Can't detect overlapping parallel lines.
+
+def Intersect(((xa1,ya1),(xa2,ya2)),((xb1,yb1),(xb2,yb2))):
+ xa = xa2 - xa1
+ ya = ya2 - ya1
+ xb = xb2 - xb1
+ yb = yb2 - yb1
+
+ a = ( xa * yb ) - ( xb * ya )
+ if ( a == 0 ):
+ return None
+
+ b = ((( xa * ya1 ) + ( xb1 * ya ) - ( xa1 * ya )) - ( xa * yb1 ))
+ tb = float(b) / float(a)
+
+ if (( tb <= 0 ) or ( tb >= 1 )):
+ return None # doesn't intersect
+
+ if ( xa == 0 ):
+ if ( ya == 0 ):
+ return None # you've confused a line with a point.
+ ta = ( yb1 + ( yb * tb ) - ya1 ) / float(ya)
+ else:
+ ta = ( xb1 + ( xb * tb ) - xa1 ) / float(xa)
+
+ if (( ta <= 0 ) or ( ta >= 1 )):
+ return None # doesn't intersect
+
+ x = xb1 + ( xb * tb )
+ y = yb1 + ( yb * tb )
+ return (x,y)
+
+
+
+def Test():
+ import random , math
+
+ def BT(xp, line1, line2):
+ assert Intersect(line1, line2) == xp
+ assert Intersect(line2, line1) == xp
+
+ def Rnd():
+ def RP():
+ return (random.random(), random.random())
+
+ (x,y) = RP() # choose intersection point.
+ (xa1,ya1) = RP() # line 1 source
+ (xb1,yb1) = RP() # line 2 source
+
+ aang = math.atan2( y - ya1 , x - xa1 ) # line 1 angle
+ bang = math.atan2( y - yb1 , x - xb1 ) # line 2 angle
+
+ xa2 = xa1 + ( math.cos(aang) * 10.0 )
+ xb2 = xb1 + ( math.cos(bang) * 10.0 )
+ ya2 = ya1 + ( math.sin(aang) * 10.0 )
+ yb2 = yb1 + ( math.sin(bang) * 10.0 )
+
+ z = Intersect(((xa1,ya1),(xa2,ya2)),((xb1,yb1),(xb2,yb2)))
+ (xi, yi) = z
+ assert math.hypot(xi - x, yi - y) < 0.0001
+
+ BT((3,2),((3,1),(3,5)),((2,2),(4,2))) # cross
+ BT(None,((3,1),(3,5)),((1,1),(1,5))) # parallel lines
+ BT((2,2),((1,1),(3,3)),((1,3),(3,1))) # X
+ BT(None,((1,1),(3,3)),((2,2),(4,4))) # parallel lines, on top of each other
+
+ for i in xrange(10000):
+ Rnd()
+
+if ( __name__ == "__main__" ):
+ Test()
+
+
diff --git a/pool/shard009/Python/0087436_test_resubmit_video_body.py b/pool/shard009/Python/0087436_test_resubmit_video_body.py
new file mode 100644
index 0000000000000000000000000000000000000000..1834d54aba67da197e5b7cfab2f255083c86d6fd
--- /dev/null
+++ b/pool/shard009/Python/0087436_test_resubmit_video_body.py
@@ -0,0 +1,53 @@
+# coding: utf-8
+
+"""
+ Flip API
+
+ Flip # noqa: E501
+
+ The version of the OpenAPI document: 3.1
+ Contact: cloudsupport@telestream.net
+ Generated by: https://openapi-generator.tech
+"""
+
+
+from __future__ import absolute_import
+
+import unittest
+import datetime
+
+import telestream_cloud_flip
+from telestream_cloud_flip.models.resubmit_video_body import ResubmitVideoBody # noqa: E501
+from telestream_cloud_flip.rest import ApiException
+
+class TestResubmitVideoBody(unittest.TestCase):
+ """ResubmitVideoBody unit test stubs"""
+
+ def setUp(self):
+ pass
+
+ def tearDown(self):
+ pass
+
+ def make_instance(self, include_optional):
+ """Test ResubmitVideoBody
+ include_option is a boolean, when False only required
+ params are included, when True both required and
+ optional params are included """
+ # model = telestream_cloud_flip.models.resubmit_video_body.ResubmitVideoBody() # noqa: E501
+ if include_optional :
+ return ResubmitVideoBody(
+ video_id = '0'
+ )
+ else :
+ return ResubmitVideoBody(
+ )
+
+ def testResubmitVideoBody(self):
+ """Test ResubmitVideoBody"""
+ inst_req_only = self.make_instance(include_optional=False)
+ inst_req_and_optional = self.make_instance(include_optional=True)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0087442_netflixAnalyze.py b/pool/shard009/Python/0087442_netflixAnalyze.py
new file mode 100644
index 0000000000000000000000000000000000000000..449574d7d3f8ba3354ad0808e72801a5fc0826f7
--- /dev/null
+++ b/pool/shard009/Python/0087442_netflixAnalyze.py
@@ -0,0 +1,174 @@
+import numpy
+from numpy import *
+from operator import truediv
+from ast import literal_eval
+import matplotlib.pyplot as plt
+import statsmodels.tsa.stattools as st
+import scipy.stats as scit
+
+s = [ 124.580002,
+124.339996,
+122.190002,
+115.419998,
+114.779999,
+114.779999,
+114.779999,
+113.379997,
+113.589996,
+115.190002,
+115.029999,
+115.209999,
+115.209999,
+115.209999,
+117.959999,
+118.040001,
+117.690002,
+117.690002,
+117.410004,
+117.410004,
+117.410004,
+116.93,
+117.510002,
+117,
+117.220001,
+120.809998,
+120.809998,
+120.809998,
+119.160004,
+124.57]
+
+p = [line.rstrip('\n') for line in open("positive.txt")]
+n = [line.rstrip('\n') for line in open("negative.txt")]
+a = [line.rstrip('\n') for line in open("all.txt")]
+p_social = [line.rstrip('\n') for line in open("positive_social.txt")]
+n_social = [line.rstrip('\n') for line in open("negative_social.txt")]
+a_social = [line.rstrip('\n') for line in open("all_social.txt")]
+
+p_election = [line.rstrip('\n') for line in open("positive_election.txt")]
+n_election = [line.rstrip('\n') for line in open("negative_election.txt")]
+a_election = [line.rstrip('\n') for line in open("all_election.txt")]
+
+p_trump = [line.rstrip('\n') for line in open("positive_trump.txt")]
+n_trump = [line.rstrip('\n') for line in open("negative_trump.txt")]
+a_trump = [line.rstrip('\n') for line in open("all_trump.txt")]
+
+pInt = numpy.array(map(float, p))+1
+nInt = numpy.array(map(float, n))+1
+aInt = numpy.array(map(float, a))+1
+
+p_s_Int = numpy.array(map(float, p_social))+1
+n_s_Int = numpy.array(map(float, n_social))+1
+a_s_Int = numpy.array(map(float, a_social))+1
+
+p_elec = numpy.array(map(float, p_election))+1
+n_elec = numpy.array(map(float, n_election))+1
+a_elec = numpy.array(map(float, a_election))+1
+
+p_tr = numpy.array(map(float, p_trump))+1
+n_tr = numpy.array(map(float, n_trump))+1
+a_tr = numpy.array(map(float, a_trump))+1
+
+# Grab 30 data points for analysis
+pInt = pInt[0:30]
+nInt = nInt[0:30]
+aInt = aInt[0:30]
+
+# Grab 30 data points for p_s_Int
+p_s_Int = p_s_Int[0:30]
+n_s_Int = n_s_Int[0:30]
+a_s_Int = a_s_Int[0:30]
+
+# Grab 30 data points for p_s_Int
+p_tr = p_tr[0:30]
+n_tr = n_tr[0:30]
+a_tr = a_tr[0:30]
+
+p_elec = p_elec[0:30]
+n_elec = n_elec[0:30]
+a_elec = a_elec[0:30]
+
+print n_tr
+print p_tr
+print a_tr
+
+print n_elec
+print p_elec
+print a_elec
+
+tr_corr = numpy.corrcoef([n_tr+p_tr+a_tr, s])
+print tr_corr
+
+elec_corr = numpy.corrcoef([n_elec + p_elec + a_elec, s])
+print elec_corr
+
+n_elec_corr = numpy.corrcoef([n_elec, s])
+print n_elec_corr
+
+p_corr = numpy.corrcoef([pInt, s])
+n_corr = numpy.corrcoef([nInt, s])
+a_corr = numpy.corrcoef([aInt, s])
+
+print "Positive Sentiment: " + str(p_corr)
+print "Negative Sentiment: " + str(n_corr)
+print "Neutral Sentiment: " + str(a_corr)
+
+
+print p_s_Int
+
+p_s_corr = numpy.corrcoef([p_s_Int, s])
+n_s_corr = numpy.corrcoef([n_s_Int, s])
+a_s_corr = numpy.corrcoef([a_s_Int, s])
+
+print "Positive Social Sentiment: " + str(p_s_corr)
+print "Negative Social Sentiment: " + str(n_s_corr)
+print "Neutral Social Sentiment: " + str(a_s_corr)
+
+p_allcorr = numpy.corrcoef([numpy.add(pInt, p_s_Int), s])
+n_allcorr = numpy.corrcoef([numpy.add(nInt, n_s_Int), s])
+a_allcorr = numpy.corrcoef([numpy.add(aInt, a_s_Int), s])
+
+print "Positive All Sentiment: " + str(p_allcorr)
+print "Negative All Sentiment: " + str(n_allcorr)
+print "Neutral All Sentiment: " + str(a_allcorr)
+
+allVolumn = numpy.add(pInt, nInt)
+allVolumn = numpy.add(allVolumn, aInt)
+allCorr = numpy.corrcoef([allVolumn, s])
+
+print "All Volumn: " + str(allCorr)
+
+pn_ratio = pInt/nInt
+print pn_ratio
+pnr_corr = numpy.corrcoef([pn_ratio, s])
+
+print "PNR Corr: " + str(pnr_corr)
+
+p_sum = numpy.add(pInt, p_s_Int)
+n_sum = numpy.add(nInt, n_s_Int)
+
+print "P_SUM:" + str(p_sum)
+print "N_SUM:" + str(n_sum)
+
+
+beta = 1
+alpha = 1
+
+p_sum = pInt*numpy.array(p_s_Int)*beta
+n_sum = nInt*numpy.array(n_s_Int)*alpha
+
+pn_sum_ratio = p_sum/n_sum
+pnr_sum_corr = numpy.corrcoef([pn_sum_ratio, s])
+
+print "PNR Sum Corr: " + str(pnr_sum_corr)
+
+spearman_r = scit.spearmanr(pn_sum_ratio, s)
+print "Spearman's Correlation: " + str(spearman_r)
+
+cross_corr = numpy.correlate(pn_sum_ratio, s)
+print cross_corr
+
+testVector = numpy.column_stack((s, pn_ratio))
+st.grangercausalitytests(testVector, 8, verbose = True)
+
+testVector = numpy.column_stack((pn_ratio, s))
+st.grangercausalitytests(testVector, 8, verbose = True)
diff --git a/pool/shard009/Python/0087445_consider_using_f_string.py b/pool/shard009/Python/0087445_consider_using_f_string.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6801989e8099e658ddfe521de57b3cef0bc8c57
--- /dev/null
+++ b/pool/shard009/Python/0087445_consider_using_f_string.py
@@ -0,0 +1,126 @@
+"""Test to see if a f-string would be possible and consider-using-f-string should be raised"""
+# pylint: disable=unused-variable, invalid-name, missing-function-docstring, pointless-statement
+# pylint: disable=expression-not-assigned, repeated-keyword, too-many-locals
+
+PARAM_1 = PARAM_2 = PARAM_3 = 1
+PARAM_LIST = [PARAM_1, PARAM_2, PARAM_3]
+PARAM_LIST_SINGLE = [PARAM_1]
+PARAM_DICT = {"Param_1": PARAM_1, "Param_2": PARAM_2, "Param_3": PARAM_3}
+PARAM_DICT_SINGLE = {"Param_1": PARAM_1}
+
+
+def return_parameter():
+ return PARAM_1
+
+
+def return_list():
+ return PARAM_LIST
+
+
+def return_dict():
+ return PARAM_DICT
+
+
+def print_good():
+ print("String {}, {} or {}".format(*PARAM_LIST))
+ print("String {}, {}, {} or {}".format(*PARAM_LIST_SINGLE, *PARAM_LIST))
+ print("String {Param}, {}, {} or {}".format(Param=PARAM_1, *PARAM_LIST))
+ print("String {Param} {Param}".format(Param=PARAM_1))
+ print("{Param_1} {Param_2}".format(**PARAM_DICT))
+ print("{Param_1} {Param_2} {Param_3}".format(**PARAM_DICT_SINGLE, **PARAM_DICT))
+ print("{Param_1} {Param_2} {Param_3}".format(Param_1=PARAM_1, **PARAM_DICT))
+ print("{Param_1} {Param_2}".format(**PARAM_DICT))
+ print("{Param_1} {Param_2}".format(**return_dict()))
+ print("%(Param_1)s %(Param_2)s" % PARAM_LIST)
+ print("%(Param_1)s %(Param_2)s" % PARAM_DICT)
+ print("%(Param_1)s %(Param_2)s" % return_dict())
+ print("{a[Param_1]}{a[Param_2]}".format(a=PARAM_DICT))
+ print("{}".format("\n"))
+ print("{}".format("\n".join(i for i in "string")))
+ print("%s" % "\n")
+ print("%s" % "\n".join(i for i in "string"))
+
+
+def print_bad():
+ print("String %f" % PARAM_1) # [consider-using-f-string]
+ print("String {}".format(PARAM_1)) # [consider-using-f-string]
+ print("String {Param_1}".format(Param_1=PARAM_1)) # [consider-using-f-string]
+ print("{} {}".format(PARAM_1, PARAM_2)) # [consider-using-f-string]
+ print("{Par_1}{Par_2}".format(Par_1=PARAM_1, Par_2=PARAM_2)) # [consider-using-f-string]
+ print("{Param_1}".format(*PARAM_LIST_SINGLE)) # [consider-using-f-string]
+ print("{Param_1}".format(**PARAM_DICT_SINGLE)) # [consider-using-f-string]
+ print("String %s" % (PARAM_1)) # [consider-using-f-string]
+ print("String %s %s" % (PARAM_1, PARAM_2)) # [consider-using-f-string]
+ print("String %s" % (PARAM_LIST_SINGLE)) # [consider-using-f-string]
+
+
+def statement_good():
+ "String {}, {} or {}".format(*PARAM_LIST)
+ "String {}, {}, {} or {}".format(*PARAM_LIST_SINGLE, *PARAM_LIST)
+ "String {Param}, {}, {} or {}".format(Param=PARAM_1, *PARAM_LIST)
+ "String {Param} {Param}".format(Param=PARAM_1)
+ "{Param_1} {Param_2}".format(**PARAM_DICT)
+ "{Param_1} {Param_2} {Param_3}".format(**PARAM_DICT_SINGLE, **PARAM_DICT)
+ "{Param_1} {Param_2} {Param_3}".format(Param_1=PARAM_1, **PARAM_DICT)
+ "{Param_1} {Param_2}".format(**PARAM_DICT)
+ "{Param_1} {Param_2}".format(**return_dict())
+ "%(Param_1)s %(Param_2)s" % PARAM_LIST
+ "%(Param_1)s %(Param_2)s" % PARAM_DICT
+ "%(Param_1)s %(Param_2)s" % return_dict()
+ "{a[Param_1]}{a[Param_2]}".format(a=PARAM_DICT)
+ "{}".format("\n")
+ "{}".format("\n".join(i for i in "string"))
+ "%s" % "\n"
+ "%s" % "\n".join(i for i in "string")
+
+def statement_bad():
+ "String %f" % PARAM_1 # [consider-using-f-string]
+ "String {}".format(PARAM_1) # [consider-using-f-string]
+ "String {Param_1}".format(Param_1=PARAM_1) # [consider-using-f-string]
+ "{} {}".format(PARAM_1, PARAM_2) # [consider-using-f-string]
+ "{Par_1}{Par_2}".format(Par_1=PARAM_1, Par_2=PARAM_2) # [consider-using-f-string]
+ "{Param_1}".format(*PARAM_LIST_SINGLE) # [consider-using-f-string]
+ "{Param_1}".format(**PARAM_DICT_SINGLE) # [consider-using-f-string]
+ "String %s" % (PARAM_1) # [consider-using-f-string]
+ "String %s %s" % (PARAM_1, PARAM_2) # [consider-using-f-string]
+ "String %s" % (PARAM_LIST_SINGLE) # [consider-using-f-string]
+
+
+def assignment_good():
+ A = "String {}, {} or {}".format(*PARAM_LIST)
+ B = "String {}, {}, {} or {}".format(*PARAM_LIST_SINGLE, *PARAM_LIST)
+ C = "String {Param}, {}, {} or {}".format(Param=PARAM_1, *PARAM_LIST)
+ D = "String {Param} {Param}".format(Param=PARAM_1)
+ E = "{Param_1} {Param_2}".format(**PARAM_DICT)
+ F = "{Param_1} {Param_2} {Param_3}".format(**PARAM_DICT_SINGLE, **PARAM_DICT)
+ G = "{Param_1} {Param_2} {Param_3}".format(Param_1=PARAM_1, **PARAM_DICT)
+ H = "{Param_1} {Param_2}".format(**PARAM_DICT)
+ I = "{Param_1} {Param_2}".format(**return_dict())
+ J = "%(Param_1)s %(Param_2)s" % PARAM_LIST
+ K = "%(Param_1)s %(Param_2)s" % PARAM_DICT
+ L = "%(Param_1)s %(Param_2)s" % return_dict()
+ M = "{a[Param_1]}{a[Param_2]}".format(a=PARAM_DICT)
+ N = "{Param}".format
+ O = "%s" % "\n"
+ P = "%s" % "\n".join(i for i in "string")
+
+
+def assignment_bad():
+ a = "String %f" % PARAM_1 # [consider-using-f-string]
+ b = "String {}".format(PARAM_1) # [consider-using-f-string]
+ c = "String {Param_1}".format(Param_1=PARAM_1) # [consider-using-f-string]
+ d = "{} {}".format(PARAM_1, PARAM_2) # [consider-using-f-string]
+ e = "{Par_1}{Par_2}".format(Par_1=PARAM_1, Par_2=PARAM_2) # [consider-using-f-string]
+ f = "{Param_1}".format(*PARAM_LIST_SINGLE) # [consider-using-f-string]
+ g = "{Param_1}".format(**PARAM_DICT_SINGLE) # [consider-using-f-string]
+ h = "String %s" % (PARAM_1) # [consider-using-f-string]
+ i = "String %s %s" % (PARAM_1, PARAM_2) # [consider-using-f-string]
+ j = "String %s" % (PARAM_LIST_SINGLE) # [consider-using-f-string]
+
+
+def regression_tests():
+ # Referencing .format in a kwarg should not be warned
+ def wrap_print(value):
+ print(value)
+
+ wrap_print(value="{}".format)
diff --git a/pool/shard009/Python/0087451_typescript.syntax.py b/pool/shard009/Python/0087451_typescript.syntax.py
new file mode 100644
index 0000000000000000000000000000000000000000..62a93f8505c2687a793ae19f2c8a2d92c699876f
--- /dev/null
+++ b/pool/shard009/Python/0087451_typescript.syntax.py
@@ -0,0 +1,128 @@
+# -*- coding: UTF-8 -*-
+# Syntax definition automatically generated by hljs2xt.py
+# source: typescript.js
+name = 'TypeScript'
+file_patterns = ['*.typescript', '*.ts']
+
+built_in = """
+ eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent
+ encodeURI encodeURIComponent escape unescape Object Function Boolean
+ Error EvalError InternalError RangeError ReferenceError
+ StopIteration SyntaxError TypeError URIError Number Math Date String
+ RegExp Array Float32Array Float64Array Int16Array Int32Array
+ Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray
+ ArrayBuffer DataView JSON Intl arguments require module console
+ window document any number boolean string void
+ """.split()
+
+keyword = """
+ in if for while finally var new function do return void else break
+ catch instanceof with throw case default try this switch continue
+ typeof delete let yield const class public private protected get set
+ super static implements enum export import declare type namespace
+ abstract
+ """.split()
+
+operator_escape = ('operator.escape', [RE(r"\\[\s\S]")])
+
+class string:
+ default_text_color = DELIMITER
+ rules = [operator_escape]
+
+class string2:
+ default_text_color = DELIMITER
+ rules = [operator_escape, ('subst', RE(r"\$\{"), [RE(r"\}")])]
+string2.__name__ = 'string'
+
+class comment:
+ default_text_color = DELIMITER
+ rules = [
+ # ignore {'begin': {'pattern': "\\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|like)\\b", 'type': 'RegExp'}},
+ ('doctag', [RE(r"(?:TODO|FIXME|NOTE|BUG|XXX):")]),
+ ]
+
+comment0 = ('comment', RE(r"//"), [RE(r"$")], comment)
+
+comment1 = ('comment', RE(r"/\*"), [RE(r"\*/")], comment)
+
+number1 = [
+ RE(r"(?:\b0[xX][a-fA-F0-9]+|(?:\b\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)"),
+]
+
+class _group2:
+ default_text_color = DELIMITER
+ rules = [operator_escape]
+
+class regexp:
+ default_text_color = DELIMITER
+ rules = [operator_escape, ('_group2', RE(r"\["), [RE(r"\]")], _group2)]
+
+class _group1:
+ default_text_color = DELIMITER
+ rules = [
+ ('keyword', ['return', 'throw', 'case']),
+ comment0,
+ comment1,
+ ('regexp', RE(r"\/"), [RE(r"\/[gimuy]*")], regexp),
+ ]
+
+class _function0:
+ default_text_color = DELIMITER
+ rules = [('_function', [RE(r"[\{;]")])]
+_function0.__name__ = '_function'
+
+class _params0:
+ default_text_color = DELIMITER
+ rules = [('_params', [RE(r"\(")])]
+_params0.__name__ = '_params'
+
+class _params2:
+ default_text_color = DELIMITER
+ rules = [('_params', [RE(r"\)")])]
+_params2.__name__ = '_params'
+
+class params:
+ default_text_color = DELIMITER
+ rules = [
+ ('built_in', built_in),
+ ('keyword', keyword),
+ ('literal', ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity']),
+ comment0,
+ comment1,
+ ]
+
+class function:
+ default_text_color = DELIMITER
+ rules = [
+ ('built_in', built_in),
+ ('keyword', keyword),
+ ('literal', ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity']),
+ ('title', [RE(r"[A-Za-z$_][0-9A-Za-z$_]*")]),
+ ('params', _params0, [_params2], params),
+ ]
+
+class _group5:
+ default_text_color = DELIMITER
+ rules = [('keyword', ['interface', 'extends']), ('keyword', ['interface'])]
+
+rules = [
+ ('built_in', built_in),
+ ('keyword', keyword),
+ ('literal', ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity']),
+ ('meta', [RE(r"^\s*['\"]use strict['\"]")]),
+ ('string', RE(r"'"), [RE(r"'")], string),
+ ('string', RE(r"\""), [RE(r"\"")], string),
+ ('string', RE(r"`"), [RE(r"`")], string2),
+ comment0,
+ comment1,
+ ('number', [RE(r"\b(?:0[bB][01]+)")]),
+ ('number', [RE(r"\b(?:0[oO][0-7]+)")]),
+ ('number', number1),
+ ('_group1', RE(r"(?:!|!=|!==|%|%=|&|&&|&=|\*|\*=|\+|\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\?|\[|\{|\(|\^|\^=|\||\|=|\|\||~|\b(?:case|return|throw)\b)\s*"), [RE(r"\B|\b")], _group1),
+ ('function', RE(r"function"), [_function0], function),
+ ('_group3', RE(r"\b(?:constructor)"), [RE(r"\{")]),
+ ('_group4', RE(r"\b(?:module)"), [RE(r"\{")]),
+ ('_group5', RE(r"\b(?:interface)"), [RE(r"\{")], _group5),
+ # ignore {'begin': {'pattern': '\\$[(.]', 'type': 'RegExp'}},
+ # ignore {'begin': '\\.[a-zA-Z]\\w*', 'relevance': 0},
+]
diff --git a/pool/shard009/Python/0087457_3dplot.py b/pool/shard009/Python/0087457_3dplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..753f721d03e13219eb55b600b366cf8f65c2f6d2
--- /dev/null
+++ b/pool/shard009/Python/0087457_3dplot.py
@@ -0,0 +1,24 @@
+import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d.axes3d import Axes3D
+import numpy as np
+from matplotlib import cm
+
+
+def f(x, y):
+ return np.cos(x**2 + y**2) / (1 + x**2 + y**2)
+
+xgrid = np.linspace(-3, 3, 50)
+ygrid = xgrid
+x, y = np.meshgrid(xgrid, ygrid)
+
+fig = plt.figure(figsize=(8, 6))
+ax = fig.add_subplot(111, projection='3d')
+ax.plot_surface(x,
+ y,
+ f(x, y),
+ rstride=2, cstride=2,
+ cmap=cm.jet,
+ alpha=0.7,
+ linewidth=0.25)
+ax.set_zlim(-0.5, 1.0)
+plt.show()
diff --git a/pool/shard009/Python/0087467_tasks.py b/pool/shard009/Python/0087467_tasks.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b6ceda4119b9b0a008963282e3317b9ae77efd2
--- /dev/null
+++ b/pool/shard009/Python/0087467_tasks.py
@@ -0,0 +1,57 @@
+"""
+Supporting celery tasks go in this module. The primarily interesting one is
+SendEmailTask, which handles sending a single Django EmailMessage object.
+"""
+from django.conf import settings
+from celery.task import Task
+from boto.ses import SESConnection
+from seacucumber.util import get_boto_ses_connection
+
+class SendEmailTask(Task):
+ """
+ Sends an email through Boto's SES API module.
+ """
+ def __init__(self):
+ self.max_retries = getattr(settings, 'CUCUMBER_MAX_RETRIES', 60)
+ self.default_retry_delay = getattr(settings, 'CUCUMBER_RETRY_DELAY', 60)
+ self.rate_limit = getattr(settings, 'CUCUMBER_RATE_LIMIT', 1)
+ # A boto.ses.SESConnection object, after running _open_ses_conn().
+ self.connection = None
+
+ def run(self, from_email, recipients, message):
+ """
+ This does the dirty work. Connects to Amazon SES via boto and fires
+ off the message.
+
+ :param str from_email: The email address the message will show as
+ originating from.
+ :param list recipients: A list of email addresses to send the
+ message to.
+ :param str message: The body of the message.
+ """
+ self._open_ses_conn()
+ try:
+ # We use the send_raw_email func here because the Django
+ # EmailMessage object we got these values from constructs all of
+ # the headers and such.
+ self.connection.send_raw_email(
+ source=from_email,
+ destinations=recipients,
+ raw_message=message,
+ )
+ except Exception, exc:
+ self.retry(exc=exc)
+
+ # We shouldn't ever block long enough to see this, but here it is
+ # just in case (for debugging?).
+ return True
+
+ def _open_ses_conn(self):
+ """
+ Create a connection to the AWS API server. This can be reused for
+ sending multiple emails.
+ """
+ if self.connection:
+ return
+
+ self.connection = get_boto_ses_connection()
diff --git a/pool/shard009/Python/0087469_launcher.py b/pool/shard009/Python/0087469_launcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaf24b6167180492b296ec9da0aa39fe145f7ce5
--- /dev/null
+++ b/pool/shard009/Python/0087469_launcher.py
@@ -0,0 +1,237 @@
+import os
+import sys
+from time import *
+import subprocess
+import signal
+from machinekit import compat
+
+_processes = []
+_realtimeStarted = False
+
+
+# ends a running Machinekit session
+def end_session():
+ stop_processes()
+ if _realtimeStarted: # Stop realtime only when explicitely started
+ stop_realtime()
+
+
+# checks wheter a single command is available or not
+def check_command(command):
+ process = subprocess.Popen('which ' + command, stdout=subprocess.PIPE,
+ shell=True)
+ process.wait()
+ if process.returncode != 0:
+ print((command + ' not found, check Machinekit installation'))
+ sys.exit(1)
+
+
+# checks the whole Machinekit installation
+def check_installation():
+ commands = ['realtime', 'configserver', 'halcmd', 'haltalk', 'webtalk']
+ for command in commands:
+ check_command(command)
+
+
+# checks for a running session and cleans it up if necessary
+def cleanup_session():
+ pids = []
+ commands = ['configserver', 'halcmd', 'haltalk', 'webtalk', 'rtapi']
+ process = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
+ out, err = process.communicate()
+ for line in out.splitlines():
+ for command in commands:
+ if command in line:
+ pid = int(line.split(None, 1)[0])
+ pids.append(pid)
+
+ if pids != []:
+ stop_realtime()
+ sys.stdout.write("cleaning up leftover session... ")
+ sys.stdout.flush()
+ for pid in pids:
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except OSError:
+ pass
+ sys.stdout.write('done\n')
+
+
+# starts a command, waits for termination and checks the output
+def check_process(command):
+ sys.stdout.write("running " + command.split(None, 1)[0] + "... ")
+ sys.stdout.flush()
+ subprocess.check_call(command, shell=True)
+ sys.stdout.write('done\n')
+
+
+# starts and registers a process
+def start_process(command, check=True, wait=1.0):
+ sys.stdout.write("starting " + command.split(None, 1)[0] + "... ")
+ sys.stdout.flush()
+ process = subprocess.Popen(command, shell=True)
+ process.command = command
+ if check:
+ sleep(wait)
+ process.poll()
+ if (process.returncode is not None):
+ raise subprocess.CalledProcessError(process.returncode, command, None)
+ _processes.append(process)
+ sys.stdout.write('done\n')
+
+
+# stops a registered process by its name
+def stop_process(command):
+ for process in _processes:
+ processCommand = process.command.split(None, 1)[0]
+ if command == processCommand:
+ sys.stdout.write('stopping ' + command + '... ')
+ sys.stdout.flush()
+ process.kill()
+ process.wait()
+ sys.stdout.write('done\n')
+
+
+# stops all registered processes
+def stop_processes():
+ for process in _processes:
+ sys.stdout.write('stopping ' + process.command.split(None, 1)[0]
+ + '... ')
+ sys.stdout.flush()
+ process.terminate()
+ process.wait()
+ sys.stdout.write('done\n')
+
+
+# loads a HAL configuraton file
+def load_hal_file(filename, ini=None):
+ sys.stdout.write("loading " + filename + '... ')
+ sys.stdout.flush()
+ command = 'halcmd'
+ if ini is not None:
+ command += ' -i ' + ini
+ command += ' -f ' + filename
+ subprocess.check_call(command, shell=True)
+ sys.stdout.write('done\n')
+
+
+# loads a BBIO configuration file
+def load_bbio_file(filename):
+ check_command('config-pin')
+ sys.stdout.write("loading " + filename + '... ')
+ sys.stdout.flush()
+ subprocess.check_call('config-pin -f ' + filename, shell=True)
+ sys.stdout.write('done\n')
+
+
+# installs a comp RT component
+def install_comp(filename):
+ install = True
+ base = os.path.splitext(os.path.basename(filename))[0]
+ flavor = compat.default_flavor()
+ moduleDir = compat.get_rtapi_config("RTLIB_DIR")
+ moduleName = flavor.name + '/' + base + flavor.mod_ext
+ modulePath = os.path.join(moduleDir, moduleName)
+ if os.path.exists(modulePath):
+ compTime = os.path.getmtime(filename)
+ moduleTime = os.path.getmtime(modulePath)
+ if (compTime < moduleTime):
+ install = False
+
+ if install is True:
+ sys.stdout.write("installing " + filename + '... ')
+ sys.stdout.flush()
+ if os.access(moduleDir, os.W_OK): # if we have write access we might not need sudo
+ subprocess.check_call('comp --install ' + filename, shell=True)
+ else:
+ subprocess.check_call('sudo comp --install ' + filename, shell=True)
+ sys.stdout.write('done\n')
+
+
+# starts realtime
+def start_realtime():
+ sys.stdout.write("starting realtime...")
+ sys.stdout.flush()
+ subprocess.check_call('realtime start', shell=True)
+ sys.stdout.write('done\n')
+ _realtimeStarted = True
+
+
+# stops realtime
+def stop_realtime():
+ sys.stdout.write("stopping realtime... ")
+ sys.stdout.flush()
+ subprocess.check_call('realtime stop', shell=True)
+ sys.stdout.write('done\n')
+ _realtimeStarted = False
+
+
+# rip the Machinekit environment
+def rip_environment(path=None, force=False):
+ if force is False and os.getenv('EMC2_PATH') is not None: # check if already ripped
+ return
+
+ if path is None:
+ command = None
+ scriptFilePath = os.environ['HOME'] + '/.bashrc'
+ if os.path.exists(scriptFilePath):
+ with open(scriptFilePath) as f: # use the bashrc
+ content = f.readlines()
+ for line in content:
+ if 'rip-environment' in line:
+ line = line.strip()
+ if (line[0] == '.'):
+ command = line
+
+ scriptFilePath = os.environ['HOME'] + '/machinekit/scripts/rip-environment'
+ if os.path.exists(scriptFilePath):
+ command = '. ' + scriptFilePath
+
+ if (command is None):
+ sys.stderr.write('Unable to rip environment')
+ sys.exit(1)
+ else:
+ command = '. ' + path + '/scripts/rip-environment'
+
+ process = subprocess.Popen(command + ' && env',
+ stdout=subprocess.PIPE,
+ shell=True)
+ for line in process.stdout:
+ (key, _, value) = line.partition('=')
+ os.environ[key] = value.rstrip()
+
+ sys.path.append(os.environ['PYTHONPATH'])
+
+
+# checks the running processes and exits when exited
+def check_processes():
+ for process in _processes:
+ process.poll()
+ if (process.returncode is not None):
+ _processes.remove(process)
+ end_session()
+ if (process.returncode != 0):
+ sys.exit(1)
+ else:
+ sys.exit(0)
+
+
+# register exit signal handlers
+def register_exit_handler():
+ signal.signal(signal.SIGINT, _exitHandler)
+ signal.signal(signal.SIGTERM, _exitHandler)
+
+
+def _exitHandler(signum, frame):
+ end_session()
+ sys.exit(0)
+
+
+# set the Machinekit debug level
+def set_debug_level(level):
+ os.environ['DEBUG'] = str(level)
+
+
+# set the Machinekit ini
+def set_machinekit_ini(ini):
+ os.environ['MACHINEKIT_INI'] = ini
diff --git a/pool/shard009/Python/0087470_cnn_encoder.py b/pool/shard009/Python/0087470_cnn_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd27100760ac371880e47e0d59455895ac96b65c
--- /dev/null
+++ b/pool/shard009/Python/0087470_cnn_encoder.py
@@ -0,0 +1,168 @@
+"""CNN for image processing."""
+
+from typing import List, Tuple, Type, Optional
+
+import numpy as np
+import tensorflow as tf
+
+from tensorflow.contrib.layers import conv2d, max_pool2d
+
+from neuralmonkey.checking import assert_shape
+from neuralmonkey.dataset import Dataset
+from neuralmonkey.decorators import tensor
+from neuralmonkey.encoders.attentive import Attentive
+from neuralmonkey.decoding_function import Attention
+from neuralmonkey.model.model_part import ModelPart, FeedDict
+from neuralmonkey.nn.projection import multilayer_projection
+
+
+class CNNEncoder(ModelPart, Attentive):
+ """An image encoder.
+
+ It projects the input image through a serie of convolutioal operations. The
+ projected image is vertically cut and fed to stacked RNN layers which
+ encode the image into a single vector.
+ """
+
+ # pylint: disable=too-many-arguments, too-many-locals
+ def __init__(self,
+ name: str,
+ data_id: str,
+ convolutions: List[Tuple[int, int, Optional[int]]],
+ image_height: int, image_width: int, pixel_dim: int,
+ fully_connected: Optional[List[int]] = None,
+ dropout_keep_prob: float = 0.5,
+ attention_type: Type = Attention,
+ save_checkpoint: Optional[str] = None,
+ load_checkpoint: Optional[str] = None) -> None:
+ """Initialize a convolutional network for image processing.
+
+ Args:
+ convolutions: Configuration of convolutional layers. It is a list
+ of triplets of integers where the values are: size of the
+ convolutional window, number of convolutional filters, and size
+ of max-pooling window. If the max-pooling size is set to None,
+ no pooling is performed.
+ data_id: Identifier of the data series in the dataset.
+ image_height: Height of the input image in pixels.
+ image_width: Width of the image.
+ pixel_dim: Number of color channels in the input images.
+ dropout_keep_prob: Probability of keeping neurons active in
+ dropout. Dropout is done between all convolutional layers and
+ fully connected layer.
+ """
+ ModelPart.__init__(self, name, save_checkpoint, load_checkpoint)
+ Attentive.__init__(self, attention_type)
+
+ self.data_id = data_id
+ self.dropout_keep_prob = dropout_keep_prob
+
+ self.image_height = image_height
+ self.image_width = image_width
+ self.pixel_dim = pixel_dim
+ self.convolutions = convolutions
+ self.fully_connected = fully_connected
+
+ # pylint: disable=no-self-use
+ @tensor
+ def train_mode(self) -> tf.Tensor:
+ return tf.placeholder(tf.bool, shape=[], name="mode_placeholder")
+ # pylint: enable=no-self-use
+
+ @tensor
+ def image_input(self) -> tf.Tensor:
+ return tf.placeholder(
+ tf.float32,
+ shape=(None, self.image_height, self.image_width,
+ self.pixel_dim),
+ name="input_images")
+
+ @tensor
+ def image_processing_layers(self) -> List[tf.Tensor]:
+ """Do all convolutions and return the last conditional map.
+
+ Applies convolutions on the input tensor with optional max pooling.
+ All the intermediate layers are stored in the `image_processing_layers`
+ attribute. There is not dropout between the convolutional layers, by
+ default the activation function is ReLU.
+ """
+ last_layer = self.image_input
+ image_processing_layers = [] # type: List[tf.Tensor]
+
+ with tf.variable_scope("convolutions"):
+ for i, (filter_size,
+ n_filters,
+ pool_size) in enumerate(self.convolutions):
+ with tf.variable_scope("cnn_layer_{}".format(i)):
+ last_layer = conv2d(last_layer, n_filters, filter_size)
+ image_processing_layers.append(last_layer)
+
+ if pool_size:
+ last_layer = max_pool2d(last_layer, pool_size)
+ image_processing_layers.append(last_layer)
+
+ return image_processing_layers
+
+ @tensor
+ def states(self):
+ # pylint: disable=unsubscriptable-object
+ return self.image_processing_layers[-1]
+ # pylint: enable=unsubscriptable-object
+
+ @tensor
+ def encoded(self) -> tf.Tensor:
+ """Output vector of the CNN.
+
+ If there are specified some fully connected layers, there are applied
+ on top of the last convolutional map. Dropout is applied between all
+ layers, default activation function is ReLU. There are only projection
+ layers, no softmax is applied.
+
+ If there is fully_connected layer specified, average-pooled last
+ convolutional map is used as a vector output.
+ """
+ # pylint: disable=no-member
+ last_height, last_width, last_n_channels = [
+ s.value for s in self.states.get_shape()[1:]]
+ # pylint: enable=no-member
+
+ if self.fully_connected is None:
+ # we average out by the image size -> shape is number
+ # channels from the last convolution
+ encoded = tf.reduce_mean(self.states, [1, 2])
+ assert_shape(encoded, [None, self.convolutions[-1][1]])
+ return encoded
+
+ states_flat = tf.reshape(
+ self.states,
+ [-1, last_width * last_height * last_n_channels])
+ return multilayer_projection(
+ states_flat, self.fully_connected,
+ activation=tf.nn.relu,
+ dropout_keep_prob=self.dropout_keep_prob,
+ train_mode=self.train_mode)
+
+ @tensor
+ def _attention_tensor(self) -> tf.Tensor:
+ # pylint: disable=no-member
+ last_height, last_width, last_n_channels = [
+ s.value for s in self.states.get_shape()[1:]]
+ # pylint: enable=no-member
+ return tf.reshape(
+ self.states,
+ [-1, last_width * last_height, last_n_channels])
+
+ @tensor
+ def _attention_mask(self) -> tf.Tensor:
+ return tf.ones(tf.shape(self._attention_tensor)[:2])
+
+ def feed_dict(self, dataset: Dataset, train: bool = False) -> FeedDict:
+ # if it is from the pickled file, it is list, not numpy tensor,
+ # so convert it as as a prevention
+ images = np.array(dataset.get_series(self.data_id))
+
+ f_dict = {}
+ f_dict[self.image_input] = images / 225.0
+
+ f_dict[self.train_mode] = train
+ return f_dict
diff --git a/pool/shard009/Python/0087471_tk_test_090920170003.py b/pool/shard009/Python/0087471_tk_test_090920170003.py
new file mode 100644
index 0000000000000000000000000000000000000000..58c4604452321bc4fcd89e13da98e86001838be5
--- /dev/null
+++ b/pool/shard009/Python/0087471_tk_test_090920170003.py
@@ -0,0 +1,13 @@
+import time
+from tkinter import *
+
+animation = Tk()
+canvas = Canvas(animation, width=800, height=600)
+canvas.pack()
+canvas.create_polygon(10, 10, 60, 50, 35, 35)
+
+for x in range(0, 140):
+ canvas.move(1, 5, 0)
+ animation.update()
+ time.sleep(0.05)
+
diff --git a/pool/shard009/Python/0087482_hbase_table_e2e_test.py b/pool/shard009/Python/0087482_hbase_table_e2e_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..12ae2b3a46234bb8534a19cfe7bcea1367d9a554
--- /dev/null
+++ b/pool/shard009/Python/0087482_hbase_table_e2e_test.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Tests for `hbase_table` module.
+"""
+import pytest
+
+from HBaseBoard.hbase_table import HBaseTable
+from HBaseBoard.hbase_wrapper import HBaseWrapper
+
+
+class TestHBaseTableClass(object):
+ def setup(self):
+ self.hb_wrapper = HBaseWrapper()
+ self.hb_wrapper.delete_all_tables()
+ self.hb_wrapper.create_default_table("test_table")
+
+ def teardown(self):
+ self.hb_wrapper.delete_all_tables()
+ self.hb_wrapper.close_connection()
+
+ def test_raises_error_if_no_table_exists(self):
+ with pytest.raises(ValueError):
+ HBaseTable("ghost", self.hb_wrapper)
+
+ def test_scan_returns_iterable_that_scans_a_table(self):
+ my_table = HBaseTable("test_table", self.hb_wrapper)
+ test_val1 = ("key1", {"cf:first_name": "bugs", "cf:last_name": "bunny"})
+ test_val2 = ("key2", {"cf:first_name": "daffy", "cf:last_name": "duck"})
+ my_table.put([test_val1, test_val2])
+
+ table_vals = []
+ for value in my_table.scan():
+ table_vals.append(value)
+
+ assert 2 == len(table_vals)
+ assert test_val1 in table_vals
+ assert test_val2 in table_vals
+
+ def test_scan_accepts_filter_on_keys(self):
+ my_table = HBaseTable("test_table", self.hb_wrapper)
+ test_val1 = ("key1_matches",
+ {"cf:first_name": "bugs", "cf:last_name": "bunny"})
+ test_val2 = ("key2_does_not_match",
+ {"cf:first_name": "daffy", "cf:last_name": "duck"})
+ test_val3 = ("key3_matches",
+ {"cf:first_name": "porky", "cf:last_name": "pig"})
+ test_val4 = ("key4_matches_not_expected",
+ {"cf:first_name": "goofy", "cf:last_name": "dog"})
+ my_table.put([test_val1, test_val2, test_val3, test_val4])
+
+ table_vals = []
+ for value in my_table.scan(key="matches$"):
+ table_vals.append(value)
+
+ assert 2 == len(table_vals)
+ assert test_val1 in table_vals
+ assert test_val3 in table_vals
+
+ def test_scan_accepts_custom_max_count(self):
+ my_table = HBaseTable("test_table", self.hb_wrapper)
+ test_val1 = ("key1", {"cf:first_name": "bugs", "cf:last_name": "bunny"})
+ test_val2 = ("key2", {"cf:first_name": "daffy", "cf:last_name": "duck"})
+ test_val3 = ("key3", {"cf:first_name": "porky", "cf:last_name": "pig"})
+ test_val4 = ("key4", {"cf:first_name": "goofy", "cf:last_name": "dog"})
+ my_table.put([test_val1, test_val2, test_val3, test_val4])
+
+ table_vals = []
+ for value in my_table.scan(max_count=3):
+ table_vals.append(value)
+
+ assert 3 == len(table_vals)
+
+ def test_scan_counts_only_the_fields_that_match(self):
+ my_table = HBaseTable("test_table", self.hb_wrapper)
+ test_val1 = ("key1_matches",
+ {"cf:first_name": "bugs", "cf:last_name": "bunny"})
+ test_val2 = ("key2_does_not_match",
+ {"cf:first_name": "daffy", "cf:last_name": "duck"})
+ test_val3 = ("key3_matches",
+ {"cf:first_name": "porky", "cf:last_name": "pig"})
+ test_val4 = ("key4_another_one_matches",
+ {"cf:first_name": "goofy", "cf:last_name": "dog"})
+ my_table.put([test_val1, test_val2, test_val3, test_val4])
+
+ table_vals = []
+ for value in my_table.scan(key="matches$", max_count=2):
+ table_vals.append(value)
+
+ assert 2 == len(table_vals)
+ assert test_val1 in table_vals
+ assert test_val3 in table_vals
diff --git a/pool/shard009/Python/0087483_sunat_3_4.py b/pool/shard009/Python/0087483_sunat_3_4.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd552ca3c907bd627f1dcc4e9d82f328cc4144d8
--- /dev/null
+++ b/pool/shard009/Python/0087483_sunat_3_4.py
@@ -0,0 +1,226 @@
+# -*- encoding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (c) 2011 NUMA Extreme Systems (www.numaes.com) for Cubic ERP - Teradata SAC. (http://cubicerp.com).
+#
+# WARNING: This program as such is intended to be used by professional
+# programmers who take the whole responsability of assessing all potential
+# consequences resulting from its eventual inadequacies and bugs
+# End users who are looking for a ready-to-use solution with commercial
+# garantees and support are strongly adviced to contract a Free Software
+# Service Company
+#
+# 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.
+#
+##############################################################################
+
+
+from openerp.osv import fields, osv
+
+class ple_3_4 (osv.Model):
+ _name = "l10n_pe.ple_3_4"
+ _inherit = "l10n_pe.ple"
+
+ _columns= {
+ 'lines_ids': fields.one2many ('l10n_pe.ple_line_3_4', 'ple_3_4_id', 'Lines', readonly=True, states={'draft':[('readonly',False)],}),
+ }
+
+ def action_reload (self, cr, uid, ids, context=None):
+ assert ids and len(ids)==1
+ ple_line_obj = self.pool.get('l10n_pe.ple_line_3_4')
+
+ #Remove existing lines
+ ple = self.browse(cr, uid, ids[0], context=context)
+ cmds = []
+ for line in ple.lines_ids:
+ cmds.append((2, line.id))
+ if cmds:
+ ple.write({'lines_ids': cmds}, context=context)
+ ple.refresh()
+
+ # Get the list of involved movements
+ period_ids = self.get_all_periods_up_to (cr, uid, ids, ple.period_id.id)
+ move_lines = self.get_move_lines (cr, uid, period_ids, '3_4', ple.company_id.id, context=context)
+
+ #Get the list of involved partners
+ partner_ids = list(set([aml.partner_id.id for aml in move_lines]))
+
+ for partner_id in partner_ids:
+ vals = {
+ 'ple_3_4_id': ple.id,
+ 'partner_id': partner_id,
+ }
+ vals.update(ple_line_obj.onchange_partner_id(cr, uid, [], partner_id, ple.period_id.id, context=context)['value'])
+ ple_line_obj.create(cr, uid, vals, context=context)
+
+ return True
+
+ def action_renumber (self, cr, uid, ids, context=None):
+ assert ids and len(ids)==1
+
+ ple = self.browse (cr, uid, ids[0], context=context)
+
+ next_seq = 1
+ for line in sorted(ple.lines_ids, key=lambda l: l.operation_date_3):
+ line.write ({'sequence': next_seq}, context=context)
+ next_seq += 1
+
+ return True
+
+ def action_report (self, cr, uid, ids, context=None):
+ assert ids and len(ids)==1
+
+ return {
+ 'type': 'ir.actions.report.xml',
+ 'report_name': 'l10n_pe.sunat_3_4',
+ 'datas': {},
+ }
+
+ def get_output_lines (self, cr, uid, ids, context=None):
+
+ assert ids and len(ids)==1
+
+ ple = self.browse (cr, uid, ids[0], context=context)
+
+ res = []
+ for r in ple.lines_ids:
+ elements = [
+ "%s%s00" % (ple.period_id.date_start[0:4], ple.period_id.date_start[5:7]),
+ self.convert_str(r.sequence),
+ self.convert_str(r.partner_doc_type_3),
+ self.convert_str(r.partner_doc_number_4),
+ self.convert_str(r.partner_name_5),
+ self.convert_date (r.operation_date_6),
+ self.convert_amount(r.amount_7),
+ self.convert_str(r.operation_state_8),
+ ]
+ res.append('|'.join(elements))
+ return res
+
+ def get_output_filename (self, cr, uid, ids, context=None):
+ return "sunat_3_4.txt"
+
+class ple_line_3_4 (osv.Model):
+ _name = 'l10n_pe.ple_line_3_4'
+ _inherit = 'l10n_pe.ple_line'
+
+ def _get_doc_type_selection (self, cr, uid, context=None):
+ bt_obj = self.pool.get('base.element')
+
+ return bt_obj.get_as_selection(cr, uid, 'PE.SUNAT.TABLA_02', context=context)
+
+ _columns = {
+ 'ple_3_4_id': fields.many2one('l10n_pe.ple_3_4', 'PLE', on_delete='cascade'),
+ 'state': fields.related ('ple_3_4_id', 'state', string='State', type="char"),
+ 'company_id': fields.related ('ple_3_4_id', 'company_id', string='Company', type="many2one", relation="res.company"),
+ 'partner_id': fields.many2one('res.partner', 'Partner', on_delete="restrict"),
+
+ 'partner_doc_type_3': fields.selection(_get_doc_type_selection, "Doc. type", required=True, size=3, help="Tipo de Documento de Identidad del accionista, socio o personal"),
+ 'partner_doc_number_4': fields.char("Partner's doc. number", size=15, help="Número de Documento de Identidad del accionista, socio o personal"),
+ 'partner_name_5': fields.char("Partner's name", size=60, required=True, help="Apellidos y Nombres, Denominación o Razón Social del accionista, socio o personal"),
+ 'operation_date_6': fields.date ('Operation date', required=True, help="Fecha de inicio de la operación"),
+ 'amount_7': fields.float('Amount', digits=(12,2), help="Monto de cada cuenta por cobrar del accionista, socio o personal"),
+ 'operation_state_8': fields.selection ([
+ ('1', '1'),
+ ('8', '8'),
+ ('9', '9'),
+ ], 'Operation state', required=True, help="""
+Registrar '1' cuando la operación corresponde al periodo,
+'8' cuando la operación corresponde a un periodo anterior y NO ha sido anotada en dicho periodo o
+'9' cuando la operación corresponde a un periodo anterior y SI ha sido anotada en dicho periodo."""),
+ }
+
+ _order = 'sequence'
+
+ _defaults = {
+ 'operation_date_6': fields.date.context_today,
+ 'operation_state_8': '1',
+ }
+
+ def onchange_partner_id (self, cr, uid, ids, partner_id, period_id, context=None):
+ vals = {}
+ if partner_id:
+ ple_3_4_obj = self.pool.get('l10n_pe.ple_3_4')
+ period_obj = self.pool.get('account.period')
+ partner_obj = self.pool.get('res.partner')
+
+ lines = ple_3_4_obj.get_move_lines(cr, uid,
+ ple_3_4_obj.get_all_periods_up_to(period_id, context=context),
+ '3_4',
+ partner_id=partner_id,
+ context=context)
+ lines.sort(key=lambda l: (l.period_id.date_start))
+
+ initial_balance = 0.0
+ final_balance = 0.0
+ first_move_date = None
+ period = period_obj.browse(cr, uid, period_id, context=context)
+ if lines:
+ for l in lines:
+ if l.date_start >= period.date_start:
+ final_balance += (l.credit - l.debit)
+ else:
+ initial_balance += (l.credit - l.debit)
+ if (not first_move_date) or first_move_date > l.date:
+ first_move_date = l.date
+ final_balance += initial_balance
+
+ partner = partner_obj.browse(cr, uid, partner_id, context=context)
+ vals['partner_doc_type_3'] = partner.doc_type
+ vals['partner_doc_number_4'] = partner.doc_number
+ vals['partner_name_5'] = partner.name
+ vals['operation_date_6'] = first_move_date
+ vals['amount_7'] = final_balance
+ return {'value': vals}
+ else:
+ return False
+
+ def onchange_doc (self, cr, uid, ids, partner_doc_type, partner_doc_number, context=None):
+ res = {}
+
+ if partner_doc_type == '0':
+ if (not partner_doc_number) or len (partner_doc_number) > 15:
+ raise osv.except_osv (_('Value error'),
+ _('Document number should be alfanumeric, not longer than 15 characters! Please check!'))
+ elif partner_doc_type == '1':
+ if (not partner_doc_number) or len (partner_doc_number) != 8 or not partner_doc_number.isdigit():
+ raise osv.except_osv (_('Value error'),
+ _('Libreta electoral or DNI should be numeric, exactly 8 numbers long! Please check!'))
+ elif partner_doc_type == '4':
+ if (not partner_doc_number) or len (partner_doc_number) > 12:
+ raise osv.except_osv (_('Value error'),
+ _('Carnet de extranjeria should be alfanumeric, not longer than 12 characters! Please check!'))
+ elif partner_doc_type == '6':
+ if (not partner_doc_number) or (len (partner_doc_number) < 8 or len(partner_doc_number) > 11) or not partner_doc_number.isdigit():
+ raise osv.except_osv (_('Value error'),
+ _('RUC should be numeric, 8-11 numbers long! Please check!'))
+ elif partner_doc_type == '7':
+ if (not partner_doc_number) or len (partner_doc_number) > 12:
+ raise osv.except_osv (_('Value error'),
+ _('Pasaporte should be alfanumeric, not longer than 12 characters! Please check!'))
+ elif partner_doc_type == 'A':
+ if (not partner_doc_number) or len (partner_doc_number) != 15 or not partner_doc_number.isdigit():
+ raise osv.except_osv (_('Value error'),
+ _('Cedula diplomatica should be numeric, exactly 15 numbers long! Please check!'))
+
+
+class ple_configuration (osv.osv):
+ _inherit = "l10n_pe.ple_configuration"
+
+ def get_report_type (self, cr, uid, context=None):
+ rep_types = super(ple_configuration, self).get_report_type(cr, uid, context=context)
+ rep_types.append (('3_4', '3.4 Accionistas'))
+ return sorted(rep_types, key=lambda e: e[0])
diff --git a/pool/shard009/Python/0087484_setup.py b/pool/shard009/Python/0087484_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e864053cee48851d7d2c1912beefcef652d752d
--- /dev/null
+++ b/pool/shard009/Python/0087484_setup.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+from __future__ import division, print_function, absolute_import
+
+
+def configuration(parent_package='',top_path=None):
+ from numpy.distutils.misc_util import Configuration
+ from numpy.distutils.system_info import get_info
+
+ config = Configuration('lobpcg',parent_package,top_path)
+ config.add_data_dir('tests')
+ config.add_data_dir('benchmarks')
+
+ return config
+
+if __name__ == '__main__':
+ from numpy.distutils.core import setup
+ setup(**configuration(top_path='').todict())
diff --git a/pool/shard009/Python/0087494_Imagen.py b/pool/shard009/Python/0087494_Imagen.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81434dc16a1c57646916a6b972941448dfa13c8
--- /dev/null
+++ b/pool/shard009/Python/0087494_Imagen.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+#-*- coding:utf-8 -*-
+
+
+from opencv.highgui import cvCreateFileCapture, cvQueryFrame, cvSaveImage, cvCreateCameraCapture, cvReleaseCapture
+from opencv.cv import cvCloneImage, CV_GRAY2RGB
+
+
+class Imagen:
+
+ def __init__(self):
+ pass
+
+ def crear_imagen(self, nombre_imagen):
+ captura = cvCreateCameraCapture(0)
+ imagen = cvQueryFrame(captura)
+ cvSaveImage("imagenes/%s.png" %nombre_imagen, imagen)
+ cvReleaseCapture(captura)
+
+
diff --git a/pool/shard009/Python/0087498_module_loader.py b/pool/shard009/Python/0087498_module_loader.py
new file mode 100644
index 0000000000000000000000000000000000000000..78ad3980316274f0bfddc9e6b198977448798d93
--- /dev/null
+++ b/pool/shard009/Python/0087498_module_loader.py
@@ -0,0 +1,110 @@
+#!/usr/bin/python
+
+"""
+Module loader, adapted for cobbler usage
+
+Copyright 2006-2009, Red Hat, Inc
+Adrian Likins
+Michael DeHaan
+
+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
+"""
+
+import distutils.sysconfig
+import os
+import sys
+import glob
+from utils import _
+from cexceptions import *
+import ConfigParser
+
+MODULE_CACHE = {}
+MODULES_BY_CATEGORY = {}
+
+cp = ConfigParser.ConfigParser()
+cp.read("/etc/cobbler/modules.conf")
+
+# A hideous hack to make this work under Ubuntu
+# plib = distutils.sysconfig.get_python_lib() - the OLD Original Script
+plib = '/usr/local/lib/python2.6/dist-packages'
+mod_path="%s/cobbler/modules" % plib
+sys.path.insert(0, mod_path)
+sys.path.insert(1, "%s/cobbler" % plib)
+
+def load_modules(module_path=mod_path, blacklist=None):
+ filenames = glob.glob("%s/*.py" % module_path)
+ filenames = filenames + glob.glob("%s/*.pyc" % module_path)
+ filenames = filenames + glob.glob("%s/*.pyo" % module_path)
+
+ mods = {}
+
+
+ for fn in filenames:
+ basename = os.path.basename(fn)
+ if basename == "__init__.py":
+ continue
+ if basename[-3:] == ".py":
+ modname = basename[:-3]
+ elif basename[-4:] in [".pyc", ".pyo"]:
+ modname = basename[:-4]
+
+
+ try:
+ blip = __import__("modules.%s" % ( modname), globals(), locals(), [modname])
+ if not hasattr(blip, "register"):
+ if not modname.startswith("__init__"):
+ errmsg = _("%(module_path)s/%(modname)s is not a proper module")
+ print errmsg % {'module_path': module_path, 'modname':modname}
+ continue
+ category = blip.register()
+ if category:
+ MODULE_CACHE[modname] = blip
+ if not MODULES_BY_CATEGORY.has_key(category):
+ MODULES_BY_CATEGORY[category] = {}
+ MODULES_BY_CATEGORY[category][modname] = blip
+ except ImportError, e:
+ print e
+ raise
+
+ return (MODULE_CACHE, MODULES_BY_CATEGORY)
+
+def get_module_by_name(name):
+ return MODULE_CACHE.get(name, None)
+
+def get_module_from_file(category,field,fallback_module_name=None,just_name=False):
+
+ try:
+ value = cp.get(category,field)
+ except:
+ if fallback_module_name is not None:
+ value = fallback_module_name
+ else:
+ raise CX(_("Cannot find config file setting for: %s") % field)
+ if just_name:
+ return value
+ rc = MODULE_CACHE.get(value, None)
+ if rc is None:
+ raise CX(_("Failed to load module for %s/%s") % (category,field))
+ return rc
+
+def get_modules_in_category(category):
+ if not MODULES_BY_CATEGORY.has_key(category):
+ return []
+ return MODULES_BY_CATEGORY[category].values()
+
+if __name__ == "__main__":
+ print load_modules(module_path)
+
diff --git a/pool/shard009/Python/0087503_run_tornado2.py b/pool/shard009/Python/0087503_run_tornado2.py
new file mode 100644
index 0000000000000000000000000000000000000000..56b95b0495fb69291248b10e45297c03962a6fdc
--- /dev/null
+++ b/pool/shard009/Python/0087503_run_tornado2.py
@@ -0,0 +1,73 @@
+"""
+Starts a Tornado static file server in a given directory.
+To start the server in the current directory:
+ tserv .
+Then go to http://localhost:8000 to browse the directory.
+Use the --prefix option to add a prefix to the served URL,
+for example to match GitHub Pages' URL scheme:
+ tserv . --prefix=jiffyclub
+Then go to http://localhost:8000/jiffyclub/ to browse.
+Use the --port option to change the port on which the server listens.
+"""
+
+from __future__ import print_function
+
+import os
+import sys
+from argparse import ArgumentParser
+
+import tornado.ioloop
+import tornado.web
+
+
+class Handler(tornado.web.StaticFileHandler):
+ def parse_url_path(self, url_path):
+ if not url_path or url_path.endswith('/'):
+ url_path = url_path + 'index.html'
+ return url_path
+
+
+def mkapp(prefix=''):
+ if prefix:
+ path = '/' + prefix + '/(.*)'
+ else:
+ path = '/(.*)'
+
+ application = tornado.web.Application([
+ (path, Handler, {'path': os.getcwd()}),
+ ], debug=True)
+
+ return application
+
+
+def start_server(prefix='', port=8000):
+ app = mkapp(prefix)
+ app.listen(port)
+ tornado.ioloop.IOLoop.instance().start()
+
+
+def parse_args(args=None):
+ parser = ArgumentParser(
+ description=(
+ 'Start a Tornado server to serve static files out of a '
+ 'given directory and with a given prefix.'))
+ parser.add_argument(
+ '-f', '--prefix', type=str, default='',
+ help='A prefix to add to the location from which pages are served.')
+ parser.add_argument(
+ '-p', '--port', type=int, default=8000,
+ help='Port on which to run server.')
+ parser.add_argument(
+ 'dir', help='Directory from which to serve files.')
+ return parser.parse_args(args)
+
+
+def main(args=None):
+ args = parse_args(args)
+ os.chdir(args.dir)
+ print('Starting server on port {}'.format(args.port))
+ start_server(prefix=args.prefix, port=args.port)
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/pool/shard009/Python/0087504_setup.py b/pool/shard009/Python/0087504_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b59935f1455ca95a64458f58317d5a536ebf49d
--- /dev/null
+++ b/pool/shard009/Python/0087504_setup.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+#
+
+from __future__ import print_function
+import codecs
+
+from setuptools import setup, find_packages
+
+import tunic
+
+
+DESCRIPTION = 'Deployment related Fabric utilities'
+AUTHOR = 'TSH Labs'
+EMAIL = 'projects@tshlabs.org'
+URL = 'https://github.com/tshlabs/tunic'
+LICENSE = 'MIT'
+CLASSIFIERS = [
+ "Development Status :: 5 - Production/Stable",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: POSIX",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2.6",
+ "Programming Language :: Python :: 2.7",
+ "Topic :: System :: Installation/Setup"
+]
+
+
+def get_contents(filename):
+ with codecs.open(filename, 'rb', encoding='utf-8') as handle:
+ return handle.read()
+
+
+REQUIRES = [
+ 'fabric'
+]
+
+README = get_contents('README.rst')
+
+setup(
+ name='tunic',
+ version=tunic.__version__,
+ author=AUTHOR,
+ description=DESCRIPTION,
+ long_description=README,
+ author_email=EMAIL,
+ classifiers=CLASSIFIERS,
+ license=LICENSE,
+ url=URL,
+ zip_safe=True,
+ install_requires=REQUIRES,
+ packages=find_packages())
diff --git a/pool/shard009/Python/0087505_urls.py b/pool/shard009/Python/0087505_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..7468f77646a3bf96a68ab86a14e692a84b53f934
--- /dev/null
+++ b/pool/shard009/Python/0087505_urls.py
@@ -0,0 +1,16 @@
+from django.conf.urls import include, url
+from mybill.views import BillIndexView
+from mybill.views import BillDoView
+from mybill.views import BillCategoryDoView
+from mybill.views import BillAccountDoView
+from mybill.views import BillAccountBookDoView
+from mybill.views import BillTxDoView
+
+urlpatterns = [
+ url(r'accountbook.do', BillAccountBookDoView.as_view()),
+ url(r'account.do', BillAccountDoView.as_view()),
+ url(r'bill.do', BillDoView.as_view()),
+ url(r'category.do', BillCategoryDoView.as_view()),
+ url(r'tx.do', BillTxDoView.as_view()),
+ url(r'$', BillIndexView.as_view()),
+]
diff --git a/pool/shard009/Python/0087507_forms.py b/pool/shard009/Python/0087507_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcbc14c8c81725b78b361863272dff35af266b16
--- /dev/null
+++ b/pool/shard009/Python/0087507_forms.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+
+# WebPyMail - IMAP python/django web mail client
+# Copyright (C) 2008 Helder Guerreiro
+
+## This file is part of WebPyMail.
+##
+## WebPyMail 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.
+##
+## WebPyMail 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 WebPyMail. If not, see .
+
+#
+# Helder Guerreiro
+#
+# $Id$
+#
+
+"""Authentication Forms"""
+
+# Global imports:
+from django import forms
+from django.utils.translation import gettext_lazy as _
+
+# Local Imports:
+from utils.config import server_list
+
+class LoginForm(forms.Form):
+ def __init__(self, *args, **kwargs):
+ super(LoginForm, self).__init__(*args, **kwargs)
+ imap_server_list = [ (s['label'], s['name'] )
+ for s in server_list() ]
+
+ self.fields['host'].choices = imap_server_list
+
+ host = forms.ChoiceField(
+ label = _('Imap Server'),
+ required=False,)
+ username = forms.CharField(
+ label = _('Username'),
+ required=False,
+ max_length=30,)
+ password = forms.CharField(
+ label = _('Password'),
+ required=False,
+ widget=forms.PasswordInput,
+ max_length=40)
+ next = forms.CharField(
+ required=False,
+ widget=forms.HiddenInput,
+ max_length=256)
+
+
+
+
diff --git a/pool/shard009/Python/0087509_test_rule_200.py b/pool/shard009/Python/0087509_test_rule_200.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ef2c74b03dbef404d7014003e495f00baf449e8
--- /dev/null
+++ b/pool/shard009/Python/0087509_test_rule_200.py
@@ -0,0 +1,48 @@
+
+import os
+import unittest
+
+from vsg.rules import loop_statement
+from vsg import vhdlFile
+from vsg.tests import utils
+
+sTestDir = os.path.dirname(__file__)
+
+lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_200_test_input.vhd'))
+
+dIndentMap = utils.read_indent_file()
+
+lExpected = []
+lExpected.append('')
+utils.read_file(os.path.join(sTestDir, 'rule_200_test_input.fixed.vhd'), lExpected)
+
+
+class test_loop_statement_rule(unittest.TestCase):
+
+ def setUp(self):
+ self.oFile = vhdlFile.vhdlFile(lFile)
+ self.assertIsNone(eError)
+ self.oFile.set_indent_map(dIndentMap)
+
+ def test_rule_200(self):
+ oRule = loop_statement.rule_200()
+ self.assertTrue(oRule)
+ self.assertEqual(oRule.name, 'loop_statement')
+ self.assertEqual(oRule.identifier, '200')
+
+ lExpected = [32, 35, 38, 41]
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
+
+ def test_fix_rule_200(self):
+ oRule = loop_statement.rule_200()
+
+ oRule.fix(self.oFile)
+
+ lActual = self.oFile.get_lines()
+
+ self.assertEqual(lExpected, lActual)
+
+ oRule.analyze(self.oFile)
+ self.assertEqual(oRule.violations, [])
diff --git a/pool/shard009/Python/0087510_concurrency.py b/pool/shard009/Python/0087510_concurrency.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2bec1eec84506b739e48ef452e76138a3e6bed2
--- /dev/null
+++ b/pool/shard009/Python/0087510_concurrency.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# File: concurrency.py
+# Author: Yuxin Wu
+
+import multiprocessing, threading
+import tensorflow as tf
+import time
+import six
+from six.moves import queue, range, zip
+
+
+from ..utils.concurrency import DIE
+from ..tfutils.modelutils import describe_model
+from ..utils import logger
+from ..utils.timer import *
+from ..tfutils import *
+
+from .base import *
+
+try:
+ if six.PY2:
+ from tornado.concurrent import Future
+ else:
+ from concurrent.futures import Future
+except ImportError:
+ logger.warn("Cannot import Future in tornado.concurrent. MultiThreadAsyncPredictor won't be available.")
+ __all__ = ['MultiProcessPredictWorker', 'MultiProcessQueuePredictWorker']
+else:
+ __all__ = ['MultiProcessPredictWorker', 'MultiProcessQueuePredictWorker',
+ 'MultiThreadAsyncPredictor']
+
+class MultiProcessPredictWorker(multiprocessing.Process):
+ """ Base class for predict worker that runs offline in multiprocess"""
+ def __init__(self, idx, config):
+ """
+ :param idx: index of the worker. the 0th worker will print log.
+ :param config: a `PredictConfig`
+ """
+ super(MultiProcessPredictWorker, self).__init__()
+ self.idx = idx
+ self.config = config
+
+ def _init_runtime(self):
+ """ Call _init_runtime under different CUDA_VISIBLE_DEVICES, you'll
+ have workers that run on multiGPUs
+ """
+ if self.idx != 0:
+ from tensorpack.models._common import disable_layer_logging
+ disable_layer_logging()
+ self.func = OfflinePredictor(self.config)
+ if self.idx == 0:
+ describe_model()
+
+class MultiProcessQueuePredictWorker(MultiProcessPredictWorker):
+ """ An offline predictor worker that takes input and produces output by queue"""
+ def __init__(self, idx, inqueue, outqueue, config):
+ """
+ :param inqueue: input queue to get data point. elements are (task_id, dp)
+ :param outqueue: output queue put result. elements are (task_id, output)
+ """
+ super(MultiProcessQueuePredictWorker, self).__init__(idx, config)
+ self.inqueue = inqueue
+ self.outqueue = outqueue
+ assert isinstance(self.inqueue, multiprocessing.Queue)
+ assert isinstance(self.outqueue, multiprocessing.Queue)
+
+ def run(self):
+ self._init_runtime()
+ while True:
+ tid, dp = self.inqueue.get()
+ if tid == DIE:
+ self.outqueue.put((DIE, None))
+ return
+ else:
+ self.outqueue.put((tid, self.func(dp)))
+
+
+class PredictorWorkerThread(threading.Thread):
+ def __init__(self, queue, pred_func, id, batch_size=5):
+ super(PredictorWorkerThread, self).__init__()
+ self.queue = queue
+ self.func = pred_func
+ self.daemon = True
+ self.batch_size = batch_size
+ self.id = id
+
+ def run(self):
+ while True:
+ batched, futures = self.fetch_batch()
+ outputs = self.func(batched)
+ #print "Worker {} batched {} Queue {}".format(
+ #self.id, len(futures), self.queue.qsize())
+ # debug, for speed testing
+ #if not hasattr(self, 'xxx'):
+ #self.xxx = outputs = self.func(batched)
+ #else:
+ #outputs = [[self.xxx[0][0]] * len(batched[0]), [self.xxx[1][0]] * len(batched[0])]
+
+ for idx, f in enumerate(futures):
+ f.set_result([k[idx] for k in outputs])
+
+ def fetch_batch(self):
+ """ Fetch a batch of data without waiting"""
+ inp, f = self.queue.get()
+ nr_input_var = len(inp)
+ batched, futures = [[] for _ in range(nr_input_var)], []
+ for k in range(nr_input_var):
+ batched[k].append(inp[k])
+ futures.append(f)
+ cnt = 1
+ while cnt < self.batch_size:
+ try:
+ inp, f = self.queue.get_nowait()
+ for k in range(nr_input_var):
+ batched[k].append(inp[k])
+ futures.append(f)
+ except queue.Empty:
+ break
+ cnt += 1
+ return batched, futures
+
+class MultiThreadAsyncPredictor(AsyncPredictorBase):
+ """
+ An multithread online async predictor which run a list of PredictorBase.
+ It would do an extra batching internally.
+ """
+ def __init__(self, predictors, batch_size=5):
+ """ :param predictors: a list of OnlinePredictor"""
+ assert len(predictors)
+ for k in predictors:
+ #assert isinstance(k, OnlinePredictor), type(k)
+ # TODO use predictors.return_input here
+ assert k.return_input == False
+ self.input_queue = queue.Queue(maxsize=len(predictors)*100)
+ self.threads = [
+ PredictorWorkerThread(
+ self.input_queue, f, id, batch_size=batch_size)
+ for id, f in enumerate(predictors)]
+
+ if six.PY2:
+ # TODO XXX set logging here to avoid affecting TF logging
+ import tornado.options as options
+ options.parse_command_line(['--logging=debug'])
+
+ def start(self):
+ for t in self.threads:
+ t.start()
+
+ def run(self): # temporarily for back-compatibility
+ self.start()
+
+ def put_task(self, dp, callback=None):
+ """
+ dp must be non-batched, i.e. single instance
+ """
+ f = Future()
+ if callback is not None:
+ f.add_done_callback(callback)
+ self.input_queue.put((dp, f))
+ return f
diff --git a/pool/shard009/Python/0087512_settings.py b/pool/shard009/Python/0087512_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..943aad70425e3e509cda13c90802d9daf1e4df39
--- /dev/null
+++ b/pool/shard009/Python/0087512_settings.py
@@ -0,0 +1,169 @@
+import os
+import gconf
+from xdg.DesktopEntry import DesktopEntry
+from fluxgui.exceptions import DirectoryCreationError
+
+
+class Settings(object):
+
+ def __init__(self):
+ self.client = GConfClient("/apps/fluxgui")
+
+ self._color = self.client.get_client_string("colortemp", 3400)
+ self._autostart = self.client.get_client_bool("autostart")
+ self._latitude = self.client.get_client_string("latitude")
+ self._longitude = self.client.get_client_string("longitude")
+ self._zipcode = self.client.get_client_string("zipcode")
+
+ self.has_set_prefs = True
+ if not self._latitude and not self._zipcode:
+ self.has_set_prefs = False
+ self._zipcode = '90210'
+ self.autostart=True
+ if int(self._color) < 2700 or not self._color:
+ # upgrade from previous version
+ temperature_keys = {
+ '0': '2700',
+ '1': '3400',
+ '2': '3800',
+ '3': '4200',
+ '4': '5000',
+ '5': '6500',
+ }
+ if self._color in temperature_keys:
+ self.color = temperature_keys[self._color]
+ else:
+ self.color = '3400'
+
+ def xflux_settings_dict(self):
+ d = {
+ 'color': self.color,
+ 'latitude': self.latitude,
+ 'longitude': self.longitude,
+ 'zipcode': self.zipcode,
+ 'pause_color': '6500'
+ }
+ return d
+
+ def _get_color(self):
+ return str(self._color)
+ def _set_color(self, value):
+ self._color = value
+ self.client.set_client_string("colortemp", value)
+
+ def _get_latitude(self):
+ return str(self._latitude)
+ def _set_latitude(self, value):
+ self._latitude = value
+ self.client.set_client_string("latitude", value)
+
+ def _get_longitude(self):
+ return str(self._longitude)
+ def _set_longitude(self, value):
+ self._longitude = value
+ self.client.set_client_string("longitude", value)
+
+ def _get_zipcode(self):
+ return str(self._zipcode)
+ def _set_zipcode(self, value):
+ self._zipcode = value
+ self.client.set_client_string("zipcode", value)
+
+ def _get_autostart(self):
+ return bool(self._autostart)
+ def _set_autostart(self, value):
+ self._autostart = value
+ self.client.set_client_bool("autostart", self._autostart)
+ if self._autostart:
+ self._create_autostarter()
+ else:
+ self._delete_autostarter()
+
+ color=property(_get_color, _set_color)
+ latitude=property(_get_latitude, _set_latitude)
+ longitude=property(_get_longitude, _set_longitude)
+ zipcode=property(_get_zipcode, _set_zipcode)
+ autostart=property(_get_autostart, _set_autostart)
+
+
+ #autostart code copied from AWN
+ def _get_autostart_file_path(self):
+ autostart_dir = os.path.join(os.environ['HOME'], '.config',
+ 'autostart')
+ return os.path.join(autostart_dir, 'fluxgui.desktop')
+
+ def _create_autostarter(self):
+ autostart_file = self._get_autostart_file_path()
+ autostart_dir = os.path.dirname(autostart_file)
+
+ if not os.path.isdir(autostart_dir):
+ #create autostart dir
+ try:
+ os.mkdir(autostart_dir)
+ except DirectoryCreationError, e:
+ print "Creation of autostart dir failed, please make it yourself: %s" % autostart_dir
+ raise e
+
+ if not os.path.isfile(autostart_file):
+ #create autostart entry
+ starter_item = DesktopEntry(autostart_file)
+ starter_item.set('Name', 'f.lux indicator applet')
+ starter_item.set('Exec', 'fluxgui')
+ starter_item.set('Icon', 'fluxgui')
+ starter_item.set('X-GNOME-Autostart-enabled', 'true')
+ starter_item.write()
+ self.autostart = True
+
+ def _delete_autostarter(self):
+ autostart_file = self._get_autostart_file_path()
+ if os.path.isfile(autostart_file):
+ os.remove(autostart_file)
+ self.autostart = False
+
+class GConfClient(object):
+ """
+ Gets and sets gconf settings.
+ """
+
+ def __init__(self, prefs_key):
+ self.client = gconf.client_get_default()
+ self.prefs_key = prefs_key
+ self.client.add_dir(self.prefs_key, gconf.CLIENT_PRELOAD_NONE)
+
+ def get_client_string(self, property_name, default=""):
+ client_string = self.client.get_string(self.prefs_key+"/"+property_name)
+ if client_string is None:
+ client_string = default
+ return client_string
+
+ def set_client_string(self, property_name, value):
+ self.client.set_string(self.prefs_key + "/" + property_name, str(value))
+
+ def get_client_bool(self, property_name, default=True):
+ try:
+ gconf_type = self.client.get(self.prefs_key + "/"
+ + property_name).type
+ except AttributeError:
+ # key is not set
+ self.set_client_bool(property_name, default)
+ client_bool = default
+ return client_bool
+
+ client_bool = None
+ if gconf_type != gconf.VALUE_BOOL:
+ # previous release used strings for autostart, handle here
+ client_string = self.get_client_string(property_name).lower()
+ if client_string == '1':
+ self.set_client_bool(property_name, True)
+ client_bool = True
+ elif client_string == '0':
+ self.set_client_bool(property_name, False)
+ client_bool = False
+ else:
+ client_bool = self.client.get_bool(self.prefs_key
+ + "/"+property_name)
+ return client_bool
+
+ def set_client_bool(self, property_name, value):
+ self.client.set_bool(self.prefs_key + "/" + property_name, bool(value))
+
diff --git a/pool/shard009/Python/0087516_kernel_methods.py b/pool/shard009/Python/0087516_kernel_methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..791574a1b294527a56db147a7cbec45788923213
--- /dev/null
+++ b/pool/shard009/Python/0087516_kernel_methods.py
@@ -0,0 +1,26 @@
+import numpy as np
+
+def make_exp_kernel(L0):
+ def exp_kernel(x1, x2):
+ x1 = np.expand_dims(x1, 2) # Append a singleton dimension
+ x2 = x2.T
+ return np.exp(-np.mean(np.abs(x1 - x2), axis=1) / L0)
+ return exp_kernel
+
+def make_sq_exp_kernel(L0):
+ def sq_exp_kernel(x1, x2):
+ x1 = np.expand_dims(x1, 2) # Append a singleton dimension
+ x2 = x2.T
+ return np.exp(-np.sum((x1 - x2)**2, axis=1) / (2 * L0**2))
+ return sq_exp_kernel
+
+def weighted_neighbors_loss(train_data, valid_data, kernel):
+ """Computes the negative log prob per data point."""
+ X_train, T_train = train_data
+ X_valid, T_valid = valid_data
+ weight_mat = kernel(X_valid, X_train)
+ label_probs = np.dot(weight_mat, T_train)
+ label_probs = label_probs / np.sum(label_probs, axis=1, keepdims=True)
+ mean_neg_log_prob = - np.mean(np.log(np.sum(label_probs * T_valid,
+ axis=1)), axis=0)
+ return mean_neg_log_prob
diff --git a/pool/shard009/Python/0087519_rbac.py b/pool/shard009/Python/0087519_rbac.py
new file mode 100644
index 0000000000000000000000000000000000000000..b70518e56298f20d1bee9e577a8d26bdb503a6f3
--- /dev/null
+++ b/pool/shard009/Python/0087519_rbac.py
@@ -0,0 +1,62 @@
+# Copyright 2018 Red Hat, Inc.
+# 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.
+
+import abc
+
+from oslo_versionedobjects import fields as obj_fields
+from six import add_metaclass
+from sqlalchemy import and_
+
+from neutron.db import rbac_db_models as models
+from neutron.objects import base
+from neutron.objects import common_types
+
+
+@add_metaclass(abc.ABCMeta)
+class RBACBaseObject(base.NeutronDbObject):
+ # Version 1.0: Initial version
+
+ VERSION = '1.0'
+
+ fields = {
+ 'id': common_types.UUIDField(),
+ 'project_id': obj_fields.StringField(),
+ 'object_id': common_types.UUIDField(),
+ 'target_tenant': obj_fields.StringField(),
+ 'action': obj_fields.StringField(),
+ }
+
+ fields_no_update = ['id', 'project_id', 'object_id']
+
+ @classmethod
+ def get_projects(cls, context, object_id=None, action=None,
+ target_tenant=None):
+ clauses = []
+ if object_id:
+ clauses.append(models.NetworkRBAC.object_id == object_id)
+ if action:
+ clauses.append(models.NetworkRBAC.action == action)
+ if target_tenant:
+ clauses.append(models.NetworkRBAC.target_tenant ==
+ target_tenant)
+ query = context.session.query(models.NetworkRBAC.target_tenant)
+ if clauses:
+ query = query.filter(and_(*clauses))
+ return [data[0] for data in query]
+
+ @classmethod
+ def get_type_class_map(cls):
+ return {klass.db_model.object_type: klass
+ for klass in cls.__subclasses__()}
diff --git a/pool/shard009/Python/0087520_arLibIssue.py b/pool/shard009/Python/0087520_arLibIssue.py
new file mode 100644
index 0000000000000000000000000000000000000000..8937ade47f82d5d486f96ebb37852a73e14a5de1
--- /dev/null
+++ b/pool/shard009/Python/0087520_arLibIssue.py
@@ -0,0 +1,63 @@
+"""
+These tests check a problem with the lib/ar setting.
+"""
+
+#
+# Copyright (c) 2001 - 2016 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, 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.
+#
+
+__revision__ = "test/D/HSTeoh/Common/arLibIssue.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
+
+import TestSCons
+
+from SCons.Environment import Base
+
+from os.path import abspath, dirname
+
+import sys
+sys.path.insert(1, abspath(dirname(__file__) + '/../../Support'))
+
+from executablesSearch import isExecutableOfToolAvailable
+
+def testForTool(tool):
+
+ test = TestSCons.TestSCons()
+
+ if not isExecutableOfToolAvailable(test, tool) :
+ test.skip_test("Required executable for tool '{0}' not found, skipping test.\n".format(tool))
+
+ test.dir_fixture('ArLibIssue')
+ test.write('SConstruct', open('SConstruct_template', 'r').read().format('tools=["{0}", "ar"]'.format(tool)))
+
+ test.run()
+
+ test.must_exist(test.workpath('a.o'))
+ test.must_exist(test.workpath('b.o'))
+ test.must_exist(test.workpath('mylib.a' if Base()['PLATFORM'] == 'win32' else 'libmylib.a'))
+
+ test.pass_test()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/pool/shard009/Python/0087530_test_products.py b/pool/shard009/Python/0087530_test_products.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ffcc5f371a9ad5313bf410e4d4d3de9610ccd1
--- /dev/null
+++ b/pool/shard009/Python/0087530_test_products.py
@@ -0,0 +1,115 @@
+# 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
+from collections import defaultdict
+from contextlib import contextmanager
+
+from pants.goal.products import MultipleRootedProducts, Products
+from pants.util.contextutil import temporary_dir
+from pants.util.dirutil import safe_open
+from pants_test.base_test import BaseTest
+
+
+class ProductsTest(BaseTest):
+ def setUp(self):
+ super(ProductsTest, self).setUp()
+ self.products = Products()
+
+ def test_require(self):
+ self.products.require('foo')
+
+ self.assertTrue(self.products.isrequired('foo'))
+ self.assertFalse(self.products.isrequired('bar'))
+
+ # require should not cross-contaminate require_data
+ self.assertFalse(self.products.is_required_data('foo'))
+ self.assertFalse(self.products.is_required_data('bar'))
+
+ def test_get(self):
+ foo_product_mapping1 = self.products.get('foo')
+ foo_product_mapping2 = self.products.get('foo')
+
+ self.assertIsInstance(foo_product_mapping1, Products.ProductMapping)
+ self.assertIs(foo_product_mapping1, foo_product_mapping2)
+
+ def test_get_does_not_require(self):
+ self.assertFalse(self.products.isrequired('foo'))
+ self.products.get('foo')
+ self.assertFalse(self.products.isrequired('foo'))
+ self.products.require('foo')
+ self.assertTrue(self.products.isrequired('foo'))
+
+ def test_require_data(self):
+ self.products.require_data('foo')
+
+ self.assertTrue(self.products.is_required_data('foo'))
+ self.assertFalse(self.products.is_required_data('bar'))
+
+ # require_data should not cross-contaminate require
+ self.assertFalse(self.products.isrequired('foo'))
+ self.assertFalse(self.products.isrequired('bar'))
+
+ def test_get_data(self):
+ self.assertIsNone(self.products.get_data('foo'))
+
+ data1 = self.products.get_data('foo', dict)
+ data2 = self.products.get_data('foo', dict)
+
+ self.assertIsInstance(data1, dict)
+ self.assertIs(data1, data2)
+
+ def test_get_data_does_not_require_data(self):
+ self.assertFalse(self.products.is_required_data('foo'))
+ self.products.get_data('foo')
+ self.assertFalse(self.products.is_required_data('foo'))
+ self.products.require_data('foo')
+ self.assertTrue(self.products.is_required_data('foo'))
+
+ def test_empty_products(self):
+ foo_product_mapping = self.products.get('foo')
+ self.assertFalse(foo_product_mapping)
+
+ @contextmanager
+ def add_products(self, context_products, product_type, target, *products):
+ product_mapping = context_products.get(product_type)
+ with temporary_dir() as outdir:
+ def create_product(product):
+ with safe_open(os.path.join(outdir, product), mode='w') as fp:
+ fp.write(product)
+ return product
+ product_mapping.add(target, outdir, map(create_product, products))
+ yield temporary_dir
+
+ def test_non_empty_products(self):
+ target = self.make_target('c')
+ with self.add_products(self.products, 'foo', target, 'a.class'):
+ foo_product_mapping = self.products.get('foo')
+ self.assertTrue(foo_product_mapping)
+
+ def test_empty_data(self):
+ foo_product_mapping = self.products.get_data('foo')
+ self.assertFalse(foo_product_mapping)
+
+ @contextmanager
+ def add_data(self, context_products, data_type, target, *products):
+ make_products = lambda: defaultdict(MultipleRootedProducts)
+ data_by_target = context_products.get_data(data_type, make_products)
+ with temporary_dir() as outdir:
+ def create_product(product):
+ abspath = os.path.join(outdir, product)
+ with safe_open(abspath, mode='w') as fp:
+ fp.write(product)
+ return abspath
+ data_by_target[target].add_abs_paths(outdir, map(create_product, products))
+ yield temporary_dir
+
+ def test_non_empty_data(self):
+ target = self.make_target('c')
+ with self.add_data(self.products, 'foo', target, 'a.class'):
+ foo_product_mapping = self.products.get_data('foo')
+ self.assertTrue(foo_product_mapping)
diff --git a/pool/shard009/Python/0087531_urls.py b/pool/shard009/Python/0087531_urls.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4ec512258f95d9d2a9120f61395ec3e29758a4c
--- /dev/null
+++ b/pool/shard009/Python/0087531_urls.py
@@ -0,0 +1,31 @@
+from __future__ import absolute_import, unicode_literals
+
+from django.conf import settings
+from django.conf.urls import include, url
+from django.contrib import admin
+
+from search import views as search_views
+from wagtail.wagtailadmin import urls as wagtailadmin_urls
+from wagtail.wagtailcore import urls as wagtail_urls
+from wagtail.wagtaildocs import urls as wagtaildocs_urls
+
+urlpatterns = [
+ url(r'^django-admin/', include(admin.site.urls)),
+
+ url(r'^admin/', include(wagtailadmin_urls)),
+ url(r'^documents/', include(wagtaildocs_urls)),
+ url(r'^search/$', search_views.search, name='search'),
+
+ url(r'^blog/', include('blog.urls', namespace="blog")),
+
+ url(r'', include(wagtail_urls)),
+]
+
+
+if settings.DEBUG:
+ from django.conf.urls.static import static
+ from django.contrib.staticfiles.urls import staticfiles_urlpatterns
+
+ # Serve static and media files from development server
+ urlpatterns += staticfiles_urlpatterns()
+ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
diff --git a/pool/shard009/Python/0087536_bootstrapped_goodies_tags.py b/pool/shard009/Python/0087536_bootstrapped_goodies_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..c67f206924a47f669c616856c6a64b5ba1475ba4
--- /dev/null
+++ b/pool/shard009/Python/0087536_bootstrapped_goodies_tags.py
@@ -0,0 +1,119 @@
+from importlib import import_module
+
+from django import template
+from django.conf import settings
+from django.template.loader import render_to_string
+
+
+register = template.Library()
+
+
+CUSTOM_FIELD_RENDERER = getattr(settings, 'DAB_FIELD_RENDERER', False)
+
+
+@register.simple_tag(takes_context=True)
+def render_with_template_if_exist(context, template, fallback):
+ text = fallback
+ try:
+ text = render_to_string(template, context)
+ except:
+ pass
+ return text
+
+@register.simple_tag(takes_context=True)
+def language_selector(context):
+ """ displays a language selector dropdown in the admin, based on Django "LANGUAGES" context.
+ requires:
+ * USE_I18N = True / settings.py
+ * LANGUAGES specified / settings.py (otherwise all Django locales will be displayed)
+ * "set_language" url configured (see https://docs.djangoproject.com/en/dev/topics/i18n/translation/#the-set-language-redirect-view)
+ """
+ output = ""
+ i18 = getattr(settings, 'USE_I18N', False)
+ if i18:
+ template = "admin/language_selector.html"
+ context['i18n_is_set'] = True
+ try:
+ output = render_to_string(template, context)
+ except:
+ pass
+ return output
+
+
+@register.filter(name='column_width')
+def column_width(value):
+ try:
+ return 12 // len(list(value))
+ except ZeroDivisionError:
+ return 12
+
+
+@register.filter(name='form_fieldset_column_width')
+def form_fieldset_column_width(form):
+ def max_line(fieldset):
+ return max([len(list(line)) for line in fieldset])
+
+ try:
+ width = max([max_line(fieldset) for fieldset in form])
+ return 12 // width
+ except ValueError:
+ return 12
+
+
+@register.filter(name='fieldset_column_width')
+def fieldset_column_width(fieldset):
+ try:
+ width = max([len(list(line)) for line in fieldset])
+ return 12 // width
+ except ValueError:
+ return 12
+
+
+@register.simple_tag(takes_context=True)
+def render_app_name(context, app, template="/admin_app_name.html"):
+ """ Render the application name using the default template name. If it cannot find a
+ template matching the given path, fallback to the application name.
+ """
+ try:
+ template = app['app_label'] + template
+ text = render_to_string(template, context)
+ except:
+ text = app['name']
+ return text
+
+
+@register.simple_tag(takes_context=True)
+def render_app_label(context, app, fallback=""):
+ """ Render the application label.
+ """
+ try:
+ text = app['app_label']
+ except KeyError:
+ text = fallback
+ except TypeError:
+ text = app
+ return text
+
+
+@register.simple_tag(takes_context=True)
+def render_app_description(context, app, fallback="", template="/admin_app_description.html"):
+ """ Render the application description using the default template name. If it cannot find a
+ template matching the given path, fallback to the fallback argument.
+ """
+ try:
+ template = app['app_label'] + template
+ text = render_to_string(template, context)
+ except:
+ text = fallback
+ return text
+
+
+@register.simple_tag(takes_context=True, name="dab_field_rendering")
+def custom_field_rendering(context, field, *args, **kwargs):
+ """ Wrapper for rendering the field via an external renderer """
+ if CUSTOM_FIELD_RENDERER:
+ mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1)
+ field_renderer = getattr(import_module(mod), cls)
+ if field_renderer:
+ return field_renderer(field, **kwargs).render()
+ return field
diff --git a/pool/shard009/Python/0087539_optimizer_v2_test.py b/pool/shard009/Python/0087539_optimizer_v2_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..e388061b17a9b92dedbbf9839049b13c8575a22c
--- /dev/null
+++ b/pool/shard009/Python/0087539_optimizer_v2_test.py
@@ -0,0 +1,71 @@
+# Copyright 2018 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 running legacy optimizer code with DistributionStrategy."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+from absl.testing import parameterized
+import numpy
+
+from tensorflow.contrib.distribute.python import combinations
+from tensorflow.contrib.distribute.python.single_loss_example import minimize_loss_example
+from tensorflow.python.eager import context
+from tensorflow.python.eager import test
+from tensorflow.python.ops import control_flow_ops
+from tensorflow.python.ops import variables
+
+
+class MinimizeLossOptimizerV2Test(test.TestCase, parameterized.TestCase):
+
+ @combinations.generate(
+ combinations.times(
+ combinations.distributions_and_v2_optimizers(),
+ combinations.combine(mode=["graph"], use_callable_loss=[True, False])
+ + combinations.combine(mode=["eager"], use_callable_loss=[True])))
+ def testTrainNetwork(self, distribution, optimizer_fn,
+ use_callable_loss=True):
+ with distribution.scope():
+ model_fn, dataset_fn, layer = minimize_loss_example(
+ optimizer_fn, use_bias=True, use_callable_loss=use_callable_loss)
+ iterator = distribution.make_input_fn_iterator(lambda _: dataset_fn())
+
+ def run_step():
+ return control_flow_ops.group(
+ distribution.unwrap(
+ distribution.extended.call_for_each_replica(
+ model_fn, args=(iterator.get_next(),))))
+
+ if not context.executing_eagerly():
+ with self.cached_session() as sess:
+ sess.run(iterator.initialize())
+ run_step = sess.make_callable(run_step())
+ self.evaluate(variables.global_variables_initializer())
+
+ weights, biases = [], []
+ for _ in range(10):
+ run_step()
+
+ weights.append(self.evaluate(layer.kernel))
+ biases.append(self.evaluate(layer.bias))
+
+ error = abs(numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1)
+ is_not_increasing = all(y <= x for x, y in zip(error, error[1:]))
+ self.assertTrue(is_not_increasing)
+
+
+if __name__ == "__main__":
+ test.main()
diff --git a/pool/shard009/Python/0087545_raw_chem.py b/pool/shard009/Python/0087545_raw_chem.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf8d66e35805c76cecb8cba9f938221103faeed3
--- /dev/null
+++ b/pool/shard009/Python/0087545_raw_chem.py
@@ -0,0 +1,157 @@
+from django.db import models
+from model_utils import FieldTracker
+from model_utils.managers import InheritanceManager
+
+from .common_info import CommonInfo
+
+
+class RawChem(CommonInfo):
+ """
+ The RawChem model is the base class for most of the object types that
+ occupy the position beneath ExtractedText in the object hierarchy. When
+ a single document has multiple chemicals associated with it, whether as
+ List Presence items from a CPCat document or as Composition items from
+ an ingredient list, the child objects inherit from the RawChem base class.
+ A curated record is one with a foreign key in the DSSToxLookup field.
+ """
+
+ CHEM_DETECTED_CHOICES = (("1", "Yes"), ("0", "No"))
+
+ extracted_text = models.ForeignKey(
+ "ExtractedText",
+ related_name="rawchem",
+ on_delete=models.CASCADE,
+ null=False,
+ blank=False,
+ )
+ raw_cas = models.CharField(
+ "Raw CAS",
+ max_length=100,
+ blank=True,
+ help_text="Chemical abstract service registry number (CASRN) as reported in original study",
+ )
+ raw_chem_name = models.CharField(
+ "Raw chemical name",
+ max_length=1300,
+ blank=True,
+ help_text="Chemical name as reported in original study",
+ )
+
+ rid = models.CharField(max_length=50, blank=True, help_text="RID")
+ dsstox = models.ForeignKey(
+ "DSSToxLookup",
+ related_name="curated_chemical",
+ on_delete=models.PROTECT,
+ null=True,
+ blank=True,
+ )
+ component = models.CharField(
+ "Component",
+ max_length=200,
+ blank=True,
+ help_text="The product component for products with multiple parts or items in a set.",
+ )
+ # Ideally the chem_detected_flag would be a nullable boolean field. However,
+ # bulk_update() seems to have a bug related to nullable booleans
+ chem_detected_flag = models.CharField(
+ "Chemical Detected",
+ max_length=1,
+ choices=CHEM_DETECTED_CHOICES,
+ null=True,
+ blank=True,
+ help_text="Flag indicating whether a chemical was ever detected in the studied medium",
+ )
+ provisional = models.BooleanField(
+ default=False,
+ help_text="""When a RawChem record has a raw_chem_name and raw_cas combination that
+ has already been curated to a certain DSSToxLookup record (and to only one),
+ Factotum will automatically populate the DSSToxLookup foreign key. The provisional
+ field indicates that this assignment was automatically performed without a curator
+ involved.""",
+ )
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["extracted_text", "dsstox", "component"]),
+ # Manually added indexes in dashboard 0190. Django does not support MySQL prefix index
+ # https://dev.mysql.com/doc/refman/8.0/en/column-indexes.html#column-indexes-prefix
+ #
+ # models.Index(fields=["raw_chem_name"], name="dashboard_rawchem_20char_rawchemname_index"),
+ # models.Index(fields=["raw_cas"], name="dashboard_rawchem_20char_rawcas_index"),
+ ]
+
+ objects = InheritanceManager()
+
+ tracker = FieldTracker()
+
+ class JSONAPIMeta:
+ resource_name = "chemicalInstance"
+
+ def __str__(self):
+ return str(self.raw_chem_name) if self.raw_chem_name else ""
+
+ @property
+ def sid(self):
+ """If there is no DSSToxLookup record via the
+ curated_chemical relationship, it evaluates to boolean False """
+ try:
+ return self.curated_chemical.sid
+ except AttributeError:
+ return False
+
+ @property
+ def data_group_id(self):
+ return str(self.extracted_text.data_document.data_group_id)
+
+ def clean(self):
+ def whitespace(fld):
+ if fld:
+ return fld.startswith(" ") or fld.endswith(" ")
+ else:
+ return False
+
+ if whitespace(self.raw_cas):
+ self.raw_cas = self.raw_cas.strip()
+ if whitespace(self.raw_chem_name):
+ self.raw_chem_name = self.raw_chem_name.strip()
+
+ @property
+ def true_cas(self):
+ return self.dsstox.true_cas if self.dsstox else None
+
+ @property
+ def true_chemname(self):
+ return self.dsstox.true_chemname if self.dsstox else None
+
+ @property
+ def rendered_chemname(self):
+ return self.dsstox.true_chemname if self.dsstox else self.raw_chem_name
+
+ @property
+ def rendered_cas(self):
+ return self.dsstox.true_cas if self.dsstox else self.raw_cas
+
+ @classmethod
+ def auditlog_fields(cls):
+ """Lists the fields to be included in the audit log triggers
+
+ Returns:
+ list -- a list of field names
+ """
+ return [
+ "raw_cas",
+ "raw_chem_name",
+ "rid",
+ "component",
+ "chem_detected_flag",
+ "dsstox_id",
+ ]
+
+ @classmethod
+ def detail_fields(cls):
+ """Lists the fields to be displayed on a detail form
+
+ Returns:
+ list -- a list of field names
+ """
+ return ["extracted_text", "raw_chem_name", "raw_cas", "chem_detected_flag"]
diff --git a/pool/shard009/Python/0087546_ottosoles.py b/pool/shard009/Python/0087546_ottosoles.py
new file mode 100644
index 0000000000000000000000000000000000000000..23141a50818f465b9ea03d9ce963b598daa102d3
--- /dev/null
+++ b/pool/shard009/Python/0087546_ottosoles.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# Copyright (C) 2013-2018 Florian Festi
+#
+# 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 boxes import *
+
+class OttoSoles(Boxes):
+ """Foam soles for the OttO bot"""
+
+ ui_group = "Misc"
+
+ def __init__(self):
+ Boxes.__init__(self)
+
+ self.buildArgParser(x=56., y=36.)
+ self.argparser.add_argument(
+ "--width", action="store", type=float, default=4.,
+ help="width of sole stripe")
+ self.argparser.add_argument(
+ "--chamfer", action="store", type=float, default=5.,
+ help="chamfer at the corners")
+ self.argparser.add_argument(
+ "--num", action="store", type=int, default=2,
+ help="number of soles")
+
+
+ def render(self):
+ x, y = self.x, self.y
+ c = self.chamfer
+ c2 = c * 2**0.5
+ w = min(self.width, c2 / 2. / math.tan(math.radians(22.5)))
+ w = self.width
+ w2 = w * 2**0.5 - c2 / 2
+ d = w * math.tan(math.radians(22.5))
+
+
+ self.edges["d"].settings.setValues(w, size=0.4, depth=0.3,
+ radius=0.05)
+
+ self.moveTo(0, y, -90)
+
+ for i in range(self.num*2):
+ if c2 >= 2 * d:
+ self.polyline((c2, 1), 45, (y-2*c, 1), 45, c2/2., 90)
+ self.edges["d"](w)
+ self.polyline(0, 90, c2/2-d, -45, (y-2*c-2*d, 1), -45,
+ (c2-2*d, 1), -45,
+ (x-2*c-2*d, 1), -45, c2/2-d, 90)
+ self.edges["D"](w)
+ self.polyline(0, 90, c2/2., 45, (x-2*c, 1), 45)
+ self.moveTo(0, w + c2/2. + 2*2**0.5*self.burn)
+ else:
+ self.polyline((c2, 1), 45, (y-2*c, 1), 45, c2/2., 90)
+ self.edges["d"](w2)
+ self.polyline(0, 45, (y-2*w, 1), -90, (x-2*w, 1), 45)
+ self.edges["D"](w2)
+ self.polyline(0, 90, c2/2., 45, (x-2*c, 3), 45)
+ self.moveTo(0, w * 2**0.5 + 2*2**0.5*self.burn)
diff --git a/pool/shard009/Python/0087547_pubsub_matcher.py b/pool/shard009/Python/0087547_pubsub_matcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..04bca0a8e4453f7cfbe15dd39505f57a91fa5803
--- /dev/null
+++ b/pool/shard009/Python/0087547_pubsub_matcher.py
@@ -0,0 +1,182 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+"""PubSub verifier used for end-to-end test."""
+
+# pytype: skip-file
+
+from __future__ import absolute_import
+
+import logging
+import time
+from collections import Counter
+
+from hamcrest.core.base_matcher import BaseMatcher
+
+from apache_beam.io.gcp.pubsub import PubsubMessage
+
+__all__ = ['PubSubMessageMatcher']
+
+# Protect against environments where pubsub library is not available.
+try:
+ from google.cloud import pubsub
+except ImportError:
+ pubsub = None
+
+DEFAULT_TIMEOUT = 5 * 60
+DEFAULT_SLEEP_TIME = 1
+DEFAULT_MAX_MESSAGES_IN_ONE_PULL = 50
+DEFAULT_PULL_TIMEOUT = 30.0
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class PubSubMessageMatcher(BaseMatcher):
+ """Matcher that verifies messages from given subscription.
+
+ This matcher can block the test and keep pulling messages from given
+ subscription until all expected messages are shown or timeout.
+ """
+ def __init__(
+ self,
+ project,
+ sub_name,
+ expected_msg=None,
+ expected_msg_len=None,
+ timeout=DEFAULT_TIMEOUT,
+ with_attributes=False,
+ strip_attributes=None,
+ sleep_time=DEFAULT_SLEEP_TIME,
+ max_messages_in_one_pull=DEFAULT_MAX_MESSAGES_IN_ONE_PULL,
+ pull_timeout=DEFAULT_PULL_TIMEOUT):
+ """Initialize PubSubMessageMatcher object.
+
+ Args:
+ project: A name string of project.
+ sub_name: A name string of subscription which is attached to output.
+ expected_msg: A string list that contains expected message data pulled
+ from the subscription. See also: with_attributes.
+ expected_msg_len: Number of expected messages pulled from the
+ subscription.
+ timeout: Timeout in seconds to wait for all expected messages appears.
+ with_attributes: If True, will match against both message data and
+ attributes. If True, expected_msg should be a list of ``PubsubMessage``
+ objects. Otherwise, it should be a list of ``bytes``.
+ strip_attributes: List of strings. If with_attributes==True, strip the
+ attributes keyed by these values from incoming messages.
+ If a key is missing, will add an attribute with an error message as
+ value to prevent a successful match.
+ sleep_time: Time in seconds between which the pulls from pubsub are done.
+ max_messages_in_one_pull: Maximum number of messages pulled from pubsub
+ at once.
+ pull_timeout: Time in seconds after which the pull from pubsub is repeated
+ """
+ if pubsub is None:
+ raise ImportError('PubSub dependencies are not installed.')
+ if not project:
+ raise ValueError('Invalid project %s.' % project)
+ if not sub_name:
+ raise ValueError('Invalid subscription %s.' % sub_name)
+ if not expected_msg_len and not expected_msg:
+ raise ValueError(
+ 'Required expected_msg: {} or expected_msg_len: {}.'.format(
+ expected_msg, expected_msg_len))
+ if expected_msg and not isinstance(expected_msg, list):
+ raise ValueError('Invalid expected messages %s.' % expected_msg)
+ if expected_msg_len and not isinstance(expected_msg_len, int):
+ raise ValueError('Invalid expected messages %s.' % expected_msg_len)
+
+ self.project = project
+ self.sub_name = sub_name
+ self.expected_msg = expected_msg
+ self.expected_msg_len = expected_msg_len or len(self.expected_msg)
+ self.timeout = timeout
+ self.messages = None
+ self.with_attributes = with_attributes
+ self.strip_attributes = strip_attributes
+ self.sleep_time = sleep_time
+ self.max_messages_in_one_pull = max_messages_in_one_pull
+ self.pull_timeout = pull_timeout
+
+ def _matches(self, _):
+ if self.messages is None:
+ self.messages = self._wait_for_messages(
+ self.expected_msg_len, self.timeout)
+ if self.expected_msg:
+ return Counter(self.messages) == Counter(self.expected_msg)
+ else:
+ return len(self.messages) == self.expected_msg_len
+
+ def _wait_for_messages(self, expected_num, timeout):
+ """Wait for messages from given subscription."""
+ total_messages = []
+
+ sub_client = pubsub.SubscriberClient()
+ start_time = time.time()
+ while time.time() - start_time <= timeout:
+ response = sub_client.pull(
+ self.sub_name,
+ max_messages=self.max_messages_in_one_pull,
+ return_immediately=True,
+ timeout=self.pull_timeout)
+ for rm in response.received_messages:
+ msg = PubsubMessage._from_message(rm.message)
+ if not self.with_attributes:
+ total_messages.append(msg.data)
+ continue
+
+ if self.strip_attributes:
+ for attr in self.strip_attributes:
+ try:
+ del msg.attributes[attr]
+ except KeyError:
+ msg.attributes[attr] = (
+ 'PubSubMessageMatcher error: '
+ 'expected attribute not found.')
+ total_messages.append(msg)
+
+ ack_ids = [rm.ack_id for rm in response.received_messages]
+ if ack_ids:
+ sub_client.acknowledge(self.sub_name, ack_ids)
+ if len(total_messages) >= expected_num:
+ break
+ time.sleep(self.sleep_time)
+
+ if time.time() - start_time > timeout:
+ _LOGGER.error(
+ 'Timeout after %d sec. Received %d messages from %s.',
+ timeout,
+ len(total_messages),
+ self.sub_name)
+ return total_messages
+
+ def describe_to(self, description):
+ description.append_text('Expected %d messages.' % self.expected_msg_len)
+
+ def describe_mismatch(self, _, mismatch_description):
+ c_expected = Counter(self.expected_msg)
+ c_actual = Counter(self.messages)
+ mismatch_description.append_text("Got %d messages. " % (len(self.messages)))
+ if self.expected_msg:
+ mismatch_description.append_text(
+ "Diffs (item, count):\n"
+ " Expected but not in actual: %s\n"
+ " Unexpected: %s" % ((c_expected - c_actual).items(),
+ (c_actual - c_expected).items()))
+ if self.with_attributes and self.strip_attributes:
+ mismatch_description.append_text(
+ '\n Stripped attributes: %r' % self.strip_attributes)
diff --git a/pool/shard009/Python/0087550_test_psycopg2_dbapi20.py b/pool/shard009/Python/0087550_test_psycopg2_dbapi20.py
new file mode 100644
index 0000000000000000000000000000000000000000..e967715305b2fd56915b61ea3b25bf11706b42e7
--- /dev/null
+++ b/pool/shard009/Python/0087550_test_psycopg2_dbapi20.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+
+# test_psycopg2_dbapi20.py - DB API conformance test for psycopg2
+#
+# Copyright (C) 2006-2011 Federico Di Gregorio
+#
+# psycopg2 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.
+#
+# In addition, as a special exception, the copyright holders give
+# permission to link this program with the OpenSSL library (or with
+# modified versions of OpenSSL that use the same license as OpenSSL),
+# and distribute linked combinations including the two.
+#
+# You must obey the GNU Lesser General Public License in all respects for
+# all of the code used other than OpenSSL.
+#
+# psycopg2 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.
+
+from . import dbapi20
+from . import dbapi20_tpc
+from .testutils import skip_if_tpc_disabled
+from .testutils import unittest, decorate_all_tests
+import psycopg2
+
+from .testconfig import dsn
+
+
+class Psycopg2Tests(dbapi20.DatabaseAPI20Test):
+ driver = psycopg2
+ connect_args = ()
+ connect_kw_args = {'dsn': dsn}
+
+ lower_func = 'lower' # For stored procedure test
+
+ def test_callproc(self):
+ # Until DBAPI 2.0 compliance, callproc should return None or it's just
+ # misleading. Therefore, we will skip the return value test for
+ # callproc and only perform the fetch test.
+ #
+ # For what it's worth, the DBAPI2.0 test_callproc doesn't actually
+ # test for DBAPI2.0 compliance! It doesn't check for modified OUT and
+ # IN/OUT parameters in the return values!
+ con = self._connect()
+ try:
+ cur = con.cursor()
+ if self.lower_func and hasattr(cur,'callproc'):
+ cur.callproc(self.lower_func,('FOO',))
+ r = cur.fetchall()
+ self.assertEqual(len(r),1,'callproc produced no result set')
+ self.assertEqual(len(r[0]),1,
+ 'callproc produced invalid result set'
+ )
+ self.assertEqual(r[0][0],'foo',
+ 'callproc produced invalid results'
+ )
+ finally:
+ con.close()
+
+ def test_setoutputsize(self):
+ # psycopg2's setoutputsize() is a no-op
+ pass
+
+ def test_nextset(self):
+ # psycopg2 does not implement nextset()
+ pass
+
+
+class Psycopg2TPCTests(dbapi20_tpc.TwoPhaseCommitTests, unittest.TestCase):
+ driver = psycopg2
+
+ def connect(self):
+ return psycopg2.connect(dsn=dsn)
+
+decorate_all_tests(Psycopg2TPCTests, skip_if_tpc_disabled)
+
+
+def test_suite():
+ return unittest.TestLoader().loadTestsFromName(__name__)
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard009/Python/0087552_stats.py b/pool/shard009/Python/0087552_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffb36bd278e175e634bc5fee8a5c5db38d55096e
--- /dev/null
+++ b/pool/shard009/Python/0087552_stats.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2018 Nicholas Domenichini ndomenic@uoguelph.ca
+#
+# Permission to use, copy, modify, and/or distribute this software for any
+# purpose with or without fee is hereby granted, provided that the above
+# copyright notice and this permission notice appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+# PERFORMANCE OF THIS SOFTWARE.
+
+import sys, getopt, os
+import json
+import string
+
+# Include common helper files.
+# Note: IFS runs this files from the main IFS/ifs folder.
+helperFunctionPath = "./tools/commonTools/"
+sys.path.append( os.path.abspath(helperFunctionPath) )
+from helperFunctions import *
+
+def decorateData(allResults, options):
+ json_string = '{"feedbackStats": ['
+
+ for results in allResults:
+ for result in results:
+ json_string += ('{'
+ + '"toolName": "c_stats",'
+ + '"type": "stat",'
+ + '"level": "basic",'
+ + '"category": "spelling",'
+ + '"filename": "' + result[0] + '",'
+ + '"statName": "' + result[1] + '",'
+ + '"statValue": "' + str(result[2]) + '",'
+ + '"name": "' + result[3] + '"'
+ + '},')
+
+ json_string = json_string[:-1]
+ json_string += ']}'
+
+ json_string = json.loads(json_string)
+ json_string = json.dumps(json_string, indent=4, sort_keys=True)
+
+ return json_string
+
+def parse (dir, tool):
+ ret = []
+
+ allFiles = os.listdir(dir)
+ for file in allFiles:
+ if file != 'stderr.txt' and file != 'stdout.txt':
+ title, val, name = tool(dir + '/' + file)
+ data = (file, title, val, name)
+ ret.append(data)
+
+ return ret
+
+def countLines(path):
+ title = 'Lines of Code'
+ val = 0
+ name = 'chCount'
+
+ with open(path) as file:
+ for i, j in enumerate(file):
+ pass
+ val = i + 1
+
+ return title, val, name
+
+def countComments(path):
+ title = 'Number of Comments'
+ val = 0
+ name = 'wordCount'
+ flag = False
+
+ with open(path) as file:
+ for line in file:
+ for i in range(len(line)):
+ if (flag == False and line[i] == '/' and line[i+1] == '*'):
+ flag = True
+ val += 1
+ if (flag == True and line[i] == '*' and line[i+1] == '/'):
+ flag = False
+ if (flag == False and line[i] == '/' and line[i+1] == '/'):
+ val += 1
+
+ return title, val, name
+
+def main (argv):
+ results = []
+ options = {
+ 'ifs': True,
+ 'tool':'stats',
+ 'dir':'',
+ 'totalLines': False,
+ 'totalComments': False,
+ }
+
+ opts, args = getopt.getopt(argv,'d:t:c:h',['directory=','totalLines=','totalComments=','help'])
+
+ for opt, arg in opts:
+ if opt in ('directory', '-d'):
+ options['dir'] = arg
+ if not (os.path.isdir(options['dir'])):
+ sys.stderr.write( 'Error. Directory ' + options['dir'] + ' does not exist.\n' )
+ sys.exit()
+ elif opt in ('totalLines', '-t'):
+ options['totalLines'] = True
+ elif opt in ('totalComments', '-c'):
+ options['totalComments'] = True
+ else:
+ print('Usage: Parses specific GCC/CPPCheck output files types to JSON format')
+ print('stats.py [-t totalLines] -d InputDirectory')
+ sys.exit()
+
+ if options['dir'] == '':
+ sys.stderr.write("No directory was provided.\n")
+ return 0
+
+ result = []
+ try:
+ if (options['totalLines']):
+ result = parse(options['dir'], countLines)
+ results.append(result)
+
+ if (options['totalComments']):
+ result = parse(options['dir'], countComments)
+ results.append(result)
+
+ displayResultToIFS(options, decorateData, options['dir'],"/feedback_stats_unzipped", results)
+
+ except:
+ sys.stderr.write("Unable to successfully retrieve statistical information.\n")
+
+if __name__ == '__main__':
+ main(sys.argv[1:])
\ No newline at end of file
diff --git a/pool/shard009/Python/0087555_test_rfh_file_importer.py b/pool/shard009/Python/0087555_test_rfh_file_importer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ee5f5c17b0507b6d79c2687a1fc8c3792d08a3c
--- /dev/null
+++ b/pool/shard009/Python/0087555_test_rfh_file_importer.py
@@ -0,0 +1,182 @@
+import datetime
+from mock import patch, MagicMock
+
+from gloss import message_type
+from gloss.tests.core import GlossTestCase
+
+from sites.rfh.importers import file_importer
+
+
+class RFHBloodCulturesFileTypeTestCase(GlossTestCase):
+
+ @property
+ def row(self):
+ class Row(object):
+ def __init__(self, **kw):
+ for k in kw:
+ setattr(self, k, kw[k])
+
+ return Row(
+ nhsno='890123456',
+ hospno='555345',
+ surn='Henderson',
+ fn='Heather',
+ dob='12121984',
+ sex='F',
+ loc='P701',
+ cons='Dr C Chalmers-Watson',
+ postcode='NW1 6XE',
+ labno='348789729',
+ pttype='NHS',
+ loc2='GP',
+ ward='P701',
+ datetest='31/05/2013',
+ daterec='01/06/2013',
+ daterep='02/06/2013',
+ samptests='URIN,URIN,LBLB',
+ samptype='URI',
+ result='Culture Result : Urine :',
+ org='Escherichia coli',
+ ami='s',
+ amo='',
+ amb='',
+ amp='R',
+ cas='',
+ aug='R',
+ pos='',
+ azt='s',
+ vor='',
+ car='',
+ cap='',
+ cem='',
+ cee='',
+ cez='',
+ cei='s',
+ cex='',
+ ceo='',
+ ctx='',
+ cfo='',
+ cxn='s',
+ cef='',
+ cta='s',
+ cfu='s',
+ cfx='R',
+ cep='',
+ crd='',
+ chl='',
+ cin='',
+ cip='s',
+ cla='',
+ cli='',
+ clf='',
+ clo='',
+ col='s',
+ cot='s',
+ cse='',
+ dap='',
+ dor='',
+ dox='',
+ ery='',
+ ert='s',
+ eta='',
+ eth='',
+ flu='',
+ flz='',
+ fivefl='',
+ fos='',
+ fuc='',
+ gen='S',
+ ges='',
+ imi='',
+ iso='',
+ itr='',
+ kan='',
+ ket='',
+ lin='',
+ lev='s',
+ lom='',
+ mec='',
+ mer='s',
+ met='',
+ mdz='',
+ mez='',
+ mil='',
+ min='',
+ mox='',
+ mof='',
+ mup='',
+ mph='',
+ nal='',
+ neo='',
+ net='',
+ nfu='S',
+ nor='',
+ nov='',
+ nys='',
+ ofl='',
+ oxa='',
+ pas='',
+ pen='',
+ pe2='',
+ peo='',
+ pe0='',
+ pip='s',
+ prl='s',
+ pol='s',
+ pri='',
+ pro='',
+ pyr='',
+ rif='',
+ rib='',
+ rox='',
+ sep='',
+ sis='',
+ spe='',
+ str='',
+ syn='',
+ sub='',
+ sud='',
+ sul='',
+ tei='',
+ tem='',
+ tet='',
+ tri='',
+ van='',
+ esbl='',
+ ampc='',
+ ampcdr='',
+ blank='')
+
+ def test_to_date(self):
+ filetype = file_importer.RFHBloodCulturesFileType('notareal.file')
+ self.assertEqual(datetime.datetime(1976, 4, 23), filetype._to_date('23/4/1976'))
+
+ def test_res(self):
+ filetype = file_importer.RFHBloodCulturesFileType('notareal.file')
+ expected = [u'Cefixime R', u'Augmentin R', u'Amphotericin R']
+ self.assertEqual(expected, filetype.res(self.row))
+
+ def test_sens(self):
+ filetype = file_importer.RFHBloodCulturesFileType('notareal.file')
+ expected = [u'Piperacillin-Tazobactam s', u'Amikacin s', u'Nitrofurantoin S',
+ u'Levofloxacin s',
+ u'Meropenem s', u'Gentamicin S', u'Ertapenem s', u'Ciprofloxacin s',
+ u'Aztreonam s',
+ u'Colistin s']
+ self.assertEqual(expected, filetype.sens(self.row))
+
+ def test_row_to_result_message(self):
+ filetype = file_importer.RFHBloodCulturesFileType('notareal.file')
+ msg = filetype.row_to_result_message(self.row)
+ self.assertIsInstance(msg, message_type.ResultMessage)
+ self.assertEqual('BC', msg.profile_code)
+
+ def test_process_file(self):
+ filetype = file_importer.RFHBloodCulturesFileType('notareal.file')
+ with patch.object(filetype, 'path') as mock_path:
+ mock_path.csv.return_value.__enter__.return_value.__iter__.return_value = [self.row]
+ service = MagicMock()
+
+ for container in filetype.import_message(service):
+ self.assertEqual('RFH', container.issuing_source)
+ self.assertEqual('555345', container.hospital_number)
diff --git a/pool/shard009/Python/0087556_graph_MT_pre__Thread.py b/pool/shard009/Python/0087556_graph_MT_pre__Thread.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b3adcfae95d972932dde7e78d949841a174dfe0
--- /dev/null
+++ b/pool/shard009/Python/0087556_graph_MT_pre__Thread.py
@@ -0,0 +1,63 @@
+"""
+__graph_MT_pre__Thread.py___________________________________________________________
+
+Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION
+____________________________________________________________________________
+"""
+import tkFont
+
+from graphEntity import *
+from GraphicalForm import *
+from ATOM3Constraint import *
+
+class graph_MT_pre__Thread(graphEntity):
+
+ def __init__(self, x, y, semObject = None):
+ self.semanticObject = semObject
+ self.sizeX, self.sizeY = 172, 82
+ graphEntity.__init__(self, x, y)
+ self.ChangesAtRunTime = 0
+ self.constraintList = []
+ if self.semanticObject: atribs = self.semanticObject.attributesToDraw()
+ else: atribs = None
+ self.graphForms = []
+ self.imageDict = self.getImageDict()
+
+ def DrawObject(self, drawing, showGG = 0):
+ self.dc = drawing
+ if showGG and self.semanticObject: self.drawGGLabel(drawing)
+ h = drawing.create_oval(self.translate([189.0, 62.0, 189.0, 62.0]), tags = (self.tag, 'connector'), outline = '', fill = '' )
+ self.connectors.append( h )
+
+ h = drawing.create_rectangle(self.translate([20.0, 20.0, 190.0, 100.0]), tags = self.tag, stipple = '', width = 1, outline = 'black', fill = 'moccasin')
+ self.gf4 = GraphicalForm(drawing, h, "gf4")
+ self.graphForms.append(self.gf4)
+
+ font = tkFont.Font( family='Arial', size=12, weight='normal', slant='roman', underline=0)
+ h = drawing.create_text(self.translate([96.0, 36.0, 96.0, 12.0])[:2], tags = self.tag, font=font, fill = 'black', anchor = 'center', text = 'MT_pre__Thread', width = '0', justify= 'left', stipple='' )
+ self.gf81 = GraphicalForm(drawing, h, 'gf81', fontObject=font)
+ self.graphForms.append(self.gf81)
+
+
+
+ helv12 = tkFont.Font ( family="Helvetica", size=12, weight="bold" )
+ h = drawing.create_text(self.translate([-3, -3]), font=helv12,
+ tags = (self.tag, self.semanticObject.getClass()),
+ fill = "black",
+ text=self.semanticObject.MT_label__.toString())
+ self.attr_display["MT_label__"] = h
+ self.gf_label = GraphicalForm(drawing, h, 'gf_label', fontObject=helv12)
+ self.graphForms.append(self.gf_label)
+
+ def postCondition( self, actionID, * params):
+ return None
+
+ def preCondition( self, actionID, * params):
+ return None
+
+ def getImageDict( self ):
+ imageDict = dict()
+
+ return imageDict
+
+new_class = graph_MT_pre__Thread
diff --git a/pool/shard009/Python/0087558_typecheck.py b/pool/shard009/Python/0087558_typecheck.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a257d81887066aaa96b9b58d0ad8c0deffd6761
--- /dev/null
+++ b/pool/shard009/Python/0087558_typecheck.py
@@ -0,0 +1,319 @@
+# Copyright 2016 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.
+# ==============================================================================
+"""Minimal runtime type checking library.
+
+This module should not be considered public API.
+"""
+# TODO(ericmc,shoyer): Delete this in favor of using pytype or mypy
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import functools
+import re
+
+from tensorflow.python.util import tf_inspect
+from tensorflow.python.util.compat import collections_abc
+
+# used for register_type_abbreviation and _type_repr below.
+_TYPE_ABBREVIATIONS = {}
+
+
+class Type(object):
+ """Base class for type checker types.
+
+ The custom types defined in this module are based on types in the standard
+ library's typing module (in Python 3.5):
+ https://docs.python.org/3/library/typing.html
+
+ The only difference should be that we use actual instances of Type classes to
+ represent custom types rather than the metaclass magic typing uses to create
+ new class objects. In practice, all this should mean is that we use
+ `List(int)` rather than `List[int]`.
+
+ Custom types should implement __instancecheck__ and inherit from Type. Every
+ argument in the constructor must be a type or Type instance, and these
+ arguments must be stored as a tuple on the `_types` attribute.
+ """
+
+ def __init__(self, *types):
+ self._types = types
+
+ def __repr__(self):
+ args_repr = ", ".join(repr(t) for t in self._types)
+ return "typecheck.%s(%s)" % (type(self).__name__, args_repr)
+
+
+class _SingleArgumentType(Type):
+ """Use this subclass for parametric types that accept only one argument."""
+
+ def __init__(self, tpe):
+ super(_SingleArgumentType, self).__init__(tpe)
+
+ @property
+ def _type(self):
+ tpe, = self._types # pylint: disable=unbalanced-tuple-unpacking
+ return tpe
+
+
+class _TwoArgumentType(Type):
+ """Use this subclass for parametric types that accept two arguments."""
+
+ def __init__(self, first_type, second_type):
+ super(_TwoArgumentType, self).__init__(first_type, second_type)
+
+
+class Union(Type):
+ """A sum type.
+
+ A correct type is any of the types provided.
+ """
+
+ def __instancecheck__(self, instance):
+ return isinstance(instance, self._types)
+
+
+class Optional(_SingleArgumentType):
+ """An optional type.
+
+ A correct type is either the provided type or NoneType.
+ """
+
+ def __instancecheck__(self, instance):
+ # types.NoneType does not exist in Python 3
+ return isinstance(instance, (self._type, type(None)))
+
+
+class List(_SingleArgumentType):
+ """A typed list.
+
+ A correct type is a list where each element has the single provided type.
+ """
+
+ def __instancecheck__(self, instance):
+ return (isinstance(instance, list) and
+ all(isinstance(x, self._type) for x in instance))
+
+
+class Sequence(_SingleArgumentType):
+ """A typed sequence.
+
+ A correct type is a sequence where each element has the single provided type.
+ """
+
+ def __instancecheck__(self, instance):
+ return (isinstance(instance, collections_abc.Sequence) and
+ all(isinstance(x, self._type) for x in instance))
+
+
+class Collection(_SingleArgumentType):
+ """A sized, iterable container.
+
+ A correct type is an iterable and container with known size where each element
+ has the single provided type.
+
+ We use this in preference to Iterable because we check each instance of the
+ iterable at runtime, and hence need to avoid iterables that could be
+ exhausted.
+ """
+
+ def __instancecheck__(self, instance):
+ return (isinstance(instance, collections_abc.Iterable) and
+ isinstance(instance, collections_abc.Sized) and
+ isinstance(instance, collections_abc.Container) and
+ all(isinstance(x, self._type) for x in instance))
+
+
+class Tuple(Type):
+ """A typed tuple.
+
+ A correct type is a tuple with the correct length where each element has
+ the correct type.
+ """
+
+ def __instancecheck__(self, instance):
+ return (isinstance(instance, tuple) and
+ len(instance) == len(self._types) and
+ all(isinstance(x, t) for x, t in zip(instance, self._types)))
+
+
+class Mapping(_TwoArgumentType):
+ """A typed mapping.
+
+ A correct type has the correct parametric types for keys and values.
+ """
+
+ def __instancecheck__(self, instance):
+ key_type, value_type = self._types # pylint: disable=unbalanced-tuple-unpacking
+ return (isinstance(instance, collections_abc.Mapping) and
+ all(isinstance(k, key_type) for k in instance.keys()) and
+ all(isinstance(k, value_type) for k in instance.values()))
+
+
+class Dict(Mapping):
+ """A typed dict.
+
+ A correct type has the correct parametric types for keys and values.
+ """
+
+ def __instancecheck__(self, instance):
+ return (isinstance(instance, dict) and
+ super(Dict, self).__instancecheck__(instance))
+
+
+def _replace_forward_references(t, context):
+ """Replace forward references in the given type."""
+ if isinstance(t, str):
+ return context[t]
+ elif isinstance(t, Type):
+ return type(t)(*[_replace_forward_references(t, context) for t in t._types]) # pylint: disable=protected-access
+ else:
+ return t
+
+
+def register_type_abbreviation(name, alias):
+ """Register an abbreviation for a type in typecheck tracebacks.
+
+ This makes otherwise very long typecheck errors much more readable.
+
+ Example:
+ typecheck.register_type_abbreviation(tf.compat.v1.Dimension,
+ 'tf.compat.v1.Dimension')
+
+ Args:
+ name: type or class to abbreviate.
+ alias: string alias to substitute.
+ """
+ _TYPE_ABBREVIATIONS[name] = alias
+
+
+def _type_repr(t):
+ """A more succinct repr for typecheck tracebacks."""
+ string = repr(t)
+ for type_, alias in _TYPE_ABBREVIATIONS.items():
+ string = string.replace(repr(type_), alias)
+ string = re.sub(r"<(class|type) '([\w.]+)'>", r"\2", string)
+ string = re.sub(r"typecheck\.(\w+)", r"\1", string)
+ return string
+
+
+class Error(TypeError):
+ """Exception for typecheck failures."""
+
+
+def accepts(*types):
+ """A decorator which checks the input types of a function.
+
+ Based on:
+ http://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments
+ The above draws from:
+ https://www.python.org/dev/peps/pep-0318/
+
+ Args:
+ *types: A list of Python types.
+
+ Returns:
+ A function to use as a decorator.
+ """
+
+ def check_accepts(f):
+ """Check the types."""
+ spec = tf_inspect.getargspec(f)
+
+ num_function_arguments = len(spec.args)
+ if len(types) != num_function_arguments:
+ raise Error(
+ "Function %r has %d arguments but only %d types were provided in the "
+ "annotation." % (f, num_function_arguments, len(types)))
+
+ if spec.defaults:
+ num_defaults = len(spec.defaults)
+ for (name, a, t) in zip(spec.args[-num_defaults:], spec.defaults,
+ types[-num_defaults:]):
+ allowed_type = _replace_forward_references(t, f.__globals__)
+ if not isinstance(a, allowed_type):
+ raise Error("default argument value %r of type %r is not an instance "
+ "of the allowed type %s for the %s argument to %r" %
+ (a, type(a), _type_repr(allowed_type), name, f))
+
+ @functools.wraps(f)
+ def new_f(*args, **kwds):
+ """A helper function."""
+ for (a, t) in zip(args, types):
+ allowed_type = _replace_forward_references(t, f.__globals__)
+ if not isinstance(a, allowed_type):
+ raise Error("%r of type %r is not an instance of the allowed type %s "
+ "for %r" % (a, type(a), _type_repr(allowed_type), f))
+ return f(*args, **kwds)
+
+ return new_f
+
+ return check_accepts
+
+
+def returns(*types):
+ """A decorator which checks the return types of a function.
+
+ Based on:
+ http://stackoverflow.com/questions/15299878/how-to-use-python-decorators-to-check-function-arguments
+ The above draws from:
+ https://www.python.org/dev/peps/pep-0318/
+
+ Args:
+ *types: A list of Python types. A list of one element corresponds to a
+ single return value. A list of several elements corresponds to several
+ return values. Note that a function with no explicit return value has an
+ implicit NoneType return and should be annotated correspondingly.
+
+ Returns:
+ A function to use as a decorator.
+ """
+
+ def check_returns(f):
+ """Check the types."""
+ if not types:
+ raise TypeError("A return type annotation must contain at least one type")
+
+ @functools.wraps(f)
+ def new_f(*args, **kwds):
+ """A helper function."""
+ return_value = f(*args, **kwds)
+
+ if len(types) == 1:
+ # The function has a single return value.
+ allowed_type = _replace_forward_references(types[0], f.__globals__)
+ if not isinstance(return_value, allowed_type):
+ raise Error(
+ "%r of type %r is not an instance of the allowed type %s "
+ "for %r" %
+ (return_value, type(return_value), _type_repr(allowed_type), f))
+
+ else:
+ if len(return_value) != len(types):
+ raise Error("Function %r has %d return values but only %d types were "
+ "provided in the annotation." %
+ (f, len(return_value), len(types)))
+
+ for (r, t) in zip(return_value, types):
+ allowed_type = _replace_forward_references(t, f.__globals__)
+ if not isinstance(r, allowed_type):
+ raise Error("%r of type %r is not an instance of allowed type %s "
+ "for %r" % (r, type(r), _type_repr(allowed_type), f))
+
+ return return_value
+
+ return new_f
+
+ return check_returns
diff --git a/pool/shard009/Python/0087559_mirrored_function_strategy.py b/pool/shard009/Python/0087559_mirrored_function_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa9ecfa1fc47c3b8a4e3a13b4b2b8eb94b5eb306
--- /dev/null
+++ b/pool/shard009/Python/0087559_mirrored_function_strategy.py
@@ -0,0 +1,196 @@
+# Copyright 2019 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.
+# ==============================================================================
+"""Class MirroredFunctionStrategy implementing tf.distribute.Strategy."""
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import threading
+
+from tensorflow.python.distribute import device_util
+from tensorflow.python.distribute import distribute_lib
+from tensorflow.python.distribute import distribution_strategy_context
+from tensorflow.python.distribute import mirrored_strategy
+from tensorflow.python.distribute import values
+from tensorflow.python.eager import context
+from tensorflow.python.eager import def_function
+from tensorflow.python.framework import constant_op
+from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import ops
+from tensorflow.python.framework import tensor_spec
+from tensorflow.python.util import nest
+
+
+_replica_index = threading.local()
+_replica_id_key = object()
+
+
+def _replica_id_tensor():
+ return ops.get_default_graph().capture_call_time_value(
+ closure=lambda: constant_op.constant(_replica_index.current),
+ spec=tensor_spec.TensorSpec((), dtypes.int32),
+ key=_replica_id_key)
+
+
+def _in_run():
+ return (hasattr(_replica_index, "current") and
+ _replica_index.current is not None)
+
+
+def _outside_run_graph():
+ if hasattr(_replica_index, "graph_outside_run"):
+ return _replica_index.graph_outside_run
+ else:
+ return None
+
+
+class MirroredFunctionStrategy(distribute_lib.Strategy):
+ """Mirrors vars to distribute across multiple devices and machines.
+
+ This strategy uses one replica per device and sync replication for its
+ multi-GPU version. Unlike `tf.distribute.MirroredStrategy`, it creates a
+ function for a single replica, and calls that function repeatedly instead of
+ recording the operations for each replica separately.
+ """
+
+ def __init__(self, devices=None):
+ """Create an instance of `MirroredFunctionStrategy`.
+
+ Args:
+ devices: a list of device strings. If `None`, all available GPUs are
+ used. If no GPUs are found, CPU is used.
+ """
+ extended = MirroredFunctionExtended(self, devices)
+ super(MirroredFunctionStrategy, self).__init__(extended)
+
+
+# TODO(josh11b): Switch to V2 when we no longer need to support tf.compat.v1.
+class MirroredFunctionExtended(distribute_lib.StrategyExtendedV1):
+ """Implementation of MirroredFunctionStrategy."""
+
+ def __init__(self, container_strategy, devices):
+ super(MirroredFunctionExtended, self).__init__(container_strategy)
+ if devices is None:
+ devices = mirrored_strategy.all_devices()
+ if not devices:
+ raise ValueError("Got an empty `devices` list. Please make sure the "
+ "`devices` you pass in is not empty.")
+ device_tuple = tuple(device_util.resolve(d) for d in devices)
+ assert len(set(device_tuple)) == len(device_tuple), (
+ "No duplicates allowed in `devices` argument: %s" % (devices,))
+ self._devices = device_tuple
+ self._retrace_functions_for_each_device = False
+
+ def _call_for_each_replica(self, fn, args, kwargs):
+ # For now, `fn` must be an @tf.function.
+ # TODO(josh11b): Relax this restriction? Main problem is if
+ # (a) executing eagerly, (b) `fn` not @tf.function, and
+ # (c) executed frequently.
+ assert isinstance(fn, def_function.Function)
+
+ if _outside_run_graph() is not None:
+ # Nested case, should just use outer function's context for things like
+ # the current replica index.
+ # TODO(josh11b): Test this case!
+ with MirroredFunctionReplicaContext(self._container_strategy()):
+ results = fn(*nest.map_structure(_unwrap_tensors, args),
+ **nest.map_structure(_unwrap_tensors, kwargs))
+ return nest.map_structure(_wrap_tensors, results)
+
+ _replica_index.graph_outside_run = ops.get_default_graph()
+ return_values = []
+
+ try:
+ with MirroredFunctionReplicaContext(self._container_strategy()):
+ for index, device in enumerate(self._devices):
+ _replica_index.current = index
+ with ops.device(device):
+ if context.executing_eagerly():
+ # NOTE: These functions need to execute concurrently if they
+ # use a collective op. This is a particular concern with eager
+ # execution.
+ with context.execution_mode(context.ASYNC):
+ return_values.append(fn(*values.select_replica(index, args),
+ **values.select_replica(index, kwargs)))
+ else:
+ return_values.append(fn(*values.select_replica(index, args),
+ **values.select_replica(index, kwargs)))
+ finally:
+ _replica_index.graph_outside_run = None
+ _replica_index.current = None
+
+ return values.regroup(return_values)
+
+ def _local_results(self, val):
+ if isinstance(val, values.DistributedValues):
+ return val.values
+ return (val,)
+
+
+class FnMergedValue(object):
+
+ def __init__(self, value):
+ self._value = value
+
+
+def _wrap_tensors(maybe_tensor):
+ if isinstance(maybe_tensor, ops.Tensor): # TODO(josh11b): or composite tensor?
+ return FnMergedValue(maybe_tensor)
+ return maybe_tensor
+
+
+def _unwrap_tensors(maybe_wrapped):
+ if isinstance(maybe_wrapped, FnMergedValue):
+ return maybe_wrapped._value # pylint: disable=protected-access
+ return maybe_wrapped
+
+
+class MirroredFunctionReplicaContext(distribute_lib.ReplicaContext):
+ """ReplicaContext used in MirroredFunctionStrategy."""
+
+ def __init__(self, strategy):
+ distribute_lib.ReplicaContext.__init__(self, strategy, None)
+
+ @property
+ def _replica_id_in_sync_group(self):
+ return _replica_id_tensor()
+
+ @_replica_id_in_sync_group.setter
+ def _replica_id_in_sync_group(self, value):
+ assert value is None
+
+ def _merge_call(self, merge_fn, args, kwargs):
+ # We wrap all args/kwargs with tensor values in a class that prevents them
+ # for being used by anything other than MirroredFunctionStrategy APIs that
+ # have been specifically written to recognize the wrapper and unwrap the
+ # values (such as extended.reduce_to/update).
+
+ # TODO(josh11b): Should these set expand_composites=True?
+ args = nest.map_structure(_wrap_tensors, args)
+ kwargs = nest.map_structure(_wrap_tensors, kwargs)
+ # pylint: disable=protected-access
+ distribution_strategy_context._push_per_thread_mode(
+ distribution_strategy_context._CrossReplicaThreadMode(self._strategy))
+ try:
+ results = merge_fn(self._strategy, *args, **kwargs)
+ finally:
+ distribution_strategy_context._pop_per_thread_mode()
+ # pylint: enable=protected-access
+ return nest.map_structure(_unwrap_tensors, results)
+
+ @property
+ def devices(self):
+ raise RuntimeError("Can't get the devices for the current replica.")
diff --git a/pool/shard009/Python/0087563_shib.py b/pool/shard009/Python/0087563_shib.py
new file mode 100644
index 0000000000000000000000000000000000000000..7329670d5bdfb49229975ba67f193667e60d684a
--- /dev/null
+++ b/pool/shard009/Python/0087563_shib.py
@@ -0,0 +1,22 @@
+from django.shortcuts import render, redirect
+from django.core.urlresolvers import reverse
+from django.http import HttpResponse, Http404
+from django.conf import settings
+
+def shib_login(request):
+ """
+ If Shibboleth is enabled on this server, a request
+ should go right through and processed in the workflow.
+ If not, the login page should be displayed (GET) and
+ processed through the workflow when submitted (POST)
+ """
+ new_person = request.session.pop('IS_NEW_PERSON',False)
+ if settings.SHIB_ENABLED:
+ if new_person:
+ #This is a new person, they should visit the about you page first
+ return redirect(reverse("approver:aboutyou"))
+ else:
+ #This person is not new and should go to the dashboard
+ return redirect(reverse("approver:dashboard"))
+ else:
+ raise Http404('This application requires Shibboleth to be running')
diff --git a/pool/shard009/Python/0087570_main__.py b/pool/shard009/Python/0087570_main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bee55b7f47b5daf41e0822bcdfc36dfce26cd8b
--- /dev/null
+++ b/pool/shard009/Python/0087570_main__.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import os
+
+head = os.path.dirname(__file__)
+pygtkweb = os.path.join(head, '..', '..', '..', 'pygtkweb')
+
+TARGETS = {
+ 'AutoGtk.py': dict(
+ options=[
+ '--library_dir',
+ os.path.join(pygtkweb, 'library'),
+ ],
+ )
+}
+
+
+PACKAGE = {
+ 'title': 'pywebgtkbuilder',
+ 'desc': 'Python Web-Gtk "GtkBuilder" example',
+}
+
+
+def setup(targets):
+ '''Setup example for translation, MUST call util.setup(targets).'''
+ util.setup(targets)
+
+
+def translate():
+ '''Translate example, MUST call util.translate().'''
+ util.translate()
+
+
+def install(package):
+ '''Install and cleanup example module. MUST call util.install(package)'''
+ util.install(package)
+
+
+##---------------------------------------##
+# --------- (-: DO NOT EDIT :-) --------- #
+##---------------------------------------##
+
+
+import sys
+import os
+
+
+examples = head = os.path.abspath(os.path.dirname(__file__))
+while os.path.split(examples)[1].lower() != 'examples':
+ examples = os.path.split(examples)[0]
+ if not examples:
+ raise ValueError("Cannot determine examples directory")
+sys.path.insert(0, os.path.join(examples))
+from _examples import util
+sys.path.pop(0)
+
+util.init(head)
+
+setup(TARGETS)
+translate()
+install(PACKAGE)
diff --git a/pool/shard009/Python/0087574_httpcookie.py b/pool/shard009/Python/0087574_httpcookie.py
new file mode 100644
index 0000000000000000000000000000000000000000..db3acec6037dee2a3c986c959a369db3d7b18511
--- /dev/null
+++ b/pool/shard009/Python/0087574_httpcookie.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+
+import weakref
+try:
+ # Python 3
+ import http.cookies as http_cookies
+except:
+ # Python 2
+ import Cookie as http_cookies
+
+from lascaux import config
+
+
+class HttpCookie(dict):
+
+ reqres = None
+
+ def __init__(self, reqres):
+ self.reqres = weakref.proxy(reqres)
+
+ def eat(self, dough):
+ """ Dough is so much better than the baked version anyway... """
+ if dough:
+ cookie = http_cookies.SimpleCookie()
+ cookie.load(dough)
+ for key in cookie:
+ self[key] = self._clean(cookie[key].value)
+
+ def bake(self):
+ if self:
+ cookie = http_cookies.SimpleCookie()
+ for key in self:
+ cookie[str(key)] = self[key]
+ self.reqres.headers['Set-cookie'] = cookie.output(header='')
+
+ def _clean(self, value):
+ """ Normalizes some values to be more pythonic... """
+ if value in ('None'):
+ return None
+ return value
diff --git a/pool/shard009/Python/0087582_fast_mapping.py b/pool/shard009/Python/0087582_fast_mapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..44f1c335f93f2185a8e071e67f260a782990b747
--- /dev/null
+++ b/pool/shard009/Python/0087582_fast_mapping.py
@@ -0,0 +1,56 @@
+import numba as nb
+import numpy as np
+import pandas as pd
+
+
+@nb.njit
+def _fast_map(fm, target, dtype=np.int32):
+ out = np.zeros(len(target), dtype=dtype)
+ for n in range(target.size):
+ out[n] = fm[target[n]]
+ return out
+
+
+class FastMapping:
+
+ def __init__(self, source, to_range=np.int64):
+ if isinstance(source, pd.Series):
+ m = nb.typed.Dict.empty(
+ key_type=nb.from_dtype(source.index.dtype),
+ value_type=nb.from_dtype(source.dtype),
+ )
+ for k, v in source.items():
+ m[k] = v
+ self._in_dtype = source.index.dtype
+ self._out_dtype = source.dtype
+ self._mapper = m
+ elif to_range:
+ m = nb.typed.Dict.empty(
+ key_type=nb.from_dtype(source.dtype),
+ value_type=nb.from_dtype(to_range),
+ )
+ for v, k in enumerate(source):
+ m[k] = v
+ self._in_dtype = source.dtype
+ self._out_dtype = to_range
+ self._mapper = m
+ else:
+ raise ValueError("invalid input")
+
+ def __len__(self):
+ return len(self._mapper)
+
+ def __contains__(self, item):
+ return item in self._mapper
+
+ def __getitem__(self, item):
+ return self._mapper[item]
+
+ def apply_to(self, target):
+ if isinstance(target, pd.Series):
+ return pd.Series(
+ _fast_map(self._mapper, target.astype(self._in_dtype).to_numpy(), dtype=self._out_dtype),
+ index=target.index,
+ )
+ return _fast_map(self._mapper, np.asarray(target, dtype=self._in_dtype), dtype=self._out_dtype)
+
diff --git a/pool/shard009/Python/0087586_a.py b/pool/shard009/Python/0087586_a.py
new file mode 100644
index 0000000000000000000000000000000000000000..871379c31fdff86098c35d03819f4b6b4181e615
--- /dev/null
+++ b/pool/shard009/Python/0087586_a.py
@@ -0,0 +1,77 @@
+#!/usr/bin/python
+
+import sys
+
+def get_file(argv):
+ if len(argv) == 1:
+ return "a.in"
+ else:
+ return "a_%s.in" % (argv[1])
+
+def get_file_out(argv):
+ if len(argv) == 1:
+ return "a.out"
+ else:
+ return "a_%s.out" % (argv[1])
+
+def print_answer(t, answer, f):
+ answer = "Case #%d: %s" % (t, answer)
+ print answer
+ f.write(answer)
+ f.write("\n")
+
+def get_number(S):
+ L = list(S)
+ M = {}
+ for c in S:
+ if c in M:
+ M[c] = M[c] + 1
+ else:
+ M[c] = 1
+ O = ['Z', 'W', 'U', 'X', 'G', 'FI', 'SV', 'HR', 'NI', 'ON']
+ uniques = {
+ 'Z': ['Z', 'E', 'R', 'O'],
+ 'W': ['T', 'W', 'O'],
+ 'U': ['F', 'O', 'U', 'R'],
+ 'X': ['S', 'I', 'X'],
+ 'G': ['E', 'I', 'G', 'H', 'T'],
+ 'FI': ['F', 'I', 'V', 'E'],
+ 'SV': ['S', 'E', 'V', 'E', 'N'],
+ 'HR': ['T', 'H', 'R', 'E', 'E'],
+ 'NI': ['N', 'I', 'N', 'E'],
+ 'ON': ['O', 'N', 'E'],
+ }
+ assert len(uniques) == 10
+ mapping = [0, 2, 4, 6, 8, 5, 7, 3, 9, 1]
+ assert len(mapping) == 10
+ numbers = []
+ for check in xrange(0, len(O)):
+ uc = O[check]
+ found_all = True
+ for test in uc:
+ if test not in M or M[test] < 1:
+ found_all = False
+ break
+ if found_all:
+ to_remove = len(S)
+ for test in uc:
+ to_remove = min(M[test], to_remove)
+ for i in xrange(0, to_remove):
+ numbers.append(str(mapping[check]))
+ for c in uniques[uc]:
+ M[c] = M[c] - 1
+ numbers.sort()
+ return ''.join(numbers)
+
+def main(argv):
+ f = open(get_file(argv), 'r')
+ f_out = open(get_file_out(argv), 'w')
+ T = int(f.readline())
+ for t in xrange(1, T+1):
+ S = f.readline().strip()
+ number = get_number(S)
+ print_answer(t, number, f_out)
+
+
+if __name__ == "__main__":
+ main(sys.argv)
diff --git a/pool/shard009/Python/0087590_plots.py b/pool/shard009/Python/0087590_plots.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dacbf2491d5c1f791f3f489c0b4461a19ac170c
--- /dev/null
+++ b/pool/shard009/Python/0087590_plots.py
@@ -0,0 +1,160 @@
+from pathlib import Path
+import logging
+import xarray
+from matplotlib.figure import Figure
+import numpy as np
+
+
+def plotazel(scale: xarray.Dataset, plottype: str = "singlecontour", img: np.ndarray = None):
+
+ if "az" not in scale:
+ return
+
+ if plottype == "singlecontour":
+ fg = Figure()
+ ax = fg.gca()
+ if img is not None:
+ ax.imshow(img, origin="lower", cmap="gray")
+ cs = ax.contour(scale["x"], scale["y"], scale["az"])
+ ax.clabel(cs, inline=1, fmt="%0.1f")
+ cs = ax.contour(scale["x"], scale["y"], scale["el"])
+ ax.clabel(cs, inline=True, fmt="%0.1f")
+ ax.set_xlabel("x-pixel")
+ ax.set_ylabel("y-pixel")
+ ax.set_title(
+ f"{Path(scale.filename).name} ({scale.lat:.2f}, {scale.lon:.2f}) {scale.time}\nAzimuth / Elevation"
+ )
+ fg.set_tight_layout(True)
+ return fg
+ elif plottype == "image":
+ fg = Figure(figsize=(12, 5))
+ ax = fg.subplots(1, 2, sharey=True)
+ hia = ax[0].imshow(scale["az"], origin="lower")
+ hc = fg.colorbar(hia)
+ hc.set_label("Azimuth [deg]")
+ elif plottype == "contour":
+ fg = Figure(figsize=(12, 5))
+ ax = fg.subplots(1, 2, sharey=True)
+ if img is not None:
+ ax[0].imshow(img, origin="lower", cmap="gray")
+ cs = ax[0].contour(scale["x"], scale["y"], scale["az"])
+ ax[0].clabel(cs, inline=1, fmt="%0.1f")
+
+ ax[0].set_xlabel("x-pixel")
+ ax[0].set_ylabel("y-pixel")
+ ax[0].set_title("azimuth")
+ # %%
+ axe = ax[1]
+ if plottype == "image":
+ hie = axe.imshow(scale["el"], origin="lower")
+ hc = fg.colorbar(hie)
+ hc.set_label("Elevation [deg]")
+ elif plottype == "contour":
+ if img is not None:
+ axe.imshow(img, origin="lower", cmap="gray")
+ cs = axe.contour(scale["x"], scale["y"], scale["el"])
+ axe.clabel(cs, inline=True, fmt="%0.1f")
+
+ axe.set_xlabel("x-pixel")
+ axe.set_title("elevation")
+ fg.suptitle(f"{Path(scale.filename).name}\n({scale.lat:.2f}, {scale.lon:.2f}) {scale.time}")
+ fg.set_tight_layout(True)
+
+ return fg
+
+
+def plotradec(scale: xarray.Dataset, plottype: str = "singlecontour", img: np.ndarray = None):
+
+ if "ra" not in scale:
+ return
+
+ if plottype == "singlecontour":
+ fg = Figure()
+ ax = fg.gca()
+ if img is not None:
+ ax.imshow(img, origin="lower", cmap="gray")
+ cs = ax.contour(scale["x"], scale["y"], scale["ra"])
+ ax.clabel(cs, inline=1, fmt="%0.1f")
+ cs = ax.contour(scale["x"], scale["y"], scale["dec"])
+ ax.clabel(cs, inline=True, fmt="%0.1f")
+ ax.set_xlabel("x-pixel")
+ ax.set_ylabel("y-pixel")
+ ax.set_title(f"{Path(scale.filename).name} Right Ascension / Declination")
+ fg.set_tight_layout(True)
+ return fg
+ elif plottype == "image":
+ fg = Figure(figsize=(12, 5))
+ ax = fg.subplots(1, 2, sharey=True)
+ hri = ax[0].imshow(scale["ra"], origin="lower")
+ hc = fg.colorbar(hri)
+ hc.set_label("RA [deg]")
+ elif plottype == "contour":
+ fg = Figure(figsize=(12, 5))
+ ax = fg.subplots(1, 2, sharey=True)
+ if img is not None:
+ ax[0].imshow(img, origin="lower", cmap="gray")
+ cs = ax[0].contour(scale["x"], scale["y"], scale["ra"])
+ ax[0].clabel(cs, inline=1, fmt="%0.1f")
+
+ ax[0].set_xlabel("x-pixel")
+ ax[0].set_ylabel("y-pixel")
+ ax[0].set_title("Right Ascension ")
+ # %%
+ if plottype == "image":
+ hdi = ax[1].imshow(scale["dec"], origin="lower")
+ hc = fg.colorbar(hdi)
+ hc.set_label("Dec [deg]")
+ elif plottype == "contour":
+ if img is not None:
+ ax[1].imshow(img, origin="lower", cmap="gray")
+ cs = ax[1].contour(scale["x"], scale["y"], scale["dec"])
+ ax[1].clabel(cs, inline=1, fmt="%0.1f")
+
+ ax[1].set_xlabel("x-pixel")
+ ax[1].set_title("Declination")
+ fg.suptitle(Path(scale.filename).name)
+
+ fg.set_tight_layout(True)
+
+ return fg
+
+
+def plotimagestack(img: np.ndarray, fn: Path, clim=None):
+ fn = Path(fn).expanduser()
+ # %% plotting
+ if img.ndim == 3 and img.shape[0] == 3: # it seems to be an RGB image
+ cmap = None
+ imnorm = None
+ img = img.transpose([1, 2, 0]) # imshow() needs colors to be last axis
+ else:
+ cmap = "gray"
+ imnorm = None
+ # imnorm = LogNorm()
+
+ fg = Figure()
+ ax = fg.gca()
+ if clim is None:
+ hi = ax.imshow(img, origin="lower", interpolation="none", cmap=cmap, norm=imnorm)
+ else:
+ hi = ax.imshow(
+ img,
+ origin="lower",
+ interpolation="none",
+ cmap=cmap,
+ vmin=clim[0],
+ vmax=clim[1],
+ norm=imnorm,
+ )
+ ax.set_xlabel("x")
+ ax.set_ylabel("y")
+ ax.set_title(str(fn))
+ if cmap is not None:
+ try:
+ hc = fg.colorbar(hi)
+ hc.set_label(f"Data numbers {img.dtype}")
+ except Exception as e:
+ logging.warning(f"trouble making picture colorbar {e}")
+
+ plotFN = fn.parent / (fn.stem + "_picture.png")
+ print("writing", plotFN)
+ fg.savefig(plotFN)
diff --git a/pool/shard009/Python/0087594_test_geometry.py b/pool/shard009/Python/0087594_test_geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdd22a6c86b43f59fbaec2ca89ca40af6535412a
--- /dev/null
+++ b/pool/shard009/Python/0087594_test_geometry.py
@@ -0,0 +1,44 @@
+__author__ = 'tonycastronova'
+
+import sys
+sys.path.append('../')
+
+import unittest
+from stdlib import *
+import datetime
+from utilities import spatial
+from advanced_geometry import *
+import random
+
+class testGeometry(unittest.TestCase):
+
+ def setUp(self):
+ self.vals = [(datetime.datetime(2014,1,1,12,0,0) + datetime.timedelta(days=i), i) for i in range(0,100)]
+ self.geometry = 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))'
+ self.srscode = '2921'
+
+
+ def test_point_grid(self):
+
+
+ # generate point geometries
+ pt_geoms = []
+ for x in range(0,3):
+ for y in range(0,3):
+ v = [(datetime.datetime(2014,1,1,12,0,0) + datetime.timedelta(days=i), i) for i in range(0,365)]
+ g = 'POINT (%d %d)' % (x,y)
+ dv = DataValues(v)
+ geom = Geometry()
+ geom.set_geom_from_wkt(g)
+ geom.type(ElementType.Point)
+ geom.srs(spatial.get_srs_from_epsg(self.srscode))
+ geom.datavalues(dv)
+ pt_geoms.append(geom)
+
+ # create element grid
+ grid = GriddedGeometry(pt_geoms,5,5,3,3)
+
+
+
+
+ # print grid.get_time_slice(datetime.datetime(2014,1,10,6,0,0))
diff --git a/pool/shard009/Python/0087600_0002_auto_20151113_1937.py b/pool/shard009/Python/0087600_0002_auto_20151113_1937.py
new file mode 100644
index 0000000000000000000000000000000000000000..baa85d584ee81bbae5ce1f52bec18560917990bd
--- /dev/null
+++ b/pool/shard009/Python/0087600_0002_auto_20151113_1937.py
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('sepomex', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='mxmunicipio',
+ name='clave',
+ field=models.CharField(max_length=10),
+ ),
+ migrations.AlterField(
+ model_name='mxmunicipio',
+ name='mx_estado',
+ field=models.ForeignKey(related_name='municipios', to='sepomex.MXEstado'),
+ ),
+ ]
diff --git a/pool/shard009/Python/0087602_logtesting.py b/pool/shard009/Python/0087602_logtesting.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aba1726a24313ccd5fd3dae290fe50f02f2e77f
--- /dev/null
+++ b/pool/shard009/Python/0087602_logtesting.py
@@ -0,0 +1,258 @@
+# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# 2. Redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution.
+#
+# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""Supports the unit-testing of logging code.
+
+Provides support for unit-testing messages logged using the built-in
+logging module.
+
+Inherit from the LoggingTestCase class for basic testing needs. For
+more advanced needs (e.g. unit-testing methods that configure logging),
+see the TestLogStream class, and perhaps also the LogTesting class.
+
+"""
+
+import logging
+import unittest2 as unittest
+
+
+class TestLogStream(object):
+
+ """Represents a file-like object for unit-testing logging.
+
+ This is meant for passing to the logging.StreamHandler constructor.
+ Log messages captured by instances of this object can be tested
+ using self.assertMessages() below.
+
+ """
+
+ def __init__(self, test_case):
+ """Create an instance.
+
+ Args:
+ test_case: A unittest.TestCase instance.
+
+ """
+ self._test_case = test_case
+ self.messages = []
+ """A list of log messages written to the stream."""
+
+ # Python documentation says that any object passed to the StreamHandler
+ # constructor should support write() and flush():
+ #
+ # http://docs.python.org/library/logging.html#module-logging.handlers
+ def write(self, message):
+ self.messages.append(message)
+
+ def flush(self):
+ pass
+
+ def assertMessages(self, messages):
+ """Assert that the given messages match the logged messages.
+
+ messages: A list of log message strings.
+
+ """
+ self._test_case.assertEqual(messages, self.messages)
+
+
+class LogTesting(object):
+
+ """Supports end-to-end unit-testing of log messages.
+
+ Sample usage:
+
+ class SampleTest(unittest.TestCase):
+
+ def setUp(self):
+ self._log = LogTesting.setUp(self) # Turn logging on.
+
+ def tearDown(self):
+ self._log.tearDown() # Turn off and reset logging.
+
+ def test_logging_in_some_method(self):
+ call_some_method() # Contains calls to _log.info(), etc.
+
+ # Check the resulting log messages.
+ self._log.assertMessages(["INFO: expected message #1",
+ "WARNING: expected message #2"])
+
+ """
+
+ def __init__(self, test_stream, handler):
+ """Create an instance.
+
+ This method should never be called directly. Instances should
+ instead be created using the static setUp() method.
+
+ Args:
+ test_stream: A TestLogStream instance.
+ handler: The handler added to the logger.
+
+ """
+ self._test_stream = test_stream
+ self._handler = handler
+
+ @staticmethod
+ def _getLogger():
+ """Return the logger being tested."""
+ # It is possible we might want to return something other than
+ # the root logger in some special situation. For now, the
+ # root logger seems to suffice.
+ return logging.getLogger()
+
+ @staticmethod
+ def setUp(test_case, logging_level=logging.INFO):
+ """Configure logging for unit testing.
+
+ Configures the root logger to log to a testing log stream.
+ Only messages logged at or above the given level are logged
+ to the stream. Messages logged to the stream are formatted
+ in the following way, for example--
+
+ "INFO: This is a test log message."
+
+ This method should normally be called in the setUp() method
+ of a unittest.TestCase. See the docstring of this class
+ for more details.
+
+ Returns:
+ A LogTesting instance.
+
+ Args:
+ test_case: A unittest.TestCase instance.
+ logging_level: An integer logging level that is the minimum level
+ of log messages you would like to test.
+
+ """
+ stream = TestLogStream(test_case)
+ handler = logging.StreamHandler(stream)
+ handler.setLevel(logging_level)
+ formatter = logging.Formatter("%(levelname)s: %(message)s")
+ handler.setFormatter(formatter)
+
+ # Notice that we only change the root logger by adding a handler
+ # to it. In particular, we do not reset its level using
+ # logger.setLevel(). This ensures that we have not interfered
+ # with how the code being tested may have configured the root
+ # logger.
+ logger = LogTesting._getLogger()
+ logger.addHandler(handler)
+
+ return LogTesting(stream, handler)
+
+ def tearDown(self):
+ """Assert there are no remaining log messages, and reset logging.
+
+ This method asserts that there are no more messages in the array of
+ log messages, and then restores logging to its original state.
+ This method should normally be called in the tearDown() method of a
+ unittest.TestCase. See the docstring of this class for more details.
+
+ """
+ self.assertMessages([])
+ logger = LogTesting._getLogger()
+ logger.removeHandler(self._handler)
+
+ def messages(self):
+ """Return the current list of log messages."""
+ return self._test_stream.messages
+
+ # FIXME: Add a clearMessages() method for cases where the caller
+ # deliberately doesn't want to assert every message.
+
+ # We clear the log messages after asserting since they are no longer
+ # needed after asserting. This serves two purposes: (1) it simplifies
+ # the calling code when we want to check multiple logging calls in a
+ # single test method, and (2) it lets us check in the tearDown() method
+ # that there are no remaining log messages to be asserted.
+ #
+ # The latter ensures that no extra log messages are getting logged that
+ # the caller might not be aware of or may have forgotten to check for.
+ # This gets us a bit more mileage out of our tests without writing any
+ # additional code.
+ def assertMessages(self, messages):
+ """Assert the current array of log messages, and clear its contents.
+
+ Args:
+ messages: A list of log message strings.
+
+ """
+ try:
+ self._test_stream.assertMessages(messages)
+ finally:
+ # We want to clear the array of messages even in the case of
+ # an Exception (e.g. an AssertionError). Otherwise, another
+ # AssertionError can occur in the tearDown() because the
+ # array might not have gotten emptied.
+ self._test_stream.messages = []
+
+
+# This class needs to inherit from unittest.TestCase. Otherwise, the
+# setUp() and tearDown() methods will not get fired for test case classes
+# that inherit from this class -- even if the class inherits from *both*
+# unittest.TestCase and LoggingTestCase.
+#
+# FIXME: Rename this class to LoggingTestCaseBase to be sure that
+# the unittest module does not interpret this class as a unittest
+# test case itself.
+class LoggingTestCase(unittest.TestCase):
+
+ """Supports end-to-end unit-testing of log messages.
+
+ Sample usage:
+
+ class SampleTest(LoggingTestCase):
+
+ def test_logging_in_some_method(self):
+ call_some_method() # Contains calls to _log.info(), etc.
+
+ # Check the resulting log messages.
+ self.assertLog(["INFO: expected message #1",
+ "WARNING: expected message #2"])
+
+ """
+
+ def setUp(self):
+ self._log = LogTesting.setUp(self)
+
+ def tearDown(self):
+ self._log.tearDown()
+
+ def logMessages(self):
+ """Return the current list of log messages."""
+ return self._log.messages()
+
+ # FIXME: Add a clearMessages() method for cases where the caller
+ # deliberately doesn't want to assert every message.
+
+ # See the code comments preceding LogTesting.assertMessages() for
+ # an explanation of why we clear the array of messages after
+ # asserting its contents.
+ def assertLog(self, messages):
+ """Assert the current array of log messages, and clear its contents.
+
+ Args:
+ messages: A list of log message strings.
+
+ """
+ self._log.assertMessages(messages)
diff --git a/pool/shard009/Python/0087603_Dislike.py b/pool/shard009/Python/0087603_Dislike.py
new file mode 100644
index 0000000000000000000000000000000000000000..102454d6da807214fcbfba6bd6746265ecd01203
--- /dev/null
+++ b/pool/shard009/Python/0087603_Dislike.py
@@ -0,0 +1,37 @@
+from .Component import Component
+from django.template.response import TemplateResponse
+from django.http import JsonResponse
+
+
+class Dislike(Component):
+
+ def __init__(self):
+ super(Dislike, self).__init__()
+
+ self.attributeTypes['userName'] = 'str'
+ self.attributeTypes['postID'] = 'str'
+ self.attributeTypes['DB'] = 'Database'
+
+ def __str__(self):
+ return "Dislike"
+
+ def description(self):
+ return "User Dislikes a post given a userID and postID"
+
+ def createHTML(self, request, instanceID):
+ return TemplateResponse(request, 'dislike.html', {}).render()
+
+ def handleAJAXRequest(self, request, instanceID):
+ if request.method == 'POST':
+ result = self['DB'].manageDislike(request)
+ return JsonResponse(result)
+
+
+ def execute(self):
+
+ result = self['DB'].addDislike(self['userName'], self['postID'])
+
+ if result == True:
+ return 'Dislike successful
'
+ else:
+ return 'Dislike unsuccessful
'
diff --git a/pool/shard009/Python/0087604_hubstorage_writer.py b/pool/shard009/Python/0087604_hubstorage_writer.py
new file mode 100644
index 0000000000000000000000000000000000000000..037cb459bb879d090cc3fa2acc6e53d08878fd6b
--- /dev/null
+++ b/pool/shard009/Python/0087604_hubstorage_writer.py
@@ -0,0 +1,68 @@
+import six
+from exporters.writers.base_writer import BaseWriter
+
+
+class HubstorageWriter(BaseWriter):
+ """
+ This writer sends items into Scrapinghub Hubstorage collection.
+
+ - apikey (str)
+ API key with access to the project where the items are being generated.
+
+ - project_id (str)
+ Id of the project.
+
+ - collection_name (str)
+ Name of the collection of items.
+
+ - key_field (str)
+ Record field which should be used as Hubstorage item key
+ """
+
+ # List of options to set up the writer
+ supported_options = {
+ "project_id": {
+ 'type': six.string_types,
+ 'help': 'Id of the project'
+ },
+ "collection_name": {
+ 'type': six.string_types,
+ 'help': 'Name of the collection of items'
+ },
+ 'key_field': {
+ 'type': six.string_types,
+ 'default': '_key',
+ 'help': 'Record field which should be used as Hubstorage item key'
+ },
+ 'apikey': {
+ 'type': six.string_types,
+ 'help': 'Hubstorage API key',
+ 'env_fallback': 'EXPORTERS_HS_APIKEY'
+ }
+ }
+
+ def __init__(self, *args, **kwargs):
+ super(HubstorageWriter, self).__init__(*args, **kwargs)
+ self.project_id = self.read_option('project_id')
+ self.collection_name = self.read_option('collection_name')
+ self.key_field = self.read_option('key_field')
+ self.collection = self._get_collection()
+ self.collection_writer = self.collection.create_writer()
+ self.logger.info('Will write items into project {}, '
+ ' collection {}'.format(self.project_id, self.collection_name))
+
+ def write_batch(self, batch):
+ for item in batch:
+ item_key = item[self.key_field]
+ self.collection_writer.write(dict(item, _key=item_key))
+ self.increment_written_items()
+ self._check_items_limit()
+
+ def flush(self):
+ self.collection_writer.flush()
+
+ def _get_collection(self):
+ import hubstorage
+ client = hubstorage.HubstorageClient(self.read_option('apikey'))
+ project = client.get_project(self.project_id)
+ return project.collections.new_store(self.collection_name)
diff --git a/pool/shard009/Python/0087606_random.py b/pool/shard009/Python/0087606_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..1474a2751d5025e7ed4fb8bdf5e36a9bd38d1312
--- /dev/null
+++ b/pool/shard009/Python/0087606_random.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python
+# -*- coding: utf8 -*-
+# *****************************************************************
+# ** PTS -- Python Toolkit for working with SKIRT **
+# ** © Astronomical Observatory, Ghent University **
+# *****************************************************************
+
+## \package pts.core.tools.random Defines a global random number generator and contains some functions to save and
+# load its state to/from file.
+
+# -----------------------------------------------------------------
+
+# Ensure Python 3 functionality
+from __future__ import absolute_import, division, print_function
+
+# Import standard modules
+import numpy as np
+
+# Import the relevant PTS classes and modules
+from . import serialization
+from ..basics.log import log
+
+# -----------------------------------------------------------------
+
+# Based on: http://stackoverflow.com/questions/20911147/choose-random-seed-and-save-it
+
+# -----------------------------------------------------------------
+
+# IMPORTANT: (from NumPy docs)
+
+# randint (low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive). # EXCLUSIVE END !
+# random_integers (low[, high, size]) Random integers of type np.int between low and high, inclusive. # INCLUSIVE END !
+
+# THE LATTER IS DEPRECATED : WE ARE GOING TO USE RANDINT(MIN, MAX + 1) THEN
+
+# -----------------------------------------------------------------
+
+# SKIRT seed
+skirt_seed = 4357
+
+# -----------------------------------------------------------------
+
+# The global random genereator = a singleton of this module
+prng = None
+
+# -----------------------------------------------------------------
+
+def init_prng(seed=None):
+
+ """
+ This function ...
+ :return:
+ """
+
+ # Inform the user
+ log.info("Initializing the random number generator ...")
+
+ global prng
+
+ # Create a new random generator
+ prng = np.random.RandomState(seed)
+
+# -----------------------------------------------------------------
+
+def setup_prng(seed):
+
+ """
+ This function ...
+ :param seed:
+ :return:
+ """
+
+ # Inform the user
+ log.info("Seeding the random number generator ...")
+
+ # Give seed
+ prng.seed(seed)
+
+ # Return the instance
+ return prng
+
+# -----------------------------------------------------------------
+
+def get_state():
+
+ """
+ This function ...
+ :return:
+ """
+
+ # Return the state
+ return prng.get_state()
+
+# -----------------------------------------------------------------
+
+def set_state(state):
+
+ """
+ This function ...
+ :return:
+ """
+
+ # Set the random state
+ prng.set_state(state)
+
+# -----------------------------------------------------------------
+
+def save_state(path):
+
+ """
+ This function ...
+ :return:
+ """
+
+ # Inform the user
+ log.info("Saving the state of the random number generator to '" + path + "' ...")
+
+ state = prng.get_state()
+ serialization.dump(state, path)
+
+# -----------------------------------------------------------------
+
+def load_state(path):
+
+ """
+ This function ...
+ :param path:
+ :return:
+ """
+
+ # Inform the user
+ log.info("Loading the state of the random number generator from '" + path + "' ...")
+
+ state = serialization.load(path)
+ prng.set_state(state)
+
+# -----------------------------------------------------------------
+
+# Initialize the global random generator
+init_prng()
+
+# -----------------------------------------------------------------
diff --git a/pool/shard009/Python/0087607_tmserver.py b/pool/shard009/Python/0087607_tmserver.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fd55ed7c81b78b31fa81c1906b85b40d78a3fbf
--- /dev/null
+++ b/pool/shard009/Python/0087607_tmserver.py
@@ -0,0 +1,88 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright © 2012 - 2017 Michal Čihař
+#
+# This file is part of Weblate
+#
+# 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 __future__ import unicode_literals
+
+from django.conf import settings
+
+from weblate.trans.machine.base import MachineTranslation, MissingConfiguration
+
+from six.moves.urllib.parse import quote
+
+
+class TMServerTranslation(MachineTranslation):
+ """tmserver machine translation support."""
+ name = 'tmserver'
+
+ def __init__(self):
+ """Check configuration."""
+ super(TMServerTranslation, self).__init__()
+ self.url = self.get_server_url()
+
+ def get_server_url(self):
+ """Return URL of a server."""
+ if settings.MT_TMSERVER is None:
+ raise MissingConfiguration(
+ 'Not configured tmserver URL'
+ )
+
+ return settings.MT_TMSERVER.rstrip('/')
+
+ def convert_language(self, language):
+ """Convert language to service specific code."""
+ return language.replace('-', '_').lower()
+
+ def download_languages(self):
+ """Download list of supported languages from a service."""
+ data = self.json_req('{0}/languages/'.format(self.url))
+ return [
+ (src, tgt)
+ for src in data['sourceLanguages']
+ for tgt in data['targetLanguages']
+ ]
+
+ def is_supported(self, source, language):
+ """Check whether given language combination is supported."""
+ if len(self.supported_languages) == 0:
+ # Fallback for old tmserver which does not export list of
+ # supported languages
+ return True
+ return (source, language) in self.supported_languages
+
+ def download_translations(self, source, language, text, unit, user):
+ """Download list of possible translations from a service."""
+ url = '{0}/{1}/{2}/unit/{3}'.format(
+ self.url,
+ quote(source),
+ quote(language),
+ quote(text[:500].replace('\r', ' ').encode('utf-8'))
+ )
+ response = self.json_req(url)
+
+ return [(line['target'], line['quality'], self.name, line['source'])
+ for line in response]
+
+
+class AmagamaTranslation(TMServerTranslation):
+ """Specific instance of tmserver ran by Virtaal authors."""
+ name = 'Amagama'
+
+ def get_server_url(self):
+ return 'https://amagama-live.translatehouse.org/api/v1'
diff --git a/pool/shard009/Python/0087608_storage_test.py b/pool/shard009/Python/0087608_storage_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e824cfe39d763ea7a9843daaee6ecce6cab57f6
--- /dev/null
+++ b/pool/shard009/Python/0087608_storage_test.py
@@ -0,0 +1,56 @@
+import os
+import unittest
+from unittest.mock import patch
+
+from blivet import util
+from blivet.size import Size
+
+from pyanaconda.storage.osinstall import InstallerStorage
+from pyanaconda.ui.lib.storage import reset_storage
+
+
+@unittest.skip("not working")
+@unittest.skipUnless(os.geteuid() == 0, "requires root privileges")
+class SetupDiskImagesNonZeroSizeTestCase(unittest.TestCase):
+ """
+ Test if size of disk images is > 0. Related: rhbz#1252703.
+ This test emulates how anaconda configures its storage.
+ """
+
+ disks = {"disk1": Size("2 GiB")}
+
+ def setUp(self):
+ self.storage = InstallerStorage()
+
+ # anaconda first configures disk images
+ for (name, size) in iter(self.disks.items()):
+ path = util.create_sparse_tempfile(name, size)
+ self.storage.disk_images[name] = path
+
+ # at this point the DMLinearDevice has correct size
+ self.storage.setup_disk_images()
+
+ # anaconda calls initialize_storage regardless of whether or not
+ # this is an image install. Somewhere along the line this will
+ # execute setup_disk_images() once more and the DMLinearDevice created
+ # in this second execution has size 0
+ with patch('blivet.flags'):
+ reset_storage()
+
+ def tearDown(self):
+ self.storage.reset()
+ self.storage.devicetree.teardown_disk_images()
+ for fn in self.storage.disk_images.values():
+ if os.path.exists(fn):
+ os.unlink(fn)
+
+ def runTest(self):
+ disk = self.storage.disks[0]
+ self.assertEqual(disk.name, list(self.disks.keys())[0])
+ for d in self.storage.devicetree.devices:
+ if d == disk or disk.depends_on(d):
+ self.assertTrue(d.size > 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/pool/shard009/Python/0087612_wpa_eapol.py b/pool/shard009/Python/0087612_wpa_eapol.py
new file mode 100644
index 0000000000000000000000000000000000000000..af17ab5388ed253504f420ffd1cf134d2008160f
--- /dev/null
+++ b/pool/shard009/Python/0087612_wpa_eapol.py
@@ -0,0 +1,35 @@
+
+# http://trac.secdev.org/scapy/ticket/104
+
+# kamene.contrib.description = WPA EAPOL dissector
+# kamene.contrib.status = loads
+
+from kamene.packet import *
+from kamene.fields import *
+from kamene.layers.l2 import *
+
+class WPA_key(Packet):
+ name = "WPA_key"
+ fields_desc = [ ByteField("descriptor_type", 1),
+ ShortField("key_info",0),
+ LenField("len", None, "H"),
+ StrFixedLenField("replay_counter", "", 8),
+ StrFixedLenField("nonce", "", 32),
+ StrFixedLenField("key_iv", "", 16),
+ StrFixedLenField("wpa_key_rsc", "", 8),
+ StrFixedLenField("wpa_key_id", "", 8),
+ StrFixedLenField("wpa_key_mic", "", 16),
+ LenField("wpa_key_length", None, "H"),
+ StrLenField("wpa_key", "", length_from=lambda pkt:pkt.wpa_key_length) ]
+ def extract_padding(self, s):
+ l = self.len
+ return s[:l],s[l:]
+ def hashret(self):
+ return chr(self.type)+self.payload.hashret()
+ def answers(self, other):
+ if isinstance(other,WPA_key):
+ return 1
+ return 0
+
+
+bind_layers( EAPOL, WPA_key, type=3)
diff --git a/pool/shard009/Python/0087614_password_migration_kit.py b/pool/shard009/Python/0087614_password_migration_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..c259bed195bb5d2d025ba54e12fed6071223a036
--- /dev/null
+++ b/pool/shard009/Python/0087614_password_migration_kit.py
@@ -0,0 +1,189 @@
+# -*- coding: utf-8 -*-
+##
+## Every db-related function of module webmessage
+##
+## This file is part of Invenio.
+## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
+##
+## Invenio 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.
+##
+## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
+## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+""" Migration from local clear password [v0.92.1] to local encrypted
+ password_migration_kit
+Usage: python password_migration_kit.py
+This utility will encrypt all the local passwords stored in the database.
+The encryption is not optional with the current Invenio code if local accounts
+are used.
+A backup copy of the user table will be created before the migration just in
+case something goes wrong.
+"""
+
+__revision__ = "$Id$"
+
+from invenio.dbquery import run_sql
+from invenio.textutils import wrap_text_in_a_box
+import sys
+
+def migrate_passwords():
+ print wrap_text_in_a_box(title="Password migration kit (for Invenio prior to v0.92.1)", style='conclusion')
+ print "Checking your installation..."
+ if __check_update_possibility():
+ print "Tables are OK."
+ else:
+ print "No need to update."
+ sys.exit(1)
+ admin_pwd = __get_admin_pwd()
+ print "There are %i passwords to migrate (including guest users)" % __count_current_passwords()
+ print "========================================================="
+ print "Creating backup...",
+ sys.stdout.flush()
+ if __creating_backup():
+ print "OK"
+ else:
+ __print_error()
+ print "Migrating all Null password to ''...",
+ sys.stdout.flush()
+ if __migrate_passwords_from_null_to_empty_quotes():
+ print "OK"
+ else:
+ __print_error(True)
+ print "Changing the column type from string to blob...",
+ sys.stdout.flush()
+ if __migrate_column_from_string_to_blob():
+ print "OK"
+ else:
+ __print_error(True)
+ print "Encrypting passwords...",
+ sys.stdout.flush()
+ if __encrypt_password():
+ print "OK"
+ else:
+ __print_error(True)
+ print "Checking that admin could enter...",
+ sys.stdout.flush()
+ if __check_admin(admin_pwd):
+ print "OK"
+ else:
+ __print_error(True)
+ print "Removing backup...",
+ sys.stdout.flush()
+ if __removing_backup():
+ print "OK"
+ else:
+ __print_error()
+ print "========================================================="
+ print "Migration to encrypted local passwords has been successful."
+
+def __check_update_possibility():
+ res = run_sql("SHOW COLUMNS FROM user LIKE 'password'");
+ if res:
+ return res[0][1] not in ('tinyblob', 'blob')
+ print "User table is broken or Invenio Database is not functional."
+
+def __count_current_passwords():
+ query = "SELECT count(*) FROM user"
+ return run_sql(query)[0][0]
+
+def __get_admin_pwd():
+ query = "SELECT password FROM user WHERE nickname='admin'"
+ return run_sql(query)[0][0]
+
+def __migrate_passwords_from_null_to_empty_quotes():
+ query = "UPDATE user SET password='' WHERE password IS NULL"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __migrate_column_from_string_to_blob():
+ query = "ALTER TABLE user CHANGE password password BLOB NOT NULL"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __encrypt_password():
+ query = "UPDATE user SET password=AES_ENCRYPT(email,password)"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __check_admin(admin_pwd):
+ query = "SELECT nickname FROM user WHERE nickname='admin' AND password=AES_ENCRYPT(email, %s)"
+ try:
+ if run_sql(query, (admin_pwd, ))[0][0] == 'admin':
+ return True
+ else:
+ return False
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+
+def __creating_backup():
+ query = "CREATE TABLE user_backup (PRIMARY KEY id (id)) SELECT * FROM user"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __removing_backup():
+ query = "DROP TABLE user_backup"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __restoring_from_backup():
+ query = "UPDATE user SET password=''"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ query = "ALTER TABLE user CHANGE password password varchar(20) NULL default NULL"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ query = "UPDATE user,user_backup SET user.password=user_backup.password WHERE user.id=user_backup.id AND user.nickname=user_backup.nickname"
+ try:
+ run_sql(query)
+ except Exception, msg:
+ print 'The query "%s" produced: %s' % (query, msg)
+ return False
+ return True
+
+def __print_error(restore_backup=False):
+ print wrap_text_in_a_box("The kit encountered errors in migrating passwords. Please contact The Invenio developers in order to get support providing all the printed messages.")
+ if restore_backup:
+ if __restoring_from_backup():
+ print wrap_text_in_a_box("Passwords were restored from the backup, but you still need to migrate them in order to use this version of Invenio.")
+ else:
+ print wrap_text_in_a_box("The kit was't unable to restore passwords from the backup")
+ sys.exit(1)
+
+if __name__ == '__main__':
+ migrate_passwords()
diff --git a/pool/shard009/Python/0087616_pilconvert.py b/pool/shard009/Python/0087616_pilconvert.py
new file mode 100644
index 0000000000000000000000000000000000000000..859d4ce431068c3626bbcfa628020966534f68b1
--- /dev/null
+++ b/pool/shard009/Python/0087616_pilconvert.py
@@ -0,0 +1,96 @@
+#!/home/jhjguxin/blogserver/bin/python
+#
+# The Python Imaging Library.
+# $Id$
+#
+# convert image files
+#
+# History:
+# 0.1 96-04-20 fl Created
+# 0.2 96-10-04 fl Use draft mode when converting images
+# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
+# 0.4 97-01-18 fl Made optimize an option (PNG, JPEG)
+# 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter)
+#
+
+import site
+import getopt, string, sys
+
+from PIL import Image
+
+def usage():
+ print "PIL Convert 0.5/1998-12-30 -- convert image files"
+ print "Usage: pilconvert [option] infile outfile"
+ print
+ print "Options:"
+ print
+ print " -c convert to format (default is given by extension)"
+ print
+ print " -g convert to greyscale"
+ print " -p convert to palette image (using standard palette)"
+ print " -r convert to rgb"
+ print
+ print " -o optimize output (trade speed for size)"
+ print " -q