diff --git a/pool/shard006/Python/0057587_dnsimple.py b/pool/shard006/Python/0057587_dnsimple.py new file mode 100644 index 0000000000000000000000000000000000000000..143d3af69ad9b962daaabcc49d7d45c252990e26 --- /dev/null +++ b/pool/shard006/Python/0057587_dnsimple.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +""" +Updater for https://dnsimple.com/ compatible dyndns services. + +This module depends on the python package dnsimple-dyndns from +https://pypi.python.org/pypi/dnsimple-dyndns +If installed, dyndnsc will be able to utilize it. + +Since dnsimple.com is a paid service, I have not had a chance to test this yet. +""" + +import logging + +from dnsimple_dyndns import DNSimple # @UnresolvedImport pylint: disable=import-error + +from .base import UpdateProtocol + +LOG = logging.getLogger(__name__) + + +class UpdateProtocolDnsimple(UpdateProtocol): + """Protocol handler for https://dnsimple.com/ .""" + + configuration_key = "dnsimple" + + def __init__(self, hostname, key, url=None, **kwargs): + """Initialize.""" + self._recordname, _, self._domain = hostname.partition(".") + self.hostname = hostname + self.handler = DNSimple(domain=self._domain, + domain_token=key) + if url is not None: + # The url must be a format string like this: + # 'https://dnsimple.com/domains/%s/records' + self.handler._baseurl = url % self._domain + + super(UpdateProtocolDnsimple, self).__init__() + + def update(self, ip): + """Update the IP on the remote service.""" + return self.handler.update_record(name=self._recordname, + address=ip) diff --git a/pool/shard006/Python/0057590_joystick.py b/pool/shard006/Python/0057590_joystick.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d636b4db4b8569df73caf5e24587ded6b0b476 --- /dev/null +++ b/pool/shard006/Python/0057590_joystick.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python + +import pygame +import sys + +import multiprocessing +import Queue #needed separately for the Empty exception +import time, datetime + +class JoystickProcess(multiprocessing.Process): + def __init__(self, outputqueue): + multiprocessing.Process.__init__(self) + self.outputqueue = outputqueue + self.exit = multiprocessing.Event() + self.sleeping = multiprocessing.Event() + + def shutdown(self): + self.exit.set() + + def sleep(self): + self.sleeping.set() + + def wake(self): + self.sleeping.clear() + + def run(self): + try: + pygame.init() + self.j = pygame.joystick.Joystick(0) + self.j.init() + print 'Found Joystick: ', self.j.get_name() + sys.stdout.flush() + + except Exception, e: + print "exception in joystick:", e + self.sleep() + time.sleep(0.1) + sys.stdout.flush() + + while not self.exit.is_set(): + + if self.sleeping.is_set(): + time.sleep(0.1) + continue + + data = self.get() + + if (data is not None): + tstamp = datetime.datetime.now() + try: + self.outputqueue.put((tstamp, data), False) + except Queue.Full: + continue + + def get(self): + out = [] + pygame.event.pump() + + #Read input from joysticks + for i in range(self.j.get_numaxes()): + out.append(self.j.get_axis(i)) + + #Read input from buttons + for i in range(self.j.get_numbuttons()): + out.append(self.j.get_button(i)) + + return out + +if __name__ == '__main__': + + q = multiprocessing.Queue(maxsize=1) + j = JoystickProcess(q) + j.start() + + while(1): + try: + tstamp, data = q.get(False) + print tstamp, data + sys.stdout.flush() + except Queue.Empty: + pass diff --git a/pool/shard006/Python/0057591_tests.py b/pool/shard006/Python/0057591_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..4a5ddfe6b093cb6a2decb8972fb5b1c73f5550ff --- /dev/null +++ b/pool/shard006/Python/0057591_tests.py @@ -0,0 +1,101 @@ +from django_dynamic_fixture import G + +from fluent_contents.plugins.rawhtml.models import RawHtmlItem + +from icekit import models +from icekit.page_types.layout_page.models import LayoutPage +from icekit.utils import fluent_contents + + +from .. import base_tests + + +class PagesAPITests(base_tests._BaseAPITestCase): + API_NAME = 'page-api' + API_IS_PUBLIC_READ = True + + def setUp(self): + super(PagesAPITests, self).setUp() + + self.layout_1 = G( + models.Layout, + template_name='icekit/layouts/default.html', + ) + self.layoutpage_1 = LayoutPage.objects.create( + author=self.superuser, + title='Test LayoutPage', + layout=self.layout_1, + ) + self.content_instance_1 = fluent_contents.create_content_instance( + RawHtmlItem, + self.layoutpage_1, + html='test 1' + ) + self.content_instance_2 = fluent_contents.create_content_instance( + RawHtmlItem, + self.layoutpage_1, + html='test 2' + ) + self.content_instance_3 = fluent_contents.create_content_instance( + RawHtmlItem, + self.layoutpage_1, + html='test 3' + ) + + def test_list_pages_with_get_and_filtered_fields(self): + self.layoutpage_1.publish() + response = self.client.get(self.listing_url() + '?fields=title') + self.assertEqual(200, response.status_code) + self.assertEqual( + { + 'count': 1, + 'next': None, + 'previous': None, + 'results': [{ + 'title': 'Test LayoutPage', + }] + }, + response.data) + + def test_page_api(self): + self.layoutpage_1.publish() + for j in range(20): + published_layoutpage = LayoutPage.objects.create( + author=self.superuser, + title='Test LayoutPage %s' % j, + layout=self.layout_1, + ) + published_layoutpage.publish() + + LayoutPage.objects.create( + author=self.superuser, + title='Draft LayoutPage %s' % j, + layout=self.layout_1, + ) + + response = self.client.get(self.listing_url()) + self.assertEqual(response.status_code, 200) + self.assertEqual(len(response.data['results']), 5) + self.assertEqual(response.data['count'], 21) + response = self.client.get(self.detail_url(self.layoutpage_1.id)) + self.assertEqual(response.status_code, 404) + response = self.client.get( + self.detail_url(self.layoutpage_1.get_published().id)) + self.assertEqual(response.status_code, 200) + self.assertEqual(len(response.data), 6) + for key in response.data.keys(): + if key is not 'content': + self.assertEqual( + response.data[key], + getattr(self.layoutpage_1.get_published(), key)) + self.assertEqual(len(response.data['content']), 3) + for number, item in enumerate(response.data['content'], 1): + self.assertEqual( + item['content'], + getattr(self, 'content_instance_%s' % number).html) + + def test_api_user_permissions_are_correct(self): + self.layoutpage_1.publish() + page_published_id = self.layoutpage_1.get_published().pk + self.assert_api_user_permissions_are_correct( + page_published_id, models.Layout) diff --git a/pool/shard006/Python/0057592_init__.py b/pool/shard006/Python/0057592_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..186416580eac636779bfea5303b7c2c8f262adfd --- /dev/null +++ b/pool/shard006/Python/0057592_init__.py @@ -0,0 +1,66 @@ +import os + +from flask import Flask + +from samantha import config + +# configure Flask +app = Flask(__name__) +app.secret_key = os.urandom(32) + +# +# Configure SQLAlchemy +# @see http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/ +# +from sqlalchemy import create_engine +from sqlalchemy.orm import scoped_session, sessionmaker +from sqlalchemy.ext.declarative import declarative_base + +engine = create_engine( + config.get('SQLALCHEMY_DATABASE_URI'), + convert_unicode=True +) +session = scoped_session( + sessionmaker( + autocommit=False, + autoflush=False, + bind=engine + ) +) +Base = declarative_base() +Base.query = session.query_property() + + +@app.teardown_appcontext +def shutdown_session(exception=None): + session.remove() + + +# +# Configure Celery +# @see http://flask.pocoo.org/docs/0.10/patterns/celery/ +# +from celery import Celery + + +def make_celery(app): + celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) + celery.conf.update(app.config) + TaskBase = celery.Task + + class ContextTask(TaskBase): + abstract = True + + def __call__(self, *args, **kwargs): + with app.app_context(): + return TaskBase.__call__(self, *args, **kwargs) + + celery.Task = ContextTask + return celery + +app.config.update( + CELERY_BROKER_URL=config.get('CELERY_BROKER_URL'), + CELERY_RESULT_BACKEND=config.get('CELERY_BROKER_URL'), + CELERY_ACCEPT_CONTENT=config.get('CELERY_ACCEPT_CONTENT').split(',') +) +celery = make_celery(app) diff --git a/pool/shard006/Python/0057597_base.py b/pool/shard006/Python/0057597_base.py new file mode 100644 index 0000000000000000000000000000000000000000..c48291f137ff189255aac2357434828ae2c4d297 --- /dev/null +++ b/pool/shard006/Python/0057597_base.py @@ -0,0 +1,57 @@ +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import object + + +def not_implemented(method): + raise NotImplementedError("Provider does not support '%s' " + "method." % method) + + +class BaseProviderBuilder(object): + def build(self, region=None): + not_implemented("build") + + +class BaseProvider(object): + def get_stack(self, stack_name, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("get_stack") + + def create_stack(self, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("create_stack") + + def update_stack(self, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("update_stack") + + def destroy_stack(self, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("destroy_stack") + + def get_stack_status(self, stack_name, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("get_stack_status") + + def get_outputs(self, stack_name, *args, **kwargs): + # pylint: disable=unused-argument + not_implemented("get_outputs") + + def get_output(self, stack_name, output): + # pylint: disable=unused-argument + return self.get_outputs(stack_name)[output] + + +class Template(object): + """A value object that represents a CloudFormation stack template, which + could be optionally uploaded to s3. + + Presence of the url attribute indicates that the template was uploaded to + S3, and the uploaded template should be used for CreateStack/UpdateStack + calls. + """ + def __init__(self, url=None, body=None): + self.url = url + self.body = body diff --git a/pool/shard006/Python/0057598_test_configuration.py b/pool/shard006/Python/0057598_test_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..04fc77120e6d3a46bd1019ca994c3e40cbf0c869 --- /dev/null +++ b/pool/shard006/Python/0057598_test_configuration.py @@ -0,0 +1,21 @@ +import os + +from paste.deploy.loadwsgi import appconfig + +from testery.tests import TestCase + + +class TestConfiguration(TestCase): + """Check that the ini files track the same configuration types.""" + + def setUp(self): + super(TestConfiguration, self).setUp() + here = os.path.dirname(__file__) + self.project_root = os.path.abspath(os.path.join(here, '..', '..')) + + def test_development_ini(self): + test_ini = os.path.join(self.project_root, 'test.ini') + test_settings = appconfig('config:' + test_ini) + dev_ini = os.path.join(self.project_root, 'development.ini') + dev_settings = appconfig('config:' + dev_ini) + self.assertEqual(test_settings.keys(), dev_settings.keys()) diff --git a/pool/shard006/Python/0057604_test_hinge.py b/pool/shard006/Python/0057604_test_hinge.py new file mode 100644 index 0000000000000000000000000000000000000000..0e74e16e4c102b7e190e3ba0294805963ea10ab2 --- /dev/null +++ b/pool/shard006/Python/0057604_test_hinge.py @@ -0,0 +1,138 @@ +import unittest + +import numpy +import six + +import chainer +from chainer.backends import cuda +from chainer import functions +from chainer import gradient_check +from chainer import testing +from chainer.testing import attr + + +@testing.parameterize(*testing.product_dict( + [{'dtype': numpy.float16, + 'forward_options': {'rtol': 3e-3, 'atol': 3e-3}, + 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}}, + {'dtype': numpy.float32, + 'forward_options': {}, + 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}}, + {'dtype': numpy.float64, + 'forward_options': {}, + 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}}, + ], + [{'reduce': 'no'}, + {'reduce': 'mean'}, + ], + [{'norm': 'L1'}, + {'norm': 'L2'}, + ], + [{'label_dtype': numpy.int8}, + {'label_dtype': numpy.int16}, + {'label_dtype': numpy.int32}, + {'label_dtype': numpy.int64}, + ], +)) +class TestHinge(unittest.TestCase): + + def setUp(self): + self._config_user = chainer.using_config('dtype', self.dtype) + self._config_user.__enter__() + + shape = (10, 5) + self.x = numpy.random.uniform(-1, 1, shape).astype(self.dtype) + # Avoid values around -1.0 for stability + self.x[numpy.logical_and(-1.01 < self.x, self.x < -0.99)] = 0.5 + self.t = numpy.random.randint( + 0, shape[1], shape[:1]).astype(self.label_dtype) + if self.reduce == 'no': + self.gy = numpy.random.uniform( + -1, 1, self.x.shape).astype(self.dtype) + + def tearDown(self): + self._config_user.__exit__(None, None, None) + + def check_forward(self, x_data, t_data): + x_val = chainer.Variable(x_data) + t_val = chainer.Variable(t_data) + loss = functions.hinge(x_val, t_val, self.norm, self.reduce) + if self.reduce == 'mean': + self.assertEqual(loss.data.shape, ()) + else: + self.assertEqual(loss.data.shape, self.x.shape) + self.assertEqual(loss.data.dtype, self.dtype) + loss_value = cuda.to_cpu(loss.data) + + # Compute expected value + for i in six.moves.range(self.x.shape[0]): + self.x[i, self.t[i]] *= -1 + for i in six.moves.range(self.x.shape[0]): + for j in six.moves.range(self.x.shape[1]): + self.x[i, j] = max(0, 1.0 + self.x[i, j]) + if self.norm == 'L1': + loss_expect = self.x + elif self.norm == 'L2': + loss_expect = self.x ** 2 + if self.reduce == 'mean': + loss_expect = numpy.sum(loss_expect) / self.x.shape[0] + + testing.assert_allclose( + loss_expect, loss_value, **self.forward_options) + + def test_forward_cpu(self): + self.check_forward(self.x, self.t) + + @attr.gpu + def test_forward_gpu(self): + self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t)) + + def check_backward(self, x_data, t_data): + def f(x, t): + return functions.hinge(x, t, self.norm) + + gradient_check.check_backward( + f, (x_data, t_data), None, dtype='d', **self.backward_options) + + def test_backward_cpu(self): + self.check_backward(self.x, self.t) + + @attr.gpu + def test_backward_gpu(self): + self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t)) + + +class TestHingeInvalidOption(unittest.TestCase): + + def setUp(self): + self.x = numpy.random.uniform(-1, 1, (10, 5)).astype(numpy.float32) + self.t = numpy.random.randint(0, 5, (10,)).astype(numpy.int32) + + def check_invalid_norm_option(self, xp): + x = xp.asarray(self.x) + t = xp.asarray(self.t) + with self.assertRaises(NotImplementedError): + functions.hinge(x, t, 'invalid_norm', 'mean') + + def test_invalid_norm_option_cpu(self): + self.check_invalid_norm_option(numpy) + + @attr.gpu + def test_invalid_norm_option_gpu(self): + self.check_invalid_norm_option(cuda.cupy) + + def check_invalid_reduce_option(self, xp): + x = xp.asarray(self.x) + t = xp.asarray(self.t) + with self.assertRaises(ValueError): + functions.hinge(x, t, 'L1', 'invalid_option') + + def test_invalid_reduce_option_cpu(self): + self.check_invalid_reduce_option(numpy) + + @attr.gpu + def test_invalid_reduce_option_gpu(self): + self.check_invalid_reduce_option(cuda.cupy) + + +testing.run_module(__name__, __file__) diff --git a/pool/shard006/Python/0057605_stats_randint.py b/pool/shard006/Python/0057605_stats_randint.py new file mode 100644 index 0000000000000000000000000000000000000000..c422dcd5cb92a483ad6aa6dbda6a210fb3df4b2d --- /dev/null +++ b/pool/shard006/Python/0057605_stats_randint.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""stats_randint.py: Demonstrate how ``scipy.stats.randint`` works. +""" +from scipy.stats import randint + +# pylint: disable=invalid-name + +# Define a dice model. +low = 1 +high = 7 +dice = randint(low, high) + +# Compute moments. +mean, var, skew, kurt = dice.stats(moments='mvsk') + +print(f"mean: {float(mean):.3f}") +print(f"median: {dice.median():.3f}") +print(f"var: {float(var):.3f}") +print(f"skew: {float(skew):.3f}") +print(f"kurt: {float(kurt):.3f}") +print(f"std: {dice.std():.3f}") # Or np.sqrt(var). diff --git a/pool/shard006/Python/0057607_foomodulegen4.py b/pool/shard006/Python/0057607_foomodulegen4.py new file mode 100644 index 0000000000000000000000000000000000000000..3930cdefae380e853883e4d7a7ff9bb7b3233225 --- /dev/null +++ b/pool/shard006/Python/0057607_foomodulegen4.py @@ -0,0 +1,76 @@ +#! /usr/bin/env python +from __future__ import unicode_literals, print_function + +import sys +import os.path + +import pybindgen +from pybindgen.module import MultiSectionFactory +from pybindgen import (FileCodeSink) + +import foomodulegen_split +import foomodulegen_common + + +class MyMultiSectionFactory(MultiSectionFactory): + + def __init__(self, main_file_name): + self.main_file_name = main_file_name + self.main_sink = FileCodeSink(open(main_file_name, "wt")) + self.header_name = "foomodule4.h" + header_file_name = os.path.join(os.path.dirname(self.main_file_name), self.header_name) + self.header_sink = FileCodeSink(open(header_file_name, "wt")) + self.section_sinks = {} + + def get_section_code_sink(self, section_name): + if section_name == '__main__': + return self.main_sink + try: + return self.section_sinks[section_name] + except KeyError: + file_name = os.path.join(os.path.dirname(self.main_file_name), "%s.cc" % section_name) + sink = FileCodeSink(open(file_name, "wt")) + self.section_sinks[section_name] = sink + return sink + + def get_main_code_sink(self): + return self.main_sink + + def get_common_header_code_sink(self): + return self.header_sink + + def get_common_header_include(self): + return '"%s"' % self.header_name + + def close(self): + self.header_sink.file.close() + self.main_sink.file.close() + for sink in self.section_sinks.values(): + sink.file.close() + +def my_module_gen(): + out = MyMultiSectionFactory(sys.argv[1]) + root_module = foomodulegen_split.module_init() + root_module.add_exception('exception', foreign_cpp_namespace='std', message_rvalue='%(EXC)s.what()') + foomodulegen_common.customize_module_pre(root_module) + + foomodulegen_split.register_types(root_module) + foomodulegen_split.register_methods(root_module) + foomodulegen_split.register_functions(root_module) + foomodulegen_common.customize_module(root_module) + + root_module.generate(out) + + out.close() + + + +if __name__ == '__main__': + try: + import cProfile as profile + except ImportError: + my_module_gen() + else: + print("** running under profiler", file=sys.stderr) + profile.run('my_module_gen()', 'foomodulegen4.pstat') + diff --git a/pool/shard006/Python/0057610_shell.py b/pool/shard006/Python/0057610_shell.py new file mode 100644 index 0000000000000000000000000000000000000000..89c9a3b01b1caeaf3e6b6fd0eec281670c6d4d78 --- /dev/null +++ b/pool/shard006/Python/0057610_shell.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- + +import re +import types +import logging +import subprocess + +from ..exceptions import (ExecuteRuntimeError, ScriptRuntimeError, + NetworkError) +from .strings import mask_string + + +block_fmt = ("\n============= %(title)s ==========\n%(content)s\n" + "======== END OF %(title)s ========") + + +def execute(cmd, workdir=None, can_fail=True, mask_list=None, + use_shell=False, log=True): + """ + Runs shell command cmd. If can_fail is set to False + ExecuteRuntimeError is raised if command returned non-zero return + code. Otherwise + """ + mask_list = mask_list or [] + repl_list = [("'", "'\\''")] + + if not isinstance(cmd, types.StringType): + import pipes + masked = ' '.join((pipes.quote(i) for i in cmd)) + else: + masked = cmd + masked = mask_string(masked, mask_list, repl_list) + if log: + logging.info("Executing command:\n%s" % masked) + + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, cwd=workdir, + shell=use_shell, close_fds=True) + out, err = proc.communicate() + masked_out = mask_string(out, mask_list, repl_list) + masked_err = mask_string(err, mask_list, repl_list) + if log: + logging.debug(block_fmt % {'title': 'STDOUT', 'content': masked_out}) + + if proc.returncode: + if log: + logging.debug(block_fmt % {'title': 'STDERR', + 'content': masked_err}) + if can_fail: + msg = 'Failed to execute command: %s' % masked_out + raise ExecuteRuntimeError(msg, stdout=out, stderr=err) + return proc.returncode, out + + +class ScriptRunner(object): + _pkg_search = 'rpm -q --whatprovides' + + def __init__(self, ip=None): + self.script = [] + self.ip = ip + + def append(self, s): + self.script.append(s) + + def clear(self): + self.script = [] + + def execute(self, can_fail=True, mask_list=None, log=True): + mask_list = mask_list or [] + repl_list = [("'", "'\\''")] + script = "\n".join(self.script) + + masked = mask_string(script, mask_list, repl_list) + if log: + logging.info("[%s] Executing script:\n%s" % + (self.ip or 'localhost', masked)) + + _PIPE = subprocess.PIPE # pylint: disable=E1101 + if self.ip: + cmd = ["ssh", "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "root@%s" % self.ip, "bash -x"] + else: + cmd = ["bash", "-x"] + obj = subprocess.Popen(cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE, + close_fds=True, shell=False) + + script = "function t(){ exit $? ; } \n trap t ERR \n" + script + out, err = obj.communicate(script) + masked_out = mask_string(out, mask_list, repl_list) + masked_err = mask_string(err, mask_list, repl_list) + if log: + logging.debug(block_fmt % {'title': 'STDOUT', + 'content': masked_out}) + + if obj.returncode: + if log: + logging.debug(block_fmt % {'title': 'STDERR', + 'content': masked_err}) + if can_fail: + pattern = (r'^ssh\:') + if re.search(pattern, err): + raise NetworkError(masked_err, stdout=out, stderr=err) + else: + msg = 'Failed to run remote script: %s' % masked_out + raise ScriptRuntimeError(msg, stdout=out, stderr=err) + return obj.returncode, out + + def template(self, src, dst, varsdict): + with open(src) as fp: + content = fp.read() % varsdict + self.append("cat > %s <<- EOF\n%s\nEOF\n" % (dst, content)) + + def if_not_exists(self, path, command): + self.append("[ -e %s ] || %s" % (path, command)) + + def if_exists(self, path, command): + self.append("[ -e %s ] && %s" % (path, command)) + + def if_installed(self, pkg, command): + self.append("%s %s && %s" % (self._pkg_search, pkg, command)) + + def if_not_installed(self, pkg, command): + self.append("%s %s || %s" % (self._pkg_search, pkg, command)) + + def chown(self, target, uid, gid): + self.append("chown %s:%s %s" % (uid, gid, target)) + + def chmod(self, target, mode): + self.append("chmod %s %s" % (mode, target)) diff --git a/pool/shard006/Python/0057612_node_power_control.py b/pool/shard006/Python/0057612_node_power_control.py new file mode 100644 index 0000000000000000000000000000000000000000..30cb24c86ce1a7d8a1e23408f027b7b4dbeab120 --- /dev/null +++ b/pool/shard006/Python/0057612_node_power_control.py @@ -0,0 +1,52 @@ +#! /usr/bin/env python +# -*- mode: python; coding: utf-8 -*- +# Copyright 2018 the HERA Collaboration +# Licensed under the 2-clause BSD license. + +"""script to control power of node elements (snaps, fem, pam) + +""" + +from hera_mc import mc, cm_utils, node + +valid_part_names = list(node.power_command_part_dict.keys()) + +if __name__ == '__main__': + parser = mc.get_mc_argument_parser() + parser.description = """Power on or off node elements (snaps, fem, pam)""" + parser.add_argument('nodes', help="list of nodes to command " + "(integers, comma-separated, no spaces) or 'active'") + parser.add_argument('parts', help="list of parts to command " + "(comma-separated, no spaces) or 'all'." + " Valid part names are: " + ' ,'.join(valid_part_names) + ".") + parser.add_argument('command', help="command: 'on' or 'off'.") + parser.add_argument('--address', help="address for node server", default=None) + parser.add_argument('--dryrun', help="just print the list of NodePowerCommand " + "objects, do not issue the power commands or log them " + "to the database' [False]", action='store_true') + parser.add_argument('--testing', help="Testing: do not use anything that " + "requires connection to nodes (implies dryrun)' [False]", + action='store_true') + + args = parser.parse_args() + db = mc.connect_to_mc_db(args) + session = db.sessionmaker() + + if args.nodes.lower() == 'active': + from hera_mc import node + node_list = node.get_node_list(nodeServerAddress=args.address) + else: + node_list = cm_utils.listify(args.nodes) + node_list = [int(node) for node in node_list] + + parts_list = cm_utils.listify(args.parts) + + for nodeID in node_list: + command_list = session.node_power_command(nodeID, parts_list, args.command, + nodeServerAddress=args.address, + dryrun=args.dryrun, + testing=args.testing) + if args.testing or args.dryrun: + for cmd in command_list: + print(cmd) + session.commit() diff --git a/pool/shard006/Python/0057613_init__.py b/pool/shard006/Python/0057613_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27319476ae1943fb17c405f220a62a73546abc4c --- /dev/null +++ b/pool/shard006/Python/0057613_init__.py @@ -0,0 +1,48 @@ +#! /usr/bin/env python + +import re +import sys +import argparse + +from .litran import LIT + +__name__ = "litcm" +__doc__ = "Language Identification and Transliteration system for Indian Languages in Roman script code mixed with English" +__author__ = "Irshad Ahmad" +__version__ = "1.0.0" +__license__ = "MIT" +__maintainer__ = "Irshad Ahmad" +__email__ = "irshad.bhat@research.iiit.ac.in" +__status__ = "Beta" +__all__ = ["litran", "indictrans", "wxILP", "main", "blm_models", "decision_trees", "extras"] + +def main(): + all_tags = ['ben', 'eng', 'guj', 'hin', 'kan', 'mal', 'tam', 'tel'] + lang_help = 'Any language combination from the set: [%s]' %'|'.join(all_tags) + parser = argparse.ArgumentParser(prog="litcm", description="Language Identification & Transliteration in Code-Mixing") + parser.add_argument('--v', action='version', version="%(prog)s 1.0") + parser.add_argument('--i', metavar='input', dest="INFILE", type=argparse.FileType('r'), default=sys.stdin, help="") + parser.add_argument('--o', metavar='output', dest="OUTFILE", type=argparse.FileType('w'), default=sys.stdout, help="") + parser.add_argument('--l', metavar='languages', dest='lang_tags', nargs='+', help=lang_help) + parser.add_argument('--t', dest='flag', action='store_true', help="set this flag for back-transliteration of Indic words") + + args = parser.parse_args() + + if args.lang_tags: + labels = [tag.lower() for tag in args.lang_tags] + assert len(labels) >= 2 + assert set(labels).issubset(set(all_tags)) + else: + labels = ['hin', 'eng'] + + lit = LIT(labels, transliteration=args.flag) + for line in args.INFILE: + if not line.strip(): + args.OUTFILE.write('\n') + continue + litsen = lit.identify(line) + args.OUTFILE.write("%s\n" %litsen) + + #close files + args.INFILE.close() + args.OUTFILE.close() diff --git a/pool/shard006/Python/0057617_MySQLInitial.py b/pool/shard006/Python/0057617_MySQLInitial.py new file mode 100644 index 0000000000000000000000000000000000000000..3d38e5b9ebf7db7ed1d3d3935bd58ba7962c1484 --- /dev/null +++ b/pool/shard006/Python/0057617_MySQLInitial.py @@ -0,0 +1,42 @@ +# Copyright 2014 Open Connectome Project (http://openconnecto.me) +# +# 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 MySQLdb +import sys + +# Edit the following: +# MySQLPass - MySQL root user password +# password_here - the password for user(in this case brain) specified in the settings_secret.py file + +def setup(MySQLPass, BrainPass): + + # Assuming ocpdjango (from settings_secret.py) + + db = MySQLdb.connect("localhost","root",MySQLPass) + cursor = db.cursor() + + # Create database for OCP + cursor.execute("create database ocpdjango;") + + # Create users for OCP + cursor.execute("create user 'brain'@'localhost' identified by '" + BrainPass + "';") + cursor.execute("grant all privileges on *.* to 'brain'@'localhost' with grant option;") + + cursor.execute("create user 'brain'@'%' identified by '" + BrainPass + "';") + cursor.execute("grant all privileges on *.* to 'brain'@'%' with grant option;") + + db.close() + +if __name__ == '__main__': + setup(*sys.argv[1:]) diff --git a/pool/shard006/Python/0057619_playerdb.py b/pool/shard006/Python/0057619_playerdb.py new file mode 100644 index 0000000000000000000000000000000000000000..e94e0a0394c04f76b5d47b7ddb847b7b76a566cc --- /dev/null +++ b/pool/shard006/Python/0057619_playerdb.py @@ -0,0 +1,86 @@ +""" + Player datablock generator, written to test an experimental super-2046 DB count + patch. +""" + +import sys +import math + +class PseudoNumber: + _value = None + _digits = None + _decimal_value = None + _converted = None + + def __init__(self, digits=None, value=None): + self._digits = digits + self._decimal_value = int(value) + + self.convert() + + def convert(self): + self._value = '' + + if (self._decimal_value == 0): + self._value = self._digits[0] + return self._value + + digit_count = len(self._digits) - 1 + + start_power = int(math.ceil(self._decimal_value / digit_count)) + temporary = int(self._decimal_value) + for current_power in reversed(range(start_power + 1)): + for current_index, current_digit in enumerate(reversed(self._digits)): + actual_index = digit_count - current_index + actual_value = actual_index * pow(digit_count + 1, current_power) + if (actual_value <= temporary and actual_value != 0): + temporary -= actual_value + self._value += self._digits[actual_index % (digit_count + 1)] + + if (temporary <= 0): + for power in range(current_power): + self._value += self._digits[0] + return self._value + + return self._value + + def __repr__(self): + return self.convert() + + def __str__(self): + return self._value + + def __int__(self): + return self._decimal_value + + def __add__(self, other): + return PseudoNumber(self._digits, self._decimal_value + other) + +class Application: + def main(self): + if (len(sys.argv) != 3): + print("Usage: %s " % sys.argv[0]) + return + + datablock_count = int(sys.argv[2]) + file_count = int(sys.argv[1]) + datablock_iterations = datablock_count / file_count + current_digit = PseudoNumber('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 0) + + for file_iteration in range(file_count): + with open("out%u.cs" % file_iteration, "w") as handle: + handle.write("// Total Count: %u\n" % datablock_iterations) + for current_datablock_iteration in range(datablock_iterations): + handle.write("// Datablock #%u\n" % current_datablock_iteration) + handle.write("datablock PlayerData(%sMaleBiodermArmor) : LightMaleHumanArmor\n" % str(current_digit)) + handle.write("{\n") + handle.write("\tshapeFile = \"bioderm_light.dts\";\n") + handle.write("};\n\n") + + current_digit += 1 + + handle.write("exec(\"scripts/out%u.cs\");" % (file_iteration + 1)) + + +if __name__ == "__main__": + Application().main() diff --git a/pool/shard006/Python/0057620_test_model_chat_analysis.py b/pool/shard006/Python/0057620_test_model_chat_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..dae9b287211da2a791f8a7f94043d557f28eb5f0 --- /dev/null +++ b/pool/shard006/Python/0057620_test_model_chat_analysis.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 + +# Copyright (c) Facebook, Inc. and its affiliates. +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. +""" +Test the analysis code for the model chat task. +""" + +import glob +import os + +import pytest +from pytest_regressions.file_regression import FileRegressionFixture + +import parlai.utils.testing as testing_utils + + +try: + + from parlai.crowdsourcing.tasks.model_chat.analysis.compile_results import ( + ModelChatResultsCompiler, + ) + from parlai.crowdsourcing.utils.tests import check_stdout + + class TestCompileResults: + """ + Test the analysis code for the model chat task. + """ + + # Dictionary of cases to test, as well as flags to use with those cases + CASES = {'basic': '--problem-buckets None', 'with_personas_and_buckets': ''} + + @pytest.fixture(scope="module") + def setup_teardown(self): + """ + Call code to set up and tear down tests. + + Run this only once because we'll be running all analysis code before + checking any results. + """ + + outputs = {} + + for case, flag_string in self.CASES.items(): + + # Paths + analysis_samples_folder = os.path.join( + os.path.dirname(os.path.abspath(__file__)), 'analysis_samples', case + ) + analysis_outputs_folder = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + 'test_model_chat_analysis', + ) + outputs[f'{case}__expected_stdout_path'] = os.path.join( + analysis_outputs_folder, f'{case}__test_stdout.txt' + ) + + prefixes = ['results', 'worker_results'] + + with testing_utils.tempdir() as tmpdir: + + # Run analysis + with testing_utils.capture_output() as output: + arg_string = f"""\ +--results-folders {analysis_samples_folder} +--output-folder {tmpdir} \ +{flag_string} +""" + parser_ = ModelChatResultsCompiler.setup_args() + args_ = parser_.parse_args(arg_string.split()) + ModelChatResultsCompiler(vars(args_)).compile_and_save_results() + stdout = output.getvalue() + + # Define output structure + filtered_stdout = '\n'.join( + [ + line + for line in stdout.split('\n') + if not line.endswith('.csv') + ] + ) + # Don't track lines that record where a file was saved to, because + # filenames are timestamped + outputs[f'{case}__stdout'] = filtered_stdout + for prefix in prefixes: + results_path = list( + glob.glob(os.path.join(tmpdir, f'{prefix}_*')) + )[0] + with open(results_path) as f: + outputs[f'{case}__{prefix}'] = f.read() + + yield outputs + # All code after this will be run upon teardown + + def test_stdout(self, setup_teardown): + """ + Check the output against what it should be. + """ + outputs = setup_teardown + for case in self.CASES.keys(): + check_stdout( + actual_stdout=outputs[f'{case}__stdout'], + expected_stdout_path=outputs[f'{case}__expected_stdout_path'], + ) + + def test_results_file( + self, setup_teardown, file_regression: FileRegressionFixture + ): + """ + Check the results file against what it should be. + + We don't use DataFrameRegression fixture because the results might include + non-numeric data. + """ + for case in self.CASES.keys(): + prefix = f'{case}__results' + outputs = setup_teardown + file_regression.check(outputs[prefix], basename=prefix) + + def test_worker_results_file( + self, setup_teardown, file_regression: FileRegressionFixture + ): + """ + Check the worker_results file against what it should be. + + We don't use DataFrameRegression fixture because the results might include + non-numeric data. + """ + for case in self.CASES.keys(): + prefix = f'{case}__worker_results' + outputs = setup_teardown + file_regression.check(outputs[prefix], basename=prefix) + + +except ImportError: + pass diff --git a/pool/shard006/Python/0057630_principals.py b/pool/shard006/Python/0057630_principals.py new file mode 100644 index 0000000000000000000000000000000000000000..05cfdbc1c794bcf2c5186bfcf47cd97667d5fa44 --- /dev/null +++ b/pool/shard006/Python/0057630_principals.py @@ -0,0 +1,53 @@ +# This file is part of Indico. +# Copyright (C) 2002 - 2021 CERN +# +# Indico is free software; you can redistribute it and/or +# modify it under the terms of the MIT License; see the +# LICENSE file for more details. + +from sqlalchemy.ext.declarative import declared_attr + +from indico.core.db import db +from indico.core.db.sqlalchemy.principals import PrincipalPermissionsMixin, PrincipalType +from indico.core.db.sqlalchemy.util.models import auto_table_args +from indico.util.string import format_repr + + +class EventPrincipal(PrincipalPermissionsMixin, db.Model): + __tablename__ = 'principals' + principal_backref_name = 'in_event_acls' + principal_for = 'Event' + unique_columns = ('event_id',) + allow_emails = True + allow_networks = True + allow_event_roles = True + allow_category_roles = True + allow_registration_forms = True + + @declared_attr + def __table_args__(cls): + permissions = "ARRAY['paper_editing', 'slides_editing', 'poster_editing']" + condition = 'type NOT IN ({}, {}) OR (NOT (permissions::text[] && {}))'.format( + PrincipalType.local_group, PrincipalType.multipass_group, permissions + ) + group_perm_constraint = db.CheckConstraint(condition, 'disallow_group_editor_permissions') + return (group_perm_constraint,) + auto_table_args(cls, schema='events') + + #: The ID of the acl entry + id = db.Column( + db.Integer, + primary_key=True + ) + #: The ID of the associated event + event_id = db.Column( + db.Integer, + db.ForeignKey('events.events.id'), + nullable=False, + index=True + ) + + # relationship backrefs: + # - event (Event.acl_entries) + + def __repr__(self): + return format_repr(self, 'id', 'event_id', 'principal', read_access=False, full_access=False, permissions=[]) diff --git a/pool/shard006/Python/0057631_FingerprintUtils.py b/pool/shard006/Python/0057631_FingerprintUtils.py new file mode 100644 index 0000000000000000000000000000000000000000..2c18cb67b542e90c4da7e47e6e4239c9188ee579 --- /dev/null +++ b/pool/shard006/Python/0057631_FingerprintUtils.py @@ -0,0 +1,112 @@ +# $Id$ +# +# Copyright (C) 2009 Greg Landrum +# All Rights Reserved +# +from __future__ import print_function +from rdkit.six.moves import cPickle +from rdkit.six import iterkeys +from rdkit import DataStructs,Chem +from rdkit import Chem + +similarityMethods={'RDK':DataStructs.ExplicitBitVect, + 'AtomPairs':DataStructs.IntSparseIntVect, + 'TopologicalTorsions':DataStructs.LongSparseIntVect, + 'Pharm2D':DataStructs.SparseBitVect, + 'Gobbi2D':DataStructs.SparseBitVect, + 'Morgan':DataStructs.UIntSparseIntVect + } +supportedSimilarityMethods=list(iterkeys(similarityMethods)) + + +class LayeredOptions: + loadLayerFlags=0xFFFFFFFF + searchLayerFlags=0x7 + minPath=1 + maxPath=6 + fpSize=1024 + wordSize=32 + nWords=fpSize//wordSize + @staticmethod + def GetFingerprint(mol,query=True): + if query: + flags=LayeredOptions.searchLayerFlags + else: + flags=LayeredOptions.loadLayerFlags + return Chem.LayeredFingerprint(mol,layerFlags=flags, + minPath=LayeredOptions.minPath,maxPath=LayeredOptions.maxPath, + fpSize=LayeredOptions.fpSize) + @staticmethod + def GetWords(mol,query=True): + txt = LayeredOptions.GetFingerprint(mol,query=query).ToBitString() + words = [int(txt[x:x+32],2) for x in range(0,len(txt),32)] + return words + + @staticmethod + def GetQueryText(mol,query=True): + words = LayeredOptions.GetWords(mol,query=query) + colqs = [] + for idx,word in enumerate(words): + if not word: + continue + idx = idx+1 + colqs.append('%(word)d&Col_%(idx)d=%(word)d'%locals()) + return ' and '.join(colqs) + + + +def BuildSigFactory(options=None,fdefFile=None, + bins=[(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,100)], + skipFeats=('LumpedHydrophobe','ZnBinder')): + if options: + fdefFile = options.fdefFile + if not fdefFile: + raise ValueError('bad fdef file') + from rdkit.Chem import ChemicalFeatures + from rdkit.Chem.Pharm2D import SigFactory + featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile) + sigFactory = SigFactory.SigFactory(featFactory, + skipFeats=skipFeats, + trianglePruneBins=False) + sigFactory.SetBins(bins) + return sigFactory + +def BuildAtomPairFP(mol): + from rdkit.Chem.AtomPairs import Pairs + fp=Pairs.GetAtomPairFingerprintAsIntVect(mol) + fp._sumCache = fp.GetTotalVal() + return fp +def BuildTorsionsFP(mol): + from rdkit.Chem.AtomPairs import Torsions + fp=Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol) + fp._sumCache = fp.GetTotalVal() + return fp +def BuildRDKitFP(mol): + fp=Chem.RDKFingerprint(mol,nBitsPerHash=1) + return fp +def BuildPharm2DFP(mol): + global sigFactory + from rdkit.Chem.Pharm2D import Generate + try: + fp=Generate.Gen2DFingerprint(mol,sigFactory) + except IndexError: + print('FAIL:',Chem.MolToSmiles(mol,True)) + raise + return fp +def BuildMorganFP(mol): + from rdkit.Chem import rdMolDescriptors + fp = rdMolDescriptors.GetMorganFingerprint(mol,2) + fp._sumCache = fp.GetTotalVal() + return fp + +def DepickleFP(pkl,similarityMethod): + if not isinstance(pkl,(bytes,str)): + pkl = str(pkl) + try: + klass=similarityMethods[similarityMethod] + fp = klass(pkl) + except: + import traceback + traceback.print_exc() + fp = cPickle.loads(pkl) + return fp diff --git a/pool/shard006/Python/0057632_etl.py b/pool/shard006/Python/0057632_etl.py new file mode 100644 index 0000000000000000000000000000000000000000..3796662ee7805a0fbae0cbe83df9cde9d53378d8 --- /dev/null +++ b/pool/shard006/Python/0057632_etl.py @@ -0,0 +1,64 @@ +#!/opt/zenoss/bin/python +DEBUG_flag=False + +import os +import sys +import re +import urllib2 +import json +import time +import datetime + +def help(): + print "Usage:" + print "etl.py -url=YOUR_HOSTNAME -component=YOUR_COMPONENT_NAME -t=MAX_TIME_SINCE_LAST_UPDATE_IN_MINUTES" + sys.exit(3) + +if (len(sys.argv) == 4): + args_str = sys.argv[1] +" "+ sys.argv[2] +" "+ sys.argv[3] + args_str = args_str.lower() + if ("-url=" in args_str and "-component=" in args_str and "-t=" in args_str): + url_str = "http://" + sys.argv[1].replace("-url=","") + "/api/component/" + component_str = sys.argv[2].replace("-component=","") + time_str = sys.argv[3].replace("-t=", "") + if DEBUG_flag: + print url_str+component_str, component_str, time_str + try: + request = urllib2.urlopen(url_str+component_str) + content = request.read() + ### Here is the main part of code ### + json_dict = json.loads(content) + status = json_dict["status"].lower() + if (status == "ok"): + #Here we should check the time since last update + time_from_json = time.strptime(json_dict["updated"], "%Y-%m-%d %H:%M:%S") + time_now = time.localtime() + time_from_json = datetime.datetime(*time_from_json[0:6]) + time_now = datetime.datetime(*time_now[0:6]) + time_delta = time_now - time_from_json + if DEBUG_flag: + print time_from_json + print time_now + print time_delta.seconds + print time_delta.days + if (time_delta.days > 0 or ((time_delta.seconds/60) > int(time_str)) ): + print "WARNING - Time since last update is greater than %s minutes" % str(time_str) + sys.exit(1) + else: + print "OK - Time since last update is less than %s minutes" % str(time_str) + sys.exit(0) + else: + message = json_dict["message"] + print 'CRITICAL - %s' % (message) + sys.exit(2) + ##################################### + except (urllib2.URLError, urllib2.HTTPError), e: + print 'CRITICAL - %s' % (e) + sys.exit(2) + else: + print "UNKNOWN - Wrong arguments" + help() + sys.exit(3) +else: + print "UNKNOWN - Not enough arguments" + sys.exit(3) \ No newline at end of file diff --git a/pool/shard006/Python/0057637_utils.py b/pool/shard006/Python/0057637_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2dff1e8d9a904a0438a546cc5fbe6559e700c750 --- /dev/null +++ b/pool/shard006/Python/0057637_utils.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from shuup_tests.utils import replace_urls + + +def get_admin_only_urls(): + from django.conf.urls import patterns, url, include + from shuup.admin.urls import get_urls + class FauxUrlPatternsModule: + urlpatterns = get_urls() + + return patterns('', + url(r'^sa/', include(FauxUrlPatternsModule, namespace="shuup_admin", app_name="shuup_admin")), + ) + +def admin_only_urls(): + return replace_urls(get_admin_only_urls()) diff --git a/pool/shard006/Python/0057641_link_finder.py b/pool/shard006/Python/0057641_link_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..8e7bffe0121ab7736bb02915c378d1a2a2fb1e69 --- /dev/null +++ b/pool/shard006/Python/0057641_link_finder.py @@ -0,0 +1,34 @@ +from __future__ import print_function +from HTMLParser import HTMLParser +from urllib2 import Request, urlopen +from urlparse import urljoin + +class LinkFinder(HTMLParser): + def handle_starttag(self, tag, attrs): + if tag == 'a': + for (key, value) in attrs: + if key == 'href': + newUrl = urljoin(self.baseUrl, value) + self.links = self.links + [newUrl] + + def getLinks(self, url): + self.links = [] + self.baseUrl = url + response = urlopen(url) + try: + htmlBytes = response.read() + htmlString = htmlBytes.decode("utf-8") + self.feed(htmlString) + return list(set(self.links)) + except Exception as e: + print(e) + return [] + +def spider(url, maxPages): + parser = LinkFinder() + for link in parser.getLinks(url=url): + print(link) + +if __name__ == "__main__": + ## running ... + spider(url="http://eu.battle.net/wow/en/", maxPages=10) diff --git a/pool/shard006/Python/0057645_sql.py b/pool/shard006/Python/0057645_sql.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd15af097328a4836d7a063a59873133bea8de7 --- /dev/null +++ b/pool/shard006/Python/0057645_sql.py @@ -0,0 +1,9 @@ +import sqlite3 + +with sqlite3.connect("blog.db") as connection: + c = connection.cursor() + c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""") + c.execute('INSERT INTO posts VALUES("Good", "I\'m good.")') + c.execute('INSERT INTO posts VALUES("Well", "I\'m well.")') + c.execute('INSERT INTO posts VALUES("Excellent", "I\'m excellent.")') + c.execute('INSERT INTO posts VALUES("Okay", "I\'m okay.")') diff --git a/pool/shard006/Python/0057649_read.py b/pool/shard006/Python/0057649_read.py new file mode 100644 index 0000000000000000000000000000000000000000..9867bdd0417cd993c1eccbc5bafb66cc0ae16211 --- /dev/null +++ b/pool/shard006/Python/0057649_read.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +# Read the light level from a GPIO pin on a raspberry pi +# Must be used with GPIO 0.3.1a or later - earlier verions +# are not fast enough! + +import time + +class readLight: + def instantiate(self, input_gpio): + self.gpio = input_gpio + #self.gpio.setmode(self.gpio.BCM) + self.RCPIN = 38 + + def get_light_level(self): + reading = 0 + self.gpio.setup(self.RCPIN, self.gpio.OUT) + self.gpio.output(self.RCPIN, self.gpio.LOW) + # 10 milliseconds + time.sleep(0.01) + + self.gpio.setup(self.RCPIN, self.gpio.IN) + # This takes about 1 millisecond per loop cycle + while (self.gpio.input(self.RCPIN) == self.gpio.LOW): + reading += 1 + return reading diff --git a/pool/shard006/Python/0057651_euler38.py b/pool/shard006/Python/0057651_euler38.py new file mode 100644 index 0000000000000000000000000000000000000000..66c7b241344f03037e4fdc5e8a88a6155ebd5fe3 --- /dev/null +++ b/pool/shard006/Python/0057651_euler38.py @@ -0,0 +1,50 @@ +#coding=utf-8 +dig='123456789' + +result=[] +results=[] +for i in range(5000,9999): + tmp=str(i)+str(i*2) + flag=True + for j in dig: + if j not in tmp: + flag=False + if flag: + result.append(i) + results.append(int(tmp)) + +for i in range(100,333): + tmp=str(i)+str(i*2)+str(i*3) + flag=True + for j in dig: + if j not in tmp or len(tmp)!=9: + flag=False + break + if flag: + result.append(i) + results.append(int(tmp)) + +for i in range(10,34): + tmp=str(i)+str(i*2)+str(i*3)+str(i*4) + flag=True + for j in dig: + if j not in tmp or len(tmp)!=9: + flag=False + break + if flag: + result.append(i) + results.append(int(tmp)) + +for i in range(1,10): + tmp=str(i)+str(i*2)+str(i*3)+str(i*4)+str(i*5) + flag=True + for j in dig: + if j not in tmp or len(tmp)!=9: + flag=False + break + if flag: + result.append(i) + results.append(int(tmp)) +print result +print results +print max(results) \ No newline at end of file diff --git a/pool/shard006/Python/0057652_spacy-nlp.py b/pool/shard006/Python/0057652_spacy-nlp.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce70a2429467ac78cad07533541f15fe98bf627 --- /dev/null +++ b/pool/shard006/Python/0057652_spacy-nlp.py @@ -0,0 +1,122 @@ +import os +import sys + +from spacy.en import English + +#INSTANTIATE SPACY PARSER +nlp = English() + +def token_process(file_in): + #_doc = nlp(unicode(file_in, encoding="utf-8")) + _doc = nlp(file_in) + return _doc + +def sent_process(file_in): + #_doc = nlp(unicode(file_in, encoding="utf-8")) + _doc = nlp(file_in) + _sents = _doc.sents + return _sents + +def pos_process(file_in): + _pos_tagged = [] + #_doc = nlp(unicode(file_in, encoding="utf-8")) + _doc = nlp(file_in) +# _doc = _doc.decode("utf-8") +# _doc = _doc.encode("ascii", "ignore") + for token in _doc: + token_pos = '{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.pos_) + _pos_tagged.append(token_pos) + return _pos_tagged + +def lemma_process(file_in): + _lemmas = [] + #_doc = nlp(unicode(file_in, encoding="utf-8")) + _doc = nlp(file_in) + for token in _doc: + token_lemma = '{}/{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.lemma_.encode("ascii", "ignore"), token.pos_) + _lemmas.append(token_lemma) + return _lemmas + +def ner_process(file_in): + _ner_tagged = [] + _doc = nlp(file_in) + #_doc = nlp(unicode(file_in, encoding="utf-8")) + for token in _doc: + if token.ent_type_ != "": + token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, '_') + else: + token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, token.ent_type_) + _ner_tagged.append(token_ner) + return _ner_tagged + +def main(): + doc = [] + sents = [] + pos_tagged = [] + lemmas = [] + ner_tagged = [] + + file = '' + #Read file without line breaks + with open(sys.argv[1], 'r') as _file: + file = _file.read().replace('\n', ' ') + + file = unicode(file, encoding="utf-8") + + if file == '': + print 'File not read properly' + sys.exit() + + if sys.argv[-1] == 'tokenize': + doc = token_process(file) + for token in doc: + print token + + elif sys.argv[-1] == 'sent_split': + sents = sent_process(file) + for sent in sents: + print sent + + elif sys.argv[-1] == 'pos_tag': + pos_tagged = pos_process(file) + for pos in pos_tagged: + print pos + + elif sys.argv[-1] == 'lemmatize': + lemmas = lemma_process(file) + for lemma in lemmas: + print lemma + + elif sys.argv[-1] == 'ner_tag': + ner_tagged = ner_process(file) + for ner in ner_tagged: + print ner + +#BEGIN PREPROCESSING EXECUTION +main() + +#TO KEEP LINE BREAKS +#with open('/Users/stc1563/programming/research/test-cases/_raw/lemmaCase-v6.txt', 'r') as f: +# strIn=f.read(); +# for line in f: +# tokenSents = nlp(unicode(line,encoding="utf-8")) +# for span in tokenSents.sents: +# sent = ''.join(tokenSents[i].string for i in range(span.start, span.end)).strip() +# sents.append(sent) + +#spacy parser creates tokens objects with callable methods that return nlp component results +#tokens = nlp(unicode(strIn,encoding="utf-8")) + +#Sents property returns spans +#Spans have indices into original string +#where each index value returns a token +#SENTENCE SPLITTING +#for span in tokens.sents: +##go from the start to the end of the span, returning each token in the sentence +##combine each token using join() +# sent = ''.join(tokens[i].string for i in range(span.start, span.end)).strip() +# sents.append(sent) +#for sentence in sents: +# tokenCount+=1 +# print '{}'.format(sentence.encode('ascii', 'ignore')) +#END SENTENCE SPLITTING \ No newline at end of file diff --git a/pool/shard006/Python/0057655_app_initialization_test.py b/pool/shard006/Python/0057655_app_initialization_test.py new file mode 100644 index 0000000000000000000000000000000000000000..acf8e2eaa4bd11870814fbddb10b38dac001c6de --- /dev/null +++ b/pool/shard006/Python/0057655_app_initialization_test.py @@ -0,0 +1,51 @@ +from superdesk.tests import TestCase +from .app_initialize import AppInitializeWithDataCommand +from .app_scaffold_data import AppScaffoldDataCommand +from superdesk import get_resource_service + + +class AppInitializeWithDataCommandTestCase(TestCase): + + def setUp(self): + super().setUp() + + def test_app_initialization(self): + with self.app.app_context(): + command = AppInitializeWithDataCommand() + result = command.run() + self.assertEquals(result, 0) + + def test_app_initialization_multiple_loads(self): + with self.app.app_context(): + command = AppInitializeWithDataCommand() + result = command.run() + self.assertEquals(result, 0) + result = command.run() + self.assertEquals(result, 0) + + def data_scaffolding_test(self): + with self.app.app_context(): + command = AppInitializeWithDataCommand() + result = command.run() + self.assertEquals(result, 0) + + service = get_resource_service('text_archive') + docs = [{ + 'type': 'text', + 'abstract': 'test abstract {}'.format(x), + 'headline': 'test headline {}'.format(x), + 'body_html': 'test long story body {}'.format(x) + } for x in range(0, 40)] + service.post(docs) + + stories_per_desk = 2 + existing_desks = 1 + command = AppScaffoldDataCommand() + result = command.run(stories_per_desk) + self.assertEquals(result, 0) + + cursor = get_resource_service('desks').get_from_mongo(None, {}) + self.assertEquals(cursor.count(), existing_desks) + + cursor = get_resource_service('archive').get_from_mongo(None, {}) + self.assertEquals(cursor.count(), existing_desks * stories_per_desk) diff --git a/pool/shard006/Python/0057662_filediff_comment.py b/pool/shard006/Python/0057662_filediff_comment.py new file mode 100644 index 0000000000000000000000000000000000000000..42447693faa42e00ab5077aa547f29f5c5f211ec --- /dev/null +++ b/pool/shard006/Python/0057662_filediff_comment.py @@ -0,0 +1,56 @@ +from djblets.util.decorators import augment_method_from + +from reviewboard.webapi.resources.base_diff_comment import \ + BaseDiffCommentResource + + +class FileDiffCommentResource(BaseDiffCommentResource): + """Provides information on comments made on a particular per-file diff. + + The list of comments cannot be modified from this resource. It's meant + purely as a way to see existing comments that were made on a diff. These + comments will span all public reviews. + """ + allowed_methods = ('GET',) + policy_id = 'diff_comment' + model_parent_key = 'filediff' + uri_object_key = None + + mimetype_list_resource_name = 'file-diff-comments' + mimetype_item_resource_name = 'file-diff-comment' + + def get_queryset(self, request, diff_revision, filediff_id, + *args, **kwargs): + """Returns a queryset for Comment models. + + This filters the query for comments on the specified review request + and made on the specified diff revision, which are either public or + owned by the requesting user. + + If the queryset is being used for a list of comment resources, + then this can be further filtered by passing ``?interdiff-revision=`` + on the URL to match the given interdiff revision, and + ``?line=`` to match comments on the given line number. + """ + q = super(FileDiffCommentResource, self).get_queryset( + request, *args, **kwargs) + return q.filter(filediff__diffset__revision=diff_revision, + filediff=filediff_id) + + @augment_method_from(BaseDiffCommentResource) + def get_list(self, request, diff_revision=None, *args, **kwargs): + """Returns the list of comments on a file in a diff. + + This list can be filtered down by using the ``?line=`` and + ``?interdiff-revision=``. + + To filter for comments that start on a particular line in the file, + using ``?line=``. + + To filter for comments that span revisions of diffs, you can specify + the second revision in the range using ``?interdiff-revision=``. + """ + pass + + +filediff_comment_resource = FileDiffCommentResource() diff --git a/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py b/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2779210e232809791f32678494caac1d896321 --- /dev/null +++ b/pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py @@ -0,0 +1,115 @@ +# +# Copyright (c) 2014 Sylvain Peyrefitte +# +# This file is part of rdpy. +# +# rdpy 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 . +# + +""" +unit test for rdpy.protocol.rdp.tpkt module +""" + +import os, sys +# Change path so we find rdpy +sys.path.insert(1, os.path.join(sys.path[0], '..')) + +import unittest +import rdpy.protocol.rdp.tpkt as tpkt +import rdpy.core.type as type +import rdpy.core.error as error + +class TPKTTest(unittest.TestCase): + """ + @summary: test case for tpkt layer (RDP) + """ + + class TPKT_PASS(Exception): + pass + + class TPKT_FAIL(Exception): + pass + + def test_tpkt_layer_connect(self): + """ + @summary: test forward connect event to presentation layer + """ + class Presentation(object): + def connect(self): + raise TPKTTest.TPKT_PASS() + + layer = tpkt.TPKT(Presentation()) + self.assertRaises(TPKTTest.TPKT_PASS, layer.connect) + + def test_tpkt_layer_recv(self): + """ + @summary: test receive in classic case + """ + class Presentation(object): + def connect(self): + pass + def recv(self, data): + data.readType(type.String("test_tpkt_layer_recv", constant = True)) + raise TPKTTest.TPKT_PASS() + + message = type.String("test_tpkt_layer_recv") + + s = type.Stream() + s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_X224), type.UInt8(), type.UInt16Be(type.sizeof(message) + 4), message)) + + layer = tpkt.TPKT(Presentation()) + layer.connect() + self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue()) + + def test_tpkt_layer_recv_fastpath(self): + """ + @summary: test receive in fastpath case + """ + class FastPathLayer(tpkt.IFastPathListener): + def setFastPathSender(self, fastPathSender): + pass + def recvFastPath(self, secFlag, fastPathS): + fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath", constant = True)) + raise TPKTTest.TPKT_PASS() + + message = type.String("test_tpkt_layer_recv_fastpath") + + s = type.Stream() + s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt8(type.sizeof(message) + 2), message)) + + layer = tpkt.TPKT(None) + layer.initFastPath(FastPathLayer()) + layer.connect() + self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue()) + + def test_tpkt_layer_recv_fastpath_ext_length(self): + """ + @summary: test receive in fastpath case with extended length + """ + class FastPathLayer(tpkt.IFastPathListener): + def setFastPathSender(self, fastPathSender): + pass + def recvFastPath(self, secflag, fastPathS): + fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath_ext_length", constant = True)) + raise TPKTTest.TPKT_PASS() + + message = type.String("test_tpkt_layer_recv_fastpath_ext_length") + + s = type.Stream() + s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt16Be((type.sizeof(message) + 3) | 0x8000), message)) + + layer = tpkt.TPKT(None) + layer.initFastPath(FastPathLayer()) + layer.connect() + self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue()) diff --git a/pool/shard006/Python/0057664_rest-server-v2.py b/pool/shard006/Python/0057664_rest-server-v2.py new file mode 100644 index 0000000000000000000000000000000000000000..ff6acb174a9ccec84ce34f49c23fe70452a2f64b --- /dev/null +++ b/pool/shard006/Python/0057664_rest-server-v2.py @@ -0,0 +1,118 @@ +#!flask/bin/python + +"""Alternative version of the ToDo RESTful server implemented using the +Flask-RESTful extension.""" + +from flask import Flask, jsonify, abort, make_response +from flask.ext.restful import Api, Resource, reqparse, fields, marshal +from flask.ext.httpauth import HTTPBasicAuth + +app = Flask(__name__, static_url_path="") +api = Api(app) +auth = HTTPBasicAuth() + + +@auth.get_password +def get_password(username): + if username == 'miguel': + return 'python' + return None + + +@auth.error_handler +def unauthorized(): + # return 403 instead of 401 to prevent browsers from displaying the default + # auth dialog + return make_response(jsonify({'message': 'Unauthorized access'}), 403) + +tasks = [ + { + 'id': 1, + 'title': u'Buy groceries', + 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', + 'done': False + }, + { + 'id': 2, + 'title': u'Learn Python', + 'description': u'Need to find a good Python tutorial on the web', + 'done': False + } +] + +task_fields = { + 'title': fields.String, + 'description': fields.String, + 'done': fields.Boolean, + 'uri': fields.Url('task') +} + + +class TaskListAPI(Resource): + decorators = [auth.login_required] + + def __init__(self): + self.reqparse = reqparse.RequestParser() + self.reqparse.add_argument('title', type=str, required=True, + help='No task title provided', + location='json') + self.reqparse.add_argument('description', type=str, default="", + location='json') + super(TaskListAPI, self).__init__() + + def get(self): + return {'tasks': [marshal(task, task_fields) for task in tasks]} + + def post(self): + args = self.reqparse.parse_args() + task = { + 'id': tasks[-1]['id'] + 1, + 'title': args['title'], + 'description': args['description'], + 'done': False + } + tasks.append(task) + return {'task': marshal(task, task_fields)}, 201 + + +class TaskAPI(Resource): + decorators = [auth.login_required] + + def __init__(self): + self.reqparse = reqparse.RequestParser() + self.reqparse.add_argument('title', type=str, location='json') + self.reqparse.add_argument('description', type=str, location='json') + self.reqparse.add_argument('done', type=bool, location='json') + super(TaskAPI, self).__init__() + + def get(self, id): + task = [task for task in tasks if task['id'] == id] + if len(task) == 0: + abort(404) + return {'task': marshal(task[0], task_fields)} + + def put(self, id): + task = [task for task in tasks if task['id'] == id] + if len(task) == 0: + abort(404) + task = task[0] + args = self.reqparse.parse_args() + for k, v in args.items(): + if v is not None: + task[k] = v + return {'task': marshal(task, task_fields)} + + def delete(self, id): + task = [task for task in tasks if task['id'] == id] + if len(task) == 0: + abort(404) + tasks.remove(task[0]) + return {'result': True} + + +api.add_resource(TaskListAPI, '/todo/api/v1.0/tasks', endpoint='tasks') +api.add_resource(TaskAPI, '/todo/api/v1.0/tasks/', endpoint='task') + + +if __name__ == '__main__': + app.run(debug=True) diff --git a/pool/shard006/Python/0057665_word_extractor.py b/pool/shard006/Python/0057665_word_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..33a804a72d3ea36d0e678fd0c3e1c333d725a5d6 --- /dev/null +++ b/pool/shard006/Python/0057665_word_extractor.py @@ -0,0 +1,75 @@ +# This file is part of Boomer Core. +# +# Boomer Core 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. +# +# Boomer Core 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 Boomer Core. If not, see . +# +# Forked from Mycroft Core on 2017-07-29 + +from speech_recognition import AudioData + +__author__ = 'jdorleans' + + +class WordExtractor: + SILENCE_SECS = 0.1 + PRECISION_RATE = 0.01 + + def __init__(self, audio, recognizer, metrics): + self.audio = audio + self.recognizer = recognizer + self.audio_size = len(self.audio.frame_data) + self.delta = int(self.audio_size / 2) + self.begin = 0 + self.end = self.audio_size + self.precision = int(self.audio_size * self.PRECISION_RATE) + self.silence_data = self.create_silence(self.SILENCE_SECS, + self.audio.sample_rate, + self.audio.sample_width) + self.metrics = metrics + + def __add(self, is_begin, value): + if is_begin: + self.begin += value + else: + self.end += value + + def __calculate_marker(self, is_begin): + dt = self.delta + sign = 1 if is_begin else -1 + + while dt > self.precision: + self.__add(is_begin, dt * sign) + segment = self.audio.frame_data[self.begin:self.end] + found = self.recognizer.is_recognized(segment, self.metrics) + if not found: + self.__add(is_begin, dt * -sign) + dt = int(dt / 2) + + def calculate_range(self): + self.__calculate_marker(False) + self.__calculate_marker(True) + + @staticmethod + def create_silence(seconds, sample_rate, sample_width): + return '\0' * int(seconds * sample_rate * sample_width) + + def get_audio_data_before(self): + byte_data = self.audio.frame_data[0:self.begin] + self.silence_data + return AudioData(byte_data, self.audio.sample_rate, + self.audio.sample_width) + + def get_audio_data_after(self): + byte_data = self.silence_data + self.audio.frame_data[self.end: + self.audio_size] + return AudioData(byte_data, self.audio.sample_rate, + self.audio.sample_width) diff --git a/pool/shard006/Python/0057667_Choice.py b/pool/shard006/Python/0057667_Choice.py new file mode 100644 index 0000000000000000000000000000000000000000..67b6d0757099f4d21524d1fd0053b500927b62f5 --- /dev/null +++ b/pool/shard006/Python/0057667_Choice.py @@ -0,0 +1,48 @@ +import random + +from CommandTemplate import CommandTemplate + + +class Command(CommandTemplate): + triggers = ['choice', 'choose'] + helptext = "Helps you make a choice between options in a comma-separated list" + + possibleReplies = ["Hmm, I'd go with {}", "Out of those, {} sounds the least bad", "{}, obviously", + "Let's go with... {}. No wait! No, yeah, that one", "I don't know! *rolls dice* Seems you should go for {}", + "Pick {0}, pick {0}!", "Eh, {} will do", "Why not {}?", "The first one! The last one! {}!", "Just pick {}"] + + def pickRandomReply(self): + #Based on a suggestion by ekimekim + while True: + #Shuffle the list initially + random.shuffle(self.possibleReplies) + #Then just feed a reply every time one is requested. Once we run out, the list is reshuffled, ready to start again + for reply in self.possibleReplies: + yield reply + + def execute(self, message): + """ + :type message: IrcMessage.IrcMessage + """ + replytext = None + if message.messagePartsLength == 0: + replytext = "My choice would be to provide me with some choices, preferably separated by commas" + else: + if ';' in message.message: + choices = message.message.split(';') + elif ',' in message.message: + choices = message.message.split(',') + else: + choices = message.messageParts + #Remove all the empty choices from the list + choices = filter(bool, choices) + if len(choices) == 0: + replytext = "That's just an empty list of choices... I'll pick nothing then" + elif len(choices) == 1: + replytext = "Ooh, that's a tough one. I'd go with the first option, seeing as there is only one" + else: + #Make a new random generator with the choices as seed, so every time you ask the bot to make a choice from the same list, it picks the same outcome + choice = random.Random(tuple(sorted(choices))).choice(choices).strip() + #Pick a random reply sentence, and then add in the previously picked choice, enclosed in quotes + replytext = self.pickRandomReply().next().format('"' + choice + '"') + message.bot.sendMessage(message.source, replytext) \ No newline at end of file diff --git a/pool/shard006/Python/0057668_hog_template.py b/pool/shard006/Python/0057668_hog_template.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ce87c7713a5d79a0d8bafdc19efc39ee0d5175 --- /dev/null +++ b/pool/shard006/Python/0057668_hog_template.py @@ -0,0 +1,232 @@ +"""The Game of Hog.""" + +from dice import four_sided, six_sided, make_test_dice +from ucb import main, trace, log_current_line, interact + +GOAL_SCORE = 100 # The goal of Hog is to score 100 points. + +###################### +# Phase 1: Simulator # +###################### + +def roll_dice(num_rolls, dice=six_sided): + """Roll DICE for NUM_ROLLS times. Return either the sum of the outcomes, + or 1 if a 1 is rolled (Pig out). This calls DICE exactly NUM_ROLLS times. + + num_rolls: The number of dice rolls that will be made; at least 1. + dice: A zero-argument function that returns an integer outcome. + """ + # These assert statements ensure that num_rolls is a positive integer. + assert type(num_rolls) == int, 'num_rolls must be an integer.' + assert num_rolls > 0, 'Must roll at least once.' + "*** YOUR CODE HERE ***" + +def take_turn(num_rolls, opponent_score, dice=six_sided): + """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free bacon). + + num_rolls: The number of dice rolls that will be made. + opponent_score: The total score of the opponent. + dice: A function of no args that returns an integer outcome. + """ + assert type(num_rolls) == int, 'num_rolls must be an integer.' + assert num_rolls >= 0, 'Cannot roll a negative number of dice.' + assert num_rolls <= 10, 'Cannot roll more than 10 dice.' + assert opponent_score < 100, 'The game should be over.' + "*** YOUR CODE HERE ***" + edits + +def select_dice(score, opponent_score): + """Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a + multiple of 7, in which case select four-sided dice (Hog wild). + """ + "*** YOUR CODE HERE ***" + +def bid_for_start(bid0, bid1, goal=GOAL_SCORE): + """Given the bids BID0 and BID1 of each player, returns three values: + + - the starting score of player 0 + - the starting score of player 1 + - the number of the player who rolls first (0 or 1) + """ + assert bid0 >= 0 and bid1 >= 0, "Bids should be non-negative!" + assert type(bid0) == int and type(bid1) == int, "Bids should be integers!" + + # The buggy code is below: + if bid0 == bid1: + return 0, goal, goal + if bid0 == bid1 - 5: + return 0, 0, 0 + if bid1 == bid0 + 5: + return 10, 0, 1 + if bid1 > bid0: + return bid1, bid0, 0 + else: + return bid0, bid1, 1 + +def other(who): + """Return the other player, for a player WHO numbered 0 or 1. + + >>> other(0) + 1 + >>> other(1) + 0 + """ + return 1 - who + +def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE): + """Simulate a game and return the final scores of both players, with + Player 0's score first, and Player 1's score second. + + A strategy is a function that takes two total scores as arguments + (the current player's score, and the opponent's score), and returns a + number of dice that the current player will roll this turn. + + strategy0: The strategy function for Player 0, who plays first + strategy1: The strategy function for Player 1, who plays second + score0 : The starting score for Player 0 + score1 : The starting score for Player 1 + """ + who = 0 # Which player is about to take a turn, 0 (first) or 1 (second) + "*** YOUR CODE HERE ***" + return score0, score1 # You may want to change this line. + +####################### +# Phase 2: Strategies # +####################### + +def always_roll(n): + """Return a strategy that always rolls N dice. + + A strategy is a function that takes two total scores as arguments + (the current player's score, and the opponent's score), and returns a + number of dice that the current player will roll this turn. + + >>> strategy = always_roll(5) + >>> strategy(0, 0) + 5 + >>> strategy(99, 99) + 5 + """ + def strategy(score, opponent_score): + return n + return strategy + +# Experiments + +def make_averaged(fn, num_samples=1000): + """Return a function that returns the average_value of FN when called. + + To implement this function, you will have to use *args syntax, a new Python + feature introduced in this project. See the project description. + + >>> dice = make_test_dice(3, 1, 5, 6) + >>> averaged_dice = make_averaged(dice, 1000) + >>> averaged_dice() + 3.75 + >>> make_averaged(roll_dice, 1000)(2, dice) + 6.0 + + In this last example, two different turn scenarios are averaged. + - In the first, the player rolls a 3 then a 1, receiving a score of 1. + - In the other, the player rolls a 5 and 6, scoring 11. + Thus, the average value is 6.0. + """ + "*** YOUR CODE HERE ***" + +def max_scoring_num_rolls(dice=six_sided): + """Return the number of dice (1 to 10) that gives the highest average turn + score by calling roll_dice with the provided DICE. Assume that dice always + return positive outcomes. + + >>> dice = make_test_dice(3) + >>> max_scoring_num_rolls(dice) + 10 + """ + "*** YOUR CODE HERE ***" + +def winner(strategy0, strategy1): + """Return 0 if strategy0 wins against strategy1, and 1 otherwise.""" + score0, score1 = play(strategy0, strategy1) + if score0 > score1: + return 0 + else: + return 1 + +def average_win_rate(strategy, baseline=always_roll(5)): + """Return the average win rate (0 to 1) of STRATEGY against BASELINE.""" + win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline) + win_rate_as_player_1 = make_averaged(winner)(baseline, strategy) + return (win_rate_as_player_0 + win_rate_as_player_1) / 2 # Average results + +def run_experiments(): + """Run a series of strategy experiments and report results.""" + if True: # Change to False when done finding max_scoring_num_rolls + six_sided_max = max_scoring_num_rolls(six_sided) + print('Max scoring num rolls for six-sided dice:', six_sided_max) + four_sided_max = max_scoring_num_rolls(four_sided) + print('Max scoring num rolls for four-sided dice:', four_sided_max) + + if False: # Change to True to test always_roll(8) + print('always_roll(8) win rate:', average_win_rate(always_roll(8))) + + if False: # Change to True to test bacon_strategy + print('bacon_strategy win rate:', average_win_rate(bacon_strategy)) + + if False: # Change to True to test swap_strategy + print('swap_strategy win rate:', average_win_rate(swap_strategy)) + + if False: # Change to True to test final_strategy + print('final_strategy win rate:', average_win_rate(final_strategy)) + + "*** You may add additional experiments as you wish ***" + +# Strategies + +def bacon_strategy(score, opponent_score, margin=8, num_rolls=5): + """This strategy rolls 0 dice if that gives at least MARGIN points, + and rolls NUM_ROLLS otherwise. + """ + "*** YOUR CODE HERE ***" + return None # Replace this statement + +def swap_strategy(score, opponent_score, margin=8, num_rolls=5): + """This strategy rolls 0 dice when it would result in a beneficial swap and + rolls NUM_ROLLS if it would result in a harmful swap. It also rolls + 0 dice if that gives at least MARGIN points and rolls + NUM_ROLLS otherwise. + """ + "*** YOUR CODE HERE ***" + return None # Replace this statement + + +def final_strategy(score, opponent_score): + """Write a brief description of your final strategy. + + *** YOUR DESCRIPTION HERE *** + """ + "*** YOUR CODE HERE ***" + return 5 # Replace this statement + + +########################## +# Command Line Interface # +########################## + +# Note: Functions in this section do not need to be changed. They use features +# of Python not yet covered in the course. + + +@main +def run(*args): + """Read in the command-line argument and calls corresponding functions. + + This function uses Python syntax/techniques not yet covered in this course. + """ + import argparse + parser = argparse.ArgumentParser(description="Play Hog") + parser.add_argument('--run_experiments', '-r', action='store_true', + help='Runs strategy experiments') + args = parser.parse_args() + + if args.run_experiments: + run_experiments() diff --git a/pool/shard006/Python/0057670_test_image_lst.py b/pool/shard006/Python/0057670_test_image_lst.py new file mode 100644 index 0000000000000000000000000000000000000000..91bb81ab58c59c17f7c11e0d1881a678ac9cbd6b --- /dev/null +++ b/pool/shard006/Python/0057670_test_image_lst.py @@ -0,0 +1,142 @@ +# =============================================================================== +# Copyright 2017 dgketchum +# +# 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 os +import unittest +from fiona import open as fopen +from rasterio import open as rasopen + +from sat_image.image import Landsat8, Landsat5, Landsat7 + + +class TestImageLST5(unittest.TestCase): + def setUp(self): + self.dir_name_LT5 = 'tests/data/ssebop_test/lt5/041_025/2000/LT50410252000194AAA01' + self.l5 = Landsat5(self.dir_name_LT5) + self.lst = self.l5.land_surface_temp() + self.lst_raster_path = os.path.join(self.dir_name_LT5, 'lst5_test.tif') + self.l5.save_array(self.lst, self.lst_raster_path) + self.point_file = 'tests/data/points/041_025_CA_Let_points.shp' + self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lt5/041_025/2000/', + 'LT50410252000194AAA01', + 'LT50410252000194AAA01_LST_EEF.tif') + + def test_surface_temps(self): + points_dict = raster_point_extract(lst_raster=self.lst_raster_path, + eef_raster=self.eef_lst_raster, + points=self.point_file) + for key, val in points_dict.items(): + eef = val['eef_lst'] + lst = val['lst_found'] + ratio = eef / lst + print('Ratio at {} of EEFlux:LST calculated is {}.'.format( + key, ratio)) + self.assertAlmostEqual(ratio, 1.0, delta=0.01) + os.remove(self.lst_raster_path) + + +class TestImageLST7(unittest.TestCase): + def setUp(self): + self.dir_name_LT7 = 'tests/data/ssebop_test/le7/041_025/2000/LE70410252000234PAC00' + self.l7 = Landsat7(self.dir_name_LT7) + self.lst = self.l7.land_surface_temp() + self.lst_raster_path = os.path.join(self.dir_name_LT7, 'lst7_test.tif') + self.l7.save_array(self.lst, self.lst_raster_path) + self.point_file = 'tests/data/points/041_025_CA_Let_points.shp' + self.eef_lst_raster = os.path.join('tests/data/ssebop_test/le7/041_025/2000', + 'LE70410252000234PAC00/LE70410252000234PAC00_LST_EEF.tif') + + def test_surface_temps(self): + points_dict = raster_point_extract(lst_raster=self.lst_raster_path, + eef_raster=self.eef_lst_raster, + points=self.point_file) + for key, val in points_dict.items(): + eef = val['eef_lst'] + lst = val['lst_found'] + ratio = eef / lst + print('Ratio at {} of EEFlux:LST calculated is {}.'.format( + key, ratio)) + self.assertAlmostEqual(ratio, 1.0, delta=0.01) + os.remove(self.lst_raster_path) + + +class TestImageLST8(unittest.TestCase): + def setUp(self): + self.dir_name_LT8 = 'tests/data/ssebop_test/lc8/038_027/2014/LC80380272014227LGN01' + self.l8 = Landsat8(self.dir_name_LT8) + self.lst = self.l8.land_surface_temp() + # self.lst_raster_path = os.path.join(self.dir_name_LT8, 'lst8_test.tif') + self.lst_raster_path = '/data01/images/sandbox/lst8_test.tif' + self.l8.save_array(self.lst, self.lst_raster_path) + self.point_file = 'tests/data/points/038_027_US_Mj_points.shp' + self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lc8/038_027', + '2014/LC80380272014227LGN01/LC80380272014227LGN01_LST_EEF.tif') + + def test_surface_temps(self): + points_dict = raster_point_extract(lst_raster=self.lst_raster_path, + eef_raster=self.eef_lst_raster, + points=self.point_file) + for key, val in points_dict.items(): + eef = val['eef_lst'] + lst = val['lst_found'] + ratio = eef / lst + print('Ratio at {} of EEFlux:LST calculated is {}.'.format( + key, ratio)) + self.assertAlmostEqual(ratio, 1.0, delta=0.01) + os.remove(self.lst_raster_path) + + +# ===================== ANCILLARY FUNCTIONS ================================= + +def raster_point_extract(lst_raster, eef_raster, points): + point_data = {} + with fopen(points, 'r') as src: + for feature in src: + try: + name = feature['properties']['Name'] + except KeyError: + name = feature['properties']['FID'] + point_data[name] = {'coords': feature['geometry']['coordinates']} + + with rasopen(lst_raster, 'r') as src: + lst_arr = src.read() + lst_arr = lst_arr.reshape(lst_arr.shape[1], lst_arr.shape[2]) + lst_affine = src.transform + + with rasopen(eef_raster, 'r') as src: + eef_lst = src.read() + eef_lst = eef_lst.reshape(eef_lst.shape[1], eef_lst.shape[2]) + eef_affine = src.transform + + for key, val in point_data.items(): + x, y, z = val['coords'] + col, row = ~lst_affine * (x, y) + val = lst_arr[int(row), int(col)] + point_data[key]['lst_found'] = val + point_data[key]['lst_row_col'] = int(row), int(col) + + col, row = ~eef_affine * (x, y) + val = eef_lst[int(row), int(col)] + point_data[key]['eef_lst'] = val + point_data[key]['eef_row_col'] = int(row), int(col) + + return point_data + + +if __name__ == '__main__': + unittest.main() + +# =============================================================================== diff --git a/pool/shard006/Python/0057672_rating.py b/pool/shard006/Python/0057672_rating.py new file mode 100644 index 0000000000000000000000000000000000000000..7060c40b6582e830835c448dddba0740136567fc --- /dev/null +++ b/pool/shard006/Python/0057672_rating.py @@ -0,0 +1,15 @@ +# coding: utf-8 +import json +from django.http import HttpResponse +from feedhoos.folder.models.folder import FolderModel + + +def execute(request): + "folderのratingを変更する。" + folder_id = request.POST["id"] + rating = request.POST["rating"] + folder_model = FolderModel.objects.get(pk=folder_id) + folder_model.rating = int(rating) + folder_model.save() + response_json = json.dumps({"msg": "OK"}, ensure_ascii=False, skipkeys=True) + return HttpResponse(response_json, content_type='application/json') diff --git a/pool/shard006/Python/0057673_get_build_status.py b/pool/shard006/Python/0057673_get_build_status.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fd8fbb25d47006e0675cad1e63b2c12391e753 --- /dev/null +++ b/pool/shard006/Python/0057673_get_build_status.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python + +# Gets the build status of specific Bamboo builds from Jut's Bamboo instance + +import requests + +# The list of builds we're interested in +builds = ["CAM-AMT", "CAM-CMT","CAM-SMOKE","CAM-IMT","CAM-QUAM","CAM-JUM","CAM-VIM","CAM-EAM","CAM-SMT"] +#builds = ["CAM-PMT"] +build_results = [] + +# Get the status of each build and add it to the build_results list +for build in builds: + r = requests.get('https://jut-io.atlassian.net/builds/rest/api/latest/result/' + build + '-latest.json', auth=('robot','mrroboto')) + build_results.append(r.json()['buildState']) + print r.json()['buildState'] + +resultfile = open('/Users/davidcook/code/scratch/build-status-leds/build_status_display/data/build_results.txt', 'w+') + +failed_count = 0 + +# Count the number of builds that failed +for result in build_results: + if result == "Failed": + failed_count += 1 + +# If any of the builds failed, write Failed to the file. If they all passed, write Successful +if failed_count > 0: + resultfile.write("Failed\n") +else: + resultfile.write("Successful\n") + +resultfile.close() diff --git a/pool/shard006/Python/0057675_EurostagState.py b/pool/shard006/Python/0057675_EurostagState.py new file mode 100644 index 0000000000000000000000000000000000000000..2671170250a8853572a7f05386540d63384f7776 --- /dev/null +++ b/pool/shard006/Python/0057675_EurostagState.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2016, Pierre Saikaly (saikalypierre@gmail.com) + +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +#===========================# +# created on 07 sept 2016 +#===========================# + +# Import Python dependencies : +# ---------------------------- +import os +import sys +import time +import argparse + +# Script : +# -------- +def CheckEurostagState(folder): + """ + Reads eurostagOutputFile and check if the situation at the beginning is stable + or unstable + Inputs : + - eurostagOutputFile : file.out containing the informations + Outputs : + - 0 -> Situation is stable + - 1 -> Situation is unstable + Used in : + - main + """ + + etat = "ETAT D'EQUILIBRE A 0.10000D-02 VERIFIE POUR LES EQUATIONS MACHINE" + etat2 = "ETAT D'EQUILIBRE A 0.10000D-02 NON VERIFIE DANS LES EQUATIONS SUIVANTES" + eurostagOutputFile = os.path.join(folder,"sim_pre_fault.out") + + + + # Checking Eurostag status : + # -------------------------- + if etat in open(eurostagOutputFile, 'U').read(): + # Eurostag returns stable + status = 0 + else: + # Eurostag returns unstable : + # --------------------------- + equi_value = [] + with open(eurostagOutputFile, 'U') as outfile: + lines = outfile.readlines() + for i, line in enumerate(lines): + if etat2 in line: + k = i+5 + while (lines[k]!="1\n" and lines[k]!="\n"): + machine_name = lines[k].split()[0] + value_line = lines[k].split()[-2] + value_real = float(value_line.split("D")[0])*10**int(value_line.split("D")[1]) + if (abs(value_real) > 0.01): + with open('ecart_groupe.csv','a') as egf: + egf.write(folder + ';' + machine_name + ';' + str(value_real) + '\n') + equi_value.append(abs(value_real)) + k += 1 + # Checking tolerance : + # -------------------- + if (len(equi_value) > 0): + if (max(equi_value) < 0.01): + status = 0 # Stable state within tolerance + else: + status = 1 # Unstable state + + else: + status = 0 # Stable state + + return status + +def main(): + """ + Get list of eurostag simulation folders and check if thoses situations are + stable or not. The outputs are stored in eurostag_status.txt file + """ + + # Creating output file : + # ---------------------- + print "Beginning writing outputs for folders in directory..." + + with open('eurostag_status.txt','w') as f: + f.write("# " + time.strftime("%d/%m/%y") + "\n") + + with open('ecart_groupe.csv','w') as egf: + egf.write(time.strftime("%d/%m/%y") + "\n") + egf.write("Situations;groupe;valeur\n") + + # Checking folders and writing output : + # ------------------------------------- + with open('eurostag_status.txt','a') as f: + for folder in os.listdir('.'): + if folder.startswith('itesla_eurostag_stabilization_'): + f.write(folder + " " + str(CheckEurostagState(folder)) + '\n') + + print "Done writing outputs in eurostag_status.txt" + print "Done analysis in ecart_groupe.csv" + +if __name__=='__main__': + + parser = argparse.ArgumentParser(description='Check eurostag status of working directory of specific folder') + parser.add_argument('-p','--eur_path', help='path of eurostag folder', required=False) + args = parser.parse_args() + + if (args.eur_path): + with open('ecart_groupe.csv','w') as egf: + egf.write(time.strftime("%d/%m/%y") + "\n") + egf.write("Situations;groupe;valeur\n") + + print args.eur_path, ' ', CheckEurostagState(args.eur_path) + print "Done analysis in ecart_groupe.csv" + else: + main() \ No newline at end of file diff --git a/pool/shard006/Python/0057680_pluginmanager.py b/pool/shard006/Python/0057680_pluginmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..f207d2c7c6de31f83e500f14fbc5962b03729866 --- /dev/null +++ b/pool/shard006/Python/0057680_pluginmanager.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- + +''' +@author: nick +''' + +import imp +import os +import logging + +class PluginManager(): + + def __init__(self, directory): + self.pluginDirs = [directory] + self.plugins = {} + self.logger = logging.getLogger('picsort') + + def addDirectory(self, directory): + self.pluginDirs.append(directory) + + + def getPlugin(self, name): + return self.plugins[name] + + + def listPlugins(self): + plugins = [] + + for directory in self.pluginDirs: + if os.path.exists(directory): + for f in os.listdir(directory): + if f.endswith(".py") and not f == "__init__.py": + plugins.append(os.path.join(directory, f)) + else: + self.logger.warn("directory not exists: {}".format(directory)) + + return plugins + + + def loadPlugins(self): + + for plugin in self.listPlugins(): + try: + name, _ = os.path.splitext(os.path.split(plugin)[1]) + + submodule = imp.load_source(name, plugin) + self.plugins[name] = submodule + except Exception, e: + self.logger.error(e) diff --git a/pool/shard006/Python/0057683_routing_metal.py b/pool/shard006/Python/0057683_routing_metal.py new file mode 100644 index 0000000000000000000000000000000000000000..e095ed7359d23f7c2cbf129a360d11f7cd7e7d7a --- /dev/null +++ b/pool/shard006/Python/0057683_routing_metal.py @@ -0,0 +1,31 @@ +""" +FIXME: electrical connections should ignore port orientation +""" + +import gdsfactory as gf + + +if __name__ == "__main__": + + c = gf.Component("mzi_with_pads") + c1 = c << gf.components.mzi_phase_shifter_top_heater_metal(length_x=70) + c2 = c << gf.components.pad_array90(columns=2) + + c2.ymin = c1.ymax + 20 + c2.x = 0 + c1.x = 0 + + ports1 = c1.get_ports_list(width=11) + ports2 = c2.get_ports_list() + + routes = gf.routing.get_bundle( + ports1=ports1, + ports2=ports2, + cross_section=gf.cross_section.metal1, + width=5, + bend=gf.components.wire_corner, + ) + for route in routes: + c.add(route.references) + + c.show() diff --git a/pool/shard006/Python/0057685_rootramfs.py b/pool/shard006/Python/0057685_rootramfs.py new file mode 100644 index 0000000000000000000000000000000000000000..0306587d9d60c1bb3b43dd62b9c20d6de301bd5a --- /dev/null +++ b/pool/shard006/Python/0057685_rootramfs.py @@ -0,0 +1,175 @@ +#!/usr/bin/python + + +__author__ = 'volodja' + + +import os +import re +import sys + + +def printList(name, list_): + print(name + ":") + for row in list_: + print(str(row).replace("\n", "")) + + +def executeShellCommand(command): + print("exec: " + command) + result_pipe = os.popen(command) + result_ = result_pipe.readlines() + result = [] + for line in result_: + result.append(line.replace('\n', '')) + return result + + +def readFSTab(): + file_fstab = open("/etc/fstab") + #file_fstab = open("/etc/fstab.1") + fstab_text = file_fstab.readlines() + fstab = [] + file_fstab.close() + + for line in fstab_text: + if line[0] != "#": + fstab_line = re.split(r"\s+", line.replace("\n", "").replace("UUID=", "")) + fstab.append(fstab_line) + + #printList("fstab", fstab) + return fstab + + +def mountSyncFSTab(): + fstab = readFSTab() + mount = executeShellCommand("mount") + + #print "fstab: " + str(fstab) + #print("mount: " + str(mount)) + + fstab_to_mount = [] + for row_fstab in fstab: + if len(row_fstab) < 2: + continue + is_need_mount = True + if row_fstab[1] == "/": + mount_point = "/ram/sync" + else: + mount_point = "/ram/sync" + row_fstab[1] + for row_mount in mount: + if len(row_fstab) > 1 and (row_fstab[0][0:4] != "/ram" or (row_fstab[0][0:4] == "/ram" and row_mount.split(" ")[2] == mount_point)): + is_need_mount = False + break + if is_need_mount: + fstab_to_mount.append(row_fstab) + + #print "fstab_to_mount = " + str(fstab_to_mount) + #exit(0) + for row_fstab in fstab_to_mount: + mount = executeShellCommand("mkdir -p /ram/sync" + row_fstab[1] + " && mount -t " + row_fstab[2] + + " /dev/disk/by-uuid/" + row_fstab[0][4:] + " /ram/sync" + row_fstab[1] + " || echo 'mount fail'") + if len(mount) > 0: + print("error: " + str(mount)) + exit(1) + + +def umountSyncFSTab(): + #fstab = readFSTab() + mount = executeShellCommand("mount") + fstab_to_umount = [] + is_was_root = False + + for row_mount in mount: + mount_point = str(row_mount.split(" ")[2]) + if mount_point[0:9] == "/ram/sync": + if len(mount_point) > 9: + fstab_to_umount.append(mount_point) + else: + is_was_root = True + if is_was_root: + fstab_to_umount.append("/ram/sync") + + for row_umount in fstab_to_umount: + umount = executeShellCommand("umount " + row_umount) + if len(umount) > 0: + print("error: " + str(umount)) + exit(1) + + +def syncCommand(args, command_, is_reverse = False): + paths = [] + + for row_args in args: + if row_args != "--exclude": + paths.append(os.path.abspath(row_args)) + + if is_reverse: + src = "/ram/sync" + paths[0] + dst = paths[0] + else: + src = paths[0] + dst = "/ram/sync" + paths[0] + + + if os.path.isdir(paths[0]): + src = src + "/" + + del paths[0] + + #user_name = getpass.getuser() + command = command_ + " " + command = command + "--exclude '*/.gvfs' " + command = command + "--exclude '/run/user/*/gvfs' " + command = command + "--exclude '/media' " + command = command + "--exclude '/mnt' " + command = command + "--exclude '/dev' " + command = command + "--exclude '/sys' " + command = command + "--exclude '/proc' " + command = command + "--exclude '/selinux' " + command = command + "--exclude '/ram' " + command = command + "--exclude '/boot' " + + + for row_paths in paths: + command = command + "--exclude '" + row_paths + "' " + + command = command + "\"" + src + "\" \"" + dst + "\" | grep -v 'xfer#' | grep -v 'xfr#' > /dev/tty && sync" + rsync = executeShellCommand(command) + #printList(command_, rsync) + + +def syncPath(args): + syncCommand(args, "rsync --progress --delete -a") + + +def diffPath(args): + syncCommand(args, "diff -r") + + +def resetPath(args): + syncCommand(args, "rsync --progress --delete -a", True) + + +if len(sys.argv) >= 3 and sys.argv[1] == "--sync": + mountSyncFSTab() + syncPath(sys.argv[2:]) + umountSyncFSTab() + exit(0) + +if len(sys.argv) >= 3 and sys.argv[1] == "--reset": + mountSyncFSTab() + resetPath(sys.argv[2:]) + umountSyncFSTab() + exit(0) + +if len(sys.argv) >= 3 and sys.argv[1] == "--diff": + mountSyncFSTab() + diffPath(sys.argv[2:]) + umountSyncFSTab() + exit(0) + + +print("usage: rootramfs --sync sync_path [exclude_path1] [exclude_path2] ...") +print("usage: rootramfs --reset sync_path [exclude_path1] [exclude_path2] ...") +print("usage: rootramfs --diff sync_path [exclude_path1] [exclude_path2] ...") diff --git a/pool/shard006/Python/0057686_gotoread.py b/pool/shard006/Python/0057686_gotoread.py new file mode 100644 index 0000000000000000000000000000000000000000..3a347b042d5ebbe469687916ddd2e6eeeea6efcb --- /dev/null +++ b/pool/shard006/Python/0057686_gotoread.py @@ -0,0 +1,35 @@ +from scrapy.selector import Selector +from scrapy.linkextractors import LinkExtractor +from scrapy.spiders import CrawlSpider, Rule +from crawlers.items import MagazineItem + +import urllib.parse + +class GotoreadSpider(CrawlSpider): + name = 'gotoread' + allowed_domains = ['gotoread.com'] + start_urls = ['http://www.gotoread.com/scatalog3687.html', + 'http://www.gotoread.com/scatalog3078.html', + 'http://www.gotoread.com/scatalog3063.html', + 'http://www.gotoread.com/scatalog3010.html', + 'http://www.gotoread.com/scatalog3117.html', + 'http://www.gotoread.com/scatalog3533.html', + 'http://www.gotoread.com/scatalog3482.html', + 'http://www.gotoread.com/scatalog3477.html' + ] + + rules = ( + Rule(LinkExtractor(allow=r'/mag/\d+/$'), callback='parse_item', follow=False), + ) + + def parse_item(self, response): + sel = Selector(response) + i = MagazineItem() + i['name'] = sel.xpath("//div[@class='ProName']/h1/text()").extract() + i['description'] = sel.xpath("//div[@class='content box-line word']").extract() + i['price'] = sel.xpath("//em/del/text()").extract()[0] + i['category'] = sel.xpath("//div[@id='DaoHang']/a/text()").extract()[-1] + imgurl = sel.xpath("//img[@id='magcoverpic']/@src").extract()[0] + absurl = urlparse.urljoin("http://www.gotoread.com/", imgurl.strip()) + i['image_urls'] = [absurl] + return i diff --git a/pool/shard006/Python/0057692_mongodb_parameter.py b/pool/shard006/Python/0057692_mongodb_parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..2820982f0833d8afc079216b62f485e9001bedce --- /dev/null +++ b/pool/shard006/Python/0057692_mongodb_parameter.py @@ -0,0 +1,216 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2016, Loic Blot +# Sponsored by Infopro Digital. http://www.infopro-digital.com/ +# Sponsored by E.T.A.I. http://www.etai.fr/ +# +# 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 + + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: mongodb_parameter +short_description: Change an administrative parameter on a MongoDB server. +description: + - Change an administrative parameter on a MongoDB server. +version_added: "2.1" +options: + login_user: + description: + - The username used to authenticate with + login_password: + description: + - The password used to authenticate with + login_host: + description: + - The host running the database + default: localhost + login_port: + description: + - The port to connect to + default: 27017 + login_database: + description: + - The database where login credentials are stored + replica_set: + description: + - Replica set to connect to (automatically connects to primary for writes) + database: + description: + - The name of the database to add/remove the user from + required: true + ssl: + description: + - Whether to use an SSL connection when connecting to the database + type: bool + default: 'no' + param: + description: + - MongoDB administrative parameter to modify + required: true + value: + description: + - MongoDB administrative parameter value to set + required: true + param_type: + description: + - Define the parameter value (str, int) + default: str + +notes: + - Requires the pymongo Python package on the remote host, version 2.4.2+. This + can be installed using pip or the OS package manager. @see http://api.mongodb.org/python/current/installation.html +requirements: [ "pymongo" ] +author: "Loic Blot (@nerzhul)" +''' + +EXAMPLES = ''' +# Set MongoDB syncdelay to 60 (this is an int) +- mongodb_parameter: + param: syncdelay + value: 60 + param_type: int +''' + +RETURN = ''' +before: + description: value before modification + returned: success + type: string +after: + description: value after modification + returned: success + type: string +''' + +import os +import traceback + +try: + from pymongo.errors import ConnectionFailure + from pymongo.errors import OperationFailure + from pymongo import version as PyMongoVersion + from pymongo import MongoClient +except ImportError: + try: # for older PyMongo 2.2 + from pymongo import Connection as MongoClient + except ImportError: + pymongo_found = False + else: + pymongo_found = True +else: + pymongo_found = True + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.six.moves import configparser +from ansible.module_utils._text import to_native + + +# ========================================= +# MongoDB module specific support methods. +# + +def load_mongocnf(): + config = configparser.RawConfigParser() + mongocnf = os.path.expanduser('~/.mongodb.cnf') + + try: + config.readfp(open(mongocnf)) + creds = dict( + user=config.get('client', 'user'), + password=config.get('client', 'pass') + ) + except (configparser.NoOptionError, IOError): + return False + + return creds + + +# ========================================= +# Module execution. +# + +def main(): + module = AnsibleModule( + argument_spec=dict( + login_user=dict(default=None), + login_password=dict(default=None, no_log=True), + login_host=dict(default='localhost'), + login_port=dict(default=27017, type='int'), + login_database=dict(default=None), + replica_set=dict(default=None), + param=dict(default=None, required=True), + value=dict(default=None, required=True), + param_type=dict(default="str", choices=['str', 'int']), + ssl=dict(default=False, type='bool'), + ) + ) + + if not pymongo_found: + module.fail_json(msg='the python pymongo module is required') + + login_user = module.params['login_user'] + login_password = module.params['login_password'] + login_host = module.params['login_host'] + login_port = module.params['login_port'] + login_database = module.params['login_database'] + + replica_set = module.params['replica_set'] + ssl = module.params['ssl'] + + param = module.params['param'] + param_type = module.params['param_type'] + value = module.params['value'] + + # Verify parameter is coherent with specified type + try: + if param_type == 'int': + value = int(value) + except ValueError: + module.fail_json(msg="value '%s' is not %s" % (value, param_type)) + + try: + if replica_set: + client = MongoClient(login_host, int(login_port), replicaset=replica_set, ssl=ssl) + else: + client = MongoClient(login_host, int(login_port), ssl=ssl) + + if login_user is None and login_password is None: + mongocnf_creds = load_mongocnf() + if mongocnf_creds is not False: + login_user = mongocnf_creds['user'] + login_password = mongocnf_creds['password'] + elif login_password is None or login_user is None: + module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided') + + if login_user is not None and login_password is not None: + client.admin.authenticate(login_user, login_password, source=login_database) + + except ConnectionFailure as e: + module.fail_json(msg='unable to connect to database: %s' % to_native(e), exception=traceback.format_exc()) + + db = client.admin + + try: + after_value = db.command("setParameter", **{param: value}) + except OperationFailure as e: + module.fail_json(msg="unable to change parameter: %s" % to_native(e), exception=traceback.format_exc()) + + if "was" not in after_value: + module.exit_json(changed=True, msg="Unable to determine old value, assume it changed.") + else: + module.exit_json(changed=(value != after_value["was"]), before=after_value["was"], + after=value) + + +if __name__ == '__main__': + main() diff --git a/pool/shard006/Python/0057693_test_bigip_profile_udp.py b/pool/shard006/Python/0057693_test_bigip_profile_udp.py new file mode 100644 index 0000000000000000000000000000000000000000..0cdb30f3dc53f5a56045eb8cc759f31f9ad60905 --- /dev/null +++ b/pool/shard006/Python/0057693_test_bigip_profile_udp.py @@ -0,0 +1,119 @@ +# -*- 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 pytest +import sys + +if sys.version_info < (2, 7): + pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") + +from ansible.module_utils.basic import AnsibleModule + +try: + from library.modules.bigip_profile_udp import ApiParameters + from library.modules.bigip_profile_udp import ModuleParameters + from library.modules.bigip_profile_udp import ModuleManager + from library.modules.bigip_profile_udp import ArgumentSpec + + # In Ansible 2.8, Ansible changed import paths. + from test.units.compat import unittest + from test.units.compat.mock import Mock + + from test.units.modules.utils import set_module_args +except ImportError: + from ansible.modules.network.f5.bigip_profile_udp import ApiParameters + from ansible.modules.network.f5.bigip_profile_udp import ModuleParameters + from ansible.modules.network.f5.bigip_profile_udp import ModuleManager + from ansible.modules.network.f5.bigip_profile_udp import ArgumentSpec + + # Ansible 2.8 imports + from units.compat import unittest + from units.compat.mock import Mock + + from units.modules.utils import set_module_args + + +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='foo', + parent='bar', + idle_timeout='500', + datagram_load_balancing=False + ) + + p = ModuleParameters(params=args) + assert p.name == 'foo' + assert p.parent == '/Common/bar' + assert p.idle_timeout == 500 + assert p.datagram_load_balancing is False + + def test_api_parameters(self): + args = load_fixture('load_ltm_profile_udp_1.json') + p = ApiParameters(params=args) + assert p.name == 'foo' + assert p.idle_timeout == 60 + + +class TestManager(unittest.TestCase): + + def setUp(self): + self.spec = ArgumentSpec() + + def test_create(self, *args): + # Configure the arguments that would be sent to the Ansible module + set_module_args(dict( + name='foo', + parent='bar', + idle_timeout=500, + datagram_load_balancing=True, + provider=dict( + server='localhost', + password='password', + 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(return_value=False) + mm.create_on_device = Mock(return_value=True) + + results = mm.exec_module() + + assert results['changed'] is True + assert results['idle_timeout'] == 500 diff --git a/pool/shard006/Python/0057699_user.py b/pool/shard006/Python/0057699_user.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb82c2c1cb67a95a4b5d9a9d2d6315ef2d7ccfa --- /dev/null +++ b/pool/shard006/Python/0057699_user.py @@ -0,0 +1,127 @@ +""" +sentry.models.user +~~~~~~~~~~~~~~~~~~ + +: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 + +import warnings + +from django.contrib.auth.models import AbstractBaseUser, UserManager +from django.db import IntegrityError, models, transaction +from django.utils import timezone +from django.utils.translation import ugettext_lazy as _ + +from sentry.db.models import BaseManager, BaseModel, BoundedAutoField + + +class UserManager(BaseManager, UserManager): + pass + + +class User(BaseModel, AbstractBaseUser): + id = BoundedAutoField(primary_key=True) + username = models.CharField(_('username'), max_length=128, unique=True) + # this column is called first_name for legacy reasons, but it is the entire + # display name + name = models.CharField(_('name'), max_length=200, blank=True, + db_column='first_name') + email = models.EmailField(_('email address'), blank=True) + is_staff = models.BooleanField( + _('staff status'), default=False, + help_text=_('Designates whether the user can log into this admin ' + 'site.')) + is_active = models.BooleanField( + _('active'), default=True, + help_text=_('Designates whether this user should be treated as ' + 'active. Unselect this instead of deleting accounts.')) + is_superuser = models.BooleanField( + _('superuser status'), default=False, + help_text=_('Designates that this user has all permissions without ' + 'explicitly assigning them.')) + is_managed = models.BooleanField( + _('managed'), default=False, + help_text=_('Designates whether this user should be treated as ' + 'managed. Select this to disallow the user from ' + 'modifying their account (username, password, etc).')) + + date_joined = models.DateTimeField(_('date joined'), default=timezone.now) + + objects = UserManager(cache_fields=['pk']) + + USERNAME_FIELD = 'username' + REQUIRED_FIELDS = ['email'] + + class Meta: + app_label = 'sentry' + db_table = 'auth_user' + verbose_name = _('user') + verbose_name_plural = _('users') + + def delete(self): + if self.username == 'sentry': + raise Exception('You cannot delete the "sentry" user as it is required by Sentry.') + return super(User, self).delete() + + def save(self, *args, **kwargs): + if not self.username: + self.username = self.email + return super(User, self).save(*args, **kwargs) + + def has_perm(self, perm_name): + warnings.warn('User.has_perm is deprecated', DeprecationWarning) + return self.is_superuser + + def has_module_perms(self, app_label): + warnings.warn('User.has_module_perms is deprecated', DeprecationWarning) + return self.is_superuser + + def get_display_name(self): + return self.name or self.email or self.username + + def get_full_name(self): + return self.name + + def get_short_name(self): + return self.username + + def merge_to(from_user, to_user): + # TODO: we could discover relations automatically and make this useful + from sentry.models import ( + AuditLogEntry, Activity, AuthIdentity, GroupBookmark, + OrganizationMember, UserOption + ) + + for obj in OrganizationMember.objects.filter(user=from_user): + try: + with transaction.atomic(): + obj.update(user=to_user) + except IntegrityError: + pass + for obj in GroupBookmark.objects.filter(user=from_user): + try: + with transaction.atomic(): + obj.update(user=to_user) + except IntegrityError: + pass + for obj in UserOption.objects.filter(user=from_user): + try: + with transaction.atomic(): + obj.update(user=to_user) + except IntegrityError: + pass + + Activity.objects.filter( + user=from_user, + ).update(user=to_user) + AuditLogEntry.objects.filter( + actor=from_user, + ).update(actor=to_user) + AuditLogEntry.objects.filter( + target_user=from_user, + ).update(target_user=to_user) + AuthIdentity.objects.filter( + user=from_user, + ).update(user=to_user) diff --git a/pool/shard006/Python/0057703_example_1.py b/pool/shard006/Python/0057703_example_1.py new file mode 100644 index 0000000000000000000000000000000000000000..d035506a4533c544ac56b80f418dd1f9654833fe --- /dev/null +++ b/pool/shard006/Python/0057703_example_1.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python2 + +import subprocess +import atexit +import sys +from math import pi +from chips.api.api import Chip, Stimulus, Response, Wire, Component + +#try: +from matplotlib import pyplot +#except ImportError: + #print "You need matplotlib to run this script!" + #exit(0) + +def test(): + + chip = Chip("square_root") + + test_in = Stimulus(chip, "input", "float", [i*0.1 for i in range(100)]) + test_out = Response(chip, "output", "float") + + #create a filter component using the C code + sqrt = Component("sqrt.c") + + #add an instance to the chip + sqrt( + chip, + inputs = { + "x":test_in, + }, + outputs = { + "sqrt_x":test_out, + }, + ) + + #run the simulation + chip.simulation_reset() + while len(test_out) < 100: + chip.simulation_step() + + pyplot.plot(list(test_in), list(test_out)) + pyplot.xlim(0, 10.1) + pyplot.title("Square Root of x") + pyplot.xlabel("x") + pyplot.ylabel("$\\sqrt{x}$") + pyplot.savefig("../docs/source/examples/images/example_1.png") + pyplot.show() + +def indent(lines): + return "\n ".join(lines.splitlines()) + +def generate_docs(): + + documentation = """ + +Calculate Square Root using Newton's Method +=========================================== + +In this example, we calculate the sqrt of a number using `Newton's method +`_. +The problem of finding the square root can be expressed as: + +.. math:: + + n = x^2 + +Which can be rearranged as: + +.. math:: + + f(x) = x^2 - n + +Using Newton's method, we can find numerically the approximate point at which +:math:`f(x) = 0`. Repeated applications of the following expression yield +increasingly accurate approximations of the Square root: + +.. math:: + + f(x_k) = x_{k-1} - \\frac{{x_{k-1}}^2 - n}{2x_{k-1}} + +Turning this into a practical solution, the following code calculates the square +root of a floating point number. An initial approximation is refined using +Newton's method until further refinements agree to within a small degree. + +.. code-block:: c + + %s + +Note that the code isn't entirely robust, and cannot handle special cases such +as Nans, infinities or negative numbers. A simple test calculates +:math:`\\sqrt{x}` where :math:`-10 < x < 10`. + +.. image:: images/example_1.png + +"""%indent(open("sqrt.c").read()) + + document = open("../docs/source/examples/example_1.rst", "w").write(documentation) + +test() +generate_docs() diff --git a/pool/shard006/Python/0057706_basehandlers.py b/pool/shard006/Python/0057706_basehandlers.py new file mode 100644 index 0000000000000000000000000000000000000000..9be8f2bb8f711f8e4ed34c1d5e2e3dcda0e597c6 --- /dev/null +++ b/pool/shard006/Python/0057706_basehandlers.py @@ -0,0 +1,68 @@ +from __future__ import absolute_import +from google.appengine.ext import ndb +from google.appengine.api import users + +import webapp2 +from webapp2_extras import jinja2 + + +class BaseHandler(webapp2.RequestHandler): + """ + All other handlers will extend this handler + """ + + def __init__(self, request, response): + self.initialize(request, response) + self.is_admin = users.is_current_user_admin() + self.login_url = users.create_login_url(self.request.uri) + self.logout_url = users.create_logout_url(webapp2.uri_for('home')) + + self.jinja2_context = { + 'request': self.request, + 'user': self.current_user, + 'is_admin': self.is_admin, + 'login_url': self.login_url, + 'logout_url': self.logout_url + } + + @webapp2.cached_property + def jinja2(self): + return jinja2.get_jinja2(app=self.app) + + @webapp2.cached_property + def current_user(self): + user = users.get_current_user() + if user: + user.key = ndb.Key('User', user.user_id()) + return user + + def render_response(self, _template, **context): + ctx = self.jinja2_context.copy() + ctx.update(context) + rv = self.jinja2.render_template(_template, **ctx) + self.response.write(rv) + + def render_response_string(self, template_string, **context): + ctx = self.jinja2_context.copy() + ctx.update(context) + self.response.write(self.jinja2.environment.from_string( + template_string).render(**ctx)) + + +class UserHandler(BaseHandler): + def dispatch(self): + if not self.current_user: + return self.redirect(self.login_url) + + return super(UserHandler, self).dispatch() + + +class AdminHandler(BaseHandler): + def dispatch(self): + if not self.current_user: + return self.redirect(self.login_url) + + if not self.is_admin: + self.abort(403, detail="You need admin privileges to access this URL.") + + super(AdminHandler, self).dispatch() diff --git a/pool/shard006/Python/0057707_RiCIMU.py b/pool/shard006/Python/0057707_RiCIMU.py new file mode 100644 index 0000000000000000000000000000000000000000..c0d70695116afbab4b9ac556d8038b6597f0bfe6 --- /dev/null +++ b/pool/shard006/Python/0057707_RiCIMU.py @@ -0,0 +1,148 @@ +import re +from threading import Thread +import rospy +import rostopic +from BAL.Handlers.keepAliveHandler import KeepAliveHandler +from BAL.Header.Requests.PublishRequest import PublishRequest +from BAL.Header.Requests.imuRequest import IMURequest +from BAL.Header.Response.ParamBuildResponse import IMU + +__author__ = 'tom1231' +from rospy import Publisher, Service +from sensor_msgs.msg import Imu, MagneticField +from BAL.Interfaces.Device import Device +from tf.transformations import euler_from_quaternion, quaternion_from_euler +from geometry_msgs.msg import Quaternion +from math import pi +from ric_board.srv._calibIMU import calibIMU, calibIMURequest +from ric_board.msg._imuCalib import imuCalib + +CALIB_ID = 1 +PUB_ID = 2 + +class RiCIMU(Device): + def __init__(self, param, output): + Device.__init__(self, param.getIMUName(), output) + self._frameId = param.getIMUFrameId() + self._angle = param.getIMUOrientation() + self._pub = Publisher('%s_AGQ' % self._name, Imu, queue_size=param.getIMUPubHz()) + self._pubMag = Publisher('%s_M' % self._name, MagneticField, queue_size=param.getIMUPubHz()) + self._pubCalib = Publisher('/imu_calib_publisher', imuCalib, queue_size=param.getIMUPubHz()) + Service('/imu_Calibration', calibIMU, self.serviceCallBack) + self._haveRightToPublish = False + self._calib = False + self._xMax = 0.0 + self._yMax = 0.0 + self._zMax = 0.0 + self._xMin = 0.0 + self._yMin = 0.0 + self._zMin = 0.0 + #KeepAliveHandler('%s_AGQ' % self._name, Imu) + + def getType(self): + return IMU + + def serviceCallBack(self, request): + validStatus = True + + if request.status == calibIMURequest.START_CALIB: + rospy.loginfo("Calibration begin") + self._output.write(IMURequest(calibIMURequest.START_CALIB).dataTosend()) + self._calib = True + + self._xMax = request.xMax + self._yMax = request.yMax + self._zMax = request.zMax + self._xMin = request.xMin + self._yMin = request.yMin + self._zMin = request.zMin + + elif request.status == calibIMURequest.STOP_CALIB: + rospy.loginfo("Calibration end") + self._output.write(IMURequest(calibIMURequest.STOP_CALIB).dataTosend()) + rospy.loginfo("Calibration setting saved") + self._calib = False + + else: + validStatus = False + return {'ack': validStatus} + + def publish(self, data): + if not self._calib and data.getImuMsgId() == PUB_ID: + q = data.getOrientation() + roll, pitch, yaw = euler_from_quaternion((q.y, q.z, q.w, q.x)) + #array = quaternion_from_euler(yaw + (self._angle * pi / 180), roll, pitch) + #array = quaternion_from_euler(yaw + (self._angle * pi / 180), -1 (roll - 180), -1 * pitch) + array = quaternion_from_euler((yaw + (self._angle * pi / 180)), roll, -1 * pitch) + res = Quaternion() + res.w = array[0] + res.x = array[1] + res.y = array[2] + res.z = array[3] + + msg = Imu() + msg.header.frame_id = self._frameId + msg.header.stamp = rospy.get_rostime() + msg.orientation = res + msg.linear_acceleration = data.getAcceleration() + msg.angular_velocity = data.getVelocity() + + magMsg = MagneticField() + magMsg.header.frame_id = self._frameId + magMsg.header.stamp = rospy.get_rostime() + magMsg.magnetic_field = data.getMagnetometer() + + self._pub.publish(msg) + self._pubMag.publish(magMsg) + + elif data.getImuMsgId() == CALIB_ID: + x, y, z = data.getValues() + msg = imuCalib() + + if x > self._xMax: + self._xMax = x + if x < self._xMin: + self._xMin = x + + if y > self._yMax: + self._yMax = y + if y < self._yMin: + self._yMin = y + + if z > self._zMax: + self._zMax = z + if z < self._zMin: + self._zMin = z + + + msg.x.data = x + msg.x.max = self._xMax + msg.x.min = self._xMin + + msg.y.data = y + msg.y.max = self._yMax + msg.y.min = self._yMin + + msg.z.data = z + msg.z.max = self._zMax + msg.z.min = self._zMin + + self._pubCalib.publish(msg) + + def checkForSubscribers(self): + try: + subCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pub.name)).group(0).split(': ')[1] + subMagCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pubMag.name)).group(0).split(': ')[1] + subCalibCheck = \ + re.search('Subscribers:.*', rostopic.get_info_text(self._pubCalib.name)).group(0).split(': ')[1] + + if not self._haveRightToPublish and (subCheck == '' or subMagCheck == '' or subCalibCheck == ''): + self._output.write(PublishRequest(IMU, 0, True).dataTosend()) + self._haveRightToPublish = True + + elif self._haveRightToPublish and ( + subCheck == 'None' and subMagCheck == 'None' and subCalibCheck == 'None'): + self._output.write(PublishRequest(IMU, 0, False).dataTosend()) + self._haveRightToPublish = False + except: + pass diff --git a/pool/shard006/Python/0057709_test_fetch.py b/pool/shard006/Python/0057709_test_fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..4933ce54b852eff8355a19b93bda6378a4df1cd9 --- /dev/null +++ b/pool/shard006/Python/0057709_test_fetch.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +# Copyright (c) 2012 Cloudera, 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 pytest +import re +from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session +from TCLIService import TCLIService + +# Simple test to make sure all the HS2 types are supported for both the row and +# column-oriented versions of the HS2 protocol. +class TestFetch(HS2TestSuite): + def __verify_result_precision_scale(self, t, precision, scale): + # This should be DECIMAL_TYPE but how do I get that in python + assert t.typeDesc.types[0].primitiveEntry.type == 15 + p = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['precision'] + s = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['scale'] + assert p.i32Value == precision + assert s.i32Value == scale + + @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1) + def test_alltypes_v1(self): + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + + execute_statement_req.statement =\ + "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 1" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + HS2TestSuite.check_response(execute_statement_resp) + results = self.fetch(execute_statement_resp.operationHandle, + TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1) + assert len(results.results.rows) == 1 + self.close(execute_statement_resp.operationHandle) + + execute_statement_req.statement =\ + "SELECT d1,d5 FROM functional.decimal_tbl ORDER BY d1 LIMIT 1" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + HS2TestSuite.check_response(execute_statement_resp) + results = self.fetch(execute_statement_resp.operationHandle, + TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1) + assert len(results.results.rows) == 1 + + # Verify the result schema is what we expect. The result has 2 columns, the + # first is decimal(9,0) and the second is decimal(10,5) + metadata_resp = self.result_metadata(execute_statement_resp.operationHandle) + column_types = metadata_resp.schema.columns + assert len(column_types) == 2 + self.__verify_result_precision_scale(column_types[0], 9, 0) + self.__verify_result_precision_scale(column_types[1], 10, 5) + + self.close(execute_statement_resp.operationHandle) + + def __query_and_fetch(self, query): + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = query + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + HS2TestSuite.check_response(execute_statement_resp) + + fetch_results_req = TCLIService.TFetchResultsReq() + fetch_results_req.operationHandle = execute_statement_resp.operationHandle + fetch_results_req.maxRows = 1024 + fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req) + HS2TestSuite.check_response(fetch_results_resp) + + return fetch_results_resp + + def __column_results_to_string(self, columns): + """Quick-and-dirty way to get a readable string to compare the output of a + columnar-oriented query to its expected output""" + formatted = "" + num_rows = 0 + # Determine the number of rows by finding the type of the first column + for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES: + typed_col = getattr(columns[0], col_type) + if typed_col != None: + num_rows = len(typed_col.values) + break + + for i in xrange(num_rows): + row = [] + for c in columns: + for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES: + typed_col = getattr(c, col_type) + if typed_col != None: + indicator = ord(typed_col.nulls[i / 8]) + if indicator & (1 << (i % 8)): + row.append("NULL") + else: + row.append(str(typed_col.values[i])) + break + formatted += (", ".join(row) + "\n") + return (num_rows, formatted) + + @needs_session() + def test_alltypes_v6(self): + """Test that a simple select statement works for all types""" + fetch_results_resp = self.__query_and_fetch( + "SELECT *, NULL from functional.alltypes ORDER BY id LIMIT 1") + + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert num_rows == 1 + assert result == \ + "0, True, 0, 0, 0, 0, 0.0, 0.0, 01/01/09, 0, 2009-01-01 00:00:00, 2009, 1, NULL\n" + + # Decimals + fetch_results_resp = self.__query_and_fetch( + "SELECT * from functional.decimal_tbl LIMIT 1") + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert result == ("1234, 2222, 1.2345678900, " + "0.12345678900000000000000000000000000000, 12345.78900, 1\n") + + # VARCHAR + fetch_results_resp = self.__query_and_fetch("SELECT CAST('str' AS VARCHAR(3))") + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert result == "str\n" + + # CHAR not inlined + fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(140))") + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert result == "car" + (" " * 137) + "\n" + + # CHAR inlined + fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(5))") + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert result == "car \n" + + @needs_session() + def test_show_partitions(self): + """Regression test for IMPALA-1330""" + for query in ["SHOW PARTITIONS functional.alltypes", + "SHOW TABLE STATS functional.alltypes"]: + fetch_results_resp = self.__query_and_fetch(query) + num_rows, result = \ + self.__column_results_to_string(fetch_results_resp.results.columns) + assert num_rows == 25 + # Match whether stats are computed or not + assert re.match( + r"2009, 1, -?\d+, -?\d+, \d*\.?\d+KB, NOT CACHED, TEXT", result) is not None + + @needs_session() + def test_show_column_stats(self): + fetch_results_resp = self.__query_and_fetch("SHOW COLUMN STATS functional.alltypes") + num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns) + assert num_rows == 13 + assert re.match(r"id, INT, -?\d+, -?\d+, (NULL|\d+), 4.0", result) is not None + + @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1) + def test_execute_select_v1(self): + """Test that a simple select statement works in the row-oriented protocol""" + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + HS2TestSuite.check_response(execute_statement_resp) + + fetch_results_req = TCLIService.TFetchResultsReq() + fetch_results_req.operationHandle = execute_statement_resp.operationHandle + fetch_results_req.maxRows = 100 + fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req) + HS2TestSuite.check_response(fetch_results_resp) + + assert len(fetch_results_resp.results.rows) == 1 + assert fetch_results_resp.results.startRowOffset == 0 + + try: + assert not fetch_results_resp.hasMoreRows + except AssertionError: + pytest.xfail("IMPALA-558") + + @needs_session() + def test_select_null(self): + """Regression test for IMPALA-1370, where NULL literals would appear as strings where + they should be booleans""" + execute_statement_req = TCLIService.TExecuteStatementReq() + execute_statement_req.sessionHandle = self.session_handle + execute_statement_req.statement = "select null" + execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req) + HS2TestSuite.check_response(execute_statement_resp) + + # Check that the expected type is boolean (for compatibility with Hive, see also + # IMPALA-914) + get_result_metadata_req = TCLIService.TGetResultSetMetadataReq() + get_result_metadata_req.operationHandle = execute_statement_resp.operationHandle + get_result_metadata_resp = \ + self.hs2_client.GetResultSetMetadata(get_result_metadata_req) + col = get_result_metadata_resp.schema.columns[0] + assert col.typeDesc.types[0].primitiveEntry.type == TCLIService.TTypeId.BOOLEAN_TYPE + + # Check that the actual type is boolean + fetch_results_req = TCLIService.TFetchResultsReq() + fetch_results_req.operationHandle = execute_statement_resp.operationHandle + fetch_results_req.maxRows = 1 + fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req) + HS2TestSuite.check_response(fetch_results_resp) + assert fetch_results_resp.results.columns[0].boolVal is not None + + assert self.__column_results_to_string( + fetch_results_resp.results.columns) == (1, "NULL\n") + + @needs_session() + def test_compute_stats(self): + """Exercise the child query path""" + self.__query_and_fetch("compute stats functional.alltypes") diff --git a/pool/shard006/Python/0057718_gmusic.py b/pool/shard006/Python/0057718_gmusic.py new file mode 100644 index 0000000000000000000000000000000000000000..bc912e9c81e2927a12ff3e8332894d57f8255a28 --- /dev/null +++ b/pool/shard006/Python/0057718_gmusic.py @@ -0,0 +1,60 @@ +from gmusicapi import Mobileclient +import getpass + +class GpmSession(object): + # Private Variables + + # Public Variables + api = None + logged_in = False + songs = None + playlists = None + + # Constructor with optionally passed credentials + # Omit credentials if you want to handle login, include for prompts from this module + def __init__(self, email=None, pw=None): + self.api = Mobileclient() + if not email and not pw == None: + email = input("Please enter an email address tied to a GPM account: ") + pw = getpass.getpass("Please enter the password associated with %s " % email) + self.logged_in = self.api.login(email, pw, Mobileclient.FROM_MAC_ADDRESS) # As per api protocol + if self.logged_in: + print("Google Play Music login successful") + else: + print("Google Play Music login failed") + + def init(self, songs = True, playlists = True): + if songs: + self.songs = self.api.get_all_songs() + if playlists: + self.playlists = self.api.get_all_playlists() + + def get_song_stream(self, title, artist=None): + print(not self.songs) + if not self.songs: + self.init(True, False) + song = next(iter((track for track in self.songs if self._filter_condition(track, title, artist)) or []), None) + if song: + return self.api.get_stream_url(song["id"]) + else: + return None + + + def _filter_condition(self, song_obj, search_title, search_artist): + result = True + if search_title: + result = result & (song_obj["title"].lower().strip() == search_title.lower().strip()) + if search_artist: + result = result & (song_obj["artist"].lower().strip() == search_artist.lower().strip()) + return result + +def main(): + session = GpmSession() + while not session.logged_in: + session = GpmSession() + session.init() + print(session.get_song_stream("Dirty Laundry", "Bitter Sweet")) + print(session.get_song_stream("1940")) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard006/Python/0057719_graphSim.py b/pool/shard006/Python/0057719_graphSim.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf7edf078a2b19e771c0618a280d17e38604e70 --- /dev/null +++ b/pool/shard006/Python/0057719_graphSim.py @@ -0,0 +1,77 @@ +#This program will run and graph the simulation, comparing serial and parallel +import sys +import ConfigParser +from subprocess import call +#If not the independent variable, these values will be used +MOLECULES = 2112 +SIZE = 40 +STEPS = 10000 +DENSITY = .033 #the density of water +#function to change the time steps in demoConfiguration.txt +def changeConfigFile(timeSteps, molecules, size): + f = open('resources/demo.config','r') + lines = f.readlines() + lines[1] = str(size) + '\n' + lines[2] = str(size) + '\n' + lines[3] = str(size) + '\n' + lines[9] = str(timeSteps) + '\n' + lines[11] = str(molecules) + '\n' + f.close() + f = open('resources/demo.config','w') + for item in lines: + f.write(item) + f.close() +#function to get the run-time from the last run +def getRunTime(): + config = ConfigParser.RawConfigParser() + config.read('run.results') + line = config.get('Results','Run-Time') + line = line.split() + return line[0] +#function to print out the help information +def printHelp(): + print "***HELP***" + print "Usage: python graphing/graphSim.py xaxis interval" + print "xaxis is what parameter should be on the xaxis: 'steps', 'size', or 'density" + print "interval is the xvalues separated by spaces" + print "density is in number of molecules/volume" + print "Example: python graphing/graphSim density .01 .02 .03 .04\n" +#Begin program +input = sys.argv +#check for invalud inputs +if len(input) < 3: + printHelp() + exit(0) +input.remove("graphing/graphSim.py") +xaxis = input.pop(0) +if xaxis != "steps" and xaxis != "size" and xaxis != "density": + print "Error: invalid format" + printHelp() + exit(0) +#capitalize for ease of printing +xaxis = xaxis.capitalize() +#run simulation and prepare output +f = open('graphing/simResults.txt', 'w') +f.write(xaxis + '\tSerial\tParallel\n') +for i in input: + if xaxis == "Steps": + changeConfigFile(i, MOLECULES, SIZE) + if xaxis == "Size": + changeConfigFile(STEPS, int(i)*int(i)*int(i)*DENSITY, i) + if xaxis == "Density": + changeConfigFile(STEPS, float(i)*SIZE*SIZE*SIZE, SIZE) + f.write(i+'\t') + call(["./bin/metrosim", "resources/demo.config", "-s"]) + f.write(getRunTime()+'\t') + call(["./bin/metrosim", "resources/demo.config", "-p"]) + f.write(getRunTime()+'\n') +f.close() +#set up gnuplot +f = open('graphing/gnuplotScript','w') +f.write("set terminal png\nset output 'graph.png'\nset key left top\n") +f.write("set title 'Serial/Parallel Time Comparison'\n") +f.write("set ylabel 'Time (s)'\nset xlabel '" + xaxis) +f.write("'\nplot 'graphing/simResults.txt' using 1:2 w lp title 'Serial', 'graphing/simResults.txt' using 1:3 w lp title 'Parallel'") +f.close() +#call gnuplot +call(["gnuplot", "graphing/gnuplotScript"]) \ No newline at end of file diff --git a/pool/shard006/Python/0057724_plot_gait.py b/pool/shard006/Python/0057724_plot_gait.py new file mode 100644 index 0000000000000000000000000000000000000000..c6903ff50413e98fde7aa4094b82106d51aa0125 --- /dev/null +++ b/pool/shard006/Python/0057724_plot_gait.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +""" +==================== +Gait (steps) example +==================== +In this example, we use DiCoDiLe on an open dataset of gait (steps) IMU +time-series to discover patterns in the data. We will then use those to attempt +to detect steps and compare our findings with the ground truth. +""" + +import matplotlib.pyplot as plt +import numpy as np + +############################################################################### +# # Retrieve trial data + +from dicodile.data.gait import get_gait_data + +trial = get_gait_data(subject=6, trial=1) + +############################################################################### +# Let’s have a look at the data for one trial. + +trial.keys() + +############################################################################### +# We get a dictionary whose keys are metadata items, plus a ‘data’ key that +# contains a numpy array with the trial time series for each sensor axis, at +# 100 Hz resolution. + +# right foot acceleration (vertical) +plt.plot(trial['data']['RAV']) + +############################################################################### +# Let’s look at a small portion of the series for both feet, overlaid on the +# same plot. + +fig, ax = plt.subplots() +ax.plot(trial['data']['LAV'][5000:5800], + label='left foot vertical acceleration') +ax.plot(trial['data']['RAV'][5000:5800], + label='right foot vertical acceleration') +ax.set_xlabel('time (x10ms)') +ax.set_ylabel('acceleration ($m.s^{-2}$)') +ax.legend() + +############################################################################### +# We can see the alternating left and right foot movements. +# +# In the rest of this example, we will only use the right foot vertical +# acceleration. + +############################################################################### +# # Convolutional Dictionary Learning + +############################################################################### +# Now, let’s use "dicodile" as solver_z to learn patterns from the data and +# reconstruct the signal from a sparse representation. +# +# First, we initialize a dictionary from parts of the signal: + +X = trial['data']['RAV'].to_numpy() + +# reshape X to (n_trials, n_channels, n_times) +X = X.reshape(1, 1, *X.shape) + +print(X.shape) + +############################################################################### +# Note the use of reshape to shape the signal as per alphacsc requirements: the +# shape of the signal should be (n_trials, n_channels, n_times). Here, we have +# a single-channel time series so it is (1, 1, n_times). + +from alphacsc.init_dict import init_dictionary + +# set dictionary size +n_atoms = 8 + +# set individual atom (patch) size. +n_times_atom = 200 + +D_init = init_dictionary(X, + n_atoms=8, + n_times_atom=200, + rank1=False, + window=True, + D_init='chunk', + random_state=60) + +print(D_init.shape) + +"" +from alphacsc import BatchCDL + +cdl = BatchCDL( + # Shape of the dictionary + n_atoms, + n_times_atom, + rank1=False, + uv_constraint='auto', + # Number of iteration for the alternate minimization and cvg threshold + n_iter=3, + # number of workers to be used for dicodile + n_jobs=4, + # solver for the z-step + solver_z='dicodile', + solver_z_kwargs={'max_iter': 10000}, + window=True, + D_init=D_init, + random_state=60) + +res = cdl.fit(X) + +"" +from dicodile.utils.viz import display_dictionaries + +D_hat = res._D_hat + +fig = display_dictionaries(D_init, D_hat) + +############################################################################### +# # Signal reconstruction + +############################################################################### +# Now, let's reconstruct the original signal. + +from alphacsc.utils import construct_X_multi + +z_hat = res._z_hat + +X_hat = construct_X_multi(z_hat, D_hat) + +############################################################################### +# Plot a small part of the original and reconstructed signals + +fig_hat, ax_hat = plt.subplots() +ax_hat.plot(X[0][0][5000:5800], + label='right foot vertical acceleration (ORIGINAL)') +ax_hat.plot(X_hat[0][0][5000:5800], + label='right foot vertical acceleration (RECONSTRUCTED)') +ax_hat.set_xlabel('time (x10ms)') +ax_hat.set_ylabel('acceleration ($m.s^{-2}$)') +ax_hat.legend() + +############################################################################### +# Check that our representation is indeed sparse: + + +np.count_nonzero(z_hat) + +############################################################################### +# Besides our visual check, a measure of how closely we’re reconstructing the +# original signal is the (normalized) cross-correlation. Let’s compute this: + +np.correlate(X[0][0], X_hat[0][0]) / np.sqrt( + np.correlate(X[0][0], X[0][0]) * np.correlate(X_hat[0][0], X_hat[0][0]) +) + +############################################################################### +# # Multichannel signals + +############################################################################### +# DiCoDiLe works just as well with multi-channel signals. The gait dataset +# contains 16 signals (8 for each foot), in the rest of this tutorial, we’ll +# use three of those. + +# Left foot Vertical acceleration, Y rotation and X acceleration +channels = ['LAV', 'LRY', 'LAX'] + +############################################################################### +# Let’s look at a small portion of multi-channel data + +colors = plt.rcParams["axes.prop_cycle"]() +mc_fig, mc_ax = plt.subplots(len(channels), sharex=True) + +for ax, chan in zip(mc_ax, channels): + ax.plot(trial['data'][chan][5000:5800], + label=chan, color=next(colors)["color"]) +mc_fig.legend(loc="upper center") + +############################################################################### +# Let’s put the data in shape for alphacsc: (n_trials, n_channels, n_times) + +X_mc_subset = trial['data'][channels].to_numpy().T + +X_mc_subset = X_mc_subset.reshape(1, *X_mc_subset.shape) + +print(X_mc_subset.shape) + +############################################################################### +# Initialize the dictionary (note that the call is identical to the +# single-channel version) + +D_init_mc = init_dictionary( + X_mc_subset, n_atoms=8, n_times_atom=200, rank1=False, + window=True, D_init='chunk', random_state=60 +) + +print(D_init_mc.shape) + +############################################################################### +# And run DiCoDiLe (note that the call is identical to the single-channel +# version here as well) + +from alphacsc import BatchCDL + +cdl = BatchCDL( + # Shape of the dictionary + n_atoms, + n_times_atom, + rank1=False, + uv_constraint='auto', + # Number of iteration for the alternate minimization and cvg threshold + n_iter=3, + # number of workers to be used for dicodile + n_jobs=4, + # solver for the z-step + solver_z='dicodile', + solver_z_kwargs={'max_iter': 10000}, + window=True, + D_init=D_init_mc, + random_state=60) + +res = cdl.fit(X_mc_subset) + +############################################################################### +# # Signal reconstruction (multichannel) + +############################################################################### +# Now, let’s reconstruct the original signal + +from alphacsc.utils import construct_X_multi + +z_hat_mc = res._z_hat + +D_hat_mc = res._D_hat + +X_hat_mc = construct_X_multi(z_hat_mc, D_hat_mc) + +############################################################################### +# Let’s visually compare a small part of the original and reconstructed signal +# along with the activations. + +z_hat_mc.shape + +"" +viz_start_idx = 4000 +viz_end_idx = 5800 +viz_chan = 2 + +max_abs = np.max(np.abs(z_hat_mc), axis=-1) +max_abs = max_abs.reshape(z_hat_mc.shape[1], 1) +z_hat_normalized = z_hat_mc / max_abs + +fig_hat_mc, ax_hat_mc = plt.subplots(2, figsize=(12, 8)) + +# plot original and constructed +ax_hat_mc[0].plot(X_mc_subset[0][viz_chan][viz_start_idx:viz_end_idx], + label='ORIGINAL') +ax_hat_mc[0].plot(X_hat_mc[0][viz_chan][viz_start_idx:viz_end_idx], + label='RECONSTRUCTED') + +ax_hat_mc[0].set_xlabel('time (x10ms)') +ax_hat_mc[0].legend() + +# plot activations +for idx in range(z_hat_normalized.shape[1]): + ax_hat_mc[1].stem(z_hat_normalized[0][idx][viz_start_idx:viz_end_idx], + linefmt=f"C{idx}-", + markerfmt=f"C{idx}o") diff --git a/pool/shard006/Python/0057730_screenshot.py b/pool/shard006/Python/0057730_screenshot.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc8d38a7889bd23c5116cf1f1306b3580117376 --- /dev/null +++ b/pool/shard006/Python/0057730_screenshot.py @@ -0,0 +1,91 @@ +# 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. + +from __future__ import absolute_import +import datetime +import logging +import os +import random +import tempfile + +import py_utils +from py_utils import cloud_storage # pylint: disable=import-error +from telemetry.util import image_util +from telemetry.internal.util import file_handle + + +def TryCaptureScreenShot(platform, tab=None, timeout=None): + """ If the platform or tab supports screenshot, attempt to take a screenshot + of the current browser. + + Args: + platform: current platform + tab: browser tab if available + timeout: An float denoting the number of seconds to wait for a successful + screenshot. If set to None, only attempts once. + + Returns: + file handle of the tempoerary file path for the screenshot if + present, None otherwise. + """ + try: + if platform.CanTakeScreenshot(): + tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png') + tf.close() + try: + py_utils.WaitFor(lambda: platform.TakeScreenshot(tf.name), timeout or 0) + except py_utils.TimeoutException: + logging.warning('Did not succeed in screenshot capture') + return file_handle.FromTempFile(tf) + if tab and tab.IsAlive() and tab.screenshot_supported: + tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png') + tf.close() + image = tab.Screenshot() + image_util.WritePngFile(image, tf.name) + return file_handle.FromTempFile(tf) + logging.warning( + 'Either tab has crashed or browser does not support taking tab ' + 'screenshot. Skip taking screenshot on failure.') + return None + except Exception as e: # pylint: disable=broad-except + logging.warning('Exception when trying to capture screenshot: %s', repr(e)) + return None + + +def TryCaptureScreenShotAndUploadToCloudStorage(platform, tab=None): + """ If the platform or tab supports screenshot, attempt to take a screenshot + of the current browser. If present it uploads this local path to cloud + storage and returns the URL of the cloud storage path. + + Args: + platform: current platform + tab: browser tab if available + + Returns: + url of the cloud storage path if screenshot is present, None otherwise + """ + fh = TryCaptureScreenShot(platform, tab) + if fh is not None: + return _UploadScreenShotToCloudStorage(fh) + + return None + +def _GenerateRemotePath(fh): + return ('browser-screenshot_%s-%s%-d%s' % + (fh.id, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), + random.randint(1, 100000), fh.extension)) + +def _UploadScreenShotToCloudStorage(fh): + """ Upload the given screenshot image to cloud storage and return the + cloud storage url if successful. + """ + try: + return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT, + _GenerateRemotePath(fh), fh.GetAbsPath()) + except cloud_storage.CloudStorageError as err: + logging.error('Cloud storage error while trying to upload screenshot: %s', + repr(err)) + return '' + finally: # Must clean up screenshot file if exists. + os.remove(fh.GetAbsPath()) diff --git a/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py b/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbfe50529f81f0d0a262e5fa16c700580a3350d --- /dev/null +++ b/pool/shard006/Python/0057733_SpatialSoftMaxCUDNN.py @@ -0,0 +1,36 @@ +import DeepFried2 as df + + +def spatial_softmax(img, algo, mode): + # check if we have 3D input + if img.ndim == 5: + # shape: bcd01 + vol_shape = img.shape + # shape: bcd(0*1) + vol = df.T.flatten(img, outdim=4) + vol = df.th.sandbox.cuda.basic_ops.gpu_contiguous(vol) + res = df.th.sandbox.cuda.dnn.GpuDnnSoftmax(tensor_format='bc01', algo=algo, mode=mode)(vol) + # shape: bcd01 + return res.reshape(vol_shape) + else: + img = df.th.sandbox.cuda.basic_ops.gpu_contiguous(img) + return df.th.sandbox.cuda.dnn.GpuDnnSoftmax(tensor_format='bc01', algo=algo, mode=mode)(img) + + +class SpatialSoftMaxCUDNN(df.Module): + def __init__(self, algo='accurate', mode='channel'): + """ + - `algo`: One of the following values: + - `'fast'`: Straightforward softmax, beware numerical problems. + - `'accurate'`: Use the "subtract max input" stabilization to avoid overflows. + - `'log'`: Compute the log-softmax instead. + - `mode`: One of the following values: + - `'instance'`: Computes a single whole softmax per image (across C,H,W; output is B). + - `'channel'`: Computs a softmax per-pixel per-image (across C; output is B,H,W). + """ + df.Module.__init__(self) + self.algo = algo + self.mode = mode + + def symb_forward(self, symb_input): + return spatial_softmax(symb_input, self.algo, self.mode) diff --git a/pool/shard006/Python/0057735_na_ontap_command.py b/pool/shard006/Python/0057735_na_ontap_command.py new file mode 100644 index 0000000000000000000000000000000000000000..1af0bb7c57e490729130fed1c61646bd162e6cd2 --- /dev/null +++ b/pool/shard006/Python/0057735_na_ontap_command.py @@ -0,0 +1,132 @@ +#!/usr/bin/python + +# (c) 2018, NetApp, 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 + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'certified'} + +DOCUMENTATION = ''' +author: NetApp Ansible Team (@carchi8py) +description: + - "Run system-cli commands on ONTAP" +extends_documentation_fragment: + - netapp.na_ontap +module: na_ontap_command +short_description: NetApp ONTAP Run any cli command, the username provided needs to have console login permission. +version_added: "2.7" +options: + command: + description: + - a comma separated list containing the command and arguments. + required: true + privilege: + description: + - privilege level at which to run the command. + choices: ['admin', 'advanced'] + default: admin + version_added: "2.8" +''' + +EXAMPLES = """ + - name: run ontap cli command + na_ontap_command: + hostname: "{{ hostname }}" + username: "{{ admin username }}" + password: "{{ admin password }}" + command: ['version'] + + - name: run ontap cli command + na_ontap_command: + hostname: "{{ hostname }}" + username: "{{ admin username }}" + password: "{{ admin password }}" + command: ['network', 'interface', 'show'] + privilege: 'admin' +""" + +RETURN = """ +""" + +import traceback +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_native +import ansible.module_utils.netapp as netapp_utils + +HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() + + +class NetAppONTAPCommand(object): + ''' calls a CLI command ''' + + def __init__(self): + self.argument_spec = netapp_utils.na_ontap_host_argument_spec() + self.argument_spec.update(dict( + command=dict(required=True, type='list'), + privilege=dict(required=False, type='str', choices=['admin', 'advanced'], + default='admin') + )) + self.module = AnsibleModule( + argument_spec=self.argument_spec, + supports_check_mode=True + ) + parameters = self.module.params + # set up state variables + self.command = parameters['command'] + self.privilege = parameters['privilege'] + + if HAS_NETAPP_LIB is False: + self.module.fail_json(msg="the python NetApp-Lib module is required") + else: + self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) + + def asup_log_for_cserver(self, event_name): + """ + Fetch admin vserver for the given cluster + Create and Autosupport log event with the given module name + :param event_name: Name of the event log + :return: None + """ + results = netapp_utils.get_cserver(self.server) + cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) + netapp_utils.ems_log_event(event_name, cserver) + + def run_command(self): + ''' calls the ZAPI ''' + self.asup_log_for_cserver("na_ontap_command: " + str(self.command)) + command_obj = netapp_utils.zapi.NaElement("system-cli") + args_obj = netapp_utils.zapi.NaElement("args") + for arg in self.command: + args_obj.add_new_child('arg', arg) + command_obj.add_child_elem(args_obj) + command_obj.add_new_child('priv', self.privilege) + + try: + output = self.server.invoke_successfully(command_obj, True) + return output.to_string() + except netapp_utils.zapi.NaApiError as error: + self.module.fail_json(msg='Error running command %s: %s' % + (self.command, to_native(error)), + exception=traceback.format_exc()) + + def apply(self): + ''' calls the command and returns raw output ''' + changed = True + output = self.run_command() + self.module.exit_json(changed=changed, msg=output) + + +def main(): + """ + Execute action from playbook + """ + command = NetAppONTAPCommand() + command.apply() + + +if __name__ == '__main__': + main() diff --git a/pool/shard006/Python/0057738_example.py b/pool/shard006/Python/0057738_example.py new file mode 100644 index 0000000000000000000000000000000000000000..97952a68a4ba9a2220242856684709db1f1fefaa --- /dev/null +++ b/pool/shard006/Python/0057738_example.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python + +import sys, os, getpass, datetime + +# PyGithub >= 1.13 is required https://pypi.python.org/pypi/PyGithub +from github import Github +from github_issues import GithubIssuesBase, GithubIssues + +# You could use OAuth here too for unattended access +# see http://developer.github.com/v3/oauth/#create-a-new-authorization +print "Enter github username:" +username = sys.stdin.readline().strip() +print +password = getpass.getpass('Enter github password: ') + +gh = Github(login_or_token=username, password=password, user_agent='PyGithub/Python') +# needed to fetch fresh rate_limiting data +repo = gh.get_repo('autotest/virt-test') + +# Requests for logged in users are limited to 5000 per hour +# or about 1 request every 0.7 seconds +start = gh.rate_limiting +# Open up cache and repository +issues = GithubIssues(gh, 'autotest/virt-test') +print "Issue #125: ", +# Any issue can be referenced by number +print issues[125] +end = gh.rate_limiting +print "Requests used: ", start[0] - end[0] +print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses) + +# Pull requests are treated as issues +issues = GithubIssues(gh, 'autotest/virt-test') +start = end +print "Pull #526: ", +print issues[526] +end = gh.rate_limiting +print "Requests used: ", start[0] - end[0] +print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses) + +# Listing issues requires finding the last issue +# this takes a while when the cache is empty +issues = GithubIssues(gh, 'autotest/virt-test') +start = end +print "Total number of issues (this could take a while):" +# This len() is used to force the slower binary-search +print GithubIssuesBase.__len__(issues) +end = gh.rate_limiting +print "Requests used: ", start[0] - end[0] +print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses) + +# Searches are supported and return lists of issue-numbers +issues = GithubIssues(gh, 'autotest/virt-test') +start = end +print "Open issues last few days without any label (could take 2-10 minutes):" +two_days = datetime.timedelta(days=2) +last_week = datetime.datetime.now() - two_days +# Search criteria is put into a dictionary +# state - str - 'open', 'closed' +# assignee - list of str (login), "none" or "*" +# mentioned - str (login) +# labels - list of str (label name) +# sort - str - 'created', 'updated', 'comments' +# direction - str - 'asc', 'desc' +# since - datetime.datetime +criteria = {'state':'open', 'since':last_week} +# Search results are cached for 10-minutes, otherwise searches can be slow +for number in issues.search(criteria): + issue = issues[number] + # some items must be searched/compared manually + if len(issue['labels']) < 1: + print ('https://github.com/autotest/virt-test/issues/%s\t"%s"' + % (issue['number'], issue['summary'])) +print +print "Requests used: ", start[0] - end[0] +print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses) + +# Now that cache is populated, this will be very fast +issues = GithubIssues(gh, 'autotest/virt-test') +start = end +print "Total number of issues (this should be a lot faster):" +# This length uses a cached issue count plus a 'since' criteria search +print len(issues) +end = gh.rate_limiting +print "Final Requests used: ", start[0] - end[0] +print "Cache hits: %s misses: %s" % (issues.cache_hits, issues.cache_misses) +del issues diff --git a/pool/shard006/Python/0057739_processor.py b/pool/shard006/Python/0057739_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..808a0c447b2211474f0c6c2b3aa0e3a13edf3388 --- /dev/null +++ b/pool/shard006/Python/0057739_processor.py @@ -0,0 +1,67 @@ +from __future__ import unicode_literals + +from django.conf import settings +from lib.core.utils import load_class +from .exceptions import DeadConnectionException +import logging +logger = logging.getLogger(__name__) + + +class MiddlewareCache(object): + _cache = None + + def __init__(self): + self._cache = {} + + def get(self, key): + + if not key in self._cache: + self.set(key, self.load(key)) + + return self._cache.get(key) + + def set(self, key, value): + self._cache[key] = value + + def load(self, key): + return load_class(key) + + +class MessageProcessor(): + + context = None + socket = None + middleware = None + _middleware_classes = None + + def __init__(self, socket): + self.socket = socket + self.context = socket.context + self._middleware_classes = getattr(settings, 'SOCKET_MIDDLEWARE_CLASSES') + self.middleware = MiddlewareCache() + + def process_message(self, message): + + for middleware in self._middleware_classes: + + try: + Middleware = self.middleware.get(middleware) + context, message = Middleware.inbound(self.context, message) + self.context = context + except KeyError: + logger.exception("KeyError in middleware '%s' at '%s' ", middleware, message) + except DeadConnectionException as e: + #raise e + pass + #except InterfaceError: + # close_connection() + except Exception as e: + logger.exception( + "Unknown Exception thrown in middleware '%s' [%s] [%s] with '%s'", + middleware, + e.message, + e.args, + message + ) + + return self.context \ No newline at end of file diff --git a/pool/shard006/Python/0057740_ProcCpuidCollector.py b/pool/shard006/Python/0057740_ProcCpuidCollector.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb482978094ed2978c0eab54a79668b5e110eaf --- /dev/null +++ b/pool/shard006/Python/0057740_ProcCpuidCollector.py @@ -0,0 +1,51 @@ +# Copyright 2016 Casey Jaymes + +# This file is part of PySCAP. +# +# PySCAP 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. +# +# PySCAP 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 PySCAP. If not, see . + +import logging +import re +import pprint + +from scap.Collector import Collector +from scap.model.cpe_matching_2_3.CPE import CPE + +logger = logging.getLogger(__name__) +class ProcCpuidCollector(Collector): + def collect(self): + if 'devices' not in self.host.facts: + self.host.facts['devices'] = {} + + if 'cpuinfo' in self.host.facts: + return + + self.host.facts['devices']['processors'] = [] + + return_code, out_lines, err_lines = self.host.exec_command('cat /proc/cpuinfo') + if return_code == 0 and len(out_lines) >= 1: + self.host.facts['cpuinfo'] = '\n'.join(out_lines) + cur_proc = {} + for line in out_lines: + line = line.strip() + if line == '': + self.host.facts['devices']['processors'].append(cur_proc) + cur_proc = {} + continue + + k, eq, v = line.partition(':') + k = k.strip() + v = v.strip() + cur_proc[k] = v + logger.debug(k + ' = ' + v) diff --git a/pool/shard006/Python/0057745_test_util.py b/pool/shard006/Python/0057745_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..f2bc918010f93c6e224f9695bb64c37b007aa43b --- /dev/null +++ b/pool/shard006/Python/0057745_test_util.py @@ -0,0 +1,158 @@ +import unittest +import os +import sys +if sys.version_info[0] >= 3: + from io import StringIO +else: + from io import BytesIO as StringIO +import utils +TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) +utils.set_search_paths(TOPDIR) + +import allosmod.util # noqa:E402 + + +class Tests(unittest.TestCase): + def test_check_output(self): + """Test check_output()""" + out = allosmod.util.check_output(['/bin/echo', 'foo'], + universal_newlines=True) + self.assertEqual(out, 'foo\n') + self.assertRaises(OSError, allosmod.util.check_output, + ['/bin/echo', 'foo'], retcode=1) + out = allosmod.util.check_output(['/bin/cat'], input="foobar", + universal_newlines=True) + self.assertEqual(out, 'foobar') + + def test_subst_file(self): + """Test subst_file""" + s_in = StringIO("@VAR1@ @@ @VAR2@\nfoo@VAR1@bar") + s_out = StringIO() + allosmod.util.subst_file(s_in, s_out, + {'VAR1': 'tvar1', 'VAR2': 'tvar2'}) + self.assertEqual(s_out.getvalue(), 'tvar1 @ tvar2\nfootvar1bar') + s_in = StringIO("@VAR1@") + s_out = StringIO() + self.assertRaises(ValueError, allosmod.util.subst_file, s_in, s_out, + {'VAR2': 'tvar2'}) + + def test_read_templates(self): + """Test read_templates function""" + with open('lst', 'w') as fh: + fh.write('test1 A 1 10\ntest2\ntest3 B 4 5\n') + self.assertEqual(allosmod.util.read_templates('lst'), + ['test1', 'test2', 'test3']) + os.unlink('lst') + + def test_fix_newlines(self): + """Test fix_newlines function""" + def assert_content(exp_content): + with open('testnl') as fh: + content = fh.read() + self.assertEqual(content, exp_content) + with open('testnl', 'w') as fh: + fh.write("test") + allosmod.util.fix_newlines("testnl") + assert_content("test") + with open('testnl', 'w') as fh: + fh.write("test\r\nbar\r\n") + allosmod.util.fix_newlines("testnl") + assert_content("test\nbar\n") + os.unlink('testnl') + + def test_sequence(self): + """Test Sequence class""" + s = allosmod.util.Sequence() + s.primary = 'ACG/VT--W' + self.assertEqual(s.get_residues(), 'ACGVTW') + + def test_pir_file_empty(self): + """Test read of empty PIR file""" + sio = StringIO("C; comment\nR; comment\n\n") + p = allosmod.util.PIRFile() + seqs = list(p.read(sio)) + self.assertEqual(len(seqs), 0) + + def test_pir_file_unterminated_midfile(self): + """Test read of PIR file with unterminated sequence midfile""" + sio = StringIO(""">P1;template +structureX::::::::: +AFVV +>P1;seq +sequence::::::::: +AFVV* +""") + p = allosmod.util.PIRFile() + self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio)) + + def test_pir_file_unterminated_endfile(self): + """Test read of PIR file with unterminated sequence at end of file""" + sio = StringIO(""">P1;template +structureX::::::::: +AFVV* +>P1;seq +sequence::::::::: +AFVV +""") + p = allosmod.util.PIRFile() + self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio)) + + def test_pir_file_ok(self): + """Test read of OK PIR file""" + sio = StringIO(""">P1; template +structureX::::::::: +A- +FVV* +>P1;seq +::::::::: +AF/VV* +""") + p = allosmod.util.PIRFile() + seqs = list(p.read(sio)) + self.assertEqual(len(seqs), 2) + self.assertEqual(seqs[0].primary, 'A-FVV') + self.assertEqual(seqs[1].primary, 'AF/VV') + # make sure whitespace is stripped from code + self.assertEqual(seqs[0].code, 'template') + self.assertEqual(seqs[0].prottyp, 'structureX') + self.assertEqual(seqs[1].prottyp, 'sequence') + + def test_pir_file_bad_header(self): + """Test read of PIR file with bad header""" + sio = StringIO(""">P1;template +garbage +A-FVV* +""") + p = allosmod.util.PIRFile() + self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio)) + + def test_pir_file_no_header(self): + """Test read of PIR file with no header""" + sio = StringIO("AFVV*") + p = allosmod.util.PIRFile() + self.assertRaises(allosmod.util.FileFormatError, list, p.read(sio)) + + def test_pir_file_write(self): + """Test write of PIR file""" + sio = StringIO() + s = allosmod.util.Sequence() + s.code = "testcode" + s.primary = 'AFV' + p = allosmod.util.PIRFile() + p.write(sio, s, width=2) + self.assertEqual(sio.getvalue(), + ">P1;testcode\nsequence:::::::::\nAF\nV\n*\n") + + def test_pdb_filters(self): + """Test PDB filters""" + self.assertTrue(allosmod.util.atom_filter("ATOM foo")) + self.assertFalse(allosmod.util.atom_filter("HETATM foo")) + self.assertFalse(allosmod.util.atom_filter("foo")) + + self.assertTrue(allosmod.util.atom_hetatm_filter("ATOM foo")) + self.assertTrue(allosmod.util.atom_hetatm_filter("HETATM foo")) + self.assertFalse(allosmod.util.atom_hetatm_filter("foo")) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py b/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py new file mode 100644 index 0000000000000000000000000000000000000000..8af7fc0285005616faa3691e653ce19862af2965 --- /dev/null +++ b/pool/shard006/Python/0057747_test_auto_DARTELNorm2MNI.py @@ -0,0 +1,53 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ....testing import assert_equal +from ..preprocess import DARTELNorm2MNI + + +def test_DARTELNorm2MNI_inputs(): + input_map = dict(apply_to_files=dict(copyfile=False, + field='mni_norm.data.subjs.images', + mandatory=True, + ), + bounding_box=dict(field='mni_norm.bb', + ), + flowfield_files=dict(field='mni_norm.data.subjs.flowfields', + mandatory=True, + ), + fwhm=dict(field='mni_norm.fwhm', + ), + ignore_exception=dict(nohash=True, + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict(usedefault=True, + ), + modulate=dict(field='mni_norm.preserve', + ), + paths=dict(), + template_file=dict(copyfile=False, + field='mni_norm.template', + mandatory=True, + ), + use_mcr=dict(), + use_v8struct=dict(min_ver='8', + usedefault=True, + ), + voxel_size=dict(field='mni_norm.vox', + ), + ) + inputs = DARTELNorm2MNI.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + yield assert_equal, getattr(inputs.traits()[key], metakey), value + + +def test_DARTELNorm2MNI_outputs(): + output_map = dict(normalization_parameter_file=dict(), + normalized_files=dict(), + ) + outputs = DARTELNorm2MNI.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + yield assert_equal, getattr(outputs.traits()[key], metakey), value diff --git a/pool/shard006/Python/0057752_travis_pypi_setup.py b/pool/shard006/Python/0057752_travis_pypi_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..df6d77757011a9e2d5ee855c72a1d98607f790fe --- /dev/null +++ b/pool/shard006/Python/0057752_travis_pypi_setup.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Update encrypted deploy password in Travis config file +""" + + +from __future__ import print_function +import base64 +import json +import os +from getpass import getpass +import yaml +from cryptography.hazmat.primitives.serialization import load_pem_public_key +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 + + +try: + from urllib import urlopen +except: + from urllib.request import urlopen + + +GITHUB_REPO = 'avsecz/concise' +TRAVIS_CONFIG_FILE = os.path.join( + os.path.dirname(os.path.abspath(__file__)), '.travis.yml') + + +def load_key(pubkey): + """Load public RSA key, with work-around for keys using + incorrect header/footer format. + + Read more about RSA encryption with cryptography: + https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ + """ + try: + return load_pem_public_key(pubkey.encode(), default_backend()) + except ValueError: + # workaround for https://github.com/travis-ci/travis-api/issues/196 + pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') + return load_pem_public_key(pubkey.encode(), default_backend()) + + +def encrypt(pubkey, password): + """Encrypt password using given RSA public key and encode it with base64. + + The encrypted password can only be decrypted by someone with the + private key (in this case, only Travis). + """ + key = load_key(pubkey) + encrypted_password = key.encrypt(password, PKCS1v15()) + return base64.b64encode(encrypted_password) + + +def fetch_public_key(repo): + """Download RSA public key Travis will use for this repo. + + Travis API docs: http://docs.travis-ci.com/api/#repository-keys + """ + keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) + data = json.loads(urlopen(keyurl).read().decode()) + if 'key' not in data: + errmsg = "Could not find public key for repo: {}.\n".format(repo) + errmsg += "Have you already added your GitHub repo to Travis?" + raise ValueError(errmsg) + return data['key'] + + +def prepend_line(filepath, line): + """Rewrite a file adding a line to its beginning. + """ + with open(filepath) as f: + lines = f.readlines() + + lines.insert(0, line) + + with open(filepath, 'w') as f: + f.writelines(lines) + + +def load_yaml_config(filepath): + with open(filepath) as f: + return yaml.load(f) + + +def save_yaml_config(filepath, config): + with open(filepath, 'w') as f: + yaml.dump(config, f, default_flow_style=False) + + +def update_travis_deploy_password(encrypted_password): + """Update the deploy section of the .travis.yml file + to use the given encrypted password. + """ + config = load_yaml_config(TRAVIS_CONFIG_FILE) + + config['deploy']['password'] = dict(secure=encrypted_password) + + save_yaml_config(TRAVIS_CONFIG_FILE, config) + + line = ('# This file was autogenerated and will overwrite' + ' each time you run travis_pypi_setup.py\n') + prepend_line(TRAVIS_CONFIG_FILE, line) + + +def main(args): + public_key = fetch_public_key(args.repo) + password = args.password or getpass('PyPI password: ') + update_travis_deploy_password(encrypt(public_key, password.encode())) + print("Wrote encrypted password to .travis.yml -- you're ready to deploy") + + +if '__main__' == __name__: + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--repo', default=GITHUB_REPO, + help='GitHub repo (default: %s)' % GITHUB_REPO) + parser.add_argument('--password', + help='PyPI password (will prompt if not provided)') + + args = parser.parse_args() + main(args) diff --git a/pool/shard006/Python/0057753_evoked.py b/pool/shard006/Python/0057753_evoked.py new file mode 100644 index 0000000000000000000000000000000000000000..ff9af06cfd868665b2ea4140e076b111c08d593e --- /dev/null +++ b/pool/shard006/Python/0057753_evoked.py @@ -0,0 +1,165 @@ +# Authors: Alexandre Gramfort +# Daniel Strohmeier +# Martin Luessi +# +# License: BSD (3-clause) +import copy +import warnings + +import numpy as np + +from ..io.pick import pick_channels_cov +from ..forward import apply_forward +from ..utils import check_random_state, verbose, _time_mask + + +@verbose +def simulate_evoked(fwd, stc, info, cov, snr=3., tmin=None, tmax=None, + iir_filter=None, random_state=None, verbose=None): + """Generate noisy evoked data. + + .. note:: No projections from ``info`` will be present in the + output ``evoked``. You can use e.g. + :func:`evoked.add_proj ` or + :func:`evoked.set_eeg_reference ` + to add them afterward as necessary. + + Parameters + ---------- + fwd : Forward + a forward solution. + stc : SourceEstimate object + The source time courses. + info : dict + Measurement info to generate the evoked. + cov : Covariance object + The noise covariance. + snr : float + signal to noise ratio in dB. It corresponds to + 10 * log10( var(signal) / var(noise) ). + tmin : float | None + start of time interval to estimate SNR. If None first time point + is used. + tmax : float | None + start of time interval to estimate SNR. If None last time point + is used. + iir_filter : None | array + IIR filter coefficients (denominator) e.g. [1, -1, 0.2]. + random_state : None | int | np.random.RandomState + To specify the random generator state. + verbose : bool, str, int, or None + If not None, override default verbose level (see :func:`mne.verbose` + and :ref:`Logging documentation ` for more). + + Returns + ------- + evoked : Evoked object + The simulated evoked data + + See Also + -------- + simulate_raw + simulate_stc + simulate_sparse_stc + + Notes + ----- + .. versionadded:: 0.10.0 + """ + evoked = apply_forward(fwd, stc, info) + if snr < np.inf: + noise = simulate_noise_evoked(evoked, cov, iir_filter, random_state) + evoked_noise = add_noise_evoked(evoked, noise, snr, tmin=tmin, + tmax=tmax) + else: + evoked_noise = evoked + return evoked_noise + + +def simulate_noise_evoked(evoked, cov, iir_filter=None, random_state=None): + """Create noise as a multivariate Gaussian. + + The spatial covariance of the noise is given from the cov matrix. + + Parameters + ---------- + evoked : evoked object + an instance of evoked used as template + cov : Covariance object + The noise covariance + iir_filter : None | array + IIR filter coefficients (denominator) + random_state : None | int | np.random.RandomState + To specify the random generator state. + + Returns + ------- + noise : evoked object + an instance of evoked + + Notes + ----- + .. versionadded:: 0.10.0 + """ + noise = evoked.copy() + noise.data = _generate_noise(evoked.info, cov, iir_filter, random_state, + evoked.data.shape[1])[0] + return noise + + +def _generate_noise(info, cov, iir_filter, random_state, n_samples, zi=None): + """Create spatially colored and temporally IIR-filtered noise.""" + from scipy.signal import lfilter + noise_cov = pick_channels_cov(cov, include=info['ch_names'], exclude=[]) + if set(info['ch_names']) != set(noise_cov.ch_names): + raise ValueError('Evoked and covariance channel names are not ' + 'identical. Cannot generate the noise matrix. ' + 'Channels missing in covariance %s.' % + np.setdiff1d(info['ch_names'], noise_cov.ch_names)) + + rng = check_random_state(random_state) + c = np.diag(noise_cov.data) if noise_cov['diag'] else noise_cov.data + mu_channels = np.zeros(len(c)) + # we almost always get a positive semidefinite warning here, so squash it + with warnings.catch_warnings(record=True): + noise = rng.multivariate_normal(mu_channels, c, n_samples).T + if iir_filter is not None: + if zi is None: + zi = np.zeros((len(c), len(iir_filter) - 1)) + noise, zf = lfilter([1], iir_filter, noise, axis=-1, zi=zi) + else: + zf = None + return noise, zf + + +def add_noise_evoked(evoked, noise, snr, tmin=None, tmax=None): + """Add noise to evoked object with specified SNR. + + SNR is computed in the interval from tmin to tmax. + + Parameters + ---------- + evoked : Evoked object + An instance of evoked with signal + noise : Evoked object + An instance of evoked with noise + snr : float + signal to noise ratio in dB. It corresponds to + 10 * log10( var(signal) / var(noise) ) + tmin : float + start time before event + tmax : float + end time after event + + Returns + ------- + evoked_noise : Evoked object + An instance of evoked corrupted by noise + """ + evoked = copy.deepcopy(evoked) + tmask = _time_mask(evoked.times, tmin, tmax, sfreq=evoked.info['sfreq']) + tmp = 10 * np.log10(np.mean((evoked.data[:, tmask] ** 2).ravel()) / + np.mean((noise.data ** 2).ravel())) + noise.data = 10 ** ((tmp - float(snr)) / 20) * noise.data + evoked.data += noise.data + return evoked diff --git a/pool/shard006/Python/0057755_decorators.py b/pool/shard006/Python/0057755_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..045c4250c39f687fc2f4bc39e2a828e9bb9d9b6e --- /dev/null +++ b/pool/shard006/Python/0057755_decorators.py @@ -0,0 +1,16 @@ +from django.contrib.auth import REDIRECT_FIELD_NAME +from django.contrib.auth.decorators import user_passes_test + +def not_anonymous_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): + """ + Decorator for views that checks that the user is logged in and his username is not contain 'anonymous', + redirecting to the log-in page if necessary. + """ + actual_decorator = user_passes_test( + lambda u: u.is_authenticated() and 'anonymous' not in u.username, + login_url=login_url, + redirect_field_name=redirect_field_name + ) + if function: + return actual_decorator(function) + return actual_decorator \ No newline at end of file diff --git a/pool/shard006/Python/0057756_module_utilities.py b/pool/shard006/Python/0057756_module_utilities.py new file mode 100644 index 0000000000000000000000000000000000000000..5fad3146ae9e00b88aa7977e0b75c34e95f310d4 --- /dev/null +++ b/pool/shard006/Python/0057756_module_utilities.py @@ -0,0 +1,208 @@ +import sys +import os +import logging +import getpass +import platform +import time +#import pkg_resources +import json + +import sassie.util.sasconfig as sasconfig + +if sasconfig.__level__ == "DEBUG": DEBUG = True + +class run_utils(): + + def __init__(self,app,txtOutput): + self.__application__ = app + self.txtOutput = txtOutput + + def write_json_file(self): + + self.logger.debug('in write_json_file') + + self.logger.info('writing json files with input variables') + + with open(self.parmfile,'w') as outfile: + json.dump([self.v],outfile) + self.logger.info('writing parameters to '+self.parmfile) + + if(os.path.isfile('.last_sas.json')): + os.system('mv .last_sas.json .last_sas.json_backup') + self.logger.info('backing up existing .last_sas.json file to .last_sas.json_backup') + + if(os.path.isfile('.last_sas_'+self.__application__+'.json')): + os.system('mv .last_sas_'+self.__application__+'.json .last_sas_'+self.__application__+'.json_backup') + self.logger.info('backing up existing .last_sas_'+self.__application__+'.json file to .last_sas_'+self.__application__+'.json_backup') + + with open('.last_sas.json','w') as outfile: + json.dump([self.v],outfile) + self.logger.info('writing parameters to .last_sas.json file') + + with open('.last_sas_'+self.__application__+'.json','w') as outfile: + json.dump([self.v],outfile) + self.logger.info('writing parameters to .last_sas_'+self.__application__+'.json file') + + self.logger.info('input variables: '+json.dumps([self.v] )) + + return + + def general_setup(self,other_self): + + ''' method to write json file of input variables and setup logging ''' + + ''' grab all of the variables in the variable class instance ''' + log = other_self.log + mvars = other_self.mvars + + log.debug('in general_setup') + + input_vars = [attr for attr in dir(mvars) if not callable(getattr(mvars,attr)) and not attr.startswith("__")] + + ''' put the variables into a dictionary to send to json ''' + + input_variables = {} + + for var in input_vars: + input_variables[var] = getattr(mvars, var) + + self.v = input_variables + + self.write_json_file() + runname = self.v['runname'] + self.runpath = os.path.join(runname,self.__application__) + + self.logger.info('setting runpath directory to : '+self.runpath) + + try: + if(not os.path.exists(runname)): + os.makedirs(self.runpath) + elif(not os.path.exists(self.runpath)): + os.mkdir(self.runpath) + self.logger.info('creating directory : '+self.runpath) + except: + self.logger.critical('FAILED to create '+self.runpath+' directory') + + other_self.runpath = self.runpath + other_self.parmfile = self.parmfile + + return + + def preamble(self): + + user = getpass.getuser() + current_path = os.getcwd() + self.logger.debug('in preamble') + #self.logger.info('sassie version(sassie) : '+sassie.__version__) + #self.logger.info('sassie version : '+pkg_resources.get_distribution("sassie_2").version) + self.logger.info('module_application : '+self.__application__) + self.logger.info('executed by user : '+user+' on '+time.ctime()) + self.logger.info('current directory : '+current_path) + self.logger.info('hostname : '+platform.node()) + + return + + def setup_logging(self,other_self): + + self.logger = logging.getLogger(self.__application__) + if (sasconfig.__level__ == 'DEBUG'): + self.logger.setLevel(logging.DEBUG) + else: + self.logger.setLevel(logging.INFO) + + timestr = time.strftime("%Y%m%d-%H%M%S") + + self.logfile = self.__application__+'_'+timestr+'.sassie_log' + self.parmfile = self.logfile[:-3]+'json' + outfile = open(self.logfile,"w") + st = 'Date\t\tTime\t\tFile\t\tMethod\t\tLine\tLevel\tMessage\n' + outfile.write(st) #; print(st) + outfile.close() + + file_handler = logging.FileHandler(self.logfile) + formatter = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s') + file_handler.setFormatter(formatter) + + output_handler = logging.StreamHandler(sys.stdout) + output_handler.setLevel(logging.WARNING) + output_handler.setFormatter(formatter) + + self.logger.addHandler(file_handler) + self.logger.addHandler(output_handler) + + self.logger.debug('in setup_logging') + self.logger.info("Program started") + + self.preamble() + + other_self.log = self.logger + other_self.logfile = self.logfile + + return + + def print_gui(self,message): + ''' + method to output message to logger and txtOutput (gui) + ''' + + self.logger.info(message) + self.txtOutput.put(message) + if DEBUG: print message + + def clean_up(self,log): + ''' + method to move files to runpath directory and finish tasks + ''' + + log.debug('in clean_up') + + os.system('mv '+self.logfile+' '+self.runpath) + os.system('mv '+self.parmfile+' '+self.runpath) + + def capture_exception(self,message): + + ''' this method is a placehoder for a possible future exception handler ... notes are below for usage in-line in code ''' + + + ''' This plain 'except:' catches all exceptions, not only system ''' + + # log = self.log + # try: + # something_that_may_fail() + # except: + # error = sys.exc_info()[0] + # log.error('ERROR: '+error) + + + ''' this is an example of EAFP ... easier to ask for forgiveness than permission ... the preferred way ... also allows some cleanup etc ''' + + #def display_username(user_id): + # try: + # db_connection = get_db_connection() + # except DatabaseEatenByGrueError: + # print('Sorry! Database was eaten by a grue.') + # else: + # print(db_connection.get_username(user_id)) + # db_connection.cleanup() + + ''' the following is an example of check first or look before you leap LBYL ... could still not work in all cases (race conditions possible) ''' + + #def print_object(some_object): + # # Check if the object is printable... + # try: + # printable = str(some_object) + # except TypeError: + # print("unprintable object") + # else: + # print(printable) + + + ''' see http://www.jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/ ''' + + + ''' proper way to open a file to read to make sure that it closes correctly if there is an error ''' + + #with open("myfile.txt") as f: + # for line in f: + # print line, + diff --git a/pool/shard006/Python/0057761_model.py b/pool/shard006/Python/0057761_model.py new file mode 100644 index 0000000000000000000000000000000000000000..3921a51364971aac852dd60778fdb20a375fbfc2 --- /dev/null +++ b/pool/shard006/Python/0057761_model.py @@ -0,0 +1,110 @@ +import math +import random +from queue import PriorityQueue +from app.logic.device import Device +from app.logic.incoming_event import IncomingEvent +from app.logic.outcoming_first_event import OutcomingFirstEvent +from app.logic.outcoming_second_event import OutcomingSecondEvent +from app.logic.request import Request + +class Model: + + event_list = None + work_time = None + inteval_time = None + model_time = None + + + @staticmethod + def initialize(work_time_value): + Model.event_list = PriorityQueue() + Model.work_time = work_time_value + Model.interval_time = 60 + Model.model_time = 0.0 + Model.device1 = Device(30, 70) + Model.device2 = Device(45, 60) + Model.add_event(IncomingEvent(0.0)) + + @staticmethod + def start(): + while Model.model_time < Model.work_time: + present_event = Model.get_event() + Model.model_time = present_event.time + present_event.handle_self(Model) + + @staticmethod + def add_event(event): + Model.event_list.put(event) + + @staticmethod + def get_event(): + return Model.event_list.get() + + @staticmethod + def get_exp_interval(): + return (-1) * math.log(1 - random.random()) * Model.interval_time + + @staticmethod + def handle_incoming_event(time): + event_time = time + Model.get_exp_interval() + Model.add_event(IncomingEvent(event_time)) + current_request_number = Model.device1.next_request_number + request = Request(current_request_number, time) + if Model.device1.present_request != None: + Model.device1.add_request(request) + else: + Model.process_device1(request) + #log function + print('[handle an incoming event]\t\t\t{0:.2f} sec.'.format(event_time)) + + @staticmethod + def process_device1(request): + Model.device1.present_request = request + Model.device1.next_request_number += 1 + time = Model.device1.get_processing_time() + totalTime = Model.model_time - request.time + Model.add_event(OutcomingFirstEvent(Model.model_time + totalTime)) + #log function + print('\t\t\trequest {0}'.format(request.number)) + + @staticmethod + def handle_outcoming_first_event(time): + present_request = Model.device1.present_request + Model.device1.present_request = None + if not Model.device1.is_empty_request_queue(): + request = Model.device1.remove_request() + process_device1(request) + else: + Model.device1.preset_request = None + if Model.device2.present_request != None: + Model.device2.add_request(present_request) + else: + Model.process_device2(present_request) + #log function + print('[handle an outcoming event from 1-st device]\t{0:.2f} sec'.format( + time)) + + @staticmethod + def process_device2(request): + Model.device2.present_request = request + Model.device2.next_request_number += 1 + time = Model.device2.get_processing_time() + totalTime = Model.model_time - request.time + Model.add_event(OutcomingSecondEvent(Model.model_time + totalTime)) + #log function + print('\t\t\trequest {0}'.format(request.number)) + + @staticmethod + def handle_outcoming_second_event(time): + Model.device2.present_request = None + if not Model.device2.is_empty_request_queue(): + request = Model.device2.remove_request() + process_device2(request) + else: + Model.device2.present_request = None + #log function + print('[handling an outcoming event from 2-nd device]\t{0:.2f} sec'.format( + time)) + + + diff --git a/pool/shard006/Python/0057763_support.py b/pool/shard006/Python/0057763_support.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d8b7af3c9b1b967e7c81f9c4a22d633978b3db --- /dev/null +++ b/pool/shard006/Python/0057763_support.py @@ -0,0 +1,139 @@ +"""Support Information module. + +The module provides functions to gain information to be included in issues. +It neither contains normal functionality nor is it used by GitGutter. +""" +import os +import subprocess +import textwrap + +import sublime +import sublime_plugin + +# get absolute path of the package +PACKAGE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if os.path.isfile(PACKAGE_PATH): + # Package is a PACKAGE.sublime-package so get its filename + PACKAGE, _ = os.path.splitext(os.path.basename(PACKAGE_PATH)) +elif os.path.isdir(PACKAGE_PATH): + # Package is a directory, so get its basename + PACKAGE = os.path.basename(PACKAGE_PATH) +else: + raise ValueError('Package is no file and no directory!') + + +def git(*args): + """Read version of git binary.""" + if os.name == 'nt': + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + else: + startupinfo = None + proc = subprocess.Popen( + args=['git'] + [arg for arg in args], startupinfo=startupinfo, + stdout=subprocess.PIPE, stdin=subprocess.PIPE, + # run command in package directory if exists. + cwd=PACKAGE_PATH if os.path.isdir(PACKAGE_PATH) else None) + stdout, _ = proc.communicate() + return stdout.decode('utf-8').strip() if stdout else None + + +def git_version(): + """Read version of git binary.""" + try: + return git('--version') + except Exception as exception: + print('%s: %s' % (PACKAGE, exception)) + return 'git version could not be acquired!' + + +def gitgutter_version(): + """Read commit hash or version of GitGutter.""" + try: + return git('rev-parse', 'HEAD')[:7] + except: + try: + return sublime.load_resource( + 'Packages/%s/VERSION' % PACKAGE).strip() + except Exception as exception: + print('%s: %s' % (PACKAGE, exception)) + return 'Version could not be acquired!' + + +def module_version(module, attr): + """Format the module version.""" + try: + version = getattr(module, attr) + if callable(version): + version = version() + except Exception as exception: + print('%s: %s' % (PACKAGE, exception)) + version = 'version could not be acquired!' + + if not isinstance(version, str): + version = '.'.join((str(x) for x in version)) + return version + + +def is_installed_by_package_control(): + """Check if installed by package control.""" + settings = sublime.load_settings('Package Control.sublime-settings') + return str(PACKAGE in set(settings.get('installed_packages', []))) + + +class GitGutterSupportInfoCommand(sublime_plugin.ApplicationCommand): + """Support Information Command.""" + + @staticmethod + def run(): + """Run command.""" + info = { + 'platform': sublime.platform(), + 'st_version': sublime.version(), + 'arch': sublime.arch(), + 'package_version': gitgutter_version(), + 'pc_install': is_installed_by_package_control(), + 'git_version': git_version() + } + + try: + import markdown + info['markdown'] = module_version(markdown, 'version') + except ImportError: + info['markdown'] = 'not installed!' + + try: + import mdpopups + info['mdpopups'] = module_version(mdpopups, 'version') + except ImportError: + info['mdpopups'] = 'not installed!' + + try: + import jinja2 + info['jinja'] = module_version(jinja2, '__version__') + except ImportError: + info['jinja'] = 'not installed!' + + try: + import pygments + info['pygments'] = module_version(pygments, '__version__') + except ImportError: + info['pygments'] = 'not installed!' + + msg = textwrap.dedent( + """\ + - Sublime Text %(st_version)s + - Platform: %(platform)s + - Arch: %(arch)s + - GitGutter %(package_version)s + - Install via PC: %(pc_install)s + - %(git_version)s + - mdpopups %(mdpopups)s + - markdown %(markdown)s + - pygments %(pygments)s + - jinja2 %(jinja)s + """ % info + ) + + sublime.message_dialog(msg + '\nInfo has been copied to clipboard.') + sublime.set_clipboard(msg) diff --git a/pool/shard006/Python/0057767_sphinx_module_loader.py b/pool/shard006/Python/0057767_sphinx_module_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb580c93230a499d836a680c96bd0a21d3af832 --- /dev/null +++ b/pool/shard006/Python/0057767_sphinx_module_loader.py @@ -0,0 +1,97 @@ +""" +Command-module loader for CMU Pocket Sphinx. + +This script is based on 'dfly-loader-wsr.py' written by Christo Butcher and +has been adapted to work with the Sphinx engine instead. + +This script can be used to look for Dragonfly command-modules for use with +the CMU Pocket Sphinx engine. It scans the directory it's in and loads any +``_*.py`` it finds. +""" + + +# TODO Have a simple GUI for pausing, resuming, cancelling and stopping +# recognition, etc + +import os.path +import logging + + +from dragonfly import RecognitionObserver, get_engine +from dragonfly.loader import CommandModuleDirectory +from dragonfly.log import setup_log + +# -------------------------------------------------------------------------- +# Set up basic logging. + +setup_log() + + +# -------------------------------------------------------------------------- +# Simple recognition observer class. + +class Observer(RecognitionObserver): + def on_begin(self): + print("Speech started.") + + def on_recognition(self, words): + print(" ".join(words)) + + def on_failure(self): + print("Sorry, what was that?") + + +# -------------------------------------------------------------------------- +# Main event driving loop. + +def main(): + logging.basicConfig(level=logging.INFO) + + try: + path = os.path.dirname(__file__) + except NameError: + # The "__file__" name is not always available, for example + # when this module is run from PythonWin. In this case we + # simply use the current working directory. + path = os.getcwd() + __file__ = os.path.join(path, "sphinx_module_loader.py") + + engine = get_engine("sphinx") + + # Try to import the local engine configuration object first. If there isn't one, + # use the default engine configuration. + log = logging.getLogger("config") + try: + import config + engine.config = config + log.info("Using local engine configuration module 'config.py'") + except ImportError: + pass + except Exception as e: + # Log errors caught when setting the configuration. + log.exception("Failed to set config using 'config.py': %s" % e) + log.warning("Falling back to the default engine configuration") + + # You can also set any configuration options here instead of using a + # config.py file. For example: + # engine.config.START_ASLEEP = False + + # Call connect() now that the engine configuration is set. + engine.connect() + + # Register a recognition observer + observer = Observer() + observer.register() + + directory = CommandModuleDirectory(path, excludes=[__file__]) + directory.load() + + # Start the engine's main recognition loop + try: + engine.recognise_forever() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/pool/shard006/Python/0057771_test_volumes_negative.py b/pool/shard006/Python/0057771_test_volumes_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..92f5ea862790c5317fb126a279ab5845984d89fa --- /dev/null +++ b/pool/shard006/Python/0057771_test_volumes_negative.py @@ -0,0 +1,111 @@ +# Copyright 2012 OpenStack 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 tempest.api.compute import base +from tempest.common.utils import data_utils +from tempest import config +from tempest.lib import exceptions as lib_exc +from tempest import test + +CONF = config.CONF + + +class VolumesNegativeTest(base.BaseV2ComputeTest): + + @classmethod + def skip_checks(cls): + super(VolumesNegativeTest, cls).skip_checks() + if not CONF.service_available.cinder: + skip_msg = ("%s skipped as Cinder is not available" % cls.__name__) + raise cls.skipException(skip_msg) + + @classmethod + def setup_clients(cls): + super(VolumesNegativeTest, cls).setup_clients() + cls.client = cls.volumes_extensions_client + + @test.attr(type=['negative']) + @test.idempotent_id('c03ea686-905b-41a2-8748-9635154b7c57') + def test_volume_get_nonexistent_volume_id(self): + # Negative: Should not be able to get details of nonexistent volume + # Creating a nonexistent volume id + # Trying to GET a non existent volume + self.assertRaises(lib_exc.NotFound, self.client.show_volume, + data_utils.rand_uuid()) + + @test.attr(type=['negative']) + @test.idempotent_id('54a34226-d910-4b00-9ef8-8683e6c55846') + def test_volume_delete_nonexistent_volume_id(self): + # Negative: Should not be able to delete nonexistent Volume + # Creating nonexistent volume id + # Trying to DELETE a non existent volume + self.assertRaises(lib_exc.NotFound, self.client.delete_volume, + data_utils.rand_uuid()) + + @test.attr(type=['negative']) + @test.idempotent_id('5125ae14-152b-40a7-b3c5-eae15e9022ef') + def test_create_volume_with_invalid_size(self): + # Negative: Should not be able to create volume with invalid size + # in request + v_name = data_utils.rand_name('Volume') + metadata = {'Type': 'work'} + self.assertRaises(lib_exc.BadRequest, self.client.create_volume, + size='#$%', display_name=v_name, metadata=metadata) + + @test.attr(type=['negative']) + @test.idempotent_id('131cb3a1-75cc-4d40-b4c3-1317f64719b0') + def test_create_volume_with_out_passing_size(self): + # Negative: Should not be able to create volume without passing size + # in request + v_name = data_utils.rand_name('Volume') + metadata = {'Type': 'work'} + self.assertRaises(lib_exc.BadRequest, self.client.create_volume, + size='', display_name=v_name, metadata=metadata) + + @test.attr(type=['negative']) + @test.idempotent_id('8cce995e-0a83-479a-b94d-e1e40b8a09d1') + def test_create_volume_with_size_zero(self): + # Negative: Should not be able to create volume with size zero + v_name = data_utils.rand_name('Volume') + metadata = {'Type': 'work'} + self.assertRaises(lib_exc.BadRequest, self.client.create_volume, + size='0', display_name=v_name, metadata=metadata) + + @test.attr(type=['negative']) + @test.idempotent_id('f01904f2-e975-4915-98ce-cb5fa27bde4f') + def test_get_invalid_volume_id(self): + # Negative: Should not be able to get volume with invalid id + self.assertRaises(lib_exc.NotFound, + self.client.show_volume, '#$%%&^&^') + + @test.attr(type=['negative']) + @test.idempotent_id('62bab09a-4c03-4617-8cca-8572bc94af9b') + def test_get_volume_without_passing_volume_id(self): + # Negative: Should not be able to get volume when empty ID is passed + self.assertRaises(lib_exc.NotFound, self.client.show_volume, '') + + @test.attr(type=['negative']) + @test.idempotent_id('62972737-124b-4513-b6cf-2f019f178494') + def test_delete_invalid_volume_id(self): + # Negative: Should not be able to delete volume when invalid ID is + # passed + self.assertRaises(lib_exc.NotFound, + self.client.delete_volume, '!@#$%^&*()') + + @test.attr(type=['negative']) + @test.idempotent_id('0d1417c5-4ae8-4c2c-adc5-5f0b864253e5') + def test_delete_volume_without_passing_volume_id(self): + # Negative: Should not be able to delete volume when empty ID is passed + self.assertRaises(lib_exc.NotFound, self.client.delete_volume, '') diff --git a/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py b/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py new file mode 100644 index 0000000000000000000000000000000000000000..7fde2a8728c10c01f6679b43eba80360d282cdc3 --- /dev/null +++ b/pool/shard006/Python/0057775_test_delegated_factory_py2_py3.py @@ -0,0 +1,25 @@ +"""DelegatedFactory provider tests.""" + +from dependency_injector import providers + +from .common import Example + + +def test_inheritance(): + assert isinstance(providers.DelegatedFactory(object), providers.Factory) + + +def test_is_provider(): + assert providers.is_provider(providers.DelegatedFactory(object)) is True + + +def test_is_delegated_provider(): + assert providers.is_delegated(providers.DelegatedFactory(object)) is True + + +def test_repr(): + provider = providers.DelegatedFactory(Example) + assert repr(provider) == ( + "".format(repr(Example), hex(id(provider))) + ) diff --git a/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py b/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py new file mode 100644 index 0000000000000000000000000000000000000000..cc9341364c5550f91b1a9cf1b9ccf37675e7eff3 --- /dev/null +++ b/pool/shard006/Python/0057776_109-convert-sorted-list-to-binary-search-tree.py @@ -0,0 +1,41 @@ +# Definition for singly-linked list. +class ListNode(object): + def __init__(self, x): + self.val = x + self.next = None + +# Definition for a binary tree node. +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution(object): + def sortedListToBST(self, head): + """ + :type head: ListNode + :rtype: TreeNode + """ + arr = [] + + while head: + arr.append(head.val) + head = head.next + + + def helper(begin, end): + if begin > end: + return None + + middle = (begin+end) / 2 + + node = TreeNode(arr[middle]) + node.left = helper(begin, middle-1) + node.right = helper(middle+1, end) + + return node + + return helper(0, len(arr)-1) + + diff --git a/pool/shard006/Python/0057784_smlchecker.py b/pool/shard006/Python/0057784_smlchecker.py new file mode 100644 index 0000000000000000000000000000000000000000..a8803dcf254687233ef594e90acecd661dc3f07c --- /dev/null +++ b/pool/shard006/Python/0057784_smlchecker.py @@ -0,0 +1,62 @@ +import hashlib +import logging + +from dns import resolver + +log = logging.getLogger(__name__) + + +def check(peppoid): + ''' + Checks whether the given PEPPOL identifier exists in the SML by doing an DNS lookup + returns True if so otherwise False + + :param peppoid: a PEPPOL identifier + :return: True or False + ''' + + if smpaddress(peppoid) is None: + return False + else: + return True + + +def smpaddress(peppoid): + ''' + Checks whether the given participant id exists in the SML by doing a DNS lookup + returns None or the DNS A-record (ipaddress) + + :param peppolid: a PEPPOL identifier + :return: str or None + ''' + + h = hostname(peppoid) + log.debug('Hostname to resolve %s', h) + # Look up the hostname in the SML; if the lookup succeeds, we know + # there is an SMP for this organization, and we are done. + # Normally, the calling application would then contact the SMP for + # endpoint details. + r = resolver.Resolver() + try: + answers = r.query(h, "A") + except resolver.NXDOMAIN: + log.error("Got NXDOMAIN for %s", h) + return None + + for rdata in answers: + log.debug('DNS A record found: %' + 's', rdata) + + return str(answers[0]) + + +def hostname(peppoid): + ''' + Calculates the hostname for a specific PEPPOL identifier + :param peppoid: + :return: + ''' + # Calculate the hash of the ID according to the SML specification + # peppol needs the organisation to be lower case + hash = hashlib.md5(str.lower(peppoid).encode('UTF-8')).hexdigest() + return "b-" + hash + ".iso6523-actorid-upis.edelivery.tech.ec.europa.eu" diff --git a/pool/shard006/Python/0057786_test_comment02.py b/pool/shard006/Python/0057786_test_comment02.py new file mode 100644 index 0000000000000000000000000000000000000000..e1660db8a25ae1b968612d3da8697ec607b0a3db --- /dev/null +++ b/pool/shard006/Python/0057786_test_comment02.py @@ -0,0 +1,39 @@ +############################################################################### +# +# Tests for XlsxWriter. +# +# SPDX-License-Identifier: BSD-2-Clause +# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org +# + +from ..excel_comparison_test import ExcelComparisonTest +from ...workbook import Workbook + + +class TestCompareXLSXFiles(ExcelComparisonTest): + """ + Test file created by XlsxWriter against a file created by Excel. + + """ + + def setUp(self): + + self.set_filename('comment02.xlsx') + + def test_create_file(self): + """Test the creation of a simple XlsxWriter file with comments.""" + + workbook = Workbook(self.got_filename) + + worksheet = workbook.add_worksheet() + + worksheet.write('A1', 'Foo') + worksheet.write_comment('B2', 'Some text') + worksheet.write_comment('D17', 'More text') + + # Set the author to match the target XLSX file. + worksheet.set_comments_author('John') + + workbook.close() + + self.assertExcelEqual() diff --git a/pool/shard006/Python/0057787_scheduler.py b/pool/shard006/Python/0057787_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..b470bc489b3f2f9552415f4694e88a7ff9c69246 --- /dev/null +++ b/pool/shard006/Python/0057787_scheduler.py @@ -0,0 +1,51 @@ +# coding: utf8 +import time +from gluon.scheduler import Scheduler + +def demo1(*args,**vars): + print 'you passed args=%s and vars=%s' % (args, vars) + return args[0] + +def demo2(): + 1/0 + +def demo3(): + time.sleep(15) + print 1/0 + return None + +def demo4(): + time.sleep(15) + print "I'm printing something" + return dict(a=1, b=2) + +def demo5(): + time.sleep(15) + print "I'm printing something" + rtn = dict(a=1, b=2) + +def demo6(): + time.sleep(5) + print '50%' + time.sleep(5) + print '!clear!100%' + return 1 + +import random +def demo7(): + time.sleep(random.randint(1,15)) + print W2P_TASK, request.now + return W2P_TASK.id, W2P_TASK.uuid + +scheduler = Scheduler(db) + +##or, alternatively : +#scheduler = Scheduler(db, +# dict( +# demo1=demo1, +# demo2=demo2, +# demo3=demo3, +# demo4=demo4, +# foo=demo5 +# ) +# ) diff --git a/pool/shard006/Python/0057789_randomWalks-segment4.py b/pool/shard006/Python/0057789_randomWalks-segment4.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b3b3e0ba1055208ad3ea2b13e6412e97959963 --- /dev/null +++ b/pool/shard006/Python/0057789_randomWalks-segment4.py @@ -0,0 +1,203 @@ + + +class Location(object): + + def __init__(self, x, y): + """x and y are floats""" + self.x = x + self.y = y + + def move(self, deltaX, deltaY): + """deltaX and deltaY are floats""" + return Location(self.x + deltaX, self.y + deltaY) + + def getX(self): + return self.x + + def getY(self): + return self.y + + def distFrom(self, other): + ox = other.x + oy = other.y + xDist = self.x - ox + yDist = self.y - oy + return (xDist**2 + yDist**2)**0.5 + + def __str__(self): + return '<' + str(self.x) + ', ' + str(self.y) + '>' + + + + + +class Field(object): + + def __init__(self): + self.drunks = {} + + def addDrunk(self, drunk, loc): + if drunk in self.drunks: + raise ValueError('Duplicate drunk') + else: + self.drunks[drunk] = loc + + def moveDrunk(self, drunk): + if not drunk in self.drunks: + raise ValueError('Drunk not in field') + xDist, yDist = drunk.takeStep() + currentLocation = self.drunks[drunk] + #use move method of Location to get new location + self.drunks[drunk] = currentLocation.move(xDist, yDist) + + def getLoc(self, drunk): + if not drunk in self.drunks: + raise ValueError('Drunk not in field') + return self.drunks[drunk] + + + + + + + + + + +import random + + +class Drunk(object): + def __init__(self, name): + self.name = name + def __str__(self): + return 'This drunk is named ' + self.name + +class UsualDrunk(Drunk): + def takeStep(self): + stepChoices =\ + [(0.0,1.0), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)] + return random.choice(stepChoices) + + +def walk(f, d, numSteps): + start = f.getLoc(d) + for s in range(numSteps): + f.moveDrunk(d) + return(start.distFrom(f.getLoc(d))) + + + +## import pylab + +## #set line width +## pylab.rcParams['lines.linewidth'] = 6 +## #set font size for titles +## pylab.rcParams['axes.titlesize'] = 20 +## #set font size for labels on axes +## pylab.rcParams['axes.labelsize'] = 20 +## #set size of numbers on x-axis +## pylab.rcParams['xtick.major.size'] = 5 +## #set size of numbers on y-axis +## pylab.rcParams['ytick.major.size'] = 5 +## #set size of markers +## pylab.rcParams['lines.markersize'] = 10 + + +###Start code added in Segment 4 + + + +def drunkTestP(numTrials = 50): + stepsTaken = [10, 100, 1000, 10000] + meanDistances = [] + for numSteps in stepsTaken: + distances = simWalks(numSteps, numTrials) + meanDistances.append(sum(distances)/len(distances)) + pylab.plot(stepsTaken, meanDistances) + pylab.title('Mean Distance from Origin') + pylab.xlabel('Steps Taken') + pylab.ylabel('Steps from Origin') + pylab.show() + + + + + +def drunkTestP1(numTrials = 50): + stepsTaken = [10, 100, 1000, 10000] + meanDistances = [] + squareRootOfSteps = [] + for numSteps in stepsTaken: + distances = simWalks(numSteps, numTrials) + meanDistances.append(sum(distances)/len(distances)) + squareRootOfSteps.append(numSteps**0.5) + pylab.plot(stepsTaken, meanDistances, 'b-', + label = 'Mean distance') + pylab.plot(stepsTaken, squareRootOfSteps, 'g-.', + label = 'Square root of steps') + pylab.title('Mean Distance from Origin') + pylab.xlabel('Steps Taken') + pylab.ylabel('Steps from Origin') + pylab.legend() + pylab.show() + + + + + + + +#Look at different kinds of drunks + +class UsualDrunk(Drunk): + def takeStep(self): + stepChoices =\ + [(0.0,1.0), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)] + return random.choice(stepChoices) + +class ColdDrunk(Drunk): + def takeStep(self): + stepChoices =\ + [(0.0,0.95), (0.0,-1.0), (1.0, 0.0), (-1.0, 0.0)] + return random.choice(stepChoices) + +class EDrunk(Drunk): + def takeStep(self): + deltaX = random.random() + if random.random() < 0.5: + deltaX = -deltaX + deltaY = random.random() + if random.random() < 0.5: + deltaY = -deltaY + return (deltaX, deltaY) + +# New version of simWalks + +def simWalks(numSteps, numTrials, dClass): + homer = dClass('Homer') + origin = Location(0, 0) + distances = [] + for t in range(numTrials): + f = Field() + f.addDrunk(homer, origin) + distances.append(walk(f, homer, numSteps)) + return distances + + +def drunkTestP(numTrials = 50): + stepsTaken = [10, 100, 1000, 10000] + for dClass in (UsualDrunk, ColdDrunk, EDrunk): + meanDistances = [] + for numSteps in stepsTaken: + distances = simWalks(numSteps, numTrials, dClass) + meanDistances.append(sum(distances)/len(distances)) + pylab.plot(stepsTaken, meanDistances, + label = dClass.__name__) + pylab.title('Mean Distance from Origin') + pylab.xlabel('Steps Taken') + pylab.ylabel('Steps from Origin') + pylab.legend(loc = 'upper left') + pylab.show() + + diff --git a/pool/shard006/Python/0057790_change.py b/pool/shard006/Python/0057790_change.py new file mode 100644 index 0000000000000000000000000000000000000000..624d981c879a7e8c8e70816bd12acee0f4083a9a --- /dev/null +++ b/pool/shard006/Python/0057790_change.py @@ -0,0 +1,64 @@ +# encoding: utf-8 +""" +change.py + +Created by Thomas Mangin on 2009-11-05. +Copyright (c) 2009-2015 Exa Networks. All rights reserved. +""" + + +class Source (object): + UNSET = 0 + CONFIGURATION = 1 + API = 2 + NETWORK = 3 + + +class Change (object): + SOURCE = Source.UNSET + + __slots__ = ['nlri','attributes'] + + def __init__ (self, nlri, attributes): + self.nlri = nlri + self.attributes = attributes + + def index (self): + return '%02x%02x' % self.nlri.family() + self.nlri.index() + + def __eq__ (self, other): + return self.nlri == other.nlri and self.attributes == other.attributes + + def __ne__ (self, other): + return self.nlri != other.nlri or self.attributes != other.attributes + + def __lt__ (self, other): + raise RuntimeError('comparing Change for ordering does not make sense') + + def __le__ (self, other): + raise RuntimeError('comparing Change for ordering does not make sense') + + def __gt__ (self, other): + raise RuntimeError('comparing Change for ordering does not make sense') + + def __ge__ (self, other): + raise RuntimeError('comparing Change for ordering does not make sense') + + def extensive (self): + # If you change this you must change as well extensive in Update + return "%s%s" % (str(self.nlri),str(self.attributes)) + + def __str__ (self): + return self.extensive() + + +class ConfigurationChange (Change): + SOURCE = Source.CONFIGURATION + + +class APIChange (Change): + SOURCE = Source.API + + +class NetworkChange (Change): + SOURCE = Source.NETWORK diff --git a/pool/shard006/Python/0057791_0002_populate_usersettings.py b/pool/shard006/Python/0057791_0002_populate_usersettings.py new file mode 100644 index 0000000000000000000000000000000000000000..b35bfc80b90cd81b9bf560adcf3f15c2f099dd0f --- /dev/null +++ b/pool/shard006/Python/0057791_0002_populate_usersettings.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +from django.contrib.auth import get_user_model +from django.db import models, migrations + +from helpdesk.settings import DEFAULT_USER_SETTINGS + + +def pickle_settings(data): + """Pickling as defined at migration's creation time""" + try: + import pickle + except ImportError: + import cPickle as pickle + from helpdesk.query import b64encode + return b64encode(pickle.dumps(data)) + + +# https://docs.djangoproject.com/en/1.7/topics/migrations/#data-migrations +def populate_usersettings(apps, schema_editor): + """Create a UserSettings entry for each existing user. + This will only happen once (at install time, or at upgrade) + when the UserSettings model doesn't already exist.""" + + _User = get_user_model() + User = apps.get_model(_User._meta.app_label, _User._meta.model_name) + + # Import historical version of models + UserSettings = apps.get_model("helpdesk", "UserSettings") + + settings_pickled = pickle_settings(DEFAULT_USER_SETTINGS) + + for u in User.objects.all(): + try: + UserSettings.objects.get(user=u) + except UserSettings.DoesNotExist: + UserSettings.objects.create(user=u, settings_pickled=settings_pickled) + + +noop = lambda *args, **kwargs: None + +class Migration(migrations.Migration): + + dependencies = [ + ('helpdesk', '0001_initial'), + ] + + operations = [ + migrations.RunPython(populate_usersettings, reverse_code=noop), + ] + + diff --git a/pool/shard006/Python/0057793_letterCombinations.py b/pool/shard006/Python/0057793_letterCombinations.py new file mode 100644 index 0000000000000000000000000000000000000000..b11ba01f8d0b10a534e319f57ea917738ea5206a --- /dev/null +++ b/pool/shard006/Python/0057793_letterCombinations.py @@ -0,0 +1,32 @@ +class Solution: + # @return a list of strings, [s1, s2] + def letterCombinations(self, digits): + if len(digits) <= 0: + return [] + map = { + "0": (), + "1": (), + "2": ("a", "b", "c"), + "3": ("d", "e", "f"), + "4": ("g", "h", "i"), + "5": ("j", "k", "l"), + "6": ("m", "n", "o"), + "7": ("p", "q", "r", "s"), + "8": ("t", "u", "v"), + "9": ("w", "x", "y", "z") + } + result1 = [ "" ] + result2 = [ ] + for ch in digits: + list = map[ch] + if 0 == len(list): + continue + for str in result1: + for suffix in list: + result2.append(str + suffix) + result1 = result2 + result2 = [ ] + return result1 + +a = Solution() +print a.letterCombinations('2') \ No newline at end of file diff --git a/pool/shard006/Python/0057803_urls.py b/pool/shard006/Python/0057803_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..1f893cdd8dbfd7358630edbae44e7e1dbfdf54ff --- /dev/null +++ b/pool/shard006/Python/0057803_urls.py @@ -0,0 +1,16 @@ + +from django.conf.urls import patterns, include, url + +urlpatterns = patterns('webhost.views', + url(r'^$', 'home', name='home'), + url(r'^about/$', 'about', name='about'), + url(r'^policy/$', 'pp', name='pp'), + url(r'^TOS/$', 'TOS', name='TOS'), + url(r'^contact/$', 'contact', name='contact'), + url(r'^copyright/$', 'copyright', name='copyright'), + url(r'^blog/$', 'blog', name='blog'), + url(r'^faq/$', 'faq', name='faq'), + url(r'^pk/$', 'pk', name='pk'), + #url(r'^so/$', 'my_view', name='my_view'), + url(r'^company/$', 'company', name='company'), +) diff --git a/pool/shard006/Python/0057806_signature_def_utils_impl.py b/pool/shard006/Python/0057806_signature_def_utils_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3fb16825d8a45c4f1681fa716d45ba84853a22 --- /dev/null +++ b/pool/shard006/Python/0057806_signature_def_utils_impl.py @@ -0,0 +1,228 @@ +# 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. +# ============================================================================== +"""SignatureDef utility functions implementation.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import utils + + +def build_signature_def(inputs=None, outputs=None, method_name=None): + """Utility function to build a SignatureDef protocol buffer. + + Args: + inputs: Inputs of the SignatureDef defined as a proto map of string to + tensor info. + outputs: Outputs of the SignatureDef defined as a proto map of string to + tensor info. + method_name: Method name of the SignatureDef as a string. + + Returns: + A SignatureDef protocol buffer constructed based on the supplied arguments. + """ + signature_def = meta_graph_pb2.SignatureDef() + if inputs is not None: + for item in inputs: + signature_def.inputs[item].CopyFrom(inputs[item]) + if outputs is not None: + for item in outputs: + signature_def.outputs[item].CopyFrom(outputs[item]) + if method_name is not None: + signature_def.method_name = method_name + return signature_def + + +def regression_signature_def(examples, predictions): + """Creates regression signature from given examples and predictions. + + Args: + examples: `Tensor`. + predictions: `Tensor`. + + Returns: + A regression-flavored signature_def. + + Raises: + ValueError: If examples is `None`. + """ + if examples is None: + raise ValueError('examples cannot be None for regression.') + if predictions is None: + raise ValueError('predictions cannot be None for regression.') + + input_tensor_info = utils.build_tensor_info(examples) + signature_inputs = {signature_constants.REGRESS_INPUTS: input_tensor_info} + + output_tensor_info = utils.build_tensor_info(predictions) + signature_outputs = {signature_constants.REGRESS_OUTPUTS: output_tensor_info} + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.REGRESS_METHOD_NAME) + + return signature_def + + +def classification_signature_def(examples, classes, scores): + """Creates classification signature from given examples and predictions. + + Args: + examples: `Tensor`. + classes: `Tensor`. + scores: `Tensor`. + + Returns: + A classification-flavored signature_def. + + Raises: + ValueError: If examples is `None`. + """ + if examples is None: + raise ValueError('examples cannot be None for classification.') + if classes is None and scores is None: + raise ValueError('classes and scores cannot both be None for ' + 'classification.') + + input_tensor_info = utils.build_tensor_info(examples) + signature_inputs = {signature_constants.CLASSIFY_INPUTS: input_tensor_info} + + signature_outputs = {} + if classes is not None: + classes_tensor_info = utils.build_tensor_info(classes) + signature_outputs[signature_constants.CLASSIFY_OUTPUT_CLASSES] = ( + classes_tensor_info) + if scores is not None: + scores_tensor_info = utils.build_tensor_info(scores) + signature_outputs[signature_constants.CLASSIFY_OUTPUT_SCORES] = ( + scores_tensor_info) + + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.CLASSIFY_METHOD_NAME) + + return signature_def + + +def predict_signature_def(inputs, outputs): + """Creates prediction signature from given inputs and outputs. + + Args: + inputs: dict of string to `Tensor`. + outputs: dict of string to `Tensor`. + + Returns: + A prediction-flavored signature_def. + + Raises: + ValueError: If inputs or outputs is `None`. + """ + if inputs is None or not inputs: + raise ValueError('inputs cannot be None or empty for prediction.') + if outputs is None: + raise ValueError('outputs cannot be None or empty for prediction.') + + signature_inputs = {key: utils.build_tensor_info(tensor) + for key, tensor in inputs.items()} + signature_outputs = {key: utils.build_tensor_info(tensor) + for key, tensor in outputs.items()} + + signature_def = build_signature_def( + signature_inputs, signature_outputs, + signature_constants.PREDICT_METHOD_NAME) + + return signature_def + + +def _get_shapes_from_tensor_info_dict(tensor_info_dict): + """Returns a map of keys to TensorShape objects. + + Args: + tensor_info_dict: map with TensorInfo proto as values. + + Returns: + Map with corresponding TensorShape objects as values. + """ + return { + key: tensor_shape.TensorShape(tensor_info.tensor_shape) + for key, tensor_info in tensor_info_dict.items() + } + + +def _get_types_from_tensor_info_dict(tensor_info_dict): + """Returns a map of keys to DType objects. + + Args: + tensor_info_dict: map with TensorInfo proto as values. + + Returns: + Map with corresponding DType objects as values. + """ + return { + key: dtypes.DType(tensor_info.dtype) + for key, tensor_info in tensor_info_dict.items() + } + + +def get_signature_def_input_shapes(signature): + """Returns map of parameter names to their shapes. + + Args: + signature: SignatureDef proto. + + Returns: + Map from string to TensorShape objects. + """ + return _get_shapes_from_tensor_info_dict(signature.inputs) + + +def get_signature_def_input_types(signature): + """Returns map of output names to their types. + + Args: + signature: SignatureDef proto. + + Returns: + Map from string to DType objects. + """ + return _get_types_from_tensor_info_dict(signature.inputs) + + +def get_signature_def_output_shapes(signature): + """Returns map of output names to their shapes. + + Args: + signature: SignatureDef proto. + + Returns: + Map from string to TensorShape objects. + """ + return _get_shapes_from_tensor_info_dict(signature.outputs) + + +def get_signature_def_output_types(signature): + """Returns map of output names to their types. + + Args: + signature: SignatureDef proto. + + Returns: + Map from string to DType objects. + """ + return _get_types_from_tensor_info_dict(signature.outputs) diff --git a/pool/shard006/Python/0057807_gaussfit.py b/pool/shard006/Python/0057807_gaussfit.py new file mode 100644 index 0000000000000000000000000000000000000000..d27f2d3e4876009e362bae40bfc049fff7d30aef --- /dev/null +++ b/pool/shard006/Python/0057807_gaussfit.py @@ -0,0 +1,166 @@ +import os as _os +on_rtd = _os.environ.get('READTHEDOCS', None) == 'True' +if not on_rtd: + import numpy as _np + import matplotlib.pyplot as _plt + +from .curve_fit_unscaled import curve_fit_unscaled as _curve_fit_unscaled +from ..matplotlib.figure import figure as _figure +import logging +logger = logging.getLogger(__name__) + + +class GaussResults(object): + """ + Fits a gaussian to a curve specified by pairs *x* and *y*, with error on *y* of *sigma_y*. + + * *plot*: Determines whether the plot is shown + * *p0*: Initial guess given by amplitude *amp*, mean *mu*, and standard deviation *rms*, in the form of: + + * :code:`[amp, mu, rms**2]` if *variance_bool* is true + * :code:`[amp, mu, rms]` if *variance_bool* is false + + * *background_bool*: If true, uses a background term in the fit, with initial guess *bg* + + Returns full statistical results in the form of an instance of class :class:`GaussResults `. + """ + def __init__(self, x, y, sigma_y=None, p0=None, variance=False, background=False): + # ====================================== + # Store things + # ====================================== + self._x = x.flatten() + self._y = y.flatten() + self._sigma_y = sigma_y + self._p0 = p0 + self._variance = variance + self._background = background + + # ====================================== + # Perform curve fit + # ====================================== + self._popt, self._pcov, self._chisq_red = _curve_fit_unscaled(self.func, self.x, self.y, sigma=self.sigma_y, p0=self.p0) + + # ====================================== + # Keep sigma positive + # ====================================== + self._popt[2] = _np.abs(self._popt[2]) + + @property + def popt(self): + """ + The fit parameters for the fit function. + """ + return self._popt + + @property + def pcov(self): + """ + The covariance for the fit parameters. + """ + return self._pcov + + @property + def chisq_red(self): + """ + The reduced chi square. + """ + return self._chisq_red + + @property + def x(self): + return self._x + + @property + def y(self): + return self._y + + @property + def sigma_y(self): + return self._sigma_y + + @property + def variance(self): + return self._variance + + @property + def background(self): + return self._background + + @property + def func(self): + # ====================================== + # Determine whether to use the variance or std dev form + # in the gaussian equation + # ====================================== + if self.variance: + if self.background: + return _gaussvar + else: + return _gaussvar_nobg + else: + if self.background: + return _gauss + else: + return _gauss_nobg + + @property + def use_error(self): + return ( self.sigma_y is not None ) + + @property + def p0(self): + # ====================================== + # Determine initial guesses + # ====================================== + if (self._p0 is None): + amp = max(self.y) + mu = sum(self.x * self.y) / sum(self.y) + rms = _np.sqrt(sum((self.x-mu)**2 * self.y) / sum(self.y)) + + # ====================================== + # Modify initial guess for variance + # ====================================== + if self.variance: + self._p0 = _np.array((amp, mu, rms**2)) + else: + self._p0 = _np.array((amp, mu, rms)) + + # ====================================== + # Modify initial guess for background + # ====================================== + if self.background: + self._p0 = _np.append(self._p0, min(self.y)) + + return self._p0 + + def plot(self): + xmin = min(self.x) + xmax = max(self.x) + x_fit = _np.linspace(xmin, xmax, 1000) + y_fit = self.func(x_fit, *self.popt) + _figure('MYTOOLS: Gauss Fit Routine') + if self.use_error: + sigma_y = self.sigma_y.flatten() + _plt.errorbar(self.x, self.y, yerr=sigma_y, fmt='o-') + _plt.plot(x_fit, y_fit) + else: + _plt.plot(self.x, self.y, 'o-', x_fit, y_fit) + + +def _gauss(x, amp, mu, sigma, bg=0): + # print 'Sigma is {}.'.format(sigma) + return _np.abs(amp) * _np.exp( -(x - mu)**2 / (2 * sigma**2)) + bg + # return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * sigma**2)) + + +def _gauss_nobg(x, amp, mu, sigma): + return _gauss(x, amp, mu, sigma) + + +def _gaussvar(x, amp, mu, variance, bg=0): + return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * variance)) + bg + # return _np.abs(amp) * _np.exp(-(x - mu)**2 / (2 * variance)) + + +def _gaussvar_nobg(x, amp, mu, variance): + return _gaussvar(x, amp, mu, variance) diff --git a/pool/shard006/Python/0057811_logger.py b/pool/shard006/Python/0057811_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..97c076d9c34a96acdda53fa768fe497bd01601af --- /dev/null +++ b/pool/shard006/Python/0057811_logger.py @@ -0,0 +1,119 @@ +''' +Created on Aug 23, 2013 + +@author: Brad +''' +import logging.handlers +import os + +class Logger(object): + ''' + This is a wrapper class for logging. + + Levels When it is used + ------ --------------- + DEBUG Detailed information, typically of interest only when + diagnosing problems. + INFO Confirmation that things are working as expected. + WARNING An indication that something unexpected happened, + or indicative of some problem in the near future + (e.g. 'disk space low'). The software is still + working as expected. + ERROR Due to a more serious problem, the software has not + been able to perform some function. + CRITICAL A serious error, indicating that the program itself + may be unable to continue running. + + ''' + + def __init__(self): + ''' + Constructor + ''' + # Default values. + self.LOG_DIR = './log/' + self.LOG_FILENAME = 'logging_rotatingfile_example.out' + self.level = logging.DEBUG + self.maxBytes = 1000000 + self.backupCount = 4 + + + def createLogger(self, name='MyLogger'): + ''' + This method creates a logger using the default values. + + Change default values before calling this method if you need + something different, such as a different logging directory. + + Ex. + log = Logger() + log.LOG_DIR = '/tmp/' + log.createLogger(name='TestLogger') + ''' + + self.setLogDirAndName() + + # Set up a specific logger with our desired output level. + my_logger = logging.getLogger(name) + my_logger.setLevel(self.level) + + # Create file handler which logs even debug messages. + handler = logging.handlers.RotatingFileHandler( + self.LOG_DIR_AND_NAME, maxBytes=self.maxBytes, backupCount=self.backupCount) + + # Create formatter. + # 2015-04-04 17:29:25,465 - + # DEBUG - + # /Users/bradfulton/GitRepos/RaspiCamPiWrap/RaspiCamPyWrap/test/utils/test_logger.py - + # test_format_VISUALLY - + # 66 - + # debug message + my_format = '%(asctime)s - %(levelname)s - %(pathname)s - %(funcName)s - %(lineno)d - %(message)s' + formatter = logging.Formatter(my_format) + # And add it to the handler. + handler.setFormatter(formatter) + + # Add the log message handler to the logger. + my_logger.addHandler(handler) + + return my_logger + + + def setLogDirAndName(self): + ''' + This method creates the logging directory if needed and sets + the LOG_DIR_AND_NAME variable using the directory and file names. + ''' + self.createLogDir() + self.LOG_DIR_AND_NAME = self.LOG_DIR + self.LOG_FILENAME + + + def createLogDir(self): + ''' + This method creates the logging directory if it doesn't already exist. + If the directory cannot be created, then a local log directory will be + created. + ''' + directory = self.LOG_DIR + try: + if not os.path.exists(directory): + os.makedirs(directory) + except Exception: + print 'Could not create: ' + os.path.realpath(self.LOG_DIR) + self.createDefaultLogDir() + + + def createDefaultLogDir(self): + ''' + This method creates the default logging directory (./log/). + ''' + self.LOG_DIR = './log/' + directory = self.LOG_DIR + try: + if not os.path.exists(directory): + os.makedirs(directory) + + print 'Created: ' + os.path.realpath(self.LOG_DIR) + except Exception as e: + print e + diff --git a/pool/shard006/Python/0057813_energy_logger.py b/pool/shard006/Python/0057813_energy_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..68bc501663640d520375f08544fb9f4655baa31f --- /dev/null +++ b/pool/shard006/Python/0057813_energy_logger.py @@ -0,0 +1,61 @@ +#!/usr/bin/python3.2 + +''' +Created on 05.06.2014 + +@author: christoph +''' +import os +from twill.commands import * +import time as time +import urllib2 + +# Energenie Password +password = "" + +# Energenie IP Address +ip_addr = "" + +login_url= "http://%s/login.html" % ip_addr +logger_url = "http://%s/energenie.html" % ip_addr + +def login(): + + go(login_url) + fv("1", "pw", password) + submit("0") + + +def get_data(): + log_file = open("energy.log", "a") + aResp = urllib2.urlopen(logger_url); + energy_data_log_webpage = aResp.read(); + + log_vars = energy_data_log_webpage.split("var") + + for i, v in enumerate(log_vars): + v1 = v.split("=") + v2 = v1[1].split(";") +# print v + if(i==10): + log_voltage = float(float(v2[0])/10) + elif(i==11): + log_current = float(float(v2[0])/100) + elif(i==12): + log_power = float(float(v2[0])/466) + elif(i==13): + log_energy = float(float(v2[0])/25600) + + ttime = time.localtime() + log_string = "%s.%s.%s-%s:%s:%s;%sV;%sA;%sW;%skWh;\n" %(ttime[2],ttime[1],ttime[0],ttime[3],ttime[4],ttime[5],log_voltage,log_current,log_power,log_energy) +# print log_string + log_file.write(log_string) + log_file.close() + +if __name__ == "__main__": + login() + while(1): + time.sleep(10) +# login() + get_data() + diff --git a/pool/shard006/Python/0057815_forms.py b/pool/shard006/Python/0057815_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..67c785530e1c6186f5371bd8f9522f9470115883 --- /dev/null +++ b/pool/shard006/Python/0057815_forms.py @@ -0,0 +1,107 @@ +from django import forms +from django.apps import apps +from django.conf import settings +from django.utils.translation import gettext as _ + +from planb.storage import storage_pools + +from .models import Fileset, HostGroup + + +class HostGroupAdminForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields['blacklist_hours'].help_text = _( + 'Specify hours during which backups are disabled using notation ' + 'h,h-h or none to disable blacklist hours. When left empty the ' + 'system blacklist hours {} are used.' + ).format(settings.PLANB_BLACKLIST_HOURS) + self.fields['retention'].help_text = _( + 'The backup retention period using notation separated ' + 'by comma: 1y,6m,3w,15d. When left empty the system retention ' + '{} is used.').format(settings.PLANB_RETENTION) + + class Meta: + model = HostGroup + fields = '__all__' + + +class FilesetAdminForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.instance.pk: + blacklist_hours = self.instance.hostgroup.get_blacklist_hours() + retention = self.instance.hostgroup.get_retention() + else: + blacklist_hours = settings.PLANB_BLACKLIST_HOURS + retention = settings.PLANB_RETENTION + self.fields['blacklist_hours'].help_text = _( + 'Specify hours during which backups are disabled using notation ' + 'h,h-h or none to disable blacklist hours. When left empty the ' + 'hostgroup blacklist hours {} are used.' + ).format(blacklist_hours) + self.fields['retention'].help_text = _( + 'The backup retention period using notation separated ' + 'by comma: 1y,6m,3w,15d. When left empty the hostgroup retention ' + '{} is used.').format(retention) + + if 'storage_alias' in self.fields: + storage_choices = tuple( + (storage.alias, storage.get_label()) + for storage in storage_pools.values()) + self.fields['storage_alias'] = forms.ChoiceField( + label=_('Storage'), choices=storage_choices) + + if 'hostgroup' in self.fields: + self.fields['hostgroup'].queryset = ( + self.fields['hostgroup'].queryset.order_by('name')) + + class Meta: + model = Fileset + exclude = ( + 'last_ok', + 'last_run', + 'first_fail', + ) + + +class FilesetRefForm(forms.ModelForm): + """ + Generate FilesetRefForm tailored to the supplied class; so sorting + of the Filesets works. + + Use in your admin class. For example: + + from django.forms import modelform_factory + from planb.forms import FilesetRefForm + + class MyModel(models.Model): + fileset = models.OneToOneField(Fileset) + + class MyModelAdmin(admin.ModelAdmin): + form = modelform_factory(MyModel, form=FilesetRefForm) + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + if 'fileset' in self.fields: + # Order. + self.fields['fileset'].queryset = ( + self.fields['fileset'].queryset.order_by('friendly_name')) + + # Get IDs of used filesets. + ids = set() + for transport_class_name in settings.PLANB_TRANSPORTS: + transport_class = apps.get_model(transport_class_name) + ids.update(transport_class.objects.values_list( + 'fileset', flat=True)) + + # Don't list used filesets. + # NOTE: This is not a fool-proof way to avoid + # MultipleObjectsReturned. But it will provide a better + # interface. + self.fields['fileset'].queryset = ( + self.fields['fileset'].queryset.exclude(id__in=ids)) + + class Meta: + fields = '__all__' diff --git a/pool/shard006/Python/0057818_make_website.py b/pool/shard006/Python/0057818_make_website.py new file mode 100644 index 0000000000000000000000000000000000000000..e155402c94beb9d80968eeab9cc2a66dc08c2f60 --- /dev/null +++ b/pool/shard006/Python/0057818_make_website.py @@ -0,0 +1,165 @@ +""" +Sun Oct 12 11:38:18 IDT 2014 +by xorpd. + +A script for auto generating the xorpd's website. +""" + +from mako.template import Template +from mako.lookup import TemplateLookup + +import os +import shutil + +import lib.utils + +class MakeWebsiteError(Exception): pass + + +# The content's directory name: +CONTENT_DIR = "content" +# The output's directory name: +OUTPUT_DIR = "output" + + +class ExceptStaticWeber(Exception): + pass + +class ExceptInvalidExtension(ExceptStaticWeber): + pass + +def change_extension(filename,new_ext): + """ + Change the extension of a file to be new_ext + """ + last_dot = filename.rfind(".") + return filename[:last_dot] + "." + new_ext + +def get_extension(filename): + """ + Get the extension of a file (What comes right after the last dot). + """ + return filename.split(".")[-1] + +def clean_empty_dirs(root_dir,ignore_prefixes=["."]): + """ + Check the directory tree for any empty directories, or directories that + contain only empty directories (etc.) + Then delete any such directories. + + Do not delete inside any directories which begin with one of the + ignore_prefixes. + """ + # We don't get into directories which begin with + # one of the ignore prefixes: + for iprefix in ignore_prefixes: + if os.path.basename(root_dir).startswith(iprefix): + return + + files = os.listdir(root_dir) + + for f in files: + new_root = os.path.join(root_dir,f) + if os.path.isdir(new_root): + clean_empty_dirs(new_root) + + # After some deleting, we get again the list of contents. + # Note that this will not be the same list from the first time. + files = os.listdir(root_dir) + if len(files) == 0: + # If there are no files inside the directory, remove it and exit: + os.rmdir(root_dir) + + +class Website(): + def __init__(self,path): + # Load the path of the website: + self.website_path = path + + def build_website(self): + + # Build the path of the content folder: + content_path = os.path.join(self.website_path,CONTENT_DIR) + + # Build the path of the output folder: + output_path = os.path.join(self.website_path,OUTPUT_DIR) + + # Directory lookup. + # This way include or inherit directive from any of the mako templates + # doesn't have to specify the full path. + wlookup = TemplateLookup(directories=[content_path]) + + # Remove output directory if it exists: + # try: + # shutil.rmtree(output_path) + # except FileNotFoundError: + # pass + + + # Iterate over all files inside the content directory, to find MAKO + # templates to render: + for root,dirs,files in os.walk(content_path): + + # Copy to the equivalent at the output directory: + rel_root = os.path.relpath(root,content_path) + # Get equivalent path inside output directory: + root_output = os.path.join(output_path,rel_root) + # Create equivalent folder if necessary: + if not os.path.exists(root_output): + os.makedirs(root_output) + + + for fl in files: + # Get full path inside content directory: + fl_path = os.path.join(root,fl) + fl_ext = lib.utils.get_extension(fl) + + props = lib.utils.get_ext_props(fl_ext) + + + if props.should_render: + # Build a template: + fl_tmp = Template(filename=fl_path,lookup=wlookup) + # Get the filename as target_ext extensioned file: + fl_with_ext = lib.utils.change_extension(fl,props.target_ext) + fl_with_ext_output = os.path.join(root_output,fl_with_ext) + + try: + # Render the template: + res_render = fl_tmp.render(my_filename=fl,\ + my_content_dir=content_path,\ + my_output_dir=output_path,\ + my_rel_dir=rel_root) + except Exception as e: + raise MakeWebsiteError('Failed rendering ' + '{}'.format(fl)) from e + + + + if props.render_output: + # Write the template's rendering result to a file at + # the output directory tree: + with open(fl_with_ext_output,"w") as fw: + fw.write(res_render) + continue + + if props.should_copy: + # We copy the file to the destination folder: + # Get equivalent path inside output directory: + fl_output = os.path.join(root_output,fl) + # Copy to output directory: + shutil.copyfile(fl_path,fl_output) + # Continue to the next file: + continue + + # Clean any empty directories inside output: + clean_empty_dirs(output_path,ignore_prefixes=["."]) + + +def go(): + wb = Website(".") + wb.build_website() + + +if __name__ == "__main__": + go() diff --git a/pool/shard006/Python/0057830_fixup.py b/pool/shard006/Python/0057830_fixup.py new file mode 100644 index 0000000000000000000000000000000000000000..85c962e869d6437f30e60ec0716fbdbbdd78ca68 --- /dev/null +++ b/pool/shard006/Python/0057830_fixup.py @@ -0,0 +1,80 @@ +import base64, hmac, marshal, mod_python.util, mod_python.Cookie +from mod_python.Cookie import CookieError, PY2 + +def fixup(self, value): + try: + if isinstance(value, str): + return bytes.__new__(self, value.encode()) + else: + return bytes.__new__(self, value) + except: + raise ValueError(str(type(value))) +mod_python.util.StringField.__new__ = fixup + +def fixup2(self): + m = base64.encodestring(marshal.dumps(self.value)) + # on long cookies, the base64 encoding can contain multiple lines + # separated by \n or \r\n + if isinstance(m, bytes): + m = m.decode() + m = ''.join(m.split()) + + result = ["%s=%s%s" % (self.name, self.hexdigest(m), m)] + for name in self._valid_attr: + if hasattr(self, name): + if name in ("secure", "discard", "httponly"): + result.append(name) + else: + result.append("%s=%s" % (name, getattr(self, name))) + return "; ".join(result) +mod_python.Cookie.MarshalCookie.__str__ = fixup2 + +def fixup3(self, str): + import hmac + if not self.__data__["secret"]: + raise CookieError("Cannot sign without a secret") + if PY2: + _hmac = hmac.new(self.__data__["secret"], self.name) + _hmac.update(str) + else: + _hmac = hmac.new(self.__data__["secret"].encode(), self.name.encode()) + _hmac.update(str.encode()) + return _hmac.hexdigest() +mod_python.Cookie.SignedCookie.hexdigest = fixup3 + +def fixup4(self, secret): + import hmac + sig, val = self.value[:32], self.value[32:] + + if PY2: + mac = hmac.new(secret, self.name) + mac.update(val) + else: + mac = hmac.new(secret.encode(), self.name.encode()) + mac.update(val.encode()) + + if mac.hexdigest() == sig: + self.value = val + self.__data__["secret"] = secret + else: + raise mod_python.Cookie.CookieError("Incorrectly Signed Cookie: %s=%s" % (self.name, self.value)) +mod_python.Cookie.SignedCookie.unsign = fixup4 + +def fixup5(self, secret): + + self.unsign(secret) + + try: + if PY2: + data = base64.decodestring(self.value) + else: + data = base64.decodestring(self.value.encode()) + except: + raise mod_python.Cookie.CookieError("Cannot base64 Decode Cookie: %s=%s" % (self.name, self.value)) + + try: + self.value = marshal.loads(data) + except (EOFError, ValueError, TypeError): + raise CookieError("Cannot Unmarshal Cookie: %s=%s" % (self.name, self.value)) +mod_python.Cookie.MarshalCookie.unmarshal = fixup5 + diff --git a/pool/shard006/Python/0057834_min_hill_sort.py b/pool/shard006/Python/0057834_min_hill_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..9e49930a5ada5569255b432b6c0e07cf08613017 --- /dev/null +++ b/pool/shard006/Python/0057834_min_hill_sort.py @@ -0,0 +1,49 @@ +""" + +""" +import unittest + + +def check_valid(arr, x): + temp_arr = arr[:] + temp_arr[0] = arr[0] - x + for i in range(1, len(arr)): + if temp_arr[i-1] < x + temp_arr[i]: + temp_arr[i] = max(temp_arr[i-1]+1, temp_arr[i]-x) + else: + return False + return True + + +def min_to_sort(arr): + low = 1 + high = 2**31 - 1 + result = -1 + while low < high: + mid = (high + low)//2 + if check_valid(arr, mid): + result = mid + high = mid - 1 + else: + low = mid + 1 + return result + + +class MyTestResults(unittest.TestCase): + def test_check_valid(self): + arr = [5, 4, 3, 2, 8] + self.assertTrue(check_valid(arr, 500)) + self.assertTrue(check_valid(arr, 5)) + self.assertTrue(check_valid(arr, 4)) + self.assertTrue(check_valid(arr, 3)) + self.assertFalse(check_valid(arr, 2)) + self.assertFalse(check_valid(arr, 1)) + self.assertFalse(check_valid(arr, 1)) + arr = [52, 71, 36, 92, 48] + self.assertTrue(check_valid(arr, 23)) + + def test_min_to_sort(self): + arr = [5, 4, 3, 2, 8] + self.assertEqual(min_to_sort(arr), 3) + arr = [52, 71, 36, 92, 48] + self.assertEqual((check_valid(arr, 23))) diff --git a/pool/shard006/Python/0057844_train_multiprocess.py b/pool/shard006/Python/0057844_train_multiprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..11ebe883f3eedc12f03da30c843fb011c7ffe4b5 --- /dev/null +++ b/pool/shard006/Python/0057844_train_multiprocess.py @@ -0,0 +1,98 @@ +# +# 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. +# + + +from singa import singa_wrap as singa +from singa import opt +import argparse +import train +import multiprocessing + +def run(args, local_rank, world_size, nccl_id): + sgd = opt.SGD(lr=args.lr, momentum=0.9, weight_decay=1e-5) + sgd = opt.DistOpt(sgd, nccl_id=nccl_id, local_rank=local_rank, world_size=world_size) + train.run(sgd.global_rank, sgd.world_size, sgd.local_rank, + args.max_epoch, args.batch_size, args.model, args.data, sgd, args.graph, args.dist_option, args.spars) + + +if __name__ == '__main__': + # use argparse to get command config: max_epoch, model, data, etc. for single gpu training + parser = argparse.ArgumentParser( + description='Training using the autograd and graph.') + parser.add_argument('model', + choices=['resnet', 'xceptionnet', 'cnn', 'mlp'], + default='cnn') + parser.add_argument('data', choices=['cifar10', 'cifar100', 'mnist'], default='mnist') + parser.add_argument('--epoch', + '--max-epoch', + default=10, + type=int, + help='maximum epochs', + dest='max_epoch') + parser.add_argument('--bs', + '--batch-size', + default=64, + type=int, + help='batch size', + dest='batch_size') + parser.add_argument('--lr', + '--learning-rate', + default=0.005, + type=float, + help='initial learning rate', + dest='lr') + parser.add_argument('--ws', + '--world-size', + default=2, + type=int, + help='number of gpus to be used', + dest='world_size') + parser.add_argument('--op', + '--option', + default='fp32', + choices=['fp32','fp16','partialUpdate','sparseTopK','sparseThreshold'], + help='distibuted training options', + dest='dist_option') # currently partialUpdate support graph=False only + parser.add_argument('--spars', + '--sparsification', + default='0.05', + type=float, + help='the sparsity parameter used for sparsification, between 0 to 1', + dest='spars') + parser.add_argument('--no-graph', + '--disable-graph', + default='True', + action='store_false', + help='disable graph', + dest='graph') + + + args = parser.parse_args() + + # Generate a NCCL ID to be used for collective communication + nccl_id = singa.NcclIdHolder() + + process = [] + for local_rank in range(0, args.world_size): + process.append( + multiprocessing.Process(target=run, + args=(args, local_rank, args.world_size, nccl_id))) + + for p in process: + p.start() diff --git a/pool/shard006/Python/0057847_testrungroup.py b/pool/shard006/Python/0057847_testrungroup.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7bc11731ea5a6e4a001fd8ae4349e8959ed548 --- /dev/null +++ b/pool/shard006/Python/0057847_testrungroup.py @@ -0,0 +1,97 @@ +__author__ = 'Jared Jorgensen' + +from slickqaweb.app import app +from slickqaweb.model.testrunGroup import TestrunGroup +from slickqaweb.model.testrun import Testrun +from slickqaweb.model.serialize import deserialize_that +from slickqaweb.model.query import queryFor +from slickqaweb.utils import * +import datetime +from flask import request, g +from .standardResponses import JsonResponse, read_request +from bson import ObjectId +from .apidocs import add_resource, accepts, returns, argument_doc, standard_query_parameters, note +from mongoengine import ListField, ReferenceField + +add_resource('/testrungroups', 'Add, update, and delete testrungroups.') + + +@app.route('/api/testrungroups') +@standard_query_parameters +@returns(ListField(ReferenceField(TestrunGroup))) +def get_testrungroups(): + """Query for testrungroups.""" + return JsonResponse(queryFor(TestrunGroup)) + +@app.route('/api/testrungroups/') +@returns(TestrunGroup) +@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).") +def get_testrungroup_by_id(testrungroup_id): + """Find a testrungroup by it's id.""" + return JsonResponse(TestrunGroup.objects(id=testrungroup_id).first()) + + +@app.route('/api/testrungroups', methods=["POST"]) +@returns(TestrunGroup) +@accepts(TestrunGroup) +@note("If you do not provide a created date, one will be created.") +def add_testrungroup(): + """Create a new testrungroup.""" + new_trg = deserialize_that(read_request(), TestrunGroup()) + if is_not_provided(new_trg, 'created'): + new_trg.created = datetime.datetime.now() + new_trg.save() + return JsonResponse(new_trg) + +@app.route('/api/testrungroups/', methods=["PUT"]) +@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).") +@returns(TestrunGroup) +@accepts(TestrunGroup) +def update_testrungroup(testrungroup_id): + """Update a testrun group's properties.""" + orig = TestrunGroup.objects(id=testrungroup_id).first() + deserialize_that(read_request(), orig) + orig.save() + return JsonResponse(orig) + +@app.route('/api/testrungroups/', methods=["DELETE"]) +@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).") +@returns(TestrunGroup) +def delete_testrungroup(testrungroup_id): + """Remove a testrun group""" + orig = TestrunGroup.objects(id=testrungroup_id).first() + orig.delete() + return JsonResponse(orig) + +@app.route('/api/testrungroups//addtestrun/', methods=["POST"]) +@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).") +@argument_doc('testrun_id', "A Testrun's id (the string representation of a BSON ObjectId).") +@returns(TestrunGroup) +def add_testrun_to_testrun_group(testrungroup_id, testrun_id): + """Add a testrun to a testrun group""" + orig = TestrunGroup.objects(id=ObjectId(testrungroup_id)).first() + testrun = Testrun.objects(id=ObjectId(testrun_id)).first() + if (not hasattr(orig, 'testruns')) or orig.testruns is None: + orig.testruns = [] + orig.testruns.append(testrun) + orig.save() + return JsonResponse(orig) + +@app.route('/api/testrungroups//removetestrun/', methods=["DELETE"]) +@argument_doc('testrungroup_id', "A Testrun Group's id (the string representation of a BSON ObjectId).") +@argument_doc('testrun_id', "A Testrun's id (the string representation of a BSON ObjectId).") +@returns(TestrunGroup) +def remove_testrun_from_testrun_group(testrungroup_id, testrun_id): + """Remove a testrun from a testrun group""" + orig = TestrunGroup.objects(id=ObjectId(testrungroup_id)).first() + real_testrunid = ObjectId(testrun_id) + index = -1 + for i in range(len(orig.testruns)): + if orig.testruns[i].id == real_testrunid: + index = i + break + if index >= 0: + del orig.testruns[index] + orig.save() + return JsonResponse(orig) + diff --git a/pool/shard006/Python/0057851_views.py b/pool/shard006/Python/0057851_views.py new file mode 100644 index 0000000000000000000000000000000000000000..1b58af0ba7a5740d56897bb9709d3d4dac4bc8cf --- /dev/null +++ b/pool/shard006/Python/0057851_views.py @@ -0,0 +1,44 @@ +# -*-coding: utf-8 -*- +from django.shortcuts import render, redirect +from django.contrib import auth +from django.contrib.auth.forms import UserCreationForm +from django.core.context_processors import csrf + + +# Create your views here. +def login(request): + args={} + args.update(csrf(request)) + if request.POST: + username=request.POST.get('username','') + password=request.POST.get('password','') + user=auth.authenticate(username=username,password=password) + if user is not None: + auth.login(request,user) + return redirect('/idea') + else: + args['login_error']="Пользователь не найдкн" + return render(request,'login.html',args) + else: + return render(request,'login.html',args) + +def logout(request): + back_url = request.META['HTTP_REFERER'] + auth.logout(request) + return redirect(back_url) + +def register(request): + args = {} + args['form'] = UserCreationForm() + if request.POST: + newuser_form = UserCreationForm() + args.update(csrf(request)) + if newuser_form.is_valid(): + newuser_form.save() + newuser = auth.authenticate(username=newuser_form.cleaned_data['username'], password=newuser_form.cleaned_data['password2']) + auth.login(request, newuser) + return redirect('/') + else: + args['form'] = UserCreationForm() + return render(request,'register.html', args) + diff --git a/pool/shard006/Python/0057859_netcmd.py b/pool/shard006/Python/0057859_netcmd.py new file mode 100644 index 0000000000000000000000000000000000000000..fc77af8d12de8f806319815438a03576c5373e92 --- /dev/null +++ b/pool/shard006/Python/0057859_netcmd.py @@ -0,0 +1,215 @@ +# This code is part of Ansible, but is an independent component. +# This particular file snippet, and this file snippet only, is BSD licensed. +# Modules you write using this snippet, which is embedded dynamically by Ansible +# still belong to the author of the module, and may assign their own license +# to the complete work. +# +# Copyright (c) 2015 Peter Sprygada, +# +# 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 re +import time +import itertools +import shlex + +from ansible.module_utils.basic import BOOLEANS_TRUE, BOOLEANS_FALSE + +class Conditional(object): + """Used in command modules to evaluate waitfor conditions + """ + + OPERATORS = { + 'eq': ['eq', '=='], + 'neq': ['neq', 'ne', '!='], + 'gt': ['gt', '>'], + 'ge': ['ge', '>='], + 'lt': ['lt', '<'], + 'le': ['le', '<='], + 'contains': ['contains'], + 'matches': ['matches'] + } + + def __init__(self, conditional, encoding='json'): + self.raw = conditional + self.encoding = encoding + + key, op, val = shlex.split(conditional) + self.key = key + self.func = self.func(op) + self.value = self._cast_value(val) + + def __call__(self, data): + value = self.get_value(dict(result=data)) + return self.func(value) + + def _cast_value(self, value): + if value in BOOLEANS_TRUE: + return True + elif value in BOOLEANS_FALSE: + return False + elif re.match(r'^\d+\.d+$', value): + return float(value) + elif re.match(r'^\d+$', value): + return int(value) + else: + return unicode(value) + + def func(self, oper): + for func, operators in self.OPERATORS.items(): + if oper in operators: + return getattr(self, func) + raise AttributeError('unknown operator: %s' % oper) + + def get_value(self, result): + if self.encoding in ['json', 'text']: + return self.get_json(result) + elif self.encoding == 'xml': + return self.get_xml(result.get('result')) + + def get_xml(self, result): + parts = self.key.split('.') + + value_index = None + match = re.match(r'^\S+(\[)(\d+)\]', parts[-1]) + if match: + start, end = match.regs[1] + parts[-1] = parts[-1][0:start] + value_index = int(match.group(2)) + + path = '/'.join(parts[1:]) + path = '/%s' % path + path += '/text()' + + index = int(re.match(r'result\[(\d+)\]', parts[0]).group(1)) + values = result[index].xpath(path) + + if value_index is not None: + return values[value_index].strip() + return [v.strip() for v in values] + + def get_json(self, result): + parts = re.split(r'\.(?=[^\]]*(?:\[|$))', self.key) + for part in parts: + match = re.findall(r'\[(\S+?)\]', part) + if match: + key = part[:part.find('[')] + result = result[key] + for m in match: + try: + m = int(m) + except ValueError: + m = str(m) + result = result[m] + else: + result = result.get(part) + return result + + def number(self, value): + if '.' in str(value): + return float(value) + else: + return int(value) + + def eq(self, value): + return value == self.value + + def neq(self, value): + return value != self.value + + def gt(self, value): + return self.number(value) > self.value + + def ge(self, value): + return self.number(value) >= self.value + + def lt(self, value): + return self.number(value) < self.value + + def le(self, value): + return self.number(value) <= self.value + + def contains(self, value): + return str(self.value) in value + + def matches(self, value): + match = re.search(value, self.value, re.M) + return match is not None + + +class FailedConditionsError(Exception): + + def __init__(self, msg, failed_conditions): + super(FailedConditionsError, self).__init__(msg) + self.failed_conditions = failed_conditions + +class CommandRunner(object): + + def __init__(self, module): + self.module = module + + self.items = list() + self.conditionals = set() + + self.retries = 10 + self.interval = 1 + + self._cache = dict() + + def add_command(self, command, output=None): + self.module.cli.add_commands(command, output=output) + + def get_command(self, command): + try: + cmdobj = self._cache[command] + return cmdobj.response + except KeyError: + for cmd in self.module.cli.commands: + if str(cmd) == command: + self._cache[command] = cmd + return cmd.response + raise ValueError("command '%s' not found" % command) + + + def add_conditional(self, condition): + self.conditionals.add(Conditional(condition)) + + def run_commands(self): + responses = self.module.cli.run_commands() + self.items = responses + + def run(self): + while self.retries > 0: + self.run_commands() + + for item in list(self.conditionals): + if item(self.items): + self.conditionals.remove(item) + + if not self.conditionals: + break + + time.sleep(self.interval) + self.retries -= 1 + else: + failed_conditions = [item.raw for item in self.conditionals] + raise FailedConditionsError('timeout waiting for value', failed_conditions) + diff --git a/pool/shard006/Python/0057862_visual_confirmation.py b/pool/shard006/Python/0057862_visual_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..8e89d8b8b8b1793dfe032da0ecf43020d57e75a7 --- /dev/null +++ b/pool/shard006/Python/0057862_visual_confirmation.py @@ -0,0 +1,97 @@ +import numpy +from investigators.visuals import cv2 # package includes a fallback cv2 +from investigators.visuals import TemplateFinder, ProportionalRegion, Grid +from investigators.visuals import ImageIdentifier, TankLevel + +# Show the starting screenshot +screenshot = cv2.imread('screenshot 1280x800, game 800x600.png') +cv2.imshow('screenshot', screenshot) +cv2.waitKey() + +# Use TemplateFinder to locate and show an image of the game on the screen +template = cv2.imread('game 640x480.png') +mask = cv2.imread('game mask 640x480.png') +possible_sizes = (600, 800), (240, 320) +finder = TemplateFinder(template, sizes=possible_sizes, mask=mask, + scale_for_speed=0.25) +t, l, b, r = finder.locate_in(screenshot) +game = screenshot[t:b, l:r] +cv2.destroyWindow('screenshot') +cv2.imshow('extracted game', game) +cv2.waitKey() + +# Use ProportionalRegion to isolate the board within the game +tlbr_proportions = (80.0 / 480, 135.0 / 640, 450.0 / 480, 504.0 / 640) +proportional = ProportionalRegion(tlbr_proportions) +t, l, b, r = proportional.region_in(game) +board = game[t:b, l:r] +cv2.imshow('extracted board', board) +cv2.waitKey() + +# Use Grid to split the grid into image cells. record only the first four +board_dimensions = 8, 8 +tile_padding = (0.1, 0.1, 0.1, 0.1) # just for demonstration +grid = Grid(board_dimensions, tile_padding) +first_four_tiles = list() +for grid_p, cell_borders in grid.borders_by_grid_position(board): + if grid_p in ((0, 0), (0, 1), (0, 2), (0, 3)): + t, l, b, r = cell_borders + first_four_tiles.append(board[t:b, l:r]) + +# Use ImageIdentifier to identify each of the first four tiles +identifier = ImageIdentifier({'red': cv2.imread('r.png'), + 'blue': cv2.imread('b.png'), + 'coins': cv2.imread('m.png'), + 'skull': cv2.imread('s.png')}) +for tile in first_four_tiles: + name = identifier.identify(tile) + cv2.putText(tile, name, (2, 20), 0, 0.6, (255, 255, 255), 2) + cv2.imshow('identified original tile', tile) + cv2.waitKey() +cv2.destroyWindow('identified original tile') +cv2.destroyWindow('extracted board') + +# Use ProportionalRegion to isolate the player's health within the game +tlbr_proportions = (76.0 / 480, 8.0 / 640, 87.0 / 480, 116.0 / 640) +proportional = ProportionalRegion(tlbr_proportions) +t, l, b, r = proportional.region_in(game) +health = game[t:b, l:r] + +# Use TankLevel to measure how full the health bar is +health_color = (4, 4, 110) +empty_health_color = (15, 15, 50) +ignore_color = (0, 0, 0) +tank_level = TankLevel(health_color, empty_health_color, ignore_color) +health = numpy.rot90(health) # make it upright for the TankLevel measurement +health_pcnt = 100.0 * tank_level.how_full(health) +health_string = '~{:2.0f}%'.format(health_pcnt) +health = numpy.rot90(health, -1) # rotate and enlarge for display +h, w = health.shape[0:2] +health = cv2.resize(health, (w * 3, h * 3), interpolation=cv2.INTER_CUBIC) +cv2.putText(health, health_string, (25, 25), 0, 0.8, (0, 255, 0), 2) +cv2.imshow('player health bar', health) +cv2.waitKey() + +# Use ProportionalRegion to isolate the extra actions area within the game +tlbr_proportions = (120.0 / 960, 1100.0 / 1280, 160.0 / 960, 1220.0 / 1280) +proportional = ProportionalRegion(tlbr_proportions) +t, l, b, r = proportional.region_in(game) +token_region = game[t:b, l:r] + +# Use TemplateFinder (multiple) to check for extra actions +token_template = cv2.imread('extra_turn_token.png') +possible_sizes = (17, 14), +finder = TemplateFinder(token_template, sizes=possible_sizes, + acceptable_threshold=0.1, immediate_threshold=0.1) +found_tokens = finder.locate_multiple_in(token_region) +for borders in found_tokens: + t, l, b, r = borders + cv2.rectangle(token_region, (l, t), (r, b), (255, 255, 255), 2) +h, w = token_region.shape[0:2] +token_region = cv2.resize(token_region, (w * 3, h * 3), + interpolation=cv2.INTER_CUBIC) +cv2.imshow('extra actions', token_region) +cv2.waitKey() + +# clean up +cv2.destroyAllWindows() diff --git a/pool/shard006/Python/0057867_setup.py b/pool/shard006/Python/0057867_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..67e307f235ecc16a14d564fecacb308f1bbd5063 --- /dev/null +++ b/pool/shard006/Python/0057867_setup.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- + +from __future__ import print_function +from setuptools import setup, find_packages, Command +from setuptools.command.sdist import sdist +from setuptools.command.build_py import build_py +from setuptools.command.egg_info import egg_info +from subprocess import check_call +import os +import sys +import platform + +here = os.path.dirname(os.path.abspath(__file__)) +node_root = os.path.join(here, 'js') +is_repo = os.path.exists(os.path.join(here, '.git')) + +npm_path = os.pathsep.join([ + os.path.join(node_root, 'node_modules', '.bin'), + os.environ.get('PATH', os.defpath), +]) + +from distutils import log +log.set_verbosity(log.DEBUG) +log.info('setup.py entered') +log.info('$PATH=%s' % os.environ['PATH']) + +LONG_DESCRIPTION = 'A Python/ThreeJS bridge utilizing the Jupyter widget infrastructure.' + +def js_prerelease(command, strict=False): + """decorator for building minified js/css prior to another command""" + class DecoratedCommand(command): + def run(self): + jsdeps = self.distribution.get_command_obj('jsdeps') + if not is_repo and all(os.path.exists(t) for t in jsdeps.targets): + # sdist, nothing to do + command.run(self) + return + + try: + self.distribution.run_command('jsdeps') + except Exception as e: + missing = [t for t in jsdeps.targets if not os.path.exists(t)] + if strict or missing: + log.warn('rebuilding js and css failed') + if missing: + log.error('missing files: %s' % missing) + raise e + else: + log.warn('rebuilding js and css failed (not a problem)') + log.warn(str(e)) + command.run(self) + update_package_data(self.distribution) + return DecoratedCommand + +def update_package_data(distribution): + """update package_data to catch changes during setup""" + build_py = distribution.get_command_obj('build_py') + # distribution.package_data = find_package_data() + # re-init build_py options which load package_data + build_py.finalize_options() + + +class NPM(Command): + description = 'install package.json dependencies using npm' + + user_options = [] + + node_modules = os.path.join(node_root, 'node_modules') + + targets = [ + os.path.join(here, 'pythreejs', 'static', 'extension.js'), + os.path.join(here, 'pythreejs', 'static', 'index.js') + ] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def has_npm(self): + try: + check_call(['npm', '--version']) + return True + except: + return False + + def should_run_npm_install(self): + package_json = os.path.join(node_root, 'package.json') + node_modules_exists = os.path.exists(self.node_modules) + return self.has_npm() + + def run(self): + has_npm = self.has_npm() + if not has_npm: + log.error("`npm` unavailable. If you're running this command using sudo, make sure `npm` is available to sudo") + + env = os.environ.copy() + env['PATH'] = npm_path + + if self.should_run_npm_install(): + log.info("Installing build dependencies with npm. This may take a while...") + check_call(['npm', 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr) + os.utime(self.node_modules, None) + + for t in self.targets: + if not os.path.exists(t): + msg = 'Missing file: %s' % t + if not has_npm: + msg += '\nnpm is required to build a development version of widgetsnbextension' + raise ValueError(msg) + + # update package data in case this created new files + update_package_data(self.distribution) + +version_ns = {} +with open(os.path.join(here, 'pythreejs', '_version.py')) as f: + exec(f.read(), {}, version_ns) + +setup_args = { + 'name': 'pythreejs', + 'version': version_ns['__version__'], + 'description': 'Interactive 3d graphics for the Jupyter notebook, using Three.js from Jupyter interactive widgets.', + 'long_description': LONG_DESCRIPTION, + 'License': 'BSD', + 'include_package_data': True, + 'data_files': [ + ('share/jupyter/nbextensions/jupyter-threejs', [ + 'pythreejs/static/extension.js', + 'pythreejs/static/index.js', + 'pythreejs/static/index.js.map', + ]), + ('share/jupyter/labextensions/jupyter-threejs', [ + 'pythreejs/staticlab/jupyter-threejs.bundle.js', + 'pythreejs/staticlab/jupyter-threejs.bundle.js.manifest', + ]), + ], + 'install_requires': ['ipywidgets>=6.0.0'], + 'packages': find_packages(), + 'zip_safe': False, + 'cmdclass': { + 'build_py': js_prerelease(build_py), + 'egg_info': js_prerelease(egg_info), + 'sdist': js_prerelease(sdist, strict=True), + 'jsdeps': NPM, + }, + 'author': 'PyThreejs Development Team', + 'author_email': 'jason@jasongrout.org', + 'url': 'https://github.com/jovyan/pythreejs', + 'keywords': ['ipython', 'jupyter', 'widgets', 'webgl', 'graphics', '3d'], + 'classifiers': [ + 'Development Status :: 4 - Beta', + 'Intended Audience :: Developers', + 'Intended Audience :: Science/Research', + 'Topic :: Multimedia :: Graphics', + 'License :: OSI Approved :: BSD License', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + ], +} + +setup(**setup_args) diff --git a/pool/shard006/Python/0057871_test_existing_network.py b/pool/shard006/Python/0057871_test_existing_network.py new file mode 100644 index 0000000000000000000000000000000000000000..d63e9f2d62e9b317beb08faa339ce096029ab7ed --- /dev/null +++ b/pool/shard006/Python/0057871_test_existing_network.py @@ -0,0 +1,83 @@ +# 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 mock + +from rally.plugins.openstack.context.network import existing_network +from tests.unit import test + +CTX = "rally.plugins.openstack.context.network" + + +class ExistingNetworkTestCase(test.TestCase): + + def setUp(self): + super(ExistingNetworkTestCase, self).setUp() + + self.config = mock.MagicMock() + self.context = test.get_test_context() + self.context.update({ + "users": [ + {"id": 1, + "tenant_id": "tenant1", + "endpoint": mock.Mock()}, + {"id": 2, + "tenant_id": "tenant2", + "endpoint": mock.Mock()}, + ], + "tenants": { + "tenant1": {}, + "tenant2": {}, + }, + "config": { + "existing_network": self.config + }, + }) + + @mock.patch("rally.osclients.Clients") + @mock.patch("rally.plugins.openstack.wrappers.network.wrap") + def test_setup(self, mock_network_wrap, mock_clients): + networks = [mock.Mock(), mock.Mock(), mock.Mock()] + net_wrappers = { + "tenant1": mock.Mock( + **{"list_networks.return_value": networks[0:2]}), + "tenant2": mock.Mock( + **{"list_networks.return_value": networks[2:]}) + } + mock_network_wrap.side_effect = [net_wrappers["tenant1"], + net_wrappers["tenant2"]] + + existing_network.ExistingNetwork(self.context).setup() + + mock_clients.assert_has_calls([ + mock.call(u["endpoint"]) for u in self.context["users"]]) + mock_network_wrap.assert_has_calls([ + mock.call(mock_clients.return_value, self.context["task"], + config=self.config), + mock.call(mock_clients.return_value, self.context["task"], + config=self.config)]) + for net_wrapper in net_wrappers.values(): + net_wrapper.list_networks.assert_called_once_with() + + self.assertDictEqual( + self.context["tenants"], + { + "tenant1": {"networks": networks[0:2]}, + "tenant2": {"networks": networks[2:]}, + } + ) + + def test_cleanup(self): + # NOTE(stpierre): Test that cleanup is not abstract + existing_network.ExistingNetwork({"task": mock.MagicMock()}).cleanup() diff --git a/pool/shard006/Python/0057874_users.py b/pool/shard006/Python/0057874_users.py new file mode 100644 index 0000000000000000000000000000000000000000..e42da5674a732086032154a7e8649002fa45b775 --- /dev/null +++ b/pool/shard006/Python/0057874_users.py @@ -0,0 +1,114 @@ +# project/api/users.py + + +from flask import Blueprint, jsonify, request, make_response +from sqlalchemy import exc + +from project.api.utils import authenticate, is_admin +from project.api.models import User +from project import db + + +users_blueprint = Blueprint('users', __name__) + + +@users_blueprint.route('/ping', methods=['GET']) +def ping_pong(): + return jsonify({ + 'status': 'success', + 'message': 'pong!' + }) + + +@users_blueprint.route('/users', methods=['POST']) +@authenticate +def add_user(resp): + if not is_admin(resp): + response_object = { + 'status': 'error', + 'message': 'You do not have permission to do that.' + } + return make_response(jsonify(response_object)), 401 + post_data = request.get_json() + if not post_data: + response_object = { + 'status': 'fail', + 'message': 'Invalid payload.' + } + return make_response(jsonify(response_object)), 400 + username = post_data.get('username') + email = post_data.get('email') + password = post_data.get('password') + try: + user = User.query.filter_by(email=email).first() + if not user: + db.session.add(User( + username=username, + email=email, + password=password)) + db.session.commit() + response_object = { + 'status': 'success', + 'message': f'{email} was added!' + } + return make_response(jsonify(response_object)), 201 + else: + response_object = { + 'status': 'fail', + 'message': 'Sorry. That email already exists.' + } + return make_response(jsonify(response_object)), 400 + except (exc.IntegrityError, ValueError) as e: + db.session().rollback() + response_object = { + 'status': 'fail', + 'message': 'Invalid payload.' + } + return make_response(jsonify(response_object)), 400 + + +@users_blueprint.route('/users/', methods=['GET']) +def get_single_user(user_id): + """Get single user details""" + response_object = { + 'status': 'fail', + 'message': 'User does not exist' + } + try: + user = User.query.filter_by(id=int(user_id)).first() + if not user: + return make_response(jsonify(response_object)), 404 + else: + response_object = { + 'status': 'success', + 'data': { + 'username': user.username, + 'email': user.email, + 'created_at': user.created_at + } + } + return make_response(jsonify(response_object)), 200 + except ValueError: + return make_response(jsonify(response_object)), 404 + + +@users_blueprint.route('/users', methods=['GET']) +def get_all_users(): + """Get all users""" + users = User.query.order_by(User.created_at.desc()).all() + users_list = [] + for user in users: + user_object = { + 'id': user.id, + 'username': user.username, + 'email': user.email, + 'created_at': user.created_at + } + users_list.append(user_object) + response_object = { + 'status': 'success', + 'data': { + 'users': users_list + } + } + return make_response(jsonify(response_object)), 200 diff --git a/pool/shard006/Python/0057876_heatmap.py b/pool/shard006/Python/0057876_heatmap.py new file mode 100644 index 0000000000000000000000000000000000000000..d85a815506b1b20d43a2c53faa51e27b0c7d4711 --- /dev/null +++ b/pool/shard006/Python/0057876_heatmap.py @@ -0,0 +1,85 @@ +import plotly.plotly as py +import plotly.graph_objs as go +from options_csv import OUTPUT_FILENAME_PREFIX_FORMAT +import re +import os +import pandas as pd + +def build_heatmap(openInt_df): + trace = go.Heatmap(z=openInt_df.fillna(0).as_matrix(), + x=openInt_df.columns, + y=openInt_df.index) + data=[trace] + layout = go.Layout( + zaxis=dict( + type='log', + autorange=True + ) + ) + fig = go.Figure(data=data, layout=layout) + py.plot(fig, filename='expiration-heatmap') + +def build_colorscale(openInt_df): + data = [{ + 'x': openInt_df.columns, + 'y': openInt_df.index, + 'z': openInt_df.fillna(0).as_matrix(), + 'type': 'heatmap', + 'colorscale': [ + # [0, 'rgb(250, 250, 250)'], #0 + # [1./10000, 'rgb(200, 200, 200)'], #10 + # [1./1000, 'rgb(150, 150, 150)'], #100 + # [1./100, 'rgb(100, 100, 100)'], #1000 + # [1./10, 'rgb(50, 50, 50)'], #10000 + # [1., 'rgb(0, 0, 0)'], #100000 + [0, 'rgb(250, 250, 250)'], #0 + [1./16.0, 'rgb(200, 200, 200)'], #10 + [1./8.0, 'rgb(150, 150, 150)'], #100 + [1./4.0, 'rgb(100, 100, 100)'], #1000 + [1./2.0, 'rgb(50, 50, 50)'], #10000 + [1., 'rgb(0, 0, 0)'], #100000 + ], + 'colorbar': { + 'tick0': 0, + 'tickmode': 'array', + 'tickvals': [0, 1000, 10000, 100000] + } + }] + + layout = {'title': 'Log Colorscale'} + + fig = {'data': data, 'layout': layout} + + py.plot(fig, filename='expiration-heatmap') + +def get_combined_options_data(csv_date, symbol, indir): + expected_prefix = OUTPUT_FILENAME_PREFIX_FORMAT.format(date=csv_date, ticker=symbol) + options_tables = {} + for root, dirs, files in os.walk(indir): + for file in files: + if file.startswith(str(csv_date)) and file.endswith(".csv"): + expiration_with_ext = file.split("_")[-1] + expiration = expiration_with_ext.split(".")[0][3:] + filename = os.path.join(root, file) + options_table = pd.DataFrame.from_csv(filename) + options_tables[expiration] = options_table + return pd.Panel(options_tables) + + +if __name__ == "__main__": + import argparse + import datetime + + parser = argparse.ArgumentParser(description="Makes a heatmap from a sequence of expirations") + parser.add_argument("--symbol", default="spx", help="Symbol in CSV files") + parser.add_argument("--indir", default=os.getcwd(), help="Directory to look for CSV files") + args = parser.parse_args() + # TODO: Add date selection (just use today for now...) + args.csv_date = datetime.date.today() + + options_panel = get_combined_options_data(args.csv_date, args.symbol, args.indir) + print(options_panel) + call_openInt = options_panel.minor_xs('call_Open Int.') + print(call_openInt) + build_colorscale(call_openInt) + diff --git a/pool/shard006/Python/0057878_FileBot.py b/pool/shard006/Python/0057878_FileBot.py new file mode 100644 index 0000000000000000000000000000000000000000..2c624ba3be3cd25c02a708450e6993b29f384d0d --- /dev/null +++ b/pool/shard006/Python/0057878_FileBot.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +__author__ = 'Chris Hamilton' +__version__ = '1.2' + +import os +import subprocess +import sys + +############################################################################## +### NZBGET POST-PROCESSING SCRIPT ### + +# FileBot. +# +# This script is a front-end wrapper for FileBot and the Automated Media Center script. +# +# Author: Chris Hamilton (clhamilton@me.com). +# License: GPLv3 (http://www.gnu.org/licenses/gpl.html). +# Version: 1.2. +# +# FileBot - http://www.filebot.net. +# Automated Media Center script - http://www.filebot.net/forums/viewtopic.php?t=215. +# Format Expressions - http://www.filebot.net/naming.html. +# Command Line Interface - http://www.filebot.net/cli.html. +# +# Subtitles are provided by OpenSubtitles.org. An OpenSubtitles.org account is required for this feature to +# function. See http://www.opensubtitles.org/en/newuser to register for an account. Once registered, run "filebot +# -script fn:configure" from a command prompt and follow the instructions. +# +# NOTE: This script requires Python 2.x. +# +############################################################################## +### OPTIONS + +# FileBot Path. +# Path to FileBot run script. +#FileBot=/usr/local/bin/filebot + +# Anime Format. +# Format expression for Anime. +#AnimeFormat={plex} + +# Movie Format. +# Format expression for Movies. +#MovieFormat={plex} + +# Music Format. +# Format expression for Music. +#MusicFormat={plex} + +# Series Format. +# Format expression for Series or TV Shows. +#SeriesFormat={plex} + +# Action (copy, hardlink, keeplink, move, reflink, symlink, test). +# Rename action. +#Action=move + +# Conflict Resolution (auto, skip). +# This option determines how FileBot will resolve a conflict between existing media and new media that shares the same +# file name. Choose "auto" to automatically overwrite existing media if new media is better. Choose "skip" to ignore +# new media if existing media is downloaded again. +#Conflict=auto + +# Output Path. +# Output path for rename action. +#Output=${DestDir} + +# Exclude List. +# Keep a list of previously processed media to be ignored in future runs. +#ExcludeList=${MainDir}/amc.txt + +# Minimum File Size. +# Only process media files larger than the given number (in bytes). +#MinFileSize=50000000 + +# Minimum Video Length. +# Only process videos longer than the given number (in milliseconds). +#MinLengthMS=60000 + +# Subtitle Languages. +# ISO 639-1 (two-letter) language codes for subtitles. Use a comma (',') separate languages (e.g. en, de, fr, +# es). See http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes for the list of ISO 639-1 language codes. +#Subtitles= + +# Pushover Key. +# Send notifications using Pushover. Use a colon (':') to separate the user key and the optional, but recommended, API +# key. See http://pushover.net/apps/clone/FileBot. +#PushoverKey= + +# Clean (yes, no). +# Automatically remove empty folders and clutter files that may be left behind after moving the media, or temporary +# extracted files after copying. +#Clean=yes + +# Log (all, fine, info, warning). +# Level of detail to log. +#Log=info + +# Log File. +# Path to log file. +#LogFile=${MainDir}/filebot.log + +# FileBot Options +# FileBot Options +#FileBotOptions= + +### NZBGET POST-PROCESSING SCRIPT ### +############################################################################## + +POSTPROCESS_SUCCESS = 93 +POSTPROCESS_ERROR = 94 +POSTPROCESS_NONE = 95 + +REQUIRED_OPTIONS = [ + 'NZBPO_FILEBOT', + 'NZBPO_OUTPUT' +] + + +def main(): + # NZBGet Parameters + nzbpp_category = os.getenv('NZBPP_CATEGORY') + nzbpp_directory = os.getenv('NZBPP_DIRECTORY') + nzbpp_totalstatus = os.getenv('NZBPP_TOTALSTATUS') + nzbpp_nzbname = os.getenv('NZBPP_NZBNAME') + for item in REQUIRED_OPTIONS: + if item not in os.environ: + print('[ERROR] Option {0} is missing from configuration file'.format(item[6:])) + sys.exit(POSTPROCESS_ERROR) + # User Parameters + nzbpo_action = os.getenv('NZBPO_ACTION') + nzbpo_animeformat = os.getenv('NZBPO_ANIMEFORMAT', '{plex}') + nzbpo_clean = os.getenv('NZBPO_CLEAN', 'no') == 'yes' + nzbpo_conflict = os.getenv('NZBPO_CONFLICT') + nzbpo_excludelist = os.getenv('NZBPO_EXCLUDELIST') + nzbpo_filebot = os.getenv('NZBPO_FILEBOT') + nzbpo_filebotoptions = os.getenv('NZBPO_FILEBOTOPTIONS') + nzbpo_log = os.getenv('NZBPO_LOG') + nzbpo_logfile = os.getenv('NZBPO_LOGFILE') + nzbpo_minfilesize = os.getenv('NZBPO_MINFILESIZE') + nzbpo_minlengthms = os.getenv('NZBPO_MINLENGTHMS') + nzbpo_movieformat = os.getenv('NZBPO_MOVIEFORMAT', '{plex}') + nzbpo_musicformat = os.getenv('NZBPO_MUSICFORMAT', '{plex}') + nzbpo_output = os.path.realpath(os.getenv('NZBPO_OUTPUT')) + nzbpo_pushoverkey = os.getenv('NZBPO_PUSHOVERKEY') + nzbpo_seriesformat = os.getenv('NZBPO_SERIESFORMAT', '{plex}') + nzbpo_subtitles = os.getenv('NZBPO_SUBTITLES') + if nzbpp_totalstatus != 'SUCCESS': + sys.exit(POSTPROCESS_NONE) + if not os.path.exists(nzbpo_output): + try: + os.mkdir(nzbpo_output) + except OSError as e: + print('[ERROR] {0}'.format(e)) + sys.exit(POSTPROCESS_ERROR) + os.environ['FILEBOT_OPTS'] = nzbpo_filebotoptions + args = [ + nzbpo_filebot, + '-no-index', + '-no-xattr', + '-non-strict', + '-script', 'fn:amc', + '--action', nzbpo_action, + '--conflict', nzbpo_conflict, + '--def', 'clean={0}'.format('y' if nzbpo_clean else 'n'), + '--def', 'excludeList={0}'.format(nzbpo_excludelist), + '--def', 'animeFormat={0}'.format(nzbpo_animeformat), + '--def', 'movieFormat={0}'.format(nzbpo_movieformat), + '--def', 'music=y', + '--def', 'musicFormat={0}'.format(nzbpo_musicformat), + '--def', 'seriesFormat={0}'.format(nzbpo_seriesformat), + '--def', 'skipExtract=y', + '--def', 'ut_dir={0}'.format(nzbpp_directory), + '--def', 'ut_label={0}'.format(nzbpp_category), + '--def', 'ut_kind=multi', + '--def', 'ut_title={0}'.format(nzbpp_nzbname), + '--log', nzbpo_log, + '--output', nzbpo_output + ] + if nzbpo_minfilesize: + args += ['--def', 'minFileSize={0}'.format(nzbpo_minfilesize)] + if nzbpo_minlengthms: + args += ['--def', 'minLengthMS={0}'.format(nzbpo_minlengthms)] + if nzbpo_logfile: + args += ['--log-file', nzbpo_logfile] + if nzbpo_pushoverkey: + args += ['--def', 'pushover={0}'.format(nzbpo_pushoverkey.replace(' ', ''))] + if nzbpo_subtitles: + args += ['--def', 'subtitles={0}'.format(nzbpo_subtitles.replace(' ', ''))] + if nzbpo_log in ('all', 'fine'): + print('[INFO] FILEBOT_OPTS = {0}'.format(nzbpo_filebotoptions)) + print('[INFO] {0}'.format(args)) + try: + with subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, text=True) as process: + for line in process.stdout: + print('[INFO] {0}'.format(line), end='') + except FileNotFoundError as e: + print('[INFO] {0}'.format(e)) + sys.exit(POSTPROCESS_ERROR) + sys.exit(POSTPROCESS_SUCCESS) + + +if __name__ == '__main__': + main() diff --git a/pool/shard006/Python/0057881_ksample.py b/pool/shard006/Python/0057881_ksample.py new file mode 100644 index 0000000000000000000000000000000000000000..560773f6c9c112e882266e6441eb8052abe73036 --- /dev/null +++ b/pool/shard006/Python/0057881_ksample.py @@ -0,0 +1,250 @@ +""" +K-sample permutation tests. +""" + + +import numpy as np +from scipy.optimize import brentq, fsolve +from scipy.stats import ttest_ind, ttest_1samp + +from .utils import get_prng, permute, permute_within_groups + + +def k_sample(x, group, reps=10**5, stat='one-way anova', + keep_dist=False, seed=None, plus1=True): + r""" + k-sample permutation test for equality of more than 2 means, + with p-value estimated by simulated random sampling with + reps replications. + + Tests the hypothesis that groupings are a random partition of x + against the alternative that at least one group comes from a + population with mean different from the rest + + If ``keep_dist``, return the distribution of values of the test statistic; + otherwise, return only the number of permutations for which the value of + the test statistic and p-value. + + Parameters + ---------- + x : array-like + Sample values + group : array-like + Group labels for each observation + reps : int + number of repetitions + stat : {'one-way anova'} + The test statistic. + + (a) If stat == 'one-way anova', use the sum of squared + distances between the group means and the overall mean + weighted by group size. + $\sum_{k=1}^K n_k(\overline{X_k} - \overline{X})^2$ + keep_dist : bool + flag for whether to store and return the array of values + of the irr test statistic + seed : RandomState instance or {None, int, RandomState instance} + If None, the pseudorandom number generator is the RandomState + instance used by `np.random`; + If int, seed is the seed used by the random number generator; + If RandomState instance, seed is the pseudorandom number generator + plus1 : bool + flag for whether to add 1 to the numerator and denominator of the + p-value based on the empirical permutation distribution. + Default is True. + + Returns + ------- + float + the estimated p-value + float + the test statistic + list + The distribution of test statistics. + These values are only returned if `keep_dist` == True + """ + + prng = get_prng(seed) + + # If stat is callable, use it as the test function. Otherwise, look in the + # dictionary + stats = { + "one-way anova" : one_way_anova + } + if callable(stat): + tst_fun = stat + else: + tst_fun = stats[stat] + + xbar = np.mean(x) + observed_tst = tst_fun(x, group, xbar) + + if keep_dist: + dist = np.empty(reps) + for i in range(reps): + group_perm = permute(group, prng) + dist[i] = tst_fun(x, group_perm, xbar) + pvalue = (plus1 + np.sum(dist >= observed_tst))/(plus1 + reps) + return pvalue, observed_tst, dist + else: + hits = 0 + for i in range(reps): + group_perm = permute(group, prng) + tst = tst_fun(x, group_perm, xbar) + if tst >= observed_tst: + hits += 1 + return (plus1 + hits)/(plus1 + reps), observed_tst + + +def one_way_anova(x, group, overall_mean): + r""" + Test statistic for one-way ANOVA + + Parameters + ---------- + x : array-like + Sample values + group : array-like + Group labels for each observation + overall_mean : float + mean of x + + Returns + ------- + float + the one-way ANOVA statistic + $\sum_{k=1}^K n_k(\overline{X_k} - \overline{X})^2$ + where $k$ indexes the groups + """ + x = np.array(x) + tst = 0 + for k in np.unique(group): + group_k = x[group == k] + group_mean = np.mean(group_k) + nk = len(group_k) + tst += (group_mean - overall_mean)**2 * nk + return tst + + +def bivariate_k_sample(x, group1, group2, reps=10**5, stat='two-way anova', + keep_dist=False, seed=None, plus1=True): + r""" + k-sample permutation test for equality of more than 2 means, + with p-value estimated by simulated random sampling with + reps replications. + + Tests the hypothesis that within grouping 1, grouping 2 is + a random partition of x against the alternative that at + least one group 2 comes from a population with mean different from the rest + + If ``keep_dist``, return the distribution of values of the test statistic; + otherwise, return only the number of permutations for which the value of + the test statistic and p-value. + + Parameters + ---------- + x : array-like + Sample values + group1 : array-like + Fixed group labels for each observation + group2 : array-like + Group labels that, under the null, are exchangeable for each + level of group1 + reps : int + number of repetitions + stat : {'two-way anova'} + The test statistic. +; + (a) If stat == 'two-way anova', use a simpler statistic that + is permutationally equivalent to the F statistic: + $SSB/(SST - SSB).$ + $SSB$ is the sum of squared deviations from the + overall mean for the group 2 means and $SST$ is + the sum of squared deviations of all observations + keep_dist : bool + flag for whether to store and return the array of values + of the irr test statistic + seed : RandomState instance or {None, int, RandomState instance} + If None, the pseudorandom number generator is the RandomState + instance used by `np.random`; + If int, seed is the seed used by the random number generator; + If RandomState instance, seed is the pseudorandom number generator + plus1 : bool + flag for whether to add 1 to the numerator and denominator of the + p-value based on the empirical permutation distribution. + Default is True. + + Returns + ------- + float + the estimated p-value + float + the test statistic + list + The distribution of test statistics. + These values are only returned if `keep_dist` == True + """ + + prng = get_prng(seed) + + # If stat is callable, use it as the test function. Otherwise, look in the + # dictionary + stats = { + "two-way anova" : two_way_anova + } + if callable(stat): + tst_fun = stat + else: + tst_fun = stats[stat] + + xbar = np.mean(x) + observed_tst = tst_fun(x, group1, group2, xbar) + + if keep_dist: + dist = np.empty(reps) + for i in range(reps): + group2_perm = permute_within_groups(group2, group1, prng) + dist[i] = tst_fun(x, group1, group2_perm, xbar) + pvalue = (plus1 + np.sum(dist >= observed_tst))/(plus1 + reps) + return pvalue, observed_tst, dist + else: + hits = 0 + for i in range(reps): + group2_perm = permute_within_groups(group2, group1, prng) + tst = tst_fun(x, group1, group2_perm, xbar) + if tst >= observed_tst: + hits += 1 + return (plus1 + hits)/(plus1 + reps), observed_tst + + +def two_way_anova(x, group1, group2, overall_mean): + """ + Test statistic for two-way ANOVA. The test statistic + is permutationally equivalent to the F statistic. + + Parameters + ---------- + x : array-like + Sample values + group1 : array-like + Fixed group labels for each observation + group2 : array-like + Group labels that, under the null, are exchangeable for each + level of group1 + overall_mean : float + mean of x + + Returns + ------- + float + the statistic $SSB/(SST - SSB),$ where + $SSB$ is the sum of squared deviations from the + overall mean for the group 2 means and $SST$ is + the sum of squared deviations of all observations + """ + sst = np.sum((x - overall_mean)**2) + ss2 = 0 + for g in np.unique(group2): + xx = x[group2 == g] + ss2 += (np.mean(xx) - overall_mean)**2 + return ss2/(sst - ss2) diff --git a/pool/shard006/Python/0057882_Databases.py b/pool/shard006/Python/0057882_Databases.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2c73e034c876fa108b73791439f00efc4f544d --- /dev/null +++ b/pool/shard006/Python/0057882_Databases.py @@ -0,0 +1,221 @@ +#import os +#os.environ['DYLD_LIBRARY_PATH'] = '/Library/PostgreSQL/9.5/lib' +import psycopg2 +import time +import itertools + +# Dictionary of database connections. Key is the database name (only within python relevant). Value is List of: [host, user, password, database, port] +databaseSetups = { + +} + + +class Database: + + def __init__(self, setup): + ''' + @param setup: string. Database Setup. Must match a key from the databaseSetups dictionary (see above) + Creates an connection to database + ''' + self.setup = setup + self.db = self._getConnection() + + def _getConnection(self): + ''' + Returns database connection. Function checks if database connection is still alive and if this is not the case it automatically reconnects to database + @return: MySQLdb connection object + ''' + try: + # check if database connection is still alive + db = self.db + cursor = db.cursor() + cursor.execute("SELECT VERSION()") + results = cursor.fetchone() + + # if result is not empty connection is alive + if results: + return db + # create new connection + else: + connectionDetails = databaseSetups[self.setup] + self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4]) + return self.db + + except: + # if an exception occurs during checking if database connection is still alive create a new connection; if it's not possible to connect to Datbase Server wait 120 sec and try to connect again + reConnect = True + while reConnect is True: + try: + connectionDetails = databaseSetups[self.setup] + self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4]) + reConnect = False + except: + time.sleep(120) + return self.db + + def closeConnection(self): + ''' + @summary: Closes connection to database + @author: JScelle + @version: 10.06.2013 + ''' + try: + self.db.close() + except: + # if closing of connection fails ignore it + pass + + def getValuesFromTable(self, sqlQueryStatement): + ''' + gets records from table + @param sqlQueryStatement: String, sql query statement e.g. "SELECT * FROM employee WHERE country = 'DE'" + @return: tuple of tuples + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not get database connection. ", str(exc.args)) + return ((),) + + #excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + # Execute the SQL command + cursor.execute(sqlQueryStatement) + # Fetch all the rows in a list of lists. + results = cursor.fetchall() + db.commit() + return results + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not execute query. ", str(exc.args)) + return ((),) + + def runQuery(self, sqlStatement): + ''' + Executes any sql statement. For getting data from the database, please use the getValuesFromTable-method + @param sqlStatement: string. any sql statement e.g. Update, Delete + @return: Returns True if everything went good. + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not get database connection. ", str(exc.args)) + return False + + #excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + # Execute the SQL command + cursor.execute(sqlStatement) + # Commit your changes in the Settings.database + db.commit() + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not execute query. ", str(exc.args)) + return False + + def runMultipleQueries(self, sqlStatements): + """ + Executes multiple SQL-statements as one transaction + @param sqlStatements: List of strings. Each String is one SQL-statement + @return: Returns True if everything went good. + """ + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: Could not get database connection. ", str(exc.args)) + return False + + # excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + for sqlStatement in sqlStatements: + # Execute the SQL command + cursor.execute(sqlStatement) + # Commit your changes in the Settings.database + db.commit() + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: One of the queries could not be executed. ", str(exc.args)) + return False + + + def insertValuesIntoTable(self, tableName, fieldList, valueList): + """ + calls _executeInsertValuesIntoTable which inserts values into table + @param tableName: String, name of table + @param fieldList: List of string, list of field names e.g ,["firstName", "lastName"] + @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]] + @return: Returns True if everything went good. + """ + try: + #define INSERT INTO part of sql query + insertIntoSqlPart = "INSERT INTO " + tableName + " (" + ",".join(fieldList) + ") VALUES" + #define ON DUPLICATE KEY part of sql query + onDuplicateKeyPart = " ON DUPLICATE KEY UPDATE " + for field in fieldList: + #replace old values with new values + onDuplicateKeyPart += str(field) + " = VALUES(" + str(field) + "), " + onDuplicateKeyPart = onDuplicateKeyPart[0:(len(onDuplicateKeyPart) - 2)] + + return self._executeInsertValuesIntoTable(fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart) + + except Exception as exc: + print("EXCEPTION: Module: Database, Function: insertValuesIntoTable, Error: Error when building the query frame. ", str(exc.args)) + return False + + + def _executeInsertValuesIntoTable(self, fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart): + ''' + inserts values into table + @param fieldList: List, list of field names e.g ,["firstName", "lastName"] + @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]] + @return: Returns True if everything went good. + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not get database connection. ", str(exc.args)) + return False + + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + + #Insert data + #divide valueList into chunks to avoid that too big packets are send to sql server + maxPackets = 5000 + for i in range(0, len(valueList), maxPackets): + chunk = valueList[i:i + maxPackets] + #define data part of sql query (string consisting of "%s" for each field for each row) + dataSqlPart = ",".join(["(" + ",".join(["%s"] * len(fieldList)) + ")"] * len(chunk)) + #put sql parts together + sql = insertIntoSqlPart + dataSqlPart + onDuplicateKeyPart + #flatten data list + valueListChunk = tuple(itertools.chain(*chunk)) + #Insert values into DB + cursor.execute(sql, valueListChunk) + + # Commit your changes in the Settings.database + db.commit() + + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not insert values. ", str(exc.args)) + return False + diff --git a/pool/shard006/Python/0057887_swarp.py b/pool/shard006/Python/0057887_swarp.py new file mode 100644 index 0000000000000000000000000000000000000000..99773e3afd0a1c153b4c680ecde907834b8c6dc5 --- /dev/null +++ b/pool/shard006/Python/0057887_swarp.py @@ -0,0 +1,128 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Jul 27 16:39:59 2017 + +@author: asadm2 +""" +### DESCRIPTION +#This script uses swarp to combine images taken using the same filter. Image +#data is updated, zeropoint is scaled to 30, units are all set to counts/s. +#The percentage of the coadd that's blank i.e. pixel value = 0 is calculated. + +from __future__ import division, print_function, absolute_import +from astropy.io import fits +import pandas as pd +import numpy as np +import subprocess +import imp +import os + +#Importing modules that are used in this script +foo = imp.load_source('ECO_funcs', '../mods_swarp/ECO_funcs.py') + +### Paths +path_to_raw = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'\ +'data/raw/' +path_to_interim = '/fs1/masad/Research/Repositories/ECO_Globular_Clusters/'\ +'data/interim/' + +#If re-running script then these files have to be removed since +#they are being opened in 'append' mode in ECO_funcs.py +if os.path.isfile(path_to_interim + 'Error_swarp.txt'): + os.remove(path_to_interim + 'Error_swarp.txt') +if os.path.isfile(path_to_interim + 'percent_blankv2.txt'): + os.remove(path_to_interim + 'percent_blankv2.txt') + +#Formatted ECO catalog with filters and new_filename column and list of +#good ECO objects +ECOnew = path_to_interim + 'ECO_formatted.txt' +goodObj = path_to_interim + 'goodObjv2.txt' + +#Using the make_dict function to return a dictionary whose keys are ECOID and +#filter name and whose values are filenames, return the list of sorted keys, +#and the formatted ECO catalog +ECO_dict,ECO_keys,ECOcat = foo.make_dict(ECOnew,goodObj) + +for index,key in enumerate(ECO_keys): + print('Key {0}/{1}'.format(index+1,len(ECO_keys))) + obj = key[0] + filter_i = key[1] + print('Object: {0} and filter: {1}'.format(obj,filter_i)) + dir_path = os.getcwd() + #Since this file is in src/ and we need to access the images we have to + #move to the data/raw folder the first time this code runs + if os.path.basename(dir_path) == 'main': + os.chdir(path_to_raw + obj) + #After the first time all that has to be done is to move out of the + #interim ECO object dir and into the raw ECO object dir + elif os.path.basename(dir_path) != obj: + os.chdir(path_to_raw + obj) + #Using the ECOID,filter key to acess the values in the new_filename column + #i.e. get a list of the images associated with this key pair + print("Getting images from catalog") + imgs_from_cat = ECO_dict.get_group(key)['new_filename'].values + + #Images from prelim_checks_3 that passed the "object-in-image" check + #as well as the non-zero pixel value check + print("Getting images from text file") + goodimagesfile = obj+'_goodimages.txt' + goodimages = pd.read_csv(goodimagesfile,header=None,names=['filenames']) + imgs_from_txt = goodimages.values + + #Common images between full list from catalog and good imaging left + print("Common images are") + imgs = [] + for img in imgs_from_cat: + if img in imgs_from_txt: + print(img) + img = img + '.fits' + imgs.append(img) + + #Using the update_header function to output the name of the text file + #that contains the names of the new versions of the fits images being + #input into the function + img_list_txt = foo.update_header(imgs,obj,filter_i) + + #To check for case where all images were in Except clause of update_header + #and run swarp even for single images + if len(imgs) >= 1 and img_list_txt != 'error': + ra = np.unique(ECOcat.RA.loc[ECOcat.ECOID==obj])[0] + dec = np.unique(ECOcat.DEC.loc[ECOcat.ECOID==obj])[0] + + #Running swarp with parameters. The only ones that change are the list + #of images, the RA and DEC of the object, the object name and the + #filter name + print('Starting to swarp') + subprocess.call(['swarp','@'+img_list_txt,'-CENTER_TYPE','MANUAL', \ + '-CENTER',str(ra)+","+str(dec),'-NTHREADS','32', '-COPY_KEYWORDS', \ + 'PHOTFLAM,MAGZPT,PHOTPLAM','-FSCALASTRO_TYPE','VARIABLE',\ + '-COMBINE_BUFSIZE','10000','-MEM_MAX','1000','-VMEM_MAX','5000',\ + '-IMAGE_SIZE','3960','-PIXELSCALE_TYPE','MANUAL','-PIXEL_SCALE',\ + '0.05','-GAIN_KEYWORD','CCDGAIN','-GAIN_DEFAULT','1.0',\ + '-SUBTRACT_BACK','Y','-IMAGEOUT_NAME',\ + obj+'_'+filter_i+'_'+'coadd.fits','-WEIGHTOUT_NAME',\ + obj+'_'+filter_i+'_'+'coadd.weight.fits','-XML_NAME',\ + obj+'_'+filter_i+'_'+'swarp.xml']) + print('Finished swarping') + + coadd = fits.open(obj+'_'+filter_i+'_'+'coadd.fits') + #Open the coadd and use the percent_blank function + foo.percent_blank(coadd,obj,filter_i) + #So that you can distinguish between interim object folder and raw + #object filder + + else: + os.chdir('..') # Moving one level up when no imgs are found + + #If the length of imgs is 1 then check if the new version that + #update_header function creates exists. If it does then calculate blank + #percentage. If the length is 0 i.e. since the original ECO catalog is + #being used some ECOID, filter pairs no longer exist since they were + #eliminated in preliminary exptime and >2filter checks so for those pairs + #the files won't exist. They are ignored which is why percent_blank doesn't + #print anything to the terminal. +# else: +# filename = imgs[0]+'_test_'+filter_i+'.fits' +# if os.path.exists(filename): #avoid empty cases where files don't exist +# single_img = fits.open(filename) +# foo.percent_blank(single_img,obj,filter_i) \ No newline at end of file diff --git a/pool/shard006/Python/0057894_runners.py b/pool/shard006/Python/0057894_runners.py new file mode 100644 index 0000000000000000000000000000000000000000..4659304a1ea8f9ebd0bcbb4d257a2d6c379bc092 --- /dev/null +++ b/pool/shard006/Python/0057894_runners.py @@ -0,0 +1,72 @@ +__all__ = 'run', + +from . import coroutines +from . import events +from . import tasks + + +def run(main, *, debug=False): + """Execute the coroutine and return the result. + + This function runs the passed coroutine, taking care of + managing the asyncio event loop and finalizing asynchronous + generators. + + This function cannot be called when another asyncio event loop is + running in the same thread. + + If debug is True, the event loop will be run in debug mode. + + This function always creates a new event loop and closes it at the end. + It should be used as a main entry point for asyncio programs, and should + ideally only be called once. + + Example: + + async def main(): + await asyncio.sleep(1) + print('hello') + + asyncio.run(main()) + """ + if events._get_running_loop() is not None: + raise RuntimeError( + "asyncio.run() cannot be called from a running event loop") + + if not coroutines.iscoroutine(main): + raise ValueError("a coroutine was expected, got {!r}".format(main)) + + loop = events.new_event_loop() + try: + events.set_event_loop(loop) + loop.set_debug(debug) + return loop.run_until_complete(main) + finally: + try: + _cancel_all_tasks(loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + finally: + events.set_event_loop(None) + loop.close() + + +def _cancel_all_tasks(loop): + to_cancel = tasks.all_tasks(loop) + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete( + tasks.gather(*to_cancel, loop=loop, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler({ + 'message': 'unhandled exception during asyncio.run() shutdown', + 'exception': task.exception(), + 'task': task, + }) diff --git a/pool/shard006/Python/0057898_init__.py b/pool/shard006/Python/0057898_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..15e618e03c0d3e4878030beea994581bccc84aed --- /dev/null +++ b/pool/shard006/Python/0057898_init__.py @@ -0,0 +1,28 @@ +"""Phpsploit framework core loader. + +This pseudo module is designed to be imported (import lib) from +the phpsploit script launcher (./phpsploit). +It also can be imported from phpsploit root directory through a +python interpreter for debugging purposes. + +It loads the phpsploit core & overwrites sys.path's first element to +the current directory (./lib/), making all self contained elements +directly importable from python. + +""" +import os +import sys + +from . import utils + +BASEDIR = utils.path.truepath(sys.path[0]) + os.sep +COREDIR = os.path.join(BASEDIR, __name__) + os.sep + +# use current directory as main python path +sys.path[0] = COREDIR + +# add src/core/shnake-0.5/ to python path +shnake_path = os.path.join(COREDIR, "shnake-0.5") + os.sep +sys.path.insert(0, shnake_path) + +del sys, os, shnake_path # clean package's content diff --git a/pool/shard006/Python/0057900_mysql.py b/pool/shard006/Python/0057900_mysql.py new file mode 100644 index 0000000000000000000000000000000000000000..39db654cdfcf5d6deffdc248696266649f141b00 --- /dev/null +++ b/pool/shard006/Python/0057900_mysql.py @@ -0,0 +1,67 @@ +import MySQLdb as mdb +import os +import re +import base64 + +class MysqlEngine: + PASSWORD_LENGTH = 10 + """ + Create databases and users and manage cloning and dumping of + databases. + """ + def __init__(self, host, user, password): + self.engine_name = "mysql" + self.host = host + self.user = user + self.password = password + + def create_connection(self, database=""): + return mdb.connect(host=self.host, user=self.user, passwd=self.password, db=database) + + + def verify_site(self, site): + safe_name = re.sub(r"[^a-zA-Z]*", "", site.name).lower() + if not hasattr(site, "database"): + site.database = {} + if not "name" in site.database: + site.database["name"] = safe_name + if not "password" in site.database: + site.database["password"] = base64.urlsafe_b64encode(os.urandom(self.PASSWORD_LENGTH)) + if not "user" in site.database: + site.database["user"] = safe_name + if not "host" in site.database: + site.database["host"] = site.platform.server.hostname + self.create_database(site.database["name"]) + self.create_user(site.database["name"], site.database["password"]) + self.grant_privileges(site.database["name"], site.database["user"], site.database["host"], site.database["password"]) + + def create_database(self, name): + db = self.create_connection() + with db: + cursor = db.cursor() + if not self._database_exists(cursor, name): + cursor.execute("CREATE DATABASE IF NOT EXISTS {0}".format(name)) + + def create_user(self, name, password): + db = self.create_connection("mysql") + with db: + cursor = db.cursor() + cursor.execute("SELECT count(User) FROM user WHERE User = %s", (name)) + if cursor.fetchone() == 0: + cursor.execute("CREATE USER {0} IDENTIFIED BY '{1}'".format(name, password)) + + def grant_privileges(self, database, username, host, password): + db = self.create_connection() + with db: + cursor = db.cursor() + cursor.execute("GRANT ALL PRIVILEGES ON {0}.* TO '{1}'@'{2}' IDENTIFIED BY '{3}'".format(database, username, host, password)) + + def close_conection(self): + self.db.close() + + def _database_exists(self, cursor, database): + cursor.execute("SHOW DATABASES") + for row in cursor.fetchall(): + if row[0] == database: + return True + return False diff --git a/pool/shard006/Python/0057902_io.py b/pool/shard006/Python/0057902_io.py new file mode 100644 index 0000000000000000000000000000000000000000..fb729af5cdf27efdaeaed79b5b7ad1eae2d5c4ea --- /dev/null +++ b/pool/shard006/Python/0057902_io.py @@ -0,0 +1,34 @@ +import os + +# TODO: use biopython + + +def make_part(part): + name = part.get('name') + desc = part.get('description') + seq = part.get('sequence') + + if name is None: + return + + desc_line = ' ({})'.format(desc) if desc is not None else '' + + if not os.path.exists(name): + os.makedirs(name) + + fasta = '>{}{}\n{}'.format(name, desc_line, seq) + with open('{}/sequence.fasta'.format(name), 'w') as f: + f.write(fasta) + + +def read_part(): + with open('sequence.fasta', 'r') as f: + fasta = f.read() + line1, seq = fasta.split('\n', 1) + if ' ' in line1: + name = line1[1: line1.find(' ')] + desc = line1[line1.find('('): line1.find(')')] + else: + name = line1[1:] + desc = None + return {'name': name, 'description': desc, 'sequence': seq} diff --git a/pool/shard006/Python/0057904_master_perf_cfg.py b/pool/shard006/Python/0057904_master_perf_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..ec41bdc871b17285bf302179be52241c2f859b9e --- /dev/null +++ b/pool/shard006/Python/0057904_master_perf_cfg.py @@ -0,0 +1,44 @@ +# Copyright 2014 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. + +from master import master_config +from master.factory import annotator_factory, chromeos_factory + +from buildbot.schedulers.basic import SingleBranchScheduler as Scheduler + +def Builder(factory_obj, board): + config = '%s-telemetry' % (board,) + builder = { + 'name': config, + 'builddir': config, + 'category': '5chromiumos perf', + 'factory': chromeos_factory.ChromiteRecipeFactory( + factory_obj, 'cros/cbuildbot'), + 'gatekeeper': 'crosperf', + 'scheduler': 'chromium_src_perf', + 'notify_on_missing': True, + 'properties': { + 'cbb_config': config, + }, + } + return builder + + +def Update(_config, active_master, c): + factory_obj = annotator_factory.AnnotatorFactory( + active_master=active_master) + + builders = [ + Builder(factory_obj, 'x86-generic'), + Builder(factory_obj, 'amd64-generic'), + ] + + c['schedulers'] += [ + Scheduler(name='chromium_src_perf', + branch='master', + treeStableTimer=60, + builderNames=[b['name'] for b in builders], + ), + ] + c['builders'] += builders diff --git a/pool/shard006/Python/0057905_run_regression_tests.py b/pool/shard006/Python/0057905_run_regression_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..a21208b644ea72ee42e21bb51b9b5aeb37d87cc4 --- /dev/null +++ b/pool/shard006/Python/0057905_run_regression_tests.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python +# Runs one or more regression tests. Retries tests up to 3 times. +# +# Example usage: +# $ python run_regression_tests.py regression-tests/cartpole-es-[tf|torch].yaml +# +# When using in BAZEL (with py_test), e.g. see in ray/rllib/BUILD: +# py_test( +# name = "run_regression_tests", +# main = "tests/run_regression_tests.py", +# tags = ["learning_tests"], +# size = "medium", # 5min timeout +# srcs = ["tests/run_regression_tests.py"], +# data = glob(["tuned_examples/regression_tests/*.yaml"]), +# # Pass `BAZEL` option and the path to look for yaml regression files. +# args = ["BAZEL", "tuned_examples/regression_tests"] +# ) + +import argparse +import os +from pathlib import Path +import sys +import yaml + +import ray +from ray.tune import run_experiments +from ray.rllib import _register_all +from ray.rllib.utils.deprecation import deprecation_warning + +parser = argparse.ArgumentParser() +parser.add_argument( + "--framework", + choices=["jax", "tf2", "tf", "tfe", "torch"], + default="tf", + help="The deep learning framework to use.") +parser.add_argument( + "--yaml-dir", + type=str, + required=True, + help="The directory in which to find all yamls to test.") +parser.add_argument( + "--local-mode", + action="store_true", + help="Run ray in local mode for easier debugging.") + +# Obsoleted arg, use --framework=torch instead. +parser.add_argument( + "--torch", + action="store_true", + help="Runs all tests with PyTorch enabled.") + +if __name__ == "__main__": + args = parser.parse_args() + + # Bazel regression test mode: Get path to look for yaml files. + # Get the path or single file to use. + rllib_dir = Path(__file__).parent.parent + print("rllib dir={}".format(rllib_dir)) + + abs_yaml_path = os.path.join(rllib_dir, args.yaml_dir) + # Single file given. + if os.path.isfile(abs_yaml_path): + yaml_files = [abs_yaml_path] + # Given path/file does not exist. + elif not os.path.isdir(abs_yaml_path): + raise ValueError("yaml-dir ({}) not found!".format(args.yaml_dir)) + # Path given -> Get all yaml files in there via rglob. + else: + yaml_files = rllib_dir.rglob(args.yaml_dir + "/*.yaml") + yaml_files = sorted( + map(lambda path: str(path.absolute()), yaml_files), reverse=True) + + print("Will run the following regression tests:") + for yaml_file in yaml_files: + print("->", yaml_file) + + # Loop through all collected files. + for yaml_file in yaml_files: + experiments = yaml.load(open(yaml_file).read()) + assert len(experiments) == 1,\ + "Error, can only run a single experiment per yaml file!" + + # Add torch option to exp config. + exp = list(experiments.values())[0] + exp["config"]["framework"] = args.framework + if args.torch: + deprecation_warning(old="--torch", new="--framework=torch") + exp["config"]["framework"] = "torch" + args.framework = "torch" + + # Print out the actual config. + print("== Test config ==") + print(yaml.dump(experiments)) + + # Try running each test 3 times and make sure it reaches the given + # reward. + passed = False + for i in range(3): + try: + ray.init(num_cpus=5, local_mode=args.local_mode) + trials = run_experiments(experiments, resume=False, verbose=2) + finally: + ray.shutdown() + _register_all() + + for t in trials: + # If we have evaluation workers, use their rewards. + # This is useful for offline learning tests, where + # we evaluate against an actual environment. + check_eval = \ + exp["config"].get("evaluation_interval", None) is not None + reward_mean = \ + t.last_result["evaluation"]["episode_reward_mean"] if \ + check_eval else t.last_result["episode_reward_mean"] + + # If we are using evaluation workers, we may have + # a stopping criterion under the "evaluation/" scope. If + # not, use `episode_reward_mean`. + if check_eval: + min_reward = t.stopping_criterion.get( + "evaluation/episode_reward_mean", + t.stopping_criterion.get("episode_reward_mean")) + # Otherwise, expect `episode_reward_mean` to be set. + else: + min_reward = t.stopping_criterion["episode_reward_mean"] + + if reward_mean >= min_reward: + passed = True + break + + if passed: + print("Regression test PASSED") + break + else: + print("Regression test FAILED on attempt {}".format(i + 1)) + + if not passed: + print("Overall regression FAILED: Exiting with Error.") + sys.exit(1) diff --git a/pool/shard006/Python/0057906_views.py b/pool/shard006/Python/0057906_views.py new file mode 100644 index 0000000000000000000000000000000000000000..e7acdd032f165808a4850ca0e0cd955e4a83205c --- /dev/null +++ b/pool/shard006/Python/0057906_views.py @@ -0,0 +1,28 @@ +import logging +from django.shortcuts import render + +# Create your views here. + +logger = logging.getLogger(__name__) + + +def timetable_landing(request): + logger.info(request) + feature_list = ( + {'icon': 'img/glasses2.svg', 'description': ('Перегляд розкладу ' + 'групи (дізнайся, яка зараз пара)'), 'class': 'feature-block'}, + {'icon': 'img/edit45.svg', 'description': ('Редагування розкладу ' + '(доступне командирам груп)'), 'class': 'feature-block'}, + {'icon': 'img/school84.svg', 'description': ('Перегляд розкладу' + ' викладача'), 'class': 'feature-block'}, + {'icon': 'img/checkmark2.svg', 'description': ('Перегляд графіку ' + 'екзаменів та практики'), 'class': 'feature-block'}, + {'icon': 'img/sun127.svg', 'description': 'Канікули', + 'class': 'feature-block'}, + ) + return render(request, 'landing/promo.html', + {'feature_list': feature_list}) + + +def timetable_about(request): + return render(request, 'landing/about.html') diff --git a/pool/shard006/Python/0057907_ordenacion.py b/pool/shard006/Python/0057907_ordenacion.py new file mode 100644 index 0000000000000000000000000000000000000000..2931f457581d23bd2c313f57fd8322c9aeabc606 --- /dev/null +++ b/pool/shard006/Python/0057907_ordenacion.py @@ -0,0 +1,117 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Practicas de Desarrollo de Aplicaciones para Internet (DAI) +# Copyright (C) 2013 - Zerjillo (zerjioi@ugr.es) +# +# 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 random + + +# Ordenacion burbuja +def burbuja(lista): + for i in range(len(lista)): + for h in range(i, len(lista) - 1): + if (lista[h] > lista[h+1]): + aux = lista[h] + lista[h] = lista[h + 1] + lista[h + 1] = aux + + +# Ordenacion burbuja con posible salida antes de tiempo +def burbujaMejorada(lista): + for i in range(len(lista)): + cambio = False + for h in range(i, len(lista) - 1): + if (lista[h] > lista[h+1]): + aux = lista[h] + lista[h] = lista[h + 1] + lista[h + 1] = aux + cambio = True + + if not cambio: + return + +# Ordenacion por reemplazo +def reemplazo(lista): + for i in range(len(lista) - 1): + currentPos = i + + for h in range(i + 1, len(lista)): + if (lista[h] < lista[currentPos]): + currentPos = h + + aux = lista[i] + lista[i] = lista[currentPos] + lista[currentPos] = aux + +def mergeSort(lista): + listaTrabajo = list(lista) + + mergeSort2(lista, 0, len(lista) - 1, listaTrabajo) + + + + +def mergeSort2(lista, i1, i2, listaTrabajo): + if (i1 == i2): # Si un solo elemento, volvemos sin mas + return + + medio = (i1 + i2) / 2 + + mergeSort2(lista, i1, medio, listaTrabajo) # Ordenamos la primera mitad (llamada recursiva!) + mergeSort2(lista, medio + 1, i2, listaTrabajo) # Ordenamos la segunda mitad (llamada recursiva!) + + # Las dos mitades están cada una ordenada + + punt1 = i1 + punt2 = medio + 1 + puntB = i1 + +# Mergueamos + + while ( (punt1 <= medio) and (punt2 <= i2) ): + if (lista[punt1] < lista[punt2]): + listaTrabajo[puntB] = lista[punt1] + punt1 += 1 + else: + listaTrabajo[puntB] = lista[punt2] + punt2 += 1 + + puntB += 1 + + for i in range(punt1, medio + 1): # Terminamos de copiar los que queden en la primera mitad + listaTrabajo[puntB] = lista[i] + puntB += 1 + + for i in range(punt2, i2 + 1): # Terminamos de copiar los que queden en la segunda mitad + listaTrabajo[puntB] = lista[i] + puntB += 1 + + for i in range(i1, i2 + 1): # Copiamos el trozo en la original + lista[i] = listaTrabajo[i] + + + +# Genera una lista de numeros aleatorios +def generaListaAleatoria(): + tamanioLista = 10000; + + lista = [] + + for i in range(tamanioLista): + lista.append(random.randint(0, 10000000)); + + return lista \ No newline at end of file diff --git a/pool/shard006/Python/0057916_views.py b/pool/shard006/Python/0057916_views.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd5db44f2f530d7da06f45ee99609c2ce62d58f --- /dev/null +++ b/pool/shard006/Python/0057916_views.py @@ -0,0 +1,178 @@ +""" +This Photo Roster LTI tool was build using the HUIT TLT bootstrap_lit_django +basic lti app from +https://github.com/penzance/bootstrap_lit_django + +This tool was adaped for use by: +Matthew Coser +IT Systems Coordinator +Harvard Kennedy School +Executive Education +matthew_coser@hks.harvard.edu +617-496-0319 + +This Canvas Photo Roster Tool can be re-worked and re-distributed as you wish +please credit the above parties. + + +""" + + +from django.shortcuts import (render, redirect) +from django.views.decorators.http import require_http_methods +from django.contrib.auth.decorators import login_required +from django.core.urlresolvers import reverse +from django.conf import settings +from ims_lti_py.tool_config import ToolConfig +from django.http import HttpResponse +from canvas_sdk.methods import enrollments +from canvas_sdk.methods import courses +from canvas_sdk.methods import users +from canvas_sdk.utils import get_all_list_data +from canvas_sdk.exceptions import CanvasAPIError +from canvas_sdk import RequestContext +import logging + +logger = logging.getLogger(__name__) + + + + +SDK_CONTEXT = request_context = RequestContext(**settings.CANVAS_SDK_SETTINGS) + +TOOL_NAME = "canvasPR_app" + +@require_http_methods(['GET']) +def index(request): + """ + Show the index file + """ + return render(request, 'canvasPR_app/index.html') + +@login_required() +@require_http_methods(['POST']) +def lti_launch(request): + """ + This method is here to build the LTI_LAUNCH dictionary containing all + the LTI parameters and place it into the session. This is nessesary as we + need to access these parameters throughout the application and they are only + available the first time the application loads. + """ + if request.user.is_authenticated(): + return redirect('canvasPR_app:main') + else: + return render(request, 'canvasPR_app/error.html', {'message': 'Error: user is not authenticated!'}) + +@login_required() +@require_http_methods(['GET']) +def main(request): + + + + #get the course ID of current course + canvas_course_id = request.session['LTI_LAUNCH'].get('custom_canvas_course_id') + logger.debug('////////////////////////////////////>') + logger.debug('canvas_course_id=%s' % canvas_course_id) + logger.debug('////////////////////////////////////>') + + + #call to get course name for roster header + canvas_course_name = get_all_list_data(SDK_CONTEXT, courses.get_single_course_courses, canvas_course_id, "all_courses") + logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>') + logger.debug(canvas_course_name) + logger.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~>') + + #get a list of STUDENTS in the current course, we will use only the user_id from the list + #the 'avatar_url' is just a required option, and we will actually use the avatar_url from the profile list below + enrollmentGet = {} + try: + enrollmentGet = get_all_list_data(SDK_CONTEXT, courses.list_users_in_course_users, canvas_course_id, 'avatar_url', enrollment_type='student') + except CanvasAPIError as api_error: + logger.debug((canvas_course_id, api_error)) + + #get a list of TEACHERS in the current course. Should be automatically hidden with js in lti_view.thml, and can be toggled with a switch + faculty = {} + try: + faculty = get_all_list_data(SDK_CONTEXT, courses.list_users_in_course_users, canvas_course_id, 'avatar_url', enrollment_type='teacher') + except CanvasAPIError as api_error: + logger.debug((canvas_course_id, api_error)) + + #for each student user in the course, get their user_id + userID = [] + for d in enrollmentGet: + userIdSingle = d['id'] + userID.append(userIdSingle) + logger.debug('*********************************************>') + logger.debug('userID=%s' %userID) + logger.debug('*********************************************>') + + facultyID = [] + for d in faculty: + facultyIdSingle = d['id'] + facultyID.append(facultyIdSingle) + logger.debug('++++++++++++++++++++++++++++++++++++++++++++++++>') + logger.debug('facultyID=%s' %facultyID) + logger.debug('++++++++++++++++++++++++++++++++++++++++++++++++>') + + + #Run the user profile call for each student user_id we just got, + #and use what we need in the html + userGet = [] + for l in userID: + try: + studentFull = get_all_list_data(SDK_CONTEXT, users.get_user_profile, l) + userGet.append(studentFull) + except CanvasAPIError as api_error: + logger.debug('CanvasAPIError in get_all_list_data enrollments.list_enrollments_courses call for canvas_course_id=%s. Exception=%s:' % (canvas_course_id, api_error)) + + facultyGet = [] + for l in facultyID: + try: + facultyFull = get_all_list_data(SDK_CONTEXT, users.get_user_profile, l) + facultyGet.append(facultyFull) + except CanvasAPIError as api_error: + logger.debug('CanvasAPIError in get_all_list_data enrollments.list_enrollments_courses call for canvas_course_id=%s. Exception=%s:' % (canvas_course_id, api_error)) + + + + #dictionary definitions for the lti_view html + return render(request, 'canvasPR_app/lti_view.html', {'request': request, 'pages': enrollmentGet, 'userGet': userGet, 'facultyGet': facultyGet, 'courseName': canvas_course_name}) + + + + + + + + +@require_http_methods(['GET']) +def tool_config(request): + """ + This produces a Canvas specific XML config that can be used to + add this tool to the Canvas LMS + """ + if request.is_secure(): + host = 'https://' + request.get_host() + else: + host = 'http://' + request.get_host() + + url = host + reverse('canvasPR_app:lti_launch') + + lti_tool_config = ToolConfig( + title='Photo Roster - Test', + launch_url=url, + secure_launch_url=url, + ) + account_nav_params = { + 'enabled': 'true', + 'visibility': 'admins', + # optionally, supply a different URL for the link: + # 'url': 'http://library.harvard.edu', + 'text': 'Photo Roster - Test', + } + lti_tool_config.set_ext_param('canvas.instructure.com', 'privacy_level', 'public') + lti_tool_config.set_ext_param('canvas.instructure.com', 'course_navigation', account_nav_params) + lti_tool_config.description = 'This LTI app shows all the LTI parameters' + + resp = HttpResponse(lti_tool_config.to_xml(), content_type='text/xml', status=200) + return resp \ No newline at end of file diff --git a/pool/shard006/Python/0057919_MD_Cluster.py b/pool/shard006/Python/0057919_MD_Cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..2a4bb013b55941a50d0c5d874ba7e3869f747a42 --- /dev/null +++ b/pool/shard006/Python/0057919_MD_Cluster.py @@ -0,0 +1,91 @@ +# First a documentation string to describe the example +"""An example script demonstrating an NVT MD simulation with Asap. + +This example runs a molecular dynamics simulation on a small copper +cluster in the NVT ensemble, i.e. with constant particle number, +constant volume and constant temperature. It uses Langevin dynamics +to get the constant temperature. +""" + +# Import ASAP and relatives +from Asap import * +from Asap.Dynamics.Langevin import Langevin +from Asap.Trajectories import NetCDFTrajectory + +# Import other essential modules +from Numeric import * + +# Set up an fcc crystal of copper. +element = 29 +lattice_constant = 3.59 # Angstrom +size = (10, 10, 10) +fcc_basis = array([[0.0, 0.5, 0.5], + [0.5, 0.0, 0.5], + [0.5, 0.5, 0.0]]) +# Now make an array which looks like +# [ [0, 0, 0] +# [0, 0, 1] +# ... +# [0, 0, 9] +# [0, 1, 0] +# ... +# [9, 9, 9] ] +# +# When it is multiplied with fcc_basis it gives a small crystal with 1000 +# atoms. +# +# The array is made with a simple loop, although fancy Numeric array +# operations could do it faster (but it would be close to +# unreadable). +pos = [] +for i in range(size[0]): + for j in range(size[1]): + for k in range(size[2]): + pos.append([i,j,k]) +positions = matrixmultiply(pos, fcc_basis) * lattice_constant + +# Now the atoms are created from the positions and a sufficiently +# large unit cell. The unit cell is uncritical as there are no +# periodic boundaries, and the atoms are able to move outside the unit +# cell, so in principle it should work with the default +# 1-Angstrom-cube unit cell. + +atoms = ListOfAtoms(positions=positions, cell=[max(positions[:,0]), + max(positions[:,1]), + max(positions[:,2])]) +atoms.SetAtomicNumbers(element) + +# Now the standard EMT Calculator is attached +atoms.SetCalculator(EMT()) + +# Make an object doing Langevin dynamics at a temperature of 800 K +dyn = Langevin(atoms, dt=5*femtosecond, temperature=800*kB, friction=0.005) + +# Make a trajectory +traj = NetCDFTrajectory('MD_Cluster.nc', atoms, interval=500) +dyn.Attach(traj) + +# Write the initial configuration +traj.Update() + +# Print the energies +def printenergy(a, step=[0,]): + n = len(a) + ekin = a.GetKineticEnergy() / n + epot = a.GetPotentialEnergy() / n + print ("%4d: E_kin = %-9.5f E_pot = %-9.5f E_tot = %-9.5f T = %.1f K" % + (step[0], ekin, epot, ekin+epot, 2.0/3.0*ekin/kB)) + step[0] += 1 + +printenergy(atoms) + +# Now do the dynamics, doing 5000 timesteps, writing energies every 50 steps +for major in range(100): + dyn.Run(50) + printenergy(atoms) + +# Now increase the temperature to 2000 K and continue +dyn.SetTemperature(2000 * kB) +for major in range(100): + dyn.Run(50) + printenergy(atoms) diff --git a/pool/shard006/Python/0057920_integration_server.py b/pool/shard006/Python/0057920_integration_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b5777a2cf4c9ca98b79853b09f0ca7160044e5bc --- /dev/null +++ b/pool/shard006/Python/0057920_integration_server.py @@ -0,0 +1,169 @@ +import errno +import io +import os +import random +import re +import shutil +import subprocess +import sys +import tempfile + + +class BaseIntegrationServer(object): + protocols = ('TCP', 'HTTP') + + protocol_re = re.compile(' '.join([ + r'(?P[A-Z]+):', + r'listening on', + r'(?P
(?:[0-9]{1,3}\.){3}[0-9]{1,3}):(?P[0-9]+)', + ])) + + version_re = re.compile(' '.join([ + r'(?P[a-z]+)', + r'v(?P[0-9]+\.[0-9]+\.[0-9]+)(?:-[a-z]+)?', + r'\(built w\/(?P[a-z0-9.-]+)\)' + ])) + + def __init__(self, address='127.0.0.1'): + self.address = address + self.protocol_ports = {} + self.data_path = tempfile.mkdtemp() + self.name, self.version, self.go_version = self._parse_version() + + def _parse_version(self): + output = subprocess.check_output([self.executable, '--version']) + match = self.version_re.match(output.decode('utf-8')) + name = match.group('name') + version = tuple(int(v) for v in match.group('version').split('.')) + go_version = match.group('go_version') + return name, version, go_version + + @property + def tcp_port(self): + return self.protocol_ports['TCP'] + + @property + def tcp_address(self): + return '%s:%d' % (self.address, self.tcp_port) + + @property + def http_port(self): + return self.protocol_ports['HTTP'] + + @property + def http_address(self): + return '%s:%d' % (self.address, self.http_port) + + def _random_port(self): + if self.version < (0, 3, 5): + return random.randint(10000, 65535) + return 0 + + def _random_address(self): + return '%s:%d' % (self.address, self._random_port()) + + def _parse_protocol_ports(self): + while len(self.protocol_ports) < len(self.protocols): + line = self.child.stderr.readline() + sys.stderr.write(line) + + if not line: + raise Exception('server exited prematurely') + + if 'listening on' not in line: + continue + + match = self.protocol_re.search(line) + if not match: + raise Exception('unexpected line: %r' % line) + + protocol = match.group('protocol') + if protocol not in self.protocols: + continue + + port = int(match.group('port'), 10) + self.protocol_ports[protocol] = port + + def __enter__(self): + sys.stderr.write('running: %s\n' % ' '.join(self.cmd)) + self.child = subprocess.Popen(self.cmd, stderr=subprocess.PIPE) + if sys.version_info[0] == 3: + self.child.stderr = io.TextIOWrapper(self.child.stderr, 'utf-8') + self._parse_protocol_ports() + return self + + def __exit__(self, exc_type, exc_value, traceback): + try: + self.child.terminate() + except OSError as error: + if error.errno == errno.ESRCH: + return + raise + + while True: + line = self.child.stderr.readline() + if not line: + break + sys.stderr.write(line) + + self.child.wait() + shutil.rmtree(self.data_path) + + +class NsqdIntegrationServer(BaseIntegrationServer): + executable = 'nsqd' + + tls_cert = os.path.join(os.path.dirname(__file__), 'cert.pem') + tls_key = os.path.join(os.path.dirname(__file__), 'key.pem') + + def __init__(self, lookupd=None, **kwargs): + super(NsqdIntegrationServer, self).__init__(**kwargs) + + if self.has_https(): + self.protocols = ('TCP', 'HTTP', 'HTTPS') + + self.lookupd = lookupd + + def has_https(self): + return self.version >= (0, 2, 28) + + @property + def https_port(self): + return self.protocol_ports['HTTPS'] + + @property + def https_address(self): + return '%s:%d' % (self.address, self.https_port) + + @property + def cmd(self): + cmd = [ + self.executable, + '--broadcast-address', self.address, + '--tcp-address', self._random_address(), + '--http-address', self._random_address(), + '--data-path', self.data_path, + '--tls-cert', self.tls_cert, + '--tls-key', self.tls_key, + ] + + if self.has_https(): + cmd.extend(['--https-address', self._random_address()]) + + if self.lookupd: + cmd.extend(['--lookupd-tcp-address', self.lookupd]) + + return cmd + + +class LookupdIntegrationServer(BaseIntegrationServer): + executable = 'nsqlookupd' + + @property + def cmd(self): + return [ + self.executable, + '--broadcast-address', self.address, + '--tcp-address', self._random_address(), + '--http-address', self._random_address(), + ] diff --git a/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py b/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py new file mode 100644 index 0000000000000000000000000000000000000000..cd65c5405c29449af64beccc6da4750737bcdca8 --- /dev/null +++ b/pool/shard006/Python/0057921_hemodynamicExample-4R-autoregulation-exe.py @@ -0,0 +1,169 @@ +""" +@author: + Timo + Lukas + +Beschreibung: +Simulation eines Netzwerkes bestehend aus 4 Regionen. +Grafik folgt. +Inklusive nicht-linearer Erweiterung + +Pythonversion: +3.5.1 +""" + +import numpy as np +import matplotlib.pyplot as plt + +from programs import RK4 as RK4 +#from programs import Euler as RK1 +from programs import hemodynamicModel as HM +#from programs import bilinearModel as BM + +#----------------------------------------------------------------------------------------------------------------- +# Parameter Beispiel 1 +T = 25. # Endzeit +t0 = 0. # Anfangszeit +dt = 0.01 # Zeitschrittlaenge +t = np.arange(t0,T,dt) # Zeitarray + +A = np.array([[-1.0, 0.0, 0.0, 0.0], + [ 0.4,-1.0, 0.0, 0.0], + [ 0.0, 0.9,-1.0, 0.0], + [ 0.4, 0.0, 0.0,-1.0]]) # Kopplung + +# Anzahl B muss Anzahl der Stimuli entsprechen +# Induzierte Kopplungänderung durch Stimuli +B1 = np.zeros((4,4)) +B = np.array([B1]) # Zusammenfassen der ind. Kopplung in ein Array + +C = np.array([[0.5], + [0.0], + [0.0], + [0.0]]) # äußerer Einfluss auf Hirnaktivität + + +# Anzahl D muss Anzahl der Hirnregionen entsprechen +# Neuronal induzierte Kopplungsänderung +D1 = np.zeros((4,4)) +D2 = np.zeros((4,4)) +D3 = np.array([[ 0.0, 0.0, 0.0, 0.0], + [-10., 0.0, 0.0, 0.0], + [ 0.0, 0.0, 0.0, 0.0], + [ 0.0, 0.0, 0.0, 0.0]]) +D4 = np.zeros((4,4)) +D = np.array([D1, D2, D3, D4]) # Zusammenfassen der neuronalen Kopplungsänderung in ein Array + +# äußerer Stimulus +u = np.zeros((len(B), len(t))) +#u[0,1010:-990:2000] = 10. # Stimulus u1 +u[0,501:541] = 10. # Stimulus u1 + +# Anfangsbedingunden +x_0 = np.ones(20) +x_0[0:8] = 0. + +# Zusammenfassen der Parameter für das "hemodynamicModel" +theta = list([A,B,C,D]) + +#----------------------------------------------------------------------------------------------------------------- +# Simulation +#z_0 = np.array([0,0,0]) +#z = RK4.RK4(BM.bilinearModel,theta,u,z_0,t0,T,dt) +x = RK4.RK4(HM.stateEquations,theta,u,x_0,t0,T,dt) # Lösung mithilfe des RK4-Verfahrens +#x = RK1.Euler(HM.stateEquations,theta,u,x_0,t0,T,dt) # Lösung mithilfe des expl. Euler-Verfahrens +y = HM.BOLDsignal(x) # Berechnung des BOLD-Signals + + + + +plt.rcParams['figure.figsize'] = (15.0, 10.0) # Fenstergröße anpassen +plt.rcParams['axes.linewidth'] = 2 + +#----------------------------------------------------------------------------------------------------------------- +# Plotten Bilineares Modell +#-------------------------- BOLD ------------------------------------ +f1 = plt.figure(1) +f1.suptitle('Nichtlineares Modell', fontsize = 22) + +# Stimulus +ax1 = plt.subplot(311) +ax1.tick_params(width = 2) +plt.plot(t,u[0,:],linewidth=2) +plt.setp(ax1.get_xticklabels(), visible=False) +plt.axis([0, 25, 0, 12]) +plt.ylabel('$u(t)$', fontsize = 22.) +plt.title('Stimulus',fontsize = 20.) + +# Gehrinaktivität +ax2 = plt.subplot(312,sharex = ax1) +plt.setp(ax2.get_xticklabels(), visible=False) +ax2.tick_params(width = 2) + + +# Region 1: +#plt.plot(t,x[0,:],'r',label='Region 1') #Gehirnaktivität +#plt.plot(t,x[4,:],'r',label='Region 1') #Vasodilatorisches Signal +#plt.plot(t,x[8,:],'r',label='Region 1') #Blutfluss +#plt.plot(t,x[12,:],'r',label='Region 1') #Blutvolumen +#plt.plot(t,x[16,:],'r',label='Region 1') #Deoxyhemoglobingehalt + +# Region 2: +plt.plot(t,x[1,:],'r',label='Region 2',linewidth=2) #Gehirnaktivität +#plt.plot(t,x[5,:],'g',label='Region 2') #Vasodilatorisches Signal +#plt.plot(t,x[9,:],'g',label='Region 2') #Blutfluss +#plt.plot(t,x[13,:],'g',label='Region 2') #Blutvolumen +#plt.plot(t,x[17,:],'g',label='Region 2') #Deoxyhemoglobingehalt + +# Region 3: +plt.plot(t,x[2,:],'g',label='Region 3',linewidth=2) #Gehirnaktivität +#plt.plot(t,x[6,:],'b',label='Region 3') #Vasodilatorisches Signal +#plt.plot(t,x[10,:],'b',label='Region 3') #Blutfluss +#plt.plot(t,x[14,:],'b',label='Region 3') #Blutvolumen +#plt.plot(t,x[18,:],'b',label='Region 3') #Deoxyhemoglobingehalt + +# Region 4: +plt.plot(t,x[3,:],'b',label='Region 4',linewidth=2) #Gehirnaktivität +#plt.plot(t,x[7,:],'c',label='Region 4') #Vasodilatorisches Signal +#plt.plot(t,x[11,:],'c',label='Region 4') #Blutfluss +#plt.plot(t,x[15,:],'c',label='Region 4') #Blutvolumen +#plt.plot(t,x[19,:],'c',label='Region 4') #Deoxyhemoglobingehalt + +plt.ylabel('$z(t)$', fontsize = 22.) +plt.axis([0,25,-0.05,0.3]) +plt.title('Gehirnaktivität nach Region',fontsize = 20.) + +# Bold-Signal +ax3 = plt.subplot(313,sharex = ax1) +plt.setp(ax3.get_xticklabels(), fontsize = 14.) +#plt.xticks(np.arange(10,110,10)) +ax3.tick_params(width = 2) + +# Region 1: +#plt.plot(t,y[0,:],'r',label='Region 1') #BOLD-Signal +# Region 2: +plt.plot(t,y[1,:],'r',label='Region 2',linewidth=2) #BOLD-Signal +#Region 3: +plt.plot(t,y[2,:],'g',label='Region 3',linewidth=2) #BOLD-Signal +#Region 4: +plt.plot(t,y[3,:],'b',label='Region 4',linewidth=2) #BOLD-Signal + +ax3.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), + fancybox=True, shadow=True, ncol=5) + +plt.xlabel('Zeit t', fontsize = 18.) +plt.ylabel('$y(t)$', fontsize = 22.) +plt.title('BOLD-Signal nach Region',fontsize = 20.) + + +#f1.savefig('hemodynamicExample-4R-autoregulation.eps') + + + + + + + + + + diff --git a/pool/shard006/Python/0057922_automation_horizontal_resharding.py b/pool/shard006/Python/0057922_automation_horizontal_resharding.py new file mode 100644 index 0000000000000000000000000000000000000000..59f45bd3bb1ffb2648f0a6d3a9cefbd27299a026 --- /dev/null +++ b/pool/shard006/Python/0057922_automation_horizontal_resharding.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python +# +# Copyright 2015, Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can +# be found in the LICENSE file. +"""End-to-end test for horizontal resharding automation.""" + +# "unittest" is used indirectly by importing "worker", but pylint does +# not grasp this. +# Import it explicitly to make pylint happy and stop it complaining about +# setUpModule, tearDownModule and the missing module docstring. +import unittest # pylint: disable=unused-import + +import environment +import utils +import worker + + +def setUpModule(): + worker.setUpModule() + utils.Vtctld().start() + + +def tearDownModule(): + worker.tearDownModule() + + +class TestAutomationHorizontalResharding(worker.TestBaseSplitClone): + """End-to-end test for horizontal resharding automation. + + This test reuses worker.py because worker.py also covers the happy path + of the horizontal resharding code. Instead of running the different resharding + steps "manually" as part of the test, they will be run by the automation + cluster operation. + """ + + KEYSPACE = 'test_keyspace' + + def test_regular_operation(self): + # Use a dedicated worker to run all vtworker commands. + worker_proc, _, worker_rpc_port = utils.run_vtworker_bg( + ['--cell', 'test_nj'], + auto_log=True) + vtworker_endpoint = 'localhost:' + str(worker_rpc_port) + + automation_server_proc, automation_server_port = ( + utils.run_automation_server()) + + source_shard_list = '0' + dest_shard_list = '-80,80-' + _, vtctld_endpoint = utils.vtctld.rpc_endpoint() + utils.run( + environment.binary_argstr('automation_client') + + ' --server localhost:' + str(automation_server_port) + + ' --task HorizontalReshardingTask' + + ' --param keyspace=' + self.KEYSPACE + + ' --param source_shard_list=' + source_shard_list + + ' --param dest_shard_list=' + dest_shard_list + + ' --param vtctld_endpoint=' + vtctld_endpoint + + ' --param vtworker_endpoint=' + vtworker_endpoint + + ' --param min_healthy_rdonly_tablets=1') + + self.verify() + + utils.kill_sub_process(automation_server_proc, soft=True) + utils.kill_sub_process(worker_proc, soft=True) + + def verify(self): + self.assert_shard_data_equal(0, worker.shard_master, + worker.shard_0_tablets.replica) + self.assert_shard_data_equal(1, worker.shard_master, + worker.shard_1_tablets.replica) + + # Verify effect of MigrateServedTypes. Dest shards are serving now. + utils.check_srv_keyspace( + 'test_nj', self.KEYSPACE, + 'Partitions(master): -80 80-\n' + 'Partitions(rdonly): -80 80-\n' + 'Partitions(replica): -80 80-\n') + + # Check that query service is disabled (source shard) or enabled (dest). + + # The 'rdonly' tablet requires an explicit healthcheck first because + # the following sequence of events is happening in this test: + # - SplitDiff returns 'rdonly' as 'spare' tablet (NOT_SERVING) + # - MigrateServedTypes runs and does not refresh then 'spare' tablet + # (still NOT_SERVING) + # Shard_TabletControl.DisableQueryService=true will be set in the topology + # - explicit or periodic healthcheck runs: + # a) tablet seen as caught up, change type from 'spare' to 'rdonly' + # (change to SERVING) + # b) post-action callback agent.refreshTablet() reads the topology + # and finds out that DisableQueryService=true is set. + # (change to NOT_SERVING) + # + # We must run an explicit healthcheck or we can see one of the two states: + # - NOT_SERVING, DisableQueryService=false, tablet type 'spare' + # (immediately after SplitDiff returned) + # - SERVING, DisableQueryService=false, tablet type 'rdonly' + # (during healthcheck before post-action callback is called) + utils.run_vtctl(['RunHealthCheck', worker.shard_rdonly1.tablet_alias], + auto_log=True) + + # source shard: query service must be disabled after MigrateServedTypes. + utils.check_tablet_query_service( + self, worker.shard_rdonly1, + serving=False, tablet_control_disabled=True) + utils.check_tablet_query_service( + self, worker.shard_replica, + serving=False, tablet_control_disabled=True) + utils.check_tablet_query_service( + self, worker.shard_master, + serving=False, tablet_control_disabled=True) + + # dest shard -80: query service must be disabled after MigrateServedTypes. + # Run explicit healthcheck because 'rdonly' tablet may still be 'spare'. + utils.run_vtctl(['RunHealthCheck', worker.shard_0_rdonly1.tablet_alias], + auto_log=True) + utils.check_tablet_query_service( + self, worker.shard_0_rdonly1, + serving=True, tablet_control_disabled=False) + utils.check_tablet_query_service( + self, worker.shard_0_replica, + serving=True, tablet_control_disabled=False) + utils.check_tablet_query_service( + self, worker.shard_0_master, + serving=True, tablet_control_disabled=False) + + # dest shard 80-: query service must be disabled after MigrateServedTypes. + # Run explicit healthcheck because 'rdonly' tablet is still 'spare'. + utils.run_vtctl(['RunHealthCheck', worker.shard_1_rdonly1.tablet_alias], + auto_log=True) + utils.check_tablet_query_service( + self, worker.shard_1_rdonly1, + serving=True, tablet_control_disabled=False) + utils.check_tablet_query_service( + self, worker.shard_1_replica, + serving=True, tablet_control_disabled=False) + utils.check_tablet_query_service( + self, worker.shard_1_master, + serving=True, tablet_control_disabled=False) + +if __name__ == '__main__': + utils.main(test_options=worker.add_test_options) diff --git a/pool/shard006/Python/0057931_main.py b/pool/shard006/Python/0057931_main.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1b8204f7824aa64fa60e32906fae2dc4d2c433 --- /dev/null +++ b/pool/shard006/Python/0057931_main.py @@ -0,0 +1,66 @@ +from couchpotato.core.helpers.variable import tryInt +from couchpotato.core.logger import CPLog +from couchpotato.core.providers.torrent.base import TorrentMagnetProvider +import traceback + +log = CPLog(__name__) + + +class Yify(TorrentMagnetProvider): + + urls = { + 'test': '%s/api', + 'search': '%s/api/list.json?keywords=%s&quality=%s', + 'detail': '%s/api/movie.json?id=%s' + } + + http_time_between_calls = 1 #seconds + + proxy_list = [ + 'http://yify.unlocktorrent.com', + 'http://yify-torrents.com.come.in', + 'http://yts.re', + 'http://yts.im' + 'https://yify-torrents.im', + ] + + def search(self, movie, quality): + + if not quality.get('hd', False): + return [] + + return super(Yify, self).search(movie, quality) + + def _search(self, movie, quality, results): + + search_url = self.urls['search'] % (self.getDomain(), movie['library']['identifier'], quality['identifier']) + + data = self.getJsonData(search_url) + + if data and data.get('MovieList'): + try: + for result in data.get('MovieList'): + + try: + title = result['TorrentUrl'].split('/')[-1][:-8].replace('_', '.').strip('._') + title = title.replace('.-.', '-') + title = title.replace('..', '.') + except: + continue + + results.append({ + 'id': result['MovieID'], + 'name': title, + 'url': result['TorrentMagnetUrl'], + 'detail_url': self.urls['detail'] % (self.getDomain(), result['MovieID']), + 'size': self.parseSize(result['Size']), + 'seeders': tryInt(result['TorrentSeeds']), + 'leechers': tryInt(result['TorrentPeers']) + }) + + except: + log.error('Failed getting results from %s: %s', (self.getName(), traceback.format_exc())) + + def correctProxy(self, data): + data = data.lower() + return 'yify' in data and 'yts' in data diff --git a/pool/shard006/Python/0057936_test_urpmichannelsync.py b/pool/shard006/Python/0057936_test_urpmichannelsync.py new file mode 100644 index 0000000000000000000000000000000000000000..51f700d2d71210da95cb5d59371d529af57e1081 --- /dev/null +++ b/pool/shard006/Python/0057936_test_urpmichannelsync.py @@ -0,0 +1,113 @@ +import os + +from smart.plugins.urpmichannelsync import syncURPMIChannels +from smart import sysconf + +from tests.mocker import MockerTestCase + + +URPMI_CONFIG_MAIN = """\ +{ +} + +Main ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/release { + key-ids: 70771ff3 +} + +Main\ Updates ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/updates { + key-ids: 22458a98 + update +} +""" + +URPMI_CONFIG_CDROM = """\ +Mandriva\ Linux\ -\ 2009.0\ (Free)\ -\ Installer cdrom://i586/media/main { + ignore + key-ids: 70771ff3 +} +""" + +PRODUCT_ID = """\ +vendor=mandriva,distribution=mandriva linux,type=base,version=2010.1,branch=final,arch=x86_64 +""" + +URPMI_CONFIG_MIRRORLIST = """\ +MirrorList http://ftp.sunet.se/pub/Linux/distributions/mandrakelinux/official/2010.1/x86_64 { + mirrorlist: $MIRRORLIST +} +""" + +RELEASE = """\ +Mandriva Linux release 2010.1 (Official) for x86_64 +""" + +URPMI_CONFIG_VARIABLES = """\ +Variables http://ftp.sunet.se/pub/Linux/distributions/mandrakelinux/official/2010.1/x86_64 { + mirrorlist: $RELEASE/$ARCH +} +""" + +class UrpmiChannelSyncTest(MockerTestCase): + + def setUp(self): + self.config_dir = self.makeDir() + self.urpmi_dir = os.path.join(self.config_dir, "urpmi") + self.media_dir = os.path.join(self.config_dir, "media") + os.mkdir(self.urpmi_dir) + sysconf.remove("channels") + + def tearDown(self): + sysconf.remove("channels") + + def test_synchronize_config_main(self): + filename = self.makeFile(URPMI_CONFIG_MAIN, dirname=self.urpmi_dir, basename="urpmi.cfg") + syncURPMIChannels(filename, self.media_dir) + self.assertEquals(sysconf.get("channels"), { + "urpmisync-Main Updates": + {"type": "urpmi", + "name": "Main Updates", + "baseurl": "ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/updates", + "hdlurl": "media_info/synthesis.hdlist.cz", + "disabled": False, + "removable": False, + "priority": 0}, + + "urpmisync-Main": + {"type": "urpmi", + "name": "Main", + "baseurl": "ftp://ftp.free.fr/mirrors/ftp.mandriva.com/MandrivaLinux/official/2009.0/i586/media/main/release", + "hdlurl": "media_info/synthesis.hdlist.cz", + "disabled": False, + "removable": False, + "priority": 0}, + }) + + def test_synchronize_config_cdrom(self): + filename = self.makeFile(URPMI_CONFIG_CDROM, dirname=self.urpmi_dir, basename="urpmi.cfg") + syncURPMIChannels(filename, self.media_dir) + self.assertEquals(sysconf.get("channels"), { + "urpmisync-Mandriva Linux - 2009.0 (Free) - Installer": + {"type": "urpmi", + "name": "Mandriva Linux - 2009.0 (Free) - Installer", + "baseurl": "localmedia://i586/media/main", + "hdlurl": "media_info/synthesis.hdlist.cz", + "disabled": True, + "removable": True, + "priority": 0}, + }) + + def test_synchronize_config_mirrorlist(self): + product_id = self.makeFile(PRODUCT_ID, dirname=self.config_dir, basename="product.id") + sysconf.set("product-id", product_id, soft=True) + filename = self.makeFile(URPMI_CONFIG_MIRRORLIST, dirname=self.urpmi_dir, basename="urpmi.cfg") + syncURPMIChannels(filename, self.media_dir) + self.assertEquals(sysconf.get("channels")["urpmisync-MirrorList"]["mirrorurl"], + "http://api.mandriva.com/mirrors/base.2010.1.x86_64.list") + + def test_synchronize_config_variables(self): + release = self.makeFile(RELEASE, dirname=self.config_dir, basename="release") + sysconf.set("release", release, soft=True) + filename = self.makeFile(URPMI_CONFIG_VARIABLES, dirname=self.urpmi_dir, basename="urpmi.cfg") + syncURPMIChannels(filename, self.media_dir) + self.assertEquals(sysconf.get("channels")["urpmisync-Variables"]["mirrorurl"], + "2010.1/x86_64") diff --git a/pool/shard006/Python/0057939_SwigRenamer.py b/pool/shard006/Python/0057939_SwigRenamer.py new file mode 100644 index 0000000000000000000000000000000000000000..2cecfeda3048116535d64d3fccb83749be97f380 --- /dev/null +++ b/pool/shard006/Python/0057939_SwigRenamer.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python +# Copyright (c) 2013 Arista Networks, Inc. All rights reserved. +# Arista Networks, Inc. Confidential and Proprietary. +from __future__ import print_function +import string +import sys + +# Converts a string_like_this from stdin to a stringLikeThis. If the +# --classname flag is provided, we capitalize the first letter: +# StringLikeThis + +i = sys.stdin.readline().strip() +if i.endswith('_t'): + i = i[:-2] +i = string.capwords(i, '_').replace('_', '') +if '--classname' not in sys.argv: + i = i[0].lower() + i[1:] +print(i, end="") diff --git a/pool/shard006/Python/0057942_mod_auth_pyanonymous.py b/pool/shard006/Python/0057942_mod_auth_pyanonymous.py new file mode 100644 index 0000000000000000000000000000000000000000..e307c55e034de75024ef47801988433818690a2f --- /dev/null +++ b/pool/shard006/Python/0057942_mod_auth_pyanonymous.py @@ -0,0 +1,59 @@ +from __future__ import unicode_literals +from prosodypy.auth import ProsodyAuthPlugin + +class ProsodyPlugin(ProsodyAuthPlugin): + """ + A rewrite of mod_auth_anonymous.lua in Python for an example of how to + write auth plugins in Python. + """ + name = 'pyanonymous' + + def __init__(self, *args): + super(ProsodyPlugin, self).__init__(*args) + self.datamanager = self.lua.require('util.datamanager') + + def test_password(self, username, password): + raise NotImplementedError("Password based auth not supported.") + + def get_password(self, username): + raise NotImplementedError("Password not available.") + + def set_password(self, username, password): + raise NotImplementedError("Password based auth not supported.") + + def user_exists(self, username): + # FIXME check if anonymous user is connected? + raise NotImplementedError("Only anonymous users are supported.") + + def create_user(self, username, password): + raise NotImplementedError("Account creation/modification not supported.") + + def get_sasl_handler(self, session): + anonymous_authentication_profile = self.lua.table_from({ + 'anonymous': lambda sasl, username, realm: True, + }) + return self.sasl.new( + self.module.host, + anonymous_authentication_profile, + ) + + def users(self): + return ( + self.lua.eval('next'), + self.prosody.hosts[self.module.host].sessions, + None, + ) + + def dm_callback(self, username, host, datastore, data): + if host == self.module.host: + return False + return username, host, datastore, data + + def load(self): + if not self.module.get_option_boolean("allow_anonymous_s2s", False): + self.module.hook("route/remote", lambda event: False, 300) + self.datamanager.add_callback(self.dm_callback) + + def unload(self): + self.datamanager.remove_callback(self.dm_callback) + diff --git a/pool/shard006/Python/0057947_GrammarChecker.py b/pool/shard006/Python/0057947_GrammarChecker.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e957cddf0f257fba61ed2d19bdebed106ac414 --- /dev/null +++ b/pool/shard006/Python/0057947_GrammarChecker.py @@ -0,0 +1,132 @@ +# Libreoffice-voikko: Linguistic extension for LibreOffice +# Copyright (C) 2015 Harri Pitkänen +# +# This Source Code Form is subject to the terms of the Mozilla Public License, +# v. 2.0. If a copy of the MPL was not distributed with this file, You can +# obtain one at http://mozilla.org/MPL/2.0/. +# +# Alternatively, the contents of this file may be used under the terms of +# the GNU General Public License Version 3 or later (the "GPL"), in which +# case the provisions of the GPL are applicable instead of those above. + +import logging +import unohelper +from com.sun.star.linguistic2 import XProofreader, ProofreadingResult, SingleProofreadingError +from com.sun.star.lang import XServiceInfo, XInitialization, XServiceDisplayName +from com.sun.star.beans import PropertyValue +from com.sun.star.text.TextMarkupType import PROOFREADING +from VoikkoHandlePool import VoikkoHandlePool +from PropertyManager import PropertyManager + +class GrammarChecker(unohelper.Base, XServiceInfo, XProofreader, XInitialization, XServiceDisplayName): + + def __init__(self, ctx, *args): + logging.debug("GrammarChecker.__init__") + self.__ignoredErrors = set() # Grammar checker error codes that should be ignored + + # From XServiceInfo + def getImplementationName(self): + return GrammarChecker.IMPLEMENTATION_NAME + + def supportsService(self, serviceName): + return serviceName in self.getSupportedServiceNames() + + def getSupportedServiceNames(self): + return GrammarChecker.SUPPORTED_SERVICE_NAMES + + # From XSupportedLocales + def getLocales(self): + return VoikkoHandlePool.getInstance().getSupportedGrammarLocales() + + def hasLocale(self, aLocale): + return VoikkoHandlePool.getInstance().supportsGrammarLocale(aLocale) + + # From XProofreader + def isSpellChecker(self): + return False + + def doProofreading(self, aDocumentIdentifier, aText, aLocale, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition, aProperties): + logging.debug("GrammarChecker.doProofreading") + result = ProofreadingResult() + result.aDocumentIdentifier = aDocumentIdentifier + result.xFlatParagraph = None + result.aText = aText + result.aLocale = aLocale + result.nStartOfSentencePosition = nStartOfSentencePos + result.nBehindEndOfSentencePosition = nSuggestedBehindEndOfSentencePosition + result.xProofreader = self + + VoikkoHandlePool.mutex.acquire() + try: + voikko = VoikkoHandlePool.getInstance().getHandle(aLocale) + if voikko is None: + logging.error("GrammarChecker.doProofreading called without initializing libvoikko") + return result + + gcErrors = [] + gcI = 0 + vErrorCount = 0 + for vError in voikko.grammarErrors(aText, PropertyManager.getInstance().getMessageLanguage()): + startPos = vError.startPos + errorLength = vError.errorLen + + if startPos < result.nStartOfSentencePosition: + continue + if startPos >= result.nBehindEndOfSentencePosition: + break + if startPos + errorLength > result.nBehindEndOfSentencePosition: + result.nBehindEndOfSentencePosition = startPos + errorLength + + # we have a real grammar error + errorCode = vError.errorCode + ruleIdentifier = str(errorCode) + if ruleIdentifier in self.__ignoredErrors: + # ignore this error + continue + + suggestions = vError.suggestions + + gcError = SingleProofreadingError() + gcErrors.append(gcError) + gcError.nErrorStart = startPos + gcError.nErrorLength = errorLength + gcError.nErrorType = PROOFREADING + comment = vError.shortDescription + gcError.aShortComment = comment + gcError.aFullComment = comment + gcError.aRuleIdentifier = ruleIdentifier + + detailUrl = PropertyValue() + detailUrl.Name = "FullCommentURL" + detailUrl.Value = "https://voikko.puimula.org/gchelp/fi/" + ruleIdentifier + ".html" + gcError.aProperties = (detailUrl,) + + # add suggestions + if len(suggestions) > 0: + gcError.aSuggestions = tuple(suggestions) + + result.aErrors = tuple(gcErrors) + result.nStartOfNextSentencePosition = result.nBehindEndOfSentencePosition + return result + finally: + VoikkoHandlePool.mutex.release() + + def ignoreRule(self, ruleIdentifier, locale): + self.__ignoredErrors.add(ruleIdentifier) + + def resetIgnoreRules(self): + ignoredErrors.clear() + + # From XInitialization + def initialize(self): + pass + + # From XServiceDisplayName + def getServiceDisplayName(self, locale): + if locale.Language == "fi": + return "Kieliopin tarkistus (Voikko)" + else: + return "Grammar checker (Voikko)" + +GrammarChecker.IMPLEMENTATION_NAME = "voikko.GrammarChecker" +GrammarChecker.SUPPORTED_SERVICE_NAMES = ("com.sun.star.linguistic2.Proofreader",) diff --git a/pool/shard006/Python/0057952_UloziskoSk.py b/pool/shard006/Python/0057952_UloziskoSk.py new file mode 100644 index 0000000000000000000000000000000000000000..7cbcb4d40e30ea69cf31625c6f8c4eb55df72fbb --- /dev/null +++ b/pool/shard006/Python/0057952_UloziskoSk.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +import re +import urlparse + +from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo + + +class UloziskoSk(SimpleHoster): + __name__ = "UloziskoSk" + __type__ = "hoster" + __version__ = "0.26" + __status__ = "testing" + + __pattern__ = r'http://(?:www\.)?ulozisko\.sk/.+' + __config__ = [("use_premium", "bool", "Use premium account if available", True)] + + __description__ = """Ulozisko.sk hoster plugin""" + __license__ = "GPLv3" + __authors__ = [("zoidberg", "zoidberg@mujmail.cz")] + + + NAME_PATTERN = r'
(?P[^<]+)
' + SIZE_PATTERN = ur'Veľkosť súboru: (?P[\d.,]+) (?P[\w^_]+)
' + OFFLINE_PATTERN = ur'Zadaný súbor neexistuje z jedného z nasledujúcich dôvodov:' + + LINK_FREE_PATTERN = r'
' + ID_PATTERN = r'' + CAPTCHA_PATTERN = r'' + IMG_PATTERN = ur'PRE ZVÄČŠENIE KLIKNITE NA OBRÁZOK
' + + + def process(self, pyfile): + self.html = self.load(pyfile.url) + self.get_fileInfo() + + m = re.search(self.IMG_PATTERN, self.html) + if m: + self.link = "http://ulozisko.sk" + m.group(1) + else: + self.handle_free(pyfile) + + + def handle_free(self, pyfile): + m = re.search(self.LINK_FREE_PATTERN, self.html) + if m is None: + self.error(_("LINK_FREE_PATTERN not found")) + parsed_url = 'http://www.ulozisko.sk' + m.group(1) + + m = re.search(self.ID_PATTERN, self.html) + if m is None: + self.error(_("ID_PATTERN not found")) + id = m.group(1) + + self.log_debug("URL:" + parsed_url + ' ID:' + id) + + m = re.search(self.CAPTCHA_PATTERN, self.html) + if m is None: + self.error(_("CAPTCHA_PATTERN not found")) + + captcha_url = urlparse.urljoin("http://www.ulozisko.sk", m.group(1)) + captcha = self.captcha.decrypt(captcha_url, cookies=True) + + self.log_debug("CAPTCHA_URL:" + captcha_url + ' CAPTCHA:' + captcha) + + self.download(parsed_url, + post={'antispam': captcha, + 'id' : id, + 'name' : pyfile.name, + 'but' : "++++STIAHNI+S%DABOR++++"}) + + +getInfo = create_getInfo(UloziskoSk) diff --git a/pool/shard006/Python/0057953_test_getthings.py b/pool/shard006/Python/0057953_test_getthings.py new file mode 100644 index 0000000000000000000000000000000000000000..76e818463ebe1b683e1d6732f53c3be753682ac0 --- /dev/null +++ b/pool/shard006/Python/0057953_test_getthings.py @@ -0,0 +1,141 @@ +from healthvaultlib.tests.testbase import TestBase +from healthvaultlib.methods.getthings import GetThings +from healthvaultlib.objects.thinggroup import ThingGroup +from healthvaultlib.objects.thingfilter import ThingFilter +from healthvaultlib.objects.thingformat import ThingFormat +from healthvaultlib.objects.thingorderbyspecs import ThingOrderBySpecs +from healthvaultlib.objects.thingintentsspec import ThingIntentsSpec +from healthvaultlib.exceptions.healthserviceexception import HealthServiceException + + +class TestGetThings(TestBase): + + def test_getthings(self): + typeid = '40750a6a-89b2-455c-bd8d-b420a4cb500b' + height_filter = ThingFilter() + height_format = ThingFormat() + height_format.sections.append('core') + height_format.sections.append('xml') + height_filter.typeids.append(typeid) + group = ThingGroup() + group.filters = [height_filter] + group.format = height_format + + method = GetThings([group]) + method.execute(self.connection) + + self.assertEqual(len(method.response.groups), 1) + + if method.response.groups[0].healthrecorditems: + item = method.response.groups[0].healthrecorditems[0] + self.assertEqual(typeid, item.type_id) + self.assertIsNotNone(item.value_m) + + def test_getthings_coreonly(self): + typeid = '40750a6a-89b2-455c-bd8d-b420a4cb500b' + height_filter = ThingFilter() + height_format = ThingFormat() + height_format.sections.append('core') + height_filter.typeids.append(typeid) + group = ThingGroup() + group.filters = [height_filter] + group.format = height_format + + method = GetThings([group]) + method.execute(self.connection) + + self.assertEqual(len(method.response.groups), 1) + + if method.response.groups[0].healthrecorditems: + item = method.response.groups[0].healthrecorditems[0] + self.assertEqual(typeid, item.type_id) + self.assertIsNone(item.value_m) + + def test_getthings_order_by(self): + # Height does not support sorting, hence weight + typeid = '3d34d87e-7fc1-4153-800f-f56592cb0d17' + weight_filter = ThingFilter() + weight_format = ThingFormat() + weight_format.sections.append('core') + weight_format.sections.append('xml') + weight_filter.typeids.append(typeid) + + order_by = ThingOrderBySpecs(typeid, 'When') + order_by.direction = 'Desc' + + group = ThingGroup() + group.filters = [weight_filter] + group.format = weight_format + group.order_by = order_by + + method = GetThings([group]) + method.execute(self.connection) + + self.assertEqual(len(method.response.groups), 1) + + if method.response.groups[0].healthrecorditems: + items = method.response.groups[0].healthrecorditems + self.assertEqual(typeid, items[0].type_id) + self.assertIsNotNone(items[0].value_kg) + self.assertTrue(items[0].when > items[1].when) + + def test_getthings_max(self): + typeid = '40750a6a-89b2-455c-bd8d-b420a4cb500b' + height_filter = ThingFilter() + height_format = ThingFormat() + height_format.sections.append('core') + height_format.sections.append('xml') + height_filter.typeids.append(typeid) + + group = ThingGroup() + group.filters = [height_filter] + group.format = height_format + group.max = 5 + group.max_full = 3 + + method = GetThings([group]) + method.execute(self.connection) + + self.assertEqual(len(method.response.groups), 1) + + if method.response.groups[0].healthrecorditems: + items = method.response.groups[0].healthrecorditems + self.assertEqual(typeid, items[0].type_id) + self.assertTrue(len(items) <= 5) + + if len(items) > 3: + self.assertIsNotNone(items[2].value_m) + self.assertIsNone(items[3].value_m) + self.assertTrue(items[3].is_partial) + + def test_getthings_validations_and_intents(self): + typeid = '40750a6a-89b2-455c-bd8d-b420a4cb500b' + height_filter = ThingFilter() + height_format = ThingFormat() + height_format.sections.append('core') + height_format.sections.append('xml') + height_filter.typeids.append(typeid) + + group = ThingGroup() + group.filters = [height_filter] + + method = GetThings([group]) + with self.assertRaises(HealthServiceException): + method.execute(self.connection) + + group.format = height_format + group.intents = ThingIntentsSpec(['view', 'pingu']) + + method = GetThings([group]) + with self.assertRaises(HealthServiceException): + method.execute(self.connection) + + group.intents = ThingIntentsSpec(['view', 'download']) + method = GetThings([group]) + method.execute(self.connection) + + self.assertEqual(len(method.response.groups), 1) + + if method.response.groups[0].healthrecorditems: + items = method.response.groups[0].healthrecorditems + self.assertEqual(typeid, items[0].type_id) diff --git a/pool/shard006/Python/0057960_Apriori.py b/pool/shard006/Python/0057960_Apriori.py new file mode 100644 index 0000000000000000000000000000000000000000..55335473445d7d73cdd058993a3ffca77495ca89 --- /dev/null +++ b/pool/shard006/Python/0057960_Apriori.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +#https://www.coursera.org/learn/data-patterns/programming/88k0r/frequent-itemset-mining-using-apriori +def test(x): + count = 0 + for record in records: + if x.issubset(record): + count += 1 + return count +def read(): + fid = open("categories.txt","r") + for line in fid: + record = line.rsplit(";") + record[-1] = record[-1][:-1] + for item in record: + if item not in words: + words[item] = 1 + else: + words[item] += 1 + records.append(set(record)) + fid.close() + fid = open("patterns1.txt","w") + result = list() + for item in words: + if words[item]>MIN: + fid.write(str(words[item])+":"+item+"\n") + result.append(set([item])) + fid.close() + results.append(result) +def find(): + fid = open("patterns2.txt","w") + for item in words: + if words[item]>MIN: + fid.write(str(words[item])+":"+item+"\n") + idx = 0 + while True: + if len(results[idx])==0: + break + result = list() + for i in range(len(results[idx])): + for j in range(i+1,len(results[idx])): + if idx>0: + if len(results[idx][i]^results[idx][j])>2: + continue + addup = results[idx][i]|results[idx][j] + if addup in result: + continue + count = test(addup) + if count>MIN: + _addup = str(count)+":" + for k in addup: + _addup += k+";" + _addup = _addup[:-1]+"\n" + fid.write(_addup) + result.append(addup) + results.append(result) + idx += 1 + fid.close() + +words = dict() +records = list() +results = list() +MIN = 771 +# Set the relative minimum support to 0.01 on the 77,185 category lists +read() +find() \ No newline at end of file diff --git a/pool/shard006/Python/0057961_program.py b/pool/shard006/Python/0057961_program.py new file mode 100644 index 0000000000000000000000000000000000000000..caf13d6453986768233fb97cbd8c6ec1521ca747 --- /dev/null +++ b/pool/shard006/Python/0057961_program.py @@ -0,0 +1,21 @@ +# import gurobipy module +from gurobipy import * + +fileName = 'PhilModel.mps' + +# create empty model +m = Model() + +# change model name attribute +m.ModelName = 'Phil Model' + +# process the pending change +m.update() + +# export model to file +m.write(fileName) + +# print to console +print 'This program creates an empty model named:', m.Modelname +print 'Model exported to file named: ', fileName + diff --git a/pool/shard006/Python/0057965_caltoday.py b/pool/shard006/Python/0057965_caltoday.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3c3a6a5816e0b7ca6d36c1d7c5cd7e3b18c0c7 --- /dev/null +++ b/pool/shard006/Python/0057965_caltoday.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python + +import datetime +import re +import sys + +day = datetime.date.today().day + +RE = re.compile(r'\b%d\b' % day) + +for line in sys.stdin.readlines(): + coloring = RE.sub(r'${color #9090e8}%d$color' % day, line[22:42]) + print(line[:22] + coloring + line[42:]) diff --git a/pool/shard006/Python/0057967_owtweetprofiler.py b/pool/shard006/Python/0057967_owtweetprofiler.py new file mode 100644 index 0000000000000000000000000000000000000000..6fdc570c450b1dc070f4a42d21f6a7d908fe007d --- /dev/null +++ b/pool/shard006/Python/0057967_owtweetprofiler.py @@ -0,0 +1,184 @@ +from PyQt4 import QtGui +from PyQt4.QtGui import QGridLayout +from PyQt4.QtGui import QLabel + +from Orange.data import StringVariable +from Orange.widgets import gui +from Orange.widgets.settings import Setting +from Orange.widgets.utils.itemmodels import VariableListModel +from Orange.widgets.widget import OWWidget, Msg +from orangecontrib.text.tweet_profiler import TweetProfiler +from orangecontrib.text.corpus import Corpus + + +class IO: + CORPUS = "Corpus" + + +class OWTweetProfiler(OWWidget): + name = "Tweet Profiler" + description = "Detect Ekman's, Plutchik's or Profile of Mood States's " \ + "emotions in tweets." + icon = "icons/TweetProfiler.svg" + priority = 46 + + inputs = [(IO.CORPUS, Corpus, 'set_corpus')] + outputs = [(IO.CORPUS, Corpus)] + + want_main_area = False + resizing_enabled = False + + token = Setting('') + model_name = Setting('') + output_mode = Setting('') + tweet_attr = Setting(0) + auto_commit = Setting(True) + + class Error(OWWidget.Error): + server_down = Msg('Our servers are not responding. ' + 'Please try again later.') + invalid_token = Msg('This token is invalid') + no_credit = Msg('Too little credits for this data set') + + def __init__(self): + super().__init__() + self.corpus = None + self.strings_attrs = [] + self.profiler = TweetProfiler( + token=self.token, + on_server_down=self.Error.server_down, + on_invalid_token=self.Error.invalid_token, + on_too_little_credit=self.Error.no_credit, + ) + + # Info box + self.n_documents = '' + self.credit = 0 + box = gui.widgetBox(self.controlArea, "Info") + gui.label(box, self, 'Documents: %(n_documents)s') + gui.label(box, self, 'Credits: %(credit)s') + + # Settings + self.controlArea.layout().addWidget(self.generate_grid_layout()) + + # Server token + box = gui.vBox(self.controlArea, 'Server Token') + gui.lineEdit(box, self, 'token', callback=self.token_changed, + controlWidth=300) + gui.button(box, self, 'Get Token', callback=self.get_new_token) + + # Auto commit + buttons_layout = QtGui.QHBoxLayout() + buttons_layout.addWidget(self.report_button) + buttons_layout.addSpacing(15) + buttons_layout.addWidget( + gui.auto_commit(None, self, 'auto_commit', 'Commit', box=False) + ) + self.controlArea.layout().addLayout(buttons_layout) + + self.refresh_token_info() + + def generate_grid_layout(self): + box = QtGui.QGroupBox(title='Options') + + layout = QGridLayout() + layout.setSpacing(10) + row = 0 + + self.tweet_attr_combo = gui.comboBox(None, self, 'tweet_attr', + callback=self.apply) + layout.addWidget(QLabel('Attribute:')) + layout.addWidget(self.tweet_attr_combo, row, 1) + + row += 1 + self.model_name_combo = gui.comboBox(None, self, 'model_name', + items=self.profiler.model_names, + sendSelectedValue=True, + callback=self.apply) + if self.profiler.model_names: + self.model_name = self.profiler.model_names[0] # select 0th + layout.addWidget(QLabel('Emotions:')) + layout.addWidget(self.model_name_combo, row, 1) + + row += 1 + self.output_mode_combo = gui.comboBox(None, self, 'output_mode', + items=self.profiler.output_modes, + sendSelectedValue=True, + callback=self.apply) + if self.profiler.output_modes: + self.output_mode = self.profiler.output_modes[0] # select 0th + layout.addWidget(QLabel('Output:')) + layout.addWidget(self.output_mode_combo, row, 1) + + box.setLayout(layout) + return box + + def set_corpus(self, corpus): + self.corpus = corpus + + if corpus is not None: + self.strings_attrs = [a for a in self.corpus.domain.metas + if isinstance(a, StringVariable)] + self.tweet_attr_combo.setModel(VariableListModel(self.strings_attrs)) + self.tweet_attr_combo.currentIndexChanged.emit(self.tweet_attr) + + # select the first feature from 'text_features' if present + ind = [self.strings_attrs.index(tf) + for tf in corpus.text_features + if tf in self.strings_attrs] + if ind: + self.tweet_attr = ind[0] + + self.n_documents = len(corpus) + self.commit() + + def apply(self): + self.commit() + + def commit(self): + self.Error.clear() + + if self.corpus is not None: + with self.progressBar(iterations=len(self.corpus)) as pb: + out = self.profiler.transform( + self.corpus, self.strings_attrs[self.tweet_attr], + self.model_name, self.output_mode, + on_advance=pb.advance) + self.send(IO.CORPUS, out) + else: + self.send(IO.CORPUS, None) + + self.refresh_token_info() + + def get_new_token(self): + self.Warning.clear() + self.profiler.new_token() + self.token = self.profiler.token + self.refresh_token_info() + self.commit() + + def token_changed(self): + self.profiler.token = self.token + self.refresh_token_info() + self.commit() + + def refresh_token_info(self): + self.credit = str(self.profiler.get_credit()) + + def send_report(self): + self.report_items([ + ('Documents', self.n_documents), + ('Attribute', self.strings_attrs[self.tweet_attr] + if len(self.strings_attrs) > self.tweet_attr else ''), + ('Emotions', self.model_name), + ('Output', self.output_mode), + ]) + + +if __name__ == '__main__': + app = QtGui.QApplication([]) + corpus = Corpus.from_file('Election-2016-Tweets.tab') + widget = OWTweetProfiler() + widget.set_corpus(corpus[:100]) + widget.show() + app.exec() diff --git a/pool/shard006/Python/0057969_loading.py b/pool/shard006/Python/0057969_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..c4931ca7a8d2181033b34563892390c787868e44 --- /dev/null +++ b/pool/shard006/Python/0057969_loading.py @@ -0,0 +1,109 @@ +import sys +import traceback + +from django.conf import settings + + +class AppNotFoundError(Exception): + pass + + +class ClassNotFoundError(Exception): + pass + + +def get_class(module_label, classname): + return get_classes(module_label, [classname, ])[0] + + +def get_classes(module_label, classnames): + """ Imports a set of classes from a given module. + + Usage:: + + get_classes('forum.models', ['Forum', 'ForumReadTrack', ]) + + """ + app_label = module_label.split('.')[0] + + app_module_path = _get_app_module_path(module_label) + if not app_module_path: + raise AppNotFoundError('No app found matching \'{}\''.format(module_label)) + + # Determines the full module path by appending the module label + # to the base package path of the considered application. + module_path = app_module_path + if '.' in app_module_path: + base_package = app_module_path.rsplit('.' + app_label, 1)[0] + module_path = '{}.{}'.format(base_package, module_label) + + # Try to import this module from the related app that is specified + # in the Django settings. + local_imported_module = _import_module(module_path, classnames) + + # If the module we tried to import is not located inside the machina + # vanilla apps, try to import it from the corresponding machina app. + machina_imported_module = None + if not app_module_path.startswith('machina.apps'): + machina_imported_module = _import_module( + '{}.{}'.format('machina.apps', module_label), classnames, + ) + + if local_imported_module is None and machina_imported_module is None: + raise AppNotFoundError('Error importing \'{}\''.format(module_path)) + + # Any local module is prioritized over the corresponding machina module + imported_modules = [ + m for m in (local_imported_module, machina_imported_module) if m is not None + ] + return _pick_up_classes(imported_modules, classnames) + + +def _import_module(module_path, classnames): + """ Tries to import the given Python module path. """ + try: + imported_module = __import__(module_path, fromlist=classnames) + return imported_module + except ImportError: + # In case of an ImportError, the module being loaded generally does not exist. But an + # ImportError can occur if the module being loaded exists and another import located inside + # it failed. + # + # In order to provide a meaningfull traceback, the execution information can be inspected in + # order to determine which case to consider. If the execution information provides more than + # a certain amount of frames, this means that an ImportError occured while loading the + # initial Python module. + __, __, exc_traceback = sys.exc_info() + frames = traceback.extract_tb(exc_traceback) + if len(frames) > 1: + raise + + +def _pick_up_classes(modules, classnames): + """ Given a list of class names to retrieve, try to fetch them from the specified list of + modules and returns the list of the fetched classes. + """ + klasses = [] + for classname in classnames: + klass = None + for module in modules: + if hasattr(module, classname): + klass = getattr(module, classname) + break + if not klass: + raise ClassNotFoundError('Error fetching \'{}\' in {}'.format( + classname, str([module.__name__ for module in modules])) + ) + klasses.append(klass) + return klasses + + +def _get_app_module_path(module_label): + """ Given a module label, loop over the apps specified in the INSTALLED_APPS to find the + corresponding application module path. + """ + app_name = module_label.rsplit('.', 1)[0] + for app in settings.INSTALLED_APPS: + if app.endswith('.' + app_name) or app == app_name: + return app + return None diff --git a/pool/shard006/Python/0057974_route.py b/pool/shard006/Python/0057974_route.py new file mode 100644 index 0000000000000000000000000000000000000000..ca42ee5de2bd9c4a64da037be2eae43c3de19c72 --- /dev/null +++ b/pool/shard006/Python/0057974_route.py @@ -0,0 +1,150 @@ +#!/usr/bin/python2.4 +# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab +# +# $Id$ +# +# Copyright (C) 1999-2006 Keith Dart +# +# 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. + +""" +Routing table via /proc/net/route. +Note that the RouteEntry returns values in host byte order, not the network +byte order that the kernel file emits. + +""" +from socket import ntohl + +FILE="/proc/net/route" + +# Flag bits +# from /usr/include/linux/route.h +RTF_UP=0x0001 # route usable +RTF_GATEWAY=0x0002 # destination is a gateway +RTF_HOST=0x0004 # host entry (net otherwise) +RTF_REINSTATE=0x0008 # reinstate route after tmout +RTF_DYNAMIC=0x0010 # created dyn. (by redirect) +RTF_MODIFIED=0x0020 # modified dyn. (by redirect) +RTF_MTU=0x0040 # specific MTU for this route +RTF_WINDOW=0x0080 # per route window clamping +RTF_IRTT=0x0100 # Initial round trip time +RTF_REJECT=0x0200 # Reject route + + +def _hex(i): + return "%8X" % (i,) + +class RouteEntry(object): + """Represents a routing table entry. """ + def __init__(self, Iface, Destination=None, Gateway=None, + Flags=0, RefCnt=0, Use=0, Metric=0, Mask=None, + MTU=0, Window=0, IRTT=0): + self.Iface = Iface + self.Destination = Destination + self.Gateway = Gateway + self.Flags = Flags + self.RefCnt = RefCnt + self.Use = Use + self.Metric = Metric + self.Mask = Mask + self.MTU = MTU + self.Window = Window + self.IRTT = IRTT + + def __str__(self): + return "\t".join([self.Iface]+map(_hex, [self.Destination, self.Gateway])+map(str, [ + self.Flags, self.RefCnt, self.Use, self.Metric]) + [_hex(self.Mask)] + + map(str, [self.MTU, self.Window, self.IRTT])) + + # informational methods + def is_up(self): + return self.Flags & RTF_UP + is_active = is_up # alias + + def is_gateway(self): + return self.Flags & RTF_GATEWAY + + def is_host(self): + return self.Flags & RTF_HOST + + def is_reject(self): + return self.Flags & RTF_REJECT + +class RouteFlags(int): + def __new__(cls, v): + return int.__new__(cls, int(v, 16)) + def __str__(self): + return "%04X" %(self,) + + +HEADER="Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT" +class RouteTable(object): + """Represents the kernel FIB. Supports sequence operators.""" + def __init__(self): + self._entries = [] + + def __str__(self): + return "\n".join([HEADER] + map(str, self._entries)) + + def __getitem__(self, idx): + return self._entries[idx] + + def __iter__(self): + return iter(self._entries) + + def update(self, filt=None): + """update([filter]) +Update the RouteTable with current values. If a filter function is supplied +then it will be called with a RouteEntry and must return a true or false value. +If true, the RouterEntry will be included in the table. If false, it will not. +""" + self._entries = [] + lines = open(FILE).readlines() + for line in lines[1:]: + [iface, dest, gateway, flags, refcnt, use, metric, mask, + mtu, window, irtt] = line.split() + rt = RouteEntry(iface, + Destination=ntohl(int(dest, 16)), + Gateway=ntohl(int(gateway, 16)), + Flags=RouteFlags(flags), + RefCnt=int(refcnt, 16), + Use=int(use, 16), + Metric=int(metric, 16), + Mask=ntohl(int(mask, 16)), + MTU=int(mtu, 16), + Window=int(window, 16), + IRTT=int(irtt, 16)) + if filt: + if filt(rt): + self._entries.append(rt) + else: + self._entries.append(rt) + +def get_route(): + rt = RouteTable() + rt.update() + return rt + +def get_active_route(): + def _active(re): + return re.is_active() + rt = RouteTable() + rt.update(_active) + return rt + +if __name__ == "__main__": + rt = get_route() + # print only UP/active routes + for r in rt: + if r.is_active(): + print r + + diff --git a/pool/shard006/Python/0057976_wigner_ville_smoothing.py b/pool/shard006/Python/0057976_wigner_ville_smoothing.py new file mode 100644 index 0000000000000000000000000000000000000000..d412ee55a5f3e675ddbebceeec5fd5c7c56b7d55 --- /dev/null +++ b/pool/shard006/Python/0057976_wigner_ville_smoothing.py @@ -0,0 +1,41 @@ +import matplotlib as mpl +mpl.rcParams['font.size'] = 9.0 +import matplotlib.pylab as plt +plt.style.use("ggplot") +from mtspec import wigner_ville_spectrum +from mtspec.util import linear_chirp, exponential_chirp +import numpy as np + +fig = plt.figure() +data = linear_chirp() + exponential_chirp() + +# Plot the data +ax1 = fig.add_axes([0.05,0.75, 0.90, 0.24]) +ax1.plot(data) +ax1.set_xlim(0, len(data)) +ax1.set_yticks([]) + +# Get the smoothed WV spectrum. +wv = wigner_ville_spectrum(data, 10, 5.0, smoothing_filter='gauss', + filter_width=25) + +# Plot the WV +ax2 = fig.add_axes([0.01, 0.025, 0.48, 0.64]) +ax2.set_yticks([]) +ax2.set_xticks([]) +ax2.imshow(abs(wv), interpolation='nearest', aspect='auto', + cmap="magma") +ax2.set_title('With smoothing') + +# Get the WV spectrum. +wv = wigner_ville_spectrum(data, 10, 5.0, smoothing_filter=None) + +# Plot the WV +ax3 = fig.add_axes([0.51, 0.025, 0.48, 0.64]) +ax3.set_yticks([]) +ax3.set_xticks([]) +ax3.imshow(abs(wv), interpolation='nearest', aspect='auto', + cmap="magma") +ax3.set_title('Without smoothing') + +plt.show() diff --git a/pool/shard006/Python/0057978_kuaishou.py b/pool/shard006/Python/0057978_kuaishou.py new file mode 100644 index 0000000000000000000000000000000000000000..917920d196444f49e300844b7a79f212f833936c --- /dev/null +++ b/pool/shard006/Python/0057978_kuaishou.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import urllib.request +import urllib.parse +import json +import re + +from ..util import log +from ..common import get_content, download_urls, print_info, playlist_not_supported, url_size + +__all__ = ['kuaishou_download_by_url'] + + +def kuaishou_download_by_url(url, info_only=False, **kwargs): + page = get_content(url) + # size = video_list[-1]['size'] + # result wrong size + try: + search_result=re.search(r"\"playUrls\":\[(\{\"quality\"\:\"\w+\",\"url\":\".*?\"\})+\]", page) + all_video_info_str = search_result.group(1) + all_video_infos=re.findall(r"\{\"quality\"\:\"(\w+)\",\"url\":\"(.*?)\"\}", all_video_info_str) + # get the one of the best quality + video_url = all_video_infos[0][1].encode("utf-8").decode('unicode-escape') + title = re.search(r"(.*?)", page).group(1) + size = url_size(video_url) + video_format = "flv"#video_url.split('.')[-1] + print_info(site_info, title, video_format, size) + if not info_only: + download_urls([video_url], title, video_format, size, **kwargs) + except:# extract image + og_image_url = re.search(r"", page).group(1) + image_url = og_image_url + title = url.split('/')[-1] + size = url_size(image_url) + image_format = image_url.split('.')[-1] + print_info(site_info, title, image_format, size) + if not info_only: + download_urls([image_url], title, image_format, size, **kwargs) + +site_info = "kuaishou.com" +download = kuaishou_download_by_url +download_playlist = playlist_not_supported('kuaishou') diff --git a/pool/shard006/Python/0057981_plugin_set.py b/pool/shard006/Python/0057981_plugin_set.py new file mode 100644 index 0000000000000000000000000000000000000000..9eda8cf7fd0886e7f6e45976d75caa49a1f3567c --- /dev/null +++ b/pool/shard006/Python/0057981_plugin_set.py @@ -0,0 +1,99 @@ +import os +import pynsive +import importlib +from operator import itemgetter + +from .utilities.dict2List import dict2List +from .utilities.logger import logger + + +class PluginSet(object): + def __init__(self, plugin_location, enabled_plugins=None): + self.plugin_location = plugin_location + self.enabled_plugins = self.identify_plugins(enabled_plugins) + + def identify_plugins(self, enabled_plugins): + if not os.path.exists(self.plugin_location): + return [] + + module_name = os.path.basename(self.plugin_location) + root_plugin_directory = os.path.join(self.plugin_location, '..') + + plugin_manager = pynsive.PluginManager() + plugin_manager.plug_into(root_plugin_directory) + + plugins = [] + + found_modules = pynsive.list_modules(module_name) + for found_module in found_modules: + module_filename, module_name = found_module.split('.') + if enabled_plugins is not None and module_name not in enabled_plugins: + # Skip this plugin since it's not listed as enabled plugins + # as long as we have specified some enabled plugins though + # this allows us to specify no specific plugins and get all of them + continue + + try: + module_obj = pynsive.import_module(found_module) + importlib.reload(module_obj) + plugin_class_obj = module_obj.message() + + if 'priority' in dir(plugin_class_obj): + priority = plugin_class_obj.priority + else: + priority = 100 + + logger.info('[*] plugin {0} registered to receive messages with {1}'.format(module_name, plugin_class_obj.registration)) + plugins.append( + { + 'plugin_class': plugin_class_obj, + 'registration': plugin_class_obj.registration, + 'priority': priority + } + ) + except Exception as e: + logger.exception('Received exception when loading {0} plugins\n{1}'.format(module_name, e)) + plugin_manager.destroy() + return plugins + + @property + def ordered_enabled_plugins(self): + return sorted(self.enabled_plugins, key=itemgetter('priority'), reverse=False) + + def run_plugins(self, message, metadata=None): + '''compare the message to the plugin registrations. + plugins register with a list of keys or values + or values they want to match on + this function compares that registration list + to the current message and sends the message to plugins + in order + ''' + if not isinstance(message, dict): + raise TypeError('event is type {0}, should be a dict'.format(type(message))) + + for plugin in self.ordered_enabled_plugins: + send = False + message_fields = [e for e in dict2List(message)] + # this is to make it so we can match on all fields + message_fields.append('*') + if isinstance(plugin['registration'], list): + if set(plugin['registration']).intersection(message_fields): + send = True + elif isinstance(plugin['registration'], str): + if plugin['registration'] in message_fields: + send = True + if send: + try: + (message, metadata) = self.send_message_to_plugin(plugin_class=plugin['plugin_class'], message=message, metadata=metadata) + except Exception as e: + logger.exception('Received exception in {0}: message: {1}\n{2}'.format(plugin['plugin_class'], message, e)) + if message is None: + return (message, metadata) + return (message, metadata) + + def send_message_to_plugin(self, plugin_class, message, metadata=None): + '''moving this logic to a separate function allows + different types of plugin_sets, such as alerts that might not care + about receiving metadata in its plugins + ''' + return plugin_class.onMessage(message, metadata) diff --git a/pool/shard006/Python/0057983_tools.py b/pool/shard006/Python/0057983_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..33cf012f87027627bf706f1bbb41f657ceeb6dd5 --- /dev/null +++ b/pool/shard006/Python/0057983_tools.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# +# generic tools for apps +# + + +def format_float(number): # {{{ + """ + format the display style of a float number + """ + threshold_min = 0.001 + threshold_max = 9999.9 + fix_fmt = '{:,.1f}' # comma as a thousands separator + exp_fmt = '{:.1e}' + # + if isinstance(number, int) or isinstance(number, float): + #return type(number) + pass + else: + return False + # + if (number > threshold_max) or (number < threshold_min): + str = exp_fmt.format(number) + else: + str = fix_fmt.format(number) + # + return str +# }}} + + diff --git a/pool/shard006/Python/0057987_problem51.py b/pool/shard006/Python/0057987_problem51.py new file mode 100644 index 0000000000000000000000000000000000000000..43259d48bd7f3ea5b63df08d5a491f285b240d0a --- /dev/null +++ b/pool/shard006/Python/0057987_problem51.py @@ -0,0 +1,63 @@ +""" +problem51.py + +https://projecteuler.net/problem=51 + +By replacing the 1st digit of the 2-digit number *3, it turns out that six of +the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. + +By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit +number is the first example having seven primes among the ten generated +numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and +56993. Consequently 56003, being the first member of this family, is the +smallest prime with this property. + +Find the smallest prime which, by replacing part of the number (not necessarily +adjacent digits) with the same digit, is part of an eight prime value family. +""" +from itertools import count, product + +from toolset import get_primes, is_prime, quantify + + +# Our strategy is as follows. Since we are seeking an eight prime family, it +# must be the case that the pattern of digits which are replaced contains +# either 0, 1, or 2 in the smallest family member. Therefore, we can search +# through primes and replace digits in patterns specified by the locations 0, +# 1, and 2. If the family of numbers that results contains eight primes, we +# have found the solution. +# +# In the example given, 56003 is the smallest member of an eight prime family. +# We would find the pattern of 0s at indices (2, 3) to produce the +# corresponding family from 56**3. +def find_indices(num): + """Yield three tuples, where each tuple contains the indices + in the num of the digits 0, 1, and 2 respectively.""" + # find_indices(18209912) --> (3), (0, 6), (2, 7) + # find_indices(56003) --> (2, 3), (), () + digits = str(num) + for target in "012": + yield tuple(i for i, x in enumerate(digits) if x == target) + +def family(num, indices): + """Yield the family of numbers resulting from replacing + digits at the specific indices with the digits 0 to 9.""" + # family(56003, (2, 3)) --> 56003, 56113, 56223, 56333, 56443, ... + template = str(num) + for i in "0123456789": + member = list(template) + for idx in indices: + member[idx] = i + # yield sentinel value (-1) in case of leading zero + yield int(''.join(member)) if member[0] != "0" else -1 + +def is_smallest_member(num): + """Does the number satisfy the problem specification?""" + return any(quantify(family(num, indices), pred=is_prime) == 8 + for indices in find_indices(num)) + +def problem51(): + return next(filter(is_smallest_member, get_primes(start=56995))) + +if __name__ == "__main__": + print(problem51()) diff --git a/pool/shard006/Python/0057989_codeline.py b/pool/shard006/Python/0057989_codeline.py new file mode 100644 index 0000000000000000000000000000000000000000..0039550fb0090d595c12e2df725d6b2403121989 --- /dev/null +++ b/pool/shard006/Python/0057989_codeline.py @@ -0,0 +1,147 @@ +"""Parse vim code to mutate vimdoc blocks.""" +import abc + +import vimdoc +import vimdoc.block + + +class CodeLine(object): + """A line of code that affects the block above it. + + For example, the documentation above a function line will be modified to set + type=FUNCTION. + """ + __metaclass__ = abc.ABCMeta + + def Update(self, block): + """Updates a single block.""" + + def Affect(self, blocks, selection): + """Affects all blocks above the code line. + + There can be multiple blocks above the code line, for example: + + " @usage item index list + " Insert {item} at {list} after {index} + " @usage value key dict + " Insert {value} in {dict} under {key} + function ... + + All blocks will be affected, regardless of selection. Then all blocks will + be unselected: once the documentation hits the codeline, the blocks are + done. + + Args: + blocks: The blocks above this codeline. + selection: the selected blocks. + + Yields: + Each block after updating it. + """ + for block in blocks: + self.Update(block) + yield block + blocks[:] = [] + selection[:] = [] + + +class Blank(CodeLine): + """A blank line.""" + + +class EndOfFile(CodeLine): + """The end of the file.""" + + +class Unrecognized(CodeLine): + """A code line that doesn't deserve decoration.""" + + def __init__(self, line): + self.line = line + + def Affect(self, blocks, selection): + """Documentation above unrecognized lines is ignored.""" + blocks[:] = [] + selection[:] = [] + return () + + +class Definition(CodeLine): + """An abstract definition line.""" + + __metaclass__ = abc.ABCMeta + + def __init__(self, typ, name): + self.name = name + self.type = typ + + def Update(self, block): + block.SetType(self.type) + block.Local(name=self.name) + + +class Function(Definition): + """Function definition.""" + + def __init__(self, name, namespace, args): + self.name = name + self.namespace = namespace + self.args = args + super(Function, self).__init__(vimdoc.FUNCTION, name) + + def Update(self, block): + super(Function, self).Update(block) + if self.namespace: + block.Local(namespace=self.namespace, local=True, args=self.args) + else: + block.Local(local=False, args=self.args) + + +class Command(Definition): + """Command definition.""" + + def __init__(self, name, **flags): + self.flags = flags + super(Command, self).__init__(vimdoc.COMMAND, name) + + def Update(self, block): + """Updates one block above the command line.""" + super(Command, self).Update(block) + # Usage is like: + # [range][count]["x][N]MyCommand[!] {req1} {req2} [optional1] [optional2] + head = '' + if self.flags.get('range'): + head += '[range]' + if self.flags.get('count'): + head += '[count]' + if self.flags.get('register'): + head += '["x]' + if self.flags.get('buffer'): + head += '[N]' + head += '<>' + if self.flags.get('bang'): + head += '[!]' + block.Local(head=head) + + +class Setting(Definition): + def __init__(self, name): + super(Setting, self).__init__(vimdoc.SETTING, name) + + +class Flag(Definition): + def __init__(self, name, default): + super(Flag, self).__init__(vimdoc.FLAG, name) + self._default = default + + def Affect(self, blocks, selection): + # Add line to show expression for default value. Can be None if vimdoc + # failed to parse a default, e.g. due to deeply-nested parentheses. + if self._default is not None: + # Append to last block, creating one if there isn't one yet. + if not blocks: + blocks.append(vimdoc.block.Block()) + # Use unbulleted list to make sure it's on its own line. Use backtick to + # avoid helpfile syntax highlighting. + blocks[-1].AddLine(' - Default: {} `'.format(self._default)) + return super(Flag, self).Affect(blocks, selection) diff --git a/pool/shard006/Python/0057991_innerproduct.py b/pool/shard006/Python/0057991_innerproduct.py new file mode 100644 index 0000000000000000000000000000000000000000..3b0fb20bf3255e30c9473bbf8745610c980255a4 --- /dev/null +++ b/pool/shard006/Python/0057991_innerproduct.py @@ -0,0 +1,138 @@ +"""Symbolic inner product.""" + +from __future__ import print_function, division + +from sympy import Expr, conjugate +from sympy.printing.pretty.stringpict import prettyForm +from sympy.physics.quantum.dagger import Dagger +from sympy.physics.quantum.state import KetBase, BraBase + +__all__ = [ + 'InnerProduct' +] + + +# InnerProduct is not an QExpr because it is really just a regular commutative +# number. We have gone back and forth about this, but we gain a lot by having +# it subclass Expr. The main challenges were getting Dagger to work +# (we use _eval_conjugate) and represent (we can use atoms and subs). Having +# it be an Expr, mean that there are no commutative QExpr subclasses, +# which simplifies the design of everything. + +class InnerProduct(Expr): + """An unevaluated inner product between a Bra and a Ket [1]. + + Parameters + ========== + + bra : BraBase or subclass + The bra on the left side of the inner product. + ket : KetBase or subclass + The ket on the right side of the inner product. + + Examples + ======== + + Create an InnerProduct and check its properties: + + >>> from sympy.physics.quantum import Bra, Ket, InnerProduct + >>> b = Bra('b') + >>> k = Ket('k') + >>> ip = b*k + >>> ip + + >>> ip.bra + >> ip.ket + |k> + + In simple products of kets and bras inner products will be automatically + identified and created:: + + >>> b*k + + + But in more complex expressions, there is ambiguity in whether inner or + outer products should be created:: + + >>> k*b*k*b + |k>*>> k*(b*k)*b + *|k>* moved to the left of the expression + because inner products are commutative complex numbers. + + References + ========== + + .. [1] http://en.wikipedia.org/wiki/Inner_product + """ + is_complex = True + + def __new__(cls, bra, ket): + if not isinstance(ket, KetBase): + raise TypeError('KetBase subclass expected, got: %r' % ket) + if not isinstance(bra, BraBase): + raise TypeError('BraBase subclass expected, got: %r' % ket) + obj = Expr.__new__(cls, bra, ket) + return obj + + @property + def bra(self): + return self.args[0] + + @property + def ket(self): + return self.args[1] + + def _eval_conjugate(self): + return InnerProduct(Dagger(self.ket), Dagger(self.bra)) + + def _sympyrepr(self, printer, *args): + return '%s(%s,%s)' % (self.__class__.__name__, + printer._print(self.bra, *args), printer._print(self.ket, *args)) + + def _sympystr(self, printer, *args): + sbra = str(self.bra) + sket = str(self.ket) + return '%s|%s' % (sbra[:-1], sket[1:]) + + def _pretty(self, printer, *args): + # Print state contents + bra = self.bra._print_contents_pretty(printer, *args) + ket = self.ket._print_contents_pretty(printer, *args) + # Print brackets + height = max(bra.height(), ket.height()) + use_unicode = printer._use_unicode + lbracket, _ = self.bra._pretty_brackets(height, use_unicode) + cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode) + # Build innerproduct + pform = prettyForm(*bra.left(lbracket)) + pform = prettyForm(*pform.right(cbracket)) + pform = prettyForm(*pform.right(ket)) + pform = prettyForm(*pform.right(rbracket)) + return pform + + def _latex(self, printer, *args): + bra_label = self.bra._print_contents_latex(printer, *args) + ket = printer._print(self.ket, *args) + return r'\left\langle %s \right. %s' % (bra_label, ket) + + def doit(self, **hints): + try: + r = self.ket._eval_innerproduct(self.bra, **hints) + except NotImplementedError: + try: + r = conjugate( + self.bra.dual._eval_innerproduct(self.ket.dual, **hints) + ) + except NotImplementedError: + r = None + if r is not None: + return r + return self diff --git a/pool/shard006/Python/0057992_collection.py b/pool/shard006/Python/0057992_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..2c8e09fc5fb60fb3291e489177529d5135d0a2f2 --- /dev/null +++ b/pool/shard006/Python/0057992_collection.py @@ -0,0 +1,74 @@ +class Collection(object): + """ + Collection of one type entities + """ + + def __init__(self, entity_cls): + self._items = {} + self._entity_cls = entity_cls + + def __call__(self, name=None, *args, **kwargs): + """ + Calling all items or item by name + :param name: collection + :return: called item + """ + if name: + return self.get(name)(*args, **kwargs) + else: + res = {} + for name, item in self.get_all().items(): + res[name] = item(*args, **kwargs) + + return res + + def get_entity_cls(self): + """ + :return: Entity class + """ + return self._entity_cls + + def get_all(self): + """ + All items + """ + return self._items + + def get(self, name): + """ + :param name: item name + :return: item value + """ + return self._items[name] + + def insert(self, __name__, **props): + """ + Inserting new item into collection + :param __name__: item name + :param props: item properties + """ + if __name__ not in self._items: + self._items[__name__] = self._entity_cls(**props) + else: + raise KeyError("Undefined property '%s'" % (__name__,)) + + def update(self, __name__, **props): + """ + Updating existing item + :param __name__: item name + :param props: item properties to update + """ + self.get(__name__).set(**props) + + def insert_or_update(self, __name__, **props): + try: + self.insert(__name__, **props) + except KeyError: + self.update(__name__, **props) + + def remove(self, name): + """ + Removing item from collection + :param name: name of item + """ + del self._items[name] diff --git a/pool/shard006/Python/0057997_cnblogs.py b/pool/shard006/Python/0057997_cnblogs.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2ec1373c70a76d8cef0c1128e57a05e2a3aa8b --- /dev/null +++ b/pool/shard006/Python/0057997_cnblogs.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +import scrapy +from PageCrawl.items import BlogItem + +class CnblogsSpider(scrapy.Spider): + name = "cnblogs" + allowed_domains = ["cnblogs.com"] + start_urls = ( + 'http://www.cnblogs.com/pick', + ) + + def parse(self, response): + page_list = response.xpath('//div[@id="post_list"]/div[@class="post_item"]') + for page in page_list: + item = BlogItem() + item['url'] = page.css('div.post_item_body>h3>a::attr(href)').extract()[0] + item['title'] = page.css('div.post_item_body>h3>a::text').extract()[0] + item['author'] = page.css('div.post_item_foot>a::text').extract()[0] + item['source'] = 'cnblogs' + yield item \ No newline at end of file diff --git a/pool/shard006/Python/0057999_samreader.py b/pool/shard006/Python/0057999_samreader.py new file mode 100644 index 0000000000000000000000000000000000000000..28a81e2e855244f36a04afa225953891aa8b6256 --- /dev/null +++ b/pool/shard006/Python/0057999_samreader.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +""" +A reader of SAM format. + + import samreader + + # ... + # Attach it to stdin and print the header. + sam_reader = SamReader(sys.stdin) + print sam_reader.header + + # ... + # Open a SAM file and store each read starting position. + with fopen(myfile) as fp: + sr = SamReader(fp) + for rec in sr: + start_coord[rec.qname] = rec.pos + + +""" + + +class CigarString(object): + """ + A basic Cigar. + """ + + def __init__(self, cigar): + self.cigar = cigar + self.set_idx = 0 + + + def __str__(self): + return self.cigar + + +class SamHeader(object): + """ + Sam Header. + """ + + def __init__(self, file_handler): + self.header_lines = list() + self.curr_idx = 0 + self._source_fh = file_handler + self.end_header_pointer = self._load_header() + + def __iter__(self): + self.curr_idx = 0 + return self + + def next(self): + if self.curr_idx == len(self.header_lines): + raise StopIteration + + value = self.header_lines[self.curr_idx] + self.curr_idx += 1 + return value + + def __str__(self): + return "\n".join(self.header_lines) + + def _load_header(self): + fh = self._source_fh + fh.seek(0) + + last_pos = fh.tell() + line = fh.readline().rstrip() + while line[0] == '@': + self.header_lines.append(line) + last_pos = fh.tell() + line = fh.readline().rstrip() + + fh.seek(last_pos) + return last_pos + + +class SamRecord(object): + """ + Record Item for SAM. + """ + + def __init__(self, sam_line): + all_tokens = sam_line.rstrip().split('\t') + # NOTE: not care about optional fields for now. + self.rec_keys = ['QNAME', 'FLAG', 'RNAME', 'POS', 'MAPQ', 'CIGAR', 'RNEXT', 'PNEXT', 'TLEN', 'SEQ', 'QUAL'] + rec = {k: all_tokens[i] for i, k in enumerate(self.rec_keys)} + rec['POS'] = int(rec['POS']) + rec['MAPQ'] = int(rec['MAPQ']) + rec['CIGAR'] = CigarString(rec['CIGAR']) + rec['PNEXT'] = int(rec['PNEXT']) + rec['TLEN'] = int(rec['TLEN']) + self.record = rec + self.pos = rec['POS'] + self.qname = rec['QNAME'] + self.mapq = rec['MAPQ'] + self.rname = rec['RNAME'] + self.flag = int(rec['FLAG']) + + def __str__(self): + return "\t".join([str(self.record[self.rec_keys[i]]) for i in range(len(self.rec_keys))]) + + +class SamReader(object): + """ + Iterable for all SAM records. + """ + + def __init__(self, file_handle): + self._source_fh = file_handle + self.header = SamHeader(file_handle) + + def __iter__(self): + self._source_fh.seek(self.header.end_header_pointer) + return self + + def next(self): + line = self._source_fh.readline() + if not line: + raise StopIteration + + return SamRecord(line) + + + + + + diff --git a/pool/shard006/Python/0058000_packages.py b/pool/shard006/Python/0058000_packages.py new file mode 100644 index 0000000000000000000000000000000000000000..5f66bfa0cd3c0d5aa2861bdadc8899e17b8a3eab --- /dev/null +++ b/pool/shard006/Python/0058000_packages.py @@ -0,0 +1,100 @@ +# +# ovirt-host-deploy -- ovirt host deployer +# Copyright (C) 2012-2015 Red Hat, Inc. +# +# 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 +# + + +"""Serial console PKI artifacts.""" + + +import gettext + + +from otopi import plugin +from otopi import util + + +from ovirt_host_deploy import constants as odeploycons + + +def _(m): + return gettext.dgettext(message=m, domain='ovirt-host-deploy') + + +@util.export +class Plugin(plugin.PluginBase): + + def __init__(self, context): + super(Plugin, self).__init__(context=context) + self._enabled = False + + @plugin.event( + stage=plugin.Stages.STAGE_INIT, + ) + def _init(self): + self._enabled = False + self.environment.setdefault( + odeploycons.VMConsoleEnv.ENABLE, + False + ) + self.environment.setdefault( + odeploycons.VMConsoleEnv.SUPPORT, + odeploycons.Const.VMCONSOLE_SUPPORT_NONE + ) + + @plugin.event( + stage=plugin.Stages.STAGE_CUSTOMIZATION, + priority=plugin.Stages.PRIORITY_HIGH, + ) + def _customization(self): + if self.packager.queryPackages( + patterns=('ovirt-vmconsole-host',), + ): + self.environment[ + odeploycons.VMConsoleEnv.SUPPORT + ] = odeploycons.Const.VMCONSOLE_SUPPORT_V1 + + @plugin.event( + stage=plugin.Stages.STAGE_VALIDATION, + condition=lambda self: self.environment[ + odeploycons.VMConsoleEnv.ENABLE + ] + ) + def _validation(self): + self._enabled = True + + @plugin.event( + stage=plugin.Stages.STAGE_PACKAGES, + condition=lambda self: self._enabled, + ) + def _packages(self): + self.packager.installUpdate(('ovirt-vmconsole-host',)) + + @plugin.event( + stage=plugin.Stages.STAGE_CLOSEUP, + priority=plugin.Stages.PRIORITY_LOW, + condition=lambda self: self._enabled, + ) + def _start(self): + self.logger.info(_('Starting ovirt-vmconsole-host-sshd')) + if self.services.exists('ovirt-vmconsole-host-sshd'): + self.services.state('ovirt-vmconsole-host-sshd', False) + self.services.state('ovirt-vmconsole-host-sshd', True) + self.services.startup('ovirt-vmconsole-host-sshd', True) + + +# vim: expandtab tabstop=4 shiftwidth=4 diff --git a/pool/shard006/Python/0058002_binary_sensor.py b/pool/shard006/Python/0058002_binary_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd13adbde6b0e9207d264f6344545497c6570b4 --- /dev/null +++ b/pool/shard006/Python/0058002_binary_sensor.py @@ -0,0 +1,75 @@ +"""Binary sensor platform for Hass.io addons.""" +from __future__ import annotations + +from homeassistant.components.binary_sensor import ( + DEVICE_CLASS_UPDATE, + BinarySensorEntity, + BinarySensorEntityDescription, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from . import ADDONS_COORDINATOR +from .const import ATTR_UPDATE_AVAILABLE, DATA_KEY_ADDONS, DATA_KEY_OS +from .entity import HassioAddonEntity, HassioOSEntity + +ENTITY_DESCRIPTIONS = ( + BinarySensorEntityDescription( + device_class=DEVICE_CLASS_UPDATE, + entity_registry_enabled_default=False, + key=ATTR_UPDATE_AVAILABLE, + name="Update Available", + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + config_entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Binary sensor set up for Hass.io config entry.""" + coordinator = hass.data[ADDONS_COORDINATOR] + + entities = [] + + for entity_description in ENTITY_DESCRIPTIONS: + for addon in coordinator.data[DATA_KEY_ADDONS].values(): + entities.append( + HassioAddonBinarySensor( + addon=addon, + coordinator=coordinator, + entity_description=entity_description, + ) + ) + + if coordinator.is_hass_os: + entities.append( + HassioOSBinarySensor( + coordinator=coordinator, + entity_description=entity_description, + ) + ) + + async_add_entities(entities) + + +class HassioAddonBinarySensor(HassioAddonEntity, BinarySensorEntity): + """Binary sensor to track whether an update is available for a Hass.io add-on.""" + + @property + def is_on(self) -> bool: + """Return true if the binary sensor is on.""" + return self.coordinator.data[DATA_KEY_ADDONS][self._addon_slug][ + self.entity_description.key + ] + + +class HassioOSBinarySensor(HassioOSEntity, BinarySensorEntity): + """Binary sensor to track whether an update is available for Hass.io OS.""" + + @property + def is_on(self) -> bool: + """Return true if the binary sensor is on.""" + return self.coordinator.data[DATA_KEY_OS][self.entity_description.key] diff --git a/pool/shard006/Python/0058003_acm_device.py b/pool/shard006/Python/0058003_acm_device.py new file mode 100644 index 0000000000000000000000000000000000000000..e53819b64ca3769bacdc279bb0a95f5692965458 --- /dev/null +++ b/pool/shard006/Python/0058003_acm_device.py @@ -0,0 +1,64 @@ +import uuid, socket +import time +from serial import Serial + + +class AcmDevice: + """Wrapper for accessing usb serial devices.""" + + def __init__(self, port, baud): + self.__port = port + self.__baud = baud + self.__connection = Serial(port, baud, timeout=1) + self.motd = "\n".join([line.strip() for line in self.__connection.readlines()]) + self.__connection.timeout = 0 + if not (self.__connection.readable() and self.__connection.writable()): + raise IOError("Insufficient read/write permissions for port %s." % port) + + def disconnect(self, disconnected=False): + """Close the serial connection.""" + if not disconnected: + self.__connection.flushOutput() + self.__connection.close() + + def flush(self): + """Empties the output buffer.""" + self.__connection.flushOutput() + + def poll(self, wait_for_ok=True): + """Poll the serial port for new data.""" + buf = "" + response = [] + timeout = 1 + while True: + poll = self.__connection.readlines() + if poll: + for line in poll: + buf += line + if line.endswith("\n"): + response.append(buf.strip()) + buf = "" + if response and response[-1].startswith("ok"): + break + elif not wait_for_ok: + if timeout > 0: + timeout -= 1 + else: + break + if buf: + response.append(buf.strip()) + return tuple(response) + + def send(self, line): + """Send a line of text to the serial port. Will automatically + be terminated with a line end.""" + self.__connection.write(line.strip() + "\n\r") + + def make_uuid(self, firmware_name): + """Deterministically generatse a uuid from this connection. + Used by firmware drivers if the firmware doesn't specify one + through other means.""" + + namespace = uuid.uuid5(uuid.NAMESPACE_DNS, socket.getfqdn()) + return uuid.uuid5(namespace, firmware_name+"@"+self.__port) + diff --git a/pool/shard006/Python/0058006_euclidean_similarity.py b/pool/shard006/Python/0058006_euclidean_similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..53b73d5afbc0cff97707b3afc486f12ee8fa8ea6 --- /dev/null +++ b/pool/shard006/Python/0058006_euclidean_similarity.py @@ -0,0 +1,40 @@ +from decimal import Decimal, getcontext + +RATINGS = { + 'User1': { + 'Seven Samurai': 4, 'Taxi Driver': 3, + 'Usual Suspects, The': 3, 'Clerks': 1, + 'Batman Forever': 2, 'Nosferatu': 4}, + 'User2': { + 'Seven Samurai': 2, 'Taxi Driver': 4, + 'Usual Suspects, The': 5, 'Clerks': 3, + 'Batman Forever': 1}} + +getcontext().prec = 2 + + +def calc_euclidean_sim(user1, user2): + """ + Calculates the Euclidean Similarity between user1 and user2 + """ + + # Get the list of similar movies + similar_movies = [movie for movie in RATINGS[user1] + if movie in RATINGS[user2]] + + # If there are similar movies calculate similarity score, else similarity + # score is 0 + sim_score = 0 + + if len(similar_movies) != 0: + eucl_distance = Decimal(sum( + pow(RATINGS[user1][movie] - RATINGS[user2][movie], 2) + for movie in similar_movies)) + + sim_score = 1 / (1 + eucl_distance) + + return sim_score + +if __name__ == '__main__': + SIMILARITY_SCORES = calc_euclidean_sim("User1", "User2") + print SIMILARITY_SCORES diff --git a/pool/shard006/Python/0058009_utils.py b/pool/shard006/Python/0058009_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1ae6730effbb5aebd8f958e7367179c5cb784865 --- /dev/null +++ b/pool/shard006/Python/0058009_utils.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + utils.py + --------------------- + Date : September 2015 + Copyright : (C) 2015 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__ = 'September 2015' +__copyright__ = '(C) 2015, Victor Olaya' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + + +from qgis.utils import iface +from PyQt4 import QtGui +from processing.core.Processing import Processing +from processing.gui.MessageDialog import MessageDialog +from processing.gui.AlgorithmDialog import AlgorithmDialog + +algorithmsToolbar = None + + +def addAlgorithmEntry(algname, menuName, submenuName, actionText=None, icon=None, addButton=False): + alg = Processing.getAlgorithm(algname) + if alg is None: + return + if menuName: + menu = getMenu(menuName, iface.mainWindow().menuBar()) + submenu = getMenu(submenuName, menu) + action = QtGui.QAction(icon or alg.getIcon(), actionText or alg.name, iface.mainWindow()) + action.triggered.connect(lambda: _executeAlgorithm(alg)) + submenu.addAction(action) + if addButton: + global algorithmsToolbar + if algorithmsToolbar is None: + algorithmsToolbar = iface.addToolBar("ProcessingAlgorithms") + algorithmsToolbar.addAction(action) + + +def _executeAlgorithm(alg): + message = alg.checkBeforeOpeningParametersDialog() + if message: + dlg = MessageDialog() + dlg.setTitle(tr('Missing dependency')) + dlg.setMessage( + tr('

Missing dependency. This algorithm cannot ' + 'be run :-(

\n%s') % message) + dlg.exec_() + return + alg = alg.getCopy() + dlg = alg.getCustomParametersDialog() + if not dlg: + dlg = AlgorithmDialog(alg) + canvas = iface.mapCanvas() + prevMapTool = canvas.mapTool() + dlg.show() + dlg.exec_() + if canvas.mapTool() != prevMapTool: + try: + canvas.mapTool().reset() + except: + pass + canvas.setMapTool(prevMapTool) + + +def getMenu(name, parent): + menus = [c for c in parent.children() if isinstance(c, QtGui.QMenu)] + menusDict = {m.title(): m for m in menus} + if name in menusDict: + return menusDict[name] + else: + menu = QtGui.QMenu(name, parent) + parent.addMenu(menu) + return menu diff --git a/pool/shard006/Python/0058011_test_addressing.py b/pool/shard006/Python/0058011_test_addressing.py new file mode 100644 index 0000000000000000000000000000000000000000..925e7017d1a8966b85a2464effb6005f75953a1c --- /dev/null +++ b/pool/shard006/Python/0058011_test_addressing.py @@ -0,0 +1,180 @@ +# Copyright (c) "Neo4j" +# Neo4j Sweden AB [http://neo4j.com] +# +# This file is part of Neo4j. +# +# 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 socket import ( + AF_INET, + AF_INET6, +) +import unittest.mock as mock + +import pytest + +from neo4j import ( + Address, + IPv4Address, +) + + +mock_socket_ipv4 = mock.Mock() +mock_socket_ipv4.getpeername = lambda: ("127.0.0.1", 7687) # (address, port) + +mock_socket_ipv6 = mock.Mock() +mock_socket_ipv6.getpeername = lambda: ("[::1]", 7687, 0, 0) # (address, port, flow info, scope id) + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (("127.0.0.1", 7687), {"family": AF_INET, "host": "127.0.0.1", "port": 7687, "str": "127.0.0.1:7687", "repr": "IPv4Address(('127.0.0.1', 7687))"}), + (("localhost", 7687), {"family": AF_INET, "host": "localhost", "port": 7687, "str": "localhost:7687", "repr": "IPv4Address(('localhost', 7687))"}), + ((None, None), {"family": AF_INET, "host": None, "port": None, "str": "None:None", "repr": "IPv4Address((None, None))"}), + (("::1", 7687), {"family": AF_INET, "host": "::1", "port": 7687, "str": "::1:7687", "repr": "IPv4Address(('::1', 7687))"}), + (("::1", 7687, 0, 0), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 0, 0))"}), + (("::1", 7687, 1, 2), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 1, 2))"}), + ((None, None, None, None), {"family": AF_INET6, "host": None, "port": None, "str": "[None]:None", "repr": "IPv6Address((None, None, None, None))"}), + (Address(("127.0.0.1", 7687)), {"family": AF_INET, "host": "127.0.0.1", "port": 7687, "str": "127.0.0.1:7687", "repr": "IPv4Address(('127.0.0.1', 7687))"}), + (Address(("::1", 7687, 1, 2)), {"family": AF_INET6, "host": "::1", "port": 7687, "str": "[::1]:7687", "repr": "IPv6Address(('::1', 7687, 1, 2))"}), + ] +) +def test_address_initialization(test_input, expected): + address = Address(test_input) + assert address.family == expected["family"] + assert address.host == expected["host"] + assert address.port == expected["port"] + assert str(address) == expected["str"] + assert repr(address) == expected["repr"] + + +@pytest.mark.parametrize( + "test_input", + [ + Address(("127.0.0.1", 7687)), + Address(("127.0.0.1", 7687, 1, 2)), + ] +) +def test_address_init_with_address_object_returns_same_instance(test_input): + address = Address(test_input) + assert address is test_input + assert id(address) == id(test_input) + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (("127.0.0.1",), ValueError), + (("127.0.0.1", 7687, 0), ValueError), + (("[::1]", 7687, 0), ValueError), + (("[::1]", 7687, 0, 0, 0), ValueError), + ] +) +def test_address_initialization_with_incorrect_input(test_input, expected): + with pytest.raises(expected): + address = Address(test_input) + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (mock_socket_ipv4, ("127.0.0.1", 7687)), + (mock_socket_ipv6, ("[::1]", 7687, 0, 0)) + ] +) +def test_address_from_socket(test_input, expected): + + address = Address.from_socket(test_input) + assert address == expected + + +def test_address_from_socket_with_none(): + with pytest.raises(AttributeError): + address = Address.from_socket(None) + + +@pytest.mark.parametrize( + "test_input, expected", + [ + ("127.0.0.1:7687", ("127.0.0.1", 7687)), + ("localhost:7687", ("localhost", 7687)), + (":7687", ("localhost", 7687)), + (":", ("localhost", 0)), + ("", ("localhost", 0)), + (":abcd", ("localhost", "abcd")), + (" ", (" ", 0)), + ] +) +def test_address_parse_with_ipv4(test_input, expected): + parsed = Address.parse(test_input) + assert parsed == expected + + +@pytest.mark.parametrize( + "test_input, expected", + [ + ("[::1]:7687", ("::1", 7687, 0, 0)), + ("[::1]:abcd", ("::1", "abcd", 0, 0)), + ("[::1]:", ("::1", 0, 0, 0)), + ("[::1]", ("::1", 0, 0, 0)), + ] +) +def test_address_should_parse_ipv6(test_input, expected): + parsed = Address.parse(test_input) + assert parsed == expected + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (None, TypeError), + (123, TypeError), + (("127.0.0.1", 7687), TypeError), + (("[::1]", 7687, 1, 2), TypeError), + (Address(("127.0.0.1", 7687)), TypeError), + ] +) +def test_address_parse_with_invalid_input(test_input, expected): + with pytest.raises(expected): + parsed = Address.parse(test_input) + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (("localhost:7687 [::1]:7687",), 2), + (("localhost:7687", "[::1]:7687"), 2), + (("localhost:7687 localhost:7688", "[::1]:7687"), 3), + (("localhost:7687 localhost:7687", "[::1]:7687"), 3), + ] +) +def test_address_parse_list(test_input, expected): + addresses = Address.parse_list(*test_input) + assert len(addresses) == expected + + +@pytest.mark.parametrize( + "test_input, expected", + [ + (("localhost:7687", None), TypeError), + (("localhost:7687", 123), TypeError), + (("localhost:7687", ("127.0.0.1", 7687)), TypeError), + (("localhost:7687", ("[::1]", 7687, 1, 2)), TypeError), + (("localhost:7687", Address(("127.0.0.1", 7687))), TypeError), + ] +) +def test_address_parse_list_with_invalid_input(test_input, expected): + with pytest.raises(TypeError): + addresses = Address.parse_list(*test_input) diff --git a/pool/shard006/Python/0058012_streaming.py b/pool/shard006/Python/0058012_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..20b4403f3485aa2f05b093df6c3735b3c4abfce7 --- /dev/null +++ b/pool/shard006/Python/0058012_streaming.py @@ -0,0 +1,107 @@ +# -*- coding: utf8 -*- + +from tweepy.streaming import StreamListener +from tweepy import OAuthHandler +from tweepy import Stream + + +from tweepy.utils import import_simplejson +json = import_simplejson() + + +import psycopg2 + +from datetime import datetime + + +# +# Insert here your own twitter API credential +# +consumer_key="MY_TWITTER_CONSUMER_KEY" +consumer_secret="MY_TWITTER_CONSUMER_SECRET" + +access_token="MY_TWITTER_ACCESS_TOKEN" +access_token_secret="MY_TWITTER_ACCESS_TOKEN_SECRET" + + +# logging +log_start = str(datetime.now()) +pg_log = open('postgres.log', 'a') +pg_log.write('\n\n*** Starting logging at: %s ***\n\n' % log_start) +tweets_log = open('tweets.log', 'a') +tweets_log.write('\n\n*** Starting logging at: %s ***\n\n' % log_start) + + +def insert(user, tweet): + + try: + # Insert the database password + conn_string = "dbname='eleito' user='eleito' password='MY_PASSWORD'" + conn=psycopg2.connect(conn_string) + except: + pg_log.write("Unable to connect to the database.\n") + + cur = conn.cursor() + insert_str = """INSERT INTO tweets(profile, name, location, tweet) + VALUES ('%s', '%s', '%s', '%s') """ %(user['screen_name'], + user['name'], user['location'], unicode(tweet)) + + try: + pg_log.write("%s\n" % insert_str) + except UnicodeEncodeError: + pass + except UnicodeDecodeError: + pass + + try: + cur.execute(insert_str) + conn.commit() + except Exception as e: + # raise e + pg_log.write("I can't insert data on database\n") + + + + +class TweetListener(StreamListener): + """ A listener handles tweets are the received from the stream. + This is a basic listener that just prints received tweets to stdout. + + """ + def on_data(self, data): + + # Loads tweet data + data = json.loads(data) + user = data['user'] + tweet = data['text'] + + # Insert tweet on database + insert(user, tweet) + + try: + # write to log file + tweets_log.write("Person: %s - @%s\nFrom: %s\nTweet: %s\n" + % (user['name'], user['screen_name'], + user['location'],tweet)) + except UnicodeEncodeError: + pass + except UnicodeDecodeError: + pass + + return True + + def on_error(self, status): + print status + +if __name__ == '__main__': + + listener = TweetListener() + + auth = OAuthHandler(consumer_key, consumer_secret) + auth.set_access_token(access_token, access_token_secret) + + stream = Stream(auth, listener) + track_list = ['dilma','aecio','eduardo campos', + 'Dilma Rousseff', u'Aécio Neves', 'Eduardo Campos', + u'eleições 2014'] + stream.filter(track=track_list) diff --git a/pool/shard006/Python/0058013_mapping_helpers.py b/pool/shard006/Python/0058013_mapping_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..c1fd358bfe08fe15cbc8da7d9ec20fa865836236 --- /dev/null +++ b/pool/shard006/Python/0058013_mapping_helpers.py @@ -0,0 +1,61 @@ +# coding=utf-8 +"""This module contains shared internal functionality for mapping-related functions across arcpy versions.""" + +# Python 2/3 compatibility +# pylint: disable=wildcard-import,unused-wildcard-import,wrong-import-order,wrong-import-position,import-error,no-name-in-module +from __future__ import (absolute_import, division, print_function, unicode_literals) +from future.builtins.disabled import * +from future.builtins import * +from future.standard_library import install_aliases +install_aliases() +from future.moves.itertools import chain, zip_longest +from future.utils import iteritems +# pylint: enable=wildcard-import,unused-wildcard-import,wrong-import-order,wrong-import-position,import-error,no-name-in-module + +import re + + +def tokenise_datasource(x): + """Given a fully qualified feature class path, returns the feature class' schema, simple name and parent dataset (optional)""" + + regex = r"([\w\.]+)?(/|\\+)([\w\.]+$)" + parts = re.search(regex, x, re.MULTILINE | re.IGNORECASE) + + if parts and len(parts.groups()) > 2: + + dataset = None if ".gdb" in parts.group(1).lower() or ".sde" in parts.group(1).lower() else tokenise_table_name( + parts.group(1)) + table = tokenise_table_name(parts.group(3)) + + return { + "database": table["database"], + "schema": None if table["schema"] is None else table["schema"], + "dataSet": None if dataset is None else dataset["name"], + "table": table["name"] + } + + else: + return None + + +def tokenise_table_name(table_name): + """Given a feature class or feature dataset name, returns the schema (optional) and simple name""" + + dot_count = table_name.count(".") + + if dot_count == 2: + dot_pos = [pos for pos, char in enumerate(table_name) if char == "."] + + return { + "database": table_name[:dot_pos[0]], + "schema": table_name[dot_pos[0] + 1:dot_pos[1]], + "name": table_name[dot_pos[1] + 1:] + } + elif dot_count == 1: + return { + "database": None, + "schema": table_name[:table_name.index(".")], + "name": table_name[table_name.index(".") + 1:] + } + else: + return {"database": None, "schema": None, "name": table_name} diff --git a/pool/shard006/Python/0058015_toeav.py b/pool/shard006/Python/0058015_toeav.py new file mode 100644 index 0000000000000000000000000000000000000000..a0b2d77cf36dac6c0bc48609b12a952cb27f1fe6 --- /dev/null +++ b/pool/shard006/Python/0058015_toeav.py @@ -0,0 +1,84 @@ +""" + +.. function:: toeav(query) -> Entity Attribute Value table + +Transforms the query input results to an Entity Attribute Value model table. + +:Returned table schema: + ID, Attribute, Value + +Examples:: + + >>> table1(''' + ... James 10 2 + ... Mark 7 3 + ... Lila 74 1 + ... ''') + >>> sql("toeav select * from table1") + rid | colname | val + --------------------- + James | b | 10 + James | c | 2 + Mark | b | 7 + Mark | c | 3 + Lila | b | 74 + Lila | c | 1 +""" +import setpath +import vtbase +import functions +import gc + +### Classic stream iterator +registered=True + +class toEAV(vtbase.VT): + def VTiter(self, *parsedArgs,**envars): + largs, dictargs = self.full_parse(parsedArgs) + + if 'query' not in dictargs: + raise functions.OperatorError(__name__.rsplit('.')[-1],"No query argument ") + query = dictargs['query'] + + cur = envars['db'].cursor() + c = cur.execute(query, parse=False) + schema = [] + + try: + schema = [x[0] for x in cur.getdescriptionsafe()] + except StopIteration: + try: + raise + finally: + try: + c.close() + except: + pass + + yield [('rid',), ('colname',), ('val',)] + lr = len(schema) + while True: + l = c.next() + rid = l[0] + for i in xrange(1, lr): + yield (rid, schema[i], l[i]) + +def Source(): + return vtbase.VTGenerator(toEAV) + +if not ('.' in __name__): + """ + This is needed to be able to test the function, put it at the end of every + new function you create + """ + import sys + import setpath + from functions import * + testfunction() + if __name__ == "__main__": + reload(sys) + sys.setdefaultencoding('utf-8') + import doctest + doctest.testmod() + + diff --git a/pool/shard006/Python/0058016_media.py b/pool/shard006/Python/0058016_media.py new file mode 100644 index 0000000000000000000000000000000000000000..6782f0329e3696d87b5274e32e1d388e0f0d61ee --- /dev/null +++ b/pool/shard006/Python/0058016_media.py @@ -0,0 +1,52 @@ +from rest_framework.permissions import AllowAny, IsAdminUser +from rest_framework.response import Response +from rest_framework.request import Request +from rest_framework.views import APIView + +from rest_service.model.model import Model; + +class AllMedia(APIView): + permission_classes = (AllowAny, ) + + def get(self, request:Request): + return Response(status=200, data=Model.create_query()) + + +class NewMedia(APIView): + permission_classes = (IsAdminUser, ) + + def post(self, request:Request, format=None): + content = { + 'status': 'request was permitted' + } + return Response(content) + + +class DeleteMedia(APIView): + permission_classes = (IsAdminUser,) + + def delete(self, request:Request, format=None): + content = { + 'status': 'request was permitted' + } + return Response(content) + + +class FindMedia(APIView): + permission_classes = (AllowAny,) + + def get(self, request:Request, format=None): + content = { + 'status': 'request was permitted' + } + return Response(content) + + +class UpdateMedia(APIView): + permission_classes = (IsAdminUser,) + + def put(self, request:Request, format=None): + content = { + 'status': 'request was permitted' + } + return Response(content) diff --git a/pool/shard006/Python/0058018_parsing.py b/pool/shard006/Python/0058018_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..68d61a8026396911ad9c911537e15ea51a46c77a --- /dev/null +++ b/pool/shard006/Python/0058018_parsing.py @@ -0,0 +1,41 @@ +import clang.cindex +import os + +__all__ = ['ClangDiagnosticException', 'parse_string', 'parse'] + + +class ClangDiagnosticException(Exception): + """Encapsulates Clang diagnostics as an exception + """ + + def __init__(self, diagnostic): + self.diagnostic = diagnostic + + def __str__(self): + s = '' + for item in self.diagnostic: + s += '%s\n' % item + return s + + +def _ensure_parse_valid(tu): + if len(tu.diagnostics) > 0: + raise ClangDiagnosticException(tu.diagnostics) + return tu + + +def parse_string(contents, name='tmp.cpp', **kwargs): + """ Parse a string of C/C++ code + """ + idx = clang.cindex.Index.create() + tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs) + return _ensure_parse_valid(tu) + + +def parse(name, **kwargs): + """ Parse a C/C++ file + """ + idx = clang.cindex.Index.create() + assert os.path.exists(name) + tu = idx.parse(name, **kwargs) + return _ensure_parse_valid(tu) diff --git a/pool/shard006/Python/0058026_tfds_backend_writer_test.py b/pool/shard006/Python/0058026_tfds_backend_writer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..07e1164b531beeb79f5d2567e508b315007d5e54 --- /dev/null +++ b/pool/shard006/Python/0058026_tfds_backend_writer_test.py @@ -0,0 +1,255 @@ +# coding=utf-8 +# Copyright 2022 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 +# +# 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 tfds_backend_writer.""" + +import os +from typing import List + +from absl.testing import absltest +import dm_env +from envlogger import step_data +from envlogger.backends import rlds_utils +from envlogger.backends import tfds_backend_testlib +from envlogger.backends import tfds_backend_writer +import numpy as np +import tensorflow as tf +import tensorflow_datasets as tfds + + +def _create_step(value: int, step_type: dm_env.StepType) -> step_data.StepData: + return step_data.StepData( + action=value, timestep=dm_env.TimeStep(step_type, value, value, value)) + + +def _tfds_features() -> tfds.features.FeaturesDict: + return tfds.features.FeaturesDict({ + 'steps': + tfds.features.Dataset({ + 'observation': tf.int64, + 'action': tf.int64, + 'reward': tf.int64, + 'is_terminal': tf.bool, + 'is_first': tf.bool, + 'is_last': tf.bool, + 'discount': tf.int64, + }), + }) + + +class TfdsBackendWriterShardTest(absltest.TestCase): + + def test_add_episodes(self): + temp_dir = self.create_tempdir() + filepath = os.path.join(temp_dir.full_path, 'myfile') + writer = tf.io.TFRecordWriter(os.fspath(filepath)) + shard = tfds_backend_writer.Shard(writer=writer) + num_bytes = 0 + for i in range(2): + record_bytes = tf.train.Example( + features=tf.train.Features(feature={ + 'intlist': + tf.train.Feature(int64_list=tf.train.Int64List(value=[i])) + })).SerializeToString() + shard.add_episode(record_bytes) + num_bytes += len(record_bytes) + shard.close_writer() + + self.assertEqual(shard.num_episodes, 2) + self.assertEqual(shard.num_bytes, num_bytes) + + def _parse_example(ex): + return tf.io.parse_single_example( + ex, {'intlist': tf.io.FixedLenFeature([], dtype=tf.int64)}) + + read_ds = tf.data.TFRecordDataset([filepath]).map(_parse_example) + + num_elements = 0 + for index, value in enumerate(read_ds): + np.testing.assert_equal([index], value['intlist']) + num_elements += 1 + self.assertEqual(num_elements, 2) + + +class TfdsBackendWriterEpisodeTest(absltest.TestCase): + + def test_add_step(self): + episode = tfds_backend_writer.Episode( + _create_step(0, dm_env.StepType.FIRST)) + step = _create_step(1, dm_env.StepType.MID) + episode.add_step(step) + + self.assertEqual(episode.prev_step, step) + self.assertLen(episode.steps, 1) + + expected_rlds_step = { + 'observation': 0, + 'action': 1, + 'reward': 1, + 'discount': 1, + 'is_first': True, + 'is_last': False, + 'is_terminal': False, + } + + self.assertEqual(episode.steps[0], expected_rlds_step) + + def test_serialize_episode(self): + episode = tfds_backend_writer.Episode( + _create_step(0, dm_env.StepType.FIRST)) + episode.add_step(_create_step(1, dm_env.StepType.MID)) + episode.add_step(_create_step(2, dm_env.StepType.LAST)) + + features = _tfds_features() + serializer = tfds.core.example_serializer.ExampleSerializer( + features.get_serialized_info()) + serialized_example = episode.serialize_episode(features, serializer) + + parser = tfds.core.example_parser.ExampleParser( + features.get_serialized_info()) + episode = parser.parse_example(serialized_example) + + self.assertIsInstance(episode, dict) + self.assertIn('steps', episode) + + steps = tf.data.Dataset.from_tensor_slices(episode['steps']) + + steps_counter = 0 + for index, step in enumerate(steps): + self.assertEqual(index, step['observation']) + self.assertFalse(step['is_terminal']) + self.assertEqual(index == 0, step['is_first']) + self.assertEqual(index == 2, step['is_last']) + next_value = 0 if index == 2 else index + 1 + for key in ['action', 'reward', 'discount']: + self.assertEqual(next_value, step[key]) + steps_counter += 1 + self.assertEqual(steps_counter, 3) + + +class TfdsBackendWriterSplitTest(absltest.TestCase): + + def test_update_split(self): + split = tfds_backend_writer.Split( + tfds.core.splits.SplitInfo( + name='split_name', + shard_lengths=[3], + num_bytes=1, + filename_template=tfds.core.ShardedFileTemplate( + dataset_name='rlds_envlogger_builder', + split='split_name', + data_dir='', + filetype_suffix='tfrecord'))) + + shard = tfds_backend_writer.Shard(writer=None, num_episodes=10, num_bytes=1) + split.update(shard) + + self.assertEqual(split.complete_shards, 1) + self.assertEqual(split.ds_name, 'rlds_envlogger_builder') + self.assertEqual(split.info.name, 'split_name') + self.assertEqual(split.info.shard_lengths, [3, 10]) + self.assertEqual(split.info.num_bytes, 2) + + def test_get_shard_path(self): + split = tfds_backend_writer.Split( + tfds.core.splits.SplitInfo( + name='split_name', + shard_lengths=[3], + num_bytes=1, + filename_template=tfds.core.ShardedFileTemplate( + dataset_name='rlds_envlogger_builder', + split='split_name', + data_dir='', + filetype_suffix='tfrecord')), + complete_shards=10) + path = split.get_shard_path() + + self.assertEqual(path, 'rlds_envlogger_builder-split_name.tfrecord-00010') + + def test_get_split_dict(self): + split_info = tfds.core.splits.SplitInfo( + name='split_name', + shard_lengths=[3], + num_bytes=1, + filename_template=tfds.core.ShardedFileTemplate( + dataset_name='rlds_envlogger_builder', + split='split_name', + data_dir='', + filetype_suffix='tfrecord')) + split = tfds_backend_writer.Split(split_info, complete_shards=10) + split_dict = split.get_split_dict() + + self.assertEqual(split_dict['split_name'].num_examples, + split_info.num_examples) + self.assertEqual(split_dict['split_name'].num_shards, split_info.num_shards) + self.assertEqual(list(split_dict.keys()), ['split_name']) + + +class TfdsBackendWriterTest(absltest.TestCase): + + def _assert_steps(self, expected_steps: List[step_data.StepData], + steps: tf.data.Dataset): + steps = steps.as_numpy_iterator() + for idx, rlds_step in enumerate(steps): + step = expected_steps[idx + 1] if idx < len(expected_steps) - 1 else None + expected_step = rlds_utils.to_rlds_step(expected_steps[idx], step) + np.testing.assert_equal(expected_step, rlds_step) + + def test_backend_writer(self): + num_episodes = 5 + max_episodes_per_file = 3 + data_dir = self.create_tempdir(name='my_data_dir').full_path + expected_episodes = tfds_backend_testlib.generate_episode_data( + backend=tfds_backend_testlib.tfds_backend_catch_env( + data_directory=data_dir, + max_episodes_per_file=max_episodes_per_file), + num_episodes=num_episodes) + + builder = tfds.builder_from_directory(data_dir) + ds = builder.as_dataset(split='train') + + num_episodes = 0 + for index, episode in enumerate(ds): + self._assert_steps(expected_episodes[index], episode['steps']) + self.assertEqual(episode['episode_id'], index) + num_episodes += 1 + + self.assertLen(expected_episodes, num_episodes) + + def test_backend_writer_with_split_name(self): + num_episodes = 1 + max_episodes_per_file = 1 + data_dir = self.create_tempdir(name='my_data_dir').full_path + expected_episodes = tfds_backend_testlib.generate_episode_data( + backend=tfds_backend_testlib.tfds_backend_catch_env( + data_directory=data_dir, + max_episodes_per_file=max_episodes_per_file, + split_name='split'), + num_episodes=num_episodes) + + builder = tfds.builder_from_directory(data_dir) + ds = builder.as_dataset(split='split') + + num_episodes = 0 + for index, episode in enumerate(ds): + self._assert_steps(expected_episodes[index], episode['steps']) + self.assertEqual(episode['episode_id'], index) + num_episodes += 1 + + self.assertLen(expected_episodes, num_episodes) + + +if __name__ == '__main__': + absltest.main() diff --git a/pool/shard006/Python/0058027_app.py b/pool/shard006/Python/0058027_app.py new file mode 100644 index 0000000000000000000000000000000000000000..450d081d8b262dc19f1c6fb0715668f71fc40249 --- /dev/null +++ b/pool/shard006/Python/0058027_app.py @@ -0,0 +1,69 @@ +import multiprocessing +import os +import time +import threading + +from pinger.config import Config +from pinger.daemon import Daemon +from pinger.exceptions import ConfigException +from pinger.ext import ActionProvider +from pinger.workers import watcher, post_processor + +local = threading.local() + + +get_current_app = lambda: getattr(local, 'app', None) + + +class PingerApp(Daemon): + """ + Pinger's main app + """ + + config = None + + def load_config(self): + if 'PINGER_SETTINGS' not in os.environ: + raise ConfigException('The environment variable PINGER_SETTINGS must be set.') + self.config = Config(os.environ['PINGER_SETTINGS']) + + def load_plugins(self): + for plugin in self.config.get('plugins', []): + __import__(plugin) + + local.plugins = [] + + for Plugin in ActionProvider.plugins: + local.plugins.append(Plugin()) + + def set_thread_app(self): + local.app = self + + def run(self): + """ + Main loop + """ + while True: + processes = [] + result_queue = multiprocessing.Queue() + for i in self.config['websites']: + p = multiprocessing.Process(target=watcher, + args=(i['url'], + i['expected_content'], + i['expected_status_code'], + i.get('interval', self.config['default_interval']), + i.get('timeout', self.config['default_timeout']), + result_queue), + name=i['name']) + p.start() + processes.append(p) + + post_processor_process = multiprocessing.Process(target=post_processor, + args=(result_queue,)) + post_processor_process.start() + processes.append(post_processor_process) + + for process in processes: + process.join() + + time.sleep(self.config['main_process_sleep']) diff --git a/pool/shard006/Python/0058030_notebook.py b/pool/shard006/Python/0058030_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..6700107cce9d481c0413fa7a6cc88d6b8684b445 --- /dev/null +++ b/pool/shard006/Python/0058030_notebook.py @@ -0,0 +1,148 @@ +''' Functions useful for loading Bokeh code and data in Jupyter/Zeppelin notebooks. + +''' +from __future__ import absolute_import +from bokeh.core.templates import NOTEBOOK_CELL_OBSERVER + +_notebook_loaded = None + +def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): + ''' Prepare the IPython notebook for displaying Bokeh plots. + + Args: + resources (Resource, optional) : + how and where to load BokehJS from (default: CDN) + + verbose (bool, optional) : + whether to report detailed settings (default: False) + + hide_banner (bool, optional): + whether to hide the Bokeh banner (default: False) + + load_timeout (int, optional) : + Timeout in milliseconds when plots assume load timed out (default: 5000) + + notebook_type (string): + notebook_type (default: jupyter) + + .. warning:: + Clearing the output cell containing the published BokehJS + resources HTML code may cause Bokeh CSS styling to be removed. + + Returns: + None + + ''' + html, js = _load_notebook_html(resources, verbose, hide_banner, load_timeout) + if notebook_type=='jupyter': + publish_display_data({'text/html': html}) + publish_display_data({'application/javascript': js}) + else: + _publish_zeppelin_data(html, js) + + +FINALIZE_JS = """ +document.getElementById("%s").textContent = "BokehJS is loading..."; +""" + +def _publish_zeppelin_data(html, js): + print('%html ' + html) + print('%html ' + '") + +def _load_notebook_html(resources=None, verbose=False, hide_banner=False, + load_timeout=5000): + global _notebook_loaded + + from .. import __version__ + from ..core.templates import AUTOLOAD_NB_JS, NOTEBOOK_LOAD + from ..util.serialization import make_id + from ..util.compiler import bundle_all_models + from ..resources import CDN + + if resources is None: + resources = CDN + + if resources.mode == 'inline': + js_info = 'inline' + css_info = 'inline' + else: + js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files + css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files + + warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn'] + + if _notebook_loaded and verbose: + warnings.append('Warning: BokehJS previously loaded') + + _notebook_loaded = resources + + element_id = make_id() + + html = NOTEBOOK_LOAD.render( + element_id = element_id, + verbose = verbose, + js_info = js_info, + css_info = css_info, + bokeh_version = __version__, + warnings = warnings, + hide_banner = hide_banner, + ) + + custom_models_js = bundle_all_models() + + js = AUTOLOAD_NB_JS.render( + elementid = '' if hide_banner else element_id, + js_urls = resources.js_files, + css_urls = resources.css_files, + js_raw = resources.js_raw + [custom_models_js] + ([] if hide_banner else [FINALIZE_JS % element_id]), + css_raw = resources.css_raw_str, + force = True, + timeout = load_timeout + ) + + return html, js + +def publish_display_data(data, source='bokeh'): + ''' Compatibility wrapper for Jupyter ``publish_display_data`` + + Later versions of Jupyter remove the ``source`` (first) argument. This + function insulates Bokeh library code from this change. + + Args: + source (str, optional) : the source arg for Jupyter (default: "bokeh") + data (dict) : the data dict to pass to ``publish_display_data`` + Typically has the form ``{'text/html': html}`` + + ''' + import IPython.core.displaypub as displaypub + try: + displaypub.publish_display_data(source, data) + except TypeError: + displaypub.publish_display_data(data) + +def get_comms(target_name): + ''' Create a Jupyter comms object for a specific target, that can + be used to update Bokeh documents in the Jupyter notebook. + + Args: + target_name (str) : the target name the Comms object should connect to + + Returns + Jupyter Comms + + ''' + from ipykernel.comm import Comm + return Comm(target_name=target_name, data={}) + + +def watch_server_cells(inner_block): + ''' Installs a MutationObserver that detects deletion of cells using + io.server_cell to wrap the output. + + The inner_block is a Javascript block that is executed when a server + cell is removed from the DOM. The id of the destroyed div is in + scope as the variable destroyed_id. + ''' + js = NOTEBOOK_CELL_OBSERVER.render(inner_block=inner_block) + script = "".format(js=js) + publish_display_data({'text/html': script}, source='bokeh') diff --git a/pool/shard006/Python/0058050_video_detect_faces_gcs_test.py b/pool/shard006/Python/0058050_video_detect_faces_gcs_test.py new file mode 100644 index 0000000000000000000000000000000000000000..341073c9c42cb03e446c3874744840e5fd542715 --- /dev/null +++ b/pool/shard006/Python/0058050_video_detect_faces_gcs_test.py @@ -0,0 +1,32 @@ +# 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 +# +# 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 os + +import pytest + +import video_detect_faces_gcs + +RESOURCES = os.path.join(os.path.dirname(__file__), "resources") + + +@pytest.mark.flaky(max_runs=3, min_passes=1) +def test_detect_faces(capsys): + input_uri = "gs://cloud-samples-data/video/googlework_short.mp4" + + video_detect_faces_gcs.detect_faces(gcs_uri=input_uri) + + out, _ = capsys.readouterr() + + assert "Face detected:" in out diff --git a/pool/shard006/Python/0058063_GroupAnagrams.py b/pool/shard006/Python/0058063_GroupAnagrams.py new file mode 100644 index 0000000000000000000000000000000000000000..6615ef00998c88feaa0f3f457beb34b1a2b16a1c --- /dev/null +++ b/pool/shard006/Python/0058063_GroupAnagrams.py @@ -0,0 +1,36 @@ +''' +Created on 2016年2月27日 + +@author: Darren +''' +''' +Given an array of strings, group anagrams together. + +For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], +Return: + +[ + ["ate", "eat","tea"], + ["nat","tan"], + ["bat"] +] +Note: +For the return value, each inner list's elements must follow the lexicographic order. +All inputs will be in lower-case. +''' +class Solution(object): + def groupAnagrams(self, strs): + """ + :type strs: List[str] + :rtype: List[List[str]] + """ + d={} + for string in strs: + sorted_s="".join(sorted(string)) + if sorted_s not in d: + d[sorted_s]=[] + d[sorted_s].append(string) + res=[] + for key in d.keys(): + res.append(sorted(d[key])) + return res \ No newline at end of file diff --git a/pool/shard006/Python/0058067_0001_initial.py b/pool/shard006/Python/0058067_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..4060fd60def974f175ce8c2fa9c50b44fff57c8f --- /dev/null +++ b/pool/shard006/Python/0058067_0001_initial.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.5 on 2016-05-08 04:01 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Doctor', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('slug', models.SlugField(verbose_name='slug')), + ('address', models.CharField(blank=True, max_length=255, verbose_name='endereço')), + ('neighborhood', models.CharField(blank=True, max_length=255, verbose_name='bairro')), + ('city', models.CharField(blank=True, max_length=255, verbose_name='cidade')), + ('phone', models.CharField(blank=True, max_length=255, verbose_name='telefone')), + ('specialization', models.CharField(blank=True, max_length=255, verbose_name='especialização')), + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'médico', + 'verbose_name_plural': 'médicos', + }, + ), + ] diff --git a/pool/shard006/Python/0058068_uploading.py b/pool/shard006/Python/0058068_uploading.py new file mode 100644 index 0000000000000000000000000000000000000000..3a91549384e9f70690d3fb0d33e209c5a0f9db83 --- /dev/null +++ b/pool/shard006/Python/0058068_uploading.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +#------------------------------------------------------------ +# seriesly - XBMC Plugin +# Conector para uploading +# http://blog.tvalacarta.info/plugin-xbmc/seriesly/ +#------------------------------------------------------------ + +import urlparse,urllib2,urllib,re +import os + +from core import scrapertools +from core import logger +from core import config + +def get_video_url( page_url , premium = False , user="" , password="", video_password="" ): + logger.info("[uploading.py] get_video_url(page_url='%s')" % page_url) + video_urls = [] + return video_urls + +# Encuentra vídeos del servidor en el texto pasado +def find_videos(data): + encontrados = set() + devuelve = [] + + # http://uploading.com/files/get/686bm1b2 + patronvideos = '(uploading.com/files/get/[a-z0-9]+)' + logger.info("[uploading.py] find_videos #"+patronvideos+"#") + matches = re.compile(patronvideos,re.DOTALL).findall(data) + + for match in matches: + titulo = "[uploading]" + url = "http://"+match + if url not in encontrados: + logger.info(" url="+url) + devuelve.append( [ titulo , url , 'uploading' ] ) + encontrados.add(url) + else: + logger.info(" url duplicada="+url) + + return devuelve diff --git a/pool/shard006/Python/0058071_glance.py b/pool/shard006/Python/0058071_glance.py new file mode 100644 index 0000000000000000000000000000000000000000..52e699857b35dd73d9798443ebb6099cbfbf0a4e --- /dev/null +++ b/pool/shard006/Python/0058071_glance.py @@ -0,0 +1,125 @@ +# -*- encoding: utf-8 -*- +# +# Copyright © 2012 New Dream Network, LLC (DreamHost) +# +# Author: Julien Danjou +# +# 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. +"""Common code for working with images +""" + +from __future__ import absolute_import + +import itertools +import glanceclient + +from ceilometer import counter +from ceilometer.openstack.common import timeutils +from ceilometer import plugin + + +class _Base(plugin.PollsterBase): + + @staticmethod + def get_glance_client(ksclient): + endpoint = ksclient.service_catalog.url_for( + service_type='image', + endpoint_type='internalURL') + + # hard-code v1 glance API version selection while v2 API matures + return glanceclient.Client('1', endpoint, + token=ksclient.auth_token) + + def iter_images(self, ksclient): + """Iterate over all images.""" + client = self.get_glance_client(ksclient) + #TODO(eglynn): use pagination to protect against unbounded + # memory usage + rawImageList = list(itertools.chain( + client.images.list(filters={"is_public": True}), + #TODO(eglynn): extend glance API with all_tenants logic to + # avoid second call to retrieve private images + client.images.list(filters={"is_public": False}))) + + # When retrieving images from glance, glance will check + # whether the user is of 'admin_role' which is + # configured in glance-api.conf. If the user is of + # admin_role, and is querying public images(which means + # that the 'is_public' param is set to be True), + # glance will ignore 'is_public' parameter and returns + # all the public images together with private images. + # As a result, if the user/tenant has an admin role + # for ceilometer to collect image list, + # the _Base.iter_images method will return a image list + # which contains duplicate images. Add the following + # code to avoid recording down duplicate image events. + imageIdSet = set(image.id for image in rawImageList) + + for image in rawImageList: + if image.id in imageIdSet: + imageIdSet -= set([image.id]) + yield image + + @staticmethod + def extract_image_metadata(image): + return dict((k, getattr(image, k)) + for k in + [ + "status", + "is_public", + "name", + "deleted", + "container_format", + "created_at", + "disk_format", + "updated_at", + "properties", + "min_disk", + "protected", + "checksum", + "deleted_at", + "min_ram", + "size", + ]) + + +class ImagePollster(_Base): + + @staticmethod + def get_counter_names(): + return ['image', 'image.size'] + + def get_counters(self, manager): + for image in self.iter_images(manager.keystone): + yield counter.Counter( + name='image', + type=counter.TYPE_GAUGE, + unit='image', + volume=1, + user_id=None, + project_id=image.owner, + resource_id=image.id, + timestamp=timeutils.isotime(), + resource_metadata=self.extract_image_metadata(image), + ) + yield counter.Counter( + name='image.size', + type=counter.TYPE_GAUGE, + unit='B', + volume=image.size, + user_id=None, + project_id=image.owner, + resource_id=image.id, + timestamp=timeutils.isotime(), + resource_metadata=self.extract_image_metadata(image), + ) diff --git a/pool/shard006/Python/0058072_0002_hydroshare_disable_autosync.py b/pool/shard006/Python/0058072_0002_hydroshare_disable_autosync.py new file mode 100644 index 0000000000000000000000000000000000000000..a8618ddbafe81a0139e814b2c9424f8a65f8255d --- /dev/null +++ b/pool/shard006/Python/0058072_0002_hydroshare_disable_autosync.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +from django.db import migrations, models + + +def disable_hydroshare_autosync(apps, schema_editor): + HydroShareResource = apps.get_model('export', 'HydroShareResource') + HydroShareResource.objects.all().update(autosync=False) + + +class Migration(migrations.Migration): + + dependencies = [ + ('export', '0001_hydroshareresource'), + ] + + operations = [ + migrations.RunPython(disable_hydroshare_autosync) + ] diff --git a/pool/shard006/Python/0058075_editor.py b/pool/shard006/Python/0058075_editor.py new file mode 100644 index 0000000000000000000000000000000000000000..315723e004d0920c804924cfa31fd53c0033319a --- /dev/null +++ b/pool/shard006/Python/0058075_editor.py @@ -0,0 +1,97 @@ +from webapp2_extras import security + +from handlers import base +from library import messages +from models.profile import Profile +from forms.profile import ProfileForm +from forms.profile_update import ProfileUpdateForm + + +class EditorHandler(base.BaseHandler): + + def create(self): + form = ProfileForm(self.request.POST) + + if self.request.method == 'POST' and form.validate(): + name = ' '.join([form.first_name.data, + form.last_name.data]) + + # Create the webapp2_extras.auth user. + model = self.auth.store.user_model + ok, user = model.create_user(form.data['email'], + password_raw=form.data['password']) + + if not ok: + self.session.add_flash(messages.EDITOR_CREATE_ERROR, + level='error') + return self.redirect_to('editors.list') + + # Create the profile. + profile = Profile(name=name, + email=form.data['email'], + is_editor=True, + auth_user_id=user.key.id()) + profile.put() + + # Force reload of profile object + Profile.get(profile.key()) + + self.session.add_flash(messages.EDITOR_CREATE_SUCCESS) + return self.redirect_to('editors.list') + + return self.render_to_response('editors/form.haml', {'form': form}) + + def delete(self, id): + editor = Profile.get_by_id(int(id)) + if not editor or not editor.is_editor: + self.session.add_flash(messages.EDITOR_NOT_FOUND, level='error') + return self.redirect_to('editors.list') + + editor.delete() + self.session.add_flash(messages.EDITOR_DELETE_SUCCESS) + return self.redirect_to('editors.list') + + def list(self): + editors = Profile.all().filter('is_editor = ', True) + return self.render_to_response('editors/list.haml', {'editors': editors}) + + def update(self, id): + editor = Profile.get_by_id(int(id)) + if not editor or not editor.is_editor: + self.session.add_flash(messages.EDITOR_NOT_FOUND, level='error') + self.redirect_to('editors.list') + + form = ProfileUpdateForm(self.request.POST, obj=editor) + form.user_id = editor.key().id() + + if self.request.method == 'GET': + names = editor.name.split(' ') + form.first_name.data = names[0] + form.last_name.data = names[1] + + form.profile_id = editor.key().id() + + if self.request.method == 'POST' and form.validate(): + # Access to the user model is only needed in this section. + user = editor.get_auth_user() + editor.name = ' '.join([form.first_name.data, form.last_name.data]) + + if form.email.data != editor.email: + user.auth_ids.remove(editor.email) + user.auth_ids.append(form.email.data) + editor.email = form.email.data + + if form.password.data: + user.password = security.generate_password_hash(form.password.data, + length=12) + + editor.put() + user.put() + + # Force reload of profile object + Profile.get(editor.key()) + self.session.add_flash(messages.EDITOR_UPDATE_SUCCESS) + + return self.redirect_to('editors.list') + + return self.render_to_response('editors/form.haml', {'form': form}) diff --git a/pool/shard006/Python/0058077_sentry.py b/pool/shard006/Python/0058077_sentry.py new file mode 100644 index 0000000000000000000000000000000000000000..63bddb14f189aa315245ed87f8f43134abf2573e --- /dev/null +++ b/pool/shard006/Python/0058077_sentry.py @@ -0,0 +1,39 @@ +from __future__ import absolute_import, unicode_literals + +__all__ = ['SentryNotifier'] + +from freight import http +from freight.models import App, TaskStatus + +from .base import Notifier, NotifierEvent + + +class SentryNotifier(Notifier): + def get_options(self): + return { + 'webhook_url': {'required': True}, + } + + def send(self, task, config, event): + if task.status != TaskStatus.finished and event != NotifierEvent.TASK_STARTED: + return + + webhook_url = config['webhook_url'] + + app = App.query.get(task.app_id) + + payload = { + 'number': task.number, + 'app_name': app.name, + 'task_name': task.name, + 'env': task.environment, + 'ref': task.ref, + 'sha': task.sha, + 'duration': task.duration, + 'event': 'started' if event == NotifierEvent.TASK_STARTED else 'finished', + 'dateStarted': task.date_started.isoformat() + 'Z' if task.date_started else None, + 'dateFinished': task.date_finished.isoformat() + 'Z' if task.date_finished else None, + 'link': http.absolute_uri('/tasks/{}/'.format(task.id)), + } + + http.post(webhook_url, json=payload) diff --git a/pool/shard006/Python/0058079_normal.py b/pool/shard006/Python/0058079_normal.py new file mode 100644 index 0000000000000000000000000000000000000000..7fbbf22455f12f3fc74a9a844ea06f8d7775da26 --- /dev/null +++ b/pool/shard006/Python/0058079_normal.py @@ -0,0 +1,249 @@ +# 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. +# ============================================================================== +"""The Normal (Gaussian) distribution class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +from tensorflow.contrib.bayesflow.python.ops import special_math +from tensorflow.contrib.distributions.python.ops import distribution +from tensorflow.contrib.distributions.python.ops import kullback_leibler +from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util +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_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops + + +class Normal(distribution.Distribution): + """The scalar Normal distribution with mean and stddev parameters mu, sigma. + + #### Mathematical details + + The PDF of this distribution is: + + ```f(x) = sqrt(1/(2*pi*sigma^2)) exp(-(x-mu)^2/(2*sigma^2))``` + + #### Examples + + Examples of initialization of one or a batch of distributions. + + ```python + # Define a single scalar Normal distribution. + dist = tf.contrib.distributions.Normal(mu=0., sigma=3.) + + # Evaluate the cdf at 1, returning a scalar. + dist.cdf(1.) + + # Define a batch of two scalar valued Normals. + # The first has mean 1 and standard deviation 11, the second 2 and 22. + dist = tf.contrib.distributions.Normal(mu=[1, 2.], sigma=[11, 22.]) + + # Evaluate the pdf of the first distribution on 0, and the second on 1.5, + # returning a length two tensor. + dist.pdf([0, 1.5]) + + # Get 3 samples, returning a 3 x 2 tensor. + dist.sample([3]) + ``` + + Arguments are broadcast when possible. + + ```python + # Define a batch of two scalar valued Normals. + # Both have mean 1, but different standard deviations. + dist = tf.contrib.distributions.Normal(mu=1., sigma=[11, 22.]) + + # Evaluate the pdf of both distributions on the same point, 3.0, + # returning a length 2 tensor. + dist.pdf(3.0) + ``` + + """ + + def __init__(self, + mu, + sigma, + validate_args=False, + allow_nan_stats=True, + name="Normal"): + """Construct Normal distributions with mean and stddev `mu` and `sigma`. + + The parameters `mu` and `sigma` must be shaped in a way that supports + broadcasting (e.g. `mu + sigma` is a valid operation). + + Args: + mu: Floating point tensor, the means of the distribution(s). + sigma: Floating point tensor, the stddevs of the distribution(s). + sigma must contain only positive values. + validate_args: `Boolean`, default `False`. Whether to assert that + `sigma > 0`. If `validate_args` is `False`, correct output is not + guaranteed when input is invalid. + allow_nan_stats: `Boolean`, default `True`. If `False`, raise an + exception if a statistic (e.g. mean/mode/etc...) is undefined for any + batch member. If `True`, batch members with valid parameters leading to + undefined statistics will return NaN for this statistic. + name: The name to give Ops created by the initializer. + + Raises: + TypeError: if mu and sigma are different dtypes. + """ + parameters = locals() + parameters.pop("self") + with ops.name_scope(name, values=[mu, sigma]) as ns: + with ops.control_dependencies([check_ops.assert_positive(sigma)] if + validate_args else []): + self._mu = array_ops.identity(mu, name="mu") + self._sigma = array_ops.identity(sigma, name="sigma") + contrib_tensor_util.assert_same_float_dtype((self._mu, self._sigma)) + super(Normal, self).__init__( + dtype=self._sigma.dtype, + is_continuous=True, + is_reparameterized=True, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._mu, self._sigma], + name=ns) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("mu", "sigma"), ([ops.convert_to_tensor( + sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def mu(self): + """Distribution parameter for the mean.""" + return self._mu + + @property + def sigma(self): + """Distribution parameter for standard deviation.""" + return self._sigma + + def _batch_shape(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.mu), array_ops.shape(self.sigma)) + + def _get_batch_shape(self): + return array_ops.broadcast_static_shape( + self._mu.get_shape(), self.sigma.get_shape()) + + def _event_shape(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _get_event_shape(self): + return tensor_shape.scalar() + + def _sample_n(self, n, seed=None): + shape = array_ops.concat(([n], array_ops.shape(self.mean())), 0) + sampled = random_ops.random_normal( + shape=shape, mean=0, stddev=1, dtype=self.mu.dtype, seed=seed) + return sampled * self.sigma + self.mu + + def _log_prob(self, x): + return (-0.5 * math.log(2. * math.pi) - math_ops.log(self.sigma) + -0.5 * math_ops.square(self._z(x))) + + def _prob(self, x): + return math_ops.exp(self._log_prob(x)) + + def _log_cdf(self, x): + return special_math.log_ndtr(self._z(x)) + + def _cdf(self, x): + return special_math.ndtr(self._z(x)) + + def _log_survival_function(self, x): + return special_math.log_ndtr(-self._z(x)) + + def _survival_function(self, x): + return special_math.ndtr(-self._z(x)) + + def _entropy(self): + # Use broadcasting rules to calculate the full broadcast sigma. + sigma = self.sigma * array_ops.ones_like(self.mu) + return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(sigma) + + def _mean(self): + return self.mu * array_ops.ones_like(self.sigma) + + def _variance(self): + return math_ops.square(self.std()) + + def _std(self): + return self.sigma * array_ops.ones_like(self.mu) + + def _mode(self): + return self._mean() + + def _z(self, x): + """Standardize input `x` to a unit normal.""" + with ops.name_scope("standardize", values=[x]): + return (x - self.mu) / self.sigma + + +class NormalWithSoftplusSigma(Normal): + """Normal with softplus applied to `sigma`.""" + + def __init__(self, + mu, + sigma, + validate_args=False, + allow_nan_stats=True, + name="NormalWithSoftplusSigma"): + parameters = locals() + parameters.pop("self") + with ops.name_scope(name, values=[sigma]) as ns: + super(NormalWithSoftplusSigma, self).__init__( + mu=mu, + sigma=nn.softplus(sigma, name="softplus_sigma"), + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + name=ns) + self._parameters = parameters + + +@kullback_leibler.RegisterKL(Normal, Normal) +def _kl_normal_normal(n_a, n_b, name=None): + """Calculate the batched KL divergence KL(n_a || n_b) with n_a and n_b Normal. + + Args: + n_a: instance of a Normal distribution object. + n_b: instance of a Normal distribution object. + name: (optional) Name to use for created operations. + default is "kl_normal_normal". + + Returns: + Batchwise KL(n_a || n_b) + """ + with ops.name_scope(name, "kl_normal_normal", [n_a.mu, n_b.mu]): + one = constant_op.constant(1, dtype=n_a.dtype) + two = constant_op.constant(2, dtype=n_a.dtype) + half = constant_op.constant(0.5, dtype=n_a.dtype) + s_a_squared = math_ops.square(n_a.sigma) + s_b_squared = math_ops.square(n_b.sigma) + ratio = s_a_squared / s_b_squared + return (math_ops.square(n_a.mu - n_b.mu) / (two * s_b_squared) + + half * (ratio - one - math_ops.log(ratio))) diff --git a/pool/shard006/Python/0058082_swift.py b/pool/shard006/Python/0058082_swift.py new file mode 100644 index 0000000000000000000000000000000000000000..6b97616aad3f1489a5b0a976c3db4a2c12c8f599 --- /dev/null +++ b/pool/shard006/Python/0058082_swift.py @@ -0,0 +1,237 @@ +# Copyright 2013 Hewlett-Packard Development Company, L.P. +# 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 hashlib + +from trove.guestagent.strategies.storage import base +from trove.openstack.common import log as logging +from trove.openstack.common.gettextutils import _ # noqa +from trove.common.remote import create_swift_client +from trove.common import cfg + +LOG = logging.getLogger(__name__) +CONF = cfg.CONF + +CHUNK_SIZE = CONF.backup_chunk_size +MAX_FILE_SIZE = CONF.backup_segment_max_size +BACKUP_CONTAINER = CONF.backup_swift_container + + +class DownloadError(Exception): + """Error running the Swift Download Command.""" + + +class SwiftDownloadIntegrityError(Exception): + """Integrity error while running the Swift Download Command.""" + + +class StreamReader(object): + """Wrap the stream from the backup process and chunk it into segements.""" + + def __init__(self, stream, filename, max_file_size=MAX_FILE_SIZE): + self.stream = stream + self.filename = filename + self.container = BACKUP_CONTAINER + self.max_file_size = max_file_size + self.segment_length = 0 + self.process = None + self.file_number = 0 + self.end_of_file = False + self.end_of_segment = False + self.segment_checksum = hashlib.md5() + + @property + def base_filename(self): + """Filename with extensions removed.""" + return self.filename.split('.')[0] + + @property + def segment(self): + return '%s_%08d' % (self.base_filename, self.file_number) + + @property + def prefix(self): + return '%s/%s_' % (self.container, self.base_filename) + + def read(self, chunk_size=CHUNK_SIZE): + if self.end_of_segment: + self.segment_length = 0 + self.segment_checksum = hashlib.md5() + self.end_of_segment = False + + # Upload to a new file if we are starting or too large + if self.segment_length > (self.max_file_size - chunk_size): + self.file_number += 1 + self.end_of_segment = True + return '' + + chunk = self.stream.read(chunk_size) + if not chunk: + self.end_of_file = True + return '' + + self.segment_checksum.update(chunk) + self.segment_length += len(chunk) + return chunk + + +class SwiftStorage(base.Storage): + """Implementation of Storage Strategy for Swift.""" + __strategy_name__ = 'swift' + + def __init__(self, *args, **kwargs): + super(SwiftStorage, self).__init__(*args, **kwargs) + self.connection = create_swift_client(self.context) + + def save(self, filename, stream): + """Persist information from the stream to swift. + + The file is saved to the location /. + The filename is defined on the backup runner manifest property + which is typically in the format '..gz' + """ + + # Create the container if it doesn't already exist + self.connection.put_container(BACKUP_CONTAINER) + + # Swift Checksum is the checksum of the concatenated segment checksums + swift_checksum = hashlib.md5() + + # Wrap the output of the backup process to segment it for swift + stream_reader = StreamReader(stream, filename) + + url = self.connection.url + # Full location where the backup manifest is stored + location = "%s/%s/%s" % (url, BACKUP_CONTAINER, filename) + + # Read from the stream and write to the container in swift + while not stream_reader.end_of_file: + etag = self.connection.put_object(BACKUP_CONTAINER, + stream_reader.segment, + stream_reader) + + segment_checksum = stream_reader.segment_checksum.hexdigest() + + # Check each segment MD5 hash against swift etag + # Raise an error and mark backup as failed + if etag != segment_checksum: + LOG.error(_("Error saving data segment to swift. " + "ETAG: %(tag)s Segment MD5: %(checksum)s."), + {'tag': etag, 'checksum': segment_checksum}) + return False, "Error saving data to Swift!", None, location + + swift_checksum.update(segment_checksum) + + # Create the manifest file + # We create the manifest file after all the segments have been uploaded + # so a partial swift object file can't be downloaded; if the manifest + # file exists then all segments have been uploaded so the whole backup + # file can be downloaded. + headers = {'X-Object-Manifest': stream_reader.prefix} + # The etag returned from the manifest PUT is the checksum of the + # manifest object (which is empty); this is not the checksum we want + self.connection.put_object(BACKUP_CONTAINER, + filename, + contents='', + headers=headers) + + resp = self.connection.head_object(BACKUP_CONTAINER, filename) + # swift returns etag in double quotes + # e.g. '"dc3b0827f276d8d78312992cc60c2c3f"' + etag = resp['etag'].strip('"') + + # Check the checksum of the concatenated segment checksums against + # swift manifest etag. + # Raise an error and mark backup as failed + final_swift_checksum = swift_checksum.hexdigest() + if etag != final_swift_checksum: + LOG.error( + _("Error saving data to swift. Manifest " + "ETAG: %(tag)s Swift MD5: %(checksum)s"), + {'tag': etag, 'checksum': final_swift_checksum}) + return False, "Error saving data to Swift!", None, location + + return (True, "Successfully saved data to Swift!", + final_swift_checksum, location) + + def _explodeLocation(self, location): + storage_url = "/".join(location.split('/')[:-2]) + container = location.split('/')[-2] + filename = location.split('/')[-1] + return storage_url, container, filename + + def _verify_checksum(self, etag, checksum): + etag_checksum = etag.strip('"') + if etag_checksum != checksum: + msg = (_("Original checksum: %(original)s does not match" + " the current checksum: %(current)s") % + {'original': etag_checksum, 'current': checksum}) + LOG.error(msg) + raise SwiftDownloadIntegrityError(msg) + return True + + def load(self, location, backup_checksum): + """Restore a backup from the input stream to the restore_location.""" + storage_url, container, filename = self._explodeLocation(location) + + headers, info = self.connection.get_object(container, filename, + resp_chunk_size=CHUNK_SIZE) + + if CONF.verify_swift_checksum_on_restore: + self._verify_checksum(headers.get('etag', ''), backup_checksum) + + return info + + def _get_attr(self, original): + """Get a friendly name from an object header key.""" + key = original.replace('-', '_') + key = key.replace('x_object_meta_', '') + return key + + def _set_attr(self, original): + """Return a swift friendly header key.""" + key = original.replace('_', '-') + return 'X-Object-Meta-%s' % key + + def load_metadata(self, location, backup_checksum): + """Load metadata from swift.""" + + storage_url, container, filename = self._explodeLocation(location) + + headers = self.connection.head_object(container, filename) + + if CONF.verify_swift_checksum_on_restore: + self._verify_checksum(headers.get('etag', ''), backup_checksum) + + _meta = {} + for key, value in headers.iteritems(): + if key.startswith('x-object-meta'): + _meta[self._get_attr(key)] = value + + return _meta + + def save_metadata(self, location, metadata={}): + """Save metadata to a swift object.""" + + storage_url, container, filename = self._explodeLocation(location) + + _headers = self.connection.head_object(container, filename) + headers = {'X-Object-Manifest': _headers.get('x-object-manifest')} + for key, value in metadata.iteritems(): + headers[self._set_attr(key)] = value + + LOG.info(_("Writing metadata: %s"), str(headers)) + self.connection.post_object(container, filename, headers=headers) diff --git a/pool/shard006/Python/0058096_plot1.py b/pool/shard006/Python/0058096_plot1.py new file mode 100644 index 0000000000000000000000000000000000000000..484e8d5fb67f284135fcdddb35f318d9e8bba605 --- /dev/null +++ b/pool/shard006/Python/0058096_plot1.py @@ -0,0 +1,11 @@ +from bokeh.plotting import figure, output_file, show + +x = [1, 2, 3, 4, 5, 6, 7, 8] +y = [.7, 1.4, 2.1, 3, 3.85, 4.55, 5.8, 6.45] + +p = figure(title='Mean wt increased vs. time', + x_axis_label='Time in days', + y_axis_label='% Mean WT increased') +p.circle(x, y, legend='Subject 1', size=10) +output_file('test.html') +show(p) diff --git a/pool/shard006/Python/0058101_07.py b/pool/shard006/Python/0058101_07.py new file mode 100644 index 0000000000000000000000000000000000000000..08ee38c0e64e819474f03f9fc78978f006c69180 --- /dev/null +++ b/pool/shard006/Python/0058101_07.py @@ -0,0 +1,41 @@ +class Dog(): + def _init(self, dogname, dogcolor, dogheight, dogbuild, dogmood, dogage): + self.name = dogname + self.color = dogcolor + self.height = dogheight + self.build = dogbuild + self.mood = dogmood + self.age = dogage + self.Hungry = False + self.Tired = False + def Eat(self): + if self.Hungry: + print('yum yum yum ...NUm nUM') + self.Hungry = False + else: + print('sniff sniff...NOT Hungty') + def Sleep(self): + print('zzzzzzzzzzzzzzzz') + self.Tired = False + def Bark(self): + if self.mood == 'Grumpy': + print('GRRRRR...woof woof') + elif self.mood == 'Laid Back': + print('yawn...ok...woof') + elif self.mood == 'Crazy': + print('Bark Bark Bark Bark') + else: + print('woof woof woof') +def main(): + beagle = Dog('Archie','Brown','short','Chubby','Grumpy',12) + print('My name is {}'.format(beagle.name)) + print('My color is {}'.format(beagle.color)) + print('My mood is {}'.format(beagle.mood)) + print('i am hungry {}'.format(beagle.Hungry)) + + beagle.Eat() + beagle.Hungry = True + beagle.Eat() + beagle.Bark() +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard006/Python/0058103_notification_sample_base.py b/pool/shard006/Python/0058103_notification_sample_base.py new file mode 100644 index 0000000000000000000000000000000000000000..b13886a4cae0a5277349517089ed49341f511a09 --- /dev/null +++ b/pool/shard006/Python/0058103_notification_sample_base.py @@ -0,0 +1,191 @@ +# 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 mock +import os +import time + +from oslo_config import cfg +from oslo_serialization import jsonutils +from oslo_utils import fixture as utils_fixture + +from nova import test +from nova.tests import fixtures as nova_fixtures +from nova.tests.functional.api import client as api_client +from nova.tests.functional import integrated_helpers +from nova.tests.unit.api.openstack.compute import test_services +from nova.tests.unit import fake_notifier +import nova.tests.unit.image.fake + +CONF = cfg.CONF + + +class NotificationSampleTestBase(test.TestCase, + integrated_helpers.InstanceHelperMixin): + """Base class for notification sample testing. + + To add tests for a versioned notification you have to store a sample file + under doc/notification_sample directory. In the test method in the subclass + trigger a change in the system that expected to generate the notification + then use the _verify_notification function to assert if the stored sample + matches with the generated one. + + If the notification has different payload content depending on the state + change you triggered then the replacements parameter of the + _verify_notification function can be used to override values coming from + the sample file. + + Check nova.functional.notification_sample_tests.test_service_update as an + example. + """ + + ANY = object() + + def setUp(self): + super(NotificationSampleTestBase, self).setUp() + # Needs to mock this to avoid REQUIRES_LOCKING to be set to True + patcher = mock.patch('oslo_concurrency.lockutils.lock') + self.addCleanup(patcher.stop) + patcher.start() + + api_fixture = self.useFixture(nova_fixtures.OSAPIFixture( + api_version='v2.1')) + + self.api = api_fixture.api + self.admin_api = api_fixture.admin_api + fake_notifier.stub_notifier(self) + self.addCleanup(fake_notifier.reset) + + self.useFixture(utils_fixture.TimeFixture(test_services.fake_utcnow())) + + self.flags(scheduler_driver='chance_scheduler') + # the image fake backend needed for image discovery + nova.tests.unit.image.fake.stub_out_image_service(self) + self.addCleanup(nova.tests.unit.image.fake.FakeImageService_reset) + + self.start_service('conductor', manager=CONF.conductor.manager) + self.start_service('scheduler') + self.start_service('network') + self.compute = self.start_service('compute') + + def _get_notification_sample(self, sample): + sample_dir = os.path.dirname(os.path.abspath(__file__)) + sample_dir = os.path.normpath(os.path.join( + sample_dir, + "../../../../doc/notification_samples")) + return sample_dir + '/' + sample + '.json' + + def _apply_replacements(self, replacements, sample_obj, notification): + replacements = replacements or {} + for key, value in replacements.items(): + obj = sample_obj['payload'] + n_obj = notification['payload'] + for sub_key in key.split('.')[:-1]: + obj = obj['nova_object.data'][sub_key] + n_obj = n_obj['nova_object.data'][sub_key] + if value == NotificationSampleTestBase.ANY: + del obj['nova_object.data'][key.split('.')[-1]] + del n_obj['nova_object.data'][key.split('.')[-1]] + else: + obj['nova_object.data'][key.split('.')[-1]] = value + + def _verify_notification(self, sample_file_name, replacements=None, + actual=None): + """Assert if the generated notification matches with the stored sample + + :param sample_file_name: The name of the sample file to match relative + to doc/notification_samples + :param replacements: A dict of key value pairs that is used to update + the payload field of the sample data before it is + matched against the generated notification. + The 'x.y':'new-value' key-value pair selects the + ["payload"]["nova_object.data"]["x"] + ["nova_object.data"]["y"] value from the sample + data and overrides it with 'new-value'. There is + a special value ANY that can be used to indicate + that the actual field value shall be ignored + during matching. + :param actual: Defines the actual notification to compare with. If + None then it defaults to the first versioned + notification emitted during the test. + """ + if not actual: + self.assertEqual(1, len(fake_notifier.VERSIONED_NOTIFICATIONS)) + notification = fake_notifier.VERSIONED_NOTIFICATIONS[0] + else: + notification = actual + + with open(self._get_notification_sample(sample_file_name)) as sample: + sample_data = sample.read() + + sample_obj = jsonutils.loads(sample_data) + self._apply_replacements(replacements, sample_obj, notification) + + self.assertJsonEqual(sample_obj, notification) + + def _boot_a_server(self, expected_status='ACTIVE', extra_params=None): + + # We have to depend on a specific image and flavor to fix the content + # of the notification that will be emitted + flavor_body = {'flavor': {'name': 'test_flavor', + 'ram': 512, + 'vcpus': 1, + 'disk': 1, + 'id': 'a22d5517-147c-4147-a0d1-e698df5cd4e3' + }} + + flavor_id = self.api.post_flavor(flavor_body)['id'] + + server = self._build_minimal_create_server_request( + self.api, 'some-server', + image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6', + flavor_id=flavor_id) + + extra_params['return_reservation_id'] = True + + if extra_params: + server.update(extra_params) + + post = {'server': server} + created_server = self.api.post_server(post) + reservation_id = created_server['reservation_id'] + created_server = self.api.get_servers( + detail=False, + search_opts={'reservation_id': reservation_id})[0] + + self.assertTrue(created_server['id']) + + # Wait for it to finish being created + found_server = self._wait_for_state_change(self.api, created_server, + expected_status) + found_server['reservation_id'] = reservation_id + return found_server + + def _wait_until_deleted(self, server): + try: + for i in range(40): + server = self.api.get_server(server['id']) + if server['status'] == 'ERROR': + self.fail('Server went to error state instead of' + 'disappearing.') + time.sleep(0.5) + + self.fail('Server failed to delete.') + except api_client.OpenStackApiNotFoundException: + return + + def _get_notifications(self, event_type): + return [notification for notification + in fake_notifier.VERSIONED_NOTIFICATIONS + if notification['event_type'] == event_type] diff --git a/pool/shard006/Python/0058105_main.py b/pool/shard006/Python/0058105_main.py new file mode 100644 index 0000000000000000000000000000000000000000..6e02f452f60c6116382ae09460a32561fef83718 --- /dev/null +++ b/pool/shard006/Python/0058105_main.py @@ -0,0 +1,21 @@ +from fastapi import FastAPI +from routers import api_router + +from database import init_db, get_db + +try: + # Try to create session to check if DB is awake + db = get_db() + db.execute("SELECT 1") +except Exception as e: + init_db() + +app = FastAPI() + + +@app.get("/") +async def root(): + return {"message": "Hello World"} + + +app.include_router(api_router, prefix="") diff --git a/pool/shard006/Python/0058108_core.py b/pool/shard006/Python/0058108_core.py new file mode 100644 index 0000000000000000000000000000000000000000..7feb738f1c06f7b08ec7b5ad1e49f6489530317b --- /dev/null +++ b/pool/shard006/Python/0058108_core.py @@ -0,0 +1,203 @@ +# coding: utf-8 +# Copyright (c) Pymatgen Development Team. +# Distributed under the terms of the MIT License. + +""" +This module implements core classes for calculation of diffraction patterns. +""" + +import collections +import abc +import numpy as np +from pymatgen.core.spectrum import Spectrum +from pymatgen.util.plotting import add_fig_kwargs + + +class DiffractionPattern(Spectrum): + """ + A representation of a diffraction pattern + """ + + XLABEL = "$2\\Theta$" + YLABEL = "Intensity" + + def __init__(self, x, y, hkls, d_hkls): + """ + Args: + x: Two theta angles. + y: Intensities + hkls: [{"hkl": (h, k, l), "multiplicity": mult}], + where {"hkl": (h, k, l), "multiplicity": mult} + is a dict of Miller + indices for all diffracted lattice facets contributing to each + intensity. + d_hkls: List of interplanar spacings. + """ + super().__init__(x, y, hkls, d_hkls) + self.hkls = hkls + self.d_hkls = d_hkls + + +class AbstractDiffractionPatternCalculator(abc.ABC): + """ + Abstract base class for computing the diffraction pattern of a crystal. + """ + # Tolerance in which to treat two peaks as having the same two theta. + TWO_THETA_TOL = 1e-5 + + # Tolerance in which to treat a peak as effectively 0 if the scaled + # intensity is less than this number. Since the max intensity is 100, + # this means the peak must be less than 1e-5 of the peak intensity to be + # considered as zero. This deals with numerical issues where systematic + # absences do not cancel exactly to zero. + SCALED_INTENSITY_TOL = 1e-3 + + @abc.abstractmethod + def get_pattern(self, structure, scaled=True, two_theta_range=(0, 90)): + """ + Calculates the diffraction pattern for a structure. + + Args: + structure (Structure): Input structure + scaled (bool): Whether to return scaled intensities. The maximum + peak is set to a value of 100. Defaults to True. Use False if + you need the absolute values to combine XRD plots. + two_theta_range ([float of length 2]): Tuple for range of + two_thetas to calculate in degrees. Defaults to (0, 90). Set to + None if you want all diffracted beams within the limiting + sphere of radius 2 / wavelength. + + Returns: + (DiffractionPattern) + """ + pass + + def get_plot(self, structure, two_theta_range=(0, 90), + annotate_peaks=True, ax=None, with_labels=True, + fontsize=16): + """ + Returns the diffraction plot as a matplotlib.pyplot. + + Args: + structure: Input structure + two_theta_range ([float of length 2]): Tuple for range of + two_thetas to calculate in degrees. Defaults to (0, 90). Set to + None if you want all diffracted beams within the limiting + sphere of radius 2 / wavelength. + annotate_peaks: Whether to annotate the peaks with plane + information. + ax: matplotlib :class:`Axes` or None if a new figure should be created. + with_labels: True to add xlabels and ylabels to the plot. + fontsize: (int) fontsize for peak labels. + + Returns: + (matplotlib.pyplot) + """ + if ax is None: + from pymatgen.util.plotting import pretty_plot + plt = pretty_plot(16, 10) + ax = plt.gca() + else: + # This to maintain the type of the return value. + import matplotlib.pyplot as plt + + xrd = self.get_pattern(structure, two_theta_range=two_theta_range) + + for two_theta, i, hkls, d_hkl in zip(xrd.x, xrd.y, xrd.hkls, xrd.d_hkls): + if two_theta_range[0] <= two_theta <= two_theta_range[1]: + label = ", ".join([str(hkl["hkl"]) for hkl in hkls]) + ax.plot([two_theta, two_theta], [0, i], color='k', + linewidth=3, label=label) + if annotate_peaks: + ax.annotate(label, xy=[two_theta, i], + xytext=[two_theta, i], fontsize=fontsize) + + if with_labels: + ax.set_xlabel(r"$2\theta$ ($^\circ$)") + ax.set_ylabel("Intensities (scaled)") + + if hasattr(ax, "tight_layout"): + ax.tight_layout() + + return plt + + def show_plot(self, structure, **kwargs): + """ + Shows the diffraction plot. + + Args: + structure (Structure): Input structure + two_theta_range ([float of length 2]): Tuple for range of + two_thetas to calculate in degrees. Defaults to (0, 90). Set to + None if you want all diffracted beams within the limiting + sphere of radius 2 / wavelength. + annotate_peaks (bool): Whether to annotate the peaks with plane + information. + """ + self.get_plot(structure, **kwargs).show() + + @add_fig_kwargs + def plot_structures(self, structures, fontsize=6, **kwargs): + """ + Plot diffraction patterns for multiple structures on the same figure. + + Args: + structures (Structure): List of structures + two_theta_range ([float of length 2]): Tuple for range of + two_thetas to calculate in degrees. Defaults to (0, 90). Set to + None if you want all diffracted beams within the limiting + sphere of radius 2 / wavelength. + annotate_peaks (bool): Whether to annotate the peaks with plane + information. + fontsize: (int) fontsize for peak labels. + """ + import matplotlib.pyplot as plt + nrows = len(structures) + fig, axes = plt.subplots(nrows=nrows, ncols=1, sharex=True, + squeeze=False) + + for i, (ax, structure) in enumerate(zip(axes.ravel(), structures)): + self.get_plot(structure, + fontsize=fontsize, ax=ax, with_labels=i == nrows - 1, + **kwargs) + spg_symbol, spg_number = structure.get_space_group_info() + ax.set_title("{} {} ({}) ".format(structure.formula, spg_symbol, + spg_number)) + + return fig + + +def get_unique_families(hkls): + """ + Returns unique families of Miller indices. Families must be permutations + of each other. + + Args: + hkls ([h, k, l]): List of Miller indices. + + Returns: + {hkl: multiplicity}: A dict with unique hkl and multiplicity. + """ + + # TODO: Definitely can be sped up. + def is_perm(hkl1, hkl2): + h1 = np.abs(hkl1) + h2 = np.abs(hkl2) + return all([i == j for i, j in zip(sorted(h1), sorted(h2))]) + + unique = collections.defaultdict(list) + for hkl1 in hkls: + found = False + for hkl2 in unique.keys(): + if is_perm(hkl1, hkl2): + found = True + unique[hkl2].append(hkl1) + break + if not found: + unique[hkl1].append(hkl1) + + pretty_unique = {} + for k, v in unique.items(): + pretty_unique[sorted(v)[-1]] = len(v) + + return pretty_unique diff --git a/pool/shard006/Python/0058112_test_load_tool.py b/pool/shard006/Python/0058112_test_load_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..26ba3f9df0807b5a20cd0c868ec2be2a66709d7c --- /dev/null +++ b/pool/shard006/Python/0058112_test_load_tool.py @@ -0,0 +1,132 @@ +"""Tests for cwltool.load_tool.""" +import logging +from pathlib import Path + +import pytest + +from cwltool.context import LoadingContext, RuntimeContext +from cwltool.errors import WorkflowException +from cwltool.load_tool import load_tool +from cwltool.loghandler import _logger, configure_logging +from cwltool.process import use_custom_schema, use_standard_schema +from cwltool.update import INTERNAL_VERSION +from cwltool.utils import CWLObjectType + +from .util import get_data + +configure_logging(_logger.handlers[-1], False, True, True, True) +_logger.setLevel(logging.DEBUG) + + +def test_check_version() -> None: + """ + It is permitted to load without updating, but not execute. + + Attempting to execute without updating to the internal version should raise an error. + """ + joborder = {"inp": "abc"} # type: CWLObjectType + loadingContext = LoadingContext({"do_update": True}) + tool = load_tool(get_data("tests/echo.cwl"), loadingContext) + for _ in tool.job(joborder, None, RuntimeContext()): + pass + + loadingContext = LoadingContext({"do_update": False}) + tool = load_tool(get_data("tests/echo.cwl"), loadingContext) + with pytest.raises(WorkflowException): + for _ in tool.job(joborder, None, RuntimeContext()): + pass + + +def test_use_metadata() -> None: + """Use the version from loadingContext.metadata if cwlVersion isn't present in the document.""" + loadingContext = LoadingContext({"do_update": False}) + tool = load_tool(get_data("tests/echo.cwl"), loadingContext) + + loadingContext = LoadingContext() + loadingContext.metadata = tool.metadata + tooldata = tool.tool.copy() + del tooldata["cwlVersion"] + load_tool(tooldata, loadingContext) + + +def test_checklink_outputSource() -> None: + """Is outputSource resolved correctly independent of value of do_validate.""" + outsrc = ( + Path(get_data("tests/wf/1st-workflow.cwl")).as_uri() + "#argument/classfile" + ) + + loadingContext = LoadingContext({"do_validate": True}) + tool = load_tool(get_data("tests/wf/1st-workflow.cwl"), loadingContext) + assert tool.tool["outputs"][0]["outputSource"] == outsrc + + loadingContext = LoadingContext({"do_validate": False}) + tool = load_tool(get_data("tests/wf/1st-workflow.cwl"), loadingContext) + assert tool.tool["outputs"][0]["outputSource"] == outsrc + + +def test_load_graph_fragment() -> None: + """Reloading from a dictionary without a cwlVersion.""" + loadingContext = LoadingContext() + uri = Path(get_data("tests/wf/scatter-wf4.cwl")).as_uri() + "#main" + tool = load_tool(uri, loadingContext) + + loader = tool.doc_loader + assert loader + rs, metadata = loader.resolve_ref(uri) + # Reload from a dict (in 'rs'), not a URI. The dict is a fragment + # of original document and doesn't have cwlVersion set, so test + # that it correctly looks up the root document to get the + # cwlVersion. + assert isinstance(rs, str) or isinstance(rs, dict) + tool = load_tool(rs, loadingContext) + assert tool.metadata["cwlVersion"] == INTERNAL_VERSION + + +def test_load_graph_fragment_from_packed() -> None: + """Loading a fragment from packed with update.""" + loadingContext = LoadingContext() + uri = Path(get_data("tests/wf/packed-with-loadlisting.cwl")).as_uri() + "#main" + try: + with open(get_data("cwltool/extensions.yml")) as res: + use_custom_schema("v1.0", "http://commonwl.org/cwltool", res.read()) + + # The updater transforms LoadListingRequirement from an + # extension (in v1.0) to a core feature (in v1.1) but there + # was a bug when loading a packed workflow and loading a + # specific fragment it would get the un-updated document. + # This recreates that case and asserts that we are using the + # updated document like we should. + + tool = load_tool(uri, loadingContext) + + assert tool.tool["requirements"] == [ + {"class": "LoadListingRequirement", "loadListing": "no_listing"} + ] + + # This tests an additional, related bug, in which the updater + # updates only one fragment of the document, but would update + # the metadata dict in-place. This had the effect of marking + # the original document as updated. On a subsequent load, it + # would get the original un-updated document, which mistakenly + # had the version modified in place, and validate it with the + # newer schema instead of the original one. + # + # The specific case where this failed was + # cwltool:LoadListingRequirement which is only recognized for + # v1.0 documents, newer documents are supposed to be + # auto-updated to the spec LoadListingRequirement, so it is + # dropped from the schema. However if we try to validate a + # v1.0 document with a v1.2 schema, it will throw an error the + # cwltool:LoadListingRequirement extension. + # + # This was solved by making a shallow copy of the metadata + # dict to ensure that the updater did not modify the original + # document. + uri2 = ( + Path(get_data("tests/wf/packed-with-loadlisting.cwl")).as_uri() + + "#16169-step.cwl" + ) + tool2 = load_tool(uri2, loadingContext) + + finally: + use_standard_schema("v1.0") diff --git a/pool/shard006/Python/0058118_service_scan.py b/pool/shard006/Python/0058118_service_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..d530bc0fe33fa1d5abcfbf20a3c7ae18a576eb3a --- /dev/null +++ b/pool/shard006/Python/0058118_service_scan.py @@ -0,0 +1,163 @@ +import multiprocessing +import socket + +from Reconnoitre.lib.file_helper import check_directory +from Reconnoitre.lib.file_helper import create_dir_structure +from Reconnoitre.lib.file_helper import get_config_options +from Reconnoitre.lib.file_helper import load_targets +from Reconnoitre.lib.file_helper import write_recommendations +from Reconnoitre.lib.subprocess_helper import run_scan + + +def nmap_scan( + ip_address, + output_directory, + dns_server, + quick, + no_udp_service_scan): + ip_address = ip_address.strip() + + print("[+] Starting quick nmap scan for %s" % (ip_address)) + flags = get_config_options('nmap', 'quickscan') + QUICKSCAN = f"nmap {flags} {ip_address} -oA '{output_directory}/{ip_address}.quick'" + quickresults = run_scan(QUICKSCAN) + + write_recommendations(quickresults, ip_address, output_directory) + print("[*] TCP quick scans completed for %s" % ip_address) + + if (quick): + return + + if dns_server: + print( + "[+] Starting detailed TCP%s nmap scans for " + "%s using DNS Server %s" % + (("" if no_udp_service_scan is True else "/UDP"), + ip_address, + dns_server)) + print("[+] Using DNS server %s" % (dns_server)) + flags = get_config_options("nmap", "tcpscan") + TCPSCAN = f"nmap {flags} --dns-servers {dns_server} -oN\ + '{output_directory}/{ip_address}.nmap' -oX\ + '{output_directory}/{ip_address}_nmap_scan_import.xml' {ip_address}" + + flags = get_config_options("nmap", "dnsudpscan") + UDPSCAN = f"nmap {flags} \ + --dns-servers {dns_server} -oN '{output_directory}/{ip_address}U.nmap' \ + -oX '{output_directory}/{ip_address}U_nmap_scan_import.xml' {ip_address}" + + else: + print("[+] Starting detailed TCP%s nmap scans for %s" % ( + ("" if no_udp_service_scan is True else "/UDP"), ip_address)) + flags = get_config_options("nmap", "tcpscan") + TCPSCAN = f"nmap {flags} -oN\ + '{output_directory}/{ip_address}.nmap' -oX\ + '{output_directory}/{ip_address}_nmap_scan_import.xml' {ip_address}" + + flags = get_config_options("nmap", "udpscan") + UDPSCAN = f"nmap {flags} {ip_address} -oA '{output_directory}/{ip_address}-udp'" + + udpresult = "" if no_udp_service_scan is True else run_scan(UDPSCAN) + tcpresults = run_scan(TCPSCAN) + + write_recommendations(tcpresults + udpresult, ip_address, output_directory) + print("[*] TCP%s scans completed for %s" % + (("" if no_udp_service_scan is True else "/UDP"), ip_address)) + + +def valid_ip(address): + try: + socket.inet_aton(address) + return True + except socket.error: + return False + + +def target_file( + target_hosts, + output_directory, + dns_server, + quiet, + quick, + no_udp_service_scan): + targets = load_targets(target_hosts, output_directory, quiet) + target_file = open(targets, 'r') + try: + target_file = open(targets, 'r') + print("[*] Loaded targets from: %s" % targets) + except Exception: + print("[!] Unable to load: %s" % targets) + + for ip_address in target_file: + ip_address = ip_address.strip() + create_dir_structure(ip_address, output_directory) + + host_directory = output_directory + "/" + ip_address + nmap_directory = host_directory + "/scans" + + jobs = [] + p = multiprocessing.Process( + target=nmap_scan, + args=( + ip_address, + nmap_directory, + dns_server, + quick, + no_udp_service_scan)) + jobs.append(p) + p.start() + target_file.close() + + +def target_ip( + target_hosts, + output_directory, + dns_server, + quiet, + quick, + no_udp_service_scan): + print("[*] Loaded single target: %s" % target_hosts) + target_hosts = target_hosts.strip() + create_dir_structure(target_hosts, output_directory) + + host_directory = output_directory + "/" + target_hosts + nmap_directory = host_directory + "/scans" + + jobs = [] + p = multiprocessing.Process( + target=nmap_scan, + args=( + target_hosts, + nmap_directory, + dns_server, + quick, + no_udp_service_scan)) + jobs.append(p) + p.start() + + +def service_scan( + target_hosts, + output_directory, + dns_server, + quiet, + quick, + no_udp_service_scan): + check_directory(output_directory) + + if (valid_ip(target_hosts)): + target_ip( + target_hosts, + output_directory, + dns_server, + quiet, + quick, + no_udp_service_scan) + else: + target_file( + target_hosts, + output_directory, + dns_server, + quiet, + quick, + no_udp_service_scan) diff --git a/pool/shard006/Python/0058119_init__.py b/pool/shard006/Python/0058119_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b77c6d9fa80a28c3f475ddb1b0e8a1654ee3abae --- /dev/null +++ b/pool/shard006/Python/0058119_init__.py @@ -0,0 +1,145 @@ +import unittest +import tempfile +import shutil +import os +from rucola import OUTPUT_DIR + + +class BaseTest(unittest.TestCase): + + def setUp(self): + + # Path pointing to current working directory. + self.cwd = os.getcwd() + # Path to commands test directory. + self.path = os.path.dirname(__file__) + # Path to temporary directory with sites. + self.temp_path = tempfile.mkdtemp() + # Set current working directory to temporary directory with sites. + os.chdir(self.temp_path) + + def tearDown(self): + # Go to previous working directory and clear files. + os.chdir(self.cwd) + shutil.rmtree(self.temp_path) + + # File system shortcuts. + + def read_file(self, path): + """Returns data from given path. Use '/' as a path separator, + path must be relative to current temp path.""" + + if os.path.isabs(path): + raise ValueError('path must be relative!') + + fp = os.path.join(self.temp_path, *path.split('/')) + self.assertTrue(os.path.exists(fp), + msg='path not found: ' + fp) + + with open(fp, encoding='utf-8') as file: + return file.read() + + def create_file(self, path, content=''): + """Creates a new file with a data. Use '/' as a path separator, + path must be relative to temp.""" + + if os.path.isabs(path): + raise ValueError('path must be relative!') + + path = os.path.join(self.temp_path, *path.split('/')) + dir_path = os.path.dirname(path) + + # Create missing dirs. + if not os.path.exists(dir_path): + os.makedirs(dir_path) + + with open(path, 'w') as file: + file.write(content) + + def create_dir(self, path): + """Creates a new directory. Use '/' as a path separator, + path must be relative to temp.""" + + if os.path.isabs(path): + raise ValueError('path must be relative!') + + path = os.path.join(self.temp_path, *path.split('/')) + os.makedirs(path) + + def remove_file(self, path): + """BE CAREFUL! Removes given file. Use '/' as a path separator, + path must be relative to temp.""" + + if os.path.isabs(path): + raise ValueError('path must be relative!') + os.remove(os.path.join(self.temp_path, *path.split('/'))) + + def remove_dir(self, path): + """BE CAREFUL! Removes directory recursively. Use '/' as a path + separator, path must be relative to temp.""" + + if os.path.isabs(path): + raise ValueError('path must be relative!') + + p = os.path.join(self.temp_path, *path.split('/')) + shutil.rmtree(p) + + +import inspect + + + +class FunctionalTest(unittest.TestCase): + + def setUp(self): + + # Clear build directory + self.test_dir = os.path.dirname(inspect.getfile(self.__class__)) + output = os.path.join(self.test_dir, OUTPUT_DIR) + if os.path.exists(output): + shutil.rmtree(output) + + + # Comparing outputs. + + def get_files(self, path): + """Returns all files in tree.""" + + paths = [] + for i in os.walk(path): + for file in i[2]: + paths.append(os.path.join(os.path.relpath(i[0], path), file)) + return paths + + def compare(self, app): + """Checks if files in test/output directory are same as generated in + site output. Argument path is patch relative to output directory.""" + + expected = os.path.join(self.test_dir, 'expected') + + for path, dirs, files in os.walk(expected): + for f in files: + + exp_file = os.path.join(path, f) + rel_file = os.path.relpath(exp_file, expected) + build_file = os.path.join(app.output, rel_file) + + # Check if file was created in output directory. + self.assertTrue(os.path.exists(build_file), + msg='File not found in build directory: ' + rel_file) + + # Compare file contents. + with open(build_file) as a: + with open(exp_file) as b: + self.assertEqual(a.read(), b.read(), + msg='Files contents do not match!') + + # Compares directory tree. + + expected_files = self.get_files(expected) + build_files = self.get_files(app.output) + self.assertCountEqual(expected_files, build_files) + + +class PluginTest(FunctionalTest): + pass \ No newline at end of file diff --git a/pool/shard006/Python/0058123_eval_runner.py b/pool/shard006/Python/0058123_eval_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..e44e0fb2be2b63c030758a97a65fe67221d2b633 --- /dev/null +++ b/pool/shard006/Python/0058123_eval_runner.py @@ -0,0 +1,258 @@ +# 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. +# ============================================================================== +"""Bypass TPUEstimator for ResNet-50 Eval.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import threading +import time + +from absl import flags +import absl.logging as _logging # pylint: disable=unused-import +import tensorflow as tf + +from tensorflow.contrib import tpu +from tensorflow.python.data.util import nest as data_nest + +FLAGS = flags.FLAGS + +_INITIAL_LOSS = 1e7 + + +def wrap_computation_in_while_loop(op_fn, n, parallel_iterations=10): + """Wraps the ops generated by `op_fn` in tf.while_loop.""" + + def computation(i): + ops = op_fn() + if not isinstance(ops, list): + ops = [ops] + with tf.control_dependencies(ops): + return i + 1 + + return tf.while_loop( + lambda i: tf.less(i, n), + computation, [tf.constant(0)], + parallel_iterations=parallel_iterations) + +def device_for_host(task=0, cpu=0): + return "/job:tpu_worker/task:%d/device:CPU:%d" %(task, cpu) + +def device_for_tpu_core(task=0, core=0): + return "/job:tpu_worker/task:%d/device:TPU_REPLICATED_CORE:%d" %(task, core) + + +def tpu_ordinal_fn(shard_index_in_host): + """Return the TPU ordinal associated with a shard. + + Required because the enqueue ops are placed on CPU. + + Args: + shard_index_in_host: the shard index + + Returns: + The ordinal of the TPU device the shard's infeed should be placed on. + """ + return shard_index_in_host % FLAGS.num_cores + + +class EvalRunner(object): + """Run Eval via direct session.run calls eliminating init and compilation + + overheads from TPU Estimator. + """ + + def __init__(self, input_fn, model_fn, params, num_steps): + self.feature_structure = {} + self.loss = None + self.enqueue_ops = None + self.metric_initializer = None + self.iterator = None + self.batch_size = params["batch_size"] + with tf.Graph().as_default() as self.graph: + self.build_model(params, input_fn, model_fn, num_steps) + self.tpu_init = tpu.initialize_system() + initializer = tf.global_variables_initializer() + self.tpu_shutdown = tpu.shutdown_system() + self.local_initializer = tf.local_variables_initializer() + self.saver = tf.train.Saver() + + cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(FLAGS.tpu) + self.sess = tf.Session(cluster_resolver.get_master(), graph=self.graph) + self.sess.run(self.tpu_init) + self.sess.run(initializer) + self.sess.run(self.local_initializer) + self.sess.run(self.iterator.initializer) + + def build_model(self, params, input_fn, model_fn, num_steps): + """Build the TPU model and infeed enqueue ops.""" + + iparams = {} + iparams["batch_size"] = params["batch_size"] // FLAGS.num_cores + + dataset = input_fn(iparams) + dataset = dataset.cache() # Cache the fully-generated eval dataset. + dataset = dataset.repeat() # Repeat indefinitely for unknown # of evals. + self.iterator = dataset.make_initializable_iterator() + + def get_tpu_step(mparams): + """Get the TPU graph generation function.""" + + def tpu_step(loss, *args): + """Generate the TPU graph.""" + del loss + unflattened_inputs = data_nest.pack_sequence_as(self.feature_structure, + args) + features = unflattened_inputs["features"] + labels = unflattened_inputs["labels"] + estimator_spec = model_fn(features, labels, tf.estimator.ModeKeys.EVAL, + mparams) + loss = estimator_spec.loss + self.eval_metrics = estimator_spec.eval_metrics + self.eval_tensors = estimator_spec.eval_metrics[1] + with tf.device(device_for_tpu_core()): + outfeed_enqueue_ops = tpu.outfeed_enqueue_tuple(self.eval_tensors) + with tf.control_dependencies([outfeed_enqueue_ops]): + return tf.identity(loss) + + return tpu_step + + infeed_queue = [] + + def get_enqueue_ops_fn(): + """Generate the enqueue ops graph function.""" + + def enqueue_ops_fn(): + """Generate the infeed enqueue ops graph.""" + + per_host_sharded_inputs = [] + control_deps = [] + with tf.device(device_for_host()): + for _ in range(FLAGS.num_cores): + with tf.control_dependencies(control_deps): + features, labels = self.iterator.get_next() + self.feature_structure["features"] = features + self.feature_structure["labels"] = labels + flattened_inputs = data_nest.flatten(self.feature_structure) + control_deps.extend(flattened_inputs) + per_host_sharded_inputs.append(flattened_inputs) + + infeed = tpu.InfeedQueue( + number_of_tuple_elements=len(per_host_sharded_inputs[0])) + infeed_queue.append(infeed) + return infeed.generate_enqueue_ops(per_host_sharded_inputs, + tpu_ordinal_function=tpu_ordinal_fn) + + return enqueue_ops_fn + + with tf.device(device_for_host()): + self.enqueue_ops = wrap_computation_in_while_loop( + get_enqueue_ops_fn(), n=num_steps, parallel_iterations=1) + + tpu_step = get_tpu_step(params) + + def tpu_loop(): + return tpu.repeat( + num_steps, tpu_step, [_INITIAL_LOSS], infeed_queue=infeed_queue[0]) + + def create_dequeue_ops(): + dequeue_ops = [] + tensor_dtypes = [] + tensor_shapes = [] + for v in self.eval_tensors: + dequeue_ops.append([]) + tensor_dtypes.append(v.dtype) + tensor_shapes.append(v.shape) + tf.logging.info("appending %s" % v.name) + for i in range(FLAGS.num_cores): + with tf.device(device_for_host()): + outfeed_tensors = tpu.outfeed_dequeue_tuple( + dtypes=tensor_dtypes, + shapes=tensor_shapes, + device_ordinal=i) + for j, item in enumerate(outfeed_tensors): + dequeue_ops[j].append(item) + for j in range(len(outfeed_tensors)): + dequeue_ops[j] = tf.concat(dequeue_ops[j], axis=0) + return dequeue_ops + + (self.loss,) = tpu.shard( + tpu_loop, + inputs=[], + num_shards=FLAGS.num_cores, + outputs_from_all_shards=False) + + self.dequeue_ops = create_dequeue_ops() + with tf.device(device_for_host()): + metrics = self.eval_metrics[0](*self.dequeue_ops) + metric_update_ops = [] + metric_value_ops = {} + for (k, v) in metrics.items(): + # print("k: ", k) + # print("v: ", v) + metric_update_ops.append(v[1]) + metric_value_ops[k] = v[0] + self.metric_update_ops = metric_update_ops + self.metric_value_ops = metric_value_ops + + self.metric_initializer = tf.variables_initializer( + tf.get_collection(tf.GraphKeys.METRIC_VARIABLES)) + + + def eval(self, num_steps, checkpoint_path): + """Run the Eval steps on the TPU device. + + Args: + num_steps: number of steps to run eval + checkpoint_path: path to the checkpoint directory + + Returns: + A dictionary of evaluation results. + """ + + start = time.time() + self.sess.run(self.metric_initializer) + self.saver.restore(self.sess, checkpoint_path) + + eval_results = {} + def outfeed_thread_fn(): + tf.logging.info("start dequeue ops") + for i in range(num_steps): + _ = self.sess.run(self.metric_update_ops) + # Compute eval metrics + session_out = self.sess.run(self.metric_value_ops) + eval_results["top_1_accuracy"] = session_out["top_1_accuracy"] + + def infeed_thread_fn(sess, enqueue_ops): + sess.run([enqueue_ops]) + + infeed_thread = threading.Thread( + target=infeed_thread_fn, args=(self.sess, self.enqueue_ops)) + infeed_thread.start() + outfeed_thread = threading.Thread(target=outfeed_thread_fn) + outfeed_thread.start() + tf.logging.info("Starting Eval on %d steps batch size %d" % + (num_steps, self.batch_size)) + loss = self.sess.run([self.loss]) + tf.logging.info("Eval Loss = {}".format(loss)) + infeed_thread.join() + outfeed_thread.join() + + end = time.time() + tf.logging.info("Eval performance: step time {} sec {} examples/sec".format( + end - start, self.batch_size / (end - start))) + + return eval_results diff --git a/pool/shard006/Python/0058124_blackbody.py b/pool/shard006/Python/0058124_blackbody.py new file mode 100644 index 0000000000000000000000000000000000000000..242b32bcb5524e715ecea1ac41ba5f57cf32e16d --- /dev/null +++ b/pool/shard006/Python/0058124_blackbody.py @@ -0,0 +1,281 @@ +# Licensed under a 3-clause BSD style license - see LICENSE.rst +""" +Model and functions related to blackbody radiation. +""" +import warnings + +import numpy as np + +from .core import Fittable1DModel +from .parameters import Parameter +from astropy import constants as const +from astropy import units as u +from astropy.utils.exceptions import AstropyUserWarning +from astropy.utils import deprecated + +__all__ = ['BlackBody1D', 'blackbody_nu', 'blackbody_lambda'] + +# Units +FNU = u.erg / (u.cm**2 * u.s * u.Hz) +FLAM = u.erg / (u.cm**2 * u.s * u.AA) + +# Some platform implementations of expm1() are buggy and Numpy uses +# them anyways--the bug is that on certain large inputs it returns +# NaN instead of INF like it should (it should only return NaN on a +# NaN input +# See https://github.com/astropy/astropy/issues/4171 +with warnings.catch_warnings(): + warnings.simplefilter('ignore', RuntimeWarning) + _has_buggy_expm1 = np.isnan(np.expm1(1000)) or np.isnan(np.expm1(1e10)) + + +@deprecated( + since="4.0", + alternative="astropy.physical_models.BlackBody", + message="BlackBody provides the same capabilities", +) +class BlackBody1D(Fittable1DModel): + """ + One dimensional blackbody model. + + Parameters + ---------- + temperature : :class:`~astropy.units.Quantity` + Blackbody temperature. + bolometric_flux : :class:`~astropy.units.Quantity` + The bolometric flux of the blackbody (i.e., the integral over the + spectral axis). + + Notes + ----- + + Model formula: + + .. math:: f(x) = \\pi B_{\\nu} f_{\\text{bolometric}} / (\\sigma T^{4}) + + Examples + -------- + >>> import warnings + >>> from astropy.modeling import models + >>> from astropy import units as u + >>> with warnings.catch_warnings(): + ... warnings.simplefilter('ignore') # Ignore deprecation warning + ... bb = models.BlackBody1D() + ... bb(6000 * u.AA) # doctest: +FLOAT_CMP + + + .. plot:: + :include-source: + + # Ignore warnings about deprecation of BlackBody1D + import warnings + warnings.simplefilter('ignore') + + import numpy as np + import matplotlib.pyplot as plt + + from astropy.modeling.models import BlackBody1D + from astropy.modeling.blackbody import FLAM + from astropy import units as u + from astropy.visualization import quantity_support + + bb = BlackBody1D(temperature=5778*u.K) + wav = np.arange(1000, 110000) * u.AA + flux = bb(wav).to(FLAM, u.spectral_density(wav)) + + with quantity_support(): + plt.figure() + plt.semilogx(wav, flux) + plt.axvline(bb.lambda_max.to(u.AA).value, ls='--') + plt.show() + + """ + + # We parametrize this model with a temperature and a bolometric flux. The + # bolometric flux is the integral of the model over the spectral axis. This + # is more useful than simply having an amplitude parameter. + temperature = Parameter(default=5000, min=0, unit=u.K) + bolometric_flux = Parameter(default=1, min=0, unit=u.erg / u.cm ** 2 / u.s) + + # We allow values without units to be passed when evaluating the model, and + # in this case the input x values are assumed to be frequencies in Hz. + _input_units_allow_dimensionless = True + + # We enable the spectral equivalency by default for the spectral axis + input_units_equivalencies = {'x': u.spectral()} + + def evaluate(self, x, temperature, bolometric_flux): + """Evaluate the model. + + Parameters + ---------- + x : float, `~numpy.ndarray`, or `~astropy.units.Quantity` + Frequency at which to compute the blackbody. If no units are given, + this defaults to Hz. + + temperature : float, `~numpy.ndarray`, or `~astropy.units.Quantity` + Temperature of the blackbody. If no units are given, this defaults + to Kelvin. + + bolometric_flux : float, `~numpy.ndarray`, or `~astropy.units.Quantity` + Desired integral for the blackbody. + + Returns + ------- + y : number or ndarray + Blackbody spectrum. The units are determined from the units of + ``bolometric_flux``. + """ + + # We need to make sure that we attach units to the temperature if it + # doesn't have any units. We do this because even though blackbody_nu + # can take temperature values without units, the / temperature ** 4 + # factor needs units to be defined. + if isinstance(temperature, u.Quantity): + temperature = temperature.to(u.K, equivalencies=u.temperature()) + else: + temperature = u.Quantity(temperature, u.K) + + # We normalize the returned blackbody so that the integral would be + # unity, and we then multiply by the bolometric flux. A normalized + # blackbody has f_nu = pi * B_nu / (sigma * T^4), which is what we + # calculate here. We convert to 1/Hz to make sure the units are + # simplified as much as possible, then we multiply by the bolometric + # flux to get the normalization right. + fnu = ((np.pi * u.sr * blackbody_nu(x, temperature) / + const.sigma_sb / temperature ** 4).to(1 / u.Hz) * + bolometric_flux) + + # If the bolometric_flux parameter has no unit, we should drop the /Hz + # and return a unitless value. This occurs for instance during fitting, + # since we drop the units temporarily. + if hasattr(bolometric_flux, 'unit'): + return fnu + else: + return fnu.value + + @property + def input_units(self): + # The input units are those of the 'x' value, which should always be + # Hz. Because we do this, and because input_units_allow_dimensionless + # is set to True, dimensionless values are assumed to be in Hz. + return {'x': u.Hz} + + def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): + return {'temperature': u.K, + 'bolometric_flux': outputs_unit['y'] * u.Hz} + + @property + def lambda_max(self): + """Peak wavelength when the curve is expressed as power density.""" + return const.b_wien / self.temperature + + +@deprecated( + since="4.0", + alternative="astropy.physical_models.BlackBody", + message="BlackBody provides the same capabilities", +) +def blackbody_nu(in_x, temperature): + """Calculate blackbody flux per steradian, :math:`B_{\\nu}(T)`. + + .. note:: + + Use `numpy.errstate` to suppress Numpy warnings, if desired. + + .. warning:: + + Output values might contain ``nan`` and ``inf``. + + Parameters + ---------- + in_x : number, array-like, or `~astropy.units.Quantity` + Frequency, wavelength, or wave number. + If not a Quantity, it is assumed to be in Hz. + + temperature : number, array-like, or `~astropy.units.Quantity` + Blackbody temperature. + If not a Quantity, it is assumed to be in Kelvin. + + Returns + ------- + flux : `~astropy.units.Quantity` + Blackbody monochromatic flux in + :math:`erg \\; cm^{-2} s^{-1} Hz^{-1} sr^{-1}`. + + Raises + ------ + ValueError + Invalid temperature. + + ZeroDivisionError + Wavelength is zero (when converting to frequency). + + """ + # Convert to units for calculations, also force double precision + with u.add_enabled_equivalencies(u.spectral() + u.temperature()): + freq = u.Quantity(in_x, u.Hz, dtype=np.float64) + temp = u.Quantity(temperature, u.K, dtype=np.float64) + + # Check if input values are physically possible + if np.any(temp < 0): + raise ValueError(f'Temperature should be positive: {temp}') + if not np.all(np.isfinite(freq)) or np.any(freq <= 0): + warnings.warn('Input contains invalid wavelength/frequency value(s)', + AstropyUserWarning) + + log_boltz = const.h * freq / (const.k_B * temp) + boltzm1 = np.expm1(log_boltz) + + if _has_buggy_expm1: + # Replace incorrect nan results with infs--any result of 'nan' is + # incorrect unless the input (in log_boltz) happened to be nan to begin + # with. (As noted in #4393 ideally this would be replaced by a version + # of expm1 that doesn't have this bug, rather than fixing incorrect + # results after the fact...) + boltzm1_nans = np.isnan(boltzm1) + if np.any(boltzm1_nans): + if boltzm1.isscalar and not np.isnan(log_boltz): + boltzm1 = np.inf + else: + boltzm1[np.where(~np.isnan(log_boltz) & boltzm1_nans)] = np.inf + + # Calculate blackbody flux + bb_nu = (2.0 * const.h * freq ** 3 / (const.c ** 2 * boltzm1)) + flux = bb_nu.to(FNU, u.spectral_density(freq)) + + return flux / u.sr # Add per steradian to output flux unit + + +@deprecated( + since="4.0", + alternative="astropy.physical_models.BlackBody", + message="BlackBody provides the same capabilities", +) +def blackbody_lambda(in_x, temperature): + """Like :func:`blackbody_nu` but for :math:`B_{\\lambda}(T)`. + + Parameters + ---------- + in_x : number, array-like, or `~astropy.units.Quantity` + Frequency, wavelength, or wave number. + If not a Quantity, it is assumed to be in Angstrom. + + temperature : number, array-like, or `~astropy.units.Quantity` + Blackbody temperature. + If not a Quantity, it is assumed to be in Kelvin. + + Returns + ------- + flux : `~astropy.units.Quantity` + Blackbody monochromatic flux in + :math:`erg \\; cm^{-2} s^{-1} \\mathring{A}^{-1} sr^{-1}`. + + """ + if getattr(in_x, 'unit', None) is None: + in_x = u.Quantity(in_x, u.AA) + + bb_nu = blackbody_nu(in_x, temperature) * u.sr # Remove sr for conversion + flux = bb_nu.to(FLAM, u.spectral_density(in_x)) + + return flux / u.sr # Add per steradian to output flux unit diff --git a/pool/shard006/Python/0058125_server.py b/pool/shard006/Python/0058125_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7d9872db7e7c8f9fa4ddf238f411e09d8d0898 --- /dev/null +++ b/pool/shard006/Python/0058125_server.py @@ -0,0 +1,164 @@ +import json + +import requests + +from flask import ( + abort, + render_template, + request, + redirect, + url_for, + flash, + session, + current_app +) + +from flask.ext.login import ( + login_required, + current_user +) + +from forms import ( + ChangeForm, + ConfirmForm +) + +from application.services import ( + post_to_cases, + is_matched, + is_owner, + get_lrid_and_roles, + get_client_lrid, + is_allowed_to_see_title, + view_count_limited +) + +from application import ( + app +) + +from .utils import get_or_log_error + +@app.route('/') +@login_required +def index(): + lrid, roles = get_lrid_and_roles(session) + return render_template('index.html', roles=roles, lrid=lrid) + + +@app.route('/property/') +@login_required +@view_count_limited +def property_by_title(title_number): + title_url = "%s/%s/%s" % ( + app.config['AUTHENTICATED_SEARCH_API'], + 'auth/titles', + title_number) + app.logger.debug("Requesting title url : %s" % title_url) + response = get_or_log_error(title_url) + title = response.json() + + app.logger.debug("Found the following title: %s" % title) + owner = is_owner(current_user, title_number) + return render_template( + 'view_property.html', + title=title, + is_owner=owner, + apiKey=app.config['OS_API_KEY']) + + +# Sticking to convention, "/property/" will show the +# resource, and "/property//edit" will show a form +# to edit said resource. Here we go a step further, and limit +# the form to a section on the resource, e.g. "proprietor". +@app.route('/property//edit/title.proprietor.', methods=['GET', 'POST']) +@login_required +@view_count_limited +def property_by_title_edit_proprietor(title_number, proprietor_index): + if is_owner(current_user, title_number): + form = ChangeForm(request.form, marriage_country='GB') + if request.method == 'GET': + title = _get_title(title_number) + app.logger.debug("Found the following title: %s" % title) + form.title_number.data = title['title_number'] + + proprietor = title['proprietorship']['fields']['proprietors'][proprietor_index - 1] + form.proprietor_full_name.data = proprietor['name']['full_name'] + + if form.validate_on_submit(): + if 'confirm' in form and form.confirm.data: + + post_to_cases('change-name-marriage', form.data) + # TODO handle non-200 responses, and ack accordingly. + return render_template('acknowledgement.html', form=form) + else: + from datatypes.validators.iso_country_code_validator import countries + + country = countries.get(alpha2=form.data['marriage_country']).name + return render_template('confirm.html', form=ConfirmForm(obj=form.data), country=country) + return render_template('edit_property.html', form=form) + else: + abort(401) + + +def _get_title(title_number): + title_url = "%s/%s/%s" % ( + app.config['AUTHENTICATED_SEARCH_API'], + 'auth/titles', + title_number) + app.logger.debug("Requesting title url : %s" % title_url) + response = get_or_log_error(title_url) + return response.json() + +@app.route('/property//changes') +@login_required +@view_count_limited +def changes(title_number): + if is_owner(current_user, title_number): + cases_url = app.config['CASES_URL'] + '/cases/property/' + title_number + app.logger.debug("Requesting cases from %s" % cases_url) + cases_response = requests.get(cases_url) + cases = cases_response.json() + pending = [] + historical_changes_list = {} + + historian_list_url = app.config['HISTORIAN_URL'] + '/titles/' + title_number + '?version=list' + historian_version_url = app.config['HISTORIAN_URL'] + '/titles/' + title_number + '?version=' + app.logger.debug('requesting history from ' + historian_list_url) + historian_list_response = requests.get(historian_list_url) + if historian_list_response: + #version information put in a list to pass to the template. + for version in historian_list_response.json()['versions']: + historian_version_response = requests.get(historian_version_url + version['version_id']) + historical_changes_list[version['version_id']] = historian_version_response.json()['contents']['last_application'] + + for case in cases: + if case['status'] != 'completed': + pending.append(case) + + order_by_latest_version_first = list(reversed(sorted(historical_changes_list.keys()))) + + return render_template('changes.html', title_number=title_number, pending=pending, + historical_changes=historical_changes_list, + order_by_latest_version_first=order_by_latest_version_first) + else: + abort(401) + +@app.route('/property//changes/') +@login_required +@view_count_limited +def change_version(title_number, version): + + historian_version_url = app.config['HISTORIAN_URL'] + '/titles/' + title_number + '?version=' + app.logger.debug('requesting historical version from ' + historian_version_url) + historian_version_response = requests.get(historian_version_url + version).json()['contents'] + converted_unix_timestamp = historian_version_response['last_application'] + owner = is_owner(current_user, title_number) + + return render_template( + 'view_property.html', + historical_view='true', + title=historian_version_response, + is_owner=owner, + apiKey=app.config['OS_API_KEY'], + change_date=converted_unix_timestamp) diff --git a/pool/shard006/Python/0058128_test_getting_users_info.py b/pool/shard006/Python/0058128_test_getting_users_info.py new file mode 100644 index 0000000000000000000000000000000000000000..44b5d138cb8c15e10b937b9264327f6771aec9f1 --- /dev/null +++ b/pool/shard006/Python/0058128_test_getting_users_info.py @@ -0,0 +1,82 @@ +# encoding: utf-8 +# pylint: disable=missing-docstring +import pytest + + +@pytest.mark.parametrize('auth_scopes', ( + ('users:write', ), + ('users:read', ), + ('users:read', 'users:write', ), +)) +def test_getting_list_of_users_by_unauthorized_user_must_fail( + flask_app_client, + regular_user, + auth_scopes +): + # pylint: disable=invalid-name + with flask_app_client.login(regular_user, auth_scopes=auth_scopes): + response = flask_app_client.get('/api/v1/users/') + + if 'users:read' in auth_scopes: + assert response.status_code == 403 + else: + assert response.status_code == 401 + assert response.content_type == 'application/json' + assert set(response.json.keys()) >= {'status', 'message'} + +@pytest.mark.parametrize('auth_scopes', ( + ('users:read', ), + ('users:read', 'users:write', ), +)) +def test_getting_list_of_users_by_authorized_user(flask_app_client, admin_user, auth_scopes): + # pylint: disable=invalid-name + with flask_app_client.login(admin_user, auth_scopes=auth_scopes): + response = flask_app_client.get('/api/v1/users/') + + assert response.status_code == 200 + assert response.content_type == 'application/json' + assert isinstance(response.json, list) + assert set(response.json[0].keys()) >= {'id', 'username'} + +def test_getting_user_info_by_unauthorized_user(flask_app_client, regular_user, admin_user): + # pylint: disable=invalid-name + with flask_app_client.login(regular_user, auth_scopes=('users:read',)): + response = flask_app_client.get('/api/v1/users/%d' % admin_user.id) + + assert response.status_code == 403 + assert response.content_type == 'application/json' + assert isinstance(response.json, dict) + assert set(response.json.keys()) >= {'status', 'message'} + +def test_getting_user_info_by_authorized_user(flask_app_client, regular_user, admin_user): + # pylint: disable=invalid-name + with flask_app_client.login(admin_user, auth_scopes=('users:read',)): + response = flask_app_client.get('/api/v1/users/%d' % regular_user.id) + + assert response.status_code == 200 + assert response.content_type == 'application/json' + assert isinstance(response.json, dict) + assert set(response.json.keys()) >= {'id', 'username'} + assert 'password' not in response.json.keys() + +def test_getting_user_info_by_owner(flask_app_client, regular_user): + # pylint: disable=invalid-name + with flask_app_client.login(regular_user, auth_scopes=('users:read',)): + response = flask_app_client.get('/api/v1/users/%d' % regular_user.id) + + assert response.status_code == 200 + assert response.content_type == 'application/json' + assert isinstance(response.json, dict) + assert set(response.json.keys()) >= {'id', 'username'} + assert 'password' not in response.json.keys() + +def test_getting_user_me_info(flask_app_client, regular_user): + # pylint: disable=invalid-name + with flask_app_client.login(regular_user, auth_scopes=('users:read',)): + response = flask_app_client.get('/api/v1/users/me') + + assert response.status_code == 200 + assert response.content_type == 'application/json' + assert isinstance(response.json, dict) + assert set(response.json.keys()) >= {'id', 'username'} + assert 'password' not in response.json.keys() diff --git a/pool/shard006/Python/0058129_TMemoryBufferTest.py b/pool/shard006/Python/0058129_TMemoryBufferTest.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb0d955a1d214ec44a62c3cf3e4c597d6b16b49 --- /dev/null +++ b/pool/shard006/Python/0058129_TMemoryBufferTest.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# Copyright (c) Facebook, Inc. and its affiliates. +# +# 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 +from __future__ import division +from __future__ import print_function +from __future__ import unicode_literals + +import unittest + +from thrift.transport.TTransport import TMemoryBuffer + + +class TestTMemoryBuffer(unittest.TestCase): + def testReadWrite(self): + buf = TMemoryBuffer(b"hello") + data = buf.read(5) + buf.write(b"world") + self.assertEquals(data, b"hello") + self.assertEquals(buf.getvalue(), b"world") + + def testNoInitialValue(self): + buf = TMemoryBuffer() + data = buf.read(5) + buf.write(b"world") + self.assertEquals(data, b"") + self.assertEquals(buf.getvalue(), b"world") + + def testClose(self): + buf = TMemoryBuffer(b"hello") + buf.close() + self.assertRaises(RuntimeError, buf.read, 5) + self.assertRaises(RuntimeError, buf.write, b"world") + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard006/Python/0058131_exampleMonteCarloUni.py b/pool/shard006/Python/0058131_exampleMonteCarloUni.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc17108ed91a65421698140213278ccaf3f1ad8 --- /dev/null +++ b/pool/shard006/Python/0058131_exampleMonteCarloUni.py @@ -0,0 +1,42 @@ +# Simple test of probabilistic modelling +# Calculates time to break through assuming plug flow + +from simplehydro import * +from monte_carlo import * +from conversion import * +import matplotlib.pyplot as plt + +x = 10 # Distance, x (m) +n = 0.3 # Effective porosity, n (-) +K = 1e-7 # Hydraulic conductivity, K (m/s) +H = 1 # Head where x=0 (m) +h = 0 # Head where x=x (m) +i = gradient2(H, h, x) + +# Deterministic +v = velocity2(K, i, n) +Breakthrough = x / v +print('Deterministic breakthrough in ' + str(round(secsToDays(Breakthrough), 2)) + ' days') + +# Probabilistic +I = 100001 # Number of iterations +pK = Normal(1e-7, 1e-8, I) # Input distrubution for K + +results = [] +for iteration in range(I): + results.append(velocity2(pK[iteration], i, n)) +results = [round(secsToDays(x/v), 2) for v in results] # Calculate breakthroughs +#print(results) + +# the histogram of the data +n, bins, patches = plt.hist(results, 50, normed=1, facecolor='green', alpha=0.75) + +# add a 'best fit' line +#l = plt.plot(bins, results, 'r--', linewidth=1) + +plt.xlabel('Breakthrough (days)') +plt.ylabel('Probability density') +plt.axis([0, max(results), 0, 200/I]) +plt.grid(True) + +plt.show() diff --git a/pool/shard006/Python/0058135_mmcorpus.py b/pool/shard006/Python/0058135_mmcorpus.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd5be7d2d521c55397480f03a3f4a7aed957d31 --- /dev/null +++ b/pool/shard006/Python/0058135_mmcorpus.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2010 Radim Rehurek +# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html + + +""" +Corpus in the Matrix Market format. +""" + + +import logging + +from gensim import interfaces, matutils +from gensim.corpora import IndexedCorpus + + +logger = logging.getLogger('gensim.corpora.mmcorpus') + + +class MmCorpus(matutils.MmReader, IndexedCorpus): + """ + Corpus in the Matrix Market format. + """ + def __init__(self, fname): + # avoid calling super(), too confusing + IndexedCorpus.__init__(self, fname) + matutils.MmReader.__init__(self, fname) + + def __iter__(self): + """ + Interpret a matrix in Matrix Market format as a streamed gensim corpus + (yielding one document at a time). + """ + for docId, doc in super(MmCorpus, self).__iter__(): + yield doc # get rid of docId, return the sparse vector only + + @staticmethod + def save_corpus(fname, corpus, id2word=None, progress_cnt=1000): + """ + Save a corpus in the Matrix Market format to disk. + + This function is automatically called by `MmCorpus.serialize`; don't + call it directly, call `serialize` instead. + """ + logger.info("storing corpus in Matrix Market format to %s" % fname) + num_terms = len(id2word) if id2word is not None else None + return matutils.MmWriter.write_corpus(fname, corpus, num_terms=num_terms, index=True, progress_cnt=progress_cnt) +#endclass MmCorpus diff --git a/pool/shard006/Python/0058141_package.py b/pool/shard006/Python/0058141_package.py new file mode 100644 index 0000000000000000000000000000000000000000..05f8cfa153287290696d7e64492b9f8fe3736c9e --- /dev/null +++ b/pool/shard006/Python/0058141_package.py @@ -0,0 +1,53 @@ +############################################################################## +# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/spack/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# 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) version 2.1, February 1999. +# +# 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 terms and +# conditions of 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * + + +class Dislin(Package): + """DISLIN is a high level and easy to use graphics library for displaying + data as curves, bar graphs, pie charts, 3D-colour plots, surfaces, + contours and maps.""" + + homepage = "http://www.mps.mpg.de/dislin" + url = "ftp://ftp.gwdg.de/pub/grafik/dislin/linux/i586_64/dislin-11.0.linux.i586_64.tar.gz" + + version('11.0.linux.i586_64', '6fb099b54f41db009cafc702eebb5bc6') + + depends_on('motif') + depends_on('mesa') + + def setup_environment(self, spack_env, run_env): + spack_env.set('DISLIN', self.prefix) + run_env.set('DISLIN', self.prefix) + run_env.prepend_path('PATH', self.prefix) + run_env.prepend_path('LD_LIBRARY_PATH', self.prefix) + run_env.prepend_path('LD_LIBRARY_PATH', self.spec['motif'].prefix.lib) + run_env.prepend_path('LD_LIBRARY_PATH', self.spec['mesa'].prefix.lib) + + def install(self, spec, prefix): + INSTALL = Executable('./INSTALL') + INSTALL() + with working_dir('examples'): + install('dislin_d.h', prefix) diff --git a/pool/shard006/Python/0058144_code_generator_util.py b/pool/shard006/Python/0058144_code_generator_util.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec3de69e31797c214d44c3047a1e8f733104c63 --- /dev/null +++ b/pool/shard006/Python/0058144_code_generator_util.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2010-2014, 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. + +"""Utilities to generate source codes.""" + +__author__ = "hidehiko" + +import struct +import types + + +def ToCppStringLiteral(s): + """Returns C-style string literal, or NULL if given s is None.""" + if s is None: + return 'NULL' + + if all(0x20 <= ord(c) <= 0x7E for c in s): + # All characters are in ascii code. + return '"%s"' % s.replace('\\', r'\\').replace('"', r'\"') + else: + # One or more characters are non-ascii. + return '"%s"' % ''.join(r'\x%02X' % ord(c) for c in s) + + +def FormatWithCppEscape(format_text, *args): + """Returns a string filling format with args.""" + literal_list = [] + for arg in args: + if isinstance(arg, (types.StringType, types.NoneType)): + arg = ToCppStringLiteral(arg) + literal_list.append(arg) + + return format_text % tuple(literal_list) + + +def WriteCppDataArray(data, variable_name, target_compiler, stream): + """Format data into C++ style array. + + Visual C++ does not support string literals longer than 65535 characters + so integer arrays (e.g. arrays of uint64) are used to represent byte arrays + on Windows. + + The generated code looks like: + const uint64 kVAR_data_wordtype[] = { + 0x0123456789ABCDEF, ... + }; + const char * const kVAR_data = + reinterpret_cast(kVAR_data_wordtype); + const size_t kVAR_size = 123; + + This implementation works well with other toolchains, too, but we use + string literals for other toolchains. + + The generated code with a string literal looks like: + const char kVAR_data[] = + "\\x12\\x34\\x56\\x78..."; + const size_t kVAR_size = 123; + + Args: + data: original data to be formatted. + variable_name: the core name of variables. + target_compiler: the target compiler which will compile the formatted + code. + stream: output stream. + """ + + # To accept "target_compiler = None", check taget_compiler itself first. + if target_compiler and target_compiler.startswith('msvs'): + stream.write('const uint64 k%s_data_wordtype[] = {\n' % variable_name) + + for word_index in xrange(0, len(data), 8): + word_chunk = data[word_index:word_index + 8].ljust(8, '\x00') + stream.write('0x%016X, ' % struct.unpack('(k%s_data_wordtype);\n' % ( + variable_name, variable_name)) + else: + stream.write('const char k%s_data[] =\n' % variable_name) + # Output 16bytes per line. + chunk_size = 16 + for index in xrange(0, len(data), chunk_size): + chunk = data[index:index + chunk_size] + stream.write('"') + stream.writelines(r'\x%02X' % ord(c) for c in chunk) + stream.write('"\n') + stream.write(';\n') + + stream.write('const size_t k%s_size = %d;\n' % (variable_name, len(data))) + + +def ToJavaStringLiteral(codepoint): + """Returns string literal with surrogate pair support.""" + utf16_string = unichr(codepoint).encode('utf-16be') + if len(utf16_string) == 2: + (u0, l0) = utf16_string + return r'"\u%02X%02X"' % (ord(u0), ord(l0)) + else: + (u0, l0, u1, l1) = utf16_string + return r'"\u%02X%02X\u%02X%02X"' % (ord(u0), ord(l0), ord(u1), ord(l1)) + + +def SkipLineComment(stream, comment_prefix='#'): + """Skips line comments from stream.""" + for line in stream: + stripped_line = line.strip() + if stripped_line and not stripped_line.startswith(comment_prefix): + yield line.rstrip('\n') + + +def ParseColumnStream(stream, num_column=None, delimiter=None): + """Returns parsed columns read from stream.""" + if num_column is None: + for line in stream: + yield line.rstrip('\n').split(delimiter) + else: + for line in stream: + yield line.rstrip('\n').split(delimiter)[:num_column] + + +def SelectColumn(stream, column_index): + """Returns the tuple specified by the column_index from the tuple stream.""" + for columns in stream: + yield tuple(columns[i] for i in column_index) + + +def SplitChunk(iterable, n): + """Splits sequence to consecutive n-element chunks. + + Quite similar to grouper in itertools section of python manual, + but slightly different if len(iterable) is not factor of n. + grouper extends the last chunk to make it an n-element chunk by adding + appropriate value, but this returns truncated chunk. + """ + for index in xrange(0, len(iterable), n): + yield iterable[index:index + n] diff --git a/pool/shard006/Python/0058165_command_runner.py b/pool/shard006/Python/0058165_command_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..81eff4a0dde6072922a8fb7c7b93ffe5267c0f36 --- /dev/null +++ b/pool/shard006/Python/0058165_command_runner.py @@ -0,0 +1,113 @@ + +import itertools +import queue +import subprocess +import sys +import threading +import psutil + +from repeated_timer import RepeatedTimer + +from distutils.sysconfig import get_python_lib as site_packages_dir + +class CommandRunner: + + UPDATE_INTERVAL = 5 + + def __init__(self, msg_func, master): + self.msg_func = msg_func + self.master = master + self.child_process = None + self.output_queue = queue.Queue() + self.output_read_thread = None + self.output_mutex = threading.RLock() + self.update_timer = RepeatedTimer(self.on_update_timer) + self._exitcode = None + + def _read_output(self): + while True: + # NOTE: don't use iterator interface since it uses an + # internal buffer and we don't see output in a timely fashion + line = self.child_process.stdout.readline() + if not line: + break + self.output_queue.put(line) + + def is_alive(self): + if self.child_process is None: + return False + return self.child_process.poll() is None + + def run_command(self, *args): + if self.is_alive(): + raise ValueError("already running a command") + + cmd = [sys.executable, "-u", "-m", "openslides"] + cmd.extend(args) + + creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + + self._exitcode = None + self.child_process = subprocess.Popen( + cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, creationflags=creationflags) + self.child_process.stdin.close() + + self.output_read_thread = threading.Thread(target=self._read_output) + self.output_read_thread.start() + self.update_timer.run(self.UPDATE_INTERVAL) + self.master.event_generate("<>", when="tail") + + def cancel_command(self): + if not self.is_alive(): + return + + self.msg_func("Stopping server...\n") + + # hard-kill the spawned process tree + # TODO: offer the server the chance for a clean shutdown + proc = psutil.Process(self.child_process.pid) + kill_procs = [proc] + kill_procs.extend(proc.children(recursive=True)) + for p in kill_procs: + p.kill() + + def on_update_timer(self): + is_alive = self.is_alive() + + if not is_alive: + # join thread to make sure everything was read + self.output_read_thread.join(5) + if self.output_read_thread.is_alive(): + self.msg_func("Internal error: failed to join output reader thread") + self.output_read_thread = None + + for line_no in itertools.count(): + try: + data = self.output_queue.get(block=False) + except queue.Empty: + break + else: + # XXX: check whether django uses utf-8 or locale for + # it's cli output + text = data.decode("utf-8", errors="replace") + with self.output_mutex: + self.msg_func(text) + + # avoid waiting too long here if child is still alive + if is_alive and line_no > 10: + break + + if not is_alive: + self._exitcode = self.child_process.returncode + self.update_timer.stop() + self.child_process = None + self.master.event_generate("<>", when="tail") + + def append_message(self, text, newline="\n"): + with self.output_mutex: + self.msg_func(text + newline) + + @property + def exitcode(self): + return self._exitcode diff --git a/pool/shard006/Python/0058167_p1.py b/pool/shard006/Python/0058167_p1.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac3396f8d40eac2ba8ce7b1ab8afc8becd419e0 --- /dev/null +++ b/pool/shard006/Python/0058167_p1.py @@ -0,0 +1,29 @@ +import sys +from PyQt4 import QtGui, QtCore +from PyQt4.QtCore import Qt + +class Main(QtGui.QMainWindow): + + def __init__(self, parent = None): + QtGui.QMainWindow.__init__(self,parent) + + self.initUI() + + def initUI(self): + + # x and y coordinates on the screen, width, height + self.setGeometry(100,100,1030,800) + + self.setWindowTitle("Writer") + +def main(): + + app = QtGui.QApplication(sys.argv) + + main = Main() + main.show() + + sys.exit(app.exec_()) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard006/Python/0058171_enc.py b/pool/shard006/Python/0058171_enc.py new file mode 100644 index 0000000000000000000000000000000000000000..df0f0f2e8a5a15637ca750eda5d24e4be6f20bf1 --- /dev/null +++ b/pool/shard006/Python/0058171_enc.py @@ -0,0 +1,181 @@ +'''Arsenal API ENC for puppet.''' +# Copyright 2015 CityGrid Media, 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 logging +from pyramid.view import view_config +from sqlalchemy.orm.exc import NoResultFound +from arsenalweb.models.common import ( + DBSession, +) +from arsenalweb.models.nodes import ( + Node, + ) +from arsenalweb.views.api.common import ( + api_200, + api_400, + api_500, + api_501, + ) + +LOG = logging.getLogger(__name__) + +def find_node_by_name_and_status(settings, node_name): + '''Find a node by name, filtered by statuses''' + + try: + status_ids = [s for s in settings['arsenal.enc.status_ids'].splitlines() if s] + except KeyError as ex: + msg = 'You must define arsenal.enc.status_ids in the main settings file to ' \ + 'enable the enc.' + LOG.error(msg) + raise type(ex)(ex.message + ' {0}'.format(msg)) + + node = DBSession.query(Node) + node = node.filter(Node.name == node_name) + node = node.filter(Node.status_id.in_(status_ids)) + + return node.one() + +def process_tags(tags, tag_type): + '''Processes tags. If the value is 'True' or 'False', converts it to a + boolean. Otherwise returns as-is (what about integers?).''' + + results = {} + for tag in tags: + LOG.debug('{0} tag: {1}={2}'.format(tag_type, tag.name, tag.value)) + if tag.value == 'True': + results[tag.name] = bool(tag.value) + elif tag.value == 'False': + results[tag.name] = bool('') + else: + try: + my_value = tag.value + my_value = int(my_value) + except ValueError: + pass + results[tag.name] = my_value + + return results + +def process_node_enc(settings, node_name, param_sources=False): + '''Process enc for node. Merges tags from the following three + objects in order from least to most specific: + + node_group + data_center + node + + Multiple node groups are sorted and take priority..?''' + + results = {} + results['classes'] = [] + results['parameters'] = {} + results['status'] = { + 'name': None, + } + if param_sources: + results['param_sources'] = {} + + try: + LOG.debug('ENC find the node...') + node = find_node_by_name_and_status(settings, node_name) + LOG.debug('ENC find the node complete') + results['name'] = node.name + results['id'] = node.id + results['status'] = node.status + + LOG.debug('ENC node name is: {0}'.format(node.name)) + LOG.debug('ENC node datacenter is: {0}'.format(node.data_center_id)) + + # What happens when there's more than one node group? What tags + # win, alphabetic? + LOG.debug('ENC find node_group tags...') + for node_group in node.node_groups: + LOG.debug('ENC node_group: {0}'.format(node_group.name)) + results['classes'].append(node_group.name) + my_tags = process_tags(node_group.tags, 'node_group') + results['parameters'].update(my_tags) + if param_sources: + for tag in my_tags: + results['param_sources'][tag] = 'node_group' + LOG.debug('ENC find node_group tags complete.') + + LOG.debug('ENC process data_center tags...') + try: + my_tags = process_tags(node.data_center.tags, 'data_center') + except AttributeError: + my_tags = {} + + LOG.debug('ENC process data_center tags complete.') + results['parameters'].update(my_tags) + if param_sources: + for tag in my_tags: + results['param_sources'][tag] = 'data_center' + + LOG.debug('ENC process node tags...') + my_tags = process_tags(node.tags, 'node') + results['parameters'].update(my_tags) + if param_sources: + for tag in my_tags: + results['param_sources'][tag] = 'node' + + LOG.debug('ENC process node tags complete.') + + except NoResultFound: + LOG.debug('node not found: {0}'.format(node_name)) + except (AttributeError, KeyError): + raise + + return results + +@view_config(route_name='api_enc', request_method='GET', renderer='json') +def api_enc(request): + '''External node classifier for puppet. Takes a required request parameter + 'name', finds all node_groups associated witht he node, and all tags merged + based on the following hierarchy: + + node_group + data_center + node + + Optional request parameter 'param_sources' will add an additional key that + identifies what level of the hierarchy each tag comes from. Returns a + dict.''' + + settings = request.registry.settings + try: + try: + name = request.params['name'] + except KeyError as ex: + msg = "Bad Request. Parameter 'name' is required." + LOG.error(msg) + return api_400(msg=msg) + + try: + param_sources = request.params['param_sources'] + except KeyError: + param_sources = False + + LOG.debug('Starting enc for node: {0}'.format(name)) + try: + results = process_node_enc(settings, name, param_sources=param_sources) + except (AttributeError, KeyError) as ex: + return api_501(msg=repr(ex)) + except Exception as ex: + msg = 'Error calling enc! Exception: {0}'.format(repr(ex)) + LOG.error(msg) + return api_500(msg=msg) + + return api_200(results=results) diff --git a/pool/shard006/Python/0058173_tests.py b/pool/shard006/Python/0058173_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..125fb6e3162aa328971d8031842dae8ffcb959db --- /dev/null +++ b/pool/shard006/Python/0058173_tests.py @@ -0,0 +1,55 @@ +""" +Run these tests with 'manage.py test'. +""" + +from django.test import TestCase +from django.utils import unittest +import views +import random +import string + +class XmlApiTest(unittest.TestCase): + + def test_get_files(self): + file_list = views.get_files() + self.assertTrue(len(file_list) > 0) + + def test_get_file_data(self): + file_list = views.get_files() + xml_data = views.get_file_data (file_list[0]) + self.assertTrue(len(xml_data.a) > 0) + + +class ViewTest(TestCase): + random_file_name = ''.join(random.choice(string.ascii_letters) for x in range(20)) + + def test_0_list(self): + response = self.client.get('/') + self.assertContains(response, '1.xml') + self.assertNotContains(response, self.random_file_name) + + def test_1_create(self): + params = {'file_name':self.random_file_name, 'a':'aaa'} + response = self.client.post('/create', params) + self.assertRedirects(response, '/list') + self.assertContains(response, self.random_file_name) + + def test_2_read(self): + response = self.client.get('/show/' + self.random_file_name) + self.assertContains(response, self.random_file_name) + self.assertContains(response, 'aaa') + + def test_3_update(self): + params = {'a': 'AAAA'} + response = self.client.post('/update/' + self.random_file_name, params) + self.assertRedirects(response, '/list') + response = self.client.get('/show/' + self.random_file_name) + self.assertContains(response, self.random_file_name) + self.assertContains(response, 'AAAA') + + def test_3_delete(self): + response = self.client.get('/delete/' + self.random_file_name) + self.assertRedirects(response, '/list') + self.assertContains(response, '1.xml') + self.assertNotContains(response, self.random_file_name) + diff --git a/pool/shard006/Python/0058176_client.py b/pool/shard006/Python/0058176_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f9284f0f6f27b5d5b3756a4b69d7881858aa23 --- /dev/null +++ b/pool/shard006/Python/0058176_client.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2010 Tom Burdick +# +# 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 sys +import signal +import logbook +from logbook import NullHandler +from logbook.more import ColorizedStderrHandler +import pyev + +sys.path.insert(0, '..') + +import whizzer +from whizzer import protocol + +logger = logbook.Logger('echo_client') + + +class EchoClientProtocol(protocol.Protocol): + def connection_made(self, address): + """When the connection is made, send something.""" + logger.info("connection made to {}".format(address)) + self.count = 0 + self.connected = True + self.transport.write(b'Echo Me') + + def data(self, data): + logger.info("echo'd " + data.decode('ASCII')) + if self.count < 10000: + self.count += 1 + self.transport.write(b'Echo Me') + else: + self.lose_connection() + self.connected = False + +def interrupt(watcher, events): + watcher.loop.unloop() + + +class EchoClient(object): + def __init__(self, id, loop, factory): + self.id = id + self.loop = loop + self.factory = factory + self.connect_client() + + def connect_client(self): + client = whizzer.TcpClient(self.loop, self.factory, "127.0.0.1", 2000) + logger.info('client calling connect') + d = client.connect() + logger.info('client called connect') + d.add_callback(self.connect_success) + d.add_errback(self.connect_failed) + self.timer = pyev.Timer(1.0, 0.0, self.loop, self.timeout, None) + self.timer.start() + + def connect_success(self, result): + logger.info('connect success, protocol is {}'.format(result.connected)) + self.connect_client() + self.timer.stop() + + def connect_failed(self, error): + logger.error('client {} connecting failed, reason {}'.format(id, error)) + + def timeout(self, watcher, events): + logger.error('timeout') + +def main(): + loop = pyev.default_loop() + + signal_handler = whizzer.signal_handler(loop) + + factory = whizzer.ProtocolFactory() + factory.protocol = EchoClientProtocol + + clients = [] + # number of parallel clients + for x in range(0, 2): + clients.append(EchoClient(x, loop, factory)) + + signal_handler.start() + loop.loop() + +if __name__ == "__main__": + stderr_handler = ColorizedStderrHandler(level='INFO') + null_handler = NullHandler() + with null_handler.applicationbound(): + with stderr_handler.applicationbound(): + main() diff --git a/pool/shard006/Python/0058190_task_factory.py b/pool/shard006/Python/0058190_task_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..bcca13b8cd676f82cd8c4bfec1d5b71931d2c8fe --- /dev/null +++ b/pool/shard006/Python/0058190_task_factory.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +import logging + +import rss_scrapper.tasks.concat +import rss_scrapper.tasks.dummy +import rss_scrapper.tasks.dump +import rss_scrapper.tasks.execute +import rss_scrapper.tasks.fork +import rss_scrapper.tasks.get +import rss_scrapper.tasks.print +import rss_scrapper.tasks.regex +import rss_scrapper.tasks.rss_gen +import rss_scrapper.tasks.selector +import rss_scrapper.tasks.text +import rss_scrapper.tasks.write +import rss_scrapper.tasks.xpath +from rss_scrapper.errors import ConfigurationError + +logger = logging.getLogger(__name__) +TASKS = [ + rss_scrapper.tasks.execute.ExecuteTask, + rss_scrapper.tasks.dummy.DummyTask, + rss_scrapper.tasks.print.PrintTask, + rss_scrapper.tasks.dump.DumpTask, + rss_scrapper.tasks.text.TextTask, + rss_scrapper.tasks.get.GetTask, + rss_scrapper.tasks.xpath.XPathTask, + rss_scrapper.tasks.selector.SelectorTask, + rss_scrapper.tasks.regex.RegexTask, + rss_scrapper.tasks.rss_gen.RssGenTask, + rss_scrapper.tasks.write.WriteTask, + rss_scrapper.tasks.write.ReadTask, + rss_scrapper.tasks.concat.ConcatTask, + rss_scrapper.tasks.fork.ForkTask, +] +TASKS_MAP = {task.name: task for task in TASKS} + + +def create_task(name, conf=None, parent_task=None): + if name not in TASKS_MAP: + raise ConfigurationError("the task '%s' does not exist" % name) + else: + task_class = TASKS_MAP[name] + return task_class(conf=conf, parent_task=parent_task) + + +def create_tasks(tasks_conf, parent_task=None): + tasks = [] + + if not isinstance(tasks_conf, list): + logger.error("Expected a task list and got a %s" % type(tasks_conf)) + raise ConfigurationError("no task list found", conf=tasks_conf) + + for task_conf in tasks_conf: + if isinstance(task_conf, str): + tasks.append(create_task(task_conf, parent_task=parent_task)) + + elif isinstance(task_conf, dict): + for task_name, task_args in task_conf.items(): + validate_task_name(task_name) + + try: + tasks.append(create_task(task_name, task_args, + parent_task=parent_task)) + except ConfigurationError as e: + e.conf = task_conf + raise e + else: + logger.error("Expected a task and got a %s at %s" % + (type(task_conf), task_conf)) + raise ConfigurationError("incorrect task definition", + conf=task_conf) + + return tasks + + +def execute_configuration(conf, dry_run=False): + if "feeds" not in conf: + logger.error("The configuration lacks a feeds collection," + " the yaml file should have a 'feeds' dictionary" + " at the top level") + raise ConfigurationError("no feeds found", conf=conf) + + feeds = conf["feeds"] + if not isinstance(feeds, dict): + raise ConfigurationError("'feeds' should be a dictionary instead of %s" + % type(feeds)) + + logger.debug("Found %d feed(s)" % len(feeds)) + + # We create every task before executing any for validation purposes + tasks = [] + for feed_name, tasks_conf in feeds.items(): + logger.info("Validating feed %s" % feed_name) + tasks.append((feed_name, create_task('execute', tasks_conf))) + + res = {} + for (feed_name, task) in tasks: + if not dry_run: + logger.info("Executing feed %s" % feed_name) + + task_res = task.execute(None) + + task_res_data = list(task_res) + + if len(task_res_data) == 0: + logger.info("The feed %s has not returned any data," + " nothing has been generated" % feed_name) + + res[feed_name] = task_res_data + return res + + +def validate_task_name(task_name): + if not isinstance(task_name, str): + logger.error("Expected a task name and got a %s" + % type(task_name)) + if isinstance(task_name, dict): + logger.error("Is there an indentation problem ? " + "The task's arguments should have one more " + "indentation level than its name") + raise ConfigurationError("task name should be a string", + conf=task_name) diff --git a/pool/shard006/Python/0058192_twitter_login.py b/pool/shard006/Python/0058192_twitter_login.py new file mode 100644 index 0000000000000000000000000000000000000000..de5fae42d5a9a130598882c96b7ef2f4b1d15012 --- /dev/null +++ b/pool/shard006/Python/0058192_twitter_login.py @@ -0,0 +1,17 @@ +from login import login +import time +from selenium import webdriver + +user,password = login() + +driver = webdriver.Chrome('/usr/local/bin/chromedriver') +driver.get('http://www.twitter.com/login') +userfield = driver.find_element_by_css_selector('.js-username-field.email-input.js-initial-focus') +userfield.send_keys(user) +passwordfield = driver.find_element_by_css_selector('.js-password-field') +passwordfield.send_keys(password) +passwordfield.submit() + +input("Press Enter to quit") + +driver.quit() # close browser diff --git a/pool/shard006/Python/0058194_0005_auto_20160923_0620.py b/pool/shard006/Python/0058194_0005_auto_20160923_0620.py new file mode 100644 index 0000000000000000000000000000000000000000..89c3d5f321b0b30f0973bc1324bc3f2d1b71a38d --- /dev/null +++ b/pool/shard006/Python/0058194_0005_auto_20160923_0620.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('sistema', '0004_manzana'), + ] + + operations = [ + migrations.CreateModel( + name='Lote', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('numero', models.PositiveIntegerField(unique=True)), + ('superficie', models.DecimalField(max_digits=6, decimal_places=2)), + ('ocupado', models.BooleanField(default=False)), + ('manzana', models.ForeignKey(to='sistema.Manzana')), + ], + ), + migrations.AlterField( + model_name='socio', + name='telefono', + field=models.PositiveIntegerField(unique=True), + ), + ] diff --git a/pool/shard006/Python/0058197_wordcount.py b/pool/shard006/Python/0058197_wordcount.py new file mode 100644 index 0000000000000000000000000000000000000000..61efd0f7a07333fa3b70ef710c53b02e9bba8eab --- /dev/null +++ b/pool/shard006/Python/0058197_wordcount.py @@ -0,0 +1,83 @@ +# +# 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. +# + +"""A word-counting workflow using the DataFrame API.""" + +# pytype: skip-file + +import argparse +import logging + +import apache_beam as beam +from apache_beam.dataframe.convert import to_dataframe +from apache_beam.dataframe.convert import to_pcollection +from apache_beam.io import ReadFromText +from apache_beam.options.pipeline_options import PipelineOptions + + +def run(argv=None): + """Main entry point; defines and runs the wordcount pipeline.""" + parser = argparse.ArgumentParser( + formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument( + '--input', + dest='input', + default='gs://dataflow-samples/shakespeare/kinglear.txt', + help='Input file to process.') + parser.add_argument( + '--output', + dest='output', + required=True, + help='Output file to write results to.') + known_args, pipeline_args = parser.parse_known_args(argv) + + # Import this here to avoid pickling the main session. + import re + + # The pipeline will be run on exiting the with block. + with beam.Pipeline(options=PipelineOptions(pipeline_args)) as p: + + # Read the text file[pattern] into a PCollection. + lines = p | 'Read' >> ReadFromText(known_args.input) + + words = ( + lines + | 'Split' >> beam.FlatMap( + lambda line: re.findall(r'[\w]+', line)).with_output_types(str) + # Map to Row objects to generate a schema suitable for conversion + # to a dataframe. + | 'ToRows' >> beam.Map(lambda word: beam.Row(word=word))) + + df = to_dataframe(words) + df['count'] = 1 + counted = df.groupby('word').sum() + counted.to_csv(known_args.output) + + # Deferred DataFrames can also be converted back to schema'd PCollections + counted_pc = to_pcollection(counted, include_indexes=True) + + # Print out every word that occurred >50 times + _ = ( + counted_pc + | beam.Filter(lambda row: row.count > 50) + | beam.Map(lambda row: f'{row.word}: {row.count}') + | beam.Map(print)) + + +if __name__ == '__main__': + logging.getLogger().setLevel(logging.INFO) + run() diff --git a/pool/shard006/Python/0058199_recipe-363774.py b/pool/shard006/Python/0058199_recipe-363774.py new file mode 100644 index 0000000000000000000000000000000000000000..a370244d962739d690c92c7656c96f5c6d8ca84a --- /dev/null +++ b/pool/shard006/Python/0058199_recipe-363774.py @@ -0,0 +1,48 @@ +"""Clear ``sys.modules`` of specific types of modules if one is stale.""" + +__docformat__ = "restructuredtext" + + +_lastModuleUpdate = time.time() +def clearModules(): + """Clear ``sys.modules`` of specific types of modules if one is stale. + + See ``properties.CLEAR_MODULES``. + + I took this method out of the ``InternalLibrary`` class so that you can + call it *really* early, even before you create a ``Context`` to pass to + ``InternalLibrary``. + + """ + global _lastModuleUpdate + if not properties.CLEAR_MODULES: + return + deleteTheseTypes = properties.CLEAR_MODULES + if not isinstance(deleteTheseTypes, list): + # Update Seamstress Exchange's properties file if you change this. + deleteTheseTypes = ["aquarium.layout","aquarium.navigation", + "aquarium.screen", "aquarium.widget"] + deleteThese = [ + moduleName + for moduleType in deleteTheseTypes + for moduleName in sys.modules.keys() + if (moduleName == moduleType or + moduleName.startswith(moduleType + ".")) + ] + for i in deleteThese: + try: + file = sys.modules[i].__file__ + except AttributeError: + continue + if file.endswith(".pyc") and os.path.exists(file[:-1]): + file = file[:-1] + ST_MTIME = 8 + if (_lastModuleUpdate < os.stat(file)[ST_MTIME]): + staleModules = True + break + else: + staleModules = False + if staleModules: + for i in deleteThese: # You can't modify a dictionary + del sys.modules[i] # during an iteration. + _lastModuleUpdate = time.time() diff --git a/pool/shard006/Python/0058204_jrpc_client.py b/pool/shard006/Python/0058204_jrpc_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2d8ab0190c0e4565c2d30190077ef9928c33a71f --- /dev/null +++ b/pool/shard006/Python/0058204_jrpc_client.py @@ -0,0 +1,20 @@ +import urllib2 +import json + + +def rpc_call(url, method, args): + data = json.dumps({ + 'id': 1, + 'method': method, + 'params': [args] + }).encode() + req = urllib2.Request(url, + data, + {'Content-Type': 'application/json'}) + f = urllib2.urlopen(req) + response = f.read() + return json.loads(response) + +url = 'http://localhost:1234/rpc' +args = {'A': 2, 'B': 3} +print rpc_call(url, "Arith.Multiply", args) diff --git a/pool/shard006/Python/0058214_generate.desc.dir.py b/pool/shard006/Python/0058214_generate.desc.dir.py new file mode 100644 index 0000000000000000000000000000000000000000..6edb7a3913728a294f5ef66e9a5a22310d21ef56 --- /dev/null +++ b/pool/shard006/Python/0058214_generate.desc.dir.py @@ -0,0 +1,142 @@ +__author__ = 'dat' +''' +generate descriptors from a protein in pdb format and a directory of ligands in mol2 format +''' +import os +import glob +import sys +import csv +import logging +from optparse import OptionParser + +from rfscore.config import logger +from rfscore.credo import contacts +from rfscore.ob import get_molecule + +def parse_options(): + ''' + ''' + # PARSE COMMAND LINE + usage = "%prog [options]" + parser = OptionParser(usage=usage) + + parser.add_option("--debug", + action = "store_true", + dest = "debug", + default = False, + help = 'Set logging level to debug and print more verbose output.') + + parser.add_option("-B", "--binsize", + dest = "binsize", + type = float, + default = 2, + help = "Bin size (in Angstrom) to use for binning contacts based on inter-atomic distance.") + + parser.add_option("-F", "--format", + dest = "format", + default = 'csv', + help = "Format to use for writing the SIFt of the protein-ligand complex.") + + parser.add_option("-O", "--output", + dest = "output", + default = "/home/dat/WORK/DB/Inna/hm_2esm_all329_elements_c12b2.csv",#None, + help = "File to which the data will be written (default=STDOUT).") + + parser.add_option("-L", "--inputligdir", + dest = "inputligdir", + default = "/home/dat/WORK/DB/Inna/201308_all329", + help = "Input directory of ligands in mol2 format (default=/home/).") + + parser.add_option("-P", "--inputpdb", + dest = "inputpdb", + default = "/home/dat/WORK/DB/Inna/hm_2esm.pdb", + help = "Input of protein in pdb format (default=/home/).") + + parser.add_option("-D", "--descriptor", + dest = "descriptor", + default = 'elements', + help = "Descriptor to use. Valid descriptors are 'credo', 'elements' and 'sybyl'.") + + # GET COMMAND LINE OPTIONS + (options, args) = parser.parse_args() + + if options.descriptor not in ('elements', 'credo', 'sybyl'): + logger.fatal("Invalid descriptor: {0}.".format(options.descriptor)) + parser.print_help() + sys.exit(1) + + return options + +def main(): + ''' + ''' + options = parse_options() + + # THIS OPTION WILL PRODUCE MORE VERBOSE OUTPUT + if options.debug: logger.setLevel(logging.DEBUG) + + if options.output: fh = open(options.output,'wb') + else: fh = sys.stdout + + # CHOOSE HOW THE OUPTPUT DATA WILL BE WRITTEN + if options.format == 'csv': + writer = csv.writer(fh, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) + + + HEADER = True + + # iterate through all mol2 files in inputdir + for mol2file in glob.glob(os.path.join(options.inputligdir, '*.mol2')): + #lig_path = os.path.join(option.inputdir, file) + lig_path = mol2file + protein_path = options.inputpdb + + if not os.path.isfile(protein_path): + logger.fatal("The protein file does not exist.".format(options.inputpdb)) + sys.exit(1) + + protein = get_molecule(protein_path) + ligand = get_molecule(lig_path) + + # calculate descriptor based on the sum of interacting element pairs + if options.descriptor == 'elements': + + # calculate element pair descriptor for this complex + descriptor, labels = contacts.element_descriptor(protein, ligand, + binsize=options.binsize) + + # calculate descriptor based on the sum of interacting element pairs + elif options.descriptor == 'sybyl': + + # calculate element pair descriptor for this complex + descriptor, labels = contacts.sybyl_atom_type_descriptor(protein, ligand, + binsize=options.binsize) + + # calculate descriptor using structural interaction fingerprints + elif options.descriptor == 'credo': + + # get the protein-ligand structural interaction fingerprint + descriptor, labels = contacts.sift_descriptor(protein, ligand, + binsize=options.binsize) + + if HEADER: + + # UPDATE COLUMN LABELS + labels.append('ligand') + + writer.writerow(labels) + + HEADER = False + + if options.format == 'csv': + #ligandname = "\"" + os.path.basename(lig_path).split('.')[0] + "\"" + ligandname = os.path.basename(lig_path).split('.')[0] + + #print(ligandname) + # FIRST COLUMN OF OUTPUT ROW + row = descriptor.tolist() + [ligandname] + + writer.writerow(row) + +main() + diff --git a/pool/shard006/Python/0058216_test_M4_C0808_failure.py b/pool/shard006/Python/0058216_test_M4_C0808_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..2709eec55af6a74478eda70426917e6056b658db --- /dev/null +++ b/pool/shard006/Python/0058216_test_M4_C0808_failure.py @@ -0,0 +1,41 @@ +import pandas as pd +import numpy as np +import pyaf.ForecastEngine as autof +import pyaf.Bench.TS_datasets as tsds + + +trainfile = "data/bugs/M4_C0808_failure.csv"; +#cols = ["ID" , "time", "AirPassengers"]; +df = pd.read_csv(trainfile, sep=r',', engine='python'); + +lEngine = autof.cForecastEngine() +lEngine + +print(df.head()); +print(df.tail()); +H = 2 +lEngine.train(df , "Date" , "C0808", H); +lEngine.getModelInfo(); + +lEngine.mSignalDecomposition.mBestModel.mTimeInfo.mResolution + +lEngine.standardPlots("outputs/M4_C0808_failure"); + +dfapp_in = df.copy(); +dfapp_in.tail() + +#H = 12 +dfapp_out = lEngine.forecast(dfapp_in, H); +dfapp_out.tail(2 * H) +print("Forecast Columns " , dfapp_out.columns); +Forecast_DF = dfapp_out[["Date" , "C0808", "C0808" + '_Forecast']] +print(Forecast_DF.info()) +print("Forecasts\n" , Forecast_DF.tail(H).values); + +print("\n\n") +print(lEngine.to_json()); +print("\n\n") +print("\n\n") +print(Forecast_DF.tail(2*H).to_json(date_format='iso')) +print("\n\n") + diff --git a/pool/shard006/Python/0058218_test_events.py b/pool/shard006/Python/0058218_test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..537adfc4420020b6d0c86f21c96fa736de3aae97 --- /dev/null +++ b/pool/shard006/Python/0058218_test_events.py @@ -0,0 +1,170 @@ +# -*- coding: utf-8 -*- +# Open Source Initiative OSI - The MIT License (MIT):Licensing +# +# The MIT License (MIT) +# Copyright (c) 2012 DotCloud Inc (opensource@dotcloud.com) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +# of the Software, and to permit persons to whom the Software is furnished to do +# so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + + +from zerorpc import zmq +import zerorpc +from testutils import teardown, random_ipc_endpoint + +class MokupContext(): + _next_id = 0 + + def new_msgid(self): + new_id = MokupContext._next_id + MokupContext._next_id += 1 + return new_id + + +def test_context(): + c = zerorpc.Context() + assert c.new_msgid() is not None + + +def test_event(): + context = MokupContext() + event = zerorpc.Event('mylittleevent', (None,), context=context) + print event + assert event.name == 'mylittleevent' + assert event.header['message_id'] == 0 + assert event.args == (None,) + + event = zerorpc.Event('mylittleevent2', ('42',), context=context) + print event + assert event.name == 'mylittleevent2' + assert event.header['message_id'] == 1 + assert event.args == ('42',) + + event = zerorpc.Event('mylittleevent3', ('a', 42), context=context) + print event + assert event.name == 'mylittleevent3' + assert event.header['message_id'] == 2 + assert event.args == ('a', 42) + + event = zerorpc.Event('mylittleevent4', ('b', 21), context=context) + print event + assert event.name == 'mylittleevent4' + assert event.header['message_id'] == 3 + assert event.args == ('b', 21) + + packed = event.pack() + unpacked = zerorpc.Event.unpack(packed) + print unpacked + + assert unpacked.name == 'mylittleevent4' + assert unpacked.header['message_id'] == 3 + assert unpacked.args == ('b', 21) + + event = zerorpc.Event('mylittleevent5', ('c', 24, True), + header={'lol': 'rofl'}, context=None) + print event + assert event.name == 'mylittleevent5' + assert event.header['lol'] == 'rofl' + assert event.args == ('c', 24, True) + + event = zerorpc.Event('mod', (42,), context=context) + print event + assert event.name == 'mod' + assert event.header['message_id'] == 4 + assert event.args == (42,) + event.header.update({'stream': True}) + assert event.header['stream'] is True + + +def test_events_req_rep(): + endpoint = random_ipc_endpoint() + server = zerorpc.Events(zmq.REP) + server.bind(endpoint) + + client = zerorpc.Events(zmq.REQ) + client.connect(endpoint) + + client.emit('myevent', ('arg1',)) + + event = server.recv() + print event + assert event.name == 'myevent' + assert event.args == ('arg1',) + + +def test_events_req_rep2(): + endpoint = random_ipc_endpoint() + server = zerorpc.Events(zmq.REP) + server.bind(endpoint) + + client = zerorpc.Events(zmq.REQ) + client.connect(endpoint) + + for i in xrange(10): + client.emit('myevent' + str(i), (i,)) + event = server.recv() + print event + assert event.name == 'myevent' + str(i) + assert event.args == (i,) + + server.emit('answser' + str(i * 2), (i * 2,)) + event = client.recv() + print event + assert event.name == 'answser' + str(i * 2) + assert event.args == (i * 2,) + + +def test_events_dealer_router(): + endpoint = random_ipc_endpoint() + server = zerorpc.Events(zmq.ROUTER) + server.bind(endpoint) + + client = zerorpc.Events(zmq.DEALER) + client.connect(endpoint) + + for i in xrange(6): + client.emit('myevent' + str(i), (i,)) + event = server.recv() + print event + assert event.name == 'myevent' + str(i) + assert event.args == (i,) + + server.emit('answser' + str(i * 2), (i * 2,), + xheader=dict(zmqid=event.header['zmqid'])) + event = client.recv() + print event + assert event.name == 'answser' + str(i * 2) + assert event.args == (i * 2,) + + +def test_events_push_pull(): + endpoint = random_ipc_endpoint() + server = zerorpc.Events(zmq.PULL) + server.bind(endpoint) + + client = zerorpc.Events(zmq.PUSH) + client.connect(endpoint) + + for x in xrange(10): + client.emit('myevent', (x,)) + + for x in xrange(10): + event = server.recv() + print event + assert event.name == 'myevent' + assert event.args == (x,) diff --git a/pool/shard006/Python/0058221_test_converter.py b/pool/shard006/Python/0058221_test_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..96947baf0c2b3cb68c7454fd59d448f9fdb42230 --- /dev/null +++ b/pool/shard006/Python/0058221_test_converter.py @@ -0,0 +1,62 @@ +"""Test converted models +""" +import os +import argparse +import sys +import logging +import mxnet as mx +from convert_caffe_modelzoo import convert_caffe_model, get_model_meta_info +curr_path = os.path.abspath(os.path.dirname(__file__)) +sys.path.append(os.path.join(curr_path, "../../example/image-classification")) +from test_score import download_data # pylint: disable=wrong-import-position +from score import score # pylint: disable=wrong-import-position +logging.basicConfig(level=logging.DEBUG) + +def test_imagenet_model(model_name, val_data, gpus, batch_size): + """test model on imagenet """ + logging.info('test %s', model_name) + meta_info = get_model_meta_info(model_name) + [model_name, mean] = convert_caffe_model(model_name, meta_info) + sym, arg_params, aux_params = mx.model.load_checkpoint(model_name, 0) + acc = [mx.metric.create('acc'), mx.metric.create('top_k_accuracy', top_k=5)] + if isinstance(mean, str): + mean_args = {'mean_img':mean} + else: + mean_args = {'rgb_mean':','.join([str(i) for i in mean])} + + print(val_data) + (speed,) = score(model=(sym, arg_params, aux_params), + data_val=val_data, + label_name='prob_label', + metrics=acc, + gpus=gpus, + batch_size=batch_size, + max_num_examples=500, + **mean_args) + logging.info('speed : %f image/sec', speed) + for a in acc: + logging.info(a.get()) + assert acc[0].get()[1] > meta_info['top-1-acc'] - 0.03 + assert acc[1].get()[1] > meta_info['top-5-acc'] - 0.03 + +def main(): + """Entrypoint for test_converter""" + parser = argparse.ArgumentParser(description='Test Caffe converter') + parser.add_argument('--cpu', action='store_true', help='use cpu?') + args = parser.parse_args() + if args.cpu: + gpus = '' + batch_size = 32 + else: + gpus = mx.test_utils.list_gpus() + assert gpus, 'At least one GPU is needed to run test_converter in GPU mode' + batch_size = 32 * len(gpus) + + models = ['bvlc_googlenet', 'vgg-16', 'resnet-50'] + + val = download_data() + for m in models: + test_imagenet_model(m, val, ','.join([str(i) for i in gpus]), batch_size) + +if __name__ == '__main__': + main() diff --git a/pool/shard006/Python/0058226_epydoc_ext.py b/pool/shard006/Python/0058226_epydoc_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5224693f403214f5a86f0c11a33d68493ece52 --- /dev/null +++ b/pool/shard006/Python/0058226_epydoc_ext.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 - +# +# This file is part of restkit released under the MIT license. +# See the NOTICE for more information. + +import os + +from docutils import nodes + +def api_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + """ + Role `:api:` bridges generated API documentation by epydoc with sphinx. + + Add `epydoc_ext` to the list of extensions + + Generate the documentation in build folder:: + + $ mkdir -p _build/html/api + $ epydoc -o _build/html/api ... + + Then run usual sphinx build command. + """ + + env = inliner.document.settings.env + fexists = lambda f: os.path.exists(os.path.join(env.config.api_build, f)) + api_basedir = env.config.api_basedir + + modparts = text.split('.') + name = None + uri = None + if fexists(os.path.join(api_basedir, "%s-module.html" % text)): + uri = "%s/%s" % (api_basedir, "%s-module.html" % text) + name = '%s' % text + elif fexists(os.path.join(api_basedir, "%s-class.html" % text)): + uri = uri = "%s/%s" % (api_basedir, "%s-class.html" % text) + name = modparts[-1] + else: + method = modparts[-1] + fprefix = '.'.join(modparts[:-1]) + if fexists(os.path.join(api_basedir, "%s-module.html" % fprefix)): + name = modparts[-1] + uri = '%s/%s#%s' % (api_basedir, "%s-module.html" % fprefix, + method) + elif fexists(os.path.join(api_basedir, "%s-class.html" % fprefix)): + name = '.'.join(modparts[-2:]) + uri = '%s/%s-class.html#%s' % (basedir, fprefix, method) + + if not name: + return [nodes.literal(rawtext, text)], [] + return [nodes.reference(rawtext, name, refuri="%s" % uri, **options)], [] + + +def setup(app): + app.add_config_value('api_basedir', 'api', '') + app.add_config_value('api_build', '_build/html/', '') + app.add_role('api', api_role) diff --git a/pool/shard006/Python/0058228_package.py b/pool/shard006/Python/0058228_package.py new file mode 100644 index 0000000000000000000000000000000000000000..34cc083d7155b78d38ba689278e3411e8571c6f2 --- /dev/null +++ b/pool/shard006/Python/0058228_package.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python + +""" +Helper for creating a zip file for consumption by elasticbeanstalk. + +Runs similar code to `eb deploy` from ebcli, but will just create the zipfile. This allows us to be specific about +the name and bind it to our branch & build number for later deployment. +""" + +import logging +import sys +import ebcli.core.fileoperations as fileoperations + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') + +if len(sys.argv) != 2: + print("Usage: {} FILENAME".format(sys.argv[0])) + print("Ex: {} myapp-BRANCH-BUILDNUMBER.zip".format(sys.argv[0])) + sys.exit(1) + +file_name = sys.argv[1] +file_path = fileoperations.get_zip_location(file_name) + +logging.info('Packaging application to %s', file_path) +ignore_files = fileoperations.get_ebignore_list() +fileoperations.io.log_info = lambda message: logging.debug(message) +fileoperations.zip_up_project(file_path, ignore_list=ignore_files) diff --git a/pool/shard006/Python/0058237_server_sqlalchemy.py b/pool/shard006/Python/0058237_server_sqlalchemy.py new file mode 100644 index 0000000000000000000000000000000000000000..09a972b2f9a103c119af79b19da1f2e181236d3a --- /dev/null +++ b/pool/shard006/Python/0058237_server_sqlalchemy.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# encoding: utf8 +# +# Copyright © Burak Arslan , +# Arskom Ltd. http://www.arskom.com.tr +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright 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. +# 3. Neither the name of the owner 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 HOLDER 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 logging +logging.basicConfig(level=logging.DEBUG) +logging.getLogger('rpclib.protocol.xml').setLevel(logging.DEBUG) +logging.getLogger('sqlalchemy.engine.base.Engine').setLevel(logging.DEBUG) + +import sqlalchemy + +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from sqlalchemy import MetaData +from sqlalchemy import Column + +from rpclib.application import Application +from rpclib.decorator import rpc +from rpclib.interface.wsdl import Wsdl11 +from rpclib.protocol.soap import Soap11 +from rpclib.model.complex import Iterable +from rpclib.model.primitive import Integer +from rpclib.model.table import TableModel +from rpclib.server.wsgi import WsgiApplication +from rpclib.service import ServiceBase + +_user_database = create_engine('sqlite:///:memory:') +metadata = MetaData(bind=_user_database) +DeclarativeBase = declarative_base(metadata=metadata) +Session = sessionmaker(bind=_user_database) + +# +# WARNING: You should NOT confuse sqlalchemy types with rpclib types. Whenever +# you see an rpclib service not starting due to some problem with __type_name__ +# that's probably because you did not use an rpclib type where you had to (e.g. +# inside @rpc decorator) +# + +class User(TableModel, DeclarativeBase): + __namespace__ = 'rpclib.examples.user_manager' + __tablename__ = 'rpclib_user' + + user_id = Column(sqlalchemy.Integer, primary_key=True) + user_name = Column(sqlalchemy.String(256)) + first_name = Column(sqlalchemy.String(256)) + last_name = Column(sqlalchemy.String(256)) + +# this is the same as the above user object. Use this method of declaring +# objects for tables that have to be defined elsewhere. +class AlternativeUser(TableModel, DeclarativeBase): + __namespace__ = 'rpclib.examples.user_manager' + __table__ = User.__table__ + +class UserManagerService(ServiceBase): + @rpc(User, _returns=Integer) + def add_user(ctx, user): + ctx.udc.session.add(user) + ctx.udc.session.flush() + + return user.user_id + + @rpc(Integer, _returns=User) + def get_user(ctx, user_id): + return ctx.udc.session.query(User).filter_by(user_id=user_id).one() + + @rpc(User) + def set_user(ctx, user): + ctx.udc.session.merge(user) + + @rpc(Integer) + def del_user(ctx, user_id): + ctx.udc.session.query(User).filter_by(user_id=user_id).delete() + + @rpc(_returns=Iterable(AlternativeUser)) + def get_all_user(ctx): + return ctx.udc.session.query(User) + +class UserDefinedContext(object): + def __init__(self): + self.session = Session() + +def _on_method_call(ctx): + ctx.udc = UserDefinedContext() + +def _on_method_return_object(ctx): + ctx.udc.session.commit() + ctx.udc.session.close() + +application = Application([UserManagerService], 'rpclib.examples.user_manager', + interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11()) + +application.event_manager.add_listener('method_call', _on_method_call) +application.event_manager.add_listener('method_return_object', _on_method_return_object) + +if __name__=='__main__': + try: + from wsgiref.simple_server import make_server + except ImportError: + print "Error: example server code requires Python >= 2.5" + + wsgi_app = WsgiApplication(application) + server = make_server('127.0.0.1', 7789, wsgi_app) + + metadata.create_all() + print "listening to http://127.0.0.1:7789" + print "wsdl is at: http://localhost:7789/?wsdl" + + server.serve_forever() diff --git a/pool/shard006/Python/0058240_http_calls.py b/pool/shard006/Python/0058240_http_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..52da69e686b5d6a19bc5e6775f23a6efb0ffef3e --- /dev/null +++ b/pool/shard006/Python/0058240_http_calls.py @@ -0,0 +1,82 @@ +from threading import Thread +from flask import request,jsonify +import imp +import facebook_osc_connect +import generator +import webserver.settings +from postpreprocess.spell_check import PreProcessor +import settings + +import sys +import traceback + +queue = [] +threadids = [] + +def process_from_facebook(addr, tags, stuff, source): + print('FACEBOOK receiving: ', addr, tags, stuff) + raw_input = stuff[0] + thread_id = stuff[1] + processed_input, _, __ = preProc.process(raw_input) + answer = generator.get_result(processed_input) + processed_output, _, __ = preProc.process(answer, return_to_lower=True) + print('FACEBOOK done: ' + processed_output) + facebook.send(processed_output, thread_id) + +preProc = PreProcessor() +generator = None +facebook = facebook_osc_connect.OscFacebook() +facebook.add_callback('/get', process_from_facebook) + + +def set_generator(gen): + global generator + print 'setting gen', gen + generator = gen + + +def input(input): + global generator + ''' + main function to get a return from machine + :return: + ''' + processed_input, _, __ = preProc.process(input) + + response = {} + def ml_magic(input): + + processed_input, _, __ = preProc.process(input) + answer = generator.get_result(processed_input) + processed_output, _, __ = preProc.process(answer, return_to_lower=True) + + try: + print "CALL ML MAGIC HERE... for: ",processed_output + response['status'] = 'ml-response' + response['response'] = processed_output + except: + print("Unexpected error:", sys.exc_info()[0]) + traceback.print_exc() + response['status'] = 'error' + + ml_thread = Thread(target=ml_magic, args=(processed_input,)) + ml_thread.start() + ml_thread.join(settings.MAX_MACHINE_TIME) + if ml_thread.is_alive: + return jsonify(response) + else: + return jsonify({'status': 'ml-timeout', 'response': 'boomchickawaowao'}) + + +def text_preproccess(input): + print input + if input.startswith('\"'): + input = input[1:-1] + # process + processed, spell_checked, grammar_checked = preProc.process(input) + + output_json = jsonify(**{"grammar_corrected" : grammar_checked, + "spell_checked" : spell_checked, + "combined" : processed}) + print ">> ", output_json + return output_json diff --git a/pool/shard006/Python/0058242_create_user_configuration.py b/pool/shard006/Python/0058242_create_user_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..93bfcb84a7bc7b4629bbb715e5f6303b72241e49 --- /dev/null +++ b/pool/shard006/Python/0058242_create_user_configuration.py @@ -0,0 +1,19 @@ +from ..util import create_element, set_xml_value +from .common import EWSAccountService + + +class CreateUserConfiguration(EWSAccountService): + """MSDN: + https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/createuserconfiguration-operation + """ + + SERVICE_NAME = "CreateUserConfiguration" + returns_elements = False + + def call(self, user_configuration): + return self._get_elements(payload=self.get_payload(user_configuration=user_configuration)) + + def get_payload(self, user_configuration): + return set_xml_value( + create_element(f"m:{self.SERVICE_NAME}"), user_configuration, version=self.protocol.version + ) diff --git a/pool/shard006/Python/0058249_ColorButton.py b/pool/shard006/Python/0058249_ColorButton.py new file mode 100644 index 0000000000000000000000000000000000000000..7e677f735be7f581ce05301008264d836cf9fc00 --- /dev/null +++ b/pool/shard006/Python/0058249_ColorButton.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +from pyqtgraph.Qt import QtGui, QtCore +import pyqtgraph.functions as functions + +__all__ = ['ColorButton'] + +class ColorButton(QtGui.QPushButton): + + sigColorChanging = QtCore.Signal(object) ## emitted whenever a new color is picked in the color dialog + sigColorChanged = QtCore.Signal(object) ## emitted when the selected color is accepted (user clicks OK) + + def __init__(self, parent=None, color=(128,128,128)): + QtGui.QPushButton.__init__(self, parent) + self.setColor(color) + self.colorDialog = QtGui.QColorDialog() + self.colorDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True) + self.colorDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog, True) + self.colorDialog.currentColorChanged.connect(self.dialogColorChanged) + self.colorDialog.rejected.connect(self.colorRejected) + self.colorDialog.colorSelected.connect(self.colorSelected) + #QtCore.QObject.connect(self.colorDialog, QtCore.SIGNAL('currentColorChanged(const QColor&)'), self.currentColorChanged) + #QtCore.QObject.connect(self.colorDialog, QtCore.SIGNAL('rejected()'), self.currentColorRejected) + self.clicked.connect(self.selectColor) + self.setMinimumHeight(15) + self.setMinimumWidth(15) + + def paintEvent(self, ev): + QtGui.QPushButton.paintEvent(self, ev) + p = QtGui.QPainter(self) + rect = self.rect().adjusted(6, 6, -6, -6) + ## draw white base, then texture for indicating transparency, then actual color + p.setBrush(functions.mkBrush('w')) + p.drawRect(rect) + p.setBrush(QtGui.QBrush(QtCore.Qt.DiagCrossPattern)) + p.drawRect(rect) + p.setBrush(functions.mkBrush(self._color)) + p.drawRect(rect) + p.end() + + def setColor(self, color, finished=True): + self._color = functions.mkColor(color) + if finished: + self.sigColorChanged.emit(self) + else: + self.sigColorChanging.emit(self) + self.update() + + def selectColor(self): + self.origColor = self.color() + self.colorDialog.setCurrentColor(self.color()) + self.colorDialog.open() + + def dialogColorChanged(self, color): + if color.isValid(): + self.setColor(color, finished=False) + + def colorRejected(self): + self.setColor(self.origColor, finished=False) + + def colorSelected(self, color): + self.setColor(self._color, finished=True) + + def saveState(self): + return functions.colorTuple(self._color) + + def restoreState(self, state): + self.setColor(state) + + def color(self): + return functions.mkColor(self._color) + + def widgetGroupInterface(self): + return (self.sigColorChanged, ColorButton.saveState, ColorButton.restoreState) + +if __name__ == '__main__': + app = QtGui.QApplication([]) + win = QtGui.QMainWindow() + btn = ColorButton() + win.setCentralWidget(btn) + win.show() + + def change(btn): + print "change", btn.color() + def done(btn): + print "done", btn.color() + + btn.sigColorChanging.connect(change) + btn.sigColorChanged.connect(done) + + ## Start Qt event loop unless running in interactive mode. + import sys + if sys.flags.interactive != 1: + app.exec_() diff --git a/pool/shard006/Python/0058256_ImDiff.py b/pool/shard006/Python/0058256_ImDiff.py new file mode 100644 index 0000000000000000000000000000000000000000..642fc7e6e5598ca128b95adc2b5659ca9b3d5a9c --- /dev/null +++ b/pool/shard006/Python/0058256_ImDiff.py @@ -0,0 +1,87 @@ +import cv2 +import numpy as np +import CropImage +from random import randint + + +def imDiff(im1, im2): + + # im1 = im1[0:im1.shape[0]-8, 0:im1.shape[1]] + # im2 = im2[0:im2.shape[0]-8, 0:im2.shape[1]] + + imGray1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) + imGray2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) + print(im1.shape, im2.shape) + im = cv2.absdiff(imGray1, imGray2) + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)) + thresh = cv2.erode(im, kernel, iterations=3) + thresh = cv2.erode(thresh, kernel, iterations=3) + ret, thresh = cv2.threshold(im, 127,255, cv2.THRESH_BINARY) + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3)) + # finalIm = thresh + thresh = cv2.dilate(thresh, kernel, iterations=2) + # thresh = cv2.cvtColor(thresh, cv2.COLOR_BGR2GRAY) + img2, contours,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_TC89_KCOS ) + # finalIm = cv2.erode(finalIm, kernel=np.ones(shape=(3, 3), dtype=np.uint8)) + contours = [cc for cc in contours if 10 < cv2.contourArea(cc) < 15000] + '''for c in contours: + x,y,w,h = cv2.boundingRect(c) + M = cv2.moments(c) + cX = int(M["m10"] / M["m00"]) + cY = int(M["m01"] / M["m00"])''' + #cv2.circle(im, (cX, cY), 2, (255, 0, 2), 3) + #cv2.rectangle(im, (cX, cY), (cX+w, cY+h), (0, 255, 0), 2) + colors = [] + for i in range(50): + colors.append((randint(0,255), randint(0,255), randint(0,255))) + # finalIm = cv2.cvtColor(im1, cv2.COLOR_GRAY2BGR) + # testEllipse = ((100, 50), (20, 100), 90) + # cv2.ellipse(im2, testEllipse, (0,0,255), 3) + # cv2.circle(im2, (50, 118), 2, (255,0,0)) + # cv2.circle(im2, (100, 100), 2, (255,0,0)) + for i, cnt in enumerate(contours): + try: + # ellipse = cv2.fitEllipse(cnt) + # if ellipse[0][0] < 0 or ellipse[0][0] > im.shape[1] or ellipse[0][1] < 0 or ellipse[0][1] > im.shape[0]: + # continue + # cv2.ellipse(im1, ellipse, colors[i], 1) + # cv2.ellipse(im2, ellipse, colors[i], 1) + cv2.drawContours(im1, [cnt], 0, colors[i], 1) + cv2.drawContours(im2, [cnt], 0, colors[i], 1) + except cv2.error: + continue + # cv2.drawContours(im1, [cnt], 0, colors[i], 2) + # cv2.drawContours(im2, [cnt], 0, colors[i], 2) + # cv2.drawContours(finalIm, contours, -1, (0,255,0), 2) + # cv2.imwrite('p441.png', im1) + # cv2.imwrite('p442.png', im2) + cv2.imshow('diff', thresh) + # cv2.waitKey() + # cv2.imwrite("difference.png", finalIm) + return im1, im2 + +if __name__ == '__main__': + + Folder = 'C:\\Users\\soumy\\Downloads\\HocusFocusSeg\\HocusFocusSeg\\' + + import os + + DownImages = [] + for f in os.listdir(Folder + 'down'): + DownImages.append(Folder + 'down\\' + str(f)) + + UpImages = [] + for f in os.listdir(Folder + 'up'): + UpImages.append(Folder + 'up\\' + str(f)) + + for u, d in zip(UpImages, DownImages): + print(u, d) + im1 = cv2.imread(u, cv2.IMREAD_GRAYSCALE) + im2 = cv2.imread(d, cv2.IMREAD_GRAYSCALE) + + # dilated1 = cv2.dilate(im1, kernel=np.zeros(shape=(3, 3)), iterations=1) + # dilated2 = cv2.dilate(im2, kernel=np.zeros(shape=(3, 3)), iterations=1) + + # imDiff(dilated1, dilated2) + imOut = CropImage.cropImage(im1, im2) + imDiff(im1, imOut) \ No newline at end of file diff --git a/pool/shard006/Python/0058265_views.py b/pool/shard006/Python/0058265_views.py new file mode 100644 index 0000000000000000000000000000000000000000..26815c82d49d3227bea92535f4cf62ea4f16275d --- /dev/null +++ b/pool/shard006/Python/0058265_views.py @@ -0,0 +1,42 @@ +from apps.proveedores.forms import ProveedorForm +from apps.proveedores.models import Proveedor +from django.views.generic import ListView, CreateView, UpdateView, DeleteView +from django.core.urlresolvers import reverse_lazy +# Create your views here. + + +class ProveedorList(ListView): + """ + Crea una lista con todos los proveedores dados de alta en el modelo + """ + model = Proveedor + template_name = 'proveedor/proveedor_lista.html' + + +class ProveedorUpdate(UpdateView): + """ + Muestra un formulario para la edición de proveedores + """ + model = Proveedor + form_class = ProveedorForm + template_name = 'proveedor/proveedor_form.html' + success_url = reverse_lazy('proveedor:proveedor_listar') + + +class ProveedorCreate(CreateView): + """ + Muestra un formulario para la creación de proveedores + """ + model = Proveedor + form_class = ProveedorForm + template_name = 'proveedor/proveedor_form.html' + success_url = reverse_lazy('proveedor:proveedor_listar') + + +class ProveedorDelete(DeleteView): + """ + Se le pide al usuario se desea la eliminación de proveedores + """ + model = Proveedor + template_name = 'proveedor/proveedor_delete.html' + success_url = reverse_lazy('proveedor:proveedor_listar') diff --git a/pool/shard006/Python/0058270_make-denovo-distance-slurms.py b/pool/shard006/Python/0058270_make-denovo-distance-slurms.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbb7a0f520f47cc2524202d31ef1ab875ff2a35 --- /dev/null +++ b/pool/shard006/Python/0058270_make-denovo-distance-slurms.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +#========================================================================= +# This is OPEN SOURCE SOFTWARE governed by the Gnu General Public +# License (GPL) version 3, as described at www.opensource.org. +# Copyright (C)2017 William H. Majoros (martiandna@gmail.com). +#========================================================================= +from __future__ import (absolute_import, division, print_function, + unicode_literals, generators, nested_scopes, with_statement) +from builtins import (bytes, dict, int, list, object, range, str, ascii, + chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) +# The above imports should allow this program to run in both Python 2 and +# Python 3. You might need to update your version of module "future". +import sys +import ProgramName +from SlurmWriter import SlurmWriter + +EXCLUDE="#SBATCH --exclude=x2-01-1,x2-01-2,x2-01-3,x2-01-4,x2-02-1,x2-02-2,x2-02-3,x2-02-4,x2-03-1\n" +THOUSAND="/home/bmajoros/1000G/assembly" +RNA=THOUSAND+"/rna150" +ID_LIST=RNA+"/IDs.txt" +SRC=THOUSAND+"/src" +PROGRAM=SRC+"/get-denovo-distances.py" +SLURM_DIR=RNA+"/distance-slurms" +JOB_NAME="DIST" +MAX_PARALLEL=1000 +NICE=500 +MEMORY=50000 +THREADS=0 + +#========================================================================= +# main() +#========================================================================= + +writer=SlurmWriter() +with open(ID_LIST,"rt") as IN: + for line in IN: + for hap in (1,2): + ID=line.rstrip() + outfile=RNA+"/distances/"+ID+"."+str(hap) + cmd=PROGRAM+" "+ID+" "+str(hap)+" > "+outfile + writer.addCommand(cmd) +writer.setQueue("new,all") +writer.nice(NICE) +if(MEMORY): writer.mem(MEMORY) +if(THREADS): writer.threads(THREADS) +writer.writeArrayScript(SLURM_DIR,JOB_NAME,MAX_PARALLEL,EXCLUDE) + + + diff --git a/pool/shard006/Python/0058276_finders.py b/pool/shard006/Python/0058276_finders.py new file mode 100644 index 0000000000000000000000000000000000000000..c18253807278a7f373e76bc5a5c0704b2fd5f05f --- /dev/null +++ b/pool/shard006/Python/0058276_finders.py @@ -0,0 +1,97 @@ +from django.contrib.staticfiles.finders import BaseFinder, AppDirectoriesFinder, FileSystemFinder, find +from django.utils._os import safe_join + +from pipeline.conf import settings + + +class PipelineFinder(BaseFinder): + def find(self, path, all=False): + """ + Looks for files in PIPELINE_CSS and PIPELINE_JS + """ + matches = [] + for elem in settings.PIPELINE_CSS.values() + settings.PIPELINE_JS.values(): + if elem['output_filename'] == path: + match = safe_join(settings.PIPELINE_ROOT, path) + if not all: + return match + matches.append(match) + return matches + + def list(self, *args): + return [] + + +class CachedFileFinder(BaseFinder): + def find(self, path, all=False): + """ + Work out the uncached name of the file and look that up instead + """ + try: + start, _, extn = path.rsplit('.', 2) + path = '.'.join((start, extn)) + return find(path, all=all) + except ValueError: + return [] + + def list(self, *args): + return [] + + +class PatternFilterMixin(object): + ignore_patterns = [] + + def get_ignored_patterns(self): + return list(set(self.ignore_patterns)) + + def list(self, ignore_patterns): + if ignore_patterns: + ignore_patterns = ignore_patterns + self.get_ignored_patterns() + return super(PatternFilterMixin, self).list(ignore_patterns) + + +class AppDirectoriesFinder(PatternFilterMixin, AppDirectoriesFinder): + """ + Like AppDirectoriesFinder, but doesn't return any additional ignored + patterns. + + This allows us to concentrate/compress our components without dragging + the raw versions in via collectstatic. + """ + ignore_patterns = [ + '*.js', + '*.css', + '*.less', + '*.scss', + ] + + +class FileSystemFinder(PatternFilterMixin, FileSystemFinder): + """ + Like FileSystemFinder, but doesn't return any additional ignored patterns + + This allows us to concentrate/compress our components without dragging + the raw versions in too. + """ + ignore_patterns = [ + '*.js', + '*.less', + '*.scss', + '*.sh', + '*.html', + '*.md', + '*.markdown', + '*.php', + '*.txt', + 'README*', + 'LICENSE*', + '*examples*', + '*test*', + '*bin*', + '*samples*', + '*docs*', + '*build*', + '*demo*', + 'Makefile*', + 'Gemfile*', + ] diff --git a/pool/shard006/Python/0058290_CheckVoltage.py b/pool/shard006/Python/0058290_CheckVoltage.py new file mode 100644 index 0000000000000000000000000000000000000000..48290bf1b5e0fbb891e688801deb67b9177c0a39 --- /dev/null +++ b/pool/shard006/Python/0058290_CheckVoltage.py @@ -0,0 +1,36 @@ +#!/usr/bin/python + +import RPi.GPIO as GPIO , time +from subprocess import call +import shlex +import sys + +import signal + +def handler(signum, frame): +# call(shlex.split("echo -ne '\e[u''\e[0m'")) + sys.exit() + +signal.signal(signal.SIGINT, handler) + +redLED=35 +GPIO.setmode(GPIO.BCM) +GPIO.setup(redLED, GPIO.IN) + +powerlow=0 +#call(shlex.split("echo -ne '\e[s'")) +while True: + if(GPIO.input(redLED)==0): + call(shlex.split("echo -ne '\e[s''\e[1;56H''\e[1;31m'POWER dipped below 4.63v'\e[u''\e[0m'")) + powerlow += 1 + else: + powerlow = 0 + call(shlex.split("echo -ne '\e[s''\e[1;78H''\e[1;31m'ON'\e[u''\e[0m'")) + + if (powerlow > 3): + break + + time.sleep(1) + +#call(shlex.split("echo -ne '\e[u''\e[0m'")) +print "Low power for " + str(powerlow) + " seconds" \ No newline at end of file diff --git a/pool/shard006/Python/0058294_core.py b/pool/shard006/Python/0058294_core.py new file mode 100644 index 0000000000000000000000000000000000000000..b69f3a7bf2e5645131a219e721d4be7d3ba8c49b --- /dev/null +++ b/pool/shard006/Python/0058294_core.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import +from envparse import env +from .locator import Locator +from .matrix import Renderer, Matrix +import time +import signal +import sys + +matrix = None +renderer = None + +def sigint_handler(signal, frame): + global matrix, renderer + if matrix: + matrix.clear() + if renderer: + renderer.join(1.0) + sys.exit(0) + +def parse_stop_ids(stop_ids): + return [id_and_dir.split('/') for id_and_dir in stop_ids.split(',')] + +def main(args): + global matrix, renderer + poll_interval = env('POLL_INTERVAL', default=30, cast=int) + display_delay = env('DISPLAY_DELAY', default=8, cast=int) + api_key = env('API_KEY') + stop_ids = env('STOP_IDS') # using format: 7637/inbound,8475/outbound + matrix_rows = env('MATRIX_ROWS', default=16, cast=int) + matrix_chain_length = env('MATRIX_CHAIN_LENGTH', default=1, cast=int) + + matrix = Matrix(rows=matrix_rows, chain_length=matrix_chain_length) + locators = [Locator(api_key=api_key, stop_id=sid, direction=dir) for (sid,dir) in parse_stop_ids(stop_ids)] + + signal.signal(signal.SIGINT, sigint_handler) + + renderer = Renderer(matrix, locators, delay=display_delay) + renderer.daemon = True + while True: + if not renderer.is_alive(): + renderer.start() + time.sleep(poll_interval) + +if __name__ == '__main__': + import sys + main(sys.argv[1:]) diff --git a/pool/shard006/Python/0058299_save_pdbs.py b/pool/shard006/Python/0058299_save_pdbs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b40191e14ccb8421c4e5e67372fe05137fe039 --- /dev/null +++ b/pool/shard006/Python/0058299_save_pdbs.py @@ -0,0 +1,11 @@ +import numpy as np +import pandas as pd +import mdtraj as md + +#os.system("hmsm means-ghmm --filename hmms.jsonlines --lag-time 1 --n-states 3 -o out.csv --dir Trajectories --top system.subset.pdb --ext h5 -a AtomIndices.dat") +name = "atompairs" + +df = pd.read_csv("./samples-%s.csv" % name) +for k, row in df.iterrows(): + trj = md.load(row["filename"])[row["index"]] + trj.save("./PDB-%s/State%d-mean.pdb" % (name, row["state"])) diff --git a/pool/shard006/Python/0058301_combine_shr_shl_by_constant_64.py b/pool/shard006/Python/0058301_combine_shr_shl_by_constant_64.py new file mode 100644 index 0000000000000000000000000000000000000000..c011a2616204a22e3cad67c86b9f93cdf4bb6fa9 --- /dev/null +++ b/pool/shard006/Python/0058301_combine_shr_shl_by_constant_64.py @@ -0,0 +1,44 @@ +from rule import Rule +from opcodes import * + +""" +Rule: +mask = shlWorkaround(u256(-1) >> unsigned(A.d()), unsigned(B.d())) +SHL(B, SHR(A, X)) -> AND(SH[L/R]([B - A / A - B], X), Mask) +Requirements: +A < BitWidth +B < BitWidth +""" + +rule = Rule() + +n_bits = 64 + +# Input vars +X = BitVec('X', n_bits) +A = BitVec('A', n_bits) +B = BitVec('B', n_bits) + +# Constants +BitWidth = BitVecVal(n_bits, n_bits) + +# Requirements +rule.require(ULT(A, BitWidth)) +rule.require(ULT(B, BitWidth)) + +# Non optimized result +nonopt = SHL(B, SHR(A, X)) + +# Optimized result +Mask = SHL(B, SHR(A, Int2BV(IntVal(-1), n_bits))) +opt = If( + UGT(A, B), + AND(SHR(A - B, X), Mask), + If( + UGT(B, A), + AND(SHL(B - A, X), Mask), + AND(X, Mask) + ) + ) + +rule.check(nonopt, opt) diff --git a/pool/shard006/Python/0058307_aiplatform_v1_generated_index_service_list_indexes_sync.py b/pool/shard006/Python/0058307_aiplatform_v1_generated_index_service_list_indexes_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..9048e9b3cd0d9b4d186e21edd257976a05db29d8 --- /dev/null +++ b/pool/shard006/Python/0058307_aiplatform_v1_generated_index_service_list_indexes_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 ListIndexes +# 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-aiplatform + + +# [START aiplatform_v1_generated_IndexService_ListIndexes_sync] +from google.cloud import aiplatform_v1 + + +def sample_list_indexes(): + # Create a client + client = aiplatform_v1.IndexServiceClient() + + # Initialize request argument(s) + request = aiplatform_v1.ListIndexesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_indexes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END aiplatform_v1_generated_IndexService_ListIndexes_sync] diff --git a/pool/shard006/Python/0058308_renderers.py b/pool/shard006/Python/0058308_renderers.py new file mode 100644 index 0000000000000000000000000000000000000000..e4369c6e59501cda6109d9f591071ed1ee7d2c21 --- /dev/null +++ b/pool/shard006/Python/0058308_renderers.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from rest_framework import renderers +from rest_framework.exceptions import APIException + +from shop.models.cart import CartModel +from shop.serializers.cart import CartSerializer + + +class TemplateContextMixin(object): + """ + Alternative implementation which does not pollute the template context with + the serialized data on the root scope. + """ + def get_template_context(self, data, renderer_context): + response = renderer_context['response'] + if response.exception: + return dict(data, status_code=response.status_code) + else: + view = renderer_context['view'] + key = getattr(view, 'context_data_name', 'data') + return {key: data} + + + +class ShopTemplateHTMLRenderer(TemplateContextMixin, renderers.TemplateHTMLRenderer): + """ + Modified TemplateHTMLRenderer, which shall be used to render templates used by django-SHOP. + Instead of polluting the template context with the serialized data, that information is + stored inside a separate `data` attribute, which allows to add a Cart and Paginator object. + + Templates created for this renderer are compatible with the `CMSPageRenderer` (see below). + """ + def render(self, data, accepted_media_type=None, renderer_context=None): + request = renderer_context['request'] + response = renderer_context['response'] + + if response.exception: + template = self.get_exception_template(response) + template_context = self.get_template_context(data, renderer_context) + return template.render(template_context) + + view = renderer_context['view'] + template_names = self.get_template_names(response, view) + template = self.resolve_template(template_names) + template_context = self.get_template_context(data, renderer_context) + self.update_with_cart_context(renderer_context) + template_context.update(renderer_context, paginator=view.paginator) + return template.render(template_context, request=request) + + def update_with_cart_context(self, context): + try: + cart = CartModel.objects.get_from_request(context['request']) + context['is_cart_filled'] = cart.items.exists() + cart_serializer = CartSerializer(cart, context=context, label='cart') + context['cart'] = cart_serializer.data + except (KeyError, CartModel.DoesNotExist): + pass + + +class CMSPageRenderer(TemplateContextMixin, renderers.TemplateHTMLRenderer): + """ + Modified TemplateHTMLRenderer, which is able to render CMS pages containing the templatetag + ``{% render_placeholder ... %}``, in addition to accept ordinary Python objects in their + rendering context. + + The serialized data object, as available to other REST renderers, is explicitly added to the + context as ``data``. Therefore keep in mind that templates for REST's + :class:`rest_framework.renderers.TemplateHTMLRenderer` are not compatible with this renderer. + """ + def render(self, data, accepted_media_type=None, renderer_context=None): + renderer_context = renderer_context or {} + view = renderer_context['view'] + request = renderer_context['request'] + response = renderer_context['response'] + + if not getattr(request, 'current_page', None): + msg = "APIView class '{}' with 'renderer_class=(CMSPageRenderer, ...)' can only be used by a CMSApp" + response = view.handle_exception(APIException(detail=msg.format(view.__class__))) + + if response.exception: + template = self.get_exception_template(response) + template_context = self.get_template_context(data, renderer_context) + return template.render(context=template_context, request=request) + + # set edit_mode, so that otherwise invisible placeholders can be edited inline + edit_mode = getattr(request.current_page, 'publisher_is_draft', False) + + template_names = [request.current_page.get_template()] + template = self.resolve_template(template_names) + template_context = self.get_template_context(data, renderer_context) + template_context.update( + renderer_context, + paginator=view.paginator, + edit_mode=edit_mode, + ) + return template.render(template_context, request=request) diff --git a/pool/shard006/Python/0058314_test_censure.py b/pool/shard006/Python/0058314_test_censure.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd8a90f0b504e3630c33720565c1e52a149344f --- /dev/null +++ b/pool/shard006/Python/0058314_test_censure.py @@ -0,0 +1,100 @@ +import numpy as np +from numpy.testing import assert_array_equal, assert_raises +from skimage.data import moon +from skimage.feature import CENSURE +from skimage._shared.testing import test_parallel + + +img = moon() +np.random.seed(0) + + +def test_censure_on_rectangular_images(): + """Censure feature detector should work on 2D image of any shape.""" + rect_image = np.random.rand(300, 200) + square_image = np.random.rand(200, 200) + CENSURE().detect((square_image)) + CENSURE().detect((rect_image)) + + +def test_keypoints_censure_color_image_unsupported_error(): + """Censure keypoints can be extracted from gray-scale images only.""" + assert_raises(ValueError, CENSURE().detect, np.zeros((20, 20, 3))) + + +def test_keypoints_censure_mode_validity_error(): + """Mode argument in keypoints_censure can be either DoB, Octagon or + STAR.""" + assert_raises(ValueError, CENSURE, mode='dummy') + + +def test_keypoints_censure_scale_range_error(): + """Difference between the the max_scale and min_scale parameters in + keypoints_censure should be greater than or equal to two.""" + assert_raises(ValueError, CENSURE, min_scale=1, max_scale=2) + + +def test_keypoints_censure_moon_image_dob(): + """Verify the actual Censure keypoints and their corresponding scale with + the expected values for DoB filter.""" + detector = CENSURE() + detector.detect(img) + expected_keypoints = np.array([[ 21, 497], + [ 36, 46], + [119, 350], + [185, 177], + [287, 250], + [357, 239], + [463, 116], + [464, 132], + [467, 260]]) + expected_scales = np.array([3, 4, 4, 2, 2, 3, 2, 2, 2]) + + assert_array_equal(expected_keypoints, detector.keypoints) + assert_array_equal(expected_scales, detector.scales) + + +@test_parallel() +def test_keypoints_censure_moon_image_octagon(): + """Verify the actual Censure keypoints and their corresponding scale with + the expected values for Octagon filter.""" + + detector = CENSURE(mode='octagon') + detector.detect(img) + expected_keypoints = np.array([[ 21, 496], + [ 35, 46], + [287, 250], + [356, 239], + [463, 116]]) + + expected_scales = np.array([3, 4, 2, 2, 2]) + + assert_array_equal(expected_keypoints, detector.keypoints) + assert_array_equal(expected_scales, detector.scales) + + +def test_keypoints_censure_moon_image_star(): + """Verify the actual Censure keypoints and their corresponding scale with + the expected values for STAR filter.""" + detector = CENSURE(mode='star') + detector.detect(img) + expected_keypoints = np.array([[ 21, 497], + [ 36, 46], + [117, 356], + [185, 177], + [260, 227], + [287, 250], + [357, 239], + [451, 281], + [463, 116], + [467, 260]]) + + expected_scales = np.array([3, 3, 6, 2, 3, 2, 3, 5, 2, 2]) + + assert_array_equal(expected_keypoints, detector.keypoints) + assert_array_equal(expected_scales, detector.scales) + + +if __name__ == '__main__': + from numpy import testing + testing.run_module_suite() diff --git a/pool/shard006/Python/0058315_make_meta.py b/pool/shard006/Python/0058315_make_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..8320991e14f2e2022f2f6c2caa1e4e6eeaed09bb --- /dev/null +++ b/pool/shard006/Python/0058315_make_meta.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +meta_template = """ +package: + name: {pytraj_status} + version: !!str {pytraj_version} + +source: +{source} + +requirements: + build: + - python + - cython + - libcpptraj {libcpptraj_version} + - libnetcdf + run: + - python + - libcpptraj {libcpptraj_version} + - libnetcdf + - numpy + +test: + commands: + - python -c 'import pytraj as pt; pt.show_versions(); from pytraj.testing import get_remd_fn' + +about: + home: http://github.com/amber-md/pytraj + license: GPL v3 + summary: Python API for cpptraj - a package for data analysis of MD simulations +""" + +source_git = """ + git_url: https://github.com/amber-md/pytraj.git + git_tag: master +""" + +source_pypi = """ + fn: pytraj-{pytraj_version}.tar.gz + # url: https://pypi.python.org/packages/source/p/pytraj/pytraj-{pytraj_version}.tar.gz + url: https://anaconda.org/hainm/pytraj/1.0.6/download/pytraj-{pytraj_version}.tar.gz +""" + + +if __name__ == '__main__': + import sys + from argparse import ArgumentParser + + parser = ArgumentParser() + parser.add_argument('-lc', + '--libcpptraj-version', + default='4.3.1', + help='libcpptraj version') + parser.add_argument('-r', + '--release', + action='store_true') + parser.add_argument('--version', + help='pytraj version', + default='1.0.6') + args = parser.parse_args(sys.argv[1:]) + + is_released = args.release + pytraj_version_str = args.version if is_released else args.version + '.dev' + pytraj_status = 'pytraj' if is_released else 'pytraj-dev' + source_ = source_pypi if is_released else source_git + source = source_.format(pytraj_version=pytraj_version_str) if '{pytraj_version}' in source_ else source_ + + meta_str = meta_template.format( + libcpptraj_version=args.libcpptraj_version, + pytraj_status=pytraj_status, + source=source, + pytraj_version=pytraj_version_str) + + print(meta_str) + + with open('pytraj/meta.yaml', 'w') as fh: + fh.write(meta_str) diff --git a/pool/shard006/Python/0058318_run-tests.py b/pool/shard006/Python/0058318_run-tests.py new file mode 100644 index 0000000000000000000000000000000000000000..581e0d89322c052d3ec991b75d9dae7901006a22 --- /dev/null +++ b/pool/shard006/Python/0058318_run-tests.py @@ -0,0 +1,113 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- + +#--------------------------------------------------------------------# +# This file is part of Py-notify. # +# # +# Copyright (C) 2007, 2008 Paul Pogonyshev. # +# # +# 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 # +#--------------------------------------------------------------------# + + +import os +import sys +import unittest + + +if not os.path.isfile (os.path.join ('notify', 'all.py')): + sys.exit ("%s: cannot find '%s', strange..." + % (sys.argv[0], os.path.join ('notify', 'all.py'))) + + + +_extensions_built = False + +def _build_extensions (): + global _extensions_built + + if not _extensions_built: + print ('Building extension...') + + # FIXME: Is that portable enough? + if os.system ('python setup.py build_ext') != 0: + sys.exit (1) + + _extensions_built = True + + + +_TEST_MODULES = ('all', 'base', 'bind', 'condition', '_gc', 'mediator', 'signal', + 'utils', 'variable') + +def _import_module (module_name): + _build_extensions () + return __import__('test.%s' % module_name, globals (), locals (), ('*',)) + +def _import_module_tests (module_name): + return unittest.defaultTestLoader.loadTestsFromModule (_import_module (module_name)) + +def _import_all_tests (): + everything = unittest.TestSuite () + for module_name in _TEST_MODULES: + everything.addTest (_import_module_tests (module_name)) + + return everything + + +class _TestModuleImporter (object): + + def __init__(self, module_name): + self._module_name = module_name + + def __call__(self): + return _import_module_tests (object.__getattribute__(self, '_module_name')) + + def __getattribute__(self, name): + try: + return object.__getattribute__(self, name) + except AttributeError: + return getattr (_import_module (object.__getattribute__(self, '_module_name')), name) + + +class AllTests (object): + + def __init__(self): + self.everything = _import_all_tests + for module_name in _TEST_MODULES: + setattr (self, module_name, _TestModuleImporter (module_name)) + + +class TestProgram (unittest.TestProgram): + + def runTests (self): + _build_extensions () + + print ('\nNote that almost all time is spent in gc.collect() calls, not in this package\n') + unittest.TestProgram.runTests (self) + + + +TestProgram (AllTests (), 'everything') + + + +# Local variables: +# mode: python +# python-indent: 4 +# indent-tabs-mode: nil +# fill-column: 90 +# End: diff --git a/pool/shard006/Python/0058329_motion_expand_COPIA_SIN_LIST.py b/pool/shard006/Python/0058329_motion_expand_COPIA_SIN_LIST.py new file mode 100644 index 0000000000000000000000000000000000000000..846c2877d06e957a5e5cf8c4cb9805f38e017a69 --- /dev/null +++ b/pool/shard006/Python/0058329_motion_expand_COPIA_SIN_LIST.py @@ -0,0 +1,146 @@ +#!/usr/bin/python +# -*- coding: iso-8859-15 -*- + +# motion_expand.py + +# Descomprime los datos con el movimiento. +import os +import sys +from GOP import GOP +from subprocess import check_call +from subprocess import CalledProcessError +from MCTF_parser import MCTF_parser + +#MOTION_DECODER_NAME = "gzip" +#MOTION_DECODER_NAME = "kdu_v_expand" +MCTF_MOTION_CODEC = os.environ["MCTF_MOTION_CODEC"] + +block_size = 16 +block_size_min = 16 +GOPs = 1 +pixels_in_x = 352 +pixels_in_y = 288 +TRLs = 5 + +parser = MCTF_parser(description="Expands the motion data.") +parser.block_size(block_size) +parser.block_size_min(block_size_min) +parser.GOPs(GOPs) +parser.pixels_in_x(pixels_in_x) +parser.pixels_in_y(pixels_in_y) +parser.TRLs(TRLs) + +args = parser.parse_known_args()[0] +if args.block_size: + block_size = int(args.block_size) +if args.block_size_min: + block_size_min = int(args.block_size_min) +if args.GOPs: + GOPs = int(args.GOPs) +if args.pixels_in_x: + pixels_in_x = int(args.pixels_in_x) +if args.pixels_in_y: + pixels_in_y = int(args.pixels_in_y) +if args.TRLs: + TRLs = int(args.TRLs) + +gop=GOP() +GOP_size = gop.get_size(TRLs) +pictures = GOPs * GOP_size + 1 + +if block_size < block_size_min: + block_size_min = block_size + +# Cálculo del tamaño de bloque usado en el nivel de resolución +# temporal más bajo. +iterations = TRLs - 1 +max_block_size = block_size +iters = TRLs - 1 +fields = pictures / 2 +iteration = 0 +while iteration < iterations: + + block_size = block_size / 2 + if (block_size < block_size_min): + block_size = block_size_min + + fields /= 2 + iteration += 1 + +blocks_in_y = pixels_in_y / block_size +blocks_in_x = pixels_in_x / block_size + +# Descomprimimos los campos de movimiento. +iteration = 1 +fields = pictures / 2 +while iteration <= iterations: + + try: + check_call("mctf motion_expand_" + MCTF_MOTION_CODEC + + " --file=" + "\"" + "motion_residue_" + str(iteration) + "\"" + + " --blocks_in_y=" + str(blocks_in_y) + + " --blocks_in_x=" + str(blocks_in_x) + + " --fields=" + str(fields) + + " --pictures=" + str(pictures), + shell=True) + except CalledProcessError: + sys.exit(-1) + + fields /= 2 + +# os.system("svc motion_expand_" + "gzip" +# + " --blocks_in_x=" + str(blocks_in_x) +# + " --blocks_in_y=" + str(blocks_in_y) +# + " --iteration=" + str(iteration) +# + " --file=" + "\"" + prefix + "_motion_residue_" + str(iteration) + "\"" +# + " --pictures=" + str(pictures) +# + " --temporal_levels=" + str(temporal_levels) +# ) + + iteration += 1 + +fields = GOPs + +try: + # Deshacemos la descorrelación bidireccional en el nivel de resolución + # temporal más bajo. + check_call("mctf bidirectional_motion_correlate" + + " --blocks_in_y=" + str(blocks_in_y) + + " --blocks_in_x=" + str(blocks_in_x) + + " --fields=" + str(fields) + + " --input=" + "\"" + "motion_residue_" + str(TRLs - 1) + "\"" + + " --output=" + "\"" + "motion_" + str(TRLs - 1) + "\"", + shell=True) +except CalledProcessError: + sys.exit(-1) + +# Deshacemos la descorrelación interlevel. +iterations = TRLs - 1 +iteration = iterations +while iteration > 1: + + iteration -= 1 + fields = pictures / (2**iteration) + + blocks_in_y = pixels_in_y / block_size + blocks_in_x = pixels_in_x / block_size + + try: + # Descorrelacionamos los campos de movimiento entre niveles de + # resolución. + check_call("mctf interlevel_motion_correlate" + + " --blocks_in_x=" + str(blocks_in_x) + + " --blocks_in_y=" + str(blocks_in_y) + + " --fields_in_predicted=" + str(fields) + + " --predicted=" + "\"" + "motion_" + str(iteration) + "\"" + + " --reference=" + "\"" + "motion_" + str(iteration+1) + "\"" + + " --residue=" + "\"" + "motion_residue_" + str(iteration) + "\"", + shell=True) + except CalledProcessError: + sys.exit(-1) + + # Calculamos el tamaño de bloque usado en esta iteración temporal. + block_size = block_size/2 + if (block_size%s

%s

%s
' % (error_str, escape(path), escape(tb))] + else: + start_response('%s %s' % (response.code, response.msg), headers) + data = response.read() + data = fix_links(data, proxy_url, host) + return [data] + + +def join(url1, *rest): + if not rest: + return url1 + url2, rest = rest[0], rest[1:] + if url1.endswith('/'): + if url2.startswith('/'): + return join(url1 + url2[1:], *rest) + else: + return join(url1 + url2, *rest) + elif url2.startswith('/'): + return join(url1 + url2, *rest) + else: + return join(url1 + '/' + url2, *rest) + + +def fix_links(data, proxy_url, host_url): + """ + >>> fix_links("> %r' % (m.group(0), result)) + return result + data = _link_re_1.sub(fix_link_cb, data) + data = _link_re_2.sub(fix_link_cb, data) + return data + +_link_re_1 = re.compile('''(?P(href|src|action)\s*=\s*)(?P['"])(?P[^#].*?)(?P=quote)''') +_link_re_2 = re.compile('''(?P(href|src|action)\s*=\s*)(?P[^'"#>][^ >]*)''') + +drop_headers = ['transfer-encoding', 'set-cookie'] + +FORM = """ +Web Proxy - gevent example + + + +
Type in URL you want to visit and press Enter
+ + + +
+""" + +if __name__ == '__main__': + from gevent.pywsgi import WSGIServer + print('Serving on %s...' % LISTEN) + WSGIServer(LISTEN, application).serve_forever() diff --git a/pool/shard006/Python/0058362_models.py b/pool/shard006/Python/0058362_models.py new file mode 100644 index 0000000000000000000000000000000000000000..516fb244b2234fc2a34b0fea9a00554c6e80d870 --- /dev/null +++ b/pool/shard006/Python/0058362_models.py @@ -0,0 +1,167 @@ +from rethinkdb import r +from six import add_metaclass +from inflection import tableize + +from .decorators import callback, dispatch_to_metaclass +from .errors import OperationError +from .field_handler import FieldHandlerBase, FieldHandler +from .object_handler import ObjectHandler +from .registry import model_registry + + +REL_TYPES = ('has_one', 'has_many', 'belongs_to', 'has_and_belongs_to_many') +CALLBACKS = ('before_save', 'after_save', 'before_delete', 'after_delete', 'after_init') + + +class ModelBase(type): + def __new__(mcs, name, bases, dct): + super_new = super(ModelBase, mcs).__new__ + + # Ensure the following are not done for the Model class itself + parents = [b for b in bases if isinstance(b, ModelBase)] + if not parents: + return super_new(mcs, name, bases, dct) + + # Set metadata + dct['table_name'] = dct.get('table_name', tableize(name)) + + rel_attrs = {rel: dct.setdefault(rel, ()) for rel in REL_TYPES} + dct['_field_handler_cls'] = FieldHandlerBase( + '%sFieldHandler' % name, + (FieldHandler,), + dict(rel_attrs, model=name)) + object_handler_cls = dct.setdefault('object_handler', ObjectHandler) + + # Register callbacks + dct['_callbacks'] = {callback: [] for callback in CALLBACKS} + for callback in CALLBACKS: + # Callback-named methods + if callback in dct: + dct['_callbacks'][callback].append(callback) + # Callback-decorated methods + dct['_callbacks'][callback].extend([key + for key, value in dct.items() + if hasattr(value, callback)]) + + new_class = super_new(mcs, name, bases, dct) + model_registry.register(name, new_class) + setattr(new_class, 'objects', object_handler_cls(new_class)) + return new_class + + # Proxies undefined attributes to Model.objects; useful for building + # ReQL queries directly on the Model (e.g.: User.order_by('name').run()) + def __getattr__(self, name): + return getattr(self.objects, name) + + +@add_metaclass(ModelBase) +class Model(object): + def __init__(self, **kwargs): + self.fields = self._field_handler_cls() + + for key, value in kwargs.items(): + # Assign fields this way to be sure that validation takes place + setattr(self.fields, key, value) + + self._run_callbacks('after_init') + + def save(self): + self._run_callbacks('before_save') + + fields_dict = self.fields.as_dict() + try: + # Attempt update + id_ = fields_dict['id'] + result = (r.table(self.table_name).get(id_).replace(r.row + .without(r.row.keys().difference(list(fields_dict.keys()))) + .merge(fields_dict), return_changes='always').run()) + + except KeyError: + # Resort to insert + result = (r.table(self.table_name).insert(fields_dict, return_changes=True) + .run()) + + if result['errors'] > 0: + raise OperationError(result['first_error']) + + # Force overwrite so that related caches are flushed + self.fields.__dict__ = result['changes'][0]['new_val'] + + self._run_callbacks('after_save') + + def update(self, **kwargs): + for key, value in kwargs.items(): + # Assign fields this way to be sure that validation takes place + setattr(self.fields, key, value) + + self.save() + + def delete(self): + self._run_callbacks('before_delete') + + try: + id_ = getattr(self.fields, 'id') + result = r.table(self.table_name).get(id_).delete().run() + except AttributeError: + raise OperationError('Cannot delete %r (object not saved or ' + 'already deleted)' % self) + + if result['errors'] > 0: + raise OperationError(result['first_error']) + + # Remove any reference to the deleted object + for field in self.fields.related: + delattr(self.fields, field) + delattr(self.fields, 'id') + + self._run_callbacks('after_delete') + + # TODO: Get rid of this nasty decorator after renaming .get() on ObjectHandler + @dispatch_to_metaclass + def get(self, key, default=None): + try: + return getattr(self.fields, key) + except AttributeError: + return default + + def __getitem__(self, key): + try: + return getattr(self.fields, key) + except AttributeError: + raise KeyError(key) + + def __setitem__(self, key, value): + try: + setattr(self.fields, key, value) + except AttributeError: + raise KeyError(key) + + def __delitem__(self, key): + try: + delattr(self.fields, key) + except AttributeError: + raise KeyError(key) + + def __contains__(self, item): + return hasattr(self.fields, item) + + def __repr__(self): + try: + id_ = self.fields.id + except AttributeError: + id_ = 'not saved' + return '<%s: %s>' % (self.__class__.__name__, id_) + + def __str__(self): + return '<%s object>' % self.__class__.__name__ + + def _run_callbacks(self, name): + for callback in self._callbacks[name]: + getattr(self, callback)() + + +before_save = callback('before_save') +after_save = callback('after_save') +before_delete = callback('before_delete') +after_delete = callback('after_delete') +after_init = callback('after_init') diff --git a/pool/shard006/Python/0058368_Euler_Problem-085.py b/pool/shard006/Python/0058368_Euler_Problem-085.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b43b3218868649b3ee555e77dad9ac7bf56c9a --- /dev/null +++ b/pool/shard006/Python/0058368_Euler_Problem-085.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python2 + +# transpiled with BefunCompile v1.3.0 (c) 2017 +import sys +def td(a,b): + return ((0)if(b==0)else(a//b)) +def tm(a,b): + return ((0)if(b==0)else(a%b)) +s=[] +def sp(): + global s + if (len(s) == 0): + return 0 + return s.pop() +def sa(v): + global s + s.append(v) +def sr(): + global s + if (len(s) == 0): + return 0 + return s[-1] +x0=2000000 +x1=2000000 +x2=0 +x3=89 +x4=0 +x5=89 +x6=89 +def _0(): + return 1 +def _1(): + global x0 + global x4 + return (3)if(x0>x4)else(2) +def _2(): + global x3 + sys.stdout.write(str(x3)+" ") + sys.stdout.flush() + return 12 +def _3(): + global x5 + global x6 + global x4 + x5=1 + x6=x4 + return 4 +def _4(): + global x2 + global x5 + global x0 + global x6 + return (5)if((((1)if(x2>x5)else(0))*((1)if(x0>x6)else(0)))!=0)else(11) +def _5(): + global x0 + global x6 + sa(x0-x6) + + return (10)if((x0-x6)<0)else(6) +def _6(): + sa(sp()-0) + return 7 +def _7(): + global x1 + return (9)if(sr()>x1)else(8) +def _8(): + global x1 + global x3 + global x5 + global x2 + x1=sp() + x3=x5*x2 + sa(0) + return 9 +def _9(): + global t0 + global x5 + global x4 + global x6 + t0=x5+1 + x5=x5+1 + t0=t0*x4 + t0=t0+x6 + x6=t0 + sp(); + return 4 +def _10(): + global t0 + t0=0 + sa(t0) + v0=sp() + v1=sp() + sa(v0) + sa(v1) + v0=sp() + sa(sp()-v0) + return 7 +def _11(): + global t0 + global x2 + global x4 + t0=x2+1 + x2=x2+1 + t0=t0+x4 + x4=t0 + return 1 +m=[_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11] +c=0 +while c<12: + c=m[c]() diff --git a/pool/shard006/Python/0058370_decorators.py b/pool/shard006/Python/0058370_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf60ddcd668608bb4a214f6b3d8e53d4fd52c26 --- /dev/null +++ b/pool/shard006/Python/0058370_decorators.py @@ -0,0 +1,221 @@ +""" +Convenience decorators for use in fabfiles. +""" +import six +import types +from functools import wraps + +try: + from Crypto import Random +except ImportError: + Random = None + +from fabric import tasks +from .context_managers import settings + + +def task(*args, **kwargs): + """ + Decorator declaring the wrapped function to be a new-style task. + + May be invoked as a simple, argument-less decorator (i.e. ``@task``) or + with arguments customizing its behavior (e.g. ``@task(alias='myalias')``). + + Please see the :ref:`new-style task ` documentation for + details on how to use this decorator. + + .. versionchanged:: 1.2 + Added the ``alias``, ``aliases``, ``task_class`` and ``default`` + keyword arguments. See :ref:`task-decorator-arguments` for details. + .. versionchanged:: 1.5 + Added the ``name`` keyword argument. + + .. seealso:: `~fabric.docs.unwrap_tasks`, `~fabric.tasks.WrappedCallableTask` + """ + invoked = bool(not args or kwargs) + task_class = kwargs.pop("task_class", tasks.WrappedCallableTask) + if not invoked: + func, args = args[0], () + + def wrapper(func): + return task_class(func, *args, **kwargs) + + return wrapper if invoked else wrapper(func) + +def _wrap_as_new(original, new): + if isinstance(original, tasks.Task): + return tasks.WrappedCallableTask(new) + return new + + +def _list_annotating_decorator(attribute, *values): + def attach_list(func): + @wraps(func) + def inner_decorator(*args, **kwargs): + return func(*args, **kwargs) + _values = values + # Allow for single iterable argument as well as *args + if len(_values) == 1 and not isinstance(_values[0], six.string_types): + _values = _values[0] + setattr(inner_decorator, attribute, list(_values)) + # Don't replace @task new-style task objects with inner_decorator by + # itself -- wrap in a new Task object first. + inner_decorator = _wrap_as_new(func, inner_decorator) + return inner_decorator + return attach_list + + +def hosts(*host_list): + """ + Decorator defining which host or hosts to execute the wrapped function on. + + For example, the following will ensure that, barring an override on the + command line, ``my_func`` will be run on ``host1``, ``host2`` and + ``host3``, and with specific users on ``host1`` and ``host3``:: + + @hosts('user1@host1', 'host2', 'user2@host3') + def my_func(): + pass + + `~fabric.decorators.hosts` may be invoked with either an argument list + (``@hosts('host1')``, ``@hosts('host1', 'host2')``) or a single, iterable + argument (``@hosts(['host1', 'host2'])``). + + Note that this decorator actually just sets the function's ``.hosts`` + attribute, which is then read prior to executing the function. + + .. versionchanged:: 0.9.2 + Allow a single, iterable argument (``@hosts(iterable)``) to be used + instead of requiring ``@hosts(*iterable)``. + """ + return _list_annotating_decorator('hosts', *host_list) + + +def roles(*role_list): + """ + Decorator defining a list of role names, used to look up host lists. + + A role is simply defined as a key in `env` whose value is a list of one or + more host connection strings. For example, the following will ensure that, + barring an override on the command line, ``my_func`` will be executed + against the hosts listed in the ``webserver`` and ``dbserver`` roles:: + + env.roledefs.update({ + 'webserver': ['www1', 'www2'], + 'dbserver': ['db1'] + }) + + @roles('webserver', 'dbserver') + def my_func(): + pass + + As with `~fabric.decorators.hosts`, `~fabric.decorators.roles` may be + invoked with either an argument list or a single, iterable argument. + Similarly, this decorator uses the same mechanism as + `~fabric.decorators.hosts` and simply sets ``.roles``. + + .. versionchanged:: 0.9.2 + Allow a single, iterable argument to be used (same as + `~fabric.decorators.hosts`). + """ + return _list_annotating_decorator('roles', *role_list) + + +def runs_once(func): + """ + Decorator preventing wrapped function from running more than once. + + By keeping internal state, this decorator allows you to mark a function + such that it will only run once per Python interpreter session, which in + typical use means "once per invocation of the ``fab`` program". + + Any function wrapped with this decorator will silently fail to execute the + 2nd, 3rd, ..., Nth time it is called, and will return the value of the + original run. + + .. note:: ``runs_once`` does not work with parallel task execution. + """ + @wraps(func) + def decorated(*args, **kwargs): + if not hasattr(decorated, 'return_value'): + decorated.return_value = func(*args, **kwargs) + return decorated.return_value + decorated = _wrap_as_new(func, decorated) + # Mark as serial (disables parallelism) and return + return serial(decorated) + + +def serial(func): + """ + Forces the wrapped function to always run sequentially, never in parallel. + + This decorator takes precedence over the global value of :ref:`env.parallel + `. However, if a task is decorated with both + `~fabric.decorators.serial` *and* `~fabric.decorators.parallel`, + `~fabric.decorators.parallel` wins. + + .. versionadded:: 1.3 + """ + if not getattr(func, 'parallel', False): + func.serial = True + return _wrap_as_new(func, func) + + +def parallel(pool_size=None): + """ + Forces the wrapped function to run in parallel, instead of sequentially. + + This decorator takes precedence over the global value of :ref:`env.parallel + `. It also takes precedence over `~fabric.decorators.serial` + if a task is decorated with both. + + .. versionadded:: 1.3 + """ + called_without_args = type(pool_size) == types.FunctionType + + def real_decorator(func): + @wraps(func) + def inner(*args, **kwargs): + # Required for ssh/PyCrypto to be happy in multiprocessing + # (as far as we can tell, this is needed even with the extra such + # calls in newer versions of paramiko.) + if Random: + Random.atfork() + return func(*args, **kwargs) + inner.parallel = True + inner.serial = False + inner.pool_size = None if called_without_args else pool_size + return _wrap_as_new(func, inner) + + # Allow non-factory-style decorator use (@decorator vs @decorator()) + if called_without_args: + return real_decorator(pool_size) + + return real_decorator + + +def with_settings(*arg_settings, **kw_settings): + """ + Decorator equivalent of ``fabric.context_managers.settings``. + + Allows you to wrap an entire function as if it was called inside a block + with the ``settings`` context manager. This may be useful if you know you + want a given setting applied to an entire function body, or wish to + retrofit old code without indenting everything. + + For example, to turn aborts into warnings for an entire task function:: + + @with_settings(warn_only=True) + def foo(): + ... + + .. seealso:: `~fabric.context_managers.settings` + .. versionadded:: 1.1 + """ + def outer(func): + @wraps(func) + def inner(*args, **kwargs): + with settings(*arg_settings, **kw_settings): + return func(*args, **kwargs) + return _wrap_as_new(func, inner) + return outer diff --git a/pool/shard006/Python/0058372_runExampleWidgetAction.py b/pool/shard006/Python/0058372_runExampleWidgetAction.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad7f6a67e507a4cbf9442b8de5fb3478164c44e --- /dev/null +++ b/pool/shard006/Python/0058372_runExampleWidgetAction.py @@ -0,0 +1,16 @@ +""" +Launch the Reparent window. +""" + +import os +import sys + +# Ensure that '/python' is on the PYTHONPATH +path = os.path.dirname(__file__) +package_path = os.path.abspath(os.path.join(path, 'python')) +sys.path.insert(0, package_path) + +if __name__ == '__main__': + import qtLearn.windows.examples.exampleWidgetAction + qtLearn.windows.examples.exampleWidgetAction.main(sys.argv) + diff --git a/pool/shard006/Python/0058374_tables.py b/pool/shard006/Python/0058374_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..b07887e5dace89e170498595d5b6196468561bbc --- /dev/null +++ b/pool/shard006/Python/0058374_tables.py @@ -0,0 +1,61 @@ +from django.utils.translation import ugettext_lazy as _ + +from horizon import tables + +from openstack_dashboard.dashboards.integra.providers import utils + + +class AddTableData(tables.LinkAction): + name = "add" + verbose_name = _("Add Provider") + url = "horizon:integra:providers:add" + classes = ("btn-launch", "ajax-modal") + +class DeleteTableData(tables.DeleteAction): + data_type_singular = _("Provider") + data_type_plural = _("Providers") + + def delete(self, request, obj_id): + utils.deleteProvider(self, obj_id) + +class FilterAction(tables.FilterAction): + def filter(self, table, providers, filter_string): + filterString = filter_string.lower() + return [provider for provider in providers + if filterString in provider.title.lower()] + +class UpdateRow(tables.Row): + ajax = True + + def get_data(self, request, post_id): + pass + +class ProviderTable(tables.DataTable): + id = tables.Column("id", + verbose_name=_("Id")) + + name = tables.Column("name", + verbose_name=_("Name")) + + description = tables.Column("description", + verbose_name=_("Description")) + + hostname = tables.Column("hostname", + verbose_name=_("Hostname")) + + port = tables.Column("port", + verbose_name=_("Port")) + + timeout = tables.Column("timeout", + verbose_name=_("Timeout")) + + secured = tables.Column("secured", + verbose_name=_("Secured")) + + class Meta: + name = "integra" + verbose_name = _("Providers") + row_class = UpdateRow + table_actions = (AddTableData, + FilterAction) + row_actions = (DeleteTableData,) diff --git a/pool/shard006/Python/0058380_collection.py b/pool/shard006/Python/0058380_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..dec1162f978b18e94d22340a532bf459bf31d317 --- /dev/null +++ b/pool/shard006/Python/0058380_collection.py @@ -0,0 +1,53 @@ +# +# Copyright (c) Elliot Peele +# +# This program is distributed under the terms of the MIT License as found +# in a file called LICENSE. If it is not present, the license +# is always available at http://www.opensource.org/licenses/mit-license.php. +# +# This program is distributed in the hope that it will be useful, but +# without any warrenty; without even the implied warranty of merchantability +# or fitness for a particular purpose. See the MIT License for full details. +# + +from .resource import BaseResource + +class Collection(BaseResource): + def __getitem__(self, idx): + return self._data[idx] + + def __setitem__(self, idx, value): + pass + + def __delitem__(self, idx): + self._cache.delete(self._data[idx].delete()) + del self._data[idx] + + def __iter__(self): + return iter(self._data) + + def __len__(self): + return len(self._data) + + def __nonzero__(self): + return bool(self._data) + + def append(self, resource, post=True): + if isinstance(resource, BaseResource): + value = resource._data + else: + value = resource + + if post: + obj = self._cache.post(self._uri, value) + self._data.append(obj) + return obj + + else: + self._data.append(resource) + + def refresh(self): + resource = self._cache.get(self._uri, cache=False) + assert isinstance(resource, Collection) + self._data = resource._data + self._metadata = resource._metadata diff --git a/pool/shard006/Python/0058381_aggregator.py b/pool/shard006/Python/0058381_aggregator.py new file mode 100644 index 0000000000000000000000000000000000000000..f4447cb75c8472c03f11e7f50d6f1cf4da0cdf05 --- /dev/null +++ b/pool/shard006/Python/0058381_aggregator.py @@ -0,0 +1,185 @@ +import fix_path +import webapp2 as webapp +from google.appengine.api import urlfetch +from google.appengine.api import taskqueue +from google.appengine.ext import blobstore +from google.appengine.api import images +from google.appengine.api import files +from google.appengine.api import memcache +from apps import DEBUG +from apps.models import * +import logging, yaml, re, datetime +from feedparser import feedparser +from readability.readability import Document +from pyquery import PyQuery + +# Load feeds from a yaml file +class LoadFeedsHandler(webapp.RequestHandler): + def get(self): + """ Load feeds from data/feeds.yaml """ + f = open('data/feeds.yaml', 'r') + array = yaml.load(f) + + feeds = [] + for item in array: + name = item['name'] + link = item['link'] + + feed = Feed.all().filter('name =', name).get() + if feed is None: + feed = Feed(name=name, link=link, updated=datetime.datetime.now()) + else: + feed.name = name + feed.link = link + feed.updated = datetime.datetime.now() + + feeds.append(feed) + + db.put(feeds) + self.response.out.write('load-feeds: done') + +# Fetch and parse feeds +class UpdateFeedsHandler(webapp.RequestHandler): + def get(self): + for feed in Feed.all(): + taskqueue.add(queue_name='update-feeds', url='/aggregator/update-single-feed', params={'id': feed.key().id_or_name()}, method='GET') + self.response.out.write('update-feeds: done') + +# Fetch and parse a single feed +class UpdateSingleFeedHandler(webapp.RequestHandler): + def get(self): + feedId = long(self.request.get('id')) + feed = Feed.get_by_id(feedId) + + res = urlfetch.fetch(feed.link, deadline=20) + data = feedparser.parse(res.content) + feedUpdated = data['feed']['updated_parsed'] + feedUpdated = datetime.datetime(*feedUpdated[:6]) # convert `time.struct_time` into a `datetime.datetime` object + + if feedUpdated != feed.updated: + toSave = [] + toFetch = [] + for entry in data.entries: + # Skip empty entries + if not hasattr(entry, 'summary'): + continue + + articleUpdated = entry.updated_parsed + articleUpdated = datetime.datetime(*articleUpdated[:6]) # convert `time.struct_time` into a `datetime.datetime` object + summary = re.sub(r'<.*?>', '', entry.summary) + summary = re.sub(r' ', '', summary) + + a = Article.all().filter("link =", entry.link).get() + if a is None: + a = Article(title=entry.title, link=entry.link, feed=feed, updated=articleUpdated, summary=summary) + toSave.append(a) + toFetch.append(a) + elif a.updated != articleUpdated: + a.title = entry.title + a.updated = articleUpdated + a.summary = summary + toSave.append(a) + toFetch.append(a) + + feed.updated = feedUpdated + toSave.append(feed) + db.put(toSave) + + # Fetch full texts of articles + for a in toFetch: + taskqueue.add(queue_name='get-full-article', url='/aggregator/get-full-article', params={'link': a.link, 'id': a.key().id_or_name()}, method='GET') + +# Fetch full texts of articles +class GetFullArticleHandler(webapp.RequestHandler): + def get(self): + articleId = long(self.request.get('id')) + article = Article.get_by_id(articleId) + + link = self.request.get('link') + res = urlfetch.fetch(link, deadline=20) + html = Document(res.content).summary() + + S = PyQuery(html) + article.origImageUrl = S("img:first").attr('src') + article.imageUrl = None + article.body = html + article.put() + + if article.origImageUrl is not None and article.imageUrl is None: + taskqueue.add(queue_name='upload-images', url='/aggregator/upload-article-image', params={'link': article.origImageUrl, 'id': articleId}, method='GET') + + self.response.out.write('OK') + +# Resize and cache thumbnails +class UploadArticleImageHandler(webapp.RequestHandler): + def get(self): + articleId = long(self.request.get('id')) + article = Article.get_by_id(articleId) + + link = self.request.get('link') + res = urlfetch.fetch(link, deadline=20) + if res.status_code == 200: + img = images.Image(res.content) + + if img.width < 100: + article.origImageUrl = None + article.imageUrl = None + else: + img.resize(width=150) + img.im_feeling_lucky() + imageData = img.execute_transforms(output_encoding=images.JPEG) + + # Create the file + file_name = files.blobstore.create(mime_type='image/jpeg') + + # Open the file and write to it + with files.open(file_name, 'a') as f: + f.write(imageData) + + # Finalize the file. Do this before attempting to read it. + files.finalize(file_name) + + # Get the file's blob key + blob_key = files.blobstore.get_blob_key(file_name) + + # Save the blob key and image serving url in the Article + article.imageBlob = blob_key + article.imageUrl = images.get_serving_url(blob_key) + + article.put() + self.response.out.write('OK') + +# Flush memcache +class FlushMemcacheHandler(webapp.RequestHandler): + def get(self): + memcache.flush_all() + self.response.out.write('flush-memcache: done') + +# Purge old articles +class PurgeOldArticlesHandler(webapp.RequestHandler): + def get(self): + oneDayAgo = datetime.datetime.now() - datetime.timedelta(days=1) + toDelete = [] + blobsToDelete = [] + + for a in Article.all().filter("updated <", oneDayAgo): + toDelete.append(a) + if a.imageBlob is not None: + blobsToDelete.append(a.imageBlob.key()) + + db.delete(toDelete) + blobstore.delete(blobsToDelete) + self.response.out.write('purge-old-articles: done') + +# +# Application +# +app = webapp.WSGIApplication([ + (r'/aggregator/load-feeds', LoadFeedsHandler), + (r'/aggregator/update-feeds', UpdateFeedsHandler), + (r'/aggregator/update-single-feed', UpdateSingleFeedHandler), + (r'/aggregator/get-full-article', GetFullArticleHandler), + (r'/aggregator/upload-article-image', UploadArticleImageHandler), + (r'/aggregator/flush-memcache', FlushMemcacheHandler), + (r'/aggregator/purge-old-articles', PurgeOldArticlesHandler) +], debug=DEBUG) diff --git a/pool/shard006/Python/0058388_interwikidata_tests.py b/pool/shard006/Python/0058388_interwikidata_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..21d317b1befd64edc97a50ef5001c5abe84c88a6 --- /dev/null +++ b/pool/shard006/Python/0058388_interwikidata_tests.py @@ -0,0 +1,105 @@ +#!/usr/bin/python3 +"""Tests for scripts/interwikidata.py.""" +# +# (C) Pywikibot team, 2015-2022 +# +# Distributed under the terms of the MIT license. +# +import unittest +from contextlib import suppress + +import pywikibot +from pywikibot import Link +from scripts import interwikidata +from tests.aspects import SiteAttributeTestCase +from tests.utils import empty_sites + + +class DummyBot(interwikidata.IWBot): + + """A dummy bot to prevent editing in production wikis.""" + + def put_current(self): + """Prevent editing.""" + return False + + def create_item(self): + """Prevent creating items.""" + return False + + def try_to_add(self): + """Prevent adding sitelinks to items.""" + return None + + +class TestInterwikidataBot(SiteAttributeTestCase): + + """Test Interwikidata.""" + + sites = { + 'en': { + 'family': 'wikipedia', + 'code': 'en', + }, + 'fa': { + 'family': 'wikipedia', + 'code': 'fa', + }, + 'wt': { + 'family': 'wikitech', + 'code': 'en', + }, + } + + def test_main(self): + """Test main function interwikidata.py.""" + # The main function should return False when no generator is defined. + with empty_sites(): + self.assertFalse(interwikidata.main()) + + def test_iw_bot(self): + """Test IWBot class.""" + page = pywikibot.Page(self.en, 'User:Ladsgroup') + text = page.get() + + # The page looks as expected. + self.assertLength(page.langlinks(), 1) + iw_link = page.langlinks()[0] + self.assertIsInstance(iw_link, Link) + self.assertEqual(iw_link.canonical_title(), 'کاربر:Ladsgroup') + self.assertEqual(iw_link.site, self.fa) + + repo = self.en.data_repository() + bot = DummyBot(generator=[page], site=self.en, ignore_ns=True) + bot.run() + + # Repo and site should not change during a run. + self.assertEqual(bot.repo, repo) + self.assertEqual(bot.site, self.en) + + # Test iwlangs method. + self.assertIn(self.fa, bot.iwlangs) + self.assertEqual(Link.fromPage(bot.iwlangs[self.fa]), iw_link) + + page2 = pywikibot.Page(self.en, 'User:Ladsgroup') + self.assertEqual(page2.get(), text) + + self.assertFalse(bot.handle_complicated()) + + def test_without_repo(self): + """Test throwing error when site does not have a data repo.""" + wt_page = pywikibot.Page(self.wt, 'User:Ladsgroup') + with self.assertRaises(ValueError): + DummyBot(generator=[wt_page], + site=self.wt) + + with self.assertRaisesRegex( + ValueError, 'wikitech:en does not have a data repository.'): + interwikidata.IWBot( + generator=[pywikibot.Page(self.wt, 'User:Dalba')], + site=self.wt) + + +if __name__ == '__main__': # pragma: no cover + with suppress(SystemExit): + unittest.main() diff --git a/pool/shard006/Python/0058390_lc0091_decode_ways.py b/pool/shard006/Python/0058390_lc0091_decode_ways.py new file mode 100644 index 0000000000000000000000000000000000000000..2b141ee1e6bb118919ef9aa7fe8683ac2ef443db --- /dev/null +++ b/pool/shard006/Python/0058390_lc0091_decode_ways.py @@ -0,0 +1,265 @@ +"""Leetcode 91. Decode Ways +Medium + +URL: https://leetcode.com/problems/decode-ways/ + +A message containing letters from A-Z is being encoded to numbers using the +following mapping: + +'A' -> 1 +'B' -> 2 +... +'Z' -> 26 + +Given a non-empty string containing only digits, determine the total number +of ways to decode it. + +Example 1: +Input: "12" +Output: 2 +Explanation: It could be decoded as "AB" (1 2) or "L" (12). + +Example 2: +Input: "226" +Output: 3 +Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). +""" + +class SolutionRecurNaive(object): + def numDecodings(self, s): + """ + :type s: str + :rtype: int + + Apply recursion. + + Time complexity: O(2^n). + Space complexity: O(n). + """ + # Base case. + if not s: + return 1 + + # Check 1 digit: if the start char is not valid. + if s[0] == '0': + return 0 + + # If valid, decode the remaining string after 1 digit. + n_ways = self.numDecodings(s[1:]) + + # Check 2 digits: if len of s >= 2 and first 2 chars are valid, + # decode the remaining string after 2 digits. + if len(s) >= 2 and '10' <= s[:2] <= '26': + n_ways += self.numDecodings(s[2:]) + + return n_ways + + +class SolutionRecur(object): + def _decodeRecur(self, s, k): + """Recursively decode the last k chars.""" + # Base case. + if k == 0: + return 1 + + # Check 1 digit: if the start of the last k chars is not valid. + start = len(s) - k + if s[start] == '0': + return 0 + + # If valid, decode the last (k - 1) chars. + n_ways = self._decodeRecur(s, k - 1) + + # Check 2 digits: if k >= 2 and first 2 chars are valid, + # decode the last (k - 2) chars. + if k >= 2 and '10' <= s[start:(start + 2)] <= '26': + n_ways += self._decodeRecur(s, k - 2) + + return n_ways + + def numDecodings(self, s): + """ + :type s: str + :rtype: int + + Apply recursion with pointer method without copying lists. + + Time complexity: O(2^n). + Space complexity: O(1). + """ + n = len(s) + return self._decodeRecur(s, n) + + +class SolutionMemo(object): + def _decodeRecur(self, s, k, T): + """Recursively check the last k chars.""" + # Base case. + if k == 0: + return 1 + + # Check 1 digit: if the start of the last k chars is not valid. + start = len(s) - k + if s[start] == '0': + return 0 + + # Check memo table. + if T[k]: + return T[k] + + # If valid, decode the remaining (k - 1) chars. + result = self._decodeRecur(s, k - 1, T) + + # Check 2 digits: if k >= 2 and first 2 chars are valid, + # decode the remaining (k - 2) chars. + if k >= 2 and '10' <= s[start:(start + 2)] <= '26': + result += self._decodeRecur(s, k - 2, T) + + T[k] = result + return result + + def numDecodings(self, s): + """ + :type s: str + :rtype: int + + Apply top-down dynamic progromming by memoization. + + Time complexity: O(n). + Space complexity: O(n). + """ + n = len(s) + T = [0] * (n + 1) + return self._decodeRecur(s, n, T) + + +class SolutionDP(object): + def numDecodings(self, s): + """ + :type s: str + :rtype: int + + Apply bottom-up dynamic progromming. + + Time complexity: O(n). + Space complexity: O(n). + """ + # Base case. + if not s: + return 1 + + # Check if the 1st char is not valid. + if s[0] == '0': + return 0 + + n = len(s) + T = [0] * (n + 1) + + # For empty string and the valid 1st char, decode in 1 way. + T[0] = 1 + T[1] = 1 + + for i in range(2, n + 1): + # Check 1 digit: if the previous 1 char is valid, add to result. + if s[i - 1] != '0': + T[i] += T[i - 1] + + # Check 2 digits: if the previous 2 are valid, add to result. + if '10' <= s[(i - 2):i] <= '26': + T[i] += T[i - 2] + + return T[-1] + + +class SolutionIter(object): + def numDecodings(self, s): + """ + :type s: str + :rtype: int + + Apply bottom-up iteration. + + Time complexity: O(n). + Space complexity: O(1). + """ + # Base case. + if not s: + return 1 + + # Check if s[0] is not valid. + if s[0] == '0': + return 0 + + n = len(s) + + # For empty string and the valid 1st char, decode in 1 way. + a, b = 1, 1 + + for i in range(2, n + 1): + c = 0 + + # Check 1 digit: if the previous 1 char is valid, add to result. + if s[i - 1] != '0': + c += b + + # Check 2 digits: if the previous 2 are valid, add to result. + if '10' <= s[(i - 2):i] <= '26': + c += a + + a, b = b, c + + return b + + +def main(): + import time + + s = '12' # Should be 2 = #{(1,2), (12)}. + + start_time = time.time() + print 'By naive recur: {}'.format(SolutionRecurNaive().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By recur: {}'.format(SolutionRecur().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By memo: {}'.format(SolutionMemo().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By DP: {}'.format(SolutionDP().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By iter: {}'.format(SolutionIter().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + print '---' + + s = '226' # Should be 3 = #{(2,2,6), (22,6), (2,26)} + + start_time = time.time() + print 'By naive recur: {}'.format(SolutionRecurNaive().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By recur: {}'.format(SolutionRecur().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By memo: {}'.format(SolutionMemo().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By DP: {}'.format(SolutionDP().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + start_time = time.time() + print 'By iter: {}'.format(SolutionIter().numDecodings(s)) + print 'Time: {}'.format(time.time() - start_time) + + +if __name__ == '__main__': + main() diff --git a/pool/shard006/Python/0058399_smessage_test_rabbitMQ_server.py b/pool/shard006/Python/0058399_smessage_test_rabbitMQ_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8679484db5d7f1bfc747feea4eabbe3360d03d9d --- /dev/null +++ b/pool/shard006/Python/0058399_smessage_test_rabbitMQ_server.py @@ -0,0 +1,53 @@ +# +# Copyright (c) 2015 Cossack Labs 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. +# + +""" +echo server for rabbitMQ +""" + +import pika +from pythemis.smessage import SMessage + +client_public = b"\x55\x45\x43\x32\x00\x00\x00\x2d\x13\x8b\xdf\x0c\x02\x1f\x09\x88\x39\xd9\x73\x3a\x84\x8f\xa8\x50\xd9\x2b\xed\x3d\x38\xcf\x1d\xd0\xce\xf4\xae\xdb\xcf\xaf\xcb\x6b\xa5\x4a\x08\x11\x21" + +server_private = b"\x52\x45\x43\x32\x00\x00\x00\x2d\x49\x87\x04\x6b\x00\xf2\x06\x07\x7d\xc7\x1c\x59\xa1\x8f\x39\xfc\x94\x81\x3f\x9e\xc5\xba\x70\x6f\x93\x08\x8d\xe3\x85\x82\x5b\xf8\x3f\xc6\x9f\x0b\xdf" + +smessage = SMessage(server_private, client_public) + +connection = pika.BlockingConnection( + pika.ConnectionParameters(host='localhost')) + +channel = connection.channel() + +channel.queue_declare(queue='smessage_queue') + + +def on_request(ch, method, props, body): + # decrypt received message + message = smessage.unwrap(body) + print(message.decode('utf-8')) + ch.basic_publish( + exchange='', routing_key=props.reply_to, + properties=pika.BasicProperties(correlation_id=props.correlation_id), + body=smessage.wrap(message)) + # encrypt and send reply message + ch.basic_ack(delivery_tag=method.delivery_tag) + + +channel.basic_qos(prefetch_count=1) +channel.basic_consume(on_request, queue='smessage_queue') + +channel.start_consuming() diff --git a/pool/shard006/Python/0058402_neoC5.py b/pool/shard006/Python/0058402_neoC5.py new file mode 100644 index 0000000000000000000000000000000000000000..70dcda3446b4248a8f0376c53353ca8da8f24021 --- /dev/null +++ b/pool/shard006/Python/0058402_neoC5.py @@ -0,0 +1,138 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +'''Pychemqt, Chemical Engineering Process simulator +Copyright (C) 2009-2017, Juan José Gómez Romera + +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 unittest import TestCase + +from lib import unidades +from lib.meos import MEoS + + +class neoC5(MEoS): + """Multiparameter equation of state for neopentane""" + name = "neopentane" + CASNumber = "463-82-1" + formula = "C(CH3)4" + synonym = "" + _refPropName = "NEOPENTN" + _coolPropName = "Neopentane" + rhoc = unidades.Density(235.9265106) + Tc = unidades.Temperature(433.74) + Pc = unidades.Pressure(3196.0, "kPa") + M = 72.14878 # g/mol + Tt = unidades.Temperature(256.6) + Tb = unidades.Temperature(282.65) + f_acent = 0.1961 + momentoDipolar = unidades.DipoleMoment(0.0, "Debye") + id = 9 + + Fi1 = {"ao_log": [1, 3.], + "pow": [0, 1], + "ao_pow": [0.8702452614, 1.6071746358], + "ao_exp": [14.422, 12.868, 17.247, 12.663], + "titao": [710/Tc, 1725/Tc, 3280/Tc, 7787/Tc]} + + f = 72.151/8.3143 + CP1 = {"ao": -0.435375*f, + "an": [0.96766e-2*f, -0.11533e-4*f, 0.108006e-7*f, -0.44851e-11*f], + "pow": [1, 2, 3, 4]} + + lemmon = { + "__type__": "Helmholtz", + "__name__": "short Helmholtz equation of state for neopentane of " + "Lemmon and Span (2006).", + "__doi__": {"autor": "Lemmon, E.W., Span, R.", + "title": "Short Fundamental Equations of State for 20 " + "Industrial Fluids", + "ref": "J. Chem. Eng. Data, 2006, 51 (3), pp 785–850", + "doi": "10.1021/je050186n"}, + + "R": 8.314472, + "cp": Fi1, + "ref": "NBP", + + "Tmin": Tt, "Tmax": 550.0, "Pmax": 200000.0, "rhomax": 8.71, + + "nr1": [1.1136, -3.1792, 1.1411, -0.10467, 0.11754, 0.00034058], + "d1": [1, 1, 1, 2, 3, 7], + "t1": [0.25, 1.125, 1.5, 1.375, 0.25, 0.875], + + "nr2": [0.29553, -0.074765, -0.31474, -0.099401, -0.039569, 0.023177], + "d2": [2, 5, 1, 4, 3, 4], + "t2": [0.625, 1.75, 3.625, 3.625, 14.5, 12.], + "c2": [1, 1, 2, 2, 3, 3], + "gamma2": [1]*6} + + polt = { + "__type__": "Helmholtz", + "__name__": "Helmholtz equation of state for neopentane of Polt " + "(1992)", + "__doi__": {"autor": "Polt, A., Platzer, B., Maurer, G.", + "title": "Parameter der thermischen Zustandsgleichung von " + "Bender fuer 14 mehratomige reine Stoffe", + "ref": "Chem. Technik 22(1992)6 , 216/224", + "doi": ""}, + + "R": 8.3143, + "cp": CP1, + "ref": "NBP", + + "Tmin": 273.0, "Tmax": 498.0, "Pmax": 20000.0, "rhomax": 8.511, + + "nr1": [-0.146552261671e1, 0.199230626557e1, -0.500821886276, + 0.119809758161e1, -0.363135896710e1, 0.312770556886e1, + -2.37405105853, 0.473735725047, 0.101500881659, 0.184937708516, + -0.290527628579e-1, -0.258919377284e-1, 0.748831217999e-1, + 0.216569936506e-1, -0.100375687935, 0.234924630013e-1], + "d1": [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5], + "t1": [3, 4, 5, 0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 0, 1, 1], + + "nr2": [0.146552261671e1, -0.199230626557e1, 0.500821886276, + -0.834410647812, 0.262918341468e1, -0.188136966583e1], + "d2": [0, 0, 0, 2, 2, 2], + "t2": [3, 4, 5, 3, 4, 5], + "c2": [2]*6, + "gamma2": [0.968832]*6} + + eq = lemmon, polt + + _vapor_Pressure = { + "eq": 3, + "n": [-0.70262e1, 0.20090e1, -0.19932e1, -0.28503e1, -0.53760], + "t": [1.0, 1.5, 2.2, 4.8, 6.2]} + _liquid_Density = { + "eq": 1, + "n": [0.56080e1, -0.13549e2, 0.29912e2, -0.28143e2, 0.89021e1], + "t": [0.45, 0.7, 1.0, 1.25, 1.6]} + _vapor_Density = { + "eq": 2, + "n": [-.25177e1, -.63565e1, -.11985e3, .43740e3, -.10749e4, .74007e3], + "t": [0.366, 1.14, 4.0, 5.0, 6.0, 6.5]} + + +class Test(TestCase): + def test_shortLemmon(self): + # Table 10, Pag 842 + st = neoC5(T=435, rhom=3) + self.assertEqual(round(st.P.kPa, 3), 3256.677) + self.assertEqual(round(st.hM.kJkmol, 3), 34334.720) + self.assertEqual(round(st.sM.kJkmolK, 3), 92.525) + self.assertEqual(round(st.cvM.kJkmolK, 3), 184.435) + self.assertEqual(round(st.cpM.kJkmolK, 3), 5161.767) + self.assertEqual(round(st.w, 3), 93.352) diff --git a/pool/shard006/Python/0058408_git.py b/pool/shard006/Python/0058408_git.py new file mode 100644 index 0000000000000000000000000000000000000000..da102285f6f304f5c589614822007d9af66917e7 --- /dev/null +++ b/pool/shard006/Python/0058408_git.py @@ -0,0 +1,63 @@ +#coding:UTF-8 + +""" +拉取代码模块 +第一阶段兼容osc +@author:yubang +2015-04-21 +""" + + +from lib import app +import json,os + + +def getCodeFromOsc(aid,gitUrl): + "从osc上拉取代码" + baseObj=json.loads(app.getConfig("config")) + codePath=baseObj['base']['codePath']+"/"+str(aid) + appPath=baseObj['base']['allAppDocument'] + + if not os.path.exists(codePath): + os.makedirs(codePath) + + os.system("rm -Rvf %s"%(codePath)) + + out=os.popen("git clone %s %s"%(gitUrl,codePath)) + log=out.read() + if log.find("Receiving objects: 100%") == -1: + return False + + #迁移clone下来的代码 + getCodeFromLocation(aid) + + return True + + +def pullCode(aid): + "更新代码仓库的代码" + baseObj=json.loads(app.getConfig("config")) + codePath=baseObj['base']['codePath']+"/"+str(aid) + appPath=baseObj['base']['allAppDocument'] + os.system("cd %s"%(codePath)) + os.system("git pull") + getCodeFromLocation(aid) + + +def getCodeFromLocation(aid): + "从本地代码仓库拉取代码" + baseObj=json.loads(app.getConfig("config")) + codePath=baseObj['base']['codePath']+"/"+str(aid) + appPath=baseObj['base']['allAppDocument'] + os.system("rm -Rvf %s"%(appPath+"/"+str(aid))) + os.system("cp -Rfv %s %s"%(codePath,appPath)) + + +def checkLocationCode(aid): + "检测本地是否有克隆好的代码" + baseObj=json.loads(app.getConfig("config")) + codePath=baseObj['base']['codePath']+"/"+str(aid) + if os.path.exists(codePath): + return True + else: + return False diff --git a/pool/shard006/Python/0058409_forms.py b/pool/shard006/Python/0058409_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..88afa2cec9a9014738c66b94d9431d4ccf359b4c --- /dev/null +++ b/pool/shard006/Python/0058409_forms.py @@ -0,0 +1,25 @@ +from crispy_forms.helper import FormHelper +from crispy_forms.bootstrap import FormActions, PrependedText +from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit +from django import forms + +from .models import Answer + +class IndexForm(forms.ModelForm): + + YES_NO = ((True, 'Yes'), (False, 'No')) + + present = forms.ChoiceField(widget=forms.RadioSelect, choices=YES_NO) + + class Meta: + model = Answer + fields = ('present',) + + def __init__(self, *args, **kwargs): + super(IndexForm, self).__init__(*args, **kwargs) + self.helper = FormHelper() + self.helper.form_method = 'post' + self.helper.form_action = '.' + self.helper.form_show_labels = False + self.helper.add_input(Submit('submit', 'Next >>')) + diff --git a/pool/shard006/Python/0058410_download.py b/pool/shard006/Python/0058410_download.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d816ebc0456274431aae80a783f0a5c2ed61e2 --- /dev/null +++ b/pool/shard006/Python/0058410_download.py @@ -0,0 +1,162 @@ +from __future__ import print_function + +import io +import os +import binascii +import hashlib +import socket +import shutil +import sys +import tarfile +import tempfile +import time +import zipfile +import logging + +try: + import urllib.request as urllib2 +except ImportError: + import urllib2 + +from ..source import Source + + +class Download(Source): + def __init__(self, url, checksum, destination, cache_directory): + Source.__init__(self) + self.url = url + self.checksum = checksum + self.destination = destination + self.cache_directory = cache_directory + self.local_download_path = os.path.join(cache_directory, checksum) + + @classmethod + def identifier(cls): + return 'download' + + def clean(self): + if not self.checksum: + raise ValueError('checksums are required for downloads') + + self.__fetch() + + logging.info('Unpacking to %s' % self.destination) + self.__clean_destination_dir() + self.__unpack() + self.__trim_lone_dirs() + + def __fetch(self): + if not os.path.exists(self.cache_directory): + os.makedirs(self.cache_directory) + + if not os.path.isfile(self.local_download_path): + self.get(self.url, self.checksum, self.local_download_path) + + @classmethod + def get(cls, url, checksum, destination): + logging.info('Downloading from %s' % url) + download = None + attempts = 0 + download_successful = False + while not download_successful and attempts < 5: + try: + download = urllib2.urlopen(url, timeout=5) + except urllib2.URLError as e: + logging.warning(e) + except socket.timeout as e: + logging.warning(e) + attempts = attempts + 1 + download_successful = download and download.code == 200 and 'content-length' in download.info() + if not download_successful: + logging.warning('Download failed. Retrying...') + time.sleep(attempts) + if not download_successful: + raise IOError('unable to download library') + size = int(download.info()['content-length']) + progress = 0 + if sys.stdout.isatty(): + print('{:.1%}'.format(float(progress) / size), end='') + sys.stdout.flush() + + local_file = tempfile.NamedTemporaryFile('wb', delete=False) + try: + chunk_size = 1024 + while True: + chunk = download.read(chunk_size) + progress = progress + chunk_size + if sys.stdout.isatty(): + print('\r{:.1%}'.format(float(progress) / size), end='') + sys.stdout.flush() + if not chunk: + break + local_file.write(chunk) + + local_file.close() + if sys.stdout.isatty(): + print('\r \r', end='') + sys.stdout.flush() + + logging.debug('Verifying checksum...') + if not cls.verify_checksum(local_file.name, checksum): + raise ValueError('incorrect checksum') + logging.debug('Checksum verified.') + + shutil.move(local_file.name, destination) + except: + os.unlink(local_file.name) + raise + + del download + + @classmethod + def verify_checksum(cls, path, expected): + expected = binascii.unhexlify(expected) + + with open(path, 'rb') as file: + file_contents = file.read() + hash = None + if len(expected) == hashlib.md5().digest_size: + hash = hashlib.md5() + elif len(expected) == hashlib.sha1().digest_size: + hash = hashlib.sha1() + else: + raise ValueError('unknown checksum type') + hash.update(file_contents) + return expected == hash.digest() + + def __clean_destination_dir(self): + if os.path.exists(self.destination): + shutil.rmtree(self.destination) + os.makedirs(self.destination) + + def __unpack(self): + if tarfile.is_tarfile(self.local_download_path): + self.__tarfile_unpack() + return + if zipfile.is_zipfile(self.local_download_path): + self.__zipfile_unpack() + return + + def __tarfile_unpack(self): + with open(self.local_download_path, 'rb') as file: + tar = tarfile.open(fileobj=file, mode='r|*') + tar.extractall(self.destination if isinstance(self.destination, str) else self.destination.encode(sys.getfilesystemencoding())) + del tar + + def __zipfile_unpack(self): + with zipfile.ZipFile(self.local_download_path, 'r') as file: + file.extractall(self.destination) + + def __trim_lone_dirs(self): + temporary_directory = os.path.join(self.cache_directory, 'temp_') + + while True: + destination_contents = os.listdir(self.destination) + if len(destination_contents) != 1: + break + lone_directory = os.path.join(self.destination, destination_contents[0]) + if not os.path.isdir(lone_directory): + break + shutil.move(lone_directory, temporary_directory) + shutil.rmtree(self.destination) + shutil.move(temporary_directory, self.destination) diff --git a/pool/shard006/Python/0058411_exasol_to_s3.py b/pool/shard006/Python/0058411_exasol_to_s3.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b53c6b1ff49a149c1e03d5c5e0d223b03b0f97 --- /dev/null +++ b/pool/shard006/Python/0058411_exasol_to_s3.py @@ -0,0 +1,115 @@ +# +# 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. +"""Transfers data from Exasol database into a S3 Bucket.""" + +from tempfile import NamedTemporaryFile +from typing import Dict, Optional + +from airflow.models import BaseOperator +from airflow.providers.amazon.aws.hooks.s3 import S3Hook +from airflow.providers.exasol.hooks.exasol import ExasolHook + + +class ExasolToS3Operator(BaseOperator): + """ + Export data from Exasol database to AWS S3 bucket. + + :param query_or_table: the sql statement to be executed or table name to export + :type query_or_table: str + :param key: S3 key that will point to the file + :type key: str + :param bucket_name: Name of the bucket in which to store the file + :type bucket_name: str + :param replace: A flag to decide whether or not to overwrite the key + if it already exists. If replace is False and the key exists, an + error will be raised. + :type replace: bool + :param encrypt: If True, the file will be encrypted on the server-side + by S3 and will be stored in an encrypted form while at rest in S3. + :type encrypt: bool + :param gzip: If True, the file will be compressed locally + :type gzip: bool + :param acl_policy: String specifying the canned ACL policy for the file being + uploaded to the S3 bucket. + :type acl_policy: str + :param query_params: Query parameters passed to underlying ``export_to_file`` + method of :class:`~pyexasol.connection.ExaConnection`. + :type query_params: dict + :param export_params: Extra parameters passed to underlying ``export_to_file`` + method of :class:`~pyexasol.connection.ExaConnection`. + :type export_params: dict + """ + + template_fields = ('query_or_table', 'key', 'bucket_name', 'query_params', 'export_params') + template_fields_renderers = {"query_or_table": "sql", "query_params": "json", "export_params": "json"} + template_ext = ('.sql',) + ui_color = '#ededed' + + def __init__( + self, + *, + query_or_table: str, + key: str, + bucket_name: Optional[str] = None, + replace: bool = False, + encrypt: bool = False, + gzip: bool = False, + acl_policy: Optional[str] = None, + query_params: Optional[Dict] = None, + export_params: Optional[Dict] = None, + exasol_conn_id: str = 'exasol_default', + aws_conn_id: str = 'aws_default', + **kwargs, + ) -> None: + super().__init__(**kwargs) + self.query_or_table = query_or_table + self.key = key + self.bucket_name = bucket_name + self.replace = replace + self.encrypt = encrypt + self.gzip = gzip + self.acl_policy = acl_policy + self.query_params = query_params + self.export_params = export_params + self.exasol_conn_id = exasol_conn_id + self.aws_conn_id = aws_conn_id + + def execute(self, context): + exasol_hook = ExasolHook(exasol_conn_id=self.exasol_conn_id) + s3_hook = S3Hook(aws_conn_id=self.aws_conn_id) + + with NamedTemporaryFile("w+") as file: + exasol_hook.export_to_file( + filename=file.name, + query_or_table=self.query_or_table, + export_params=self.export_params, + query_params=self.query_params, + ) + file.flush() + self.log.info("Uploading the data as %s", self.key) + s3_hook.load_file( + filename=file.name, + key=self.key, + bucket_name=self.bucket_name, + replace=self.replace, + encrypt=self.encrypt, + gzip=self.gzip, + acl_policy=self.acl_policy, + ) + self.log.info("Data uploaded") + return self.key diff --git a/pool/shard006/Python/0058412_prune_database.py b/pool/shard006/Python/0058412_prune_database.py new file mode 100644 index 0000000000000000000000000000000000000000..5b33f1368cf7eb0658199d4a2ffba8d11c17144b --- /dev/null +++ b/pool/shard006/Python/0058412_prune_database.py @@ -0,0 +1,63 @@ +import os +import sys +from datetime import datetime +from datetime import timedelta +import json +import pytz + +from django.core.management.base import BaseCommand, CommandError +from django.conf import settings +from django.utils import timezone +from django.utils.dateparse import parse_datetime +from radio.models import * +from django.db import transaction,connections,connection + +db_name = connection.settings_dict['NAME'] +db_engine = connection.vendor +print('db_name is "%s"' % db_name) +print('db_engine is "%s"' % db_engine) + +class Command(BaseCommand): + help = 'Prune transmisison table' + + def add_arguments(self, parser): + parser.add_argument( + '--days', + type=int, + #action='store_true', + #dest='source', + default=5, + help='Set the number of days older than to prune', + ) + + def handle(self, *args, **options): + print('You passed in {}'.format(options['days'])) + purge_trans(options) + + + +def purge_trans(options): + + days_opt = options['days'] + days_default = False + if days_opt == -1: + days_opt = 0 + days_default = True + + t = Transmission.objects.filter(start_datetime__lt=timezone.now() - timedelta(days=days_opt)) + print('Pruning %s transmissions older than %s days.' % (t.count(), days_opt)) + t.delete() + print('Pruning complete') + if 'sqlite' in db_engine: + def vacuum_db(using='default'): + cursor = connections[using].cursor() + cursor.execute("VACUUM") + transaction.commit() + + print ("Vacuuming database...") + before = os.stat(db_name).st_size + print ("Size before: %s bytes" % before) + vacuum_db() + after = os.stat(db_name).st_size + print ("Size after: %s bytes" % after) + print ("Reclaimed: %s bytes" % (before - after)) diff --git a/pool/shard006/Python/0058415_Note.py b/pool/shard006/Python/0058415_Note.py new file mode 100644 index 0000000000000000000000000000000000000000..5e63df8aabf02758c45521a184259f79c4a24546 --- /dev/null +++ b/pool/shard006/Python/0058415_Note.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# -*- coding: utf-8 -*- +""" + +@author: mel +""" +from beatle.model import TComponent, ClassDiagram + +class Note(TComponent): + """Implements class representation""" + def __init__(self, **kwargs): + """Initialization method""" + kwargs['visibleInTree'] = False + super(Note, self).__init__(**kwargs) + + def get_kwargs(self): + """Returns the kwargs needed for this object""" + kwargs = {} + kwargs.update(super(Note, self).get_kwargs()) + return kwargs + + def Delete(self): + """Delete diagram objects""" + #process diagrams + dias = self.project(ClassDiagram) + for dia in dias: + # Check if inherit is in + elem = dia.FindElement(self) + if elem is not None: + dia.SaveState() + dia.RemoveElement(elem) + if hasattr(dia, '_pane') and dia._pane is not None: + dia._pane.Refresh() + super(Note, self).Delete() + + def OnUndoRedoChanged(self): + """Update from app""" + #update class diagrams + project = self.project + if project is not None: + dias = project(ClassDiagram) + for dia in dias: + # Check if class is in + elem = dia.FindElement(self) + if elem is not None: + elem.Layout() + if hasattr(dia, '_pane') and dia._pane is not None: + dia._pane.Refresh() + super(Note, self).OnUndoRedoChanged() diff --git a/pool/shard006/Python/0058419_upload.py b/pool/shard006/Python/0058419_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..1610c8e7a885e79df8b240bb2575cee490b75ea1 --- /dev/null +++ b/pool/shard006/Python/0058419_upload.py @@ -0,0 +1,31 @@ + +import requests +import threading +import logging + +logger = logging.getLogger('photobooth.upload') + +PHOTO_API_KEY = '''TODO: Your API key here''' + + +def upload_image_async(upload_to, file_path): + UploadThread(upload_to, file_path).start() + + +class UploadThread(threading.Thread): + def __init__(self, url, file_path): + super(UploadThread, self).__init__() + self.url = url + self.file_path = file_path + + def run(self): + logger.info("Uploading to website: %s", self.file_path) + with open(self.file_path, 'rb') as f: + files = {'file': f} + headers = {'X-API-TOKEN': PHOTO_API_KEY} + try: + r = requests.post(self.url, files=files, headers=headers) + r.raise_for_status() + logger.info("Uploaded %s successfully", self.file_path) + except Exception: + logger.exception("Failed to upload %s. ", self.file_path) diff --git a/pool/shard006/Python/0058422_hook-PySide2.py b/pool/shard006/Python/0058422_hook-PySide2.py new file mode 100644 index 0000000000000000000000000000000000000000..23c657919811c3695396b91387a5eff26064a300 --- /dev/null +++ b/pool/shard006/Python/0058422_hook-PySide2.py @@ -0,0 +1,23 @@ +#----------------------------------------------------------------------------- +# Copyright (c) 2005-2019, PyInstaller Development Team. +# +# Distributed under the terms of the GNU General Public License with exception +# for distributing bootloader. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- +import os.path + +from PyInstaller.utils.hooks import collect_system_data_files +from PyInstaller.utils.hooks.qt import pyside2_library_info, get_qt_binaries + +hiddenimports = ['shiboken2'] + +# Collect the ``qt.conf`` file. +datas = [x for x in + collect_system_data_files(pyside2_library_info.location['PrefixPath'], + 'PySide2') + if os.path.basename(x[0]) == 'qt.conf'] + +# Collect required Qt binaries. +binaries = get_qt_binaries(pyside2_library_info) diff --git a/pool/shard006/Python/0058425_utils.py b/pool/shard006/Python/0058425_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..66339ac2a1c12e601c765a3aa9313253b86b3345 --- /dev/null +++ b/pool/shard006/Python/0058425_utils.py @@ -0,0 +1,40 @@ +import types +import urllib +import logging +from flask import request, url_for + +logger = logging.getLogger(__name__) + + +def default_handler(obj, role="admin"): + """JSON handler for default query formatting""" + if hasattr(obj, "isoformat"): + return obj.isoformat() + if hasattr(obj, "dump"): + return obj.dump(role=role) + if isinstance(obj, (set, frozenset, types.GeneratorType)): + return list(obj) + if isinstance(obj, BaseException): + return str(obj) + raise TypeError( + "Object of type %s with value of %r " + "is not JSON serializable" % (type(obj), obj) + ) + + +def rebuild_url(url, base_split): + split = urllib.parse.urlsplit(url) + if split.scheme and split.netloc: + return url # url is fine + new_split = urllib.parse.SplitResult( + scheme=split.scheme or base_split.scheme, + netloc=split.netloc or base_split.netloc, + path=split.path, + query="", + fragment="", + ) + return urllib.parse.urlunsplit(new_split) + + +def redirect_url(default="services"): + return request.args.get("next") or request.referrer or url_for(default) diff --git a/pool/shard006/Python/0058426_test_PeacockMainWindow.py b/pool/shard006/Python/0058426_test_PeacockMainWindow.py new file mode 100644 index 0000000000000000000000000000000000000000..7b196985d9219221e88f39531b34fa7874f5352d --- /dev/null +++ b/pool/shard006/Python/0058426_test_PeacockMainWindow.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +from peacock.PeacockMainWindow import PeacockMainWindow +from peacock.utils import Testing +import argparse, os + +class Tests(Testing.PeacockTester): + def newWidget(self, args=[]): + parser = argparse.ArgumentParser() + PeacockMainWindow.commandLineArgs(parser) + w = PeacockMainWindow() + w.show() + w.initialize(parser.parse_args(args)) + return w + + def testConsole(self): + w = self.newWidget() + self.assertEqual(w.console.isVisible(), False) + w._showConsole() + self.assertEqual(w.console.isVisible(), True) + w.setPythonVariable("foo", "bar") + + def testConnections(self): + w = self.newWidget(args=[]) + path = Testing.find_moose_test_exe() + w.tab_plugin.ExecuteTabPlugin.ExecuteOptionsPlugin.setExecutablePath(path) + self.assertIn(path, w.windowTitle()) + runner = w.tab_plugin.ExecuteTabPlugin.ExecuteRunnerPlugin + self.assertEqual(runner._total_steps, 0) + + w.tab_plugin.InputFileEditorWithMesh.setInputFile("../../common/transient.i") + self.assertIn("transient.i", w.windowTitle()) + + self.assertEqual(runner._total_steps, 8) + + w.tab_plugin.ExecuteTabPlugin.ExecuteRunnerPlugin.runClicked() + Testing.process_events(self.qapp, t=2) + self.assertTrue(os.path.exists("out_transient.e")) + + +if __name__ == '__main__': + Testing.run_tests() diff --git a/pool/shard006/Python/0058427_test_classifier.py b/pool/shard006/Python/0058427_test_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..70cf5a77c876b87938bf047a3eff0bf7dfbe9f6f --- /dev/null +++ b/pool/shard006/Python/0058427_test_classifier.py @@ -0,0 +1,170 @@ +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, division, print_function, unicode_literals + +from unittest import TestCase + +try: + import numpy as np + from scipy.sparse import csr_matrix +except ImportError: + pass + +from jubakit.classifier import Schema, Dataset, Classifier, Config +from jubakit.compat import * + +from . import requireSklearn +from .stub import * + +class SchemaTest(TestCase): + def test_simple(self): + schema = Schema({ + 'k1': Schema.STRING, + 'k2': Schema.LABEL, + }) + + (label, d) = schema.transform({'k1': 'abc', 'k2': 'def'}) + self.assertEqual(label, 'def') + self.assertEqual({'k1': 'abc'}, dict(d.string_values)) + + (label, d) = schema.transform({'k1': 'foo', 'k2': None}) # unlabeled data + self.assertEqual(label, None) + self.assertEqual({'k1': 'foo'}, dict(d.string_values)) + + def test_predict(self): + schema = Schema({ + 'k1': Schema.STRING, + 'k2': Schema.LABEL, + }) + self.assertRaises(RuntimeError, schema.predict, {}, True) + + def test_illegal_label(self): + # schema without label + self.assertRaises(RuntimeError, Schema, { + 'k1': Schema.STRING, + }) + + # schema with multiple labels + self.assertRaises(RuntimeError, Schema, { + 'k1': Schema.LABEL, + 'k2': Schema.LABEL + }) + + # schema fallback set to label + self.assertRaises(RuntimeError, Schema, { + 'k1': Schema.LABEL + }, Schema.LABEL) + +class DatasetTest(TestCase): + def test_simple(self): + loader = StubLoader() + schema = Schema({'v': Schema.LABEL}) + ds = Dataset(loader, schema) + for (idx, (label, d)) in ds: + self.assertEqual(unicode_t(idx+1), label) + self.assertEqual(0, len(d.string_values)) + self.assertEqual(0, len(d.num_values)) + self.assertEqual(0, len(d.binary_values)) + self.assertEqual(['1','2','3'], list(ds.get_labels())) + + def test_predict(self): + loader = StubLoader() + self.assertRaises(RuntimeError, Dataset, loader, None) + + def test_get_labels(self): + loader = StubLoader() + schema = Schema({'v': Schema.LABEL}) + ds = Dataset(loader, schema) + self.assertEqual(['1', '2', '3'], list(ds.get_labels())) + + def test_invalid_get_labels(self): + loader = StubLoader() + schema = Schema({'v': Schema.LABEL}) + ds = Dataset(loader, schema, static=False) + + # get_labels returns generator; as generator will be evaluated + # when actually iterating over it, pass it to list(). + self.assertRaises(RuntimeError, list, ds.get_labels()) + + def test_from_array(self): + ds = Dataset.from_array( + [ [10,20,30], [20,10,50], [40,10,30] ], # data + [ 0, 1, 0 ], # labels + ['k1', 'k2', 'k3'], # feature_names + ['pos', 'neg'], # label_names + ) + + expected_labels = ['pos', 'neg', 'pos'] + expected_k1s = [10, 20, 40] + actual_labels = [] + actual_k1s = [] + for (idx, (label, d)) in ds: + actual_labels.append(label) + actual_k1s.append(dict(d.num_values)['k1']) + + self.assertEqual(expected_labels, actual_labels) + self.assertEqual(expected_k1s, actual_k1s) + + @requireSklearn + def test_from_matrix(self): + ds = Dataset.from_matrix( + self._create_matrix(), # data + [ 0, 1, 0 ], # labels + [ 'k1', 'k2', 'k3'], # feature_names + [ 'pos', 'neg'], # label_names + ) + + expected_labels = ['pos', 'neg', 'pos'] + expected_k1s = [1,None,4] + expected_k3s = [2,3,6] + actual_labels = [] + actual_k1s = [] + actual_k3s = [] + for (idx, (label, d)) in ds: + actual_labels.append(label) + actual_k1s.append(dict(d.num_values).get('k1', None)) + actual_k3s.append(dict(d.num_values).get('k3', None)) + + self.assertEqual(expected_labels, actual_labels) + self.assertEqual(expected_k1s, actual_k1s) + self.assertEqual(expected_k3s, actual_k3s) + + def _create_matrix(self): + """ + Create a sparse matrix: + + [[1, 0, 2], + [0, 0, 3], + [4, 5, 6]] + """ + row = np.array([0, 0, 1, 2, 2, 2]) + col = np.array([0, 2, 2, 0, 1, 2]) + data = np.array([1, 2, 3, 4, 5, 6]) + return csr_matrix((data, (row, col)), shape=(3, 3)) + +class ClassifierTest(TestCase): + def test_simple(self): + classifier = Classifier() + +class ConfigTest(TestCase): + def test_simple(self): + config = Config() + self.assertEqual('AROW', config['method']) + + def test_methods(self): + config = Config() + self.assertTrue(isinstance(config.methods(), list)) + + def test_default(self): + config = Config.default() + self.assertEqual('AROW', config['method']) + + def test_method_param(self): + self.assertTrue('parameter' not in Config(method='PA')) + self.assertTrue('regularization_weight' in Config(method='PA1')['parameter']) + self.assertTrue('nearest_neighbor_num' in Config(method='NN')['parameter']) + self.assertTrue('nearest_neighbor_num' in Config(method='cosine')['parameter']) + self.assertTrue('nearest_neighbor_num' in Config(method='euclidean')['parameter']) + + def test_invalid_method(self): + self.assertRaises(RuntimeError, Config._default_parameter, 'invalid_method') diff --git a/pool/shard006/Python/0058431_Honeybee_PerimeterCoreZoning.py b/pool/shard006/Python/0058431_Honeybee_PerimeterCoreZoning.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2ddbb7d421347251fdb036e2cc5a10941198ac --- /dev/null +++ b/pool/shard006/Python/0058431_Honeybee_PerimeterCoreZoning.py @@ -0,0 +1,102 @@ +# +# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari +# +# This file is part of Honeybee. +# +# Copyright (c) 2013-2020, Chien Si Harriman - Modified by Mostapha Sadeghipour Roudsari +# Honeybee 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. +# +# Honeybee 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 Honeybee; If not, see . +# +# @license GPL-3.0+ + + +""" +Separate zones into perimeter and core +- +Provided by Honeybee 0.0.66 + + Args: + _bldgMasses: A Closed brep representing a building or a list of closed Breps. + bldgsFlr2FlrHeights_: A floor height in Rhino model units or list of building floor heights for the geometries. + perimeterZoneDepth_: A perimeter zone dpeth in Rhino model units or list of bperimeter depths for the geometries. + _createHoneybeeZones: Set Boolean to True to split up the building mass into zones. + Returns: + readMe!: ... + _splitBldgMasses: A lot of breps that correspond to the recommended means of breaking up geometry into zones for energy simulations. +""" + + +ghenv.Component.Name = 'Honeybee_PerimeterCoreZoning' +ghenv.Component.NickName = 'PerimeterCore' +ghenv.Component.Message = 'VER 0.0.66\nJUL_07_2020' +ghenv.Component.IconDisplayMode = ghenv.Component.IconDisplayMode.application +ghenv.Component.Category = "HB-Legacy" +ghenv.Component.SubCategory = "00 | Honeybee" +#compatibleHBVersion = VER 0.0.56\nNOV_04_2016 +#compatibleLBVersion = VER 0.0.59\nFEB_01_2015 +try: ghenv.Component.AdditionalHelpFromDocStrings = "0" +except: pass + + +import uuid + +import scriptcontext as sc +import Grasshopper.Kernel as gh + + +def main(HBZones): + + if not sc.sticky.has_key("honeybee_release"): + print "You should first let the Honeybee fly..." + w = gh.GH_RuntimeMessageLevel.Warning + ghenv.Component.AddRuntimeMessage(w, "You should first let the Honeybee fly...") + return -1 + + try: + if not sc.sticky['honeybee_release'].isCompatible(ghenv.Component): return -1 + if sc.sticky['honeybee_release'].isInputMissing(ghenv.Component): return -1 + except: + warning = "You need a newer version of Honeybee to use this compoent." + \ + "Use updateHoneybee component to update userObjects.\n" + \ + "If you have already updated userObjects drag Honeybee_Honeybee component " + \ + "into canvas and try again." + w = gh.GH_RuntimeMessageLevel.Warning + ghenv.Component.AddRuntimeMessage(w, warning) + return -1 + + hb_hive = sc.sticky["honeybee_Hive"]() + HBZonesFromHive = hb_hive.visualizeFromHoneybeeHive(HBZones) + print len(HBZonesFromHive) + interiorzones = [] + perimeterzones = [] + for zone in HBZonesFromHive: + + for surface in zone.surfaces: + if surface.type == 0 and surface.BC.upper() == "OUTDOORS": + #this is a perimeter wall + perimeterzones.append(zone) + break + + if zone not in perimeterzones: + interiorzones.append(zone) + + perims = hb_hive.addToHoneybeeHive(perimeterzones, ghenv.Component) + ints = hb_hive.addToHoneybeeHive(interiorzones, ghenv.Component, False) + + return perims,ints + + +zones = main(_HBZones) + +if zones!=-1: + perimeters, interiors = zones \ No newline at end of file diff --git a/pool/shard006/Python/0058433_TestingIso.py b/pool/shard006/Python/0058433_TestingIso.py new file mode 100644 index 0000000000000000000000000000000000000000..0e39e8363bef6d58ba85b5457408ec6534b83dff --- /dev/null +++ b/pool/shard006/Python/0058433_TestingIso.py @@ -0,0 +1,116 @@ +import TestGraphs +from GraphIsomorphism import checkIsomorphic + +print "Testing graph with 10 nodes" + +maker = TestGraphs.MakeRandom(10) +(gph1,gph2) = maker.getIsoPair() + + +def isoAction(perm): + assert gph1.iso(gph2,perm), \ + 'Failure iso test10' + +def noIsoAction(): + raise Exception('Failure with test10 ') + +def failAction(): + raise Exception('Failure with test10') + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +maker = TestGraphs.MakeRandom(10) +(gph1,gph2) = maker.getNonIsoPair() + +def isoAction(perm): + raise Exception('Failure with non iso test10') + +def noIsoAction(): + pass # the result we expect + +def failAction(): + raise Exception('Failure with non iso test10') + + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +print "Testing graph with 100 nodes" + +maker = TestGraphs.MakeRandom(100) +(gph1,gph2) = maker.getIsoPair() + + +def isoAction(perm): + assert gph1.iso(gph2,perm), \ + 'Failure iso test100' + +def noIsoAction(): + raise Exception('Failure with test100 ') + +def failAction(): + raise Exception('Failure with test100') + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +maker = TestGraphs.MakeRandom(100) +(gph1,gph2) = maker.getNonIsoPair() + +def isoAction(perm): + raise Exception('Failure with non iso test100') + +def noIsoAction(): + pass # the result we expect + +def failAction(): + raise Exception('Failure with non iso test100') + + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +print "Testing graph with 500 nodes" + +maker = TestGraphs.MakeRandom(500) +(gph1,gph2) = maker.getIsoPair() + + +def isoAction(perm): + assert gph1.iso(gph2,perm), \ + 'Failure iso test500' + +def noIsoAction(): + raise Exception('Failure with test500 ') + +def failAction(): + raise Exception('Failure with test500') + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +maker = TestGraphs.MakeRandom(500) +(gph1,gph2) = maker.getNonIsoPair() + +def isoAction(perm): + raise Exception('Failure with non iso test500') + +def noIsoAction(): + pass # the result we expect + +def failAction(): + raise Exception('Failure with non iso test500') + + +checkIsomorphic( + gph1, gph2, isoAction, noIsoAction, failAction +) + +print 'Testing Graphs of size 10, 500, and 500 passed' + diff --git a/pool/shard006/Python/0058434_aitools.py b/pool/shard006/Python/0058434_aitools.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2dd46bfab7cc9ff69db29b51595680e41e968f --- /dev/null +++ b/pool/shard006/Python/0058434_aitools.py @@ -0,0 +1,168 @@ +import random + +from utils import vector +from utils.settings import * + + +# Misc Functions + + +def random_location_on_screen(): + return int(random.random() * SCREEN_HEIGHT), int(random.random() * SCREEN_WIDTH) + + +def point_off_screen(distance=32): + screen_side = int(random.random() * 3 + 1) - 1 + + if screen_side == LEFT: + point = vector.Vector2d(-distance, random.random() * SCREEN_HEIGHT) + elif screen_side == TOP: + point = vector.Vector2d(random.random() * SCREEN_WIDTH, -distance) + elif screen_side == RIGHT: + point = vector.Vector2d(SCREEN_WIDTH + distance, random.random() * SCREEN_HEIGHT) + elif screen_side == BOTTOM: + point = vector.Vector2d(random.random() * SCREEN_WIDTH, SCREEN_HEIGHT + distance) + + return point + +# Spawning Functions + + +def spawn_at_point(actor, point): + actor.position = vector.Vector2d(point) + + +def spawn_away_from_target(actor, target, distance=256): + check = False + + while not check: + actor.position = vector.Vector2d((random.random() * actor.bounds[RIGHT]), + (random.random() * actor.bounds[BOTTOM])) + check = True + + check_distance = actor.position - target.position + if check_distance.get_magnitude() < distance: + check = False + + +def spawn_on_screen(actor): + """Position the actor randomly on the screen such that their bounds are + contained within the screen rect""" + + actor.position = vector.Vector2d(((random.random() * (actor.bounds[RIGHT] - actor.bounds[LEFT])) + actor.bounds[LEFT]), + ((random.random() * (actor.bounds[BOTTOM] - actor.bounds[TOP])) + actor.bounds[TOP])) + + +def spawn_off_screen(actor, distance=32): + screen_side = int(random.random() * 3 + 1) - 1 + + if screen_side == LEFT: + actor.position = vector.Vector2d(-distance, random.random() * SCREEN_HEIGHT) + + elif screen_side == TOP: + actor.position = vector.Vector2d(random.random() * SCREEN_WIDTH, -distance) + + elif screen_side == RIGHT: + actor.position = vector.Vector2d(SCREEN_WIDTH + distance, random.random() * SCREEN_HEIGHT) + + elif screen_side == BOTTOM: + actor.position = vector.Vector2d(random.random() * SCREEN_WIDTH, SCREEN_HEIGHT + distance) + + +# AI Styles +def hide(actor, hide_behind, hide_from, offset=128): + # Find the location that the actor should go to + goal_location = hide_behind.position + offset_direction = hide_behind.position - hide_from.position + offset_direction.make_normal() + goal_location += (offset_direction * offset) + + # Send the actor to target location + bearing = goal_location - actor.position + + if bearing.get_magnitude() > actor.speed: + bearing.set_magnitude(actor.speed) + + actor.velocity = bearing + + +def go_to_point(actor, point): + bearing = point - actor.position + + if bearing.get_magnitude() > actor.speed: + bearing.set_magnitude(actor.speed) + + actor.velocity = bearing + + +def go_to_target(actor, target): + bearing = target.position - actor.position + + if bearing.get_magnitude() > actor.speed: + bearing.set_magnitude(actor.speed) + + actor.velocity = bearing + + +def arc_to_point(actor, target_point, degree=1): + goal_bearing = target_point - actor.position + goal_bearing.make_normal() + goal_bearing *= degree + + actor.velocity += goal_bearing + actor.velocity.set_magnitude(actor.speed) + + +def cardinal_direction(actor): + if int(random.random() * 2 + 1) - 1: + if int(random.random() * 2 + 1) - 1: + actor.velocity = vector.Vector2d(actor.speed, 0.0) + + else: + actor.velocity = vector.Vector2d(-actor.speed, 0.0) + + else: + if int(random.random() * 2 + 1) - 1: + actor.velocity = vector.Vector2d(0.0, actor.speed) + + else: + actor.velocity = vector.Vector2d(0.0, -actor.speed) + + +# AI tools +def get_closest(search_actor, test_group_list, actor_type_list=None): + """Find the closest actor. + + Arguments: + search_actor: The actor that you want to find the closest other actor + test_group_list: The actor groups that you want to test, expects a list of lists + actors_type_list: The actor types you want to test, expects a list of actor types + + Returns closest actor or self + """ + test_actor_list = [] + + if not actor_type_list: + for test_group in test_group_list: + for test_actor in test_group: + test_actor_list.append(test_actor) + else: + for test_group in test_group_list: + for test_actor in test_group: + if test_actor.actor_type in actor_type_list: + test_actor_list.append(test_actor) + + closest_distance = 100000 + closest_object = None + + if not test_actor_list: + return search_actor + + for test_actor in test_actor_list: + test_actor_distance = test_actor.position - search_actor.position + + if closest_distance > test_actor_distance.get_magnitude(): + closest_distance = test_actor_distance.get_magnitude() + closest_object = test_actor + + return closest_object diff --git a/pool/shard006/Python/0058437_auth.py b/pool/shard006/Python/0058437_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..d2423d20d91cf26bc66faa331a92398baaa00705 --- /dev/null +++ b/pool/shard006/Python/0058437_auth.py @@ -0,0 +1,179 @@ +""" +The application interface to roles which checks whether any user trying to change +authorization has authorization to do so, which infers authorization via role hierarchy +(GlobalStaff is superset of auths of course instructor, ...), which consults the config +to decide whether to check course creator role, and other such functions. +""" +from __future__ import absolute_import + +from ccx_keys.locator import CCXBlockUsageLocator, CCXLocator +from django.conf import settings +from django.core.exceptions import PermissionDenied +from opaque_keys.edx.locator import LibraryLocator + +from student.roles import ( + CourseBetaTesterRole, + CourseCreatorRole, + CourseInstructorRole, + CourseRole, + CourseStaffRole, + GlobalStaff, + LibraryUserRole, + OrgInstructorRole, + OrgLibraryUserRole, + OrgStaffRole +) + +# Studio permissions: +STUDIO_EDIT_ROLES = 8 +STUDIO_VIEW_USERS = 4 +STUDIO_EDIT_CONTENT = 2 +STUDIO_VIEW_CONTENT = 1 +STUDIO_NO_PERMISSIONS = 0 +# In addition to the above, one is always allowed to "demote" oneself to a lower role within a course, or remove oneself + + +def is_ccx_course(course_key): + """ + Check whether the course locator maps to a CCX course; this is important + because we don't allow access to CCX courses in Studio. + """ + return isinstance(course_key, CCXLocator) or isinstance(course_key, CCXBlockUsageLocator) + + +def user_has_role(user, role): + """ + Check whether this user has access to this role (either direct or implied) + :param user: + :param role: an AccessRole + """ + if not user.is_active: + return False + # do cheapest check first even tho it's not the direct one + if GlobalStaff().has_user(user): + return True + # CourseCreator is odd b/c it can be disabled via config + if isinstance(role, CourseCreatorRole): + # completely shut down course creation setting + if settings.FEATURES.get('DISABLE_COURSE_CREATION', False): + return False + # wide open course creation setting + if not settings.FEATURES.get('ENABLE_CREATOR_GROUP', False): + return True + + if role.has_user(user): + return True + # if not, then check inferred permissions + if (isinstance(role, (CourseStaffRole, CourseBetaTesterRole)) and + CourseInstructorRole(role.course_key).has_user(user)): + return True + return False + + +def get_user_permissions(user, course_key, org=None): + """ + Get the bitmask of permissions that this user has in the given course context. + Can also set course_key=None and pass in an org to get the user's + permissions for that organization as a whole. + """ + if org is None: + org = course_key.org + course_key = course_key.for_branch(None) + else: + assert course_key is None + # No one has studio permissions for CCX courses + if is_ccx_course(course_key): + return STUDIO_NO_PERMISSIONS + all_perms = STUDIO_EDIT_ROLES | STUDIO_VIEW_USERS | STUDIO_EDIT_CONTENT | STUDIO_VIEW_CONTENT + # global staff, org instructors, and course instructors have all permissions: + if GlobalStaff().has_user(user) or OrgInstructorRole(org=org).has_user(user): + return all_perms + if course_key and user_has_role(user, CourseInstructorRole(course_key)): + return all_perms + # Staff have all permissions except EDIT_ROLES: + if OrgStaffRole(org=org).has_user(user) or (course_key and user_has_role(user, CourseStaffRole(course_key))): + return STUDIO_VIEW_USERS | STUDIO_EDIT_CONTENT | STUDIO_VIEW_CONTENT + # Otherwise, for libraries, users can view only: + if course_key and isinstance(course_key, LibraryLocator): + if OrgLibraryUserRole(org=org).has_user(user) or user_has_role(user, LibraryUserRole(course_key)): + return STUDIO_VIEW_USERS | STUDIO_VIEW_CONTENT + return STUDIO_NO_PERMISSIONS + + +def has_studio_write_access(user, course_key): + """ + Return True if user has studio write access to the given course. + Note that the CMS permissions model is with respect to courses. + There is a super-admin permissions if user.is_staff is set. + Also, since we're unifying the user database between LMS and CAS, + I'm presuming that the course instructor (formally known as admin) + will not be in both INSTRUCTOR and STAFF groups, so we have to cascade our + queries here as INSTRUCTOR has all the rights that STAFF do. + + :param user: + :param course_key: a CourseKey + """ + return bool(STUDIO_EDIT_CONTENT & get_user_permissions(user, course_key)) + + +def has_course_author_access(user, course_key): + """ + Old name for has_studio_write_access + """ + return has_studio_write_access(user, course_key) + + +def has_studio_read_access(user, course_key): + """ + Return True iff user is allowed to view this course/library in studio. + Will also return True if user has write access in studio (has_course_author_access) + + There is currently no such thing as read-only course access in studio, but + there is read-only access to content libraries. + """ + return bool(STUDIO_VIEW_CONTENT & get_user_permissions(user, course_key)) + + +def add_users(caller, role, *users): + """ + The caller requests adding the given users to the role. Checks that the caller + has sufficient authority. + + :param caller: a user + :param role: an AccessRole + """ + _check_caller_authority(caller, role) + role.add_users(*users) + + +def remove_users(caller, role, *users): + """ + The caller requests removing the given users from the role. Checks that the caller + has sufficient authority. + + :param caller: a user + :param role: an AccessRole + """ + # can always remove self (at this layer) + if not(len(users) == 1 and caller == users[0]): + _check_caller_authority(caller, role) + role.remove_users(*users) + + +def _check_caller_authority(caller, role): + """ + Internal function to check whether the caller has authority to manipulate this role + :param caller: a user + :param role: an AccessRole + """ + if not (caller.is_authenticated and caller.is_active): + raise PermissionDenied + # superuser + if GlobalStaff().has_user(caller): + return + + if isinstance(role, (GlobalStaff, CourseCreatorRole)): + raise PermissionDenied + elif isinstance(role, CourseRole): # instructors can change the roles w/in their course + if not user_has_role(caller, CourseInstructorRole(role.course_key)): + raise PermissionDenied diff --git a/pool/shard006/Python/0058439_test_diag.py b/pool/shard006/Python/0058439_test_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0bfbefcb3ebbb7256f9677082d854b0ccaf0ea --- /dev/null +++ b/pool/shard006/Python/0058439_test_diag.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- + +# This code is part of Qiskit. +# +# (C) Copyright IBM 2019. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + + +"""Diagonal gate tests.""" + +import unittest +import numpy as np + +from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute + +from qiskit.test import QiskitTestCase +from qiskit.compiler import transpile +from qiskit.quantum_info.operators.predicates import matrix_equal + + +class TestDiagGate(QiskitTestCase): + """ + Diagonal gate tests. + """ + def test_diag_gate(self): + """Test diagonal gates.""" + for phases in [[0, 0], [0, 0.8], [0, 0, 1, 1], [0, 1, 0.5, 1], + (2 * np.pi * np.random.rand(2 ** 3)).tolist(), + (2 * np.pi * np.random.rand(2 ** 4)).tolist(), + (2 * np.pi * np.random.rand(2 ** 5)).tolist()]: + with self.subTest(phases=phases): + diag = [np.exp(1j * ph) for ph in phases] + num_qubits = int(np.log2(len(diag))) + q = QuantumRegister(num_qubits) + qc = QuantumCircuit(q) + qc.diag_gate(diag, q[0:num_qubits]) + # Decompose the gate + qc = transpile(qc, basis_gates=['u1', 'u3', 'u2', 'cx', 'id']) + # Simulate the decomposed gate + simulator = BasicAer.get_backend('unitary_simulator') + result = execute(qc, simulator).result() + unitary = result.get_unitary(qc) + unitary_desired = _get_diag_gate_matrix(diag) + self.assertTrue(matrix_equal(unitary, unitary_desired, ignore_phase=True)) + + +def _get_diag_gate_matrix(diag): + return np.diagflat(diag) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard006/Python/0058440_client.py b/pool/shard006/Python/0058440_client.py new file mode 100644 index 0000000000000000000000000000000000000000..962b9bf37dc3b50e1fdf2c9868964a0f8707e49d --- /dev/null +++ b/pool/shard006/Python/0058440_client.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# This file is part of the bliss project +# +# Copyright (c) 2016 Beamline Control Unit, ESRF +# Distributed under the GNU LGPLv3. See LICENSE for more info. + +import sys +import os +import gevent + +sys.path.insert( + 0, + os.path.abspath( + os.path.join( + os.path.dirname(__file__), + os.path.pardir, os.path.pardir))) + +from bliss.common.data_manager import get_node + +toto = get_node("toto") + +for node in toto.iterator.walk(filter=('scan', 'lima')): + print node.db_name + +""" +for node in toto.iterator.walk(filter='lima'): + gevent.spawn(analyse_data, node) + +def analyse_data(node): + for data in node.iterator.walk_data(): + print data +""" diff --git a/pool/shard006/Python/0058441_test_simple_formatter.py b/pool/shard006/Python/0058441_test_simple_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..e2e211479e0fa232ec9cfbfb1fe991fa45fa6292 --- /dev/null +++ b/pool/shard006/Python/0058441_test_simple_formatter.py @@ -0,0 +1,49 @@ +from unittest.mock import Mock, sentinel + +import pytest + +from jj.logs import SimpleFormatter + +from .._test_utils.steps import given, then, when +from ._log_record import TestLogRecord + + +@pytest.fixture() +def formatter(): + return SimpleFormatter() + + +@pytest.fixture() +def record(): + return TestLogRecord(sentinel.message) + + +def test_format_without_request_and_response(formatter: SimpleFormatter, record: TestLogRecord): + with when: + res = formatter.format(record) + + with then: + assert res == str(sentinel.message) + + +def test_format_with_request(formatter: SimpleFormatter, record: TestLogRecord): + with given: + record.jj_request = Mock(url=Mock(path=sentinel.path)) + + with when: + res = formatter.format(record) + + with then: + assert res == "-> {}".format(sentinel.path) + + +def test_format_with_response(formatter: SimpleFormatter, record: TestLogRecord): + with given: + record.jj_request = Mock() + record.jj_response = Mock(status=sentinel.status, reason=sentinel.reason) + + with when: + res = formatter.format(record) + + with then: + assert res == "<- {} {}\n".format(sentinel.status, sentinel.reason) diff --git a/pool/shard006/Python/0058443_extract_pca_kernels.py b/pool/shard006/Python/0058443_extract_pca_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6c18ba511aabd96f654dc2e781d1e1d037e696 --- /dev/null +++ b/pool/shard006/Python/0058443_extract_pca_kernels.py @@ -0,0 +1,63 @@ +# Computes the gaussian gradients on a boxm_alpha_scene + +import bvpl_octree_batch; +import os; +import optparse; +import time; +class dbvalue: + def __init__(self, index, type): + self.id = index # unsigned integer + self.type = type # string + + +if __name__=="__main__": + + bvpl_octree_batch.register_processes(); + bvpl_octree_batch.register_datatypes(); + + #Parse inputs + parser = optparse.OptionParser(description='Compute PCA basis'); + + parser.add_option('--model_dir', action="store", dest="model_dir"); + parser.add_option('--pca_dir', action="store", dest="pca_dir"); + parser.add_option('--train_fraction', action="store", dest="train_fraction", type="float", default =0.0) + options, args = parser.parse_args() + + model_dir = options.model_dir; + pca_dir = options.pca_dir; + train_fraction = (options.train_fraction)/10; + + if not os.path.isdir(model_dir +"/"): + print "Invalid Model Dir" + sys.exit(-1); + + if not os.path.isdir( pca_dir + "/"): + os.makedirs( pca_dir + "/"); + + + print("Extracting Principal Components patches"); + + print("Creating a Scene"); + bvpl_octree_batch.init_process("boxmCreateSceneProcess"); + bvpl_octree_batch.set_input_string(0, model_dir +"/mean_color_scene.xml"); + bvpl_octree_batch.run_process(); + (scene_id, scene_type) = bvpl_octree_batch.commit_output(0); + scene= dbvalue(scene_id, scene_type); + + start_time = time.time(); + + print("Extract PC"); + bvpl_octree_batch.init_process("bvplDiscoverPCAFeaturesProcess"); + bvpl_octree_batch.set_input_from_db(0, scene); + bvpl_octree_batch.set_input_string(1, pca_dir); + bvpl_octree_batch.set_input_double(2, train_fraction); + bvpl_octree_batch.set_input_int(3, -2); #min and max points of the kernle + bvpl_octree_batch.set_input_int(4, -2); + bvpl_octree_batch.set_input_int(5, -2); + bvpl_octree_batch.set_input_int(6, 2); + bvpl_octree_batch.set_input_int(7, 2); + bvpl_octree_batch.set_input_int(8, 2); + bvpl_octree_batch.run_process(); + + print ("Runing time forbvplDiscoverPCAFeaturesProcess:") + print(time.time() - start_time); \ No newline at end of file diff --git a/pool/shard006/Python/0058445_views.py b/pool/shard006/Python/0058445_views.py new file mode 100644 index 0000000000000000000000000000000000000000..cf51c77c9d4d46621df701982b5cf740e6e54f98 --- /dev/null +++ b/pool/shard006/Python/0058445_views.py @@ -0,0 +1,136 @@ +#coding: utf-8 + + +import json +import urllib +import geocoder +import pytz +from datetime import datetime +from django.shortcuts import render +from django.core.serializers.json import DjangoJSONEncoder +from django.http import HttpResponse + +from django.utils import timezone +from .models import Ephemeris, Event, Houses, Location + + + +from utils import PLANET_NAMES, SIGNS, dms + + + +def home(request): + now = timezone.now() + params = {} + params['datenow'] = now.strftime("%d/%m/%Y") + params['timenow'] = now.strftime("%H:%M") + + return render(request, 'horoscope/home.html', params) + +def my_events(request): + + return render(request, 'horoscope/event_list.html', {'events': Event.objects.all().select_related('ephemeris', 'location')}) + + +def parse_date(date_str, time_str): + now = datetime.now() + if not date_str and not time_str: + return now + + if not date_str: + date = now.date() + else: + date = datetime.strptime(date_str, "%d-%m-%Y").date() + + if not time_str: + time = now.time() + else: + time = datetime.strptime(time_str, "%H:%M").time() + + return datetime.combine(date, time) + + +def eph(request): + data = {} + date = request.GET.get('date', None) + time = request.GET.get('time', None) + + date = parse_date(date, time) + location = request.GET.get('city', None) + + if date and time and location: + l = Location.create(location) + date = l.timezone.localize(date) + date = date.astimezone(pytz.utc) + houses = Houses.create(date, l.lat, l.lng) + data['houses'] = [getattr(houses, i.name) for i in houses._meta.fields[1:]] + data['location'] = {'city': l.city, 'lat': dms(l.lat), 'lng': dms(l.lng)} + + data['planets'] = get_planets(date) + data['date'] = str(date) + + return HttpResponse( + json.dumps(data, indent=4), + content_type='application/javascript; charset=utf8' + ) + + +def get_planets(date): + e = Ephemeris.create(date) + + + planets = [] + + for index, field in enumerate(e._meta.fields[:11]): + if field.name != 'id': + v = getattr(e, field.name) + planet = {} + planet['index'] = index + planet['name'] = field.name + planet['angle'] = v + planet['sign_index'] = int(v/30) + planets.append(planet) + return planets + + +def chart(request): + date_str = request.GET.get('date', None) + time_str = request.GET.get('time', None) + date = parse_date(date_str, time_str) + planets = [] + for p in get_planets(date): + p['code'] = p['name'] + p['angle'] = p['angle'] % 30 + p['name'] = PLANET_NAMES[p['code']] + p['sign_code'], p['sign'] = SIGNS[p['sign_index']] + planets.append(p) + + return render(request, 'horoscope/chart.html', {'date': date, 'planets': planets}) + + +def save_event(request): + print 'save_event' + if request.method == 'POST': + name = request.POST.get('name') + date = request.POST.get('date') + time = request.POST.get('time') + location = request.POST.get('location') + + e = Event.create(name, date, time, location) + e.save() + print request.POST + return HttpResponse(request.POST) + +def geocode(request): + query = request.GET.get('query', None) + query = urllib.unquote(query).decode('utf8') + g = geocoder.google(query) + if g.ok and g.city: + data = [{'value': g.address, 'tokens': g.city.split()}] + else: + data = {} + + data = json.dumps(data, cls=DjangoJSONEncoder, indent=2, separators=(',', ': ')) + + return HttpResponse(data, content_type="application/json") + diff --git a/pool/shard006/Python/0058448_list.py b/pool/shard006/Python/0058448_list.py new file mode 100644 index 0000000000000000000000000000000000000000..e41ff9be88c4f2fb65992e61125451e1af8ee8a6 --- /dev/null +++ b/pool/shard006/Python/0058448_list.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# This file is part of Shoop. +# +# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +from babel.dates import format_datetime +from django.utils.html import escape +from django.utils.timezone import localtime +from django.utils.translation import ugettext as _ + +from shoop.admin.utils.picotable import ( + ChoicesFilter, Column, DateRangeFilter, MultiFieldTextFilter, RangeFilter, TextFilter +) +from shoop.admin.utils.views import PicotableListView +from shoop.core.models import Order, OrderStatus, PaymentStatus, ShippingStatus +from shoop.utils.i18n import format_money, get_current_babel_locale + + +class OrderListView(PicotableListView): + model = Order + columns = [ + Column("identifier", _(u"Order"), linked=True, filter_config=TextFilter(operator="startswith")), + Column("order_date", _(u"Order Date"), display="format_order_date", filter_config=DateRangeFilter()), + Column( + "customer", _(u"Customer"), + filter_config=MultiFieldTextFilter(filter_fields=("customer__email", "customer__name")) + ), + Column("status", _(u"Status"), filter_config=ChoicesFilter(choices=OrderStatus.objects.all())), + Column("payment_status", _(u"Payment Status"), filter_config=ChoicesFilter(choices=PaymentStatus.choices)), + Column("shipping_status", _(u"Shipping Status"), filter_config=ChoicesFilter(choices=ShippingStatus.choices)), + Column( + "taxful_total_price", _(u"Total"), sort_field="taxful_total_price_value", + display="format_taxful_total_price", class_name="text-right", + filter_config=RangeFilter(field_type="number") + ), + ] + + def get_queryset(self): + return super(OrderListView, self).get_queryset().exclude(deleted=True) + + def format_order_date(self, instance, *args, **kwargs): + return format_datetime(localtime(instance.order_date), locale=get_current_babel_locale()) + + def format_taxful_total_price(self, instance, *args, **kwargs): + return escape(format_money(instance.taxful_total_price)) + + def get_object_abstract(self, instance, item): + return [ + {"text": "%s" % instance, "class": "header"}, + {"title": _(u"Total"), "text": item["taxful_total_price"]}, + {"title": _(u"Status"), "text": item["status"]} + ] diff --git a/pool/shard006/Python/0058449_uniqueFastaID.py b/pool/shard006/Python/0058449_uniqueFastaID.py new file mode 100644 index 0000000000000000000000000000000000000000..ddd55305c55b579deedf5af34dde0acf74a2ff66 --- /dev/null +++ b/pool/shard006/Python/0058449_uniqueFastaID.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python + +"""uniqueFastaID alters the ID of each FASTA entry in a file + +Some programs such as IDBA-UD may create multiple fasta/q files where +the ID of the entries in each file are identical. uniqueFastaId simply takes a +fasta/q file and appends a user defined string to each Fasta Header ID to +ensure that each file will not have headers that clash if the files need to be +concatenated for use by various programs. Unqique adds a number to each ID to +avoid repeats. + +Copyright: + + uniqueFastaId Makes the id of each FASTA entry in a file unique + + Copyright (C) 2016 William Brazelton, Alex Hyer + + 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 sys +from Bio import SeqIO +from Bio.SeqRecord import SeqRecord +from bioinformatic_tools import fastaOrFastq +from bioinformatic_tools import qualityCheck + +__version__ = '0.12' + + +def appendStringToHeaders(in_file, string_to_append): + # Appends string to each FASTA Header ID + fileType = fastaOrFastq(in_file) + with open(in_file, 'r') as in_handle: + out_file = '' + for i in in_file.split('.')[0:-1]: + out_file += '{0}.'.format(i) + out_file += 'string.' + in_file.split('.')[-1] + with open(out_file, 'a') as out_handle: + for seq_record in SeqIO.parse(in_handle, fileType): + if args.replace is True: + seq_record.id = '' + if args.strip_description is True: + seq_record.description = '' + seq_record.id += string_to_append + SeqIO.write(seq_record, out_handle, fileType) + qualityCheck(out_file, fileType, in_file, out_file) + + +def appendNumberToHeaders(in_file): + # Appends number to each FASTA Header ID + fileType = fastaOrFastq(in_file) + with open(in_file, 'r') as in_handle: + out_file = '' + for i in in_file.split('.')[0:-1]: + out_file += '{0}.'.format(i) + out_file += 'unique.' + in_file.split('.')[-1] + with open(out_file, 'a') as out_handle: + counter = 0 + for seq_record in SeqIO.parse(in_handle, fileType): + if args.replace is True: + seq_record.id = '' + seq_record.id += str(counter) + if args.strip_description is True: + seq_record.description = '' + SeqIO.write(seq_record, out_handle, fileType) + counter += 1 + qualityCheck(out_file, fileType, in_file, out_file) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='appends a string to to all ' + 'Header IDs in a FASTA/Q file') + parser.add_argument('input_file', + default=None, + nargs='*', + help='FASTA/Q file to modify') + parser.add_argument('--replace', + action='store_true', + help='replace header ID with string or number') + parser.add_argument('--strip_description', + action='store_true', + help='remove FASTA header description') + choices = parser.add_mutually_exclusive_group(required=True) + choices.add_argument('--string', + default=None, + nargs='?', + help='the string to add to each ID the file') + choices.add_argument('--unique', + action='store_true', + help='make each ID unique by appending a number') + parser.add_argument('--version', '-v', + help='prints version and exits', + action='store_true') + args = parser.parse_args() + + if args.version: + print(__version__) + sys.exit(0) + elif args.input_file is None: + print(__doc__) + sys.exit(0) + elif args.string is not None: + for f in args.input_file: + appendStringToHeaders(f, args.string) + else: + for f in args.input_file: + appendNumberToHeaders(f) + + sys.exit(0) diff --git a/pool/shard006/Python/0058451_test_stack.py b/pool/shard006/Python/0058451_test_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..4476b4875a2d756b69bc9e2933f86527adaed2b5 --- /dev/null +++ b/pool/shard006/Python/0058451_test_stack.py @@ -0,0 +1,72 @@ +''' +Test suite for stack.py + +This test suite copies heavily from test_linked_list +in my data-structures repository. + +Usefully informed about the way unit tests look by: +https://github.com/linsomniac/python-unittest-skeleton/ +blob/master/tests/test_skeleton.py + +Note that every attribute of the Node class is tested +by the tests for the Stack class's methods. +''' + +import unittest +import stack + + +class test_Stack(unittest.TestCase): + + def setUp(self): + # The program needs several stacks to test with, and the unit tests + # can modify these stacks as they go. + # To be safe, use self.setUp on every new testing call. + self.test_stack = stack.Stack() + for each_number in range(1, 10): + self.test_stack.push(each_number) + self.test_stack_for_one_node = stack.Stack() + self.test_stack_for_one_node.push("one node stack test data") + self.test_stack_for_string_data = stack.Stack() + self.test_stack_for_string_data.push("TestData") + self.test_stack_for_string_data.push(61) + self.test_stack_for_string_data.push("Additional Test Data") + self.test_stack_for_no_nodes = stack.Stack() + + def test_Stack(self): + self.setUp() + # This feels pretty superfluous due to setUp, which appears to + # be intended to come first, but here it is anyways. + # We'll say it's for future-proofing. + stack_constructor_test_object = stack.Stack() + self.assertTrue(isinstance(stack_constructor_test_object, + stack.Stack)) + + def test_push(self): + self.setUp() + # All push(val) needs to do is successfully create + # a node that holds the value. + # This will test the Node class's basic functionality as well. + push_test_string = 'push() test data' + self.test_stack.push(push_test_string) + self.assertEqual(self.test_stack.head.data, push_test_string) + self.test_stack_for_one_node.push(push_test_string) + self.assertEqual(self.test_stack_for_one_node.head.data, + push_test_string) + self.test_stack_for_no_nodes.push(push_test_string) + self.assertEqual(self.test_stack_for_no_nodes.head.data, + push_test_string) + + def test_pop(self): + self.setUp() + pop_test_string = 'pop() test data' + self.test_stack.push(pop_test_string) + pop_test_return_data = self.test_stack.pop() + self.assertEqual(pop_test_return_data, pop_test_string) + self.assertEqual(self.test_stack_for_one_node.pop(), + "one node stack test data") + with self.assertRaises(Exception): + self.test_stack_for_no_nodes.pop() + + +unittest.main() diff --git a/pool/shard006/Python/0058458_repeatable.py b/pool/shard006/Python/0058458_repeatable.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed6b5abbfde283fb7f27550d1ae9da9e20ae396 --- /dev/null +++ b/pool/shard006/Python/0058458_repeatable.py @@ -0,0 +1,22 @@ +import unittest + +class TestSuite(unittest.TestSuite): + """Modified TestSuite which supports repeating multiple times + TestCases containing a count attribute. Useful for randomly + generated test cases.""" + def __iter__(self): + for test in self._tests: + count = test.count if hasattr(test, 'count') else 1 + for i in xrange(count): + yield test + +def make_load_tests(test_cases): + """Return a load_tests function suitable for using test discovery + with our modified TestSuite class""" + def load_tests(loader, tests, pattern): + suite = TestSuite() + for test_class in test_cases: + tests = loader.loadTestsFromTestCase(test_class) + suite.addTests(tests) + return suite + return load_tests \ No newline at end of file diff --git a/pool/shard006/Python/0058460_main__.py b/pool/shard006/Python/0058460_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..97456f7bcdb25bbf17c112a9dcc7afcb0cc4360f --- /dev/null +++ b/pool/shard006/Python/0058460_main__.py @@ -0,0 +1,66 @@ +# --------------------------------------------------------------------------- # +# Copyright (c) 2016-17 William José Moreno Reyes # +# Cacao Accounting is free libre open source software (FLOSS), licensed under # +# the GNU General Public License version 3 (GPLv3), see the LICENSE file or a # +# copy at: http://www.gnu.org/licenses/ # +# --------------------------------------------------------------------------- # + +"""Main user Interface for the Cacao Accounting Software.""" + +import logging +import sys + +from PyQt5.QtWidgets import QApplication + +from cacao_accounting_commons import ERPApi +from cacao_accounting_commons.dbconn import __dbinfo__ + +from cacao_accounting.gui import MainWindow +from cacao_accounting.login import LoginScreen +from cacao_accounting.newdb import NewDatabaseWizard +from cacao_accounting.wizard import SetupWizard + + +def login(): + """Validate user, password and databse login information.""" + _app = QApplication(sys.argv) + _gui = LoginScreen() + _gui.show() + _app.exec_() + + +def configure(): + """Init the Cacao Accounting's Setup Wizard.""" + _app = QApplication(sys.argv) + _wizard = SetupWizard() + _wizard.show() + _app.exec_() + + +def newdb(): + """Simple grafical interface to source a new database.""" + _app = QApplication(sys.argv) + _newdb = NewDatabaseWizard() + _newdb.show() + _app.exec_() + + +def main(): + """Start Cacao Accounting User Interface.""" + if __dbinfo__: + login() + else: + logging.warning("Not valid configuration found.") + configure() + + +def _main(): + """Just to check main window layout, do not connect to the database.""" + _app = QApplication(sys.argv) + _main = MainWindow() + _main.show() + _app.exec_() + + +if __name__ == "__main__": + main() diff --git a/pool/shard006/Python/0058462_ShapeFactory2.py b/pool/shard006/Python/0058462_ShapeFactory2.py new file mode 100644 index 0000000000000000000000000000000000000000..b15d18807eed0cf495d294db6dca6440db9d1a07 --- /dev/null +++ b/pool/shard006/Python/0058462_ShapeFactory2.py @@ -0,0 +1,62 @@ +#: c05:shapefact2:ShapeFactory2.py +# Polymorphic factory methods. +from __future__ import generators +import random + +class ShapeFactory: + factories = {} + def addFactory(id, shapeFactory): + ShapeFactory.factories.put[id] = shapeFactory + addFactory = staticmethod(addFactory) + # A Template Method: + def createShape(id): + if not ShapeFactory.factories.has_key(id): + ShapeFactory.factories[id] = \ + eval(id + '.Factory()') + return ShapeFactory.factories[id].create() + createShape = staticmethod(createShape) + +class Shape(object): pass + +class Circle(Shape): + def draw(self): print "Circle.draw" + def erase(self): print "Circle.erase" + class Factory: + def create(self): return Circle() + +class Square(Shape): + def draw(self): + print "Square.draw" + def erase(self): + print "Square.erase" + class Factory: + def create(self): return Square() + +def shapeNameGen(n): + types = Shape.__subclasses__() + for i in range(n): + yield random.choice(types).__name__ + +shapes = [ ShapeFactory.createShape(i) + for i in shapeNameGen(7)] + +for shape in shapes: + shape.draw() + shape.erase() +#
+output = ''' +Square.draw +Square.erase +Circle.draw +Circle.erase +Circle.draw +Circle.erase +Square.draw +Square.erase +Circle.draw +Circle.erase +Circle.draw +Circle.erase +Square.draw +Square.erase +''' diff --git a/pool/shard006/Python/0058464_test_server_status.py b/pool/shard006/Python/0058464_test_server_status.py new file mode 100644 index 0000000000000000000000000000000000000000..0c9fe7942585ffddcea8e88be477d7131930ac5f --- /dev/null +++ b/pool/shard006/Python/0058464_test_server_status.py @@ -0,0 +1,71 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +import contextlib + +from socorro.external.postgresql import server_status +from socorro.unittest.external.postgresql.unittestbase import PostgreSQLTestCase + + +@contextlib.contextmanager +def mock_get_file(): + def mock_get_file(fn): + vals = { + 'socorro_revision.txt': '42', + 'breakpad_revision.txt': '43' + } + return vals[fn] + + old_get_file = server_status.get_file + server_status.get_file = mock_get_file + yield + server_status.get_file = old_get_file + + +class IntegrationTestServerStatus(PostgreSQLTestCase): + """Test socorro.external.postgresql.server_status.ServerStatus class. """ + + def setUp(self): + """Set up this test class by populating the database with fake data. + """ + super(IntegrationTestServerStatus, self).setUp() + + cursor = self.connection.cursor() + + # Prepare data for the schema revision + # Clean up from init routine + cursor.execute("TRUNCATE alembic_version CASCADE;") + + cursor.execute(""" + INSERT INTO alembic_version + (version_num) + VALUES + ( + 'aaaaaaaaaaaa' + ) + """) + + self.connection.commit() + + def tearDown(self): + """Clean up the database. """ + cursor = self.connection.cursor() + cursor.execute("TRUNCATE alembic_version CASCADE;") + self.connection.commit() + super(IntegrationTestServerStatus, self).tearDown() + + def test_get(self): + # NOTE(willkg): This mocks out the pkg_resources code that gets the + # files, so this test doesn't test that aspect of server_status. + with mock_get_file(): + status = server_status.ServerStatus(config=self.config) + res = status.get() + + res_expected = { + "socorro_revision": "42", + "breakpad_revision": "43", + "schema_revision": "aaaaaaaaaaaa", + } + + assert res == res_expected diff --git a/pool/shard006/Python/0058466_registry.py b/pool/shard006/Python/0058466_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..602b9cd1a34c32fcb69e813c0e0226fb5f02677c --- /dev/null +++ b/pool/shard006/Python/0058466_registry.py @@ -0,0 +1,67 @@ +# 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 inspect +import os +import sys + +from oslo_log import log as logging +from oslo_utils import importutils + +import act + + +LOG = logging.getLogger(__name__) + +REGISTRY = [] + + +def import_modules_from_package(package): + base = os.path.join(os.path.dirname(act.__file__), os.pardir) + path = os.path.normpath(os.path.join(base, *package.split('.'))) + + for root, dirs, files in os.walk(path): + for filename in files: + if filename.startswith('__') or not filename.endswith('.py'): + continue + + relative_path = os.path.relpath(os.path.join(root, filename), base) + name = os.path.splitext(relative_path)[0] # remove extension + module_name = '.'.join(name.split(os.sep)) # convert / to . + + if module_name not in sys.modules: + module = importutils.import_module(module_name) + sys.modules[module_name] = module + else: + module = sys.modules[module_name] + + yield module + + +def init(): + global REGISTRY + + modules = import_modules_from_package('act.actions') + + klazz_list = [] + for module in modules: + class_info_list = inspect.getmembers(module, inspect.isclass) + klazz_list += [ci[1] for ci in class_info_list] + + REGISTRY = [k() for k in klazz_list] + + LOG.info('Registry: %s', REGISTRY) + + +def get_actions(): + return REGISTRY diff --git a/pool/shard006/Python/0058470_find-the-secret-foo.py b/pool/shard006/Python/0058470_find-the-secret-foo.py new file mode 100644 index 0000000000000000000000000000000000000000..98e5f699391f8512c3315555330201104298063b --- /dev/null +++ b/pool/shard006/Python/0058470_find-the-secret-foo.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +import curses,sys,string,random,datetime,signal + +basetime = datetime.datetime.now() +att = 0 + +def update_time(screen): + global basetime + now = datetime.datetime.now() + time = str(now - basetime) + screen.addstr(3,2,"It was been %s already... " % time) + +def getRand(): + letter = '' + while letter == 'q' or letter == '': + letter = random.choice(string.letters).lower() + return letter + + +def listen(screen): + global att + t = getRand() + c = screen.getch() + if c == ord('q'): + return False + elif c == -1: + return True + elif c == ord(t): + screen.addstr(12,25,"You've found the secret foo!") + screen.addstr(13,25,'It is %s!!!' % t) + screen.nodelay(0) + while screen.getch() != ord('q'): + screen.addstr(14,25,"Congrats! Press 'q' to exit!") + return False + else: + screen.addstr(13,25,'It was %s!!!' % t) + att = att + 1 + tries(screen,att) + curses.beep() + return True + +def tries(screen,amount): + screen.addstr(5,2,"You've tried %d times to find the missing foo!" % amount) + +try: + s = signal.signal(signal.SIGINT, signal.SIG_IGN) + screen = curses.initscr() + curses.noecho() + screen.nodelay(1) + curses.curs_set(0) + screen.border() + screen.addstr(1,1,'Find the secret foo') + screen.addstr(12,25,'Can you find me?!?!') + size = screen.getmaxyx() + screen.addstr(size[0]-2,1,"Press 'q' to exit") + while listen(screen): + update_time(screen) + screen.refresh() +except Exception as e: + sys.exit('Something broke!\n' + e.message) +finally: + signal.signal(signal.SIGINT, s) + curses.endwin() diff --git a/pool/shard006/Python/0058477_log.py b/pool/shard006/Python/0058477_log.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e0219287283b693e16d99ebaf84f18d7283a9a --- /dev/null +++ b/pool/shard006/Python/0058477_log.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +# ETHERCUT SUITE +# Author: Ivan 'evilgroot' Luengo +# Email: evilgroot@gmail.com + +# This project is released under a GPLv3 license + +""" +Logging subsystem +""" + +import logging + +class EthercutFormatter(logging.Formatter): + """ + Subclass of Formatter from logging module to print the messges with a custom format. + """ + + error_fmt = "[E] %(msg)s" + warn_fmt = "[W] %(msg)s" + debug_fmt = "[D] %(msg)s" + info_fmt = "[I] %(msg)s" + + def __init__(self, fmt="[%(levelno)s] %(msg)s"): + super(EthercutFormatter, self).__init__(fmt) + + def format(self, record): + orig = self._fmt + + # Replace the original format with a custom one depending of the log level + if record.levelno == logging.DEBUG: + self._fmt = self.debug_fmt + elif record.levelno == logging.INFO: + self._fmt = self.info_fmt + elif record.levelno == logging.WARNING: + self._fmt = self.warn_fmt + elif record.levelno == logging.ERROR: + self._fmt = self.error_fmt + + # Call the superclass format method to format the message + ret = super(EthercutFormatter, self).format(record) + + # Restore the original _fmt + self._fmt = orig + + return ret diff --git a/pool/shard006/Python/0058478_cms_app.py b/pool/shard006/Python/0058478_cms_app.py new file mode 100644 index 0000000000000000000000000000000000000000..a6afb376b0aaa45bed4563c94cbf05546bf65692 --- /dev/null +++ b/pool/shard006/Python/0058478_cms_app.py @@ -0,0 +1,23 @@ +from cms.app_base import CMSApp +from cms.apphook_pool import apphook_pool +from django.utils.translation import ugettext_lazy as _ + + +class AssopyApphook(CMSApp): + name = _("Assopy") + urls = ["assopy.urls"] + + +class ConferenceApphook(CMSApp): + name = _("Conference") + urls = ["conference.urls"] + + +class P3Apphook(CMSApp): + name = _("P3") + urls = ["p3.urls"] + + +apphook_pool.register(AssopyApphook) +apphook_pool.register(ConferenceApphook) +apphook_pool.register(P3Apphook) diff --git a/pool/shard006/Python/0058479_page.py b/pool/shard006/Python/0058479_page.py new file mode 100644 index 0000000000000000000000000000000000000000..87ee145bd84f708ccd7c9a8dcff85f94357f4b26 --- /dev/null +++ b/pool/shard006/Python/0058479_page.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +# libccc demo.py code get from pygtk helloworld.py + +try: + import cccanvas +except: + import sys + sys.path.insert(0,"./../.libs/") + import cccanvas + +class Page: + + def __init__(self): + self.title = 'Empty Page' + + # Create CCCanvas item and widget with this item as root + self.cc_item = cccanvas.Item() + self.widget = cccanvas.view_widget_new_root(self.cc_item) + + # show the widget + self.widget.show() + + + + diff --git a/pool/shard006/Python/0058480_step_and_print.py b/pool/shard006/Python/0058480_step_and_print.py new file mode 100644 index 0000000000000000000000000000000000000000..41364ef97ba84c839b77b7d1a6b80d734915ea93 --- /dev/null +++ b/pool/shard006/Python/0058480_step_and_print.py @@ -0,0 +1,24 @@ +""" Does a step-over then prints the local variables or only the ones passed in """ +import lldb + +class StepAndPrint: + def __init__(self, debugger, unused): + return + + def __call__(self, debugger, command, exe_ctx, result): + # Set the command to synchronous so the step will complete + # before we try to run the frame variable. + old_async = debugger.GetAsync() + debugger.SetAsync(False) + + debugger.HandleCommand("thread step-over") + print("---------- Values: -------------------\n") + debugger.HandleCommand("frame variable %s"%(command)) + + debugger.SetAsync(old_async) + + def get_short_help(self): + return "Does a step-over then runs frame variable passing the command args to it\n" + +def __lldb_init_module(debugger, unused): + debugger.HandleCommand("command script add -c step_and_print.StepAndPrint sap") diff --git a/pool/shard006/Python/0058483_translation.summary.py b/pool/shard006/Python/0058483_translation.summary.py new file mode 100644 index 0000000000000000000000000000000000000000..a090fcd97d2ab01be2587b13abf8ad8c6af53165 --- /dev/null +++ b/pool/shard006/Python/0058483_translation.summary.py @@ -0,0 +1,39 @@ +def ignore(line): + return line.startswith("m4_include") or line.startswith("#") or line.startswith("l:") or line.startswith("h:") or not len(line) + + +def print_summary(summary): + for language, data in summary.items(): + with open(language.split()[1] + ".txt", "w", encoding='utf-8-sig') as outFile: + keyLen = max(map(len, data)) + valueLen = max(map(len, data.values())) + for item, str in data.items(): + print(item.ljust(keyLen), "|", str.ljust(valueLen), file = outFile) + + +def generate(): + with open(r"..\farlang.templ.m4", "r", encoding='utf-8-sig') as feedFile: + lines = [l.rstrip() for l in feedFile.readlines() if not ignore(l.rstrip())] + + count = int(lines[1]) + languages = lines[2 : 2 + count] + + summary = {} + + for i, line in enumerate(lines): + if line.startswith("upd:"): + labelIndex = i - 1 + while not lines[labelIndex].startswith("M"): + labelIndex = labelIndex - 1 + lngIndex = i - labelIndex - 1 + + if languages[lngIndex] not in summary.keys(): + summary[languages[lngIndex]] = {} + + summary[languages[lngIndex]][lines[labelIndex]] = lines[i][4 :] + + print_summary(summary) + + +if __name__=="__main__": + generate() diff --git a/pool/shard006/Python/0058488_least_squares_test.py b/pool/shard006/Python/0058488_least_squares_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2a9100903aae5689919a6b25fcb18ff192f250b3 --- /dev/null +++ b/pool/shard006/Python/0058488_least_squares_test.py @@ -0,0 +1,87 @@ +# 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. +# ============================================================================== + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np + +from tensorflow.contrib.solvers.python.ops import least_squares +from tensorflow.contrib.solvers.python.ops import util +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test as test_lib + + +def _add_test(test, test_name, fn): + test_name = "_".join(["test", test_name]) + if hasattr(test, test_name): + raise RuntimeError("Test %s defined more than once" % test_name) + setattr(test, test_name, fn) + + +class LeastSquaresTest(test_lib.TestCase): + pass # Filled in below. + + +def _get_least_squares_tests(dtype_, use_static_shape_, shape_): + + def test_cgls(self): + np.random.seed(1) + a_np = np.random.uniform( + low=-1.0, high=1.0, size=np.prod(shape_)).reshape(shape_).astype(dtype_) + rhs_np = np.random.uniform( + low=-1.0, high=1.0, size=shape_[0]).astype(dtype_) + tol = 1e-12 if dtype_ == np.float64 else 1e-6 + max_iter = 20 + with self.cached_session() as sess: + if use_static_shape_: + a = constant_op.constant(a_np) + rhs = constant_op.constant(rhs_np) + else: + a = array_ops.placeholder(dtype_) + rhs = array_ops.placeholder(dtype_) + operator = util.create_operator(a) + cgls_graph = least_squares.cgls(operator, rhs, tol=tol, max_iter=max_iter) + if use_static_shape_: + cgls_val = sess.run(cgls_graph) + else: + cgls_val = sess.run(cgls_graph, feed_dict={a: a_np, rhs: rhs_np}) + # Below we use s = A^* (rhs - A x), s0 = A^* rhs + norm_s0 = np.linalg.norm(np.dot(a_np.T, rhs_np)) + norm_s = np.sqrt(cgls_val.gamma) + self.assertLessEqual(norm_s, tol * norm_s0) + # Validate that we get an equally small residual norm with numpy + # using the computed solution. + r_np = rhs_np - np.dot(a_np, cgls_val.x) + norm_s_np = np.linalg.norm(np.dot(a_np.T, r_np)) + self.assertLessEqual(norm_s_np, tol * norm_s0) + + return [test_cgls] + + +if __name__ == "__main__": + for dtype in np.float32, np.float64: + for shape in [[4, 4], [8, 5], [3, 7]]: + for use_static_shape in True, False: + arg_string = "%s_%s_staticshape_%s" % (dtype.__name__, + "_".join(map(str, shape)), + use_static_shape) + for test_fn in _get_least_squares_tests(dtype, use_static_shape, shape): + name = "_".join(["LeastSquares", test_fn.__name__, arg_string]) + _add_test(LeastSquaresTest, name, test_fn) + + test_lib.main() diff --git a/pool/shard006/Python/0058491_models.py b/pool/shard006/Python/0058491_models.py new file mode 100644 index 0000000000000000000000000000000000000000..52d079e9218a85bc9c0f30faecd754805be5deb1 --- /dev/null +++ b/pool/shard006/Python/0058491_models.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +from django.db import models +from django.core.urlresolvers import reverse +from django.utils.text import slugify +from PIL import Image + +from futebolistica.settings import MEDIA_URL + + +class Team(models.Model): + name = models.CharField(max_length=200) + abbr = models.CharField(max_length=3) + flag = models.ImageField(upload_to='flags') + players = models.ManyToManyField('Player', through='TeamPlayer') + slug = models.SlugField(null=True, blank=True) + + def __unicode__(self): + return self.name + + def get_absolute_url(self): + return reverse('teams:detail', args=[self.slug, ]) + + def get_flag_url(self): + return u'{}{}'.format(MEDIA_URL, self.flag) + + def save(self, *args, **kwargs): + self.slug = slugify(self.name) + + image = Image.open(self.flag) + (width, height) = image.size + image = image.resize((25, 23), Image.ANTIALIAS) + super(Team, self).save(*args, **kwargs) + image.save(self.flag.path) + + +class Position(models.Model): + title = models.CharField(max_length=100) + + def __unicode__(self): + return self.title + + +class Player(models.Model): + name = models.CharField(max_length=200) + position = models.ForeignKey('Position') + + def __unicode__(self): + return self.name + + +class TeamPlayer(models.Model): + team = models.ForeignKey('Team') + shirt_number = models.PositiveSmallIntegerField() + player = models.ForeignKey('Player') + league = models.ForeignKey('leagues.League') + + class Meta: + ordering = ('league', 'team', 'player__name') + unique_together = ( + ('league', 'player'), + ('team', 'shirt_number', 'league'), + ) + + def __unicode__(self): + return u'{} - {} ({})'.format(self.player, self.team, self.league) diff --git a/pool/shard006/Python/0058492_test_editra.py b/pool/shard006/Python/0058492_test_editra.py new file mode 100644 index 0000000000000000000000000000000000000000..bb67339425065b86346101cd724fcfb6f8b51207 --- /dev/null +++ b/pool/shard006/Python/0058492_test_editra.py @@ -0,0 +1,70 @@ +# peppy Copyright (c) 2006-2008 Rob McMullen +# Licenced under the GPLv2; see http://peppy.flipturn.org for more info +""" + +""" + +import os, sys, re, copy +from cStringIO import StringIO + +from peppy.editra.facade import * + +from nose.tools import * + +class testEditraLanguages(object): + def setup(self): + self.facade = EditraFacade() + self.facade._extreg.LoadDefault() + + def testLangs(self): + langs = self.facade.getAllEditraLanguages() + + def testPython(self): + exts = self.facade.getExtensionsForLanguage("Python") + assert "py" in exts + assert "python" in exts + + def testXML(self): + exts = self.facade.getExtensionsForLanguage("XML") + assert "xml" in exts + assert "xul" in exts + + def testAddXMLExtension(self): + exts = self.facade.getExtensionsForLanguage("XML") + print(exts) + print(self.facade._extreg["XML"]) + self.facade.addExtensionForLanguage("XML", "abcxml") + exts = self.facade.getExtensionsForLanguage("XML") + print(exts) + print(self.facade._extreg["XML"]) + assert "xml" in exts + assert "xul" in exts + assert "abcxml" in exts + + def testPeppyKeywords(self): + mapping = { + "68k Assembly": "68k Assembly", + "Bash Shell Script": "Bash", + "C#": "C#", + "DOT": "Graphviz", + "Makefile": "Makefile", + "Objective C": "Objective C", + "Tcl/Tk": "Tcl/Tk", + } + for editra, peppy in mapping.iteritems(): + eq_(peppy, self.facade.getPeppyModeKeyword(editra)) + + def testPeppyFileNames(self): + mapping = { + "68k Assembly": "_68k_assembly", + "Bash Shell Script": "bash", + "C#": "csharp", + "DOT": "graphviz", + "Makefile": "makefile", + "Objective C": "objective_c", + "Tcl/Tk": "tcl_tk", + } + for editra, peppy in mapping.iteritems(): + eq_(peppy, self.facade.getPeppyFileName(editra)) + + diff --git a/pool/shard006/Python/0058493_turbomole_H2.py b/pool/shard006/Python/0058493_turbomole_H2.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb65e3c8bfc52c02e0a3a82a1d63c0dd536c6de --- /dev/null +++ b/pool/shard006/Python/0058493_turbomole_H2.py @@ -0,0 +1,28 @@ +import os +from subprocess import Popen, PIPE, STDOUT + +from ase import Atoms +from ase.calculators.turbomole import Turbomole + +# Delete old coord, control, ... files, if exist +for f in ['coord', + 'basis', + 'energy', + 'mos', + 'statistics', + 'control']: + if os.path.exists(f): + os.remove(f) + +atoms = Atoms('H2', positions=[(0, 0, 0), (0, 0, 1.1)]) +atoms.set_calculator(Turbomole()) # Writes a coord file as well + +# Write all commands for the define command in a string +define_str = '\n\na coord\n*\nno\nb all sto-3g hondo\n*\neht\n\n\n\n*' + +# Run define +p = Popen('define', stdout=PIPE, stdin=PIPE, stderr=STDOUT) +stdout = p.communicate(input=define_str) + +# Run turbomole +atoms.get_potential_energy() diff --git a/pool/shard006/Python/0058498_runAllTasks.py b/pool/shard006/Python/0058498_runAllTasks.py new file mode 100644 index 0000000000000000000000000000000000000000..c35f2af3a69cbab25fd89cb37376da0d68756ab5 --- /dev/null +++ b/pool/shard006/Python/0058498_runAllTasks.py @@ -0,0 +1,80 @@ +#!/usr/bin/python +# usage: +# change the following path variables +# (too long to consider them as input of the script) +# 1. pregelixPath: the path to the pregelix platform +# 2. graphPath: the path to the adm graph file +# 3. projectJarPath" the path to the project jar + +# The following variables need to be configured according to the graph +# sourceId: source ID for task 1 and sub graph display; +# numberResuls: number of results for task 3; +# numVertices: number of vertices in the graph for task 4 (self configuration); +# iterations: number of iterations to be run for task 2, 3 and sub graph display. + +import runTask +import bootstrap +import task4 +## change here for your path +pregelixPath = "/Users/liqiangw/Documents/workspace/twitter_graph/hyracks/pregelix/pregelix-dist/target/pregelix-dist-0.2.9-binary-assembly/" +# path to the graph +## change here for your path +graphPath = "/Volumes/TOSHIBA/BigGraphData/10k/adm/" +## change here for your path +projectJarPath = "/Users/liqiangw/Documents/workspace/Pregelix_Social_Graph/target/project-0.2.9-jar-with-dependencies.jar" +# path to spanning tree results +outputPath = "/tmp/pregelix/WeightedShortestPath/" +# get ip script +getIp = "`bin/getip.sh`" +# port number +portNo = 13199 +# source id +sourceId = 0 +# number results for task 3 +numberResults = 10 +# number of vertexes +numVertices = 20 +# iteration number +iterations = 10 +if __name__ == '__main__': + # establish database + bootstrap.bootstrap() + + # run task one + print "run task one..." + outputPath = "/tmp/pregelix/WeightedShortestPathVertex/" + sourceId = 1 + runTask.runTask("WeightedShortestPathVertex", pregelixPath, projectJarPath, \ + "edu.uci.ics.biggraph.algo.WeightedShortestPathVertex", graphPath, \ + outputPath, getIp, portNo, sourceId, numberResults, numVertices, iterations) + + # run task two + print "run task two..." + outputPath = "/tmp/pregelix/CommunityClusterVertex/" + iterations = 10 + runTask.runTask("CommunityClusterVertex", pregelixPath, projectJarPath, \ + "edu.uci.ics.biggraph.algo.CommunityClusterVertex", graphPath, \ + outputPath, getIp, portNo, sourceId, numberResults, numVertices, iterations) + + # run task three + print "run task three..." + outputPath = "/tmp/pregelix/SocialSuggestionVertex/" + iterations = 10 + numberResults = 10 + runTask.runTask("SocialSuggestionVertex", pregelixPath, projectJarPath, \ + "edu.uci.ics.biggraph.algo.SocialSuggestionVertex", graphPath, \ + outputPath, getIp, portNo, sourceId, numberResults, numVertices, iterations) + + # run task four + print "run task four..." + task4.task4(pregelixPath, graphPath, projectJarPath) + + # run display graph + print "run display graph task..." + outputPath = "/tmp/pregelix/SubGraphVertex/" + iterations = 10 + sourceId = 1 + runTask.runTask("SubGraphVertex", pregelixPath, projectJarPath, \ + "edu.uci.ics.biggraph.algo.SubGraphVertex", graphPath, \ + outputPath, getIp, portNo, sourceId, numberResults, numVertices, iterations) + diff --git a/pool/shard006/Python/0058499_DataIntegrityHandler.py b/pool/shard006/Python/0058499_DataIntegrityHandler.py new file mode 100644 index 0000000000000000000000000000000000000000..4b19f2713f4a7d0112b8314c140d2708ff5a2c44 --- /dev/null +++ b/pool/shard006/Python/0058499_DataIntegrityHandler.py @@ -0,0 +1,164 @@ +######################################################################## +# $HeadURL $ +# File: DataIntegrityHandler.py +######################################################################## +""" +:mod: DataIntegrityHandler + + +.. module: DataIntegrityHandler + + :synopsis: DataIntegrityHandler is the implementation of the Data Integrity service in + the DISET framework + +""" + +__RCSID__ = "$Id$" + +## imports +from types import DictType, IntType, LongType, ListType, StringType +## from DIRAC +from DIRAC.Core.DISET.RequestHandler import RequestHandler +from DIRAC import gLogger, S_OK +from DIRAC.DataManagementSystem.DB.DataIntegrityDB import DataIntegrityDB + +# This is a global instance of the DataIntegrityDB class +gDataIntegrityDB = False + +def initializeDataIntegrityHandler( serviceInfo ): + """ Check that we can connect to the DB and that the tables are properly created or updated + """ + global gDataIntegrityDB + gDataIntegrityDB = DataIntegrityDB( checkTables = True ) + res = gDataIntegrityDB._connect() + if not res['OK']: + return res + + return S_OK() + +class DataIntegrityHandler( RequestHandler ): + """ + .. class:: DataIntegrityHandler + + Implementation of the Data Integrity service in the DISET framework. + """ + + types_removeProblematic = [ [IntType, LongType, ListType] ] + @staticmethod + def export_removeProblematic( fileID ): + """ Remove the file with the supplied FileID from the database + """ + if type( fileID ) == ListType: + fileIDs = fileID + else: + fileIDs = [int( fileID )] + gLogger.info( "DataIntegrityHandler.removeProblematic: Attempting to remove problematic." ) + res = gDataIntegrityDB.removeProblematic( fileIDs ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.removeProblematic: Failed to remove problematic.", res['Message'] ) + return res + + types_getProblematic = [] + @staticmethod + def export_getProblematic(): + """ Get the next problematic to resolve from the IntegrityDB + """ + gLogger.info( "DataIntegrityHandler.getProblematic: Getting file to resolve." ) + res = gDataIntegrityDB.getProblematic() + if not res['OK']: + gLogger.error( "DataIntegrityHandler.getProblematic: Failed to get problematic file to resolve.", res['Message'] ) + return res + + types_getPrognosisProblematics = [StringType] + @staticmethod + def export_getPrognosisProblematics( prognosis ): + """ Get problematic files from the problematics table of the IntegrityDB + """ + gLogger.info( "DataIntegrityHandler.getPrognosisProblematics: Getting files with %s prognosis." % prognosis ) + res = gDataIntegrityDB.getPrognosisProblematics( prognosis ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.getPrognosisProblematics: Failed to get prognosis files.", res['Message'] ) + return res + + types_setProblematicStatus = [[IntType, LongType], StringType] + @staticmethod + def export_setProblematicStatus( fileID, status ): + """ Update the status of the problematics with the provided fileID + """ + gLogger.info( "DataIntegrityHandler.setProblematicStatus: Setting file %s status to %s." % ( fileID, status ) ) + res = gDataIntegrityDB.setProblematicStatus( fileID, status ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.setProblematicStatus: Failed to set status.", res['Message'] ) + return res + + types_incrementProblematicRetry = [[IntType, LongType]] + @staticmethod + def export_incrementProblematicRetry( fileID ): + """ Update the retry count for supplied file ID. + """ + gLogger.info( "DataIntegrityHandler.incrementProblematicRetry: Incrementing retries for file %s." % ( fileID ) ) + res = gDataIntegrityDB.incrementProblematicRetry( fileID ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.incrementProblematicRetry: Failed to increment retries.", res['Message'] ) + return res + + types_insertProblematic = [StringType, DictType] + @staticmethod + def export_insertProblematic( source, fileMetadata ): + """ Insert problematic files into the problematics table of the IntegrityDB + """ + gLogger.info( "DataIntegrityHandler.insertProblematic: Inserting problematic file to integrity DB." ) + res = gDataIntegrityDB.insertProblematic( source, fileMetadata ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.insertProblematic: Failed to insert.", res['Message'] ) + return res + + types_changeProblematicPrognosis = [] + @staticmethod + def export_changeProblematicPrognosis( fileID, newPrognosis ): + """ Change the prognosis for the supplied file """ + gLogger.info( "DataIntegrityHandler.changeProblematicPrognosis: Changing problematic prognosis." ) + res = gDataIntegrityDB.changeProblematicPrognosis( fileID, newPrognosis ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.changeProblematicPrognosis: Failed to update.", res['Message'] ) + return res + + types_getTransformationProblematics = [ [IntType, LongType] ] + @staticmethod + def export_getTransformationProblematics( transID ): + """ Get the problematics for a given transformation """ + gLogger.info( "DataIntegrityHandler.getTransformationProblematics: Getting problematics for transformation." ) + res = gDataIntegrityDB.getTransformationProblematics( transID ) + if not res['OK']: + gLogger.error( "DataIntegrityHandler.getTransformationProblematics: Failed.", res['Message'] ) + return res + + types_getProblematicsSummary = [] + @staticmethod + def export_getProblematicsSummary(): + """ Get a summary from the Problematics table from the IntegrityDB + """ + gLogger.info( "DataIntegrityHandler.getProblematicsSummary: Getting problematics summary." ) + res = gDataIntegrityDB.getProblematicsSummary() + if res['OK']: + for prognosis, statusDict in res['Value'].items(): + gLogger.info( "DataIntegrityHandler.getProblematicsSummary: %s." % prognosis ) + for status, count in statusDict.items(): + gLogger.info( "DataIntegrityHandler.getProblematicsSummary: \t%-10s %-10s." % ( status, str( count ) ) ) + else: + gLogger.error( "DataIntegrityHandler.getProblematicsSummary: Failed to get summary.", res['Message'] ) + return res + + types_getDistinctPrognosis = [] + @staticmethod + def export_getDistinctPrognosis(): + """ Get a list of the distinct prognosis from the IntegrityDB + """ + gLogger.info( "DataIntegrityHandler.getDistinctPrognosis: Getting distinct prognosis." ) + res = gDataIntegrityDB.getDistinctPrognosis() + if res['OK']: + for prognosis in res['Value']: + gLogger.info( "DataIntegrityHandler.getDistinctPrognosis: \t%s." % prognosis ) + else: + gLogger.error( "DataIntegrityHandler.getDistinctPrognosis: Failed to get unique prognosis.", res['Message'] ) + return res diff --git a/pool/shard006/Python/0058502_test_connection.py b/pool/shard006/Python/0058502_test_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..5c5be7ea7afab568d03745f89ee88b20c59b7a3b --- /dev/null +++ b/pool/shard006/Python/0058502_test_connection.py @@ -0,0 +1,107 @@ +import unittest +import vdebug.connection + +class SocketMockError(): + pass + +class SocketMock(): + def __init__(self): + self.response = [] + self.last_msg = [] + + def recv(self,length): + ret = self.response[0] + if len(ret) >= length: + chars = ret[0:length] + newval = ret[length:] + if len(newval) > 0: + self.response[0] = newval + else: + self.response.pop(0) + if (length == 1): + return b"".join(chars) + else : + return b''.join(chars) + #if type(chars[0]) is int: + # print("len same as length") + # print(ret[0:length]) + # return b''.join([bytes(i) for i in chars]) + # return b"".join(chars) + #else: + # return b"".join(chars) + else: + self.response.pop(0) + return b'' + + def add_response(self,res): + digitlist = [] + for i in str(res): + digitlist.append(bytes(i, "utf8")) + self.response.append(digitlist) + + #res = bytes(res, 'utf8') + #self.response.append(list(res)) + self.response.append([b'\x00']) + + def send(self,msg): + self.last_msg.append( msg ) + return len(msg) + + def get_last_sent(self): + last = self.last_msg + self.last_msg = []; + return b''.join(last).decode('UTF-8') + + def close(self): + pass + + +class ConnectionTest(unittest.TestCase): + + def setUp(self): + self.conn = vdebug.connection.ConnectionHandler('', 0) + self.conn.sock = SocketMock() + + """ + Test that the recv_msg method reads from the socket object. + + The socket's recv() method is called for three purposes + 1. Message length + 2. Message body + 3. A finishing null byte + """ + def test_read(self): + self.conn.sock.add_response(3) + self.conn.sock.add_response('foo') + self.conn.sock.add_response('\0') + + response = self.conn.recv_msg() + assert response == 'foo' + + """ + Test a longer read. + """ + def test_read_long(self): + self.conn.sock.add_response(24) + self.conn.sock.add_response('this is a longer message') + self.conn.sock.add_response('\0') + + response = self.conn.recv_msg() + assert response == 'this is a longer message' + + """ + Test that an EOFError is raised if the socket appears to be closed. + """ + def test_read_eof(self): + self.conn.sock.add_response('') + self.assertRaises(EOFError,self.conn.recv_msg) + + """ + Test that the send_msg command calls send on the socket, + and adds a null byte to the string. + """ + def test_send(self): + cmd = 'this is a cmd' + self.conn.send_msg(cmd) + sent = self.conn.sock.get_last_sent() + assert sent == cmd+'\0' diff --git a/pool/shard006/Python/0058503_setup.py b/pool/shard006/Python/0058503_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..dac6a3ea3b8b03090dc2341172f23352dc0f74ee --- /dev/null +++ b/pool/shard006/Python/0058503_setup.py @@ -0,0 +1,32 @@ +import setuptools + +from os import path + +this_directory = path.abspath(path.dirname(__file__)) +with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: + long_description = f.read() + +setuptools.setup( + name="wolk-connect", + version="3.3.0", + install_requires=["paho_mqtt==1.4.0", "python-persistent-queue==1.3.0"], + include_package_data=True, + license="Apache License 2.0", + author="WolkAbout", + author_email="info@wolkabout.com", + description="Python 3 library for connecting to WolkAbout IoT Platform", + long_description=long_description, + long_description_content_type="text/markdown", + keywords=["IoT", "WolkAbout", "Internet of Things"], + url="https://github.com/Wolkabout/WolkConnect-Python", + packages=setuptools.find_packages(), + classifiers=( + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Natural Language :: English", + "Programming Language :: Python :: 3 :: Only", + "Operating System :: OS Independent", + "Topic :: Internet", + ), +) diff --git a/pool/shard006/Python/0058506_util.py b/pool/shard006/Python/0058506_util.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3b9d212989f3f99b93851d61b71dde98fda266 --- /dev/null +++ b/pool/shard006/Python/0058506_util.py @@ -0,0 +1,191 @@ +import argparse +from configparser import ConfigParser +from datetime import datetime +from itertools import chain +from pathlib import Path +import re + +from attr import attrib, attrs + +import firefed.__version__ as version + + +PROFILES_INI_PATHS = [ + '~/.mozilla/firefox', + '~/Library/Application Support/Firefox', + '~/Library/Mozilla/Firefox', + '~/Library/Application Support/Firefox/Profiles', + '~/Library/Mozilla/Firefox/Profiles', +] +PROFILES_INI = 'profiles.ini' + + +@attrs +class Profile: + name = attrib() + path = attrib() + default = attrib(default=False, converter=lambda x: bool(int(x))) + + +class ProfileNotFoundError(Exception): + + def __init__(self, name): + if name is None: + text = 'No default profile found. Use -p/--profile to specify one.' + else: + text = 'Profile "%s" not found.' % name + super().__init__(text) + + +class FatalError(Exception): + """Raised when an unrecoverable error in a feature occurs.""" + pass + + +def fatal(text): + raise FatalError(text) + + +def mozilla_dir(): + for root in PROFILES_INI_PATHS: + path = Path(root).expanduser() + if (path / PROFILES_INI).exists(): + return path + raise FatalError('Couldn\'t find profiles.ini to read local profiles.') + + +def read_profiles(): + root = mozilla_dir() + config = ConfigParser() + config.read(str(root / PROFILES_INI)) + for section, profile in config.items(): + if not section.startswith('Profile'): + continue + path = Path(profile.get('Path')) + if int(profile['IsRelative']): + path = Path(root / path) + yield Profile(profile.get('Name'), path, profile.get('Default', 0)) + + +def profile_dir(name): + """Return path to FF profile for a given profile name or path.""" + if name: + possible_path = Path(name) + if possible_path.exists(): + return possible_path + profiles = list(read_profiles()) + try: + if name: + profile = next(p for p in profiles if p.name == name) + else: + profile = next(p for p in profiles if p.default) + except StopIteration: + raise ProfileNotFoundError(name) + return profile.path + + +def moz_datetime(ts): + """Convert Mozilla timestamp to datetime.""" + return datetime.fromtimestamp(moz_to_unix_timestamp(ts)) + + +def moz_to_unix_timestamp(ts): + """Convert Mozilla timestamp to Unix timestamp.""" + try: + return ts // 1000000 + except TypeError: + return 0 + + +def make_parser(): + from firefed.feature import Feature + parser = argparse.ArgumentParser( + 'firefed', + description=version.__description__, + ) + parser.add_argument( + '-V', + '--version', + action='version', + version='%(prog)s v' + version.__version__, + ) + parser.add_argument( + '-P', + '--profiles', + help='show all local profiles', + action='store_true', + dest='show_profiles', + ) + parser.add_argument( + '-p', + '--profile', + help='profile name or directory to be used when running a feature', + ) + parser.add_argument( + '-v', + '--verbose', + help='verbose output (can be used multiple times)', + action='count', + dest='verbosity', + default=0, + ) + parser.add_argument( + '-f', + '--force', + help='treat target as a profile directory even if it doesn\'t' + ' look like one', + action='store_true', + default=False, + ) + subparsers = parser.add_subparsers( + title='features', + metavar='FEATURE', + description='Set the feature you want to run as positional argument. ' + 'Each feature has its own sub arguments which can be listed with ' + '`firefed -h`.', + dest='feature', + ) + for name, feature in Feature.feature_map().items(): + feature_parser = subparsers.add_parser(name, + help=feature.description()) + for args, kwargs in feature.cli_args(): + feature_parser.add_argument(*args, **kwargs) + return parser + + +@attrs +class Tabulate: + + rows = attrib(converter=list) + headers = attrib() + maximums = attrib(init=False) + + def __attrs_post_init__(self): + maxs = [0] * len(self.rows[0]) + for row in chain([self.headers], self.rows): + for i, column in enumerate(row): + maxs[i] = max(maxs[i], len(self.strip_invisible(column))) + self.maximums = maxs + + def __call__(self): + self.print_row(self.headers) + self.print_row([''] * len(self.maximums), ch='-') + for row in self.rows: + self.print_row(row) + + def pad(self, s, num, ch): + missing = num - len(self.strip_invisible(s)) + return s + missing * ch + + def print_row(self, row, ch=' '): + print(' '.join([self.pad(c, self.maximums[i], ch) for i, c in + enumerate(row)])) + + @staticmethod + def strip_invisible(s): + invisibles = re.compile(r'\x1b\[\d*m') + return re.sub(invisibles, '', s) + + +def tabulate(*args, **kwargs): + Tabulate(*args, **kwargs)() diff --git a/pool/shard006/Python/0058508_source_remote.py b/pool/shard006/Python/0058508_source_remote.py new file mode 100644 index 0000000000000000000000000000000000000000..4afae41bc9a672c2c991f8fd2c3e1e6eecac193f --- /dev/null +++ b/pool/shard006/Python/0058508_source_remote.py @@ -0,0 +1,226 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Communicating tracebacks and source code with debug server.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import socket + +import grpc + +from tensorflow.core.debug import debug_service_pb2 +from tensorflow.core.protobuf import debug_pb2 +from tensorflow.python.debug.lib import common +from tensorflow.python.debug.lib import debug_service_pb2_grpc +from tensorflow.python.debug.lib import source_utils +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging +from tensorflow.python.profiler import tfprof_logger + + +def _load_debugged_source_file(file_path, source_file_proto): + file_stat = gfile.Stat(file_path) + source_file_proto.host = socket.gethostname() + source_file_proto.file_path = file_path + source_file_proto.last_modified = file_stat.mtime_nsec + source_file_proto.bytes = file_stat.length + try: + with gfile.Open(file_path, "r") as f: + source_file_proto.lines.extend(f.read().splitlines()) + except IOError: + pass + + +def _string_to_id(string, string_to_id): + if string not in string_to_id: + string_to_id[string] = len(string_to_id) + return string_to_id[string] + + +def _format_origin_stack(origin_stack, call_traceback_proto): + """Format a traceback stack for a `CallTraceback` proto. + + Args: + origin_stack: The stack list as returned by `traceback.extract_stack()`. + call_traceback_proto: A `CallTraceback` proto whose fields are to be + populated. + """ + string_to_id = dict() + string_to_id[None] = 0 + for frame in origin_stack: + file_path, lineno, func_name, line_text = frame + call_traceback_proto.origin_stack.traces.add( + file_id=_string_to_id(file_path, string_to_id), + lineno=lineno, + function_id=_string_to_id(func_name, string_to_id), + line_id=_string_to_id(line_text, string_to_id)) + + id_to_string = call_traceback_proto.origin_id_to_string + for key, value in string_to_id.items(): + id_to_string[value] = key if key is not None else "" + + +def _source_file_paths_outside_tensorflow_py_library(code_defs, id_to_string): + """Extract source file paths outside TensorFlow Python library. + + Args: + code_defs: An iterable of `CodeDef` protos, i.e., an iterable of stack + traces. + id_to_string: A proto map from integer ids to strings. + + Returns: + An iterable of source file paths outside the TensorFlow Python library. + """ + file_ids = set() + for code_def in code_defs: + for trace in code_def.traces: + file_ids.add(trace.file_id) + non_tf_files = (id_to_string[file_id] for file_id in file_ids) + non_tf_files = ( + f for f in non_tf_files + if not source_utils.guess_is_tensorflow_py_library(f) and gfile.Exists(f)) + return non_tf_files + + +def grpc_message_length_bytes(): + """Maximum gRPC message length in bytes.""" + return 4 * 1024 * 1024 + + +def _send_call_tracebacks(destinations, + origin_stack, + is_eager_execution=False, + call_key=None, + graph=None, + send_source=True): + """Send the tracebacks of a TensorFlow execution call. + + To gRPC debug server(s). This applies to graph execution (`tf.Session.run()`) + calls and eager execution calls. + + If `send_source`, also sends the underlying source files outside the + TensorFlow library. + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + `CallTraceback` proto payload will be sent to all the destinations. + origin_stack: The traceback stack for the origin of the execution call. For + graph execution, this is the traceback of the `tf.Session.run()` + invocation. For eager execution, this is the traceback of the Python + line that executes the eager opertion. + is_eager_execution: (`bool`) whether an eager execution call (i.e., not a + `tf.Session.run` or derived methods) is being sent. + call_key: The key of the execution call, as a string. For graph execution, + this is a string describing the feeds, fetches (and targets) names of the + `tf.Session.run` call. For eager execution, this is ignored. + graph: A Python `tf.Graph` object (i.e., *not* a `tf.GraphDef`), which + contains op tracebacks, if applicable. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + if not isinstance(destinations, list): + destinations = [destinations] + # Strip grpc:// prefix, if any is present. + destinations = [ + dest[len(common.GRPC_URL_PREFIX):] + if dest.startswith(common.GRPC_URL_PREFIX) else dest + for dest in destinations] + + call_type = (debug_service_pb2.CallTraceback.EAGER_EXECUTION + if is_eager_execution + else debug_service_pb2.CallTraceback.GRAPH_EXECUTION) + graph_traceback = tfprof_logger.merge_default_with_oplog( + graph, add_trainable_var=False) if graph else None + call_traceback = debug_service_pb2.CallTraceback( + call_type=call_type, call_key=call_key, graph_traceback=graph_traceback, + graph_version=graph.version if graph else None) + + _format_origin_stack(origin_stack, call_traceback) + + if send_source: + source_file_paths = set() + source_file_paths.update(_source_file_paths_outside_tensorflow_py_library( + (log_entry.code_def for log_entry + in call_traceback.graph_traceback.log_entries), + call_traceback.graph_traceback.id_to_string)) + source_file_paths.update(_source_file_paths_outside_tensorflow_py_library( + [call_traceback.origin_stack], call_traceback.origin_id_to_string)) + + debugged_source_files = [] + for file_path in source_file_paths: + source_files = debug_pb2.DebuggedSourceFiles() + _load_debugged_source_file( + file_path, source_files.source_files.add()) + debugged_source_files.append(source_files) + + for destination in destinations: + channel = grpc.insecure_channel(destination) + stub = debug_service_pb2_grpc.EventListenerStub(channel) + stub.SendTracebacks(call_traceback) + if send_source: + for path, source_files in zip( + source_file_paths, debugged_source_files): + if source_files.ByteSize() < grpc_message_length_bytes(): + stub.SendSourceFiles(source_files) + else: + tf_logging.warn( + "The content of the source file at %s is not sent to " + "gRPC debug server %s, because the message size exceeds " + "gRPC message length limit (%d bytes)." % ( + path, destination, grpc_message_length_bytes())) + + +def send_graph_tracebacks(destinations, + run_key, + origin_stack, + graph, + send_source=True): + """Send the tracebacks of a graph execution call to debug server(s). + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + `CallTraceback` proto payload will be sent to all the destinations. + run_key: A string describing the feeds, fetches (and targets) names of the + `tf.Session.run` call. + origin_stack: The traceback of the `tf.Session.run()` invocation. + graph: A Python `tf.Graph` object (i.e., *not* a `tf.GraphDef`), which + contains op tracebacks. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + _send_call_tracebacks( + destinations, origin_stack, is_eager_execution=False, call_key=run_key, + graph=graph, send_source=send_source) + + +def send_eager_tracebacks(destinations, + origin_stack, + send_source=True): + """Send the tracebacks of an eager execution call to debug server(s). + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + origin_stack: The traceback of the eager operation invocation. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + _send_call_tracebacks( + destinations, origin_stack, is_eager_execution=True, + send_source=send_source) diff --git a/pool/shard006/Python/0058512_update_plugins.py b/pool/shard006/Python/0058512_update_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..0cfb7908197e330214cd67f31a5125b1f7a11bd3 --- /dev/null +++ b/pool/shard006/Python/0058512_update_plugins.py @@ -0,0 +1,112 @@ +#!/usr/bin/python + +try: + import concurrent.futures as futures +except ImportError: + try: + import futures + except ImportError: + futures = None + +import zipfile +import shutil +import tempfile +import requests + +from os import path + + +#--- Globals ---------------------------------------------- +PLUGINS = """ +ack.vim https://github.com/mileszs/ack.vim +ag.vim https://github.com/rking/ag.vim +bufexplorer https://github.com/corntrace/bufexplorer +ctrlp.vim https://github.com/ctrlpvim/ctrlp.vim +mayansmoke https://github.com/vim-scripts/mayansmoke +nerdtree https://github.com/scrooloose/nerdtree +nginx-vim-syntax https://github.com/evanmiller/nginx-vim-syntax +open_file_under_cursor.vim https://github.com/amix/open_file_under_cursor.vim +snipmate-snippets https://github.com/scrooloose/snipmate-snippets +tlib https://github.com/vim-scripts/tlib +vim-addon-mw-utils https://github.com/MarcWeber/vim-addon-mw-utils +vim-bundle-mako https://github.com/sophacles/vim-bundle-mako +vim-coffee-script https://github.com/kchmck/vim-coffee-script +vim-colors-solarized https://github.com/altercation/vim-colors-solarized +vim-indent-object https://github.com/michaeljsmith/vim-indent-object +vim-less https://github.com/groenewege/vim-less +vim-markdown https://github.com/plasticboy/vim-markdown +vim-pyte https://github.com/therubymug/vim-pyte +vim-snipmate https://github.com/garbas/vim-snipmate +vim-snippets https://github.com/honza/vim-snippets +vim-surround https://github.com/tpope/vim-surround +vim-expand-region https://github.com/terryma/vim-expand-region +vim-multiple-cursors https://github.com/terryma/vim-multiple-cursors +vim-fugitive https://github.com/tpope/vim-fugitive +goyo.vim https://github.com/junegunn/goyo.vim +vim-zenroom2 https://github.com/amix/vim-zenroom2 +syntastic https://github.com/scrooloose/syntastic +vim-repeat https://github.com/tpope/vim-repeat +vim-commentary https://github.com/tpope/vim-commentary +vim-go https://github.com/fatih/vim-go +vim-gitgutter https://github.com/airblade/vim-gitgutter +gruvbox https://github.com/morhetz/gruvbox +vim-flake8 https://github.com/nvie/vim-flake8 +vim-pug https://github.com/digitaltoad/vim-pug +vim-yankstack https://github.com/maxbrunsfeld/vim-yankstack +lightline.vim https://github.com/itchyny/lightline.vim +papercolor-theme https://github.com/nlknguyen/papercolor-theme +vim-airline https://github.com/bling/vim-airline +vim-marked https://github.com/itspriddle/vim-marked +lexima.vim https://github.com/cohama/lexima.vim +vim-terraform https://github.com/hashivim/vim-terraform +""".strip() + +GITHUB_ZIP = '%s/archive/master.zip' + +SOURCE_DIR = path.join(path.dirname(__file__), 'sources_non_forked') + + +def download_extract_replace(plugin_name, zip_path, temp_dir, source_dir): + temp_zip_path = path.join(temp_dir, plugin_name) + + # Download and extract file in temp dir + req = requests.get(zip_path) + open(temp_zip_path, 'wb').write(req.content) + + zip_f = zipfile.ZipFile(temp_zip_path) + zip_f.extractall(temp_dir) + + plugin_temp_path = path.join(temp_dir, + path.join(temp_dir, '%s-master' % plugin_name)) + + # Remove the current plugin and replace it with the extracted + plugin_dest_path = path.join(source_dir, plugin_name) + + try: + shutil.rmtree(plugin_dest_path) + except OSError: + pass + + shutil.move(plugin_temp_path, plugin_dest_path) + + print('Updated {0}'.format(plugin_name)) + + +def update(plugin): + name, github_url = plugin.split(' ') + zip_path = GITHUB_ZIP % github_url + download_extract_replace(name, zip_path, + temp_directory, SOURCE_DIR) + + +if __name__ == '__main__': + temp_directory = tempfile.mkdtemp() + + try: + if futures: + with futures.ThreadPoolExecutor(16) as executor: + executor.map(update, PLUGINS.splitlines()) + else: + [update(x) for x in PLUGINS.splitlines()] + finally: + shutil.rmtree(temp_directory) diff --git a/pool/shard006/Python/0058514_error_handlers.py b/pool/shard006/Python/0058514_error_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..e4e8d29edfeae10c495334e9a8b4bd6cfc83dac4 --- /dev/null +++ b/pool/shard006/Python/0058514_error_handlers.py @@ -0,0 +1,40 @@ +import app_config + +# HTTP errors will only be called when app_config.debug is True. + +context = { + "appname": app_config.app.get("name") +} + +# bad request +def HTTP_400(request, response, exception): + response.out.write("400") + response.set_status(400) + +# unauthorized +def HTTP_401(request, response, exception): + response.out.write("401 Unauthorized") + response.set_status(401) + +# forbidden +def HTTP_403(request, response, exception): + response.out.write("403 Forbidden") + response.set_status(403) + +# not found +def HTTP_404(request, response, exception): + response.out.write("404 Not Found") + response.set_status(404) + +# not allowed +def HTTP_405(request, response, exception): + response.out.write("405 Not Allowed") + response.set_status(405) + + +# internal server error +def HTTP_500(request, response, exception): + response.out.write("500 Internal Server Error") + response.set_status(500) + + \ No newline at end of file diff --git a/pool/shard006/Python/0058519_vaaliraapija_spider.py b/pool/shard006/Python/0058519_vaaliraapija_spider.py new file mode 100644 index 0000000000000000000000000000000000000000..190fd7dfc8cc558a4c1bdb4427f6add53bc03d31 --- /dev/null +++ b/pool/shard006/Python/0058519_vaaliraapija_spider.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# VaaliRaapija - Yksinkertainen web scraper Vaalivalvontaviraston sivujen +# raapimiseen +# Tekijänoikeus (C) 2011 Joona Lehtomäki +# +# Tämä on vapaa ohjelma: tätä ohjelmaa saa levittää edelleen ja muuttaa Free +# Software Foundationin julkaiseman GNU General Public Licensen (GPL-lisenssi) +# version 3 tai (valinnan mukaan) myöhemmän version ehtojen mukaisesti +# +# Tätä ohjelmaa levitetään siinä toivossa, että se olisi hyödyllinen mutta +# ILMAN MITÄÄN TAKUUTA; edes hiljaista takuuta KAUPALLISESTI HYVÄKSYTTÄVÄSTÄ +# LAADUSTA tai SOVELTUVUUDESTA TIETTYYN TARKOITUKSEEN. Katso GPL-lisenssistä +# lisää yksityiskohtia. +# +# Tämän ohjelman mukana pitäisi tulla kopio GPL-lisenssistä. Jos näin ei ole, +# katso . + +import re + +from scrapy.contrib.spiders import CrawlSpider, Rule +from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor +from scrapy.selector import HtmlXPathSelector +from vaaliraapija.items import VaalirahoitusItem +from vaaliraapija.resources import vaalipiirit, puolueet + +class VaaliraapijaSpider(CrawlSpider): + name = "vaalirahoitusvalvonta.fi" + allowed_domains = ["vaalirahoitusvalvonta.fi"] + start_urls = [ + "http://www.vaalirahoitusvalvonta.fi/fi/index/vaalirahailmoituksia/ilmoituslistaus/EV2011.html" + ] + + rules = ( + # Sallitaan ehdokaslinkit, mukana vain suomenkieliset sivut + Rule(SgmlLinkExtractor(allow='^(http://www\.vaalirahoitusvalvonta\.fi/fi)\S+(/EV2011/[0-9]{2})\.html'), + follow=True), + # Ehdokaslinkit parsitaan metodilla parse_ehdokas + Rule(SgmlLinkExtractor(allow='^(http://)\S+(E_EI_EV2011\.html)'), + callback='parse_ehdokas', follow=False), + ) + + def parse_ehdokas(self, response): + self.log('Prosessoidaan ehdokasta: %s' % response.url) + + # Ehdokkaan ennakkoilmoitussivulta parsitaan 2 ensimmäistä kohtaa. + # HTML:ssä kohdat erottuvat DIV-määreen "ann_form_table_basic" + # perusteella. response-oliosta tehdyn valintalistan (1. valinta) + # alkiot ovat seuraavat: + # [0] A = Ilmoittajan tiedot + # [1] B = Vaalikamppanjan kulujen ja rahoituksen yhteenveto + # TODO: parsi loputkin alkiot -> mukana tarkempaa tietoa rahoituksen + # yksityiskohdista + + hxs = HtmlXPathSelector(response) + # 1. valinta + data = hxs.select('//div[@class="ann_form_table_basic"]') + item = VaalirahoitusItem() + + ## KOHTA A: Ilmoittajan tiedot ######################################### + + # Ilmoittajan tiedot, valinnassa parsittavat tiedot löytyvät seuraavista + # listan alkioista: + # [0] = Sukunimi, etunimi + # [1] = Ammatti + # [2] = Puolue + # [3] = Kotipaikka + info = data[0].select('.//tr//td/text()').extract() + # Sukunimi ja etunimi on erotettu pilkulla, erottele nimet + names = info[0].split(',') + # Poistetaan välilyönnit nimistä + names = [name.strip() for name in names] + + item['sukunimi'] = names[0] + item['etunimi'] = names[1] + item['ammatti'] = info[1].strip() + puolue = info[2].strip() + item['puolue'] = puolue + try: + item['puolue_lyh'] = puolueet[puolue] + except KeyError: + item['puolue_lyh'] = u'' + item['kunta'] = info[3].strip() + + # Vaalipiiriä ei ole ilmoitettu sellaisenaan sivulla, joten irroitetaan + # vaalipiirin numero sivun urlista ja haetaan vastaavaa vaalipiirin nimi + district_id = response.url.split('/')[-3] + item['vaalipiiri'] = vaalipiirit[district_id] + + ## KOHTA B: Vaalikampanjan kulujen ja rahoituksen yhteenveto ########### + + # Ehdokkaan ilmoitussivulla olevat euromäärät ovat kahdessa + # DIV-luokassa: + # kulut yhteensä & rahoitus yhteensä -> div="cell_light_blue number" + # [0] = Vaalikampanjan kulut yhteensä + # [1] = Vaalikampanjan rahoitus yhteensä + # loput erittelyt 8 kpl -> div="number" + # [0] = Rahoitus sisältää omia varoja yhteensä + # [1] = Rahoitus sisältää ehdokkaan ja tukiryhmän ottamia lainoja yhteensä + # [2] = Rahoitus sisältää yksityishenkilöiltä saatua tukea yhteensä + # [3] = Rahoitus sisältää yrityksiltä saatua tukea yhteensä + # [4] = Rahoitus sisältää puolueelta saatua tukea yhteensä + # [5] = Rahoitus sisältää puolueyhdistyksiltä saatua tukea yhteensä + # [6] = Rahoitus sisältää muilta tahoilta saatua tukea yhteensä + # [7] = Rahoitus sisältää välitettyä tukea yhteensä + + yhteensa_euroja = data[1].select('.//td[@class="cell_light_blue number"]').extract() + erittely_euroja = data[1].select('.//td[@class="number"]').extract() + + ## KOHTA C: Vaalikampanjan kulujen erittely ############################ + # Euromäärien irroittaminen samalla tavalla kuin kohdassa B + # kulut yhteensä -> div="cell_light_blue number" + # [0] = Vaalikampanjan kulut yhteensä + # HUOM: tätä ei tarvita, koska pitäisi olla sama kuin edellisestä + # saatava "vaalikampanjan kulut yhteensä" + # loput erittelyt 8 kpl -> div="number" + # [0] = Sanoma, ilmaisjakelu- ja aikakauslehdet + # [1] = Radio + # [2] = Televisio + # [3] = Tietoverkot + # [4] = Muut viestintävälineet + # [5] = Ulkomainonta + # [6] = Vaalilehtien, esitteiden ja muun painetun materiaalin hankinta + # Vaalimainonta = [0:6] + # [7] = Mainonnan suunnittelu + # [8] = Vaalitilaisuudet + # [9] = Vastikkeellisen tuen hankintakulut + # [10] = Muut kulut + + # Ei tarvita + #kulut_yhteensa_euroja = data[2].select('.//td[@class="cell_light_blue number"]').extract() + kulut_erittely_euroja = data[2].select('.//td[@class="number"]').extract() + + def set_item(item, attr, luku): + ''' Apufunktio, jolla asetetaan VaalirahoituItemin attribuutit + oikein. + ''' + + # Ehdokkaan ilmoitussivulla olevia euromääriä ei ole tallennettu + # taulukossa td-arvoina, vaan numerot liitetään sivudokumenttiin + # JavaScript-funktiolla document.write(addSpaces(XXX)). XXX täytyy + # siis parsia irti funktiokutsusta -> käytetään regexiä + + p = re.compile('(?<=addSpaces\()[0-9]+') + # Etsitään kaikki regex-osumat + # FIXME: onko findall tässä hyvä? Match ei palauttanut yhtään + # osumaa + luku = p.findall(luku) + if luku: + # findall palautta lis tan osumia, joita pitäisi olla vain 1 + # -> valitaan listan 1. alkio + item[attr] = luku[0] + else: + # jos osumia ei ole, astetaan euromääräksi 0 + item[attr] = 0 + + # Aseta VaalirahoitusItemin attribuutit + set_item(item, 'kulut_kaikki', yhteensa_euroja[0]) + set_item(item, 'rahoitus_kaikki', yhteensa_euroja[1]) + set_item(item, 'omat_varat', erittely_euroja[0]) + set_item(item, 'lainat', erittely_euroja[1]) + set_item(item, 'yksityinen_tuki', erittely_euroja[2]) + set_item(item, 'yritys_tuki', erittely_euroja[3]) + set_item(item, 'puolue_tuki', erittely_euroja[4]) + set_item(item, 'puolueyhdistys_tuki', erittely_euroja[5]) + set_item(item, 'muu_tuki', erittely_euroja[6]) + set_item(item, 'valitetty_tuki', erittely_euroja[7]) + set_item(item, 'kulut_lehdet', kulut_erittely_euroja[0]) + set_item(item, 'kulut_radio', kulut_erittely_euroja[1]) + set_item(item, 'kulut_televisio', kulut_erittely_euroja[2]) + set_item(item, 'kulut_tietoverkot', kulut_erittely_euroja[3]) + set_item(item, 'kulut_muut_viestintavalineet', kulut_erittely_euroja[4]) + set_item(item, 'kulut_ulkomainonta', kulut_erittely_euroja[5]) + set_item(item, 'kulut_painettu_mat', kulut_erittely_euroja[6]) + set_item(item, 'kulut_mainonnan_suunnittelu', kulut_erittely_euroja[7]) + set_item(item, 'kulut_vaalitilaisuudet', kulut_erittely_euroja[8]) + set_item(item, 'kulut_tuen_hankintakulut', kulut_erittely_euroja[9]) + set_item(item, 'kulut_muut', kulut_erittely_euroja[10]) + + return item \ No newline at end of file diff --git a/pool/shard006/Python/0058523_item_issue_justification.py b/pool/shard006/Python/0058523_item_issue_justification.py new file mode 100644 index 0000000000000000000000000000000000000000..6a99a85febe4f9b509833a7a552b09d08377a4f8 --- /dev/null +++ b/pool/shard006/Python/0058523_item_issue_justification.py @@ -0,0 +1,151 @@ +# Copyright 2014 Netflix, 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 security_monkey.views import AuthenticatedService +from security_monkey.views import AUDIT_FIELDS +from security_monkey.datastore import ItemAudit +from security_monkey import db, rbac + +from flask_restful import marshal +from flask_login import current_user +import datetime + + +class JustifyPostDelete(AuthenticatedService): + decorators = [ + rbac.allow(["Justify"], ["POST", "DELETE"]) + ] + + def post(self, audit_id): + """ + .. http:post:: /api/1/issues/1234/justification + + Justify an audit issue on a specific item. + + **Example Request**: + + .. sourcecode:: http + + POST /api/1/issues/1234/justification HTTP/1.1 + Host: example.com + Accept: application/json + + { + 'justification': 'I promise not to abuse this.' + } + + **Example Response**: + + .. sourcecode:: http + + HTTP/1.1 201 OK + Vary: Accept + Content-Type: application/json + + { + "result": { + "justification": "I promise not to abuse this.", + "issue": "Example Issue", + "notes": "Example Notes", + "score": 0, + "item_id": 11890, + "justified_user": "user@example.com", + "justified": true, + "justified_date": "2014-06-19 21:45:58.779168", + "id": 1234 + }, + "auth": { + "authenticated": true, + "user": "user@example.com" + } + } + + + :statuscode 201: no error + :statuscode 401: Authentication Error. Please Login. + """ + + self.reqparse.add_argument('justification', required=False, type=str, help='Must provide justification', location='json') + args = self.reqparse.parse_args() + + item = ItemAudit.query.filter(ItemAudit.id == audit_id).first() + if not item: + return {"Error": "Item with audit_id {} not found".format(audit_id)}, 404 + + item.justified_user_id = current_user.id + item.justified = True + item.justified_date = datetime.datetime.utcnow() + item.justification = args['justification'] + + db.session.add(item) + db.session.commit() + db.session.refresh(item) + + retdict = {'auth': self.auth_dict} + if item.user: + retdict['result'] = dict( + marshal(item.__dict__, AUDIT_FIELDS).items() + + {"justified_user": item.user.email}.items()) + else: + retdict['result'] = dict( + marshal(item.__dict__, AUDIT_FIELDS).items() + + {"justified_user": None}.items()) + + return retdict, 200 + + def delete(self, audit_id): + """ + .. http:delete:: /api/1/issues/1234/justification + + Remove a justification on an audit issue on a specific item. + + **Example Request**: + + .. sourcecode:: http + + DELETE /api/1/issues/1234/justification HTTP/1.1 + Host: example.com + Accept: application/json + + + **Example Response**: + + .. sourcecode:: http + + HTTP/1.1 202 OK + Vary: Accept + Content-Type: application/json + + { + "status": "deleted" + } + + + :statuscode 202: Accepted + :statuscode 401: Authentication Error. Please Login. + """ + + item = ItemAudit.query.filter(ItemAudit.id == audit_id).first() + if not item: + return {"Error": "Item with audit_id {} not found".format(audit_id)}, 404 + + item.justified_user_id = None + item.justified = False + item.justified_date = None + item.justification = None + + db.session.add(item) + db.session.commit() + + return {"status": "deleted"}, 202 diff --git a/pool/shard006/Python/0058525_serial_listener.py b/pool/shard006/Python/0058525_serial_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..28b9aaa8e18a5be33b3c84b4807537ff3c056621 --- /dev/null +++ b/pool/shard006/Python/0058525_serial_listener.py @@ -0,0 +1,53 @@ +import serial +import sys +import MySQLdb + +try: + from configparser import ConfigParser +except ImportError: + from ConfigParser import ConfigParser # ver. < 3.0 + +config = ConfigParser() # instantiate +config.read('mysql.config.ini') # parse existing file +# read values from a mysql.config.ini +myhost = config.get('mysql', 'host') +myuser = config.get('mysql', 'user') +mypasswd = config.get('mysql', 'passwd') +mydb = config.get('mysql', 'db') + +# check that we have usb connected +try: + serialport = serial.Serial("/dev/ttyUSB0", 57600, timeout=0.5) +except Exception, e: + print >> sys.stderr, "Exception: %s" % str(e) + print >> sys.stderr, "No valid usb found from dev" + sys.exit(1) + +# use config settings to db connection +db = MySQLdb.Connect(host=myhost, # your host, usually localhost + user=myuser, # your username + passwd=mypasswd, # your password + db=mydb) # name of the data base + +cur = db.cursor() + +# loop +while True: + command = serialport.readline() + s = command.strip() + suffix = ";" + if s.endswith(suffix) == False: # in line is not ending with ; forget it + x = "x" # do nothing + elif not s: # if s is empty forget it + print "tyhja" + else: + s = s[:-1] # remove tailing ; + node, value = s.split(":") # split message and assing variables + if node == '1Node': + cur.execute("INSERT INTO lampo1 (node, lampo) VALUES (%s, %s) ", (node, value)) + db.commit() + print command + else: + cur.execute("INSERT INTO rele1 (node, tila) VALUES (%s, %s) ", (node, value)) + db.commit() + print command diff --git a/pool/shard006/Python/0058535_0026_auto_20190122_2128.py b/pool/shard006/Python/0058535_0026_auto_20190122_2128.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee72e68c727942cdc55785a594d9146a97c2a06 --- /dev/null +++ b/pool/shard006/Python/0058535_0026_auto_20190122_2128.py @@ -0,0 +1,32 @@ +# Generated by Django 2.1.5 on 2019-01-22 21:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('build', '0025_buildflowasset_category'), + ] + + operations = [ + migrations.RemoveField( + model_name='flowtask', + name='name', + ), + migrations.RemoveField( + model_name='flowtask', + name='step_string', + ), + migrations.AddField( + model_name='flowtask', + name='path', + field=models.CharField(default='', help_text='dotted path e.g. flow1.flow2.task_name', max_length=2048), + preserve_default=False, + ), + migrations.AlterField( + model_name='flowtask', + name='stepnum', + field=models.CharField(help_text='dotted step number for CCI task', max_length=64), + ), + ] diff --git a/pool/shard006/Python/0058536_content_frame.py b/pool/shard006/Python/0058536_content_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc3c37fe0cf4b5a720dba63471f9636e23d333b --- /dev/null +++ b/pool/shard006/Python/0058536_content_frame.py @@ -0,0 +1,74 @@ +''' +Copyright (c) 2011-2015, Agora Games, LLC All rights reserved. + +https://github.com/agoragames/haigha/blob/master/LICENSE.txt +''' + +from haigha.writer import Writer +from haigha.frames.frame import Frame + + +class ContentFrame(Frame): + + ''' + Frame for reading in content. + ''' + + @classmethod + def type(cls): + return 3 + + @property + def payload(self): + return self._payload + + @classmethod + def parse(self, channel_id, payload): + return ContentFrame(channel_id, payload) + + @classmethod + def create_frames(self, channel_id, buf, frame_max): + ''' + A generator which will create frames from a buffer given a max + frame size. + ''' + size = frame_max - 8 # 8 bytes overhead for frame header and footer + offset = 0 + while True: + payload = buf[offset:(offset + size)] + if len(payload) == 0: + break + offset += size + + yield ContentFrame(channel_id, payload) + if offset >= len(buf): + break + + def __init__(self, channel_id, payload): + Frame.__init__(self, channel_id) + self._payload = payload + + def __str__(self): + if isinstance(self._payload, str): + payload = ''.join(['\\x%s' % (c.encode('hex')) + for c in self._payload]) + else: + payload = str(self._payload) + + return "%s[channel: %d, payload: %s]" % ( + self.__class__.__name__, self.channel_id, payload) + + def write_frame(self, buf): + ''' + Write the frame into an existing buffer. + ''' + writer = Writer(buf) + + writer.write_octet(self.type()).\ + write_short(self.channel_id).\ + write_long(len(self._payload)).\ + write(self._payload).\ + write_octet(0xce) + + +ContentFrame.register() diff --git a/pool/shard006/Python/0058537_utils.py b/pool/shard006/Python/0058537_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..02b491bb9cad0f874a5275102adcb22cbc891951 --- /dev/null +++ b/pool/shard006/Python/0058537_utils.py @@ -0,0 +1,90 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from datetime import datetime +import time +import json +import os.path +import os + +########################### + +class bcolors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKGREEN = '\033[92m' + WARNING = '\033[37m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + +########################### + +debug = False + +def get_project_base_folder(): + path = os.path.abspath(os.path.curdir) + if not path.endswith('wescores-python'): + path = os.path.abspath(os.path.pardir) + return path + +def get_project_file_path(path): + return get_project_base_folder() + path + +def timestamp_from_datestr(datestr): + atime = time.strptime(datestr, '%m/%d/%Y') + return int(time.mktime(atime) * 1000) + +def datestr_from_timestamp(timestamp): + return datetime.fromtimestamp(timestamp / 1000).strftime('%m/%d/%Y') + +def lines_of_file(file_path): + if os.path.isfile(file_path): + with open(file_path, 'r') as file: + lines = [line.rstrip() for line in file.readlines()] + return lines + else: + return [] + +def first_line_of_file(file_path): + lines = lines_of_file(file_path) + if len(lines) > 0: + return lines[0] + else: + return '' + +def write_line_into_file(line, file_path): + os.system('touch %s'%(file_path)) + with open(file_path, 'w') as file: + file.write(line) + + +########################### +# Folder +########################### + +def get_dirs_in_folder(folder_path): + return [f for f in os.listdir(folder_path) if os.path.isdir(folder_path + '/' + f)] + +def get_files_in_folder(folder_path): + return [f for f in os.listdir(folder_path) if os.path.isfile(folder_path + '/' + f) and not f.startswith('.')] + + +if __name__ == "__main__": + print get_project_base_folder() + + print get_dirs_in_folder(get_project_base_folder() + "/doc") + print get_files_in_folder(get_project_base_folder() + "/doc/how/pod") + + # print get_project_file_path('/file.log') + # print get_project_file_path('/aaa/file.log') + + # print "utils" + # timestamp = timestamp_from_datestr('5/16/2014') + # print timestamp + # timestr = datestr_from_timestamp(timestamp) + # print timestr + + + diff --git a/pool/shard006/Python/0058542_popupmenu.py b/pool/shard006/Python/0058542_popupmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..3130edcf530fa1b08d0303d8a8c9d4c75cbfb175 --- /dev/null +++ b/pool/shard006/Python/0058542_popupmenu.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +"""This module implements a pop up menu widget""" +from __future__ import division +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals +from collections import defaultdict +from functools import partial +from asciimatics.event import KeyboardEvent, MouseEvent +from asciimatics.screen import Screen +from asciimatics.widgets.button import Button +from asciimatics.widgets.frame import Frame +from asciimatics.widgets.layout import Layout + + +class PopupMenu(Frame): + """ + A widget for displaying a menu. + """ + + palette = defaultdict(lambda: (Screen.COLOUR_WHITE, Screen.A_NORMAL, Screen.COLOUR_CYAN)) + palette["focus_button"] = (Screen.COLOUR_CYAN, Screen.A_NORMAL, Screen.COLOUR_WHITE) + + def __init__(self, screen, menu_items, x, y): + """ + :param screen: The Screen being used for this pop-up. + :param menu_items: a list of items to be displayed in the menu. + :param x: The X coordinate for the desired pop-up. + :param y: The Y coordinate for the desired pop-up. + + The menu_items parameter is a list of 2-tuples, which define the text to be displayed in + the menu and the function to call when that menu item is clicked. For example: + + menu_items = [("Open", file_open), ("Save", file_save), ("Close", file_close)] + """ + # Sort out location based on width of menu text. + w = max(len(i[0]) for i in menu_items) + h = len(menu_items) + if x + w >= screen.width: + x -= w - 1 + if y + h >= screen.height: + y -= h - 1 + + # Construct the Frame + super(PopupMenu, self).__init__( + screen, h, w, x=x, y=y, has_border=False, can_scroll=False, is_modal=True, hover_focus=True) + + # Build the widget to display the time selection. + layout = Layout([1], fill_frame=True) + self.add_layout(layout) + for item in menu_items: + func = partial(self._destroy, item[1]) + layout.add_widget(Button(item[0], func, add_box=False), 0) + self.fix() + + def _destroy(self, callback=None): + self._scene.remove_effect(self) + if callback is not None: + callback() + + def process_event(self, event): + # Look for events that will close the pop-up - e.g. clicking outside the Frame or ESC key. + if event is not None: + if isinstance(event, KeyboardEvent): + if event.key_code == Screen.KEY_ESCAPE: + event = None + elif isinstance(event, MouseEvent) and event.buttons != 0: + origin = self._canvas.origin + if event.y < origin[1] or event.y >= origin[1] + self._canvas.height: + event = None + elif event.x < origin[0] or event.x >= origin[0] + self._canvas.width: + event = None + if event is None: + self._destroy() + return super(PopupMenu, self).process_event(event) diff --git a/pool/shard006/Python/0058546_clangxx.py b/pool/shard006/Python/0058546_clangxx.py new file mode 100644 index 0000000000000000000000000000000000000000..736d45506b6b669b75acc820990bfe15dfeef079 --- /dev/null +++ b/pool/shard006/Python/0058546_clangxx.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8; -*- + +"""SCons.Tool.clang++ + +Tool-specific initialization for clang++. + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +# +# __COPYRIGHT__ +# +# 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" + +# Based on SCons/Tool/g++.py by Paweł Tomulik 2014 as a separate tool. +# Brought into the SCons mainline by Russel Winder 2017. + +import os.path +import re +import subprocess +import sys + +import SCons.Tool +import SCons.Util +import SCons.Tool.cxx +from SCons.Tool.clangCommon import get_clang_install_dirs +from SCons.Tool.MSCommon import msvc_setup_env_once + + +compilers = ['clang++'] + +def generate(env): + """Add Builders and construction variables for clang++ to an Environment.""" + static_obj, shared_obj = SCons.Tool.createObjBuilders(env) + + SCons.Tool.cxx.generate(env) + + env['CXX'] = env.Detect(compilers) or 'clang++' + + # platform specific settings + if env['PLATFORM'] == 'aix': + env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -mminimal-toc') + env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 + env['SHOBJSUFFIX'] = '$OBJSUFFIX' + elif env['PLATFORM'] == 'hpux': + env['SHOBJSUFFIX'] = '.pic.o' + elif env['PLATFORM'] == 'sunos': + env['SHOBJSUFFIX'] = '.pic.o' + elif env['PLATFORM'] == 'win32': + # Ensure that we have a proper path for clang++ + clangxx = SCons.Tool.find_program_path(env, compilers[0], default_paths=get_clang_install_dirs(env['PLATFORM'])) + if clangxx: + clangxx_bin_dir = os.path.dirname(clangxx) + env.AppendENVPath('PATH', clangxx_bin_dir) + + # Set-up ms tools paths + msvc_setup_env_once(env) + + + # determine compiler version + if env['CXX']: + pipe = SCons.Action._subproc(env, [env['CXX'], '--version'], + stdin='devnull', + stderr='devnull', + stdout=subprocess.PIPE) + if pipe.wait() != 0: + return + + # clang -dumpversion is of no use + with pipe.stdout: + line = pipe.stdout.readline() + line = line.decode() + match = re.search(r'clang +version +([0-9]+(?:\.[0-9]+)+)', line) + if match: + env['CXXVERSION'] = match.group(1) + +def exists(env): + return env.Detect(compilers) + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=4: diff --git a/pool/shard006/Python/0058548_test_accessors.py b/pool/shard006/Python/0058548_test_accessors.py new file mode 100644 index 0000000000000000000000000000000000000000..f5860cf87401ede62a70c3180267dcbcd3b3f039 --- /dev/null +++ b/pool/shard006/Python/0058548_test_accessors.py @@ -0,0 +1,126 @@ +############################################################################## +# +# Copyright (c) 2003 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +"""Test Interface accessor methods. + +$Id: test_accessors.py 29436 2005-03-11 04:11:07Z poster $ +""" +import unittest +from zope.interface import Interface, implements +from zope.schema import Text, accessors +from zope.schema.interfaces import IText +from zope.schema.accessors import FieldReadAccessor, FieldWriteAccessor +from zope.interface.verify import verifyClass, verifyObject +from zope.interface import document +from zope.interface.interfaces import IMethod + +class Test(unittest.TestCase): + + def test(self): + + field = Text(title=u"Foo thing") + + class I(Interface): + + getFoo, setFoo = accessors(field) + + class Bad(object): + implements(I) + + class Good(object): + implements(I) + + def __init__(self): + self.set = 0 + + def getFoo(self): + return u"foo" + + def setFoo(self, v): + self.set += 1 + + names = I.names() + names.sort() + self.assertEqual(names, ['getFoo', 'setFoo']) + self.assertEqual(I['getFoo'].field, field) + self.assertEqual(I['getFoo'].__name__, 'getFoo') + self.assertEqual(I['getFoo'].__doc__, u'get Foo thing') + self.assertEqual(I['getFoo'].__class__, FieldReadAccessor) + self.assertEqual(I['getFoo'].writer, I['setFoo']) + + # test some field attrs + for attr in ('title', 'description', 'readonly'): + self.assertEqual(getattr(I['getFoo'], attr), getattr(field, attr)) + + self.assert_(IText.providedBy(I['getFoo'])) + + self.assert_(IMethod.providedBy(I['getFoo'])) + self.assert_(IMethod.providedBy(I['setFoo'])) + + self.assertEqual(I['setFoo'].field, field) + self.assertEqual(I['setFoo'].__name__, 'setFoo') + self.assertEqual(I['setFoo'].__doc__, u'set Foo thing') + self.assertEqual(I['setFoo'].__class__, FieldWriteAccessor) + + self.assertRaises(Exception, verifyClass, I, Bad) + self.assertRaises(Exception, verifyObject, I, Bad()) + + self.assertEquals(I['getFoo'].query(Bad(), 42), 42) + self.assertRaises(AttributeError, I['getFoo'].get, Bad()) + + verifyClass(I, Good) + verifyObject(I, Good()) + + self.assertEquals(I['getFoo'].query(Good(), 42), u'foo') + self.assertEquals(I['getFoo'].get(Good()), u'foo') + instance = Good() + I['getFoo'].set(instance, u'whatever') + self.assertEquals(instance.set, 1) + + def test_doc(self): + + field = Text(title=u"Foo thing") + + class I(Interface): + + getFoo, setFoo = accessors(field) + def bar(): pass + x = Text() + + d = document.asStructuredText(I) + self.assertEqual(d, + "I\n" + "\n" + " Attributes:\n" + "\n" + " x -- no documentation\n" + "\n" + " Methods:\n" + "\n" + " bar() -- no documentation\n" + "\n" + " getFoo() -- get Foo thing\n" + "\n" + " setFoo(newvalue) -- set Foo thing\n" + "\n" + ) + + +def test_suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(Test)) + return suite + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard006/Python/0058554_test_makesuperuser.py b/pool/shard006/Python/0058554_test_makesuperuser.py new file mode 100644 index 0000000000000000000000000000000000000000..45e16f31d2284e40769c470abfb32645bb5f3b85 --- /dev/null +++ b/pool/shard006/Python/0058554_test_makesuperuser.py @@ -0,0 +1,97 @@ +import contextlib +from StringIO import StringIO + +import mock +import pytest + +from django.contrib.auth.models import User +from django.core.management.base import CommandError + +from crashstats.base.tests.testbase import DjangoTestCase +from crashstats.authentication.management.commands import makesuperuser + + +@contextlib.contextmanager +def redirect_stdout(stream): + import sys + sys.stdout = stream + yield + sys.stdout = sys.__stdout__ + + +@contextlib.contextmanager +def redirect_stderr(stream): + import sys + sys.stderr = stream + yield + sys.stderr = sys.__stderr__ + + +class TestMakeSuperuserCommand(DjangoTestCase): + + def test_make_existing_user(self): + bob = User.objects.create(username='bob', email='bob@mozilla.com') + cmd = makesuperuser.Command() + buffer = StringIO() + with redirect_stdout(buffer): + cmd.handle(emailaddress=['BOB@mozilla.com']) + assert 'bob@mozilla.com is now a superuser' in buffer.getvalue() + # reload + assert User.objects.get(pk=bob.pk, is_superuser=True) + + def test_make_already_user(self): + bob = User.objects.create(username='bob', email='bob@mozilla.com') + bob.is_superuser = True + bob.save() + cmd = makesuperuser.Command() + buffer = StringIO() + with redirect_stdout(buffer): + cmd.handle(emailaddress=['BOB@mozilla.com']) + assert 'bob@mozilla.com was already a superuser' in buffer.getvalue() + # reload + assert User.objects.get(pk=bob.pk, is_superuser=True) + + def test_make_two_user_superuser(self): + bob = User.objects.create(username='bob', email='bob@mozilla.com') + bob.is_superuser = True # already + bob.save() + otto = User.objects.create(username='otto', email='otto@mozilla.com') + cmd = makesuperuser.Command() + buffer = StringIO() + with redirect_stdout(buffer): + cmd.handle(emailaddress=['BOB@mozilla.com', 'oTTo@mozilla.com']) + assert User.objects.get(pk=bob.pk, is_superuser=True) + assert User.objects.get(pk=otto.pk, is_superuser=True) + + def test_nonexisting_user(self): + cmd = makesuperuser.Command() + buffer = StringIO() + email = 'neverheardof@mozilla.com' + with redirect_stdout(buffer): + cmd.handle(emailaddress=[email]) + assert User.objects.get(email=email, is_superuser=True) + assert '{} is now a superuser'.format(email) in buffer.getvalue() + + @mock.patch( + 'crashstats.authentication.management.commands.makesuperuser.' + 'get_input', + return_value='BOB@mozilla.com ' + ) + def test_with_raw_input(self, mocked_raw_input): + User.objects.create(username='bob', email='bob@mozilla.com') + cmd = makesuperuser.Command() + buffer = StringIO() + with redirect_stdout(buffer): + cmd.handle(emailaddress=[]) + # reload + assert User.objects.get(email='bob@mozilla.com', is_superuser=True) + + @mock.patch( + 'crashstats.authentication.management.commands.makesuperuser.' + 'get_input', + return_value='\n' + ) + def test_with_raw_input_but_empty(self, mocked_raw_input): + cmd = makesuperuser.Command() + with pytest.raises(CommandError): + cmd.handle(emailaddress=[]) diff --git a/pool/shard006/Python/0058558_template_tester.py b/pool/shard006/Python/0058558_template_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb5f7012aea952c115e180809e938c95acb6252 --- /dev/null +++ b/pool/shard006/Python/0058558_template_tester.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Template tester script, used to test and mark template as usable. + +get: + Export bash vars to be eval'd for template testing with the jenkins runner + +latest: + Export bash vars to be eval'd for getting the latest usable template + +mark: + Mark a template as tested and, if it passes, usable. + +""" +import os +import sys + +from cfme.utils import trackerbot + + +def get(api, request_type=None, template_name=None): + list_of_templates = trackerbot.templates_to_test(api, request_type=request_type, limit=200) + + if len(list_of_templates) == 0: + # No templates to test for this provider type + return 0 + + if not template_name: + # If no specific name specified, return 1st element + template, provider_key, stream, provider_type = list_of_templates[0] + else: + # Filter the list for only templates matching 'template_name' + filtered_list = [t for t in list_of_templates if t[0] == template_name] + if len(filtered_list) > 0: + template, provider_key, stream, provider_type = filtered_list[0] + else: + # No templates to test for this template name + return 0 + + # Print envvar exports to be eval'd + export( + appliance_template=template, + provider_key=provider_key, + stream=stream, + provider_type=provider_type + ) + + +def latest(api, stream, provider_key=None): + try: + if provider_key: + prov = api.provider(provider_key).get() + res = prov['latest_templates'][stream] + else: + res = api.group(stream).get() + except IndexError: + # No templates in stream + return 1 + + export( + appliance_template=res['latest_template'], + provider_keys=' '.join(res['latest_template_providers']) + ) + + +def export(**env_vars): + for varname, value in env_vars.items(): + print(f'export {varname}="{value}";') + print("# to import these into your bash environment: eval $({})".format(' '.join(sys.argv))) + + +def mark(api, provider_key, template, usable, diagnose): + # set some defaults + diagnosis = None + build_number = None + if not usable: + build_number = os.environ.get('BUILD_NUMBER') + +# temporarily disabled; diagnosis is causing template marking to fail on downstream appliances :( +# if diagnose: +# # diagnose will return None on a usable appliance, so don't bother +# from utils.appliance import IPAppliance +# ipa = IPAppliance() +# diagnosis = ipa.diagnose_evm_failure() +# if diagnosis: +# logger.error('Appliance failed: {}'.format(diagnosis.split(os.linesep)[0])) + + trackerbot.mark_provider_template(api, provider_key, template, tested=True, usable=usable, + diagnosis=diagnosis, build_number=build_number) + + +def retest(api, provider_key, template): + trackerbot.mark_provider_template(api, provider_key, template, tested=False) + + +def check_tested(api, template_name, provider_type): + """ + Check if a template has been tested and passed (marked usable) for a provider. + + If not usable, mark it untested so jenkins picks it up for testing. + """ + trackerbot.mark_unusable_as_untested(api, template_name, provider_type) + print(str(trackerbot.check_if_tested(api, template_name, provider_type)).lower()) + + +if __name__ == '__main__': + parser = trackerbot.cmdline_parser() + subs = parser.add_subparsers(title='commands', dest='command') + + parse_get = subs.add_parser('get', help='get a template to test') + parse_get.set_defaults(func=get) + parse_get.add_argument('--request_type', dest='request_type', help='provider type') + parse_get.add_argument('--template', dest='template', help='template name (optional)') + + parse_check_tested = subs.add_parser( + 'check_tested', help='check if template passed tests at least once on given provider type') + parse_check_tested.set_defaults(func=check_tested) + parse_check_tested.add_argument('--request_type', dest='request_type', help='provider type') + parse_check_tested.add_argument('--template', dest='template', help='template name') + + parse_latest = subs.add_parser('latest', help='get the latest usable template for a provider') + parse_latest.set_defaults(func=latest) + parse_latest.add_argument('stream', help='template stream (e.g. upstream, downstream-52z') + parse_latest.add_argument('provider_key', nargs='?', default=None) + + parse_mark = subs.add_parser('mark', help='mark a tested template') + parse_mark.set_defaults(func=mark) + parse_mark.add_argument('provider_key') + parse_mark.add_argument('template') + parse_mark.add_argument('-n', '--not-usable', dest='usable', action='store_false', + default=True, help='mark template as not usable (templates are marked usable by default') + parse_mark.add_argument('-d', '--diagnose', dest='diagnose', action='store_true', + default=False, help='attempt to diagnose an unusable template and submit the result') + + parse_retest = subs.add_parser('retest', help='flag a tested template for retesting') + parse_retest.set_defaults(func=retest) + parse_retest.add_argument('provider_key') + parse_retest.add_argument('template') + + args = parser.parse_args() + api = trackerbot.api(args.trackerbot_url) + func_map = { + get: lambda: get(api, args.request_type, args.template), + latest: lambda: latest(api, args.stream, args.provider_key), + mark: lambda: mark(api, args.provider_key, args.template, args.usable, args.diagnose), + retest: lambda: retest(api, args.provider_key, args.template), + check_tested: lambda: check_tested(api, args.template, args.request_type), + } + sys.exit(func_map[args.func]()) diff --git a/pool/shard006/Python/0058563_param_conversion_util.py b/pool/shard006/Python/0058563_param_conversion_util.py new file mode 100644 index 0000000000000000000000000000000000000000..9ab1feac14f87bf73653c7f86298f5aa54f45d92 --- /dev/null +++ b/pool/shard006/Python/0058563_param_conversion_util.py @@ -0,0 +1,77 @@ +# 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. + +"""Common parameter conversion utilities.""" + +import collections +import re +from typing import Any, Dict, List, Mapping, Tuple + +import jax.numpy as jnp +import tensorflow as tf + + +def load_tf_params(checkpoint_path: str) -> Dict[str, Any]: + """Loads TF parameters from the checkpoint at the given path.""" + ckpt_reader = tf.train.load_checkpoint(checkpoint_path) + return { + tf_name: ckpt_reader.get_tensor(tf_name) + for tf_name in ckpt_reader.get_variable_to_dtype_map() + } + + +def convert_tf_params( + tf_params: Dict[str, Any], + mapping: Mapping[Tuple[str, ...], str], + tf_prefix: str = '', +) -> Dict[str, Any]: + """Given a mapping from TF to Flax names returns a Flax parameters dict. + + A utility method that given a TF parameters dictionary, a mapping between the + Flax parameter of depth one (i.e only two keys in the returned dictionary) and + a tf_prefix returns a partial dictionary of the Flax parameters. The method is + used in the rest of the functions to create a final full dictionary of Flax + parameters. + + Args: + tf_params: TF BERT model parameters extracted from the checkpoint. + mapping: A parameters mapping between a slice of Flax BERT model dictionary + of parameters and the TF parameters. + tf_prefix: A shared prefix of the TF parameter keys. Will be prepended to + each of TF parameter key in the mapping. + + Returns: + Partial parameters for the Flax BERT model. + """ + params = collections.defaultdict(dict) + for jax_key, tf_var in mapping.items(): + tf_name = f'{tf_prefix}{tf_var}' + if tf_name in tf_params: + tf_value = tf_params[tf_name] + elif f'{tf_name}:0' in tf_params: + tf_value = tf_params[f'{tf_name}:0'] + else: + raise ValueError(f'tf_params does not contain {tf_name!r}') + + param_dict = params + for jax_key_part in jax_key[:-1]: + param_dict = param_dict[jax_key_part] + param_dict[jax_key[-1]] = jnp.asarray(tf_value) + return params + + +def get_int_regex_matches(pattern: str, state: Mapping[str, Any]) -> List[int]: + """Matches a pattern with an integer capture group against state keys.""" + matches = [re.match(pattern, key) for key in state] + return sorted(set(int(m.group(1)) for m in matches if m is not None)) diff --git a/pool/shard006/Python/0058564_color.py b/pool/shard006/Python/0058564_color.py new file mode 100644 index 0000000000000000000000000000000000000000..c4f18dfadba6a4ff24f95db9ff8df0b1ce27e74d --- /dev/null +++ b/pool/shard006/Python/0058564_color.py @@ -0,0 +1,152 @@ +# Copyright(c) 2007-2008 by Lorenzo Gil Sanchez +# 2009 by Yaco S.L. +# +# This file is part of PyCha. +# +# PyCha 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. +# +# PyCha 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 PyCha. If not, see . + +import unittest + +import pycha.color + + +class SimpleColorScheme(pycha.color.ColorScheme): + pass + + +class ColorTests(unittest.TestCase): + def test_clamp(self): + self.assertEqual(pycha.color.clamp(0, 1, 2), 1) + self.assertEqual(pycha.color.clamp(0, 1, -1), 0) + self.assertEqual(pycha.color.clamp(0, 1, 0.5), 0.5) + self.assertEqual(pycha.color.clamp(0, 1, 1), 1) + self.assertEqual(pycha.color.clamp(0, 1, 0), 0) + + def test_hex2rgb(self): + color = pycha.color.hex2rgb('#ff0000') + self.assert_(isinstance(color, tuple)) + self.assertAlmostEqual(1, color[0]) + self.assertAlmostEqual(0, color[1]) + self.assertAlmostEqual(0, color[2]) + + color2 = pycha.color.hex2rgb(color) + self.assertEqual(color, color2) + + color = pycha.color.hex2rgb('#000fff000', digits=3) + self.assert_(isinstance(color, tuple)) + self.assertEqual(0, color[0]) + self.assertEqual(1, color[1]) + self.assertEqual(0, color[2]) + + color = pycha.color.hex2rgb('#00000000ffff', digits=4) + self.assert_(isinstance(color, tuple)) + self.assertEqual(0, color[0]) + self.assertEqual(0, color[1]) + self.assertEqual(1, color[2]) + + def test_rgb2hsv_and_hsv2rgb(self): + for rgb, hsv in (((1.0, 0.0, 0.0), (0.0, 1.0, 1.0)), + ((1.0, 0.5, 0.0), (30.0, 1.0, 1.0)), + ((1.0, 1.0, 0.0), (60.0, 1.0, 1.0)), + ((0.5, 1.0, 0.0), (90.0, 1.0, 1.0)), + ((0.0, 1.0, 0.0), (120.0, 1.0, 1.0)), + ((0.0, 1.0, 0.5), (150.0, 1.0, 1.0)), + ((0.0, 1.0, 1.0), (180.0, 1.0, 1.0)), + ((0.0, 0.5, 1.0), (210.0, 1.0, 1.0)), + ((0.0, 0.0, 1.0), (240.0, 1.0, 1.0)), + ((0.5, 0.0, 1.0), (270.0, 1.0, 1.0)), + ((1.0, 0.0, 1.0), (300.0, 1.0, 1.0)), + ((1.0, 0.0, 0.5), (330.0, 1.0, 1.0)), + ((0.375, 0.5, 0.25), (90.0, 0.5, 0.5)), + ((0.21875, 0.25, 0.1875), (90.0, 0.25, 0.25))): + self._assertColors(pycha.color.rgb2hsv(*rgb), hsv, 5) + self._assertColors(pycha.color.hsv2rgb(*hsv), rgb, 5) + + def test_lighten(self): + r, g, b = (1.0, 1.0, 0.0) + r2, g2, b2 = pycha.color.lighten(r, g, b, 0.1) + self.assertEqual((r2, g2, b2), (1.0, 1.0, 0.1)) + + r3, g3, b3 = pycha.color.lighten(r2, g2, b2, 0.5) + self.assertEqual((r3, g3, b3), (1.0, 1.0, 0.6)) + + def _assertColors(self, c1, c2, precission): + for i in range(3): + self.assertAlmostEqual(c1[i], c2[i], precission) + + def test_basicColors(self): + colors = ('red', 'green', 'blue', 'grey', 'black', 'darkcyan') + for color in colors: + self.assert_(color in pycha.color.basicColors) + + def test_ColorSchemeRegistry(self): + self.assertEquals(SimpleColorScheme, + pycha.color.ColorScheme.getColorScheme('simple')) + self.assertEquals(None, + pycha.color.ColorScheme.getColorScheme('foo')) + + def test_FixedColorScheme(self): + keys = range(3) + colors = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) + scheme = pycha.color.FixedColorScheme(keys, colors) + self._assertColors(scheme[0], (1.0, 0.0, 0.0), 1) + self._assertColors(scheme[1], (0.0, 1.0, 0.0), 3) + self._assertColors(scheme[2], (0.0, 0.0, 1.0), 3) + + def test_GradientColorScheme(self): + keys = range(5) + scheme = pycha.color.GradientColorScheme(keys, "#000000") + self._assertColors(scheme[0], (0.0, 0.0, 0.0), 3) + self._assertColors(scheme[1], (0.1, 0.1, 0.1), 3) + self._assertColors(scheme[2], (0.2, 0.2, 0.2), 3) + self._assertColors(scheme[3], (0.3, 0.3, 0.3), 3) + self._assertColors(scheme[4], (0.4, 0.4, 0.4), 3) + + def test_autoLighting(self): + """This test ensures that the colors don't get to white too fast. + + See bug #8. + """ + # we have a lot of keys + n = 50 + keys = range(n) + color = '#ff0000' + scheme = pycha.color.GradientColorScheme(keys, color) + + # ensure that the last color is not completely white + color = scheme[n - 1] + + # the red component was already 1 + self.assertAlmostEqual(color[0], 1.0, 4) + self.assertNotAlmostEqual(color[1], 1.0, 4) + self.assertNotAlmostEqual(color[2], 1.0, 4) + + def test_RainbowColorScheme(self): + keys = range(5) + scheme = pycha.color.GradientColorScheme(keys, "#ff0000") + self._assertColors(scheme[0], (1.0, 0.0, 0.0), 3) + self._assertColors(scheme[1], (1.0, 0.1, 0.1), 3) + self._assertColors(scheme[2], (1.0, 0.2, 0.2), 3) + self._assertColors(scheme[3], (1.0, 0.3, 0.3), 3) + self._assertColors(scheme[4], (1.0, 0.4, 0.4), 3) + + +def test_suite(): + return unittest.TestSuite(( + unittest.makeSuite(ColorTests), + )) + + +if __name__ == '__main__': + unittest.main(defaultTest='test_suite') diff --git a/pool/shard006/Python/0058571_test_pressure.py b/pool/shard006/Python/0058571_test_pressure.py new file mode 100644 index 0000000000000000000000000000000000000000..0109d045a553b881a88c9b6ca7dab7594a8f1532 --- /dev/null +++ b/pool/shard006/Python/0058571_test_pressure.py @@ -0,0 +1,110 @@ +"""Test Home Assistant pressure utility functions.""" +import pytest + +from homeassistant.const import ( + PRESSURE_CBAR, + PRESSURE_HPA, + PRESSURE_INHG, + PRESSURE_KPA, + PRESSURE_MBAR, + PRESSURE_PA, + PRESSURE_PSI, +) +import homeassistant.util.pressure as pressure_util + +INVALID_SYMBOL = "bob" +VALID_SYMBOL = PRESSURE_PA + + +def test_convert_same_unit(): + """Test conversion from any unit to same unit.""" + assert pressure_util.convert(2, PRESSURE_PA, PRESSURE_PA) == 2 + assert pressure_util.convert(3, PRESSURE_HPA, PRESSURE_HPA) == 3 + assert pressure_util.convert(4, PRESSURE_MBAR, PRESSURE_MBAR) == 4 + assert pressure_util.convert(5, PRESSURE_INHG, PRESSURE_INHG) == 5 + assert pressure_util.convert(6, PRESSURE_KPA, PRESSURE_KPA) == 6 + assert pressure_util.convert(7, PRESSURE_CBAR, PRESSURE_CBAR) == 7 + + +def test_convert_invalid_unit(): + """Test exception is thrown for invalid units.""" + with pytest.raises(ValueError): + pressure_util.convert(5, INVALID_SYMBOL, VALID_SYMBOL) + + with pytest.raises(ValueError): + pressure_util.convert(5, VALID_SYMBOL, INVALID_SYMBOL) + + +def test_convert_nonnumeric_value(): + """Test exception is thrown for nonnumeric type.""" + with pytest.raises(TypeError): + pressure_util.convert("a", PRESSURE_HPA, PRESSURE_INHG) + + +def test_convert_from_hpascals(): + """Test conversion from hPA to other units.""" + hpascals = 1000 + assert pressure_util.convert(hpascals, PRESSURE_HPA, PRESSURE_PSI) == pytest.approx( + 14.5037743897 + ) + assert pressure_util.convert( + hpascals, PRESSURE_HPA, PRESSURE_INHG + ) == pytest.approx(29.5299801647) + assert pressure_util.convert(hpascals, PRESSURE_HPA, PRESSURE_PA) == pytest.approx( + 100000 + ) + assert pressure_util.convert(hpascals, PRESSURE_HPA, PRESSURE_KPA) == pytest.approx( + 100 + ) + assert pressure_util.convert( + hpascals, PRESSURE_HPA, PRESSURE_MBAR + ) == pytest.approx(1000) + assert pressure_util.convert( + hpascals, PRESSURE_HPA, PRESSURE_CBAR + ) == pytest.approx(100) + + +def test_convert_from_kpascals(): + """Test conversion from hPA to other units.""" + kpascals = 100 + assert pressure_util.convert(kpascals, PRESSURE_KPA, PRESSURE_PSI) == pytest.approx( + 14.5037743897 + ) + assert pressure_util.convert( + kpascals, PRESSURE_KPA, PRESSURE_INHG + ) == pytest.approx(29.5299801647) + assert pressure_util.convert(kpascals, PRESSURE_KPA, PRESSURE_PA) == pytest.approx( + 100000 + ) + assert pressure_util.convert(kpascals, PRESSURE_KPA, PRESSURE_HPA) == pytest.approx( + 1000 + ) + assert pressure_util.convert( + kpascals, PRESSURE_KPA, PRESSURE_MBAR + ) == pytest.approx(1000) + assert pressure_util.convert( + kpascals, PRESSURE_KPA, PRESSURE_CBAR + ) == pytest.approx(100) + + +def test_convert_from_inhg(): + """Test conversion from inHg to other units.""" + inhg = 30 + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_PSI) == pytest.approx( + 14.7346266155 + ) + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_KPA) == pytest.approx( + 101.59167 + ) + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_HPA) == pytest.approx( + 1015.9167 + ) + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_PA) == pytest.approx( + 101591.67 + ) + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_MBAR) == pytest.approx( + 1015.9167 + ) + assert pressure_util.convert(inhg, PRESSURE_INHG, PRESSURE_CBAR) == pytest.approx( + 101.59167 + ) diff --git a/pool/shard006/Python/0058574_lenet_mnist.py b/pool/shard006/Python/0058574_lenet_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..3007dd1c35449f426251d6ce8a2fb4262e8b9d97 --- /dev/null +++ b/pool/shard006/Python/0058574_lenet_mnist.py @@ -0,0 +1,93 @@ +''' +USAGE +python lenet_mnist.py --save-model 1 --weights output/lenet_weights.hdf5 +python lenet_mnist.py --load-model 1 --weights output/lenet_weights.hdf5 +''' + +# import the necessary packages +import numpy as np +import argparse +import cv2 +from pyimagesearch.cnn.networks import LeNet +from sklearn.cross_validation import train_test_split +from sklearn import datasets +from keras.optimizers import SGD +from keras.utils import np_utils + + +# construct the argument parse and parse the arguments +ap = argparse.ArgumentParser() +ap.add_argument("-s", "--save-model", type=int, default=-1, + help="(optional) whether or not model should be saved to disk") +ap.add_argument("-l", "--load-model", type=int, default=-1, + help="(optional) whether or not pre-trained model should be loaded") +ap.add_argument("-w", "--weights", type=str, + help="(optional) path to weights file") +args = vars(ap.parse_args()) + +# grab the MNIST dataset (if this is your first time running this +# script, the download may take a minute -- the 55MB MNIST dataset +# will be downloaded) +print("[INFO] downloading MNIST...") +dataset = datasets.fetch_mldata("MNIST Original") + +# reshape the MNIST dataset from a flat list of 784-dim vectors, to +# 28 x 28 pixel images, then scale the data to the range [0, 1.0] +# and construct the training and testing splits +data = dataset.data.reshape((dataset.data.shape[0], 28, 28)) +data = data[:, np.newaxis, :, :] +(trainData, testData, trainLabels, testLabels) = train_test_split( + data / 255.0, dataset.target.astype("int"), test_size=0.33) + +# transform the training and testing labels into vectors in the +# range [0, classes] -- this generates a vector for each label, +# where the index of the label is set to `1` and all other entries +# to `0`; in the case of MNIST, there are 10 class labels +trainLabels = np_utils.to_categorical(trainLabels, 10) +testLabels = np_utils.to_categorical(testLabels, 10) + +# initialize the optimizer and model +print("[INFO] compiling model...") +opt = SGD(lr=0.01) +model = LeNet.build(width=28, height=28, depth=1, classes=10, + weightsPath=args["weights"] if args["load_model"] > 0 else None) +model.compile(loss="categorical_crossentropy", optimizer=opt, + metrics=["accuracy"]) + +# only train and evaluate the model if we *are not* loading a +# pre-existing model +if args["load_model"] < 0: + print("[INFO] training...") + model.fit(trainData, trainLabels, batch_size=128, nb_epoch=20, + verbose=1) + + # show the accuracy on the testing set + print("[INFO] evaluating...") + (loss, accuracy) = model.evaluate(testData, testLabels, + batch_size=128, verbose=1) + print("[INFO] accuracy: {:.2f}%".format(accuracy * 100)) + +# check to see if the model should be saved to file +if args["save_model"] > 0: + print("[INFO] dumping weights to file...") + model.save_weights(args["weights"], overwrite=True) + +# randomly select a few testing digits +for i in np.random.choice(np.arange(0, len(testLabels)), size=(10,)): + # classify the digit + probs = model.predict(testData[np.newaxis, i]) + prediction = probs.argmax(axis=1) + + # resize the image from a 28 x 28 image to a 96 x 96 image so we + # can better see it + image = (testData[i][0] * 255).astype("uint8") + image = cv2.merge([image] * 3) + image = cv2.resize(image, (96, 96), interpolation=cv2.INTER_LINEAR) + cv2.putText(image, str(prediction[0]), (5, 20), + cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) + + # show the image and prediction + print("[INFO] Predicted: {}, Actual: {}".format(prediction[0], + np.argmax(testLabels[i]))) + cv2.imshow("Digit", image) + cv2.waitKey(3000) \ No newline at end of file diff --git a/pool/shard006/Python/0058578_resources.py b/pool/shard006/Python/0058578_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..335348d86a73fea7510078f0463434bb722ba4bd --- /dev/null +++ b/pool/shard006/Python/0058578_resources.py @@ -0,0 +1,56 @@ +# coding=utf-8 +"""Resource utilities.""" + +import os +import logging + +import qgis # NOQA pylint: disable=unused-import +from qgis.PyQt import uic + +LOGGER = logging.getLogger('SG-Downloader') + + +def get_ui_class(ui_file): + """Get UI Python class from .ui file. + + Can be filename.ui or subdirectory/filename.ui + + :param ui_file: The file of the ui in safe.gui.ui + :type ui_file: str + """ + os.path.sep.join(ui_file.split('/')) + ui_file_path = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + os.pardir, + 'ui', + ui_file + ) + ) + LOGGER.debug( + 'UI file path %s is exist: %s' % ( + ui_file_path, os.path.exists(ui_file_path))) + return uic.loadUiType(ui_file_path)[0] + + +def resources_path(*args): + """Get the path to our resources folder. + + .. versionadded:: 3.0 + + Note that in version 3.0 we removed the use of Qt Resource files in + favour of directly accessing on-disk resources. + + :param args List of path elements e.g. ['img', 'logos', 'image.png'] + :type args: str + + :return: Absolute path to the resources folder. + :rtype: str + """ + path = os.path.dirname(__file__) + path = os.path.abspath( + os.path.join(path, os.path.pardir, 'resources')) + for item in args: + path = os.path.abspath(os.path.join(path, item)) + + return path diff --git a/pool/shard006/Python/0058584_cmd.py b/pool/shard006/Python/0058584_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5f2d94d1155450e1978b16d394635d6760d1f3 --- /dev/null +++ b/pool/shard006/Python/0058584_cmd.py @@ -0,0 +1,57 @@ +import json +import subprocess +from os import path + + +def _file(f): + return path.join(_base(), '../../{}'.format(f)) + + +def _base(): + return path.dirname(__file__) + + +def _bin(): + c = _file('bin/longhorn') + assert path.exists(c) + return c + + +def snapshot_create(): + cmd = [_bin(), '--debug', 'snapshot', 'create'] + return subprocess.check_output(cmd).strip() + + +def snapshot_rm(name): + cmd = [_bin(), '--debug', 'snapshot', 'rm', name] + subprocess.check_call(cmd) + + +def snapshot_revert(name): + cmd = [_bin(), '--debug', 'snapshot', 'revert', name] + subprocess.check_call(cmd) + + +def snapshot_ls(): + cmd = [_bin(), '--debug', 'snapshot', 'ls'] + return subprocess.check_output(cmd) + + +def backup_create(snapshot, dest): + cmd = [_bin(), '--debug', 'backup', 'create', snapshot, '--dest', dest] + return subprocess.check_output(cmd).strip() + + +def backup_rm(backup): + cmd = [_bin(), '--debug', 'backup', 'rm', backup] + return subprocess.check_call(cmd) + + +def backup_restore(backup): + cmd = [_bin(), '--debug', 'backup', 'restore', backup] + return subprocess.check_output(cmd).strip() + + +def backup_inspect(backup): + cmd = [_bin(), '--debug', 'backup', 'inspect', backup] + return json.loads(subprocess.check_output(cmd)) diff --git a/pool/shard006/Python/0058586_test_jobs.py b/pool/shard006/Python/0058586_test_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..94b5e760cb9ea86387382986d4bc5ae9f9d55665 --- /dev/null +++ b/pool/shard006/Python/0058586_test_jobs.py @@ -0,0 +1,33 @@ +from catkin_tools.jobs.utils import merge_envs + + +def test_merge_envs_basic(): + job_env = { 'PATH': '/usr/local/bin:/usr/bin', 'FOO': 'foo' } + + merge_envs(job_env, [ + { 'PATH': '/usr/local/bin:/bar/baz/bin' }, + { 'BAR': 'bar' } ]) + + # Validate that the known path was not moved from the existing order, and the unfamiliar + # path was correctly prepended. + assert job_env['PATH'] == '/bar/baz/bin:/usr/local/bin:/usr/bin' + + # Confirm that a key only in the original env persists. + assert job_env['FOO'] == 'foo' + + # Confirm that a new key is added. + assert job_env['BAR'] == 'bar' + + +def test_merge_envs_complex(): + ''' Confirm that merged paths are deduplicated and that order is maintained. ''' + job_env = { 'PATH': 'C:B:A' } + merge_envs(job_env, [{ 'PATH': 'D:C' }, { 'PATH': 'E:A:C' }]) + assert job_env['PATH'] == 'E:D:C:B:A', job_env['PATH'] + + +def test_merge_envs_nonpaths(): + ''' Confirm that non-path vars are simply overwritten on a last-wins policy. ''' + job_env = { 'FOO': 'foo:bar' } + merge_envs(job_env, [{ 'FOO': 'bar:baz' }, { 'FOO': 'baz:bar' }]) + assert job_env['FOO'] == 'baz:bar' diff --git a/pool/shard006/Python/0058587_services.py b/pool/shard006/Python/0058587_services.py new file mode 100644 index 0000000000000000000000000000000000000000..924ed7166daab8663088a66d416451d17ef1bd8b --- /dev/null +++ b/pool/shard006/Python/0058587_services.py @@ -0,0 +1,131 @@ +# Copyright (c) 2014 Rackspace, 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 uuid + +from cdn.storage import base + +CQL_CREATE_SERVICE = ''' + INSERT INTO services (service_name, service_id) + VALUES (%s, %s) +''' + +CQL_DELETE_SERVICE = ''' + DELETE FROM services + WHERE service_name = %s +''' + + +class ServicesController(base.ServicesBase): + + def __init__(self, *args, **kwargs): + super(ServicesController, self).__init__(*args, **kwargs) + + self._session = self.driver.service_database + + + def list(self): + services = { + "links": [ + { + "rel": "next", + "href": "/v1.0/services?marker=www.myothersite.com&limit=20" + } + ], + "services" : [ + { + "domains": [ + { + "domain": "www.mywebsite.com" + } + ], + "origins": [ + { + "origin": "mywebsite.com", + "port": 80, + "ssl": False + } + ], + "caching": [ + { "name" : "default", "ttl" : 3600 }, + { + "name" : "home", + "ttl" : 17200, + "rules" : [ + { "name" : "index", "request_url" : "/index.htm" } + ] + }, + { + "name" : "images", + "ttl" : 12800, + "rules" : [ + { "name" : "images", "request_url" : "*.png" } + ] + } + ], + "restrictions" : [ + { + "name" : "website only", + "rules" : [ { "name" : "mywebsite.com", "http_host" : "www.mywebsite.com" } ] + } + ], + "links" : [ + { + "href": "/v1.0/services/mywebsite", + "rel" : "self" + } + ] + } + ] + } + + return services + + def get(self): + # get the requested service from storage + print "get service" + + def create(self, service_name, service_json): + + # create the service in storage + service = service_json + + """Creates a new service""" + args = (service_name, uuid.uuid1()) + res = self._session.execute(CQL_CREATE_SERVICE, args) + + print "stored new record in cassandra" + + + # create at providers + providers = super(ServicesController, self).create(service_name, service) + + return providers + + def update(self, service_name, service_json): + # update configuration in storage + + # update at providers + return super(ServicesController, self).update(service_name, service_json) + + def delete(self, service_name): + # delete local configuration from storage + args = (service_name, ) + res = self._session.execute(CQL_DELETE_SERVICE, args) + + # delete from providers + return super(ServicesController, self).delete(service_name) + + diff --git a/pool/shard006/Python/0058594_0001_initial.py b/pool/shard006/Python/0058594_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..25d0f3492d6b94e57b7a4c3bc32fbf78a7146ac5 --- /dev/null +++ b/pool/shard006/Python/0058594_0001_initial.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.5 on 2016-04-08 18:27 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Client', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=200, unique=True, verbose_name='Name')), + ], + ), + migrations.CreateModel( + name='ProductArea', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=200, unique=True, verbose_name='Name')), + ], + ), + ] diff --git a/pool/shard006/Python/0058596_iasystem.py b/pool/shard006/Python/0058596_iasystem.py new file mode 100644 index 0000000000000000000000000000000000000000..392fbf771ecbfc81353c3d86323f3aec7cfc085f --- /dev/null +++ b/pool/shard006/Python/0058596_iasystem.py @@ -0,0 +1,22 @@ +from django.db import models + + +class Evaluation(models.Model): + section_sln = models.IntegerField(max_length=5) + eval_open_date = models.DateTimeField() + eval_close_date = models.DateTimeField() + is_completed = models.NullBooleanField() + eval_status = models.CharField(max_length=7) + eval_url = models.URLField() + + def __init__(self, *args, **kwargs): + super(Evaluation, self).__init__(*args, **kwargs) + self.instructor_ids = [] + + def __str__(self): + return "{%s: %d, %s: %s, %s: %s, %s: %s, %s: %s}" % ( + "sln", self.section_sln, + "eval_open_date", self.eval_open_date, + "eval_close_date", self.eval_close_date, + "eval_url", self.eval_url, + "is_completed", self.is_completed) diff --git a/pool/shard006/Python/0058599_utils.py b/pool/shard006/Python/0058599_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a46881ae7e7b4776a72acbac976755b1b6b050 --- /dev/null +++ b/pool/shard006/Python/0058599_utils.py @@ -0,0 +1,24 @@ +import os +import re + +from lxml import etree + +from sepaxml import validation + + +def validate_xml(xmlout, schema): + with open(os.path.join(os.path.dirname(validation.__file__), 'schemas', schema + '.xsd'), 'rb') as schema_file: + schema_xml = schema_file.read() + schema_root = etree.XML(schema_xml) + schema = etree.XMLSchema(schema_root) + parser = etree.XMLParser(schema=schema) + xml_root = etree.fromstring(xmlout, parser) + return etree.tostring(xml_root, pretty_print=True) + + +def clean_ids(xmlout): + pat1 = re.compile(b'-[0-9a-f]{12}') + pat2 = re.compile(b'[^<]*') + pat3 = re.compile(b'\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d') + pat4 = re.compile(b'\\d\\d\\d\\d-\\d\\d-\\d\\d') + return pat4.sub(b'0000-00-00', pat3.sub(b'0000-00-00T00:00:00', pat2.sub(b'', pat1.sub(b'-000000000000', xmlout)))) diff --git a/pool/shard006/Python/0058600_platform.py b/pool/shard006/Python/0058600_platform.py new file mode 100644 index 0000000000000000000000000000000000000000..95c8273115af83dbf0ba7a61543f3a11d4253784 --- /dev/null +++ b/pool/shard006/Python/0058600_platform.py @@ -0,0 +1,34 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +from selenium.webdriver.common.by import By + +from pages.base import BasePage +from pages.regions.download_button import DownloadButton +from pages.regions.modal import ModalProtocol + + +class PlatformDownloadPage(BasePage): + + URL_TEMPLATE = '/{locale}/firefox/{slug}/' + + _download_button_locator = (By.ID, 'download-button-desktop-release') + _platforms_modal_link_locator = (By.CLASS_NAME, 'js-platform-modal-button') + _platforms_modal_content_locator = (By.CLASS_NAME, 'mzp-u-modal-content') + + @property + def download_button(self): + el = self.find_element(*self._download_button_locator) + return DownloadButton(self, root=el) + + def download_firefox(self): + self.download_button.click() + from pages.firefox.new.thank_you import ThankYouPage + return ThankYouPage(self.selenium, self.base_url).wait_for_page_to_load() + + def open_other_platforms_modal(self): + modal = ModalProtocol(self) + self.find_element(*self._platforms_modal_link_locator).click() + self.wait.until(lambda s: modal.displays(self._platforms_modal_content_locator)) + return modal diff --git a/pool/shard006/Python/0058601_views.py b/pool/shard006/Python/0058601_views.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb175a9eca1b218f2b7974509aae4d2fdb94474 --- /dev/null +++ b/pool/shard006/Python/0058601_views.py @@ -0,0 +1,130 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2013, Mirantis Inc +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, 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: Tatiana Mazur + + +from django.utils.translation import ugettext_lazy as _ # noqa + +from horizon import exceptions +from horizon import tabs +from horizon import workflows + +import logging + +from openstack_dashboard import api + +from openstack_dashboard.dashboards.project.vpn import tabs as vpn_tabs +from openstack_dashboard.dashboards.project.vpn import \ + workflows as vpn_workflow + +import re + +LOG = logging.getLogger(__name__) + + +class IndexView(tabs.TabbedTableView): + tab_group_class = vpn_tabs.VPNTabs + template_name = 'project/vpn/index.html' + + def post(self, request, *args, **kwargs): + obj_ids = request.POST.getlist('object_ids') + action = request.POST['action'] + m = re.search('.delete([a-z]+)', action).group(1) + if obj_ids == []: + obj_ids.append(re.search('([0-9a-z-]+)$', action).group(1)) + if m == 'vpnservice': + for obj_id in obj_ids: + try: + api.vpn.vpnservice_delete(request, obj_id) + except Exception: + exceptions.handle(request, + _('Unable to delete VPN Service.')) + elif m == 'ikepolicy': + for obj_id in obj_ids: + try: + api.vpn.ikepolicy_delete(request, obj_id) + except Exception: + exceptions.handle(request, + _('Unable to delete IKE Policy.')) + elif m == 'ipsecpolicy': + for obj_id in obj_ids: + try: + api.vpn.ipsecpolicy_delete(request, obj_id) + except Exception: + exceptions.handle(request, + _('Unable to delete IPSec Policy.')) + elif m == 'ipsecsiteconnection': + for obj_id in obj_ids: + try: + api.vpn.ipsecsiteconnection_delete(request, obj_id) + except Exception: + exceptions.handle(request, + _('Unable to delete IPSec Site Connection.')) + + return self.get(request, *args, **kwargs) + + +class AddVPNServiceView(workflows.WorkflowView): + workflow_class = vpn_workflow.AddVPNService + + def get_initial(self): + initial = super(AddVPNServiceView, self).get_initial() + return initial + + +class AddIPSecSiteConnectionView(workflows.WorkflowView): + workflow_class = vpn_workflow.AddIPSecSiteConnection + + def get_initial(self): + initial = super(AddIPSecSiteConnectionView, self).get_initial() + return initial + + +class AddIKEPolicyView(workflows.WorkflowView): + workflow_class = vpn_workflow.AddIKEPolicy + + def get_initial(self): + initial = super(AddIKEPolicyView, self).get_initial() + return initial + + +class AddIPSecPolicyView(workflows.WorkflowView): + workflow_class = vpn_workflow.AddIPSecPolicy + + def get_initial(self): + initial = super(AddIPSecPolicyView, self).get_initial() + return initial + + +class IKEPolicyDetailsView(tabs.TabView): + tab_group_class = (vpn_tabs.IKEPolicyDetailsTabs) + template_name = 'project/vpn/details_tabs.html' + + +class IPSecPolicyDetailsView(tabs.TabView): + tab_group_class = (vpn_tabs.IPSecPolicyDetailsTabs) + template_name = 'project/vpn/details_tabs.html' + + +class VPNServiceDetailsView(tabs.TabView): + tab_group_class = (vpn_tabs.VPNServiceDetailsTabs) + template_name = 'project/vpn/details_tabs.html' + + +class IPSecSiteConnectionDetailsView(tabs.TabView): + tab_group_class = (vpn_tabs.IPSecSiteConnectionDetailsTabs) + template_name = 'project/vpn/details_tabs.html' diff --git a/pool/shard006/Python/0058604_package.py b/pool/shard006/Python/0058604_package.py new file mode 100644 index 0000000000000000000000000000000000000000..5c3f90516771414cd591b2974432c7cfc61aba42 --- /dev/null +++ b/pool/shard006/Python/0058604_package.py @@ -0,0 +1,42 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from spack import * +import glob +import os + + +class Hybpiper(Package): + """HybPiper was designed for targeted sequence capture, in which DNA + sequencing libraries are enriched for gene regions of interest, + especially for phylogenetics. HybPiper is a suite of Python scripts + that wrap and connect bioinformatics tools in order to extract target + sequences from high-throughput DNA sequencing reads""" + + homepage = "https://github.com/mossmatters/HybPiper" + url = "https://github.com/mossmatters/HybPiper/archive/v1.2.0.tar.gz" + git = "https://github.com/mossmatters/HybPiper/HybPiper.git" + + version('1.3.1', sha256='7ca07a9390d1ca52c72721774fa220546f18d3fa3b58500f68f3b2d89dbc0ecf') + version('1.2.0', sha256='34c7b324e9bcacb6ccfe87dc50615d6f93866433b61a59291707efa858b6df57') + + depends_on('python@2.7:', type=('build', 'run')) + depends_on('py-biopython', type=('build', 'run')) + depends_on('exonerate') + depends_on('blast-plus') + depends_on('spades') + depends_on('parallel') + depends_on('bwa') + depends_on('samtools') + + def setup_run_environment(self, env): + env.set('HYBPIPER_HOME', self.prefix) + + def install(self, spec, prefix): + mkdirp(prefix.bin) + files = glob.iglob("*.py") + for file in files: + if os.path.isfile(file): + install(file, prefix.bin) diff --git a/pool/shard006/Python/0058606_oscillateur_harmonique_periode.py b/pool/shard006/Python/0058606_oscillateur_harmonique_periode.py new file mode 100644 index 0000000000000000000000000000000000000000..061d4f7a5ca63b3c64cebba2a7643dd001fb22dd --- /dev/null +++ b/pool/shard006/Python/0058606_oscillateur_harmonique_periode.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- + +import os + +''' +Simple résolution numérique de l'équation d'un oscillateur harmonique pour +illustrer l'isochronisme des oscillations quelle que soit l'amplitude de départ. +''' + +import numpy as np # Pour np.linspace +import scipy as sp # Simple alias usuel +import scipy.integrate # Pour l'intégration +import matplotlib.pyplot as plt # Pour les dessins + +omega0 = 1 # On définit la pulsation propre + + +def equadiff(y, t): + '''Renvoie l'action du système dx/dt = vx et dvx/dt = -omega0**2 * x + soit bien l'oscillateur harmonique x'' + omega0**2 * x = 0''' + x, vx = y # y contient position et vitesse + return [vx, - omega0**2 * x] # On renvoie un doublet pour [dx/dt,dvx/dt] + +nb_CI = 10 # Nombre de conditions initiales explorées + +t = np.linspace(0, 10, 1000) # Le temps total d'intégration +x0 = np.linspace(-5, 5, nb_CI) # Les positions initiales choisies +v0 = [0] * nb_CI # Les vitesses initiales choisies + +for i in range(nb_CI): # Pour chaque condition initiale + # L'intégration proprement dite + sol = sp.integrate.odeint(equadiff, [x0[i], v0[i]], t) + x = sol[:, 0] # Récupération de la position + plt.plot(t, x) # et affichage + +# Il ne reste que le traitement cosmétique + +plt.title('Oscillateur harmonique pour differentes amplitudes initiales') +plt.ylabel('Position (unite arbitraire)') +plt.xlabel('Temps (unite arbitraire)') +plt.savefig('PNG/S01_oscillateur_harmonique_periode.png') + +os.system("pause") diff --git a/pool/shard006/Python/0058608_qqunf.py b/pool/shard006/Python/0058608_qqunf.py new file mode 100644 index 0000000000000000000000000000000000000000..62c9fc4556605560f9e73ff8c39eaf39fb8e60d3 --- /dev/null +++ b/pool/shard006/Python/0058608_qqunf.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python +from __future__ import print_function +from builtins import input +import sys + + +import pmagpy.pmagplotlib as pmagplotlib +import pmagpy.pmag as pmag + +def main(): + """ + NAME + qqunf.py + + DESCRIPTION + makes qq plot from input data against uniform distribution + + SYNTAX + qqunf.py [command line options] + + OPTIONS + -h help message + -f FILE, specify file on command line + + """ + fmt,plot='svg',0 + if '-h' in sys.argv: # check if help is needed + print(main.__doc__) + sys.exit() # graceful quit + elif '-f' in sys.argv: # ask for filename + ind=sys.argv.index('-f') + file=sys.argv[ind+1] + f=open(file,'r') + input=f.readlines() + Data=[] + for line in input: + line.replace('\n','') + if '\t' in line: # read in the data from standard input + rec=line.split('\t') # split each line on space to get records + else: + rec=line.split() # split each line on space to get records + Data.append(float(rec[0])) + +# + if len(Data) >=10: + QQ={'unf1':1} + pmagplotlib.plot_init(QQ['unf1'],5,5) + pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot + else: + print('you need N> 10') + sys.exit() + pmagplotlib.draw_figs(QQ) + files={} + for key in list(QQ.keys()): + files[key]=key+'.'+fmt + if pmagplotlib.isServer: + black = '#000000' + purple = '#800080' + titles={} + titles['eq']='Equal Area Plot' + EQ = pmagplotlib.add_borders(EQ,titles,black,purple) + pmagplotlib.save_plots(QQ,files) + elif plot==1: + files['qq']=file+'.'+fmt + pmagplotlib.save_plots(QQ,files) + else: + ans=input(" S[a]ve to save plot, [q]uit without saving: ") + if ans=="a": pmagplotlib.save_plots(QQ,files) + +if __name__ == "__main__": + main() diff --git a/pool/shard006/Python/0058612_relational_join.py b/pool/shard006/Python/0058612_relational_join.py new file mode 100644 index 0000000000000000000000000000000000000000..bac3173e1daeb33700d63b6d06f3b60d924ca4c1 --- /dev/null +++ b/pool/shard006/Python/0058612_relational_join.py @@ -0,0 +1,39 @@ +import MapReduce +import sys + +""" +Relational join - Sanjeed Schamnad + SELECT * + FROM Orders, LineItem + WHERE Order.order_id = LineItem.order_id +Sample input: +["order", "1", "36901", "O", "173665.47", "1996-01-02", "5-LOW", "Clerk#000000951", "0", "nstructions sleep furiously among "] +["line_item", "1", "63700", "3701", "3", "8", "13309.60", "0.10", "0.02", "N", " +O", "1996-01-29", "1996-03-05", "1996-01-31", "TAKE BACK RETURN", "REG AIR", "ri +ously. regular, express dep"] +The first field indicates what type of record, second field is the order_id. +Combination should have 27 +""" + +mr = MapReduce.MapReduce() + +# ============================= +# Do not modify above this line + +def mapper(record): + order_id = record[1] + mr.emit_intermediate(order_id, record) + +def reducer(key, list_of_values): + length = len(list_of_values) + + for i in range(1,length): + attr_list = [] + attr_list += list_of_values[0] + list_of_values[i] + mr.emit(attr_list) + +# Do not modify below this line +# ============================= +if __name__ == '__main__': + inputdata = open(sys.argv[1]) + mr.execute(inputdata, mapper, reducer) diff --git a/pool/shard006/Python/0058615_ComputeChangedEntries.py b/pool/shard006/Python/0058615_ComputeChangedEntries.py new file mode 100644 index 0000000000000000000000000000000000000000..7497495d38c18ff1fa2d15779b32b1940884a0dc --- /dev/null +++ b/pool/shard006/Python/0058615_ComputeChangedEntries.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +""" +Created on Thu Jul 24 20:53:00 2014 + +@author: mrowe +""" + +import csv +import tldextract +from Record import Record + +cleanedExport = "../data/export_cleaned.csv" + +# Changed entries found in: https://api.blocked.org.uk/data/changes-20141127.csv.gz + +# Transitions to examine: +# 1: Error to ok +# 2: Ok to error + +# Create a list of filter records +recordList = [] + +# Get the export file and read it in as a map between URL and probe tests +print 'Reading in export from the file' +count = 0 +with open(cleanedExport, 'rb') as csvfile: + # tokenise the line by comma delimiter + csvReader = csv.reader(csvfile, delimiter=',', quotechar='"') + for row in csvReader: + # Create a data object and output it + record = Record(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7]) + recordList.append(record) +# print row[0] +# print record + + # Output the count so far + count += 1 + print count + + # Insert a temporary break to test for this +# if(count > 10000): +# break + +# Parse the domains and get the blocks per domain +domainsToBlocksDict = {} +for record in recordList: + # check to see if the record is a block + if record.status == "blocked": + # get the domain of the record + domain = tldextract.extract(record.url) + domain = domain.domain + + # check to see if the dictionary contains the key + if domain in domainsToBlocksDict: + domainsToBlocksDict[domain] += 1 + else: + domainsToBlocksDict[domain] = 1 + +# Write the dictionary to a local file for R to plot +file = open("../data/domainToBlockCount.tsv","w") +file.write("Domain\tBlock.Count\n") +for domain in domainsToBlocksDict: + file.write(domain + "\t" + str(domainsToBlocksDict[domain]) + "\n") +file.close() + + + + + + + + + diff --git a/pool/shard006/Python/0058616_day_of_the_programmer.py b/pool/shard006/Python/0058616_day_of_the_programmer.py new file mode 100644 index 0000000000000000000000000000000000000000..f7846480fa3c8cf060c1fc6d4da9e3847da5a0c4 --- /dev/null +++ b/pool/shard006/Python/0058616_day_of_the_programmer.py @@ -0,0 +1,32 @@ +def julian_is_leap(year): + return year % 4 == 0 + + +def gregorian_is_leap(year): + return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) + + +def solve(year): + month = '09' + day = '13' + + if year <= 1917: + is_leap_year = julian_is_leap(year) + elif year == 1918: + day = '26' + is_leap_year = False + else: + is_leap_year = gregorian_is_leap(year) + + if is_leap_year: + day = '12' + + return '{}.{}.{}'.format( + day, + month, + year, + ) + + +input_year = int(input().strip()) +print(solve(input_year)) diff --git a/pool/shard006/Python/0058618_correlation.py b/pool/shard006/Python/0058618_correlation.py new file mode 100644 index 0000000000000000000000000000000000000000..5147de182bcac985ced550343cd27ae802f5eb16 --- /dev/null +++ b/pool/shard006/Python/0058618_correlation.py @@ -0,0 +1,221 @@ +'''correlation plots + +Author: Josef Perktold +License: BSD-3 + +example for usage with different options in +statsmodels/sandbox/examples/thirdparty/ex_ratereturn.py + +''' +import numpy as np + +from . import utils + + +def plot_corr(dcorr, xnames=None, ynames=None, title=None, normcolor=False, + ax=None, cmap='RdYlBu_r'): + """Plot correlation of many variables in a tight color grid. + + Parameters + ---------- + dcorr : ndarray + Correlation matrix, square 2-D array. + xnames : list[str], optional + Labels for the horizontal axis. If not given (None), then the + matplotlib defaults (integers) are used. If it is an empty list, [], + then no ticks and labels are added. + ynames : list[str], optional + Labels for the vertical axis. Works the same way as `xnames`. + If not given, the same names as for `xnames` are re-used. + title : str, optional + The figure title. If None, the default ('Correlation Matrix') is used. + If ``title=''``, then no title is added. + normcolor : bool or tuple of scalars, optional + If False (default), then the color coding range corresponds to the + range of `dcorr`. If True, then the color range is normalized to + (-1, 1). If this is a tuple of two numbers, then they define the range + for the color bar. + ax : AxesSubplot, optional + If `ax` is None, then a figure is created. If an axis instance is + given, then only the main plot but not the colorbar is created. + cmap : str or Matplotlib Colormap instance, optional + The colormap for the plot. Can be any valid Matplotlib Colormap + instance or name. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> import statsmodels.graphics.api as smg + + >>> hie_data = sm.datasets.randhie.load_pandas() + >>> corr_matrix = np.corrcoef(hie_data.data.T) + >>> smg.plot_corr(corr_matrix, xnames=hie_data.names) + >>> plt.show() + + ..plot :: plots/graphics_correlation_plot_corr.py + """ + if ax is None: + create_colorbar = True + else: + create_colorbar = False + + fig, ax = utils.create_mpl_ax(ax) + + nvars = dcorr.shape[0] + + if ynames is None: + ynames = xnames + if title is None: + title = 'Correlation Matrix' + if isinstance(normcolor, tuple): + vmin, vmax = normcolor + elif normcolor: + vmin, vmax = -1.0, 1.0 + else: + vmin, vmax = None, None + + axim = ax.imshow(dcorr, cmap=cmap, interpolation='nearest', + extent=(0,nvars,0,nvars), vmin=vmin, vmax=vmax) + + # create list of label positions + labelPos = np.arange(0, nvars) + 0.5 + + if isinstance(ynames, list) and len(ynames) == 0: + ax.set_yticks([]) + elif ynames is not None: + ax.set_yticks(labelPos) + ax.set_yticks(labelPos[:-1]+0.5, minor=True) + ax.set_yticklabels(ynames[::-1], fontsize='small', + horizontalalignment='right') + + if isinstance(xnames, list) and len(xnames) == 0: + ax.set_xticks([]) + elif xnames is not None: + ax.set_xticks(labelPos) + ax.set_xticks(labelPos[:-1]+0.5, minor=True) + ax.set_xticklabels(xnames, fontsize='small', rotation=45, + horizontalalignment='right') + + + if not title == '': + ax.set_title(title) + + if create_colorbar: + fig.colorbar(axim, use_gridspec=True) + fig.tight_layout() + + ax.tick_params(which='minor', length=0) + ax.tick_params(direction='out', top=False, right=False) + try: + ax.grid(True, which='minor', linestyle='-', color='w', lw=1) + except AttributeError: + # Seems to fail for axes created with AxesGrid. MPL bug? + pass + + return fig + + +def plot_corr_grid(dcorrs, titles=None, ncols=None, normcolor=False, xnames=None, + ynames=None, fig=None, cmap='RdYlBu_r'): + """ + Create a grid of correlation plots. + + The individual correlation plots are assumed to all have the same + variables, axis labels can be specified only once. + + Parameters + ---------- + dcorrs : list or iterable of ndarrays + List of correlation matrices. + titles : list[str], optional + List of titles for the subplots. By default no title are shown. + ncols : int, optional + Number of columns in the subplot grid. If not given, the number of + columns is determined automatically. + normcolor : bool or tuple, optional + If False (default), then the color coding range corresponds to the + range of `dcorr`. If True, then the color range is normalized to + (-1, 1). If this is a tuple of two numbers, then they define the range + for the color bar. + xnames : list[str], optional + Labels for the horizontal axis. If not given (None), then the + matplotlib defaults (integers) are used. If it is an empty list, [], + then no ticks and labels are added. + ynames : list[str], optional + Labels for the vertical axis. Works the same way as `xnames`. + If not given, the same names as for `xnames` are re-used. + fig : Figure, optional + If given, this figure is simply returned. Otherwise a new figure is + created. + cmap : str or Matplotlib Colormap instance, optional + The colormap for the plot. Can be any valid Matplotlib Colormap + instance or name. + + Returns + ------- + Figure + If `ax` is None, the created figure. Otherwise the figure to which + `ax` is connected. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> import statsmodels.api as sm + + In this example we just reuse the same correlation matrix several times. + Of course in reality one would show a different correlation (measuring a + another type of correlation, for example Pearson (linear) and Spearman, + Kendall (nonlinear) correlations) for the same variables. + + >>> hie_data = sm.datasets.randhie.load_pandas() + >>> corr_matrix = np.corrcoef(hie_data.data.T) + >>> sm.graphics.plot_corr_grid([corr_matrix] * 8, xnames=hie_data.names) + >>> plt.show() + + ..plot :: plots/graphics_correlation_plot_corr_grid.py + """ + if ynames is None: + ynames = xnames + + if not titles: + titles = ['']*len(dcorrs) + + n_plots = len(dcorrs) + if ncols is not None: + nrows = int(np.ceil(n_plots / float(ncols))) + else: + # Determine number of rows and columns, square if possible, otherwise + # prefer a wide (more columns) over a high layout. + if n_plots < 4: + nrows, ncols = 1, n_plots + else: + nrows = int(np.sqrt(n_plots)) + ncols = int(np.ceil(n_plots / float(nrows))) + + # Create a figure with the correct size + aspect = min(ncols / float(nrows), 1.8) + vsize = np.sqrt(nrows) * 5 + fig = utils.create_mpl_fig(fig, figsize=(vsize * aspect + 1, vsize)) + + for i, c in enumerate(dcorrs): + ax = fig.add_subplot(nrows, ncols, i+1) + # Ensure to only plot labels on bottom row and left column + _xnames = xnames if nrows * ncols - (i+1) < ncols else [] + _ynames = ynames if (i+1) % ncols == 1 else [] + plot_corr(c, xnames=_xnames, ynames=_ynames, title=titles[i], + normcolor=normcolor, ax=ax, cmap=cmap) + + # Adjust figure margins and add a colorbar + fig.subplots_adjust(bottom=0.1, left=0.09, right=0.9, top=0.9) + cax = fig.add_axes([0.92, 0.1, 0.025, 0.8]) + fig.colorbar(fig.axes[0].images[0], cax=cax) + + return fig diff --git a/pool/shard006/Python/0058621_SNSConvertToMDTest.py b/pool/shard006/Python/0058621_SNSConvertToMDTest.py new file mode 100644 index 0000000000000000000000000000000000000000..1e5e546227b39ec0d91b10d75064b30d76e45376 --- /dev/null +++ b/pool/shard006/Python/0058621_SNSConvertToMDTest.py @@ -0,0 +1,215 @@ +#pylint: disable=invalid-name,no-init +from __future__ import (absolute_import, division, print_function) +import stresstesting +from mantid.simpleapi import * + +###################################################################### +# Common configuration +# Main data file /SNS/SEQ/IPTS-4783/data +DATA_FILE = "SEQ_11499_event.nxs" +# Vanadium file +VAN_FILE = "SEQ_van.nxs" +# Initial energy guess +E_GUESS = 50 +# Energy bins: Emin, Estep, Emax +E_RANGE = "-10.0,0.2,45.0" +####################################################################### + + +def makeOutputName(ws_name, dohist, doproj): + md_ws_name = ws_name + '_md' + tag="" + if dohist: + tag += "h" + else: + tag += "e" + if doproj: + tag += "wp" + else: + tag += "np" + + md_ws_name += "_" + tag + return md_ws_name + + +def execReduction(dohist, doproj): + # Set the facility + config['default.facility'] = "SNS" + # SPE workspace name + workspace_name = "reduced" + # Run the reduction + DgsReduction(SampleInputFile=DATA_FILE, + IncidentBeamNormalisation="ByCurrent", + OutputWorkspace=workspace_name, + IncidentEnergyGuess=E_GUESS, + EnergyTransferRange=E_RANGE, + SofPhiEIsDistribution=dohist, + DetectorVanadiumInputFile=VAN_FILE, + UseProcessedDetVan=True) + + # Set the goniometer. Add a rotation angle fix as well. + SetGoniometer(Workspace=workspace_name, Axis0="CCR13VRot,0,1,0,1", + Axis1="49.73,0,1,0,1") + + # Set the information for the UB matrix + SetUB(Workspace=workspace_name, + a=3.643, b=3.643, c=5.781, alpha=90, beta=90, gamma=120, + u='1,1,0', v='0,0,1') + + # Create the MDEventWorkspace + md_output_ws = makeOutputName(workspace_name, dohist, doproj) + + if not doproj: + ConvertToMD(InputWorkspace=workspace_name, + OutputWorkspace=md_output_ws, + QDimensions='Q3D', MinValues='-5,-5,-5,-10', + QConversionScales='HKL', + MaxValues='5,5,5,45', MaxRecursionDepth='1') + else: + ConvertToMD(InputWorkspace=workspace_name, + OutputWorkspace=md_output_ws, + QDimensions='Q3D', MinValues='-5,-5,-5,-10', + QConversionScales='HKL', + MaxValues='5,5,5,45', MaxRecursionDepth='1', + Uproj='1,1,0', Vproj='1,-1,0', Wproj='0,0,1') + + # Remove SPE workspace + DeleteWorkspace(Workspace=workspace_name) + + return md_output_ws + + +def validateMD(result,reference,tol=1.e-5,class_name='dummy',mismatchName=None): + """Returns the name of the workspace & file to compare""" + #elf.disableChecking.append('SpectraMap') + #elf.disableChecking.append('Instrument') + + valNames = [result,reference] + + if reference not in mtd: + Load(Filename=reference,OutputWorkspace=valNames[1]) + + checker = AlgorithmManager.create("CompareMDWorkspaces") + checker.setLogging(True) + checker.setPropertyValue("Workspace1",result) + checker.setPropertyValue("Workspace2",valNames[1]) + checker.setPropertyValue("Tolerance", str(tol)) + checker.setPropertyValue("IgnoreBoxID", "1") + checker.setPropertyValue("CheckEvents", "1") + + checker.execute() + if checker.getPropertyValue("Equals") != "1": + print(" Workspaces do not match, result: ",checker.getPropertyValue("Result")) + print(" Test {0} fails".format(class_name)) + if mismatchName: + targetFilename = class_name+mismatchName+'-mismatch.nxs' + else: + targetFilename = class_name+'-mismatch.nxs' + + SaveMD(InputWorkspace=valNames[0],Filename=targetFilename ) + return False + else: + return True + + +class SNSConvertToMDNoHistNoProjTest(stresstesting.MantidStressTest): + truth_file = "SEQ_11499_md_enp.nxs" + output_ws=None + tolerance=0.0 + gold_ws_name ='' + + def requiredMemoryMB(self): + """ Require about 2.5GB free """ + return 2500 + + def requiredFiles(self): + files = [self.truth_file, DATA_FILE] + return files + + def runTest(self): + self.output_ws = execReduction(False, False) + + self.gold_ws_name = self.truth_file.split('.')[0] + "_golden" + LoadMD(self.truth_file, OutputWorkspace=self.gold_ws_name) + + def validate(self): + self.tolerance = 1.0e-1 + return validateMD(self.output_ws, self.gold_ws_name,self.tolerance,self.__class__.__name__) + + +class SNSConvertToMDHistNoProjTest(stresstesting.MantidStressTest): + truth_file = "SEQ_11499_md_hnp.nxs" + output_ws=None + tolerance=0.0 + gold_ws_name ='' + + def requiredMemoryMB(self): + """ Require about 2.5GB free """ + return 2500 + + def requiredFiles(self): + config.appendDataSearchDir("/home/builder/data/SystemTests/AnalysisTests/ReferenceResults/") + files = [self.truth_file, DATA_FILE] + return files + + def runTest(self): + self.output_ws = execReduction(True, False) + + self.gold_ws_name = self.truth_file.split('.')[0] + "_golden" + LoadMD(self.truth_file, OutputWorkspace=self.gold_ws_name) + + def validate(self): + self.tolerance = 1.0e-1 + return validateMD(self.output_ws, self.gold_ws_name,self.tolerance,self.__class__.__name__,self.gold_ws_name) + + +class SNSConvertToMDNoHistProjTest(stresstesting.MantidStressTest): + truth_file = "SEQ_11499_md_ewp.nxs" + output_ws=None + tolerance=0.0 + gold_ws_name ='' + + def requiredMemoryMB(self): + """ Require about 2.5GB free """ + return 2500 + + def requiredFiles(self): + files = [self.truth_file, DATA_FILE] + return files + + def runTest(self): + self.output_ws = execReduction(False, True) + + self.gold_ws_name = self.truth_file.split('.')[0] + "_golden" + LoadMD(self.truth_file, OutputWorkspace=self.gold_ws_name) + + def validate(self): + self.tolerance = 1.0e-3 + return validateMD(self.output_ws, self.gold_ws_name,self.tolerance,self.__class__.__name__,self.gold_ws_name) + #return (self.output_ws, self.gold_ws_name) + + +class SNSConvertToMDHistProjTest(stresstesting.MantidStressTest): + truth_file = "SEQ_11499_md_hwp.nxs" + output_ws=None + tolerance=0.0 + gold_ws_name ='' + + def requiredMemoryMB(self): + """ Require about 2.5GB free """ + return 2500 + + def requiredFiles(self): + files = [self.truth_file, DATA_FILE] + return files + + def runTest(self): + self.output_ws = execReduction(True, True) + + self.gold_ws_name = self.truth_file.split('.')[0] + "_golden" + LoadMD(self.truth_file, OutputWorkspace=self.gold_ws_name) + + def validate(self): + self.tolerance = 1.0e-3 + return validateMD(self.output_ws, self.gold_ws_name,self.tolerance,self.__class__.__name__,self.gold_ws_name) + #return (self.output_ws, self.gold_ws_name) diff --git a/pool/shard006/Python/0058629_castfree.py b/pool/shard006/Python/0058629_castfree.py new file mode 100644 index 0000000000000000000000000000000000000000..51dfd7c767f3d507fd3161fc0ec6b99d0a3a64e2 --- /dev/null +++ b/pool/shard006/Python/0058629_castfree.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- + + +import re,urlparse +from liveresolver.modules import client + +def resolve(url): + try: + try: referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0] + except: referer = url + result = client.request(url, referer = referer) + streamer = re.findall("'streamer',\s*'(.+?)'\);",result)[0] + file = re.findall("'file',\s*'(.+?)'\);",result)[0] + + token = re.findall("'token',\s*'(.+?)'\);",result)[0] + url = streamer +' playpath='+ file + ' swfUrl=http://www.castfree.me/player.swf flashver=WIN\\2019,0,0,226 token='+ token.decode('ascii','ignore') +' live=1 timeout=14 swfVfy=1 pageUrl=' + url + return url + except: + return + diff --git a/pool/shard006/Python/0058631_polarisation_dep_logic.py b/pool/shard006/Python/0058631_polarisation_dep_logic.py new file mode 100644 index 0000000000000000000000000000000000000000..8d2d2342c055fd49b3969a62463f3dcacbac3db9 --- /dev/null +++ b/pool/shard006/Python/0058631_polarisation_dep_logic.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +""" +This file contains the Qudi logic class for performing polarisation dependence measurements. + +Qudi 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. + +Qudi 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 Qudi. If not, see . + +Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the +top-level directory of this distribution and at +""" + +from core.module import Connector +from logic.generic_logic import GenericLogic +from qtpy import QtCore + + +class PolarisationDepLogic(GenericLogic): + """This logic module rotates polarisation and records signal as a function of angle. + + """ + + _modclass = 'polarisationdeplogic' + _modtype = 'logic' + + ## declare connectors + counterlogic = Connector(interface='CounterLogic') + savelogic = Connector(interface='SaveLogic') + motor = Connector(interface='MotorInterface') + + signal_rotation_finished = QtCore.Signal() + signal_start_rotation = QtCore.Signal() + + def on_activate(self): + """ Initialisation performed during activation of the module. + """ + + self._counter_logic = self.get_connector('counterlogic') +# print("Counting device is", self._counting_device) + + self._save_logic = self.get_connector('savelogic') + + self._hwpmotor = self.get_connector('motor') + + # Initialise measurement parameters + self.scan_length = 360 + self.scan_speed = 10 #not yet used + + # Connect signals + self.signal_rotation_finished.connect(self.finish_scan, QtCore.Qt.QueuedConnection) + self.signal_start_rotation.connect(self.rotate_polarisation, QtCore.Qt.QueuedConnection) + + + def on_deactivate(self): + """ Deinitialisation performed during deactivation of the module. + """ + return + + def measure_polarisation_dependence(self): + """Do a simple pol dep measurement. + """ + + # Set up measurement + self._hwpmotor.move_abs(0) + + # configure the countergui + + + self._counter_logic.start_saving() + self.signal_start_rotation.emit() + + def rotate_polarisation(self): + self._hwpmotor.move_rel(self.scan_length) + self.log.info('rotation finished, saving data') + self.signal_rotation_finished.emit() + + def finish_scan(self): + self._counter_logic.save_data() +# self._counter_logic.stopCount() diff --git a/pool/shard006/Python/0058633_commands.py b/pool/shard006/Python/0058633_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..b810dc0097a9238dd88d5242abfe624fdcc92751 --- /dev/null +++ b/pool/shard006/Python/0058633_commands.py @@ -0,0 +1,94 @@ +import sys +import _ast +import ast +from astunparse import unparse +from ASTeditor.editor import globals +from ASTeditor.tui import menu + +def next_child(): + node = globals["node"] + globals["node"] = node.next_child() + +def next_sibling(): + node = globals["node"] + globals["node"] = node.next_sibling() + +def previous_sibling(): + node = globals["node"] + globals["node"] = node.previous_sibling() + +def parent_node(): + globals["node"] = globals["node"].parent or globals["node"] + +def add_ast_node(node): + parent = globals['node'] + parent.node.body.append(node) + parent.build_children() + +def build_function(): + config = menu('name') + name = config['name'] + function = _ast.FunctionDef(name=name, args=[], defaults=[], body=[], decorator_list=[]) + add_ast_node(function) + parent = globals['node'] + for child in parent.children: + if (child.node == function): + globals['node'] = child + break + +def build_pass(): + add_ast_node(_ast.Pass()) + +def build_continue(): + add_ast_node(_ast.Continue()) + +def build_break(): + add_ast_node(_ast.Break()) + +def build_import(): + module = menu('module')['module'] + add_ast_node(_ast.Import(names=[_ast.alias(name=module, asname=None)])) + +def build_if(): + test = menu('test')['test'] + test = ast.parse(test).body[0].value + add_ast_node(_ast.If( + test=test, + body=[], + orelse=[], + )) + +def build_for(): + config = menu("target", "iterable") + target = _ast.Name(id=config["target"]) + iterable = ast.parse(config["iterable"]).body[0].value + add_ast_node(_ast.For( + target=target, + iter=iterable, + body=[], + orelse=[], + )) + + +def build_expr(): + expression = menu('expression')['expression'] + expression = ast.parse(expression).body[0] + add_ast_node(expression) + +def delete_node(): + current = globals["node"] + parent = current.parent + if parent is None: + return + for field in parent.node._fields: + filtered = [node for node in getattr(parent.node, field) if node != current.node] + setattr(parent.node, field, filtered) + parent.build_children() + globals["node"] = parent + + +def save(): + file_name = sys.argv[1] + output = unparse(globals['tree'].node) + with open(file_name, 'w') as file: + file.write(output) diff --git a/pool/shard006/Python/0058634_purpleair-parser.py b/pool/shard006/Python/0058634_purpleair-parser.py new file mode 100644 index 0000000000000000000000000000000000000000..74ab7ab51cfe8efe8a817be838199ca513ba6dad --- /dev/null +++ b/pool/shard006/Python/0058634_purpleair-parser.py @@ -0,0 +1,181 @@ +# purpleair_parser.py +# Custom PurpleAir weather service for RainMachine +# Released under the MIT License +# https://github.com/medmunds/rainmachine-weather-purpleair/LICENSE + +import time +import sys +from math import exp + +from RMParserFramework.rmParser import RMParser +from RMUtilsFramework.rmLogging import log + +import json + + +PROJECT = "rainmachine-weather-purpleair" +VERSION = "0.2" +ABOUT_URL = "https://github.com/medmunds/rainmachine-weather-purpleair" + +log.info("Loaded %s v%s", PROJECT, VERSION) + +# Older RainMachine models (e.g., Mini-8) have outdated root certificates, +# which don't work with https://www.purpleair.com. Fall back to http for them. +USE_HTTPS = sys.version_info >= (2, 7, 12) +if not USE_HTTPS: + log.info("Falling back to http due to outdated platform") + +# Identify ourself when querying PurpleAir's API +USER_AGENT = "{project}/{version} ({about_url})".format(project=PROJECT, version=VERSION, about_url=ABOUT_URL) + + +class PurpleAir(RMParser): + parserName = "PurpleAir Parser" + parserDescription = "Obtain temperature from PurpleAir sensor" + parserForecast = False + parserHistorical = True + parserInterval = 60 * 60 # seconds (no point reporting more than once an hour) + parserDebug = False + purpleAirUrl = "%s://www.purpleair.com/json" % ("https" if USE_HTTPS else "http") + params = { + "sensorId": None, + "keyForPrivateSensor": None, + } + defaultParams = { + "sensorId": None, + "keyForPrivateSensor": None, + } + maxAgeMinutes = 60 # ignore data older than this + + def isEnabledForLocation(self, timezone, lat, long): + return self.parserEnabled + + def perform(self): + sensor_id = self.params.get("sensorId", None) + if not sensor_id: + # TBD: could probably query nearby PurpleAir sensors + # based on self.settings.location.latitude and .longitude + self.lastKnownError = "must set PurpleAir sensorId" + log.error(self.lastKnownError) + return + + api_key = self.params.get("keyForPrivateSensor", None) + + data = self.fetch_sensor_data(sensor_id, api_key) + if data is not None: + cleaned = self.clean_sensor_data(data) + if cleaned is not None: + self.add_sensor_data(cleaned) + + def fetch_sensor_data(self, sensor_id, api_key=None): + params = {"show": sensor_id} + if api_key: + # Key is only required to access private sensors + params["key"] = api_key + response = self.openURL(self.purpleAirUrl, params, headers={"user-agent": USER_AGENT}) + if response is None: + # For errors from urllib2.urlopen, openURL logs the actual error, + # sets lastKnownError to generic "Error: Can not open url", + # and returns None. Improve that error (slightly): + self.lastKnownError = "error querying PurpleAir sensor '%s'; check logs" % sensor_id + log.error(self.lastKnownError) + return None + + body = response.read() + try: + data = json.loads(body) + except ValueError as err: + self.lastKnownError = "error loading json response" + log.exception(self.lastKnownError, exc_info=err) + return None + else: + log.info("data retrieved for sensor %s", sensor_id) + return data + + def clean_sensor_data(self, data): + # For a multi-sensor PurpleAir device, the first result includes temperature, etc. + try: + result = data["results"][0] + except KeyError as err: + self.lastKnownError = "unexpected response format" + log.exception(self.lastKnownError, exc_info=err) + return None + except IndexError: # `{ "results": [] }` + self.lastKnownError = "unknown PurpleAir sensorId" + log.error(self.lastKnownError) + return None + + try: + # https://www2.purpleair.com/community/faq#hc-json-object-fields + timestamp = result["LastSeen"] # "Last seen data time stamp in UTC" + temp_f = float(result["temp_f"]) + humidity = float(result["humidity"]) # 0..100 + pressure_millibars = float(result["pressure"]) + except (KeyError, TypeError, ValueError) as err: + self.lastKnownError = "unexpected response format" + log.exception(self.lastKnownError, exc_info=err) + return None + + # Filter out responses that are too old (e.g., offline sensors). + # (Another approach would be to check result["AGE"], which is in minutes.) + data_age_minutes = (time.time() - timestamp) / 60 + if data_age_minutes > self.maxAgeMinutes: + self.lastKnownError = "ignoring old data (%d minutes)" % data_age_minutes + log.warning(self.lastKnownError) + return None + + # Convert from PurpleAir's to RainMachine's preferred units + temp_c = f_to_c(temp_f) + pressure_kpa = millibars_to_kpa(pressure_millibars) + + temp_c, humidity = self.correct_for_purpleair_heating(temp_c, humidity) + + return { + "timestamp": timestamp, + RMParser.dataType.TEMPERATURE: temp_c, + RMParser.dataType.RH: humidity, + RMParser.dataType.PRESSURE: pressure_kpa, + } + + def add_sensor_data(self, cleaned): + timestamp = cleaned.pop("timestamp") + for data_type, value in cleaned.items(): + self.addValue(data_type, timestamp, value) + log.debug("added '%s': %0.1f at %d" % (data_type, value, timestamp)) + + @staticmethod + def correct_for_purpleair_heating(temp_c_pa, humidity_pa): + """ + Return adjusted temp_c and humidity after correcting + for internal heating caused by PurpleAir's electronics. + """ + # Source: Dr. Peter Jackson of University of Northern British Columbia, based + # on two year colocation study of 150+ Purple Air sensors in Prince George, BC. + # Discussion in PurpleAir community thread: + # https://www.facebook.com/groups/purpleair/posts/722201454903597/?comment_id=722399368217139 + temp_c = temp_c_pa - 5.24 + humidity = (humidity_pa * saturation_vapour_pressure(temp_c_pa) + / saturation_vapour_pressure(temp_c)) + return temp_c, humidity + + +def f_to_c(temp_f): + return (temp_f - 32.0) * 5.0 / 9.0 + + +def millibars_to_kpa(pressure_millibars): + return pressure_millibars / 10.0 + + +def saturation_vapour_pressure(temp_c): + """ + Approximate saturation vapour pressure of liquid water, in kPa, + at the given temperature. + """ + # Buck Equation is accurate across most meteorological temperatures. + # https://en.wikipedia.org/wiki/Arden_Buck_equation + # https://en.wikipedia.org/wiki/Vapour_pressure_of_water#Accuracy_of_different_formulations + return 0.61121 * exp( + (18.678 - (temp_c / 234.5)) * + (temp_c / (257.14 + temp_c)) + ) diff --git a/pool/shard006/Python/0058641_events_parser.py b/pool/shard006/Python/0058641_events_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..5af295045f22769fddec5410fd3122fc9f220209 --- /dev/null +++ b/pool/shard006/Python/0058641_events_parser.py @@ -0,0 +1,155 @@ +import csv +import re + +import markdown + + +# title = models.CharField(max_length=255) +# start_time = models.DateTimeField() +# end_time = models.DateTimeField() +# +# featured_image = models.ForeignKey(MatteImage, null=True, blank=False, on_delete=models.SET_NULL) +# url = models.URLField(blank=True, default='') +# social_facebook = models.URLField(blank=True, default='') +# kicker = models.CharField(max_length=255, default='') +# location_display = models.CharField(max_length=255, default='') +# embargo_until = models.DateTimeField(null=True) +# +# venue = models.ForeignKey(Venue, blank=True, null=True) +# short_description = models.TextField(default='') +# +# is_over_18_only = models.BooleanField(default=False) +# ticket_level = models.CharField(max_length=2, choices=TICKET_LEVEL_CHOICES, default=NA) +# cost = models.CharField(max_length=10, choices=COST_CHOICES, default=NA) +# alcohol = models.CharField(max_length=2, choices=ALCOHOL_CHOICES, default=NOT_ALCOHOL_FOCUSED) +# +# bundle = models.ForeignKey(Bundle, null=True, blank=True) +# category = models.ForeignKey(Category, null=True, blank=True) +# type = models.ForeignKey(Type, null=True, blank=True) +import datetime +import json + + +def parse_time(text): + parts = text.split(':') + mins = 0 + + if len(parts) > 1: + mins = int(parts[1]) + + hour = int(parts[0]) + + return hour, mins + + +def parse_bool(text): + if text.lower() in ['y', 'yes']: + return True + + if text.lower() in ['n', 'no']: + return False + + print(f'WARNING: "{text}" is not a boolean value') + + return False + +def json_serial(obj): + """JSON serializer for objects not serializable by default json code""" + + if isinstance(obj, datetime.datetime): + return obj.isoformat() + raise TypeError ("Type %s not serializable" % type(obj)) + + +available_columns = ( + 'title', + 'body', + 'day', + 'start_time', + 'end_time', + 'short_description', + + 'location', + 'type', + 'categories', + + 'free', + 'is_over_18_only', + + 'contains_loud_music', + 'contains_uneven_ground', + 'has_level_access', + + 'audience_suitable_kids_families', + 'audience_just_for_pgs', + 'audience_good_to_meet_people', + + + 'alcohol_free', + 'alcohol_available', +) + +START_ROW = 8 +METADATA_ROW = 7 + +date_matcher = re.compile("[A-Za-z]+ ([0-9]+)/([0-9]+)") + +with open('2019.csv', 'r+', encoding='utf-8') as f: + reader = csv.reader(f) + parsed_events = [] + + column_map = {} + found_columns = [] + for index, row in enumerate(reader): + def get_row(name): + if name in found_columns: + return row[column_map[name]] + else: + raise IndexError(f'{name} not found in map') + if index == METADATA_ROW: + for col_index, col in enumerate(row): + if col in available_columns: + column_map[col] = col_index + else: + print(col, 'not in av') + found_columns = column_map.keys() + elif index <= START_ROW: + pass + else: + title = get_row('title') + try: + title = get_row('title') + start_day = int(date_matcher.match(get_row('day')).group(1)) + print(start_day) + + start_time_hour, start_time_min = parse_time(get_row('start_time')) + end_time_hour, end_time_min = parse_time(get_row('end_time')) + alcohol_free_event = parse_bool(get_row('alcohol_free')) + alcohol_available = parse_bool(get_row('alcohol_available')) + free_event = parse_bool(get_row('free')) + over_18_only = parse_bool(get_row('is_over_18_only')) + parsed_events.append({ + 'title': title, + 'start_time': datetime.datetime(2019, 9, start_day, start_time_hour, start_time_min), + 'end_time': datetime.datetime(2019, 9, start_day if start_time_hour <= end_time_hour else start_day + 1, end_time_hour, end_time_min), + 'short_description': get_row('short_description'), + 'body': markdown.markdown(get_row('body')), + 'location': get_row('location'), + 'alcohol': 'NO' if alcohol_free_event and not alcohol_available else 'AV' if not alcohol_free_event and alcohol_available else 'NF', + 'cost': 'FREE' if free_event else 'NA', + 'is_over_18_only': over_18_only, + 'type': get_row('type'), + 'categories': [cat.strip() for cat in re.split(r'[:,;]', get_row('categories'))], + 'audience_suitable_kids_families': parse_bool(get_row('audience_suitable_kids_families')), + 'audience_just_for_pgs': parse_bool(get_row('audience_just_for_pgs')), + 'audience_good_to_meet_people': parse_bool(get_row('audience_good_to_meet_people')), + + 'contains_loud_music': parse_bool(get_row('contains_loud_music')), + 'contains_uneven_ground': parse_bool(get_row('contains_uneven_ground')), + 'has_level_access': parse_bool(get_row('has_level_access')), + + }) + except (IndexError, ValueError, AttributeError) as e: + print('failed to parse ', index, title, e) + + print(json.dumps({'events': parsed_events}, default=json_serial)) diff --git a/pool/shard006/Python/0058643_class_inspect.py b/pool/shard006/Python/0058643_class_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..cf444b79aa15b97a71c53cfcd571636b67185312 --- /dev/null +++ b/pool/shard006/Python/0058643_class_inspect.py @@ -0,0 +1,89 @@ +""" Small utilities to inspect classes +""" + +from sklearn.base import BaseEstimator +import inspect + +from .exceptions import AuthorizedException + + +def get_params(cls, instance, ignore=None): + """ Retrieve the initialization parameters corresponding to a class + + This helper function retrieves the parameters of function __init__ for + class 'cls' and returns the value for these parameters in object + 'instance'. When using a composition pattern (e.g. with a NiftiMasker + class), it is useful to forward parameters from one instance to another. + + Parameters + ========== + cls: class + The class that gives us the list of parameters we are interested + in + + instance: object, instance of BaseEstimator + The object that gives us the values of the parameters + + ignore: None or list of strings + Names of the parameters that are not returned. + + Returns + ======= + params: dict + The dict of parameters + """ + + _ignore = set(('memory', 'memory_level', 'verbose', 'copy', 'n_jobs')) + if ignore is not None: + _ignore.update(ignore) + + param_names = cls._get_param_names() + + params = dict() + for param_name in param_names: + if param_name in _ignore: + continue + if hasattr(instance, param_name): + params[param_name] = getattr(instance, param_name) + + return params + + +def enclosing_scope_name(ensure_estimator=True, stack_level=2): + """ Find the name of the enclosing scope for debug output purpose + + Use inspection to climb up the stack until the calling object. This is + typically used to get the estimator at the origin of a functional call + for debug print purpose. + + Parameters + ========== + ensure_estimator: boolean, default: True + If true, find the enclosing object deriving from 'BaseEstimator' + stack_level: integer, default 2 + If ensure_estimator is not True, stack_level quantifies the + number of frame we will go up. + """ + try: + frame = inspect.currentframe() + if not ensure_estimator: + for _ in range(stack_level): + frame = frame.f_back + else: + while True: + frame = frame.f_back + if not 'self' in frame.f_locals: + continue + if not isinstance(frame.f_locals['self'], BaseEstimator): + continue + break + if 'self' in frame.f_locals: + caller_name = frame.f_locals['self'].__class__.__name__ + caller_name = '%s.%s' % (caller_name, + frame.f_code.co_name) + else: + caller_name = frame.f_code.co_name + + return caller_name + except AuthorizedException: + return 'Unknown' diff --git a/pool/shard006/Python/0058646_models.py b/pool/shard006/Python/0058646_models.py new file mode 100644 index 0000000000000000000000000000000000000000..5c349522213880a66a24869c3080410bd63c3178 --- /dev/null +++ b/pool/shard006/Python/0058646_models.py @@ -0,0 +1,271 @@ +import base64 +import logging +import pickle + +try: + from django.utils.timezone import now as datetime_now + datetime_now # workaround for pyflakes +except ImportError: + from datetime import datetime + datetime_now = datetime.now + +from django.core.mail import EmailMessage +from django.db import models +from django.utils.translation import ugettext_lazy as _ + + +PRIORITIES = ( + ("1", "high"), + ("2", "medium"), + ("3", "low"), + ("4", "deferred"), +) + + +class MessageManager(models.Manager): + + def high_priority(self): + """ + the high priority messages in the queue + """ + return self.filter(priority="1") + + def medium_priority(self): + """ + the medium priority messages in the queue + """ + return self.filter(priority="2") + + def low_priority(self): + """ + the low priority messages in the queue + """ + return self.filter(priority="3") + + def non_deferred(self): + """ + the messages in the queue not deferred + """ + return self.filter(priority__lt="4") + + def deferred(self): + """ + the deferred messages in the queue + """ + return self.filter(priority="4") + + def retry_deferred(self, new_priority=2): + count = 0 + for message in self.deferred(): + if message.retry(new_priority): + count += 1 + return count + + +def email_to_db(email): + # pickle.dumps returns essentially binary data which we need to encode + # to store in a unicode field. + return base64.encodestring(pickle.dumps(email)) + + +def db_to_email(data): + if data == u"": + return None + else: + try: + return pickle.loads(base64.decodestring(data.encode("ascii"))) + except Exception: + try: + # previous method was to just do pickle.dumps(val) + return pickle.loads(data.encode("ascii")) + except Exception: + return None + + +class Message(models.Model): + + # The actual data - a pickled EmailMessage + message_data = models.TextField() + when_added = models.DateTimeField(default=datetime_now) + priority = models.CharField(max_length=1, choices=PRIORITIES, default="2") + # @@@ campaign? + # @@@ content_type? + + objects = MessageManager() + + class Meta: + verbose_name = _("message") + verbose_name_plural = _("messages") + + def defer(self): + self.priority = "4" + self.save() + + def retry(self, new_priority=2): + if self.priority == "4": + self.priority = new_priority + self.save() + return True + else: + return False + + def _get_email(self): + return db_to_email(self.message_data) + + def _set_email(self, val): + self.message_data = email_to_db(val) + + email = property(_get_email, _set_email, doc= + """EmailMessage object. If this is mutated, you will need to +set the attribute again to cause the underlying serialised data to be updated.""") + + @property + def to_addresses(self): + email = self.email + if email is not None: + return email.to + else: + return [] + + @property + def subject(self): + email = self.email + if email is not None: + return email.subject + else: + return "" + + +def filter_recipient_list(lst): + if lst is None: + return None + retval = [] + for e in lst: + if DontSendEntry.objects.has_address(e): + logging.info("skipping email to %s as on don't send list " % e.encode("utf-8")) + else: + retval.append(e) + return retval + + +def make_message(subject="", body="", from_email=None, to=None, cc=None, bcc=None, + attachments=None, headers=None, priority=None): + """ + Creates a simple message for the email parameters supplied. + The 'to' and 'bcc' lists are filtered using DontSendEntry. + + If needed, the 'email' attribute can be set to any instance of EmailMessage + if e-mails with attachments etc. need to be supported. + + Call 'save()' on the result when it is ready to be sent, and not before. + """ + to = filter_recipient_list(to) + cc = filter_recipient_list(cc) + bcc = filter_recipient_list(bcc) + core_msg = EmailMessage( + subject=subject, + body=body, + from_email=from_email, + to=to, + cc=cc, + bcc=bcc, + attachments=attachments, + headers=headers + ) + db_msg = Message(priority=priority) + db_msg.email = core_msg + return db_msg + + +class DontSendEntryManager(models.Manager): + + def has_address(self, address): + """ + is the given address on the don't send list? + """ + queryset = self.filter(to_address__iexact=address) + try: + # Django 1.2 + return queryset.exists() + except AttributeError: + # AttributeError: 'QuerySet' object has no attribute 'exists' + return bool(queryset.count()) + + +class DontSendEntry(models.Model): + + to_address = models.EmailField() + when_added = models.DateTimeField() + # @@@ who added? + # @@@ comment field? + + objects = DontSendEntryManager() + + class Meta: + verbose_name = _("don't send entry") + verbose_name_plural = _("don't send entries") + + +RESULT_CODES = ( + ("1", "success"), + ("2", "don't send"), + ("3", "failure"), + # @@@ other types of failure? +) + + +class MessageLogManager(models.Manager): + + def log(self, message, result_code, log_message=""): + """ + create a log entry for an attempt to send the given message and + record the given result and (optionally) a log message + """ + return self.create( + message_data = message.message_data, + when_added = message.when_added, + priority = message.priority, + # @@@ other fields from Message + result = result_code, + log_message = log_message, + ) + + +class MessageLog(models.Model): + + # fields from Message + message_data = models.TextField() + when_added = models.DateTimeField(db_index=True) + priority = models.CharField(max_length=1, choices=PRIORITIES, db_index=True) + # @@@ campaign? + + # additional logging fields + when_attempted = models.DateTimeField(default=datetime_now) + result = models.CharField(max_length=1, choices=RESULT_CODES) + log_message = models.TextField() + + objects = MessageLogManager() + + class Meta: + verbose_name = _("message log") + verbose_name_plural = _("message logs") + + @property + def email(self): + return db_to_email(self.message_data) + + @property + def to_addresses(self): + email = self.email + if email is not None: + return email.to + else: + return [] + + @property + def subject(self): + email = self.email + if email is not None: + return email.subject + else: + return "" diff --git a/pool/shard006/Python/0058654_test-services-organizations.py b/pool/shard006/Python/0058654_test-services-organizations.py new file mode 100644 index 0000000000000000000000000000000000000000..5b899b866b99688b76f00204b73d6559b6271a4a --- /dev/null +++ b/pool/shard006/Python/0058654_test-services-organizations.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- + +from opinel.services.cloudtrail import * +from opinel.utils.aws import connect_service +from opinel.utils.console import configPrintException, printError, printException, printInfo +from opinel.utils.credentials import read_creds, read_creds_from_environment_variables, assume_role + +from opinel.services.organizations import * + +class TestOpinelServicesOrganizations: + + def setup(self): + configPrintException(True) + self.creds = read_creds_from_environment_variables() + if self.creds['AccessKeyId'] == None: + self.creds = read_creds('travislike') + self.org_creds = assume_role('OpinelUnitTest', self.creds,'arn:aws:iam::990492604467:role/OpinelUnitTest', 'opinelunittesting') + self.badapi_client = connect_service('organizations', self.creds, 'us-east-1') + self.api_client = connect_service('organizations', self.org_creds, 'us-east-1') + + + def test_get_children_organizational_units(self): + try: + get_children_organizational_units(self.badapi_client, [{'Id': 'r-6qnh'}]) + except Exception as e: + assert (e.response['Error']['Code'] == 'AccessDeniedException') + ous = get_children_organizational_units(self.api_client, [{'Id': 'r-6qnh'}]) + self.check_ous(ous) + + + def test_get_organization_account_ids(self): + try: + get_organization_account_ids(self.badapi_client) + except Exception as e: + assert (e.response['Error']['Code'] == 'AccessDeniedException') + assert ('990492604467' in get_organization_account_ids(self.api_client)) + assert ('990492604467' not in get_organization_account_ids(self.api_client, exceptions = ['990492604467'])) + get_organization_account_ids(self.api_client, quiet = False) + + + def test_get_organization_accounts(self): + try: + get_organization_accounts(self.badapi_client) + except Exception as e: + assert (e.response['Error']['Code'] == 'AccessDeniedException') + accounts = get_organization_accounts(self.api_client) + self.check_accounts(accounts) + + + def test_get_organizational_units(self): + try: + get_organizational_units(self.badapi_client) + except Exception as e: + assert (e.response['Error']['Code'] == 'AccessDeniedException') + ous = get_organizational_units(self.api_client) + self.check_ous(ous) + + + def test_list_accounts_for_parent(self): + try: + list_accounts_for_parent(self.badapi_client, {'Id': 'r-6qnh'}) + except Exception as e: + assert (e.response['Error']['Code'] == 'AccessDeniedException') + accounts = list_accounts_for_parent(self.api_client, {'Id': 'r-6qnh'}) + self.check_accounts(accounts) + + + def check_accounts(self, accounts): + root_found = False + for account in accounts: + if account['Id'] == '990492604467': + root_found = True + break + assert (root_found) + + def check_ous(self, ous): + ou_found = False + for ou in ous: + if ou['Id'] == 'ou-6qnh-jqod4xev': + ou_found = True + break + assert (ou_found) diff --git a/pool/shard006/Python/0058657_access.py b/pool/shard006/Python/0058657_access.py new file mode 100644 index 0000000000000000000000000000000000000000..44c934de595e2f22bb9a5734b742037e88f5c14b --- /dev/null +++ b/pool/shard006/Python/0058657_access.py @@ -0,0 +1,42 @@ +from collections import namedtuple +import random +import numpy as np + + +Memory = namedtuple("Memory", + ["state", "action", "reward", "done", "next_state"]) + + +class Access(object): + def __init__(self, capacity): + self.capacity = capacity + self.cache = [None] * capacity + self.pointer = 0 + self.length = 0 + + def reset(self): + self.cache = [None] * self.capacity + self.pointer = 0 + self.length = 0 + + def __len__(self): + return self.capacity + + def __call__(self, *args, **kwargs): + self.append(*args) + + def append(self, *args): + self.cache[self.pointer] = Memory(*args) + self.pointer = (self.pointer + 1) % self.capacity + if self.length < self.capacity: + self.length += 1 + elif self.length >= self.capacity: + pass + + def sample(self, batch_size=64): + if self.length < self.capacity: + buffer = zip(*random.sample( + self.cache[:self.length], batch_size)) + else: + buffer = zip(*random.sample(self.cache, batch_size)) + return [np.array(i) for i in buffer] diff --git a/pool/shard006/Python/0058658_challenge.py b/pool/shard006/Python/0058658_challenge.py new file mode 100644 index 0000000000000000000000000000000000000000..4dbf5352a408e9444c144a178b9d58b7fbe0c093 --- /dev/null +++ b/pool/shard006/Python/0058658_challenge.py @@ -0,0 +1,44 @@ +# https://github.com/elmar-hinz/Python.Challenges +from challenges import Challenge + +class HelloGraphChallenge(Challenge): + """ + Given: Two nodes and a list of edges denoting a path + Return: Graph between the nodes and it's weight + """ + + sample = ''' + 2 + 4 + 1->2:2 + 2->3:4 + 3->4:10 + 4->5:8 + 5->6:1 + ''' + + expect = ''' + 2->3->4 + 14 + ''' + + def build(self): + self.model = self.lines_to_graph(start=2) + self.model.start = self.line_to_integer(0) + self.model.stop = self.line_to_integer(1) + + def calc(self): + tail = self.model.start + self.result.path = [tail] + self.result.weight = 0 + while tail != self.model.stop: + # it's a path, just one way to go + head = self.model.edges[tail][0] + self.result.path.append(head) + self.result.weight += self.model.weights[(tail, head)] + tail = head + + def format(self): + self.output = self.format_path(self.result.path) + self.output += self.br + self.output += str(self.result.weight) diff --git a/pool/shard006/Python/0058659_embed.py b/pool/shard006/Python/0058659_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..fd33219e4bcfac84a1a68ed564b9d4656333be51 --- /dev/null +++ b/pool/shard006/Python/0058659_embed.py @@ -0,0 +1,105 @@ +import json +import logging +import time + +import pystache +from authentication import current_org +from flask import current_app, render_template, request, safe_join, send_file +from flask_login import current_user, login_required +from flask_restful import abort +from funcy import project +from redash import models, serializers, settings, utils +from redash.handlers import routes +from redash.handlers.base import (get_object_or_404, org_scoped_rule, + record_event) +from redash.handlers.query_results import collect_query_parameters +from redash.permissions import require_access, view_only +from redash.utils import (collect_parameters_from_request, gen_query_hash, + json_dumps) + + +# +# Run a parameterized query synchronously and return the result +# DISCLAIMER: Temporary solution to support parameters in queries. Should be +# removed once we refactor the query results API endpoints and handling +# on the client side. Please don't reuse in other API handlers. +# +def run_query_sync(data_source, parameter_values, query_text, max_age=0): + query_parameters = set(collect_query_parameters(query_text)) + missing_params = set(query_parameters) - set(parameter_values.keys()) + if missing_params: + raise Exception('Missing parameter value for: {}'.format(", ".join(missing_params))) + + if query_parameters: + query_text = pystache.render(query_text, parameter_values) + + if max_age <= 0: + query_result = None + else: + query_result = models.QueryResult.get_latest(data_source, query_text, max_age) + + query_hash = gen_query_hash(query_text) + + if query_result: + logging.info("Returning cached result for query %s" % query_hash) + return query_result.data + + try: + started_at = time.time() + data, error = data_source.query_runner.run_query(query_text, current_user) + + if error: + return None + # update cache + if max_age > 0: + run_time = time.time() - started_at + query_result, updated_query_ids = models.QueryResult.store_result(data_source.org_id, data_source.id, + query_hash, query_text, data, + run_time, utils.utcnow()) + + models.db.session.commit() + return data + except Exception, e: + if max_age > 0: + abort(404, message="Unable to get result from the database, and no cached query result found.") + else: + abort(503, message="Unable to get result from the database.") + return None + + +@routes.route(org_scoped_rule('/embed//'), methods=['GET']) +def embed(query_token, visualization_id): + query = models.Query.get_by_token(query_token) + # record_event(current_org, current_user._get_current_object(), { + # 'action': 'view', + # 'object_type': 'query', + # 'query_id': query.id, + # 'embed': True, + # 'referer': request.headers.get('Referer') + # }) + + print(request.headers.get('Referer')) + referrer = request.headers.get('Referer') + if not models.VisualizationReferrer.find_by_ids(visualization_id, referrer): + abort(403) + + full_path = safe_join(settings.STATIC_ASSETS_PATHS[-2], 'index.html') + models.db.session.commit() + return send_file(full_path, **dict(cache_timeout=0, conditional=True)) + + +@routes.route(org_scoped_rule('/public/dashboards/'), methods=['GET']) +@login_required +def public_dashboard(token, org_slug=None): + # TODO: bring this back. + # record_event(current_org, current_user, { + # 'action': 'view', + # 'object_id': dashboard.id, + # 'object_type': 'dashboard', + # 'public': True, + # 'headless': 'embed' in request.args, + # 'referer': request.headers.get('Referer') + # }) + # models.db.session.commit() + full_path = safe_join(settings.STATIC_ASSETS_PATHS[-2], 'index.html') + return send_file(full_path, **dict(cache_timeout=0, conditional=True)) diff --git a/pool/shard006/Python/0058662_queue_count.py b/pool/shard006/Python/0058662_queue_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0a14dd1da2425d90260eff647493973df1939c --- /dev/null +++ b/pool/shard006/Python/0058662_queue_count.py @@ -0,0 +1,14 @@ +import pathmagic +from bottle import route +from bottle import request +from bottle import response +from bson.json_util import dumps +from Utils.Functions import number_of_jobs_on_queue + + +@route('/api/v1/queue_count', method='GET') +def task_finished(): + count = (number_of_jobs_on_queue('task_private_vt') + + number_of_jobs_on_queue('task_public_vt') + + number_of_jobs_on_queue('task_no_vt')) + return dumps({"count": count}) diff --git a/pool/shard006/Python/0058668_setup.py b/pool/shard006/Python/0058668_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4e12323cefae4f748d234144e267dbde146f829e --- /dev/null +++ b/pool/shard006/Python/0058668_setup.py @@ -0,0 +1,125 @@ +"""A setuptools based setup module. + +See: +https://packaging.python.org/en/latest/distributing.html +https://github.com/pypa/sampleproject +""" + +# Always prefer setuptools over distutils +from setuptools import setup, find_packages +# To use a consistent encoding +from codecs import open +from os import path + +here = path.abspath(path.dirname(__file__)) + + + +## Trick to use MarkDown, and still supply Pypi with RST +## from: https://stackoverflow.com/a/23265673 +try: + from pypandoc import convert + read_md = lambda f: convert(f, 'rst').replace('\r\n','\n') +except ImportError: + print("warning: pypandoc module not found, could not convert Markdown to RST") + read_md = lambda f: open(f, 'r').read() + + +long_description = read_md(path.join(here, 'README.md')) +print(repr(long_description)) + +setup( + name='subprocess_maximize', + + # Versions should comply with PEP440. For a discussion on single-sourcing + # the version across setup.py and the project code, see + # https://packaging.python.org/en/latest/single_source_version.html + version='0.9.3', + + description='Popen with process-priority and window-state', + long_description=long_description, + + # The project's main homepage. + url='https://github.com/HenkHcks/subprocess_maximize', + + # Author details + author='Henk', + author_email='', + + # Choose your license + license='MIT', + + # See https://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + # How mature is this project? Common values are + # 3 - Alpha + # 4 - Beta + # 5 - Production/Stable + 'Development Status :: 4 - Beta', + + # Indicate who your project is intended for + 'Intended Audience :: Developers', + #'Topic :: Software Development :: Build Tools', + + # Pick your license as you wish (should match "license" above) + 'License :: OSI Approved :: MIT License', + + # Specify the Python versions you support here. In particular, ensure + # that you indicate whether you support Python 2, Python 3 or both. + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + ], + + # What does your project relate to? + keywords='Popen subprocess', + + # You can just specify the packages manually here if your project is + # simple. Or you can use find_packages(). + packages=find_packages(exclude=['contrib', 'docs', 'tests']), + + # Alternatively, if you want to distribute just a my_module.py, uncomment + # this: + # py_modules=["my_module"], + + # List run-time dependencies here. These will be installed by pip when + # your project is installed. For an analysis of "install_requires" vs pip's + # requirements files see: + # https://packaging.python.org/en/latest/requirements.html + #install_requires=['peppercorn'], + + # List additional groups of dependencies here (e.g. development + # dependencies). You can install these using the following syntax, + # for example: + # $ pip install -e .[dev,test] + #extras_require={ + # 'dev': ['check-manifest'], + # 'test': ['coverage'], + #}, + + # If there are data files included in your packages that need to be + # installed, specify them here. If using Python 2.6 or less, then these + # have to be included in MANIFEST.in as well. + #package_data={ + # 'sample': ['package_data.dat'], + #}, + + # Although 'package_data' is the preferred approach, in some case you may + # need to place data files outside of your packages. See: + # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa + # In this case, 'data_file' will be installed into '/my_data' + #data_files=[('my_data', ['data/data_file'])], + + # To provide executable scripts, use entry points in preference to the + # "scripts" keyword. Entry points provide cross-platform support and allow + # pip to create the appropriate form of executable for the target platform. + #entry_points={ + # 'console_scripts': [ + # 'sample=sample:main', + # ], + #}, +) diff --git a/pool/shard006/Python/0058669_t4apply.py b/pool/shard006/Python/0058669_t4apply.py new file mode 100644 index 0000000000000000000000000000000000000000..a71646283baaf9e38cae033cad8e76eb612d676d --- /dev/null +++ b/pool/shard006/Python/0058669_t4apply.py @@ -0,0 +1,46 @@ +#!/usr/bin/python +# Auxiliary functions for exercising python-apply. +######################################################################## +# +# Copyright (C) 2008 Omer Zak. +# 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, in a file named COPYING; if not, write to the +# Free Software Foundation, Inc., 59 Temple Place, Suite 330, +# Boston, MA 02111-1307 USA +# +# For licensing issues, contact . +# +######################################################################## + +def return_args(*args,**kw): + return("positional: %s keywords: %s" % (repr(args),repr(kw))) + +class cl1(object): + def __init__(self,num=1,str="2"): + self.num = num + self.str = str + + def myfunc(self,arg="x"): + return(arg + self.str) + +class cl2(object): + def __init__(self,num=3): + self.num2 = num + self.mycl1 = cl1(10,str="Twenty") + + def cl2func(self,argx="y"): + return(str(self.num2) + argx) + +mainobj = cl2(33) + +# End of t4apply.py diff --git a/pool/shard006/Python/0058670_enumeration.py b/pool/shard006/Python/0058670_enumeration.py new file mode 100644 index 0000000000000000000000000000000000000000..dc6fb98561bade062d0718699418c699434e507f --- /dev/null +++ b/pool/shard006/Python/0058670_enumeration.py @@ -0,0 +1,138 @@ +# Copyright 2004-2008 Roman Yakovenko. +# Distributed under the Boost Software License, Version 1.0. (See +# accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +""" +defines class, that describes C++ enum +""" + +import copy +import types +import compilers +import declaration + +class enumeration_t( declaration.declaration_t ): + """ + describes C++ enum + """ + def __init__( self, name='', values=None ): + """creates class that describes C++ enum declaration + + The items of the list 'values' may either be strings containing + the enumeration value name or tuples (name, numvalue). + + @param name: Enum name + @type name: str + @param parent: Parent declaration + @type parent: declaration_t + @param values: Enumeration values + @type values: list + """ + declaration.declaration_t.__init__( self, name ) + + # A list of tuples (valname(str), valnum(int)). The order of the list should + # be the same as the order in the C/C++ source file. + self._values = [] + + # Initialize values via property access + self.values = values + self._byte_size = 0 + self._byte_align = 0 + + def __eq__(self, other): + if not declaration.declaration_t.__eq__( self, other ): + return False + return self.values == other.values + + def _get__cmp__items( self ): + """implementation details""" + return [self.values] + + def _get_values(self): + return copy.copy(self._values) + def _set_values(self, values): + self._values = [] + # None is treated like an empty list + if (values==None): + return + # Check that we have indeed a list... + if type(values)!=list: + raise ValueError, "'values' must be a list (got a %s instead)"%type(values).__name__ + # Append the items individually. This has the effect that there's + # some additional type checking and that a copy of 'values' is stored + # and the caller cannot further manipulate the list via his own reference + for item in values: + if isinstance(item, types.StringTypes): + self.append_value(item) + elif type(item)==tuple: + name,num = item + self.append_value(name, num) + else: + raise ValueError, "'values' contains an invalid item: %s"%item + values = property( _get_values, _set_values + , doc="""A list of tuples (valname(str), valnum(int)) that contain the enumeration values. + @type: list""") + + def append_value(self, valuename, valuenum=None): + """Append another enumeration value to the enum. + + The numeric value may be None in which case it is automatically determined by + increasing the value of the last item. + + When the 'values' attribute is accessed the resulting list will be in the same + order as append_value() was called. + + @param valuename: The name of the value. + @type valuename: str + @param valuenum: The numeric value or None. + @type valuenum: int + """ + # No number given? Then use the previous one + 1 + if valuenum==None: + if len(self._values)==0: + valuenum = 0 + else: + valuenum = self._values[-1][1]+1 + + # Store the new value + self._values.append((valuename, int(valuenum))) + + def has_value_name(self, name): + """Check if this enum has a particular name among its values. + + @param name: Enumeration value name + @type name: str + @return: True if there is an enumeration value with the given name + """ + for val,num in self._values: + if val==name: + return True + return False + + def get_name2value_dict( self ): + """returns a dictionary, that maps between enum name( key ) and enum value( value )""" + x = {} + for val, num in self._values: + x[val] = num + return x + + def i_depend_on_them( self, recursive=True ): + return [] + + def _get_byte_size(self): + return self._byte_size + def _set_byte_size( self, new_byte_size ): + self._byte_size = new_byte_size + byte_size = property( _get_byte_size, _set_byte_size + , doc="Size of this class in bytes @type: int") + + def _get_byte_align(self): + if self.compiler == compilers.MSVC_PDB_9: + compilers.on_missing_functionality( self.compiler, "byte align" ) + return self._byte_align + def _set_byte_align( self, new_byte_align ): + self._byte_align = new_byte_align + byte_align = property( _get_byte_align, _set_byte_align + , doc="Alignment of this class in bytes @type: int") + diff --git a/pool/shard006/Python/0058673_command_injection.py b/pool/shard006/Python/0058673_command_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..88aa0f629a50e2dbe1cf677e54a306dc63cb2eab --- /dev/null +++ b/pool/shard006/Python/0058673_command_injection.py @@ -0,0 +1,27 @@ +from flask_wtf import Form +from wtforms.fields import SubmitField, StringField +import subprocess +import os + + +class Grocery(Form): + grocery_name = StringField('Grocery') + add_grocery = SubmitField('Add Grocery') + reset_groceries = SubmitField('Reset Groceries') + + +def save_grocery(grocery_name): + command = 'echo ' + grocery_name + ' >> ' + ' groceries.txt' + subprocess.call(command, shell=True) + +def get_groceries(): + filename = 'groceries.txt' + if os.path.isfile(filename): + with open(filename, 'r') as fd: + for line in fd: + yield line + +def reset_groceries(): + filename = 'groceries.txt' + if os.path.isfile(filename): + os.remove(filename) diff --git a/pool/shard006/Python/0058677_init__.py b/pool/shard006/Python/0058677_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2eda4f5c78f1c1f9dd380ceea2ebb8973590b3ce --- /dev/null +++ b/pool/shard006/Python/0058677_init__.py @@ -0,0 +1,60 @@ +# Copyright (c) 2014 by Ecreall under licence AGPL terms +# available on http://www.gnu.org/licenses/agpl.html + +# licence: AGPL +# author: Amen Souissi +import xlrd + + +SEPARATOR = ',' + +TRUE_VALUE = 'true' + +def toInteger(value): + return int(str(value).strip()) + + +def toBoolean(value): + return str(value).strip() == TRUE_VALUE + + +def toString(value): + return str(value).strip() + + +def toStrings(value): + return [a.strip() for a in str(value).split(SEPARATOR) if a.strip()] + + +transformation_rols = {("String", False): toString, + ("String", True): toStrings, + ("Integer", False): toInteger, + ("Boolean", False): toBoolean} + + +# properties = {'at1':('Type', Multiplicity),...} +def get_data_from_xl(file, properties): + book = xlrd.open_workbook(file_contents=file.fp.read()) + sheet = book.sheet_by_index(0)# or: sheet_by_name("Ma feuille") + header = [] + for col_index in range(sheet.ncols): + value = sheet.cell(rowx=0, colx=col_index).value + header.append(value) + + data = [] + properties_keys = dict([(k.lower(), k) for k in properties.keys()]) + for row_index in range(sheet.nrows)[1:]: + appstruct = {} + for col_index in range(sheet.ncols): + value = sheet.cell(rowx=row_index, colx=col_index).value + key = header[col_index].lower() + if key in properties_keys: + metadata = properties[key] + property_type = metadata[0] + multiplicity = metadata[1] + value = transformation_rols[(property_type, multiplicity)](value) + appstruct[properties_keys[key]] = value + + data.append(appstruct) + + return data diff --git a/pool/shard006/Python/0058678_legendgrouptitle.py b/pool/shard006/Python/0058678_legendgrouptitle.py new file mode 100644 index 0000000000000000000000000000000000000000..fc24c6acaa8e6e43a0caf7cee61f73f2572d9422 --- /dev/null +++ b/pool/shard006/Python/0058678_legendgrouptitle.py @@ -0,0 +1,154 @@ +from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType +import copy as _copy + + +class Legendgrouptitle(_BaseTraceHierarchyType): + + # class properties + # -------------------- + _parent_path_str = "icicle" + _path_str = "icicle.legendgrouptitle" + _valid_props = {"font", "text"} + + # font + # ---- + @property + def font(self): + """ + Sets this legend group's title font. + + The 'font' property is an instance of Font + that may be specified as: + - An instance of :class:`plotly.graph_objs.icicle.legendgrouptitle.Font` + - A dict of string/value properties that will be passed + to the Font constructor + + Supported dict properties: + + color + + family + HTML font family - the typeface that will be + applied by the web browser. The web browser + will only be able to apply a font if it is + available on the system which it operates. + Provide multiple font families, separated by + commas, to indicate the preference in which to + apply fonts if they aren't available on the + system. The Chart Studio Cloud (at + https://chart-studio.plotly.com or on-premise) + generates images on a server, where only a + select number of fonts are installed and + supported. These include "Arial", "Balto", + "Courier New", "Droid Sans",, "Droid Serif", + "Droid Sans Mono", "Gravitas One", "Old + Standard TT", "Open Sans", "Overpass", "PT Sans + Narrow", "Raleway", "Times New Roman". + size + + Returns + ------- + plotly.graph_objs.icicle.legendgrouptitle.Font + """ + return self["font"] + + @font.setter + def font(self, val): + self["font"] = val + + # text + # ---- + @property + def text(self): + """ + Sets the title of the legend group. + + The 'text' property is a string and must be specified as: + - A string + - A number that will be converted to a string + + Returns + ------- + str + """ + return self["text"] + + @text.setter + def text(self, val): + self["text"] = val + + # Self properties description + # --------------------------- + @property + def _prop_descriptions(self): + return """\ + font + Sets this legend group's title font. + text + Sets the title of the legend group. + """ + + def __init__(self, arg=None, font=None, text=None, **kwargs): + """ + Construct a new Legendgrouptitle object + + Parameters + ---------- + arg + dict of properties compatible with this constructor or + an instance of + :class:`plotly.graph_objs.icicle.Legendgrouptitle` + font + Sets this legend group's title font. + text + Sets the title of the legend group. + + Returns + ------- + Legendgrouptitle + """ + super(Legendgrouptitle, self).__init__("legendgrouptitle") + + if "_parent" in kwargs: + self._parent = kwargs["_parent"] + return + + # Validate arg + # ------------ + if arg is None: + arg = {} + elif isinstance(arg, self.__class__): + arg = arg.to_plotly_json() + elif isinstance(arg, dict): + arg = _copy.copy(arg) + else: + raise ValueError( + """\ +The first argument to the plotly.graph_objs.icicle.Legendgrouptitle +constructor must be a dict or +an instance of :class:`plotly.graph_objs.icicle.Legendgrouptitle`""" + ) + + # Handle skip_invalid + # ------------------- + self._skip_invalid = kwargs.pop("skip_invalid", False) + self._validate = kwargs.pop("_validate", True) + + # Populate data dict with properties + # ---------------------------------- + _v = arg.pop("font", None) + _v = font if font is not None else _v + if _v is not None: + self["font"] = _v + _v = arg.pop("text", None) + _v = text if text is not None else _v + if _v is not None: + self["text"] = _v + + # Process unknown kwargs + # ---------------------- + self._process_kwargs(**dict(arg, **kwargs)) + + # Reset skip_invalid + # ------------------ + self._skip_invalid = False diff --git a/pool/shard006/Python/0058680_settings.py b/pool/shard006/Python/0058680_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..f924a7fcf029cb002bfcac2ebac15b34c91cd7c5 --- /dev/null +++ b/pool/shard006/Python/0058680_settings.py @@ -0,0 +1,31 @@ +# +# 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 horizon.test.settings import * # noqa +from openstack_dashboard.test.settings import * # noqa + +INSTALLED_APPS = list(INSTALLED_APPS) +INSTALLED_APPS.append('trove_dashboard.content.database_backups') +INSTALLED_APPS.append('trove_dashboard.content.database_clusters') +INSTALLED_APPS.append('trove_dashboard.content.database_configurations') +INSTALLED_APPS.append('trove_dashboard.content.databases') + +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + 'OPTIONS': { + 'MAX_ENTRIES': 1200, + 'CULL_FREQUENCY': 20 + } + } +} diff --git a/pool/shard006/Python/0058687_admin.py b/pool/shard006/Python/0058687_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea084b699ae178fe089a659821f05766de08322 --- /dev/null +++ b/pool/shard006/Python/0058687_admin.py @@ -0,0 +1,69 @@ +from django.conf.urls import url +from django.contrib import admin +from django.core.urlresolvers import reverse +from django.forms import ModelForm +from django.http import HttpResponseRedirect + +from livinglots import get_owner_contact_model + +from .admin_views import MakeAliasesView +from .models import Alias + + +class OwnerAdminMixin(object): + actions = ('make_aliases',) + + def aliases_summary(self, obj): + return ', '.join(obj.aliases.all().values_list('name', flat=True)) + aliases_summary.short_description = 'AKA' + + def make_aliases(self, request, queryset): + ids = queryset.values_list('pk', flat=True) + ids = [str(id) for id in ids] + return HttpResponseRedirect(reverse('admin:owners_owner_make_aliases') + + '?ids=%s' % (','.join(ids))) + + def get_urls(self): + opts = self.model._meta + app_label, object_name = (opts.app_label, opts.object_name.lower()) + prefix = "%s_%s" % (app_label, object_name) + + urls = super(OwnerAdminMixin, self).get_urls() + my_urls = [ + url(r'^make-aliases/', MakeAliasesView.as_view(), + name='%s_make_aliases' % prefix), + ] + return my_urls + urls + + +class BaseOwnerForm(ModelForm): + def __init__(self, *args, **kwargs): + super(BaseOwnerForm, self).__init__(*args, **kwargs) + self.fields['default_contact'].queryset = \ + get_owner_contact_model().objects.filter(owner=self.instance) + + +class BaseOwnerAdmin(OwnerAdminMixin, admin.ModelAdmin): + form = BaseOwnerForm + list_display = ('name', 'owner_type', 'aliases_summary',) + list_filter = ('owner_type',) + search_fields = ('name',) + + +class BaseOwnerContactAdmin(admin.ModelAdmin): + list_display = ('name', 'owner', 'phone', 'email',) + list_filter = ('owner__owner_type',) + search_fields = ('name', 'owner', 'email',) + + +class BaseOwnerGroupAdmin(admin.ModelAdmin): + list_display = ('name', 'owner_type',) + list_filter = ('owner_type',) + search_fields = ('name',) + + +class AliasAdmin(admin.ModelAdmin): + list_display = ('name',) + + +admin.site.register(Alias, AliasAdmin) diff --git a/pool/shard006/Python/0058691_html2text.py b/pool/shard006/Python/0058691_html2text.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc1474142df6f0a777e950ea514a1a161065bfe --- /dev/null +++ b/pool/shard006/Python/0058691_html2text.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +# Copyright (c) 2008-11 Qtrac Ltd. All rights reserved. +# This program or module 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. It is provided for educational +# purposes and 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. + +import html.entities +import os +import re +import sys + + +def main(): + if len(sys.argv) > 1 and sys.argv[1] in {"-h", "--help"}: + print("""usage: {0} [infile] [outfile] +if no files are specified reads stdin and writes to stdout; +if one file is specified reads it and writes to stdout; +if both files are specified reads the first and writes to the second +""".format(os.path.basename(sys.argv[0]))) + sys.exit(2) + + fin, fout = (sys.stdin, sys.stdout) + close_in, close_out = (False, False) + if len(sys.argv) > 1: + fin = open(sys.argv[1], encoding="utf8") + close_in = True + if len(sys.argv) > 2: + fout = open(sys.argv[2], "w", encoding="utf8") + close_out = True + html_text = fin.read() + if close_in: + fin.close() + fout.write(html2text(html_text)) + if close_out: + fout.close() + else: + print() + + +def html2text(html_text): + def char_from_entity(match): + code = html.entities.name2codepoint.get(match.group(1), 0xFFFD) + return chr(code) + + text = re.sub(r"", "", html_text) #1 + text = re.sub(r"<[Pp][^>]*?>", "\n\n", text) #2 + text = re.sub(r"<[^>]*?>", "", text) #3 + text = re.sub(r"&#(\d+);", lambda m: chr(int(m.group(1))), text) + text = re.sub(r"&([A-Za-z]+);", char_from_entity, text) #5 + text = re.sub(r"\n(?:[ \xA0\t]+\n)+", "\n", text) #6 + return re.sub(r"\n\n+", "\n\n", text.strip()) #7 + + +main() diff --git a/pool/shard006/Python/0058704_mock.py b/pool/shard006/Python/0058704_mock.py new file mode 100644 index 0000000000000000000000000000000000000000..9b119221fff46228bdcf97a9b0a6cdd84ac53dfa --- /dev/null +++ b/pool/shard006/Python/0058704_mock.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- + +"""Mock Kwik files.""" + +#------------------------------------------------------------------------------ +# Imports +#------------------------------------------------------------------------------ + +import os.path as op + +import numpy as np +import numpy.random as nr + +from .mea import staggered_positions +from .h5 import open_h5 +from .model import _create_clustering + + +#------------------------------------------------------------------------------ +# Mock functions +#------------------------------------------------------------------------------ + +def artificial_waveforms(n_spikes=None, n_samples=None, n_channels=None): + # TODO: more realistic waveforms. + return .25 * nr.normal(size=(n_spikes, n_samples, n_channels)) + + +def artificial_features(*args): + return .25 * nr.normal(size=args) + + +def artificial_masks(n_spikes=None, n_channels=None): + masks = nr.uniform(size=(n_spikes, n_channels)) + masks[masks < .25] = 0 + return masks + + +def artificial_traces(n_samples, n_channels): + # TODO: more realistic traces. + return .25 * nr.normal(size=(n_samples, n_channels)) + + +def artificial_spike_clusters(n_spikes, n_clusters, low=0): + return nr.randint(size=n_spikes, low=low, high=max(1, n_clusters)) + + +def artificial_spike_samples(n_spikes, max_isi=50): + return np.cumsum(nr.randint(low=0, high=max_isi, size=n_spikes)) + + +def artificial_correlograms(n_clusters, n_samples): + return nr.uniform(size=(n_clusters, n_clusters, n_samples)) + + +def mock_prm(dat_path): + return dict( + prb_file='1x32_buzsaki', + traces=dict( + raw_data_files=[dat_path, dat_path], + voltage_gain=10., + sample_rate=20000, + n_channels=32, + dtype='int16', + ), + spikedetekt={ + 'n_features_per_channel': 4, + }, + klustakwik2={}, + ) + + +#------------------------------------------------------------------------------ +# Mock Kwik file +#------------------------------------------------------------------------------ + +def create_mock_kwik(dir_path, n_clusters=None, n_spikes=None, + n_channels=None, n_features_per_channel=None, + n_samples_traces=None, + with_kwx=True, + with_kwd=True, + add_original=True, + ): + """Create a test kwik file.""" + filename = op.join(dir_path, '_test.kwik') + kwx_filename = op.join(dir_path, '_test.kwx') + kwd_filename = op.join(dir_path, '_test.raw.kwd') + + # Create the kwik file. + with open_h5(filename, 'w') as f: + f.write_attr('/', 'kwik_version', 2) + + def _write_metadata(key, value): + f.write_attr('/application_data/spikedetekt', key, value) + + _write_metadata('sample_rate', 20000.) + + # Filter parameters. + _write_metadata('filter_low', 500.) + _write_metadata('filter_high_factor', 0.95 * .5) + _write_metadata('filter_butter_order', 3) + + _write_metadata('extract_s_before', 15) + _write_metadata('extract_s_after', 25) + + _write_metadata('n_features_per_channel', n_features_per_channel) + + # Create spike times. + spike_samples = artificial_spike_samples(n_spikes).astype(np.int64) + spike_recordings = np.zeros(n_spikes, dtype=np.uint16) + # Size of the first recording. + recording_size = 2 * n_spikes // 3 + if recording_size > 0: + # Find the recording offset. + recording_offset = spike_samples[recording_size] + recording_offset += spike_samples[recording_size + 1] + recording_offset //= 2 + spike_recordings[recording_size:] = 1 + # Make sure the spike samples of the second recording start over. + spike_samples[recording_size:] -= spike_samples[recording_size] + spike_samples[recording_size:] += 10 + else: + recording_offset = 1 + + if spike_samples.max() >= n_samples_traces: + raise ValueError("There are too many spikes: decrease 'n_spikes'.") + + f.write('/channel_groups/1/spikes/time_samples', spike_samples) + f.write('/channel_groups/1/spikes/recording', spike_recordings) + f.write_attr('/channel_groups/1', 'channel_order', + np.arange(1, n_channels - 1)[::-1]) + graph = np.array([[1, 2], [2, 3]]) + f.write_attr('/channel_groups/1', 'adjacency_graph', graph) + + # Create channels. + positions = staggered_positions(n_channels) + for channel in range(n_channels): + group = '/channel_groups/1/channels/{0:d}'.format(channel) + f.write_attr(group, 'name', str(channel)) + f.write_attr(group, 'position', positions[channel]) + + # Create spike clusters. + clusterings = [('main', n_clusters)] + if add_original: + clusterings += [('original', n_clusters * 2)] + for clustering, n_clusters_rec in clusterings: + spike_clusters = artificial_spike_clusters(n_spikes, + n_clusters_rec) + groups = {0: 0, 1: 1, 2: 2} + _create_clustering(f, clustering, 1, spike_clusters, groups) + + # Create recordings. + f.write_attr('/recordings/0', 'name', 'recording_0') + f.write_attr('/recordings/1', 'name', 'recording_1') + + f.write_attr('/recordings/0/raw', 'hdf5_path', kwd_filename) + f.write_attr('/recordings/1/raw', 'hdf5_path', kwd_filename) + + # Create the kwx file. + if with_kwx: + with open_h5(kwx_filename, 'w') as f: + f.write_attr('/', 'kwik_version', 2) + features = artificial_features(n_spikes, + (n_channels - 2) * + n_features_per_channel) + masks = artificial_masks(n_spikes, + (n_channels - 2) * + n_features_per_channel) + fm = np.dstack((features, masks)).astype(np.float32) + f.write('/channel_groups/1/features_masks', fm) + + # Create the raw kwd file. + if with_kwd: + with open_h5(kwd_filename, 'w') as f: + f.write_attr('/', 'kwik_version', 2) + traces = artificial_traces(n_samples_traces, n_channels) + # TODO: int16 traces + f.write('/recordings/0/data', + traces[:recording_offset, ...].astype(np.float32)) + f.write('/recordings/1/data', + traces[recording_offset:, ...].astype(np.float32)) + + return filename diff --git a/pool/shard006/Python/0058708_mockserver.py b/pool/shard006/Python/0058708_mockserver.py new file mode 100644 index 0000000000000000000000000000000000000000..26ab51183ddff170307fb28dc2651766138b7488 --- /dev/null +++ b/pool/shard006/Python/0058708_mockserver.py @@ -0,0 +1,222 @@ +from __future__ import print_function +import sys, time, random, os, json +from six.moves.urllib.parse import urlencode +from subprocess import Popen, PIPE + +from twisted.web.server import Site, NOT_DONE_YET +from twisted.web.resource import Resource +from twisted.web.static import File +from twisted.web.test.test_webclient import PayloadResource +from twisted.web.server import GzipEncoderFactory +from twisted.web.resource import EncodingResourceWrapper +from twisted.web.util import redirectTo +from twisted.internet import reactor, ssl +from twisted.internet.task import deferLater + + +from scrapy.utils.python import to_bytes, to_unicode +from tests import tests_datadir + + +def getarg(request, name, default=None, type=None): + if name in request.args: + value = request.args[name][0] + if type is not None: + value = type(value) + return value + else: + return default + + +class LeafResource(Resource): + + isLeaf = True + + def deferRequest(self, request, delay, f, *a, **kw): + def _cancelrequest(_): + # silence CancelledError + d.addErrback(lambda _: None) + d.cancel() + + d = deferLater(reactor, delay, f, *a, **kw) + request.notifyFinish().addErrback(_cancelrequest) + return d + + +class Follow(LeafResource): + + def render(self, request): + total = getarg(request, b"total", 100, type=int) + show = getarg(request, b"show", 1, type=int) + order = getarg(request, b"order", b"desc") + maxlatency = getarg(request, b"maxlatency", 0, type=float) + n = getarg(request, b"n", total, type=int) + if order == b"rand": + nlist = [random.randint(1, total) for _ in range(show)] + else: # order == "desc" + nlist = range(n, max(n - show, 0), -1) + + lag = random.random() * maxlatency + self.deferRequest(request, lag, self.renderRequest, request, nlist) + return NOT_DONE_YET + + def renderRequest(self, request, nlist): + s = """ """ + args = request.args.copy() + for nl in nlist: + args[b"n"] = [to_bytes(str(nl))] + argstr = urlencode(args, doseq=True) + s += "
follow %d
" % (argstr, nl) + s += """""" + request.write(to_bytes(s)) + request.finish() + + +class Delay(LeafResource): + + def render_GET(self, request): + n = getarg(request, b"n", 1, type=float) + b = getarg(request, b"b", 1, type=int) + if b: + # send headers now and delay body + request.write('') + self.deferRequest(request, n, self._delayedRender, request, n) + return NOT_DONE_YET + + def _delayedRender(self, request, n): + request.write(to_bytes("Response delayed for %0.3f seconds\n" % n)) + request.finish() + + +class Status(LeafResource): + + def render_GET(self, request): + n = getarg(request, b"n", 200, type=int) + request.setResponseCode(n) + return b"" + + +class Raw(LeafResource): + + def render_GET(self, request): + request.startedWriting = 1 + self.deferRequest(request, 0, self._delayedRender, request) + return NOT_DONE_YET + render_POST = render_GET + + def _delayedRender(self, request): + raw = getarg(request, b'raw', b'HTTP 1.1 200 OK\n') + request.startedWriting = 1 + request.write(raw) + request.channel.transport.loseConnection() + request.finish() + + +class Echo(LeafResource): + + def render_GET(self, request): + output = { + 'headers': dict( + (to_unicode(k), [to_unicode(v) for v in vs]) + for k, vs in request.requestHeaders.getAllRawHeaders()), + 'body': to_unicode(request.content.read()), + } + return to_bytes(json.dumps(output)) + + +class RedirectTo(LeafResource): + + def render(self, request): + goto = getarg(request, b'goto', b'/') + # we force the body content, otherwise Twisted redirectTo() + # returns HTML with +# +############################################################################### +# Copyright (c) 2009, Even Rouault +# +# 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 sys + +sys.path.append( '../pymod' ) + +import gdaltest + +############################################################################### +# Test reading a - fake - JDEM dataset + +def jdem_1(): + + tst = gdaltest.GDALTest( 'JDEM', 'fakejdem.mem', 1, 15 ) + return tst.testOpen() + +gdaltest_list = [ + jdem_1 ] + +if __name__ == '__main__': + + gdaltest.setup_run( 'jdem' ) + + gdaltest.run_tests( gdaltest_list ) + + gdaltest.summarize() + diff --git a/pool/shard006/Python/0058710_container.py b/pool/shard006/Python/0058710_container.py new file mode 100644 index 0000000000000000000000000000000000000000..8adbd41c28d5c4b9c8aea62dd8cdb4ed3ad01bd3 --- /dev/null +++ b/pool/shard006/Python/0058710_container.py @@ -0,0 +1,80 @@ +from flask import _app_ctx_stack + + +class ContainerState(object): + def __init__(self, app, callback, options): + self.app = app + self.instance = callback(app, options) + + def __getattr__(self, name): + return getattr(self.instance, name) + + +class ContainerMethod(object): + """ + Proxies a method to an extension allowing us to bind the result + to the correct application state. + """ + def __init__(self, ext, name): + self.ext = ext + self.name = name + + def __call__(self, *args, **kwargs): + state = self.ext.get_state() + return getattr(state, self.name)(*args, **kwargs) + + +class Container(object): + """ + Creates an extension container for app-bound execution of an object. + + >>> redis = Container( + >>> lambda app, kwargs: redis.StrictClient(**kwargs), + >>> {'host': 'localhost'}) + """ + def __init__(self, callback, options=None, name=None): + self.callback = callback + self.options = options or {} + self.ident = name or id(self) + self.app = None + + def __getattr__(self, name): + state = self.get_state() + attr = getattr(state, name) + if callable(attr): + method = ContainerMethod(self, name) + method.__name__ = name + method.__doc__ = name.__doc__ + return method + return attr + + def init_app(self, app): + self.app = app + if not hasattr(app, 'extensions'): + app.extensions = {} + app.extensions[self.ident] = ContainerState( + app=app, + callback=self.callback, + options=self.options, + ) + + def get_state(self, app=None): + """Gets the state for the application""" + if app is None: + app = self.get_app() + assert self.ident in app.extensions, \ + 'The extension was not registered to the current ' \ + 'application. Please make sure to call init_app() first.' + return app.extensions[self.ident] + + def get_app(self, reference_app=None): + if reference_app is not None: + return reference_app + if self.app is not None: + return self.app + ctx = _app_ctx_stack.top + if ctx is not None: + return ctx.app + raise RuntimeError('application not registered on ' + 'instance and no application bound ' + 'to current context') diff --git a/pool/shard006/Python/0058722_ivy_task_mixin.py b/pool/shard006/Python/0058722_ivy_task_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..48dda45c87025d79bc319cacc0b27276f5511e39 --- /dev/null +++ b/pool/shard006/Python/0058722_ivy_task_mixin.py @@ -0,0 +1,213 @@ +# 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 copy +import logging +import os +import shutil +import threading +from collections import defaultdict + +from twitter.common.collections import maybe_list + +from pants.backend.jvm.ivy_utils import IvyUtils +from pants.backend.jvm.targets.jar_library import JarLibrary +from pants.backend.jvm.targets.jvm_target import JvmTarget +from pants.base.cache_manager import VersionedTargetSet +from pants.base.exceptions import TaskError +from pants.base.fingerprint_strategy import DefaultFingerprintHashingMixin, FingerprintStrategy +from pants.ivy.bootstrapper import Bootstrapper +from pants.java.util import execute_runner +from pants.util.dirutil import safe_mkdir + + +logger = logging.getLogger(__name__) + + +class IvyResolveFingerprintStrategy(DefaultFingerprintHashingMixin, FingerprintStrategy): + + def compute_fingerprint(self, target): + if isinstance(target, JarLibrary): + return target.payload.fingerprint() + if isinstance(target, JvmTarget): + if target.payload.excludes or target.payload.configurations: + return target.payload.fingerprint(field_keys=('excludes', 'configurations')) + return None + + + +class IvyTaskMixin(object): + @classmethod + def register_options(cls, register): + super(IvyTaskMixin, cls).register_options(register) + register('--jvm-options', action='append', metavar='