diff --git a/pool/shard003/Python/0027227_pycaw.test.py b/pool/shard003/Python/0027227_pycaw.test.py new file mode 100644 index 0000000000000000000000000000000000000000..deeb438f596286d5b5815a4fd25f96667989fd79 --- /dev/null +++ b/pool/shard003/Python/0027227_pycaw.test.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 + +from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume +from pydub import AudioSegment +from pydub.playback import play + +# https://stackoverflow.com/a/43727046 +def main(): + song = AudioSegment.from_mp3("beep.mp3") + + global sess, vol + + play(song) + sessions = AudioUtilities.GetAllSessions() + for session in sessions: + # if session.Process: + # print(session.Process.name()) + if session.Process and session.Process.name() == "python.exe": + sess = session + vol = sess._ctl.QueryInterface(ISimpleAudioVolume) + print("volume.GetMasterVolume(): %s" % vol.GetMasterVolume()) + vol.SetMasterVolume(0, None) + + play(song) + vol.SetMasterVolume(1, None) + play(song) + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard003/Python/0027232_generate.py b/pool/shard003/Python/0027232_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..b46fac3f38c14685ef181da44f8844e9577dbab3 --- /dev/null +++ b/pool/shard003/Python/0027232_generate.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# Copyright (C) 2017-2020 The Project X-Ray Authors. +# +# Use of this source code is governed by a ISC-style +# license that can be found in the LICENSE file or at +# https://opensource.org/licenses/ISC +# +# SPDX-License-Identifier: ISC + +import json + +from prjxray.segmaker import Segmaker +from prjxray import verilog + + +def add_enum_bits(segmk, params, key, options): + for opt in options: + segmk.add_site_tag( + params['tile'], '{}_{}'.format(key, opt), params[key] == opt) + + +def output_integer_tags(segmk, params, key, invert=False): + tile = params['tile'] + bits = verilog.parse_bitstr(params[key]) + for bit, tag_val in enumerate(bits): + if not invert: + segmk.add_tile_tag( + tile, "{}[{}]".format(key, + len(bits) - bit - 1), tag_val) + else: + segmk.add_tile_tag( + tile, "Z{}[{}]".format(key, + len(bits) - bit - 1), + 0 if tag_val else 1) + + +def main(): + segmk = Segmaker("design.bits") + + print("Loading tags") + with open('params.json') as f: + params = json.load(f) + + for tile_param in params: + if tile_param['EN_SYN'] and tile_param['DATA_WIDTH'] == 4: + output_integer_tags( + segmk, tile_param, 'ALMOST_EMPTY_OFFSET', invert=True) + output_integer_tags( + segmk, tile_param, 'ALMOST_FULL_OFFSET', invert=True) + + for param in ('EN_SYN', 'FIRST_WORD_FALL_THROUGH'): + segmk.add_tile_tag(tile_param['tile'], param, tile_param[param]) + + segmk.compile() + segmk.write() + + +if __name__ == '__main__': + main() diff --git a/pool/shard003/Python/0027236_sgf.py b/pool/shard003/Python/0027236_sgf.py new file mode 100644 index 0000000000000000000000000000000000000000..fed864a6261d85ed9736f0ad42f3145c1e004ce2 --- /dev/null +++ b/pool/shard003/Python/0027236_sgf.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +""" + pygments.lexers.sgf + ~~~~~~~~~~~~~~~~~~~ + + Lexer for Smart Game Format (sgf) file format. + + :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from pygments.lexer import RegexLexer, bygroups +from pygments.token import Name, Literal, String, Text, Punctuation + +__all__ = ["SmartGameFormatLexer"] + + +class SmartGameFormatLexer(RegexLexer): + """ + Lexer for Smart Game Format (sgf) file format. + + The format is used to store game records of board games for two players + (mainly Go game). + For more information about the definition of the format, see: + https://www.red-bean.com/sgf/ + + .. versionadded:: 2.4 + """ + name = 'SmartGameFormat' + aliases = ['sgf'] + filenames = ['*.sgf'] + + tokens = { + 'root': [ + (r'[\s():;]', Punctuation), + # tokens: + (r'(A[BW]|AE|AN|AP|AR|AS|[BW]L|BM|[BW]R|[BW]S|[BW]T|CA|CH|CP|CR|' + r'DD|DM|DO|DT|EL|EV|EX|FF|FG|G[BW]|GC|GM|GN|HA|HO|ID|IP|IT|IY|KM|' + r'KO|LB|LN|LT|L|MA|MN|M|N|OB|OM|ON|OP|OT|OV|P[BW]|PC|PL|PM|RE|RG|' + r'RO|RU|SO|SC|SE|SI|SL|SO|SQ|ST|SU|SZ|T[BW]|TC|TE|TM|TR|UC|US|VW|' + r'V|[BW]|C)', + Name.Builtin), + # number: + (r'(\[)([0-9.]+)(\])', + bygroups(Punctuation, Literal.Number, Punctuation)), + # date: + (r'(\[)([0-9]{4}-[0-9]{2}-[0-9]{2})(\])', + bygroups(Punctuation, Literal.Date, Punctuation)), + # point: + (r'(\[)([a-z]{2})(\])', + bygroups(Punctuation, String, Punctuation)), + # double points: + (r'(\[)([a-z]{2})(:)([a-z]{2})(\])', + bygroups(Punctuation, String, Punctuation, String, Punctuation)), + + (r'(\[)([\w\s#()+,\-.:?]+)(\])', + bygroups(Punctuation, String, Punctuation)), + (r'(\[)(\s.*)(\])', + bygroups(Punctuation, Text, Punctuation)), + ], + } diff --git a/pool/shard003/Python/0027242_test4.py b/pool/shard003/Python/0027242_test4.py new file mode 100644 index 0000000000000000000000000000000000000000..f673d55a1135c710309ca2dae655243a2f3fb741 --- /dev/null +++ b/pool/shard003/Python/0027242_test4.py @@ -0,0 +1,55 @@ +#trying to build a prime number finder +#only designed to work on positive numbers +#I want users to eventually be able to input top and bottom numbers to search +#1 is being defined as non-prime for this + +#variables +prime = True #assigning this variable a value to start with + +aNumber = input("What's the smallest number that you'd like me to test?") #The number being tested, starts at the bottom and increments throughout the program +maxSize = input("what's the largest number that you'd like me to test?") #largest number to be tested + +#test that entries are numbers +try: + divisor = int(aNumber)-1 #dividing by a number less than the tested number, this decriments through the program +except: + print("Python thinks you didn't enter a smaller number. Let's just call it 2.") + aNumber = 2 + divisor = int(aNumber)-1 +else: + aNumber = int(aNumber) + divisor = int(aNumber)-1 + +try: + maxSize = int(maxSize) +except: + print("Python thinks that you didn't enter a larger number. Let's call it ",aNumber) + maxSize = int(aNumber) +else: + maxSize = int(maxSize) + +#test the aNumber is a postive number +if aNumber < 1: + print("You entered 0 or a negative number, I'm bumping you up to 1 to start") + aNumber = 1 +if maxSize < 1: + print("You entered 0 or a negative number, I'm bumping you up to 2 to start") + maxSize = 2 + +#quick test for starting numbers larger than ending number +if aNumber > maxSize: + print("your smallest number (",aNumber,") is larger than your largest number)",maxSize,") so I'm going to swap them") + foo = aNumber + aNumber = maxSize + maxSize = foo + +while (aNumber <= maxSize): + if divisor < 1: prime = False #tests that we're not using + while (divisor > 1 and prime == True): + if aNumber % divisor == 0:prime = False + divisor -= 1 + if prime == True: print ("Prime number found: ", aNumber) + prime = True + divisor = aNumber + aNumber +=1 + \ No newline at end of file diff --git a/pool/shard003/Python/0027243_d38e04c12aa2_add_serialized_dag_table.py b/pool/shard003/Python/0027243_d38e04c12aa2_add_serialized_dag_table.py new file mode 100644 index 0000000000000000000000000000000000000000..d8022b44877870e8b5e3cdac5aff442b6875e051 --- /dev/null +++ b/pool/shard003/Python/0027243_d38e04c12aa2_add_serialized_dag_table.py @@ -0,0 +1,93 @@ +# +# 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. + +"""add serialized_dag table + +Revision ID: d38e04c12aa2 +Revises: 6e96a59344a4 +Create Date: 2019-08-01 14:39:35.616417 + +""" +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import mysql + +# revision identifiers, used by Alembic. +revision = 'd38e04c12aa2' +down_revision = '6e96a59344a4' +branch_labels = None +depends_on = None + + +def upgrade(): + """Upgrade version.""" + json_type = sa.JSON + conn = op.get_bind() + + if conn.dialect.name != "postgresql": + # Mysql 5.7+/MariaDB 10.2.3 has JSON support. Rather than checking for + # versions, check for the function existing. + try: + conn.execute("SELECT JSON_VALID(1)").fetchone() + except (sa.exc.OperationalError, sa.exc.ProgrammingError): + json_type = sa.Text + + op.create_table( + 'serialized_dag', + sa.Column('dag_id', sa.String(length=250), nullable=False), + sa.Column('fileloc', sa.String(length=2000), nullable=False), + sa.Column('fileloc_hash', sa.Integer(), nullable=False), + sa.Column('data', json_type(), nullable=False), + sa.Column('last_updated', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('dag_id'), + ) + op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash']) + + if conn.dialect.name == "mysql": + conn.execute("SET time_zone = '+00:00'") + cur = conn.execute("SELECT @@explicit_defaults_for_timestamp") + res = cur.fetchall() + if res[0][0] == 0: + raise Exception("Global variable explicit_defaults_for_timestamp needs to be on (1) for mysql") + + op.alter_column( + table_name="serialized_dag", + column_name="last_updated", + type_=mysql.TIMESTAMP(fsp=6), + nullable=False, + ) + else: + # sqlite and mssql datetime are fine as is. Therefore, not converting + if conn.dialect.name in ("sqlite", "mssql"): + return + + # we try to be database agnostic, but not every db (e.g. sqlserver) + # supports per session time zones + if conn.dialect.name == "postgresql": + conn.execute("set timezone=UTC") + + op.alter_column( + table_name="serialized_dag", + column_name="last_updated", + type_=sa.TIMESTAMP(timezone=True), + ) + + +def downgrade(): + """Downgrade version.""" + op.drop_table('serialized_dag') diff --git a/pool/shard003/Python/0027246_chartDrawing.py b/pool/shard003/Python/0027246_chartDrawing.py new file mode 100644 index 0000000000000000000000000000000000000000..4f5225d104a32df73426884a3ca47f7c46ae1c36 --- /dev/null +++ b/pool/shard003/Python/0027246_chartDrawing.py @@ -0,0 +1,24 @@ +import numpy as np +from matplotlib import pyplot as plt + + +def drawWaiteForAnyCustomer(xList, yList,name): + fig = plt.figure() + width = .5 + ind = np.arange(len(yList)) + plt.bar(ind, yList) + plt.xticks(ind + width / 2, xList) + # fig.autofmt_xdate() + + plt.savefig("results/"+name+"_waitingPerCustomer.pdf") + + +def drawFrequencyForAnyWaiteData(xList, yList, name): + fig = plt.figure() + width = .5 + ind = np.arange(len(yList)) + plt.bar(ind, yList) + plt.xticks(ind + width / 2, xList) + # fig.autofmt_xdate() + + plt.savefig("results/"+name+"_FrequencyPerWaitAmount.pdf") diff --git a/pool/shard003/Python/0027250_utils.py b/pool/shard003/Python/0027250_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6cbdf3a579da0e3e1152d4c678c3fc0985319f0b --- /dev/null +++ b/pool/shard003/Python/0027250_utils.py @@ -0,0 +1,44 @@ +from collections import namedtuple +import xml.etree.ElementTree as ET + +OPERA_TIMESTAMP_FORMAT = "%Y%m%dT%H:%M:%S" + + +def parse_receipts_xml(receipt_xml_data): + tree = ET.fromstring(receipt_xml_data) + return map(receipt_to_namedtuple, tree.findall('receipt')) + + +def receipt_element_to_dict(element): + """ + Turn an ElementTree element '1' into {el: 1}. + Not recursive! + + >>> data = ET.fromstring("1") + >>> receipt_element_to_dict(data) + {'el': '1'} + >>> + + """ + return dict([(child.tag, child.text) for child in element.getchildren()]) + + +def receipt_to_namedtuple(element): + """ + Turn an ElementTree element into an object with named params. + Not recursive! + + >>> data = ET.fromstring("1") + >>> receipt_to_namedtuple(data) + data(el='1') + + """ + d = receipt_element_to_dict(element) + klass = namedtuple(element.tag, d.keys()) + return klass._make(d.values()) + + +def parse_post_event_xml(post_event_xml_data): + tree = ET.fromstring(post_event_xml_data) + fields = tree.findall('field') + return dict([(field.attrib['name'], field.text) for field in fields]) diff --git a/pool/shard003/Python/0027253_local.py b/pool/shard003/Python/0027253_local.py new file mode 100644 index 0000000000000000000000000000000000000000..535a38b7962d0ecc494825c6531278a1ec023843 --- /dev/null +++ b/pool/shard003/Python/0027253_local.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright 2012-2015 clowwindy +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import sys +import os +import logging +import signal + +from module import shell +from module import daemon +from module import eventloop +from module import tcprelay +from module import udprelay +from module import asyncdns + +def main(): + + ''' + main function + ''' + + shell.check_python() + + config = shell.get_config(True) + + if not config.get('dns_ipv6', False): + asyncdns.IPV6_CONNECTION_SUPPORT = False + + daemon.daemon_exec(config) + + show_str = "local start with protocol[%s] password [%s] method [%s] obfs [%s] obfs_param [%s]" % ( + config['protocol'], + config['password'], + config['method'], + config['obfs'], + config['obfs_param'] + ) + + logging.info(show_str) + + try: + show_str_1 = "starting local at %s:%d" % ( + config['local_address'], + config['local_port'] + ) + logging.info(show_str_1) + print(config['server']) + + dns_resolver = asyncdns.DNSResolver() + tcp_server = tcprelay.TCPRelay(config, dns_resolver, True) + udp_server = udprelay.UDPRelay(config, dns_resolver, True) + loop = eventloop.EventLoop() + dns_resolver.add_to_loop(loop) + tcp_server.add_to_loop(loop) + udp_server.add_to_loop(loop) + + def handler(signum, _): + logging.warn('received SIGQUIT, doing graceful shutting down..') + tcp_server.close(next_tick=True) + udp_server.close(next_tick=True) + signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler) + + def int_handler(signum, _): + sys.exit(1) + signal.signal(signal.SIGINT, int_handler) + + daemon.set_user(config.get('user', None)) + loop.run() + except Exception as e: + shell.print_exception(e) + sys.exit(1) + +if __name__ == '__main__': + main() diff --git a/pool/shard003/Python/0027254_problem035.py b/pool/shard003/Python/0027254_problem035.py new file mode 100644 index 0000000000000000000000000000000000000000..17bc4ddc7dbc794791db9a9e5ad452431a6fadbe --- /dev/null +++ b/pool/shard003/Python/0027254_problem035.py @@ -0,0 +1,22 @@ +from common import primes + +def main(): + print(len(circularPrimesBelow(1000000))) + +def circularPrimesBelow(limit): + primeList = [] + for i in range(limit): + if isCircularPrime(i): + primeList.append(i) + return primeList + +def isCircularPrime(n): + n = str(n) + for _ in range(len(n)): + if not primes.isPrime(int(n)): + return False + n = n[1:] + n[0] + return True + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard003/Python/0027266_test_ip_lib.py b/pool/shard003/Python/0027266_test_ip_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..c6051d7564f799a8a3612691ec92d5c9393880f0 --- /dev/null +++ b/pool/shard003/Python/0027266_test_ip_lib.py @@ -0,0 +1,94 @@ +# Copyright 2016 Cloudbase Solutions. +# 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 netifaces + +from neutron.agent.windows import ip_lib +from neutron.tests import base + + +class TestIpWrapper(base.BaseTestCase): + + def test_get_device_by_ip_no_ip(self): + ret = ip_lib.IPWrapper().get_device_by_ip(None) + self.assertIsNone(ret) + + @mock.patch.object(ip_lib.IPWrapper, 'get_devices') + def test_get_device_by_ip(self, mock_get_devices): + mock_dev1 = mock.MagicMock() + mock_dev2 = mock.MagicMock() + mock_dev1.device_has_ip.return_value = False + mock_dev2.device_has_ip.return_value = True + mock_get_devices.return_value = [mock_dev1, mock_dev2] + ret = ip_lib.IPWrapper().get_device_by_ip('fake_ip') + + self.assertEqual(mock_dev2, ret) + + @mock.patch('netifaces.interfaces') + def test_get_devices(self, mock_interfaces): + mock_interfaces.return_value = [mock.sentinel.dev1, + mock.sentinel.dev2] + + ret = ip_lib.IPWrapper().get_devices() + self.assertEqual(mock.sentinel.dev1, ret[0].device_name) + self.assertEqual(mock.sentinel.dev2, ret[1].device_name) + + @mock.patch('netifaces.interfaces') + def test_get_devices_error(self, mock_interfaces): + mock_interfaces.side_effect = OSError + ret = ip_lib.IPWrapper().get_devices() + + self.assertEqual([], ret) + + +class TestIpDevice(base.BaseTestCase): + + @mock.patch('netifaces.ifaddresses') + def test_device_has_ip(self, mock_netifaces): + mock_address = {'addr': mock.sentinel.fake_addr} + mock_netifaces.return_value = {netifaces.AF_INET: [mock_address]} + + ret = ip_lib.IPDevice("fake_dev").device_has_ip( + mock.sentinel.fake_addr) + + self.assertTrue(ret) + + @mock.patch('netifaces.ifaddresses') + def test_device_has_ip_false(self, mock_netifaces): + mock_netifaces.return_value = {} + + ret = ip_lib.IPDevice("fake_dev").device_has_ip( + mock.sentinel.fake_addr) + + self.assertFalse(ret) + + @mock.patch('netifaces.ifaddresses') + def test_device_has_ip_error(self, mock_netifaces): + mock_netifaces.side_effect = OSError + + ret = ip_lib.IPDevice("fake_dev").device_has_ip( + mock.sentinel.fake_addr) + + self.assertFalse(ret) + + @mock.patch('netifaces.ifaddresses') + def test_device_not_found(self, mock_netifaces): + mock_netifaces.side_effect = ValueError + + ret = ip_lib.IPDevice("fake_dev").device_has_ip( + mock.sentinel.fake_addr) + + self.assertFalse(ret) diff --git a/pool/shard003/Python/0027273_0001_initial.py b/pool/shard003/Python/0027273_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..a2cccaec70b370de2b000dca336c804c3b4ea6ee --- /dev/null +++ b/pool/shard003/Python/0027273_0001_initial.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10 on 2016-08-31 18:03 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Bactracking_Solutiion', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('matrix_size', models.IntegerField(default=0)), + ('solution_cost', models.FloatField(default=0.0)), + ('coordinates', models.CharField(max_length=100000)), + ('expanded_nodes', models.IntegerField(default=0)), + ('excecution_time', models.FloatField(default=0.0)), + ], + ), + ] diff --git a/pool/shard003/Python/0027275_test_exp.py b/pool/shard003/Python/0027275_test_exp.py new file mode 100644 index 0000000000000000000000000000000000000000..d768eb29003fa0364117bb65145c8f16fae9b370 --- /dev/null +++ b/pool/shard003/Python/0027275_test_exp.py @@ -0,0 +1,91 @@ +from rump import Request, types, and_, or_, not_ + + +def test_str(): + cases = [ + (Request.client_ip4.in_(types.IPNetwork('1/8')), + 'client_ip4 in 1.0.0.0/8'), + (Request.client_ip4.in_(types.IPNetwork('1/8')) & + (Request.method == 'GET'), + 'client_ip4 in 1.0.0.0/8 and method = "GET"'), + (Request.client_ip4.in_(types.IPNetwork('1/8')) | + (Request.method == 'GET'), + 'client_ip4 in 1.0.0.0/8 or method = "GET"'), + (Request.client_ip4 != types.IPAddress('1.2.3.4'), + 'client_ip4 != 1.2.3.4'), + (Request.path.match('/v[1234]/resources'), + 'path ~ "/v[1234]/resources"'), + (~Request.path.match('/v[1234]/resources'), + 'path !~ "/v[1234]/resources"'), + ] + for case, expected in cases: + assert str(case) == expected + + +def test_compile(): + cases = [ + Request.client_ip4.in_(types.IPNetwork('1/8')), + Request.client_ip4.in_(types.IPNetwork('1/8')) & (Request.method == 'GET'), + Request.client_ip4.in_(types.IPNetwork('1/8')) | (Request.method == 'GET'), + Request.client_ip4 != types.IPAddress('1.2.3.4'), + Request.path.match('/v[1234]/resources'), + Request.path.startswith('/veep/'), + Request.path.endswith('/'), + Request.path.contains('veep'), + Request.content_length < 100, + Request.content_length >= 100, + Request.has_content, + ] + for case in cases: + assert case.compile(case.symbols()) + + +def test_traverse(): + e = and_( + Request.client_ip4.in_(types.IPNetwork('1.2.3.4/32')), + Request.method == 'GET', + or_( + not_(Request.path.match('/something/.+')), + Request.query.contains('a'), + ) + ) + + def _visit(v): + vs.append(v) + return v + + vs = [] + e.traverse(bool_op=_visit, field_op=_visit, order=e.PREFIX) + assert map(str, vs) == [ + 'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query', + 'client_ip4 in 1.2.3.4/32 and method = "GET"', + 'client_ip4 in 1.2.3.4/32', + 'method = "GET"', + 'path !~ "/something/.+" or a in query', + 'path !~ "/something/.+"', + 'a in query', + ] + + vs = [] + e.traverse(bool_op=_visit, field_op=_visit, order=e.INFIX) + assert map(str, vs) == [ + 'client_ip4 in 1.2.3.4/32', + 'client_ip4 in 1.2.3.4/32 and method = "GET"', + 'method = "GET"', + 'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query', + 'path !~ "/something/.+"', + 'path !~ "/something/.+" or a in query', + 'a in query', + ] + + vs = [] + e.traverse(bool_op=_visit, field_op=_visit, order=e.POSTFIX) + assert map(str, vs) == [ + 'client_ip4 in 1.2.3.4/32', + 'method = "GET"', + 'client_ip4 in 1.2.3.4/32 and method = "GET"', + 'path !~ "/something/.+"', + 'a in query', + 'path !~ "/something/.+" or a in query', + 'client_ip4 in 1.2.3.4/32 and method = "GET" and path !~ "/something/.+" or a in query' + ] diff --git a/pool/shard003/Python/0027277_models.py b/pool/shard003/Python/0027277_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4d96dfd1136e5e84733431a0066c1860c8b162da --- /dev/null +++ b/pool/shard003/Python/0027277_models.py @@ -0,0 +1,14 @@ +from django.db import models + +class Url(models.Model): + '''Hostname and urls''' + title = models.CharField( max_length=100, ) + ip = models.CharField( max_length=100, ) + urls = models.CharField( max_length=500, ) + slug = models.SlugField() + + def __unicode__(self): + return u'%s' % self.title + +# class Meta: +# ordering = ['slug'] diff --git a/pool/shard003/Python/0027278_beerpoint.py b/pool/shard003/Python/0027278_beerpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..8dcec9d3d9bcad2d96571c3665c7a40c974a4219 --- /dev/null +++ b/pool/shard003/Python/0027278_beerpoint.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +import re +from BeautifulSoup import BeautifulSoup + +@given('Beer point') +@when('Looking at home page') +def step(context): + context.browser.go(context.baseurl) + context.page = context.browser.get_html().decode('utf-8') + assert context.page + +@then('We see beer point name') +def step(context): + assert re.search('beer point name: \w+', context.page) + +@then('We see "{text}" in title') +def step(context, text): + assert text in context.browser.get_title() + +@then('We see beer styles') +def step(context): + for row in context.table: + assert row['type'] in context.page + +@when('Number of pints for a beer is {text} 0') +def step(context, text): + # base on text pattern + if text == 'equal': pattern = 'pints=0' + if text == 'greater than': pattern = 'pints=[1-9]' + # find all beers descriptions + beerslist = BeautifulSoup(context.page).findAll('li') + context.beerslist = [] + for beer_d in beerslist: + # beers descriptions maching pattern add to context.beerslist + if re.search(pattern ,beer_d.text): + context.beerslist.append(str(beer_d)) + # check that pattern exist in page and we have good example to test + assert re.search(pattern,context.page) + +@then('The Beer description is {text}') +def step(context, text): + for beer_d in context.beerslist: + if text == 'red': + assert re.search('color=["\']red["\']', beer_d) + if text == 'not red': + assert not re.search('color=["\']red["\']', beer_d) diff --git a/pool/shard003/Python/0027284_hiplicious.py b/pool/shard003/Python/0027284_hiplicious.py new file mode 100644 index 0000000000000000000000000000000000000000..d627277d35fa1fcf6fd30bb0fff8c2976df66e56 --- /dev/null +++ b/pool/shard003/Python/0027284_hiplicious.py @@ -0,0 +1,255 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +import argparse +import base64 +import datetime +import json +import re +import urllib +import urllib2 + +config = { + 'DELICIOUS_USERNAME': '-------', + 'DELICIOUS_PASSWORD': '-------', + 'DELICIOUS_BASE_URI': 'https://api.delicious.com/v1', + 'DELICIOUS_SHARED': 'no', + 'HIPCHAT_TOKEN': '-------', + 'HIPCHAT_ROOM': '-------', + 'HIPCHAT_BASE_URI': 'https://api.hipchat.com/v1', + 'HIPCHAT_INCLUDE_FILES': False, + 'LOG_FILE': 'hiplicious.log' +} + +# Set up and parse command line argments +parser = argparse.ArgumentParser(description='Import links from a HipChat room\ + to Delicious.com') +parser.add_argument('-a', '--all', + action='store_true', + help='Import the entire history') +parser.add_argument('-c', '--continuous', + action='store_true', + help='Continue from the specified date until today') +parser.add_argument('-d', '--date', + help='Specify a date (YYYY-MM-DD format) to import') +args = parser.parse_args() + +def build_url(provider, endpoint, **kwargs): + """Builds a request URL + + :param provider: either 'hipchat' or 'delicious' + :param endpoint: the API endpoint + :param **kwargs: optional URL parameters + """ + if provider == 'hipchat': + base = config.get('HIPCHAT_BASE_URI') + elif provider == 'delicious': + base = config.get('DELICIOUS_BASE_URI') + + # Keep urlencode from choking on unicode data + # http://stackoverflow.com/a/3121311 + string_kwargs = {} + for k, v in kwargs.iteritems(): + string_kwargs[k] = unicode(v).encode('utf-8') + + return ''.join([base, endpoint, '?', urllib.urlencode(string_kwargs)]) + +def make_request(url, auth=None, json_format=True): + """ + Makes a request using urllib2 and returns the response in the requested + format. + + :param url: the url to send a request to + :param auth: (optional) List containing a username and password + :param json_format: (optional) whether to load the response as json and + return a Dict. Defaults to True. + """ + request = urllib2.Request(url) + + if auth and len(auth) == 2: + base64string = base64.encodestring(':'.join(auth)).replace('\n', '') + request.add_header("Authorization", "Basic %s" % base64string) + + try: + response = urllib2.urlopen(request) + except urllib2.URLError as e: + print e.reason + + data = response.read() + + if json_format: + return json.loads(data) + else: + return data + +def hipchat_get_creation_date(): + """ + Returns the creation date of config['HIPCHAT_ROOM'] in YYYY-MM-DD format + """ + + endpoint = '/rooms/show' + options = { + 'room_id': config.get('HIPCHAT_ROOM'), + 'format': json, + 'auth_token': config.get('HIPCHAT_TOKEN') + } + request_url = build_url('hipchat', endpoint, **options) + response = make_request(request_url) + + date = datetime.datetime.fromtimestamp(int(response['room']['created'])) + return date.strftime("%Y-%m-%d") + +def hipchat_get_log(date): + """ + Given a date, returns Hipchat log for that date + + :param date: date in YYYY-MM-DD format + """ + print 'Retrieving log for ', date + + endpoint = '/rooms/history' + options = { + 'room_id': config.get('HIPCHAT_ROOM'), + 'date': date, + 'format': json, + 'auth_token': config.get('HIPCHAT_TOKEN') + } + request_url = build_url('hipchat', endpoint, **options) + response = make_request(request_url) + + print 'Log retrieved' + return response + +def get_urls_from_log(log, include_files=config.get('HIPCHAT_INCLUDE_FILES', + False)): + """ + Given a dict containing a list of Hipchat messages, extracts URLs and builds + bookmark dicts + + :param log: Dict containing a Hipchat history + :param include_files: (optional) whether to include file attachment URLs or + just in-message URLs. Defaults to False. + """ + print 'Extracting URLs' + regexp = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F]'\ + '[0-9a-fA-F]))+' + bookmarks = [] + + for item in log['messages']: + urls = re.findall(regexp, item['message']) + if urls: + for url in urls: + # Remove the URL from the comment itself + pattern = re.escape(url) + placeholder = '[link]' + comment = re.sub(pattern, placeholder, item['message']) + + # Remove characters that choke Delicious's API. Couldn't figure + # out how to combine these... + comment = re.sub(u'\u2026', ' ', comment) + comment = re.sub('[<>]', ' ', comment) + + if comment.strip() == placeholder: + comment = '' + bookmark = { + 'url': url, + 'comment': comment, + 'dt': item['date'], + 'tags': ','.join([item['from']['name'], + get_tags_from_message(item['message'])]) + } + bookmarks.append(bookmark) + if include_files: + if item.get('file'): + bookmark = { + 'url': item['file']['url'], + 'comment': comment, + 'dt': item['date'], + 'tags': ','.join([item['from']['name'], 'file', + get_tags_from_message(item['message'])]) + } + bookmarks.append(bookmark) + print len(bookmarks), ' bookmarks found' + return bookmarks + +def get_tags_from_message(message): + """ + Given a message string, extracts hashtags and returns a comma-separated list + + :param message: a Hipchat message body + """ + tags = {word.strip('#') for word in message.split() if word.startswith('#')} + return ','.join(tags) + +def format_date_string(datestring): + """ + Given a Hipchat-style date string, reformat to Delicious-style date string, + e.g. 2013-08-06T19:46:49+0000 to 2013-08-06T19:46:49Z + + :param datestring: the Hipchat date string + """ + return re.sub('\+(.)*$', 'Z', datestring) + +def delicious_add_bookmarks(bookmarks): + print 'Adding bookmarks to delicious.com' + + endpoint = '/posts/add' + + for bookmark in bookmarks: + #print bookmark.get('comment') + options = { + 'url': bookmark.get('url'), + 'description': bookmark.get('url'), + 'extended': bookmark.get('comment'), + 'tags': bookmark.get('tags'), + 'dt': format_date_string(bookmark.get('dt')), + 'shared': config.get('DELICIOUS_SHARED') + } + request_url = build_url('delicious', endpoint, **options) + creds = [config.get('DELICIOUS_USERNAME'), + config.get('DELICIOUS_PASSWORD')] + response = make_request(request_url, auth=creds, json_format=False) + + if 'done' in response: + print ' '.join(['Added', bookmark.get('url')]) + else: + print ' '.join(['Could not add', bookmark.get('url')]) + with open(config.get('LOG_FILE'), 'a') as logfile: + logfile.write('\n' + bookmark.get('url')) + +def make_my_hipchat_delicious(start, continuous=False): + """Iterates over dates and runs the import/export + + :param start: String of a start date in YYYY-MM-DD format. + :param continuous: (optional) whether to proceed from the start date until + today. Defaults to False. + """ + + if continuous: + date = datetime.datetime.strptime(start, '%Y-%m-%d').date() + while date <= datetime.date.today(): + run_import(date.strftime('%Y-%m-%d')) + date += datetime.timedelta(days=1) + else: + run_import(start) + +def run_import(date): + """Runs the import steps + + :param date: Date in YYYY-MM-DD format + """ + log = hipchat_get_log(date) + bookmarks = get_urls_from_log(log) + delicious_add_bookmarks(bookmarks) + +if __name__ == '__main__': + if args.date: + desired_date = args.date + elif args.all: + desired_date = hipchat_get_creation_date() + else: + desired_date = datetime.date.today().strftime('%Y-%m-%d') + + continuous = args.continuous + + make_my_hipchat_delicious(desired_date, continuous) \ No newline at end of file diff --git a/pool/shard003/Python/0027286_quadrat_builder.py b/pool/shard003/Python/0027286_quadrat_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..912efd843b39dc2a15ee744b1aaa3d9b807c6e3b --- /dev/null +++ b/pool/shard003/Python/0027286_quadrat_builder.py @@ -0,0 +1,49 @@ +from .vertex import Vertex +from .quadrat import Quadrat +from .helpers import get_midpoint_of_edge + + +class QuadratBuilder(object): + """A class that builds quadrats on a mesh, starting from the centre position.""" + + def build(self, box, size): + """ + Method to contruct a list of quadrats using a given bounding box. + @param box the bounding box of the meshes to measure + @param size the size of the square quadrilateral (in the units of the provided mesh) + @return list of the quadrats that fit the bounding box + """ + centroid = box.centroid + edge1_midpoint = get_midpoint_of_edge( + box.vertices[0], box.vertices[1]) + distance_to_edge1 = centroid.distance_to_xyz(edge1_midpoint) + quadrat_indexes1 = range(int(distance_to_edge1 / size) + 1) + + edge2_midpoint = get_midpoint_of_edge( + box.vertices[0], box.vertices[3]) + distance_to_edge2 = centroid.distance_to_xyz(edge2_midpoint) + quadrat_indexes2 = range(int(distance_to_edge2 / size) + 1) + + quadrats = list() + for i in quadrat_indexes2: + for j in quadrat_indexes1: + if i == 0 and j == 0: + quadrats.append(Quadrat((0, 0), size, centroid)) + else: + top_right = Vertex(centroid.x + i * size, + centroid.y + (j * size), centroid.z) + top_left = Vertex(centroid.x + i * size, + centroid.y - (j * size), centroid.z) + bottom_right = Vertex( + centroid.x - i * size, centroid.y + (j * size), centroid.z) + bottom_left = Vertex( + centroid.x - i * size, centroid.y - (j * size), centroid.z) + four_quadrats = [Quadrat((i, j), size, top_right), + Quadrat((i, -1 * j), size, top_left), + Quadrat((-1 * i, j), size, bottom_right), + Quadrat((-1 * i, -1 * j), size, bottom_left)] + quadrats_inside = list( + filter(lambda x: box.contains(x.midpoint), four_quadrats)) + quadrats += quadrats_inside + # print("There are this many quadrats: " + str(len(quadrats))) + return tuple(set(quadrats)) diff --git a/pool/shard003/Python/0027288_camshift.py b/pool/shard003/Python/0027288_camshift.py new file mode 100644 index 0000000000000000000000000000000000000000..40a62f380b2ad4d8a701cbf78f9f964b969f84b4 --- /dev/null +++ b/pool/shard003/Python/0027288_camshift.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python + +''' +Camshift tracker +================ +This is a demo that shows mean-shift based tracking +You select a color objects such as your face and it tracks it. +This reads from video camera (0 by default, or the camera number the user enters) +http://www.robinhewitt.com/research/track/camshift.html +Usage: +------ + camshift.py [