"
+
+ msgBox = QMessageBox()
+ msgBox.setWindowTitle("Help")
+ msgBox.setTextFormat(Qt.RichText)
+ msgBox.setText(msg + doc_link)
+ msgBox.exec_()
+
+ # QMessageBox.information(self,
+ # self.tr(self.wizname),
+ # msg)
+ # self._lastHelpMsg = msg
+
+
+def get_graphic_path():
+ if have_odmltables:
+ data_path = os.path.join(os.path.dirname(odmltables.__file__),
+ 'gui',
+ 'graphics')
+ return data_path
diff --git a/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py b/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..86d23cb46e2a27086efc973ca1bbe83854599880
--- /dev/null
+++ b/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+# encoding: utf-8
+
+r"""
+Traveltime in 2D
+----------------
+"""
+
+import numpy as np
+
+import pygimli as pg
+
+import pygimli.meshtools as mt
+from pygimli.physics.traveltime import Refraction
+
+# Create geometry definition for the modelling domain
+world = mt.createWorld(start=[-20, 0], end=[20, -16], layers=[-2, -8],
+ worldMarker=False)
+
+# Create a mesh from the geometry definition
+mesh = mt.createMesh(world, quality=33, area=0.1, smooth=[1, 10])
+
+pg.show(mesh, mesh.cellMarker(), label='marker')
+
+scheme = pg.physics.traveltime.createRAData(np.linspace(-15., 15., 31))
+
+ra = Refraction()
+
+data = ra.simulate(mesh, np.array(mesh.cellMarker())*1000,
+ scheme, noiseLevel=0.01, noiseAbs=1e-5, verbose=1)
+ra.showVA(data)
+ra.showData(data)
+
+pg.wait()
diff --git a/pool/shard002/Python/0026144_cmd.py b/pool/shard002/Python/0026144_cmd.py
new file mode 100644
index 0000000000000000000000000000000000000000..3276a8e40f5698bad23593b29b159abb086d2d76
--- /dev/null
+++ b/pool/shard002/Python/0026144_cmd.py
@@ -0,0 +1,76 @@
+"""Command line utility for mat4py.
+
+Provides a routine for converting Matlab MAT-files to/from JSON files.
+
+Call
+
+ python -m mat4py.cmd -h
+
+to get help with command line usage.
+"""
+
+import argparse
+import json
+import os
+
+from mat4py import loadmat, savemat
+
+
+def main():
+ #
+ # get arguments and invoke the conversion routines
+ #
+
+ parser = argparse.ArgumentParser(
+ description='Convert Matlab '
+ 'MAT-files to JSON formated text files, and the other way around.')
+
+ parser.add_argument(
+ 'file', nargs='+',
+ help='path to a Matlab MAT-file or a JSON file')
+ parser.add_argument(
+ '--remove-input', action='store_const', const=True,
+ default=False, help='remove input file after conversion')
+ parser.add_argument(
+ '-f', '--force', action='store_const', const=True,
+ default=False, help='overwrite existing files when converting')
+ args = parser.parse_args()
+
+ for path in args.file:
+ spl = os.path.splitext(path)
+ ext = spl[1].lower()
+
+ if ext == '.mat':
+ dest = spl[0] + '.json'
+ try:
+ if os.path.exists(dest) and not args.force:
+ raise Exception('File {} already exists.'.format(dest))
+ data = loadmat(path)
+ with open(dest, 'w') as fp:
+ json.dump(data, fp)
+ if args.remove_input:
+ os.remove(path)
+ except Exception as e:
+ print('Error: {}'.format(e))
+ exit(1)
+
+ elif ext == '.json':
+ dest = spl[0] + '.mat'
+ try:
+ if os.path.exists(dest) and not args.force:
+ raise Exception('File {} already exists.'.format(dest))
+ with open(path) as fp:
+ data = json.load(fp)
+ savemat(dest, data)
+ if args.remove_input:
+ os.remove(path)
+ except RuntimeError as e:
+ print('Error: {}'.format(e))
+ exit(1)
+ else:
+ print('Unsupported file extension on file: {0}'.format(path))
+ exit(1)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard002/Python/0026147_fibonacci.py b/pool/shard002/Python/0026147_fibonacci.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8c487ddbb061fe7701baffbd8021a14d62882d5
--- /dev/null
+++ b/pool/shard002/Python/0026147_fibonacci.py
@@ -0,0 +1,48 @@
+"""
+Fibonacci numbers function.
+"""
+
+# Copyright 2014 The University of Edinburgh.
+#
+# 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
+
+def fibonacci(n):
+ """
+ Calculate the Fibonacci number of the given integer.
+ @param n If n <= 0 then 0 is assumed.
+ @return fibonacci number.
+ """
+ if n <= 0:
+ return 0
+ elif n == 1:
+ return 1
+ else:
+ return fibonacci(n - 1) + fibonacci(n - 2)
+
+def print_usage():
+ """ Print usage information. """
+ print("Usage: python fibonacci.py N")
+ print(" where N >= 0")
+
+if __name__ == '__main__':
+ if (len(sys.argv) < 2):
+ print_usage()
+ exit(1)
+ n = int(sys.argv[1])
+ if (n < 0):
+ print_usage()
+ exit(2)
+ fib = fibonacci(n)
+ print("fibonacci(%d) = %d" % (n, fib))
diff --git a/pool/shard002/Python/0026149_problem2.py b/pool/shard002/Python/0026149_problem2.py
new file mode 100644
index 0000000000000000000000000000000000000000..49a0f4a5ebdf1d35d6bdd30a25e47ba63134d538
--- /dev/null
+++ b/pool/shard002/Python/0026149_problem2.py
@@ -0,0 +1,20 @@
+# Krystal Kwan
+# 2/14/2016
+# Print a rectangle according to the user's output
+
+while True:
+ print "This program will print a rectangle according to your input:"
+ print "What is the height?"
+ h = int(raw_input("> "))
+ print "What is the length?"
+ l = int(raw_input("> "))
+ for a in range(0,h):
+ for b in range(0,l):
+ print "*",
+ print
+ print "Do you want to continue (y/n)?"
+ ans = str(raw_input("> "))
+ if ans == "y":
+ continue
+ else:
+ break
diff --git a/pool/shard002/Python/0026152_CheckSum.py b/pool/shard002/Python/0026152_CheckSum.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc9e90f783767f837182057dbb32530911d362c4
--- /dev/null
+++ b/pool/shard002/Python/0026152_CheckSum.py
@@ -0,0 +1,143 @@
+# Copyright 2002 by Yves Bastide and Brad Chapman.
+# Copyright 2007 by Sebastian Bassi
+# All rights reserved.
+# This code is part of the Biopython distribution and governed by its
+# license. Please see the LICENSE file that should have been included
+# as part of this package.
+
+"""Functions to calculate assorted sequence checksums."""
+
+# crc32, crc64, gcg, and seguid
+# crc64 is adapted from BioPerl
+
+from __future__ import print_function
+
+from binascii import crc32 as _crc32
+from Bio._py3k import _as_bytes
+
+__docformat__ = "restructuredtext en"
+
+
+def crc32(seq):
+ """Returns the crc32 checksum for a sequence (string or Seq object)."""
+ # NOTE - On Python 2 returns a signed int, on Python 3 it is unsigned
+ # Docs suggest should use crc32(x) & 0xffffffff for consistency.
+ # TODO - Should we return crc32(x) & 0xffffffff here?
+ try:
+ # Assume its a Seq object
+ return _crc32(_as_bytes(str(seq)))
+ except AttributeError:
+ # Assume its a string/unicode
+ return _crc32(_as_bytes(seq))
+
+
+def _init_table_h():
+ _table_h = []
+ for i in range(256):
+ l = i
+ part_h = 0
+ for j in range(8):
+ rflag = l & 1
+ l >>= 1
+ if part_h & 1:
+ l |= (1 << 31)
+ part_h >>= 1
+ if rflag:
+ part_h ^= 0xd8000000
+ _table_h.append(part_h)
+ return _table_h
+
+# Initialisation
+_table_h = _init_table_h()
+
+
+def crc64(s):
+ """Returns the crc64 checksum for a sequence (string or Seq object)."""
+ crcl = 0
+ crch = 0
+ for c in s:
+ shr = (crch & 0xFF) << 24
+ temp1h = crch >> 8
+ temp1l = (crcl >> 8) | shr
+ idx = (crcl ^ ord(c)) & 0xFF
+ crch = temp1h ^ _table_h[idx]
+ crcl = temp1l
+
+ return "CRC-%08X%08X" % (crch, crcl)
+
+
+def gcg(seq):
+ """Returns the GCG checksum (int) for a sequence (string or Seq object).
+
+ Given a nucleotide or amino-acid secuence (or any string),
+ returns the GCG checksum (int). Checksum used by GCG program.
+ seq type = str.
+
+ Based on BioPerl GCG_checksum. Adapted by Sebastian Bassi
+ with the help of John Lenton, Pablo Ziliani, and Gabriel Genellina.
+
+ All sequences are converted to uppercase.
+ """
+ try:
+ # Assume its a Seq object
+ seq = str(seq)
+ except AttributeError:
+ # Assume its a string
+ pass
+ index = checksum = 0
+ for char in seq:
+ index += 1
+ checksum += index * ord(char.upper())
+ if index == 57:
+ index = 0
+ return checksum % 10000
+
+
+def seguid(seq):
+ """Returns the SEGUID (string) for a sequence (string or Seq object).
+
+ Given a nucleotide or amino-acid secuence (or any string),
+ returns the SEGUID string (A SEquence Globally Unique IDentifier).
+ seq type = str.
+
+ For more information about SEGUID, see:
+ http://bioinformatics.anl.gov/seguid/
+ DOI: 10.1002/pmic.200600032
+ """
+ import hashlib
+ import base64
+ m = hashlib.sha1()
+ try:
+ # Assume it's a Seq object
+ seq = str(seq)
+ except AttributeError:
+ # Assume it's a string
+ pass
+ m.update(_as_bytes(seq.upper()))
+ try:
+ # For Python 3+
+ return base64.encodebytes(m.digest()).decode().replace("\n", "").rstrip("=")
+ except AttributeError:
+ pass
+ # For all other Pythons
+ return base64.b64encode(m.digest()).rstrip("=")
+
+
+if __name__ == "__main__":
+ print("Quick self test")
+
+ str_light_chain_one = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \
+ + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \
+ + "YCSSYAGSSTLVFGGGTKLTVL"
+
+ str_light_chain_two = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \
+ + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \
+ + "YCCSYAGSSTWVFGGGTKLTVL"
+
+ assert crc64(str_light_chain_one) == crc64(str_light_chain_two)
+ assert 'CRC-44CAAD88706CC153' == crc64(str_light_chain_one)
+
+ assert 'BpBeDdcNUYNsdk46JoJdw7Pd3BI' == seguid(str_light_chain_one)
+ assert 'X5XEaayob1nZLOc7eVT9qyczarY' == seguid(str_light_chain_two)
+
+ print("Done")
diff --git a/pool/shard002/Python/0026153_0002_auto_20160815_1814.py b/pool/shard002/Python/0026153_0002_auto_20160815_1814.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb597fe3da5123d0be40c5e3ded468cdebcc967a
--- /dev/null
+++ b/pool/shard002/Python/0026153_0002_auto_20160815_1814.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import DrydenMusicApp.models
+from django.utils.timezone import utc
+import storages.backends.s3boto
+import datetime
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('DrydenMusicApp', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='music',
+ name='added',
+ field=models.DateTimeField(default=datetime.datetime(2016, 8, 15, 18, 14, 43, 265487, tzinfo=utc), auto_now_add=True),
+ preserve_default=False,
+ ),
+ migrations.AddField(
+ model_name='music',
+ name='first_line',
+ field=models.CharField(max_length=200, blank=True),
+ ),
+ migrations.AddField(
+ model_name='music',
+ name='title',
+ field=models.CharField(max_length=200, blank=True),
+ ),
+ migrations.AlterField(
+ model_name='music',
+ name='music_file',
+ field=models.FileField(null=True, upload_to=DrydenMusicApp.models.data_file_path, storage=storages.backends.s3boto.S3BotoStorage(acl='private', location='music_files'), blank=True),
+ ),
+ ]
diff --git a/pool/shard002/Python/0026155_dfs.py b/pool/shard002/Python/0026155_dfs.py
new file mode 100644
index 0000000000000000000000000000000000000000..879edae61783b5d770b493ed8cd66e713eccdd63
--- /dev/null
+++ b/pool/shard002/Python/0026155_dfs.py
@@ -0,0 +1,104 @@
+import decimal
+
+class Coord:
+ def __init__(self, lat, lon):
+ self.lat = lat
+ self.lon = lon
+
+class Way:
+ def __init__(self, source, target):
+ self.source = source
+ self.target = target
+
+
+f = open('nodes', 'r')
+lat = None
+nodes = []
+for line in f:
+ loaded = decimal.Decimal(line)
+ if lat is None:
+ lat = loaded
+ else:
+ nodes.append(Coord(lat, loaded))
+ lat = None
+f.close()
+
+f = open('ways', 'r')
+source = None
+ways = []
+for line in f:
+ loaded = int(line)
+ if source is None:
+ source = loaded
+ else:
+ ways.append(Way(source, loaded))
+ source = None
+f.close()
+
+before = """
+
+
+
+ Leaflet Quick Start Guide Example
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+"""
+print before
+way = ways[80]
+print "[" + str(nodes[way.source].lat) + ", " + str(nodes[way.source].lon) + "],"
+print "[" + str(nodes[way.target].lat) + ", " + str(nodes[way.target].lon) + "]"
+""" [51.509, -0.08],
+ [51.503, -0.06],
+ [51.51, -0.047]
+"""
+print after
\ No newline at end of file
diff --git a/pool/shard002/Python/0026157_main.py b/pool/shard002/Python/0026157_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..202609d9740464d9ef7d1c06a08a6193a15fc6d0
--- /dev/null
+++ b/pool/shard002/Python/0026157_main.py
@@ -0,0 +1,38 @@
+class AccountSqlite:
+ def get_password(self, id):
+ account = {
+ 'kent': 'abcd',
+ 'alex': 'xyz'
+ }
+ try:
+ password = account[id]
+ except:
+ password = None
+ return password
+
+
+class Hash:
+ def get_hash(self, password):
+ return 'abcd' if password == '123' else None
+
+class MobileManager:
+ def send_text(self, user, msg):
+ print '{0} sent a message: {1}'.format(user, msg)
+
+
+class ValidateAccount:
+ def __init__(self, account_db, passwd_hash, mobile_manager):
+ self.account_db = account_db
+ self.passwd_hash = passwd_hash
+ self.mobile_manager = mobile_manager
+
+ def check_account(self, id, password):
+ password_by_id = self.account_db.get_password(id)
+ password_by_hash = self.passwd_hash.get_hash(password)
+ if password_by_id == password_by_hash:
+ self.mobile_manager.send_text(id, 'Account Valid') # send sms
+ return True
+ else:
+ self.mobile_manager.send_text(id, 'Account Not Valid') # send sms
+ return False
+
\ No newline at end of file
diff --git a/pool/shard002/Python/0026158_test_signal_handlers.py b/pool/shard002/Python/0026158_test_signal_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..138927acfaf811255af73c064ff1d20b7e175f50
--- /dev/null
+++ b/pool/shard002/Python/0026158_test_signal_handlers.py
@@ -0,0 +1,82 @@
+from django.db import transaction
+from django.test import TransactionTestCase, override_settings
+
+from wagtail.core.models import Collection
+from wagtail.images import get_image_model, signal_handlers
+from wagtail.images.tests.utils import get_test_image_file
+
+
+class TestFilesDeletedForDefaultModels(TransactionTestCase):
+ """
+ Because we expect file deletion to only happen once a transaction is
+ successfully committed, we must run these tests using TransactionTestCase
+ per the following documentation:
+
+ Django's TestCase class wraps each test in a transaction and rolls back that
+ transaction after each test, in order to provide test isolation. This means
+ that no transaction is ever actually committed, thus your on_commit()
+ callbacks will never be run. If you need to test the results of an
+ on_commit() callback, use a TransactionTestCase instead.
+ https://docs.djangoproject.com/en/1.10/topics/db/transactions/#use-in-tests
+ """
+
+ def setUp(self):
+ # Required to create root collection because the TransactionTestCase
+ # does not make initial data loaded in migrations available and
+ # serialized_rollback=True causes other problems in the test suite.
+ # ref: https://docs.djangoproject.com/en/1.10/topics/testing/overview/#rollback-emulation
+ Collection.objects.get_or_create(
+ name="Root",
+ path="0001",
+ depth=1,
+ numchild=0,
+ )
+
+ def test_image_file_deleted_oncommit(self):
+ with transaction.atomic():
+ image = get_image_model().objects.create(
+ title="Test Image", file=get_test_image_file()
+ )
+ filename = image.file.name
+ self.assertTrue(image.file.storage.exists(filename))
+ image.delete()
+ self.assertTrue(image.file.storage.exists(filename))
+ self.assertFalse(image.file.storage.exists(filename))
+
+ def test_rendition_file_deleted_oncommit(self):
+ with transaction.atomic():
+ image = get_image_model().objects.create(
+ title="Test Image", file=get_test_image_file()
+ )
+ rendition = image.get_rendition("original")
+ filename = rendition.file.name
+ self.assertTrue(rendition.file.storage.exists(filename))
+ rendition.delete()
+ self.assertTrue(rendition.file.storage.exists(filename))
+ self.assertFalse(rendition.file.storage.exists(filename))
+
+
+@override_settings(WAGTAILIMAGES_IMAGE_MODEL="tests.CustomImage")
+class TestFilesDeletedForCustomModels(TestFilesDeletedForDefaultModels):
+ def setUp(self):
+ # Required to create root collection because the TransactionTestCase
+ # does not make initial data loaded in migrations available and
+ # serialized_rollback=True causes other problems in the test suite.
+ # ref: https://docs.djangoproject.com/en/1.10/topics/testing/overview/#rollback-emulation
+ Collection.objects.get_or_create(
+ name="Root",
+ path="0001",
+ depth=1,
+ numchild=0,
+ )
+
+ #: Sadly signal receivers only get connected when starting django.
+ #: We will re-attach them here to mimic the django startup behavior
+ #: and get the signals connected to our custom model..
+ signal_handlers.register_signal_handlers()
+
+ def test_image_model(self):
+ cls = get_image_model()
+ self.assertEqual(
+ "%s.%s" % (cls._meta.app_label, cls.__name__), "tests.CustomImage"
+ )
diff --git a/pool/shard002/Python/0026160_admin.py b/pool/shard002/Python/0026160_admin.py
new file mode 100644
index 0000000000000000000000000000000000000000..19b6730a2bb1594829a8b4c935b70a200e3666e3
--- /dev/null
+++ b/pool/shard002/Python/0026160_admin.py
@@ -0,0 +1,147 @@
+from django.contrib.admin.options import ModelAdmin, csrf_protect_m
+from django.contrib.admin.views.main import ChangeList
+from django.db import transaction
+from django.utils.translation import ugettext_lazy as _
+
+
+def textual(title, ordering_field=None):
+ """
+ Fallbacks textual field to '---' instead of (None) in admin.
+
+ Sets proper title using ``title`` and if specified also ``admin_order_field``
+ using ``ordering_field`` attribute.
+ """
+ def decorator(func):
+ def wraps(self, obj):
+ result = func(self, obj)
+ return result if result else u'---'
+
+ wraps.short_description = title
+ wraps.allow_tags = True
+
+ if ordering_field:
+ wraps.admin_order_field = ordering_field
+
+ return wraps
+ return decorator
+
+
+class BorisChangeList(ChangeList):
+ """Change list_display with respect to request."""
+
+ remove_in_popup = ('actions_display',)
+
+ def __init__(self, request, *args, **kwargs):
+ super(BorisChangeList, self).__init__(request, *args, **kwargs)
+
+ # Display different buttons based on whether we render a pop-up window.
+ if 'pop' in request.GET:
+ if isinstance(self.list_display, tuple):
+ self.list_display = list(self.list_display)
+ self.list_display.insert(0, 'select_link')
+ self.list_display = filter(lambda x: x not in self.remove_in_popup,
+ self.list_display)
+
+
+class BorisBaseAdmin(ModelAdmin):
+ """
+ Adds ``list_actions`` to simplify addition of actions to changelist rows.
+ """
+ list_actions = ('change_button',)
+
+ def __init__(self, *args, **kwargs):
+ self.list_display += ('actions_display',)
+ super(BorisBaseAdmin, self).__init__(*args, **kwargs)
+
+ def get_changelist(self, request, **kwargs):
+ return BorisChangeList
+
+ def actions_display(self, obj):
+ return ''.join(getattr(self, a)(obj) for a in self.list_actions)
+ actions_display.allow_tags = True
+ actions_display.short_description = _(u'Akce')
+
+ def change_button(self, obj):
+ return u'%s' % (
+ obj.get_admin_url(), _('upravit'))
+
+ def select_link(self, obj):
+ return u'%s' % (
+ '%s/' % obj.pk, obj.pk, _('vybrat'))
+ select_link.allow_tags = True
+ select_link.short_description = ''
+
+ def show_save(self, obj):
+ if not obj or not obj.pk:
+ return True
+ return False
+
+ def show_save_as_new(self, obj):
+ return False
+
+ def show_save_and_continue(self, obj):
+ return True
+
+ def show_save_and_add_another(self, obj):
+ return False
+
+ def force_show_delete(self, obj):
+ return False
+
+ def button_captions(self, obj):
+ """
+ Specify various button captions.
+
+ Override to change the captions. The default values are in the
+ templates/admin/submit_line.html template. Below dictionary serves
+ to document all possible captions.
+
+ """
+ return {
+ 'BO_SAVE_CAPTION': '',
+ 'BO_SAVE_AS_NEW_CAPTION': '',
+ 'BO_SAVE_AND_CONT_CAPTION': '',
+ 'BO_SAVE_AND_ADD_ANOTHER_CAPTION': '',
+ 'BO_DELETE_CAPTION': '',
+ }
+
+ @csrf_protect_m
+ @transaction.atomic
+ def change_view(self, request, object_id, extra_context=None):
+ obj = self.get_object(request, object_id)
+ buttons_context = {
+ 'BO_SHOW_SAVE': self.show_save(obj),
+ 'BO_SHOW_SAVE_AS_NEW': self.show_save_as_new(obj),
+ 'BO_SHOW_SAVE_AND_CONT': self.show_save_and_continue(obj),
+ 'BO_SHOW_SAVE_AND_ADD_ANOTHER': self.show_save_and_add_another(obj),
+ 'BO_FORCE_SHOW_DELETE': self.force_show_delete(obj),
+ }
+ buttons_context.update(self.button_captions(obj))
+ if extra_context is not None:
+ extra_context.update(buttons_context)
+ else:
+ extra_context = buttons_context
+ return super(BorisBaseAdmin, self).change_view(request, object_id, extra_context=extra_context)
+
+ @csrf_protect_m
+ @transaction.atomic
+ def add_view(self, request, form_url='', extra_context=None):
+ empty_obj = self.model()
+ buttons_context = {
+ 'BO_SHOW_SAVE': self.show_save(empty_obj),
+ 'BO_SHOW_SAVE_AS_NEW': self.show_save_as_new(empty_obj),
+ 'BO_SHOW_SAVE_AND_CONT': self.show_save_and_continue(empty_obj),
+ 'BO_SHOW_SAVE_AND_ADD_ANOTHER': self.show_save_and_add_another(
+ empty_obj),
+ 'BO_FORCE_SHOW_DELETE': self.force_show_delete(empty_obj)
+ }
+ buttons_context.update(self.button_captions(empty_obj))
+ if extra_context is not None:
+ extra_context.update(buttons_context)
+ else:
+ extra_context = buttons_context
+ return super(BorisBaseAdmin, self).add_view(request, form_url, extra_context=extra_context)
diff --git a/pool/shard002/Python/0026163_handlers.py b/pool/shard002/Python/0026163_handlers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d7bdd149a5d2a10d72f8c170f39d431e2aabcc3
--- /dev/null
+++ b/pool/shard002/Python/0026163_handlers.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+
+import re
+from django.db.models import get_model
+from django.conf import settings
+from transifex.projects.signals import project_created, project_deleted
+from transifex.projects.models import Project
+
+def outsource_to_mozilla(sender, **kwargs):
+ """
+ Outsources translation of the newborn project to general Mozilla project
+ """
+ try:
+ mozilla = Project.objects.get(slug='mozilla')
+ sender.outsource = mozilla
+ sender.save()
+ except Project.DoesNotExist:
+ pass
+
+def connect():
+ project_created.connect(outsource_to_mozilla)
diff --git a/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py b/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..963e8f3f9ae56d43d8e1917ea6db917243faebcf
--- /dev/null
+++ b/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py
@@ -0,0 +1,23 @@
+#!/usr/bin/python
+# coding: utf-8
+
+class Solution(object):
+ def convert(self, s, numRows):
+ """
+ :type s: str
+ :type numRows: int
+ :rtype: str
+ """
+ if numRows < 2:
+ return s
+ res = []
+ lag = 2 * (numRows - 1)
+ num = len(s)
+ for i in range(numRows):
+ for j in range(i, num, lag):
+ res.append(s[j])
+ if i > 0 and i < numRows - 1:
+ n = j + lag - 2 * i
+ if n < num:
+ res.append(s[n])
+ return "".join(res)
diff --git a/pool/shard002/Python/0026168_crack_8_3.py b/pool/shard002/Python/0026168_crack_8_3.py
new file mode 100644
index 0000000000000000000000000000000000000000..317d1060ef0c11f0a480b9e4f1ad6e3ed6e3eba9
--- /dev/null
+++ b/pool/shard002/Python/0026168_crack_8_3.py
@@ -0,0 +1,21 @@
+import copy
+
+def subset(sets):
+ if len(sets) > 1:
+ sub = subset(sets[1:])
+ temp = copy.deepcopy(sub)
+ for s in sub:
+ t = s[:]
+ t.append(sets[0])
+ temp.append(t)
+ sub = copy.deepcopy(temp)
+ return sub
+ elif len(sets) == 1:
+ sub = []
+ sub.append([])
+ sub.append(sets)
+ return sub
+
+if __name__ == '__main__':
+ test = [1,2,3,4]
+ print subset(test)
\ No newline at end of file
diff --git a/pool/shard002/Python/0026170_XenAPIDomain.py b/pool/shard002/Python/0026170_XenAPIDomain.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ca2307c27749da5585818698ef70c840b5ab730
--- /dev/null
+++ b/pool/shard002/Python/0026170_XenAPIDomain.py
@@ -0,0 +1,183 @@
+#!/usr/bin/python
+"""
+ Copyright (C) International Business Machines Corp., 2005
+ Author: Stefan Berger
+
+ Based on XenDomain.py by Dan Smith
+
+ 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; under version 2 of the License.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+"""
+import os
+import sys
+from XmTestLib import *
+from types import DictType
+
+
+class XenAPIConfig:
+ """An object to help create a VM configuration usable via Xen-API"""
+ def __init__(self):
+ self.opts = {}
+ #Array to translate old option to new ones
+ self.opttrlate = { 'name' : 'name_label' ,
+ 'memory' : [ 'memory_static_max' ,
+ 'memory_static_min' ,
+ 'memory_dynamic_min',
+ 'memory_dynamic_max' ],
+ 'kernel' : 'PV_kernel',
+ 'ramdisk': 'PV_ramdisk',
+ 'root' : 'PV_args',
+ 'extra' : 'PV_args' }
+
+ def setOpt(self, name, value):
+ """Set an option in the config"""
+ if name == "memory":
+ value <<= 20
+ if name == "root":
+ value = "root=" + value
+ if name in self.opttrlate.keys():
+ _name = self.opttrlate[name]
+ else:
+ _name = name
+
+ if isinstance(_name, list):
+ for _n in _name:
+ self.opts[_n] = value
+ else:
+ if not self.opts.get(_name) or \
+ not _name in [ "PV_args" ]:
+ self.opts[_name] = value
+ else:
+ self.opts[_name] += " " + value
+
+ def getOpt(self, name):
+ """Return the value of a config option"""
+ if name in self.opts.keys():
+ return self.opts[name]
+ else:
+ return None
+
+ def setOpts(self, opts):
+ """Batch-set options from a dictionary"""
+ for k, v in opts.items():
+ self.setOpt(k, v)
+
+ def getOpts(self):
+ return self.opts
+
+
+class XenAPIDomain(XenDomain):
+
+ def __init__(self, name=None, config=None):
+ if name:
+ self.name = name
+ else:
+ self.name = getUniqueName()
+
+ self.config = config
+ self.console = None
+ self.netEnv = "bridge"
+
+ self.session = xapi.connect()
+ try:
+ self.vm_uuid = self.session.xenapi.VM.create(self.config.getOpts())
+ addXAPIDomain(self.vm_uuid)
+ except:
+ raise DomainError("Could not create VM config file for "
+ "managed domain.")
+
+ #Only support PV for now.
+ self.type = "PV"
+
+ def start(self, noConsole=False, startpaused=False):
+ #start the VM
+ session = self.session
+ if self.vm_uuid:
+ try:
+ session.xenapi.VM.start(self.vm_uuid, startpaused)
+ except:
+ raise DomainError("Could not start domain")
+ else:
+ raise DomainError("VM has no UUID - does VM config exist?")
+
+ if startpaused:
+ return
+
+ if self.getDomainType() == "HVM":
+ waitForBoot()
+
+ if self.console and noConsole == True:
+ self.closeConsole()
+
+ elif self.console and noConsole == False:
+ return self.console
+
+ elif not self.console and noConsole == False:
+ return self.getConsole()
+
+ def stop(self):
+ if self.vm_uuid:
+ self.session.xenapi.VM.hard_shutdown(self.vm_uuid)
+ else:
+ raise DomainError("VM has no UUID - does VM config exist?")
+
+ def destroy(self):
+ #Stop VM first.
+ self.stop()
+ if self.vm_uuid:
+ self.session.xenapi.VM.destroy(self.vm_uuid)
+ delXAPIDomain(self.vm_uuid)
+ else:
+ raise DomainError("VM has no UUID - does VM config exist?")
+
+ def get_uuid(self):
+ return self.vm_uuid
+
+ def newDevice(self, Device, *args):
+ raise DomainError("No support for newDevice().")
+
+ def removeDevice(self, id):
+ raise DomainError("No support for removeDevice().")
+
+ def removeAllDevices(self, id):
+ raise DomainError("No support for removeAllDevices().")
+
+ def isRunning(self):
+ return isDomainRunning(self.name)
+
+ def getDevice(self, id):
+ raise DomainError("No support for getDevice().")
+
+
+class XmTestAPIDomain(XenAPIDomain):
+
+ """Create a new managed xm-test domain
+ @param name: The requested domain name
+ @param extraConfig: Additional configuration options
+ @param baseConfig: The initial configuration defaults to use
+ """
+ def __init__(self, name=None, extraConfig=None,
+ baseConfig=arch.configDefaults):
+ config = XenAPIConfig()
+ config.setOpts(baseConfig)
+ if extraConfig:
+ config.setOpts(extraConfig)
+
+ if name:
+ config.setOpt("name_label", name)
+ elif not config.getOpt("name_label"):
+ config.setOpt("name_label", getUniqueName())
+
+ XenAPIDomain.__init__(self, config.getOpt("name_label"),
+ config=config)
diff --git a/pool/shard002/Python/0026172_test_cases.py b/pool/shard002/Python/0026172_test_cases.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1b0ed5187d5ed06d6bc0cbfc000e7121d9ad150
--- /dev/null
+++ b/pool/shard002/Python/0026172_test_cases.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+
+from django.core.management import call_command
+from django.test import TestCase
+
+import supervisor.xmlrpc
+import xmlrpclib
+
+
+class CeleryMonTestCase(TestCase):
+ def test_a_is_down(self):
+ server = xmlrpclib.ServerProxy(
+ 'http://127.0.0.1',
+ transport=supervisor.xmlrpc.SupervisorTransport(
+ None, None, 'unix:///var/run/supervisor.sock')
+ )
+
+ self.assertEquals(
+ server.supervisor.getProcessInfo('default').get('state'), 20)
+ self.assertEquals(
+ server.supervisor.getProcessInfo('mail').get('state'), 20)
+
+ server.supervisor.stopProcess('default')
+
+ self.assertEquals(
+ server.supervisor.getProcessInfo('default').get('state'), 0)
+ self.assertEquals(
+ server.supervisor.getProcessInfo('mail').get('state'), 20)
+
+ call_command('check_celery_state')
+
+ self.assertEquals(
+ server.supervisor.getProcessInfo('default').get('state'), 20)
+ self.assertEquals(
+ server.supervisor.getProcessInfo('mail').get('state'), 20)
diff --git a/pool/shard002/Python/0026183_services.py b/pool/shard002/Python/0026183_services.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffbd4ebb532f5fb63579b1a86cd4f3805908b09f
--- /dev/null
+++ b/pool/shard002/Python/0026183_services.py
@@ -0,0 +1,68 @@
+# Copyright (C) 2010-2014 GRNET S.A.
+#
+# 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 copy import deepcopy
+from synnefo.lib import join_urls
+from urlparse import urlparse
+
+
+def fill_endpoints(services, base_url):
+ for name, service in services.iteritems():
+ prefix = service['prefix']
+ endpoints = service['endpoints']
+ for endpoint in endpoints:
+ version = endpoint['versionId']
+ publicURL = endpoint['publicURL']
+ if publicURL is not None:
+ continue
+
+ publicURL = join_urls(base_url, prefix, version).rstrip('/')
+ endpoint['publicURL'] = publicURL
+
+
+def filter_public(services):
+ public_services = {}
+ for name, service in services.iteritems():
+ if service.get('public', False):
+ public_services[name] = deepcopy(service)
+ return public_services
+
+
+def get_public_endpoint(services, service_type, version=None):
+ found_endpoints = {}
+ for service_name, service in services.iteritems():
+ if service_type != service['type']:
+ continue
+
+ for endpoint in service['endpoints']:
+ endpoint_version = endpoint['versionId']
+ if version is not None:
+ if version != endpoint_version:
+ continue
+ found_endpoints[endpoint_version] = endpoint
+
+ if not found_endpoints:
+ m = "No endpoint found for service type '{0}'".format(service_type)
+ if version is not None:
+ m += " and version '{0}'".format(version)
+ raise ValueError(m)
+
+ selected = sorted(found_endpoints.keys())[-1]
+ return found_endpoints[selected]['publicURL']
+
+
+def get_service_path(services, service_type, version=None):
+ service_url = get_public_endpoint(services, service_type, version=version)
+ return urlparse(service_url).path.rstrip('/')
diff --git a/pool/shard002/Python/0026185_package.py b/pool/shard002/Python/0026185_package.py
new file mode 100644
index 0000000000000000000000000000000000000000..c339abf1f038c36b2a2035651bf279931cfe0bf9
--- /dev/null
+++ b/pool/shard002/Python/0026185_package.py
@@ -0,0 +1,37 @@
+# Copyright 2013-2021 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 *
+
+
+class Lis(AutotoolsPackage):
+ """Lis (Library of Iterative Solvers for linear systems,
+ pronounced [lis]) is a parallel software library for
+ solving discretized linear equations and eigenvalue
+ problems that arise in the numerical solution of partial
+ differential equations using iterative methods."""
+
+ homepage = "https://www.ssisc.org/lis/index.en.html"
+ url = "https://www.ssisc.org/lis/dl/lis-2.0.27.zip"
+
+ version('2.0.27', sha256='85f32f4abbc94d1b40b22c10b915170271b19822b6aa6939b1cb295f6e455237')
+
+ variant('mpi', default=False, description='Build with MPI library')
+ variant('omp', default=False, description='Build with openMP library')
+ variant('f90', default=False, description='enable FORTRAN 90 compatible interfaces')
+
+ depends_on('mpi', when='+mpi')
+
+ def configure_args(self):
+ config_args = []
+ config_args.extend(self.enable_or_disable('mpi'))
+ config_args.extend(self.enable_or_disable('omp'))
+ config_args.extend(self.enable_or_disable('f90'))
+
+ if self.spec.satisfies('%fj'):
+ config_args.append('CLIBS=-lm')
+ config_args.append('FCLDFLAGS=-mlcmain=main')
+
+ return config_args
diff --git a/pool/shard002/Python/0026201_import_existing_files.py b/pool/shard002/Python/0026201_import_existing_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..83e8c69009c94aa136e7521485cd82a07f3c7f1e
--- /dev/null
+++ b/pool/shard002/Python/0026201_import_existing_files.py
@@ -0,0 +1,76 @@
+import os
+import re
+
+from filer.models import File, Image, Folder
+from filer_addons.filer_utils.management.commands.subcommands.base import SubcommandsCommand
+
+
+def is_image(filename):
+ name, ext = os.path.splitext(filename)
+ if ext.lower()[1:] in ['jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff']:
+ return True
+
+
+# TODO: via setting
+file_exclude_pattern = r'(_fb_thumb\.)|(_fancybox_thumb\.)|(_home_image\.)|(_left_col_small\.)' \
+ r'|(_partner\.)|(_people\.)|(_small\.)|(_thumbnail\.)'
+file_exclude_pattern = r'_q85'
+
+folder_exclude_pattern = r'(_big)|(_thumb)'
+
+
+class ImportExistingFilesCommand(SubcommandsCommand):
+ help_string = "Import existing files not currently in filer db, but on " \
+ "filesystem. Must use --force, if you have existing files" \
+ "in your database"
+ command_name = 'import_existing_files'
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ '--force',
+ action='store_true',
+ dest='force',
+ default=False,
+ help='Force import, with existing content in database.',
+ )
+
+ def handle(self, *args, **options):
+ print(File.objects.count())
+ if not options.get('force', False) and File.objects.count():
+ raise Exception('Must use --force, you have existing files in db!')
+
+ from filer import settings as filer_settings
+ self.storage_public = filer_settings.FILER_PUBLICMEDIA_STORAGE
+ self.prefix_public = filer_settings.FILER_STORAGES['public']['main']['UPLOAD_TO_PREFIX']
+
+ def walk(absdir, reldir, db_folder):
+ print("walk %s" % db_folder)
+ storage = self.storage_public
+ child_dirs, files = storage.listdir(absdir)
+ for filename in files:
+ matches = []
+ if file_exclude_pattern:
+ matches = re.findall(file_exclude_pattern, filename)
+ if not len(matches):
+ filename_with_relpath = os.path.join(reldir, filename)
+ # media_root = os.path.join(self.storage_public.location)
+ # filename_with_abspath = os.path.join(media_root, filename_with_relpath)
+ # django_file = DjangoFile(open(filename_with_abspath, 'rb'), name=filename)
+ file_cls = File
+ if is_image(filename):
+ file_cls = Image
+ file_cls.objects.create(
+ original_filename=filename,
+ folder=db_folder,
+ file=filename_with_relpath,
+ is_public=True,
+ )
+ for child in child_dirs:
+ kwargs = {}
+ if db_folder:
+ kwargs['parent'] = db_folder
+ new_folder, created = Folder.objects.get_or_create(name=child, **kwargs)
+ walk(os.path.join(absdir, child), os.path.join(reldir, child), new_folder)
+
+ public_path = os.path.join(self.storage_public.location, self.prefix_public)
+ walk(public_path, self.prefix_public, None)
diff --git a/pool/shard002/Python/0026205_rule3_1.py b/pool/shard002/Python/0026205_rule3_1.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bdde203a48d7d09556d35b4b44e99537158a439
--- /dev/null
+++ b/pool/shard002/Python/0026205_rule3_1.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+
+from rules.rule import *
+
+class Rule(KLCRule):
+ """
+ Create the methods check and fix to use with the kicad lib files.
+ """
+ def __init__(self, component):
+ super(Rule, self).__init__(component, 'Rule 3.1', 'Using a 100mils grid, pin ends and origin must lie on grid nodes (IEC-60617).')
+
+ def check(self):
+ """
+ Proceeds the checking of the rule.
+ The following variables will be accessible after checking:
+ * violating_pins
+ """
+ self.violating_pins = []
+ for pin in self.component.pins:
+ posx = int(pin['posx'])
+ posy = int(pin['posy'])
+ if (posx % 100) != 0 or (posy % 100) != 0:
+ self.violating_pins.append(pin)
+ self.verboseOut(Verbosity.HIGH, Severity.ERROR, 'pin: {0} ({1}), {2}'.format(pin['name'], pin['num'], positionFormater(pin)))
+
+ return True if len(self.violating_pins) > 0 else False
+
+ def fix(self):
+ """
+ Proceeds the fixing of the rule, if possible.
+ """
+ self.verboseOut(Verbosity.NORMAL, Severity.INFO, "FIX: not yet supported" )
+ # TODO
diff --git a/pool/shard002/Python/0026206_Estimation-labeled-l5.py b/pool/shard002/Python/0026206_Estimation-labeled-l5.py
new file mode 100644
index 0000000000000000000000000000000000000000..401e66c5df7bb8801ac04fc62eaf9e80ceb9aa64
--- /dev/null
+++ b/pool/shard002/Python/0026206_Estimation-labeled-l5.py
@@ -0,0 +1,83 @@
+# Copyright (C) 2017 Zhixian MA
+
+import sys
+import os
+import pickle
+import numpy as np
+
+import utils
+import ConvNet
+import ConvAE_FT
+
+def pos_to_line(label_pos):
+ return np.max(label_pos,axis=1)
+
+def main(argv):
+
+ # folder for saving
+ subfold = argv[1]
+ if not os.path.exists(subfold):
+ os.mkdir(subfold)
+ # load data
+ fname = '../LRG-fits/data/lrg_171020/sample-LRG-120-120-10-c3.pkl'
+ with open(fname, 'rb') as fp:
+ datadict = pickle.load(fp)
+ X_raw = datadict['data']
+
+ # Reshape and generate train and test dataset
+ rs = 120
+ # normalization and whitening
+ '''
+ with open("../nets/norm_params.pkl", 'rb') as fp:
+ normparam = pickle.load(fp)
+ X_max = normparam["X_max"]
+ X_min = normparam["X_min"]
+ X_mean = normparam["X_mean"]
+
+ X_train_pre = X_raw
+ X_train_pre = (X_train_pre - X_min) / (X_max - X_min)
+ X_in = X_train_pre.reshape(-1,rs,rs,1)
+ X_mean = np.mean(X_train_pre)
+ X_w = X_in - X_mean # Whitening?
+ '''
+ X_w = X_raw.reshape(-1,rs,rs,1).astype('float32')
+
+ numclass = 2
+ encode_nodes = 64
+ cnn = ConvNet.ConvNet(input_shape=X_w.shape,
+ kernel_size=[3,3,3,3,3],
+ kernel_num = [8,8,16,32,32],
+ fc_nodes=[], encode_nodes=encode_nodes,
+ padding=('SAME','SAME'),
+ stride=(2,2),
+ numclass = numclass,
+ sess = None,
+ name = None)
+ cnn.cae_build()
+ cnn.cnn_build(learning_rate=0.001) # In order to init the weights
+
+
+ foldname = "{0}/net_l5_140".format(subfold)
+ name = "net_l5.pkl"
+ cnn.sess, cnn.name = utils.load_net(os.path.join(foldname, name))
+
+ # estimate
+ label, label_pos = cnn.cnn_predict(img=X_w)
+ label_new_pos = pos_to_line(label_pos)
+
+ # save result
+ savefold = "{0}/est_labeled".format(subfold)
+ if not os.path.exists(savefold):
+ os.mkdir(savefold)
+ savepath = "est_l5.pkl"
+ savedict = {"label_raw": np.array(datadict['type']),
+ "z": np.array(datadict['redshift']),
+ "snvss": np.array(datadict['snvss']),
+ "name": np.array(datadict['name']),
+ "label_est": label,
+ "label_pos": label_new_pos}
+ with open(os.path.join(savefold,savepath), 'wb') as fp:
+ pickle.dump(savedict, fp)
+
+if __name__ == "__main__":
+ main(sys.argv)
diff --git a/pool/shard002/Python/0026216_dfu.py b/pool/shard002/Python/0026216_dfu.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d8fc154ec1fced559f578d61ecf02848a2080f8
--- /dev/null
+++ b/pool/shard002/Python/0026216_dfu.py
@@ -0,0 +1,59 @@
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+from future import standard_library
+standard_library.install_aliases()
+from builtins import str
+from builtins import object
+import os
+import esptool
+import urllib.request
+
+from .consts import IotsaError, VERBOSE
+
+class DFU(object):
+ """Handle Resetting flash and uploading initial binary over Serial connection (or USB)"""
+ def __init__(self, port=None):
+ self.port = port
+
+ def _run(self, cmd, args=[], nostub=False):
+ """Run a single esptool command"""
+ command = ["--after", "no_reset"]
+ if self.port:
+ command += ["--port", self.port]
+ if nostub:
+ command += ["--no-stub"]
+ command += [cmd]
+ command += args
+ try:
+ esptool.main(command)
+ except esptool.FatalError as e:
+ raise IotsaError(str(e))
+
+ def dfuWait(self):
+ """Test to see whether a board in programmable mode is connected"""
+ try:
+ self._run("chip_id", nostub=True)
+ except IotsaError:
+ print("** To use DFU mode on a iotsa device:")
+ print(" 1. Connect iotsa device to serial using FTDI232 or similar interface")
+ print(" 2. Ensure iotsa device is powered through normal power supply")
+ print(" 3. Press-and-hold PRG button while pressing RST button")
+ raise
+
+ def dfuClear(self):
+ """Erase flash"""
+ self.dfuWait()
+ self._run("erase_flash")
+
+ def dfuRun(self):
+ """Run program stored in iotsa flash memory"""
+ self.dfuWait()
+ self._run("run", nostub=True)
+
+ def dfuLoad(self, filename):
+ """Load a new program into iotsa flash memory"""
+ self.dfuWait()
+ if not os.path.exists(filename):
+ filename, _ = urllib.request.urlretrieve(filename)
+ self._run("write_flash", args=["0", filename])
diff --git a/pool/shard002/Python/0026218_promisc_kernel.py b/pool/shard002/Python/0026218_promisc_kernel.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ed43e9777f4f073858ce017810049732a6ffc5
--- /dev/null
+++ b/pool/shard002/Python/0026218_promisc_kernel.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+
+# 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/.
+# Copyright (c) 2014 Mozilla Corporation
+#
+# This code alerts on every successfully opened session on any of the host from a given list
+
+from lib.alerttask import AlertTask
+from mozdef_util.query_models import SearchQuery, TermMatch, QueryStringMatch, PhraseMatch
+
+
+class PromiscKernel(AlertTask):
+ def main(self):
+
+ search_query = SearchQuery(minutes=2)
+
+ search_query.add_must([
+ TermMatch('category', 'syslog'),
+ PhraseMatch('summary', 'promiscuous'),
+ PhraseMatch('summary', 'entered')
+ ])
+
+ search_query.add_must_not([
+ QueryStringMatch('summary: veth*'),
+ ])
+
+ self.filtersManual(search_query)
+ self.searchEventsAggregated('hostname', samplesLimit=10)
+ self.walkAggregations(threshold=1)
+
+ def onAggregation(self, aggreg):
+ category = 'promisc'
+ severity = 'WARNING'
+ tags = ['promisc', 'kernel']
+
+ summary = 'Promiscuous mode enabled on {1} [{0}]'.format(aggreg['count'], aggreg['value'])
+
+ return self.createAlertDict(summary, category, tags, aggreg['events'], severity)
diff --git a/pool/shard002/Python/0026222_corrector.py b/pool/shard002/Python/0026222_corrector.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fd87307395a7799ff02a3a96db0170c529a45cf
--- /dev/null
+++ b/pool/shard002/Python/0026222_corrector.py
@@ -0,0 +1,76 @@
+#coding=utf-8
+from __future__ import unicode_literals
+
+import re
+import os
+
+from bwikibot.cli import get_wiki, action
+from bwikibot.ui import print_diff, ask_y_n
+from bwikibot.utils import ON_2
+
+if ON_2:
+ from codecs import open
+
+
+@action('spell')
+def spell(*page_name):
+ ''' Make autocorrection with dictionary '''
+ wiki = get_wiki()
+
+ page = wiki.page(' '.join(page_name))
+ text = page.read()
+ if not page.exists():
+ print('Page "%s" not exists!' % page.title)
+ return
+ correction = correct(text)
+
+ if correction == text:
+ print('Текст в порядку')
+ return
+
+ print_diff(text, correction)
+ if ask_y_n('Здійснити виправлення?'):
+ print('Виправляємо')
+ page.write(correction, 'автовиправлення по словнику')
+
+
+def here(filename):
+ return os.path.join(os.path.dirname(__file__), filename)
+
+class Corrector:
+ def __init__(self):
+ self.substitutions = []
+
+ with open(here('genitive_a_u.txt'), encoding='utf-8') as f:
+ self.load_genitive_a_u(f)
+
+ def load_genitive_a_u(self, f):
+ for word in f:
+ word = word.strip()
+ if word.endswith('а'):
+ err_end = 'у'
+ elif word.endswith('у'):
+ err_end = 'а'
+ else:
+ print('Слово "%s" має помилкове закінчення' % word)
+ continue
+
+ self.substitutions.append((
+ word[:-1] + err_end + r'\b',
+ word
+ ))
+
+ word = word.capitalize()
+ self.substitutions.append((
+ word[:-1] + err_end + r'\b',
+ word
+ ))
+
+ def correct(self, text):
+ for subst in self.substitutions:
+ text = re.sub(subst[0], subst[1], text, flags=re.U)
+ return text
+
+ __call__ = correct # shortcut for main action of this class
+
+correct = Corrector()
diff --git a/pool/shard002/Python/0026223_init__.py b/pool/shard002/Python/0026223_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01a52ef633784f198959569e1dbad8db7f493159
--- /dev/null
+++ b/pool/shard002/Python/0026223_init__.py
@@ -0,0 +1,223 @@
+# Copyright 2014-2015 ARM Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+
+# pylint: disable=E1101
+import os
+import re
+import time
+
+import pexpect
+
+from wlauto import BigLittleDevice, Parameter
+from wlauto.exceptions import DeviceError
+from wlauto.utils.serial_port import open_serial_connection, pulse_dtr
+from wlauto.utils.android import adb_connect, adb_disconnect, adb_list_devices
+from wlauto.utils.uefi import UefiMenu, UefiConfig
+from wlauto.utils.uboot import UbootMenu
+
+
+AUTOSTART_MESSAGE = 'Press Enter to stop auto boot...'
+
+
+class Juno(BigLittleDevice):
+
+ name = 'juno'
+ description = """
+ ARM Juno next generation big.LITTLE development platform.
+ """
+
+ capabilities = ['reset_power']
+
+ has_gpu = True
+
+ core_modules = [
+ 'vexpress',
+ ]
+
+ parameters = [
+ Parameter('retries', kind=int, default=2,
+ description="""Specifies the number of times the device will attempt to recover
+ (normally, with a hard reset) if it detects that something went wrong."""),
+
+ Parameter('microsd_mount_point', default='/media/JUNO',
+ description='Location at which the device\'s MicroSD card will be mounted.'),
+ Parameter('port', default='/dev/ttyS0', description='Serial port on which the device is connected.'),
+ Parameter('baudrate', kind=int, default=115200, description='Serial connection baud.'),
+ Parameter('timeout', kind=int, default=300, description='Serial connection timeout.'),
+ Parameter('core_names', default=['a53', 'a53', 'a53', 'a53', 'a57', 'a57'], override=True),
+ Parameter('core_clusters', default=[0, 0, 0, 0, 1, 1], override=True),
+
+ Parameter('bootloader', default='uefi', allowed_values=['uefi', 'u-boot'],
+ description="""Bootloader used on the device."""),
+ Parameter('actually_disconnect', kind=bool, default=False,
+ description="""
+ Actually perfom "adb disconnect" on closing the connection to the device.
+ """),
+
+ # VExpress flasher expects a device to have these:
+ Parameter('uefi_entry', default='WA',
+ description='The name of the entry to use (will be created if does not exist).'),
+ Parameter('uefi_config', kind=UefiConfig,
+ description='''Specifies the configuration for the UEFI entry for his device. In an
+ entry specified by ``uefi_entry`` parameter doesn't exist in UEFI menu,
+ it will be created using this config. This configuration will also be
+ used, when flashing new images.''',
+ default={
+ 'image_name': 'Image',
+ 'image_args': None, # populated from bootargs if not specified
+ 'fdt_support': True,
+ }
+ ),
+ Parameter('bootargs', default='console=ttyAMA0,115200 earlyprintk=pl011,0x7ff80000 '
+ 'verbose debug init=/init root=/dev/sda1 rw ip=dhcp '
+ 'rootwait video=DVI-D-1:1920x1080R@60',
+ description='''Default boot arguments to use when boot_arguments were not.'''),
+ ]
+
+ short_delay = 1
+ firmware_prompt = 'Cmd>'
+
+ def validate(self):
+ if not self.uefi_config.image_args:
+ self.uefi_config.image_args = self.bootargs
+
+ def boot(self, hard=False, **kwargs):
+ if kwargs:
+ self.bootargs = kwargs # pylint: disable=attribute-defined-outside-init
+ if hard:
+ self.logger.debug('Performing a hard reset.')
+ self.hard_reset()
+ else:
+ self.logger.debug('Resetting the device.')
+ self.reset()
+ if self.bootloader == 'uefi':
+ self._boot_via_uefi()
+ else:
+ self._boot_via_uboot(bootargs=self.bootargs)
+
+ def _boot_via_uboot(self, **kwargs):
+ if not kwargs:
+ # Standard linaro configuration will proceed directly to the kernel
+ return
+ with open_serial_connection(port=self.port,
+ baudrate=self.baudrate,
+ timeout=self.timeout,
+ init_dtr=0) as target:
+ menu = UbootMenu(target)
+ self.logger.debug('Waiting for U-Boot prompt...')
+ menu.open(timeout=120)
+ for var, value in kwargs.iteritems():
+ menu.setenv(var, value)
+ menu.boot()
+
+ def _boot_via_uefi(self):
+ with open_serial_connection(port=self.port,
+ baudrate=self.baudrate,
+ timeout=self.timeout,
+ init_dtr=0) as target:
+ menu = UefiMenu(target)
+ self.logger.debug('Waiting for UEFI menu...')
+ menu.open(timeout=120)
+ try:
+ menu.select(self.uefi_entry)
+ except LookupError:
+ self.logger.debug('{} UEFI entry not found.'.format(self.uefi_entry))
+ self.logger.debug('Attempting to create one using default flasher configuration.')
+ menu.create_entry(self.uefi_entry, self.uefi_config)
+ menu.select(self.uefi_entry)
+ self.logger.debug('Waiting for the Android prompt.')
+ target.expect(self.android_prompt, timeout=self.timeout)
+
+ def connect(self):
+ if not self._is_ready:
+ if not self.adb_name: # pylint: disable=E0203
+ with open_serial_connection(timeout=self.timeout,
+ port=self.port,
+ baudrate=self.baudrate,
+ init_dtr=0) as target:
+ target.sendline('')
+ self.logger.debug('Waiting for the Android prompt.')
+ target.expect(self.android_prompt)
+
+ self.logger.debug('Waiting for IP address...')
+ wait_start_time = time.time()
+ while True:
+ target.sendline('ip addr list eth0')
+ time.sleep(1)
+ try:
+ target.expect('inet ([1-9]\d*.\d+.\d+.\d+)', timeout=10)
+ self.adb_name = target.match.group(1) + ':5555' # pylint: disable=W0201
+ break
+ except pexpect.TIMEOUT:
+ pass # We have our own timeout -- see below.
+ if (time.time() - wait_start_time) > self.ready_timeout:
+ raise DeviceError('Could not acquire IP address.')
+
+ if self.adb_name in adb_list_devices():
+ adb_disconnect(self.adb_name)
+ adb_connect(self.adb_name, timeout=self.timeout)
+ super(Juno, self).connect() # wait for boot to complete etc.
+ self._is_ready = True
+
+ def disconnect(self):
+ if self._is_ready:
+ super(Juno, self).disconnect()
+ if self.actually_disconnect:
+ adb_disconnect(self.adb_name)
+ self._is_ready = False
+
+ def reset(self):
+ # Currently, reboot is not working in Android on Juno, so
+ # perfrom a ahard reset instead
+ self.hard_reset()
+
+ def hard_reset(self):
+ self.disconnect()
+ self.adb_name = None # Force re-acquire IP address on reboot. pylint: disable=attribute-defined-outside-init
+ with open_serial_connection(port=self.port,
+ baudrate=self.baudrate,
+ timeout=300,
+ init_dtr=0,
+ get_conn=True) as (target, conn):
+ pulse_dtr(conn, state=True, duration=0.1) # TRM specifies a pulse of >=100ms
+
+ i = target.expect([AUTOSTART_MESSAGE, self.firmware_prompt])
+ if i:
+ self.logger.debug('Saw firmware prompt.')
+ time.sleep(self.short_delay)
+ target.sendline('reboot')
+ else:
+ self.logger.debug('Saw auto boot message.')
+
+ def wait_for_microsd_mount_point(self, target, timeout=100):
+ attempts = 1 + self.retries
+ if os.path.exists(os.path.join(self.microsd_mount_point, 'config.txt')):
+ return
+
+ self.logger.debug('Waiting for VExpress MicroSD to mount...')
+ for i in xrange(attempts):
+ if i: # Do not reboot on the first attempt.
+ target.sendline('reboot')
+ for _ in xrange(timeout):
+ time.sleep(self.short_delay)
+ if os.path.exists(os.path.join(self.microsd_mount_point, 'config.txt')):
+ return
+ raise DeviceError('Did not detect MicroSD mount on {}'.format(self.microsd_mount_point))
+
+ def get_android_id(self):
+ # Android ID currenlty not set properly in Juno Android builds.
+ return 'abad1deadeadbeef'
+
diff --git a/pool/shard002/Python/0026226_dr.py b/pool/shard002/Python/0026226_dr.py
new file mode 100644
index 0000000000000000000000000000000000000000..34a04bcc103842dadc23299da4080be138292190
--- /dev/null
+++ b/pool/shard002/Python/0026226_dr.py
@@ -0,0 +1,14 @@
+from pcs import usage
+from pcs.cli import dr
+from pcs.cli.common.routing import create_router
+
+dr_cmd = create_router(
+ {
+ "help": lambda lib, argv, modifiers: print(usage.dr(argv)),
+ "config": dr.config,
+ "destroy": dr.destroy,
+ "set-recovery-site": dr.set_recovery_site,
+ "status": dr.status,
+ },
+ ["dr"],
+)
diff --git a/pool/shard002/Python/0026227_freeze_graph.py b/pool/shard002/Python/0026227_freeze_graph.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6a456833987aaebb236e9eaf12533557ce803dd
--- /dev/null
+++ b/pool/shard002/Python/0026227_freeze_graph.py
@@ -0,0 +1,135 @@
+# Copyright 2015 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.
+# ==============================================================================
+"""Converts checkpoint variables into Const ops in a standalone GraphDef file.
+
+This script is designed to take a GraphDef proto, a SaverDef proto, and a set of
+variable values stored in a checkpoint file, and output a GraphDef with all of
+the variable ops converted into const ops containing the values of the
+variables.
+
+It's useful to do this when we need to load a single file in C++, especially in
+environments like mobile or embedded where we may not have access to the
+RestoreTensor ops and file loading calls that they rely on.
+
+An example of command-line usage is:
+bazel build tensorflow/python/tools:freeze_graph && \
+bazel-bin/tensorflow/python/tools/freeze_graph \
+--input_graph=some_graph_def.pb \
+--input_checkpoint=model.ckpt-8361242 \
+--output_graph=/tmp/frozen_graph.pb --output_node_names=softmax
+
+You can also look at freeze_graph_test.py for an example of how to use it.
+
+"""
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+
+import tensorflow as tf
+
+from google.protobuf import text_format
+from tensorflow.python.framework import graph_util
+
+
+FLAGS = tf.app.flags.FLAGS
+
+tf.app.flags.DEFINE_string("input_graph", "",
+ """TensorFlow 'GraphDef' file to load.""")
+tf.app.flags.DEFINE_string("input_saver", "",
+ """TensorFlow saver file to load.""")
+tf.app.flags.DEFINE_string("input_checkpoint", "",
+ """TensorFlow variables file to load.""")
+tf.app.flags.DEFINE_string("output_graph", "",
+ """Output 'GraphDef' file name.""")
+tf.app.flags.DEFINE_boolean("input_binary", False,
+ """Whether the input files are in binary format.""")
+tf.app.flags.DEFINE_string("output_node_names", "",
+ """The name of the output nodes, comma separated.""")
+tf.app.flags.DEFINE_string("restore_op_name", "save/restore_all",
+ """The name of the master restore operator.""")
+tf.app.flags.DEFINE_string("filename_tensor_name", "save/Const:0",
+ """The name of the tensor holding the save path.""")
+tf.app.flags.DEFINE_boolean("clear_devices", True,
+ """Whether to remove device specifications.""")
+tf.app.flags.DEFINE_string("initializer_nodes", "", "comma separated list of "
+ "initializer nodes to run before freezing.")
+
+
+def freeze_graph(input_graph, input_saver, input_binary, input_checkpoint,
+ output_node_names, restore_op_name, filename_tensor_name,
+ output_graph, clear_devices, initializer_nodes):
+ """Converts all variables in a graph and checkpoint into constants."""
+
+ if not tf.gfile.Exists(input_graph):
+ print("Input graph file '" + input_graph + "' does not exist!")
+ return -1
+
+ if input_saver and not tf.gfile.Exists(input_saver):
+ print("Input saver file '" + input_saver + "' does not exist!")
+ return -1
+
+ # 'input_checkpoint' may be a prefix if we're using Saver V2 format
+ if not tf.train.checkpoint_exists(input_checkpoint):
+ print("Input checkpoint '" + input_checkpoint + "' doesn't exist!")
+ return -1
+
+ if not output_node_names:
+ print("You need to supply the name of a node to --output_node_names.")
+ return -1
+
+ input_graph_def = tf.GraphDef()
+ mode = "rb" if input_binary else "r"
+ with tf.gfile.FastGFile(input_graph, mode) as f:
+ if input_binary:
+ input_graph_def.ParseFromString(f.read())
+ else:
+ text_format.Merge(f.read().decode("utf-8"), input_graph_def)
+ # Remove all the explicit device specifications for this node. This helps to
+ # make the graph more portable.
+ if clear_devices:
+ for node in input_graph_def.node:
+ node.device = ""
+ _ = tf.import_graph_def(input_graph_def, name="")
+
+ with tf.Session() as sess:
+ if input_saver:
+ with tf.gfile.FastGFile(input_saver, mode) as f:
+ saver_def = tf.train.SaverDef()
+ if input_binary:
+ saver_def.ParseFromString(f.read())
+ else:
+ text_format.Merge(f.read(), saver_def)
+ saver = tf.train.Saver(saver_def=saver_def)
+ saver.restore(sess, input_checkpoint)
+ else:
+ sess.run([restore_op_name], {filename_tensor_name: input_checkpoint})
+ if initializer_nodes:
+ sess.run(initializer_nodes)
+ output_graph_def = graph_util.convert_variables_to_constants(
+ sess, input_graph_def, output_node_names.split(","))
+
+ with tf.gfile.GFile(output_graph, "wb") as f:
+ f.write(output_graph_def.SerializeToString())
+ print("%d ops in the final graph." % len(output_graph_def.node))
+
+
+def main(unused_args):
+ freeze_graph(FLAGS.input_graph, FLAGS.input_saver, FLAGS.input_binary,
+ FLAGS.input_checkpoint, FLAGS.output_node_names,
+ FLAGS.restore_op_name, FLAGS.filename_tensor_name,
+ FLAGS.output_graph, FLAGS.clear_devices, FLAGS.initializer_nodes)
+
+if __name__ == "__main__":
+ tf.app.run()
diff --git a/pool/shard002/Python/0026229_test_index.py b/pool/shard002/Python/0026229_test_index.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5351c2b101796adf81c5d92f4b4e9f27903b80e
--- /dev/null
+++ b/pool/shard002/Python/0026229_test_index.py
@@ -0,0 +1,94 @@
+import unittest
+import numpy as np
+
+from numcube import Index
+
+
+class IndexTests(unittest.TestCase):
+
+ def test_create_index(self):
+ a = Index("A", [10, 20, 30])
+ self.assertEqual(a.name, "A")
+ self.assertEqual(len(a), 3)
+
+ a = Index("Dim", ["a", "b", "c", "d"])
+ self.assertEqual(a.name, "Dim")
+ self.assertEqual(len(a), 4)
+
+ # duplicate values
+ self.assertRaises(ValueError, Index, "A", ["a", "b", "a"])
+ self.assertRaises(ValueError, Index, "A", [0, 1, 1])
+
+ # invalid Index name
+ self.assertRaises(TypeError, Index, 1, [1, 2, 3])
+
+ def test_index_take(self):
+ a = Index("A", ["a", "b", "c", "d"])
+ self.assertEqual(a.take([0, 2]).name, "A") # keep name
+ self.assertTrue(np.array_equal(a.take([0, 2]).values, ["a", "c"]))
+ self.assertTrue(np.array_equal(a.take([2, 0]).values, ["c", "a"]))
+ self.assertRaises(ValueError, a.take, [0, 2, 0]) # duplicate values in Index
+
+ def test_compress(self):
+ a = Index("A", ["a", "b", "c", "d"])
+ selector = [True, False, True, False]
+ b = a.compress(selector)
+ c = a[np.array(selector)]
+ self.assertTrue(np.array_equal(b.values, c.values))
+ self.assertEqual(a.name, b.name) # keep name
+ self.assertTrue(np.array_equal(b.values, a.values.compress(selector)))
+
+ def test_writeable(self):
+ # once index has been created, its values cannot be changed in order not to break lookup function
+ a = Index("A", [10, 20, 30])
+ self.assertRaises(ValueError, a.values.__setitem__, 0, 40)
+ self.assertRaises(ValueError, a.values.sort)
+
+ def test_indexof(self):
+ a = Index("A", [10, 20, 30])
+ b = Index("Dim", ["ab", "bc", "cd", "de"])
+
+ # a single value
+ self.assertEqual(a.indexof(10), 0)
+ self.assertEqual(b.indexof("cd"), 2)
+ self.assertEqual(b.indexof(["cd"]), 2)
+
+ # multiple values
+ self.assertTrue(np.array_equal(a.indexof([10, 30]), [0, 2]))
+ self.assertTrue(np.array_equal(b.indexof(["de", "cd"]), [3, 2]))
+
+ # non-existent value raises KeyError (similar to dictionary lookup)
+ self.assertRaises(KeyError, a.indexof, 0)
+ self.assertRaises(KeyError, b.indexof, "ef")
+ self.assertRaises(KeyError, b.indexof, None)
+ self.assertRaises(KeyError, a.indexof, [0, 1])
+ self.assertRaises(KeyError, b.indexof, ["de", "ef"])
+
+ def test_operator_in(self):
+ a = Index("A", [10, 20, 30])
+ b = Index("B", ["ab", "bc", "cd", "de"])
+
+ self.assertTrue(20 in a)
+ self.assertFalse(40 in a)
+ self.assertTrue("bc" in b)
+ self.assertFalse("ef" in b)
+
+ # unlike Index.contains() operator 'in' cannot work with multiple values
+ #self.assertRaises(TypeError, a, __contains__, [0, 10])
+ #self.assertRaises(TypeError, a, __contains__, (0, 10))
+
+ def test_contains(self):
+ a = Index("A", [10, 20, 30])
+ b = Index("B", ["ab", "bc", "cd", "de"])
+
+ # a single value (in this case, operator 'in' is preferred)
+ self.assertTrue(a.contains(20))
+ self.assertFalse(a.contains(40))
+ self.assertTrue(b.contains("bc"))
+ self.assertFalse(b.contains("ef"))
+
+ # multiple values returns one-dimensional numpy array of logical values
+ self.assertTrue(np.array_equal(a.contains([0, 10, 20, 40]), [False, True, True, False]))
+ self.assertTrue(np.array_equal(b.contains(["ab"]), [True]))
+ self.assertTrue(np.array_equal(b.contains(["ab", "ef", "bc"]), [True, False, True]))
+ self.assertTrue(np.array_equal(b.contains(("ab", "ef", "bc")), [True, False, True]))
diff --git a/pool/shard002/Python/0026230_config.py b/pool/shard002/Python/0026230_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..f13808d7e6de3762f6bad1625f474a165165ad0e
--- /dev/null
+++ b/pool/shard002/Python/0026230_config.py
@@ -0,0 +1,26 @@
+"""
+Created on September 18, 2015
+
+@author: oleg-toporkov
+"""
+import ConfigParser
+import os
+import selenium.webdriver as webdriver
+
+
+class Config(object):
+ """
+ Config class for storing values from config.ini and browser types.
+ """
+ browser_types = \
+ dict(chrome=webdriver.Chrome, firefox=webdriver.Firefox, ie=webdriver.Ie, phantomjs=webdriver.PhantomJS)
+ config = ConfigParser.ConfigParser()
+ config.read('config.ini')
+
+ BROWSER = config.get('SELENIUM', 'Browser').lower()
+ HIGHLIGHT = config.getboolean('SELENIUM', 'Highlight')
+ REUSE = config.getboolean('SELENIUM', 'Reuse')
+
+ APP_URL = config.get('APPLICATION', 'URL')
+
+ LOG_DIR = os.path.abspath('logs')
diff --git a/pool/shard002/Python/0026231_status.py b/pool/shard002/Python/0026231_status.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c2ff31a7687b53bd2061f11bd9a0e115ae26f14
--- /dev/null
+++ b/pool/shard002/Python/0026231_status.py
@@ -0,0 +1,240 @@
+"""status.py - Statusbar for main window."""
+
+import gtk
+
+from mcomix import i18n
+from mcomix import constants
+from mcomix.preferences import prefs
+
+class Statusbar(gtk.EventBox):
+
+ SPACING = 5
+
+ def __init__(self):
+ super(Statusbar, self).__init__()
+
+ self._loading = True
+
+ # Status text, page number, file number, resolution, path, filename
+ self.status = gtk.Statusbar()
+ self.add(self.status)
+
+ # Create popup menu for enabling/disabling status boxes.
+ self.ui_manager = gtk.UIManager()
+ self.tooltipstatus = TooltipStatusHelper(self.ui_manager, self.status)
+ ui_description = """
+
+
+
+
+
+
+
+
+
+ """
+ self.ui_manager.add_ui_from_string(ui_description)
+
+ actiongroup = gtk.ActionGroup('mcomix-statusbar')
+ actiongroup.add_toggle_actions([
+ ('pagenumber', None, _('Show page numbers'), None, None,
+ self.toggle_status_visibility),
+ ('filenumber', None, _('Show file numbers'), None, None,
+ self.toggle_status_visibility),
+ ('resolution', None, _('Show resolution'), None, None,
+ self.toggle_status_visibility),
+ ('rootpath', None, _('Show path'), None, None,
+ self.toggle_status_visibility),
+ ('filename', None, _('Show filename'), None, None,
+ self.toggle_status_visibility)])
+ self.ui_manager.insert_action_group(actiongroup, 0)
+
+ # Hook mouse release event
+ self.connect('button-release-event', self._button_released)
+ self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK)
+
+ # Default status information
+ self._page_info = ''
+ self._file_info = ''
+ self._resolution = ''
+ self._root = ''
+ self._filename = ''
+ self._update_sensitivity()
+ self.show_all()
+
+ self._loading = False
+
+ def set_message(self, message):
+ """Set a specific message (such as an error message) on the statusbar,
+ replacing whatever was there earlier.
+ """
+ self.status.pop(0)
+ self.status.push(0, " " * Statusbar.SPACING + message)
+
+ def set_page_number(self, page, total, this_screen):
+ """Update the page number."""
+ page_info = ""
+ for i in range(this_screen):
+ page_info += '%d' % (page + i)
+ if i < this_screen - 1:
+ page_info +=','
+ page_info += ' / %d' % total
+ self._page_info = page_info
+
+ def get_page_number(self):
+ """Returns the bar's page information."""
+ return self._page_info
+
+ def set_file_number(self, fileno, total):
+ """Updates the file number (i.e. number of current file/total
+ files loaded)."""
+ if total > 0:
+ self._file_info = '(%d / %d)' % (fileno, total)
+ else:
+ self._file_info = ''
+
+ def get_file_number(self):
+ """ Returns the bar's file information."""
+ return self._file_info
+
+ def set_resolution(self, dimensions): # 2D only
+ """Update the resolution data.
+
+ Takes an iterable of tuples, (x, y, scale), describing the original
+ resolution of an image as well as the currently displayed scale.
+ """
+ resolution = ""
+ for i in range(len(dimensions)):
+ d = dimensions[i]
+ resolution += '%dx%d (%.1f%%)' % (d[0], d[1], d[2] * 100.0)
+ if i < len(dimensions) - 1:
+ resolution += ', '
+ self._resolution = resolution
+
+ def set_root(self, root):
+ """Set the name of the root (directory or archive)."""
+ self._root = i18n.to_unicode(root)
+
+ def set_filename(self, filename):
+ """Update the filename."""
+ self._filename = i18n.to_unicode(filename)
+
+ def update(self):
+ """Set the statusbar to display the current state."""
+
+ space = " " * Statusbar.SPACING
+ text = (space + "|" + space).join(self._get_status_text())
+ self.status.pop(0)
+ self.status.push(0, space + text)
+
+ def push(self, context_id, message):
+ """ Compatibility with gtk.Statusbar. """
+ assert context_id >= 0
+ self.status.push(context_id + 1, message)
+
+ def pop(self, context_id):
+ """ Compatibility with gtk.Statusbar. """
+ assert context_id >= 0
+ self.status.pop(context_id + 1)
+
+ def _get_status_text(self):
+ """ Returns an array of text fields that should be displayed. """
+ fields = []
+
+ if prefs['statusbar fields'] & constants.STATUS_PAGE:
+ fields.append(self._page_info)
+ if prefs['statusbar fields'] & constants.STATUS_FILENUMBER:
+ fields.append(self._file_info)
+ if prefs['statusbar fields'] & constants.STATUS_RESOLUTION:
+ fields.append(self._resolution)
+ if prefs['statusbar fields'] & constants.STATUS_PATH:
+ fields.append(self._root)
+ if prefs['statusbar fields'] & constants.STATUS_FILENAME:
+ fields.append(self._filename)
+
+ return fields
+
+ def toggle_status_visibility(self, action, *args):
+ """ Called when status entries visibility is to be changed. """
+
+ # Ignore events as long as control is still loading.
+ if self._loading:
+ return
+
+ actionname = action.get_name()
+ if actionname == 'pagenumber':
+ bit = constants.STATUS_PAGE
+ elif actionname == 'resolution':
+ bit = constants.STATUS_RESOLUTION
+ elif actionname == 'rootpath':
+ bit = constants.STATUS_PATH
+ elif actionname == 'filename':
+ bit = constants.STATUS_FILENAME
+ elif actionname == 'filenumber':
+ bit = constants.STATUS_FILENUMBER
+
+ if action.get_active():
+ prefs['statusbar fields'] |= bit
+ else:
+ prefs['statusbar fields'] &= ~bit
+
+ self.update()
+ self._update_sensitivity()
+
+ def _button_released(self, widget, event, *args):
+ """ Triggered when a mouse button is released to open the context
+ menu. """
+ if event.button == 3:
+ self.ui_manager.get_widget('/Statusbar').popup(None, None, None,
+ event.button, event.time)
+
+ def _update_sensitivity(self):
+ """ Updates the action menu's sensitivity based on user preferences. """
+
+ page_visible = prefs['statusbar fields'] & constants.STATUS_PAGE
+ fileno_visible = prefs['statusbar fields'] & constants.STATUS_FILENUMBER
+ resolution_visible = prefs['statusbar fields'] & constants.STATUS_RESOLUTION
+ path_visible = prefs['statusbar fields'] & constants.STATUS_PATH
+ filename_visible = prefs['statusbar fields'] & constants.STATUS_FILENAME
+
+ for name, visible in (('pagenumber', page_visible),
+ ('filenumber', fileno_visible),
+ ('resolution', resolution_visible),
+ ('rootpath', path_visible),
+ ('filename', filename_visible)):
+ action = self.ui_manager.get_action('/Statusbar/' + name)
+ action.set_active(visible)
+
+
+class TooltipStatusHelper(object):
+ """ Attaches to a L{gtk.UIManager} to provide statusbar tooltips when
+ selecting menu items. """
+
+ def __init__(self, uimanager, statusbar):
+ self._statusbar = statusbar
+
+ uimanager.connect('connect-proxy', self._on_connect_proxy)
+ uimanager.connect('disconnect-proxy', self._on_disconnect_proxy)
+
+ def _on_connect_proxy(self, uimgr, action, widget):
+ """ Connects the widget's selection handlers to the status bar update.
+ """
+ tooltip = action.get_property('tooltip')
+ if isinstance(widget, gtk.MenuItem) and tooltip:
+ cid = widget.connect('select', self._on_item_select, tooltip)
+ cid2 = widget.connect('deselect', self._on_item_deselect)
+ setattr(widget, 'app::connect-ids', (cid, cid2))
+
+ def _on_disconnect_proxy(self, uimgr, action, widget):
+ """ Disconnects the widget's selection handlers. """
+ cids = getattr(widget, 'app::connect-ids', ())
+ for cid in cids:
+ widget.disconnect(cid)
+
+ def _on_item_select(self, menuitem, tooltip):
+ self._statusbar.push(0, " " * Statusbar.SPACING + tooltip)
+
+ def _on_item_deselect(self, menuitem):
+ self._statusbar.pop(0)
+
+# vim: expandtab:sw=4:ts=4
diff --git a/pool/shard002/Python/0026233_sensor.py b/pool/shard002/Python/0026233_sensor.py
new file mode 100644
index 0000000000000000000000000000000000000000..2edaa3cf933ebd7e32277380d359fa3c201868c0
--- /dev/null
+++ b/pool/shard002/Python/0026233_sensor.py
@@ -0,0 +1,144 @@
+"""Sensor for Spot Crime."""
+
+from collections import defaultdict
+from datetime import timedelta
+import logging
+
+import spotcrime
+import voluptuous as vol
+
+from homeassistant.components.sensor import PLATFORM_SCHEMA
+from homeassistant.const import (
+ ATTR_ATTRIBUTION,
+ ATTR_LATITUDE,
+ ATTR_LONGITUDE,
+ CONF_API_KEY,
+ CONF_EXCLUDE,
+ CONF_INCLUDE,
+ CONF_LATITUDE,
+ CONF_LONGITUDE,
+ CONF_NAME,
+ CONF_RADIUS,
+)
+import homeassistant.helpers.config_validation as cv
+from homeassistant.helpers.entity import Entity
+from homeassistant.util import slugify
+
+_LOGGER = logging.getLogger(__name__)
+
+CONF_DAYS = "days"
+DEFAULT_DAYS = 1
+NAME = "spotcrime"
+
+EVENT_INCIDENT = f"{NAME}_incident"
+
+SCAN_INTERVAL = timedelta(minutes=30)
+
+PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
+ {
+ vol.Required(CONF_NAME): cv.string,
+ vol.Required(CONF_RADIUS): vol.Coerce(float),
+ vol.Required(CONF_API_KEY): cv.string,
+ vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude,
+ vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude,
+ vol.Optional(CONF_DAYS, default=DEFAULT_DAYS): cv.positive_int,
+ vol.Optional(CONF_INCLUDE): vol.All(cv.ensure_list, [cv.string]),
+ vol.Optional(CONF_EXCLUDE): vol.All(cv.ensure_list, [cv.string]),
+ }
+)
+
+
+def setup_platform(hass, config, add_entities, discovery_info=None):
+ """Set up the Crime Reports platform."""
+ latitude = config.get(CONF_LATITUDE, hass.config.latitude)
+ longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
+ name = config[CONF_NAME]
+ radius = config[CONF_RADIUS]
+ api_key = config[CONF_API_KEY]
+ days = config.get(CONF_DAYS)
+ include = config.get(CONF_INCLUDE)
+ exclude = config.get(CONF_EXCLUDE)
+
+ add_entities(
+ [
+ SpotCrimeSensor(
+ name, latitude, longitude, radius, include, exclude, api_key, days
+ )
+ ],
+ True,
+ )
+
+
+class SpotCrimeSensor(Entity):
+ """Representation of a Spot Crime Sensor."""
+
+ def __init__(
+ self, name, latitude, longitude, radius, include, exclude, api_key, days
+ ):
+ """Initialize the Spot Crime sensor."""
+
+ self._name = name
+ self._include = include
+ self._exclude = exclude
+ self.api_key = api_key
+ self.days = days
+ self._spotcrime = spotcrime.SpotCrime(
+ (latitude, longitude),
+ radius,
+ self._include,
+ self._exclude,
+ self.api_key,
+ self.days,
+ )
+ self._attributes = None
+ self._state = None
+ self._previous_incidents = set()
+ self._attributes = {ATTR_ATTRIBUTION: spotcrime.ATTRIBUTION}
+
+ @property
+ def name(self):
+ """Return the name of the sensor."""
+ return self._name
+
+ @property
+ def state(self):
+ """Return the state of the sensor."""
+ return self._state
+
+ @property
+ def device_state_attributes(self):
+ """Return the state attributes."""
+ return self._attributes
+
+ def _incident_event(self, incident):
+ data = {
+ "type": incident.get("type"),
+ "timestamp": incident.get("timestamp"),
+ "address": incident.get("location"),
+ }
+ if incident.get("coordinates"):
+ data.update(
+ {
+ ATTR_LATITUDE: incident.get("lat"),
+ ATTR_LONGITUDE: incident.get("lon"),
+ }
+ )
+ self.hass.bus.fire(EVENT_INCIDENT, data)
+
+ def update(self):
+ """Update device state."""
+ incident_counts = defaultdict(int)
+ incidents = self._spotcrime.get_incidents()
+ if len(incidents) < len(self._previous_incidents):
+ self._previous_incidents = set()
+ for incident in incidents:
+ incident_type = slugify(incident.get("type"))
+ incident_counts[incident_type] += 1
+ if (
+ self._previous_incidents
+ and incident.get("id") not in self._previous_incidents
+ ):
+ self._incident_event(incident)
+ self._previous_incidents.add(incident.get("id"))
+ self._attributes.update(incident_counts)
+ self._state = len(incidents)
diff --git a/pool/shard002/Python/0026235_forms.py b/pool/shard002/Python/0026235_forms.py
new file mode 100644
index 0000000000000000000000000000000000000000..d31d360cc807e3a41953d8fa5c5e1a9bed86bc40
--- /dev/null
+++ b/pool/shard002/Python/0026235_forms.py
@@ -0,0 +1,17 @@
+from django import forms
+
+from .models import Quote
+
+
+class QuoteForm(forms.ModelForm):
+ author_field = forms.CharField(label='Author', required=False)
+
+ class Meta:
+ model = Quote
+ exclude = ('user', 'metadata', 'author', 'star_count')
+
+ def __init__(self, *args, **kwargs):
+ super(QuoteForm, self).__init__(*args, **kwargs)
+ for label, field in self.fields.items():
+ field.widget.attrs['placeholder'] = field.help_text
+ field.help_text = None
diff --git a/pool/shard002/Python/0026237_data.py b/pool/shard002/Python/0026237_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..47211ad5addce57b520ab0804ac18a36f4612291
--- /dev/null
+++ b/pool/shard002/Python/0026237_data.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python
+
+"""
+Author: Dan Salo
+Initial Commit: 12/5/2016
+Purpose: Class for MNIST
+Adapted from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py
+"""
+
+from .base import Data
+from shutil import copyfile
+import numpy as np
+import os
+import gzip
+import urllib.request
+
+
+class Mnist(Data):
+ def __init__(self, flags):
+ super().__init__(flags)
+
+ def load_data(self, test_percent=0.15):
+ one_hot = True
+ validation_size = 5000
+
+ SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
+ TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
+ TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
+ TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
+ TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
+
+ local_file = self.maybe_download(TRAIN_IMAGES, self.flags['data_directory'], SOURCE_URL + TRAIN_IMAGES)
+ with open(local_file, 'rb') as f:
+ train_images = self.extract_images(f)
+
+ local_file = self.maybe_download(TRAIN_LABELS, self.flags['data_directory'], SOURCE_URL + TRAIN_LABELS)
+ with open(local_file, 'rb') as f:
+ train_labels = self.extract_labels(f, one_hot=one_hot)
+
+ local_file = self.maybe_download(TEST_IMAGES, self.flags['data_directory'], SOURCE_URL + TEST_IMAGES)
+ with open(local_file, 'rb') as f:
+ test_images = self.extract_images(f)
+
+ local_file = self.maybe_download(TEST_LABELS, self.flags['data_directory'], SOURCE_URL + TEST_LABELS)
+ with open(local_file, 'rb') as f:
+ test_labels = self.extract_labels(f, one_hot=one_hot)
+
+ if not 0 <= validation_size <= len(train_labels):
+ raise ValueError(
+ 'Validation size should be between 0 and {}. Received: {}.'.format(len(train_labels), validation_size))
+ return train_images, train_labels, test_images, test_labels
+
+ def maybe_download(self, filename, work_directory, source_url):
+ """Download the data from source url, unless it's already here.
+ Args:
+ filename: string, name of the file in the directory.
+ work_directory: string, path to working directory.
+ source_url: url to download from if file doesn't exist.
+ Returns:
+ Path to resulting file.
+ """
+ if not os.path.exists(work_directory):
+ os.makedirs(work_directory)
+ filepath = os.path.join(work_directory, filename)
+ if not os.path.exists(filepath):
+ temp_file_name, _ = urllib.request.urlretrieve(source_url)
+ copyfile(temp_file_name, filepath)
+ print('Successfully downloaded', filename)
+ return filepath
+
+ def extract_images(self, f):
+ """Extract the images into a 4D uint8 numpy array [index, y, x, depth].
+ Args:
+ f: A file object that can be passed into a gzip reader.
+ Returns:
+ data: A 4D unit8 numpy array [index, y, x, depth].
+ Raises:
+ ValueError: If the bytestream does not start with 2051.
+ """
+ print('Extracting', f.name)
+ with gzip.GzipFile(fileobj=f) as bytestream:
+ magic = self._read32(bytestream)
+ if magic != 2051:
+ raise ValueError('Invalid magic number %d in MNIST image file: %s' %
+ (magic, f.name))
+ num_images = self._read32(bytestream)
+ rows = self._read32(bytestream)
+ cols = self._read32(bytestream)
+ buf = bytestream.read(rows * cols * num_images)
+ data = np.frombuffer(buf, dtype=np.uint8)
+ data = data.reshape(num_images, rows, cols, 1)
+ return data
+
+ def extract_labels(self, f, one_hot=False, num_classes=10):
+ """Extract the labels into a 1D uint8 numpy array [index].
+ Args:
+ f: A file object that can be passed into a gzip reader.
+ one_hot: Does one hot encoding for the result.
+ num_classes: Number of classes for the one hot encoding.
+ Returns:
+ labels: a 1D unit8 numpy array.
+ Raises:
+ ValueError: If the bystream doesn't start with 2049.
+ """
+ print('Extracting', f.name)
+ with gzip.GzipFile(fileobj=f) as bytestream:
+ magic = self._read32(bytestream)
+ if magic != 2049:
+ raise ValueError('Invalid magic number %d in MNIST label file: %s' %
+ (magic, f.name))
+ num_items = self._read32(bytestream)
+ buf = bytestream.read(num_items)
+ labels = np.frombuffer(buf, dtype=np.uint8)
+ if one_hot:
+ return self.dense_to_one_hot(labels, num_classes)
+ return labels
+
+ @staticmethod
+ def dense_to_one_hot(labels_dense, num_classes):
+ """Convert class labels from scalars to one-hot vectors."""
+ num_labels = labels_dense.shape[0]
+ index_offset = np.arange(num_labels) * num_classes
+ labels_one_hot = np.zeros((num_labels, num_classes))
+ labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
+ return labels_one_hot
+
+ @staticmethod
+ def _read32(bytestream):
+ dt = np.dtype(np.uint32).newbyteorder('>')
+ return np.frombuffer(bytestream.read(4), dtype=dt)[0]
diff --git a/pool/shard002/Python/0026242_status.py b/pool/shard002/Python/0026242_status.py
new file mode 100644
index 0000000000000000000000000000000000000000..da8ebacf26a8e901bed6c494de0c9a3921d1b0ba
--- /dev/null
+++ b/pool/shard002/Python/0026242_status.py
@@ -0,0 +1,102 @@
+# Copyright 2022 UW-IT, University of Washington
+# SPDX-License-Identifier: Apache-2.0
+
+from django.conf import settings
+from django.shortcuts import render
+from django.views.decorators.cache import never_cache
+from django.utils import timezone
+from uw_saml.decorators import group_required
+from uw_sws.models import Term
+from course_grader.models import SubmittedGradeRoster, GradeImport
+from course_grader.dao.term import (
+ term_from_param, current_term, current_datetime)
+from datetime import datetime, timedelta
+from logging import getLogger
+import json
+
+logger = getLogger(__name__)
+
+
+@group_required(settings.GRADEPAGE_SUPPORT_GROUP)
+@never_cache
+def status(request):
+ try:
+ curr_term = current_term()
+ except Exception as ex:
+ logger.error("GET current term failed: {}".format(ex))
+ raise
+
+ term_id = request.GET.get("term", "").strip()
+ try:
+ selected_term = term_from_param(term_id)
+ except Exception as ex:
+ selected_term = curr_term
+
+ graderosters = SubmittedGradeRoster.objects.get_status_by_term(
+ selected_term)
+
+ grade_imports = GradeImport.objects.get_import_sources_by_term(
+ selected_term)
+
+ if selected_term.quarter == Term.SUMMER:
+ grading_period_open = selected_term.aterm_grading_period_open
+ else:
+ grading_period_open = selected_term.grading_period_open
+
+ start_date = timezone.make_aware(grading_period_open,
+ timezone.get_default_timezone())
+ end_date = timezone.make_aware(selected_term.grade_submission_deadline,
+ timezone.get_default_timezone())
+ epoch = timezone.make_aware(datetime(1970, 1, 1),
+ timezone.get_default_timezone())
+
+ chart_data = {
+ "submissions": {
+ "plot_lines": [],
+ "grading_period_open": get_total_milliseconds(start_date - epoch),
+ "data": []
+ },
+ "grade_imports": {
+ "catalyst": [],
+ "canvas": [],
+ "csv": [],
+ }
+ }
+
+ while start_date < end_date:
+ if start_date.strftime("%a") == "Mon":
+ chart_data["submissions"]["plot_lines"].append({
+ "value": get_total_milliseconds(start_date - epoch),
+ "color": "#707070",
+ "width": 1,
+ "dashStyle": "ShortDot"
+ })
+ start_date = start_date + timedelta(days=1)
+
+ for index, graderoster in enumerate(graderosters):
+ chart_data["submissions"]["data"].append([
+ get_total_milliseconds(graderoster["submitted_date"] - epoch),
+ index + 1
+ ])
+
+ for grade_import in grade_imports:
+ chart_data["grade_imports"][grade_import["source"]].append([
+ get_total_milliseconds(grade_import["imported_date"] - epoch),
+ len(chart_data["grade_imports"][grade_import["source"]]) + 1
+ ])
+
+ params = {
+ "graderosters": graderosters,
+ "selected_year": selected_term.year,
+ "selected_quarter": selected_term.get_quarter_display(),
+ "grading_period_open": grading_period_open,
+ "grade_submission_deadline": selected_term.grade_submission_deadline,
+ "current_datetime": current_datetime(),
+ "chart_data": json.dumps(chart_data),
+ "term_id": term_id
+ }
+ return render(request, "support/status.html", params)
+
+
+def get_total_milliseconds(td):
+ return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e3
diff --git a/pool/shard002/Python/0026246_test_deposit_validators.py b/pool/shard002/Python/0026246_test_deposit_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba120606522b2f46d707b3f747dfa66975098573
--- /dev/null
+++ b/pool/shard002/Python/0026246_test_deposit_validators.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of Invenio.
+# Copyright (C) 2015 CERN.
+#
+# Invenio is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of the
+# License, or (at your option) any later version.
+#
+# Invenio is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Invenio; if not, write to the Free Software Foundation, Inc.,
+# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+
+"""Unit tests for deposit module validators."""
+
+from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite
+
+from wtforms.validators import ValidationError
+
+
+class Field(object):
+
+ def __init__(self, old_doi, new_doi):
+ self.object_data = old_doi
+ self.data = new_doi
+
+
+class Form(object):
+ pass
+
+
+LOCAL_DOI_PREFIX = "10.5072"
+REMOTE_DOI_PREFIX = "10.7777"
+
+
+class MintedDOIValidatorTest(InvenioTestCase):
+ """Test MitedDOIValidator."""
+
+ def test_doi_new(self):
+ from invenio.modules.deposit.validation_utils import MintedDOIValidator
+
+ validator = MintedDOIValidator()
+ field = Field("", LOCAL_DOI_PREFIX + "/test.77777")
+ field2 = Field("", REMOTE_DOI_PREFIX + "/test.77777")
+ form = Form()
+
+ self.assertIsNone(validator(form, field))
+ self.assertIsNone(validator(form, field2))
+
+ def test_matching_doi(self):
+ from invenio.modules.deposit.validation_utils import MintedDOIValidator
+
+ validator = MintedDOIValidator()
+ field = Field(
+ LOCAL_DOI_PREFIX + "/test.77777",
+ LOCAL_DOI_PREFIX + "/test.77777")
+ field2 = Field(
+ REMOTE_DOI_PREFIX + "/test.77777",
+ REMOTE_DOI_PREFIX + "/test.77777")
+ form = Form()
+
+ self.assertIsNone(validator(form, field))
+ self.assertIsNone(validator(form, field2))
+
+ def test__different_doi_(self):
+ from invenio.modules.deposit.validation_utils import MintedDOIValidator
+
+ validator = MintedDOIValidator()
+ field = Field(
+ LOCAL_DOI_PREFIX + "/test.12345",
+ LOCAL_DOI_PREFIX + "/test.77777")
+ field2 = Field(
+ REMOTE_DOI_PREFIX + "/test.12345",
+ REMOTE_DOI_PREFIX + "/test.77777")
+ form = Form()
+
+ with self.assertRaises(ValidationError):
+ validator(form, field)
+ with self.assertRaises(ValidationError):
+ validator(form, field2)
+
+
+TEST_SUITE = make_test_suite(MintedDOIValidatorTest)
+
+if __name__ == "__main__":
+ run_test_suite(TEST_SUITE)
diff --git a/pool/shard002/Python/0026247_test_eq.py b/pool/shard002/Python/0026247_test_eq.py
new file mode 100644
index 0000000000000000000000000000000000000000..9064dea7e0485d3132a4360b268ac2be6bf4b5b1
--- /dev/null
+++ b/pool/shard002/Python/0026247_test_eq.py
@@ -0,0 +1,29 @@
+from littlepython.ast import Var, Block, If, ControlBlock, Int
+from tests import t
+
+
+def test_ast_eq_dif_types():
+ assert Int(t("1")) != Var(t("1"))
+
+
+def test_ast_eq_same_type_diff_attr():
+ c1 = Int(t("1"))
+ c2 = Int(t("1"))
+ c2.left = "bla"
+ assert c1 != c2
+
+
+def test_ast_eq_same_type_same_attr_diff_value():
+ c1 = Int(t("1"))
+ c2 = Int(t("1"))
+ c1.left = "bla"
+ c2.left = "bla1"
+ assert c1 != c2
+
+
+def test_if_eq_diff_type():
+ assert If([], Block()) != Var(t("1"))
+
+
+def test_control_block_eq_diff_type():
+ assert ControlBlock([If([], Block())]) != Var(t("1"))
diff --git a/pool/shard002/Python/0026255_bipartition.py b/pool/shard002/Python/0026255_bipartition.py
new file mode 100644
index 0000000000000000000000000000000000000000..4277fa4b34a7d31480431a8e50f5a6c06a112fa6
--- /dev/null
+++ b/pool/shard002/Python/0026255_bipartition.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+from functools import partial, total_ordering
+from typing import Callable, Optional, Sequence
+
+import attr
+import funcy as fn
+from lazytree import LazyTree
+
+from monotone_bipartition import hausdorff as mbph
+from monotone_bipartition import rectangles # unit_rec
+from monotone_bipartition import refine as mbpr # bounding_box
+from monotone_bipartition import search as mdts # binsearch
+from monotone_bipartition.rectangles import Rec
+
+
+Point = Sequence[float]
+Threshold = Callable[[Point], bool]
+FindIntersectScheme = Callable[[Rec, Threshold], Point]
+BoundaryPointOracle = Callable[[Rec], Point]
+
+
+@attr.s
+@total_ordering
+class BiPartition:
+ tree: LazyTree = attr.ib()
+
+ @property
+ def dim(self):
+ return len(self.tree.view())
+
+ def approx(self, tol=1e-4):
+ recs = self.tree \
+ .prune(isleaf=lambda r: r.shortest_edge <= tol) \
+ .leaves()
+
+ return list(recs)
+
+ def dist(self, other, tol=1e-4) -> rectangles.Interval:
+ approxes = mbph.gen_dists(self, other)
+ within_tol = (i for i in approxes if i.radius < tol)
+ return fn.first(within_tol)
+
+ def label(self, point) -> bool:
+ # TODO: Should support either finite precision or max depth.
+ domain = rectangles.unit_rec(self.dim)
+
+ def above(rec):
+ return point in domain.forward_cone(rec.bot) and \
+ point not in domain.backward_cone(rec.top)
+
+ def below(rec):
+ return point not in domain.forward_cone(rec.bot) and \
+ point in domain.backward_cone(rec.top)
+
+ def not_inside(rec):
+ return point not in domain.forward_cone(rec.bot) or \
+ point not in domain.backward_cone(rec.top)
+
+ recs = self.tree.prune(isleaf=not_inside).bfs()
+ for rec in recs:
+ if above(rec):
+ return True
+
+ if not not_inside(rec):
+ if all(x == 0 for x in rec.diag): # point rec.
+ return True
+ elif below(rec):
+ return all(x == 0 for x in rec.bot)
+
+ raise RuntimeError("Point outside domain?!?!?!")
+
+ def __le__(self, other):
+ raise NotImplementedError
+
+ def project(self, point_or_ordering, *,
+ lexicographic=False, tol=1e-4, percent=False):
+ """
+ If lexicographic is False, then returns an approximation
+ to the *unique* point that intersect the threshold
+ boundary AND the line intersecting the origin and the
+ user defined point.
+
+ If lexicographic is True, then returns an approximation to the
+ minimum point on the threshold boundary that is minimum in the
+ ordering provided. The ordering is given as a list of pairs:
+ `(index, minimize)`. The index is minimized if `minimize` is
+ true, and maximized otherwise. For example, `[(1, False), (0,
+ True)]` encodes maximizing along axis 1 of the unit box and
+ then minimizing along axis 0.
+ """
+ if lexicographic:
+ assert not percent
+ return mdts.lexicographic_opt(self.label, point_or_ordering, tol)
+
+ point = point_or_ordering
+ return mdts.line_intersect(self.label, point, tol, percent=percent)
+
+ @staticmethod
+ def from_bound_point_oracle(
+ oracle: BoundaryPointOracle, domain: Rec, *, memoize: bool = True
+ ) -> BiPartition:
+ refine = partial(mbpr.refine, diagsearch=oracle)
+ if memoize:
+ refine = fn.memoize()(refine)
+
+ return BiPartition(LazyTree(root=domain, child_map=refine))
+
+
+def from_threshold(func,
+ dim: int,
+ *,
+ memoize_nodes: bool = True,
+ find_intersect: FindIntersectScheme = mdts.binsearch,
+ bounding_box: Optional[Rec] = None) -> BiPartition:
+
+ if bounding_box is None:
+ bounding_box = mbpr.bounding_box(
+ oracle=func,
+ domain=rectangles.unit_rec(dim),
+ find_intersect=find_intersect
+ )
+
+ diagsearch = partial(find_intersect, oracle=func)
+
+ return BiPartition.from_bound_point_oracle(
+ oracle=diagsearch,
+ domain=bounding_box,
+ memoize=memoize_nodes,
+ )
diff --git a/pool/shard002/Python/0026257_mockengine.py b/pool/shard002/Python/0026257_mockengine.py
new file mode 100644
index 0000000000000000000000000000000000000000..24fe5facaa8c3c61bc96242b282cadd28da213d6
--- /dev/null
+++ b/pool/shard002/Python/0026257_mockengine.py
@@ -0,0 +1,100 @@
+"""
+Simple in-memory Engine mock.
+
+"""
+from microcosm_dynamodb.errors import ModelNotFoundError
+
+
+class MockQuery:
+ def __init__(self, engine, model_class):
+ self._engine = engine
+ self._model_class = model_class
+ self._criterion = None
+ self._limit = None
+
+ @property
+ def instances(self):
+ return self._engine.models[self._model_class]
+
+ @instances.setter
+ def instances(self, value):
+ self._engine.models[self._model_class] = value
+
+ def filter(self, *criterion):
+ self._criterion = criterion
+ return self
+
+ def limit(self, limit):
+ self._limit = limit
+ return self
+
+ def check_criterion(self, instance):
+ # XXX criterion checking is not implemented
+ return True
+
+ def all(self):
+ return list(self.gen())
+
+ def delete(self):
+ keep = []
+ count = 0
+ for instance in self.instances:
+ if self.check_criterion(instance):
+ count += 1
+ else:
+ keep += instance
+ self.instances = keep
+ return count
+
+ def gen(self):
+ count = 0
+ for id, instance in self.instances.items():
+ if not self.check_criterion(instance):
+ continue
+ yield instance
+ count += 1
+ if count == self._limit:
+ break
+
+ def one(self):
+ for instance in self.gen():
+ return instance
+ raise ModelNotFoundError
+
+
+class MockEngine:
+ def __init__(self, namespace):
+ self.namespace = namespace
+ self.region = None
+ self.models = {}
+
+ def connect_to_region(self, region):
+ self.region = region
+
+ def register(self, model):
+ self.models.setdefault(model, {})
+
+ def delete_schema(self):
+ pass
+
+ def create_schema(self):
+ pass
+
+ def save(self, instance):
+ self.models[instance.__class__][instance.id] = instance
+
+ def scan(self, model_class):
+ return self.query(model_class)
+
+ def sync(self, instance):
+ if instance.id in self.models[instance.__class__]:
+ self.save(instance)
+ else:
+ raise ModelNotFoundError
+
+ def query(self, model_class):
+ return MockQuery(self, model_class)
+
+ def get(self, model_class, **identifiers):
+ # XXX identifier lookup is not fully featured
+ return self.models[model_class][identifiers["id"]]
diff --git a/pool/shard002/Python/0026259_content.py b/pool/shard002/Python/0026259_content.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4cea57c09befa4e6e753ecb78b0723fc45879be
--- /dev/null
+++ b/pool/shard002/Python/0026259_content.py
@@ -0,0 +1,278 @@
+import json
+
+from sqlalchemy.orm import sessionmaker, scoped_session
+
+from atod.db import engine
+from atod import files
+# db models
+from atod.db_models.hero import HeroModel
+from atod.db_models.ability import AbilityModel
+from atod.db_models.ability_specs import AbilitySpecsModel
+from atod.db_models.ability_texts import AbilityTextsModel
+# utils
+from atod.utils import txt2json, json2rows, abilities
+from . import schemas
+
+session = scoped_session(sessionmaker(bind=engine))
+
+
+def add_heroes(npc_heroes: str, patch: str):
+ ''' Unite everything that is needed to add heroes to the db table.
+
+ That method does: parses `raw_file` to json, extracts information from
+ json according to heroes table schema, adds heroes to the table.
+
+ Args:
+ npc_heroes: full path to the npc_heroes.txt file.
+ patch: version of the game from which info was taken.
+ '''
+ heroes_file = npc_heroes
+
+ heroes_dict = txt2json.to_json(heroes_file)
+
+ rows = json2rows.heroes_to_rows(heroes_dict,
+ schemas.get_heroes_columns())
+
+ for row in rows:
+ row['patch'] = patch
+ hero = HeroModel(row)
+ session.add(hero)
+
+ session.commit()
+
+
+def add_abilities_specs(npc_abilties: str, patch: str):
+ ''' Fills table with the data from cleaned npc_abilities file.
+
+ Args:
+ npc_abilties: full path to the npc_abilities.txt file.
+ patch: version of the game from which info was taken.
+
+ '''
+
+ parsed = txt2json.to_json(npc_abilties)
+ clean = abilities.get_cleaned_abilities(parsed)
+
+ schema = schemas.get_abilities_specs_columns()
+
+ with open(files.CONVERTER_FILE, 'r') as fp:
+ converter = json.load(fp)
+
+ for skill, description in clean.items():
+ try:
+ hero, skill_name = json2rows.parse_skill_name(skill)
+ # if skill name cannot be parsed
+ except ValueError:
+ continue
+
+ for row in json2rows.ability_to_row(description, schema):
+ row['HeroID'] = converter[hero]
+ row['name'] = skill_name
+ row['pk'] = str(row['ID']) + '.' + str(row['lvl'])
+ row['patch'] = patch
+
+ skill = AbilitySpecsModel(row)
+ session.add(skill)
+
+ session.commit()
+
+
+def add_abilities(labels: str, patch: str):
+ ''' Fills abilities table.
+
+ Args:
+ labels: full path to the labeled_abilities.json file
+ patch: version of the data
+ '''
+
+ with open(labels, 'r') as fp:
+ skills = json.load(fp)
+
+ with open(files.CONVERTER_FILE, 'r') as fp:
+ converter = json.load(fp)
+
+ for skill, description in skills.items():
+ if 'special' in skill:
+ continue
+
+ # get skill and hero names
+ try:
+ hero, skill_name = json2rows.parse_skill_name(skill)
+ except ValueError:
+ continue
+
+ # for marked abilities
+ if 'labels' in description:
+ row = json2rows.binarize_labels(description['labels'],
+ schemas.LABELS)
+ # for unmarked abilities
+ else:
+ row = {k: 0 for k in schemas.LABELS}
+
+ row['HeroID'] = converter[hero]
+ row['name'] = skill_name
+ row['ID'] = description['ID']
+ row['patch'] = patch
+
+ skill = AbilityModel(row)
+ session.add(skill)
+
+ session.commit()
+
+
+def add_abilities_texts(dota_english: str, patch):
+ ''' Fills abilities_texts table.
+
+ Notes:
+ This function need AbilitiesTable to be created for current
+ version. I will fix it in future versions.
+
+ Args:
+ dota_english: full path to the dota_english.txt file.
+ patch: version of the game from which info was taken.
+ '''
+
+ for specification in get_abilities_texts(dota_english):
+ # if specification is empty
+ if not specification:
+ continue
+
+ specification['patch'] = patch
+ texts = AbilityTextsModel(specification)
+ session.add(texts)
+
+ session.commit()
+
+
+''' Functions below are doing utils of abilities texts and the reason
+ they are here is because they need filled database tables (heroes and
+ abilities).
+'''
+def group_abilities_texts(texts):
+ ''' Groups the information in dota_english by ability.
+
+ Args:
+ texts (dict): *parsed* dota_english.txt
+
+ Returns:
+ desc_by_ability (dict): {: }
+ '''
+
+ desc_by_ability = dict()
+ keys = sorted(texts)
+ ability = ' '
+
+ for key in keys:
+ if ability in key:
+ desc_by_ability[ability][key[len(ability) + 1:]] = texts[key]
+ else:
+ ability = key
+ desc_by_ability[ability] = dict()
+ desc_by_ability[ability]['name'] = texts[ability]
+
+ return desc_by_ability
+
+
+def get_abilities_texts(dota_english: str):
+ ''' Produces ready to use dictionaries to create AbilityTextsModel object.
+
+ Yields:
+ dict: containing all the needed keys or empty if texts can not be
+ sorted
+ '''
+
+ texts_file = dota_english
+ # parse texts file and take only texts from it
+ parsed_texts = txt2json.to_json(texts_file)['lang']['Tokens']
+ # group texts by ability
+ grouped_texts = group_abilities_texts(parsed_texts)
+
+ # for all keys in grouped_texts
+ prefix = 'DOTA_Tooltip_ability_'
+ for key in list(grouped_texts):
+ if not key.startswith(prefix):
+ del grouped_texts[key]
+ continue
+
+ # this is a tuple
+ parsed_name = json2rows.parse_skill_name(key[len(prefix):])
+
+ # there are 2 independent `if` statements to call parse_skill_name()
+ # one time and only if it is needed
+
+ # if the name cann't be parsed
+ if len(parsed_name) < 2:
+ del grouped_texts[key]
+ continue
+ # if the name can be split to the hero name and skill name -- change
+ # original uppercase name to in-game style: all lower case with under
+ # instead of space
+ else:
+ grouped_texts[key]['name'] = parsed_name[1]
+ sorted_ = sort_texts(grouped_texts[key])
+ id_ = get_id_from_in_game_name(parsed_name[0], parsed_name[1])
+ if sorted_ and id_ is not None:
+ sorted_['ID'] = id_
+ yield sorted_
+ else:
+ yield {}
+
+
+def sort_texts(unsorted):
+ ''' Creates a dictionary that fits AbilityTextsModel init method.
+
+ Args:
+ unsorted (dict): all fields in dota_english file for an ability.
+
+ Returns:
+ dict: where keys are columns in AbilityTextsModel
+ '''
+
+ # description is the most important text, so if ability doesn't contain
+ # one it wouldn't be added in db
+ if 'Description' not in unsorted:
+ return {}
+
+ sorted_ = dict()
+ sorted_['name'] = unsorted['name']
+ sorted_['description'] = unsorted['Description']
+ sorted_['lore'] = unsorted['Lore'] if 'Lore' in unsorted else ''
+
+ sorted_['notes'] = ''
+ sorted_['other'] = ''
+ for key in unsorted:
+ if 'Note' in key:
+ # all notes are just sentences, so there is no need in special
+ # delimiter
+ sorted_['notes'] += unsorted[key] + ' '
+ elif key.lower() not in sorted_:
+ sorted_['other'] += unsorted[key] + ' | '
+
+ return sorted_
+
+
+def get_id_from_in_game_name(hero_name, skill_name):
+ ''' Finds skill id.
+
+ This function is needed to prevent collision: when a few heroes have
+ skill with the same name.
+
+ Args:
+ hero_name (str): hero part of in-game ability name
+ skill_name (str): skill part of in-game ability name
+
+ Returns:
+ int or None: int if id is found, None otherwise
+ '''
+
+ query = session.query(HeroModel.HeroID)
+ hero_id = query.filter(HeroModel.in_game_name == hero_name).first()[0]
+
+ query = session.query(AbilityModel.ID)
+ ability_id_ = query.filter(AbilityModel.HeroID == hero_id,
+ AbilityModel.name == skill_name).first()
+
+ if ability_id_ is None:
+ return None
+ else:
+ return ability_id_[0]
diff --git a/pool/shard002/Python/0026261_create.py b/pool/shard002/Python/0026261_create.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e99543631fb2f9d2be4b76207f3b5bc32a5ac48
--- /dev/null
+++ b/pool/shard002/Python/0026261_create.py
@@ -0,0 +1,20 @@
+"""
+Create a simple, single-elimination demo tournament with 8 teams.
+
+"""
+from django.contrib.auth.models import User
+
+from .utils import generate_tournament
+
+
+teams = ['Team {}'.format(i) for i in range(1, 9)]
+
+team_defaults = {
+ 'creator': User.objects.get(pk=1),
+}
+
+
+generate_tournament(
+ teams=teams,
+ team_defaults=team_defaults
+)
diff --git a/pool/shard002/Python/0026266_choral.py b/pool/shard002/Python/0026266_choral.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7397e4646573d748b738ab873fa5794a5a5d293
--- /dev/null
+++ b/pool/shard002/Python/0026266_choral.py
@@ -0,0 +1,41 @@
+"""A simple choral texture."""
+
+import oort
+import random
+oort.print_off()
+oort.control_rate(15000)
+
+playing = True
+def play():
+ oort.wait(random.choice(range(10))*0.1)
+ while playing:
+ dur = 2 + random.randint(-10, 10)*.05
+ w.dur = dur*random.randint(2,4)
+ w.pitch = oort.mtof(random.choice(scale))
+ w.play()
+ oort.wait(dur)
+
+def control():
+ global playing
+ global scale
+ for _ in xrange(6):
+ offset = random.randint(-2,2)
+ scale = [x+offset for x in scale]
+ oort.wait(20)
+ playing = False
+
+w = oort.WAVETABLE()
+w.amp = 5000
+w.wavetable = oort.maketable('wave', 1000, 1, 0.1)
+
+adsr = oort.ADSR(2, 0.5, 0.5, 2)
+shimmer = oort.Shimmer(amt=0.03, count=10)
+w.apply_behaviors(shimmer, adsr)
+
+scale = [ p+octave*12
+ for p in 0,2,4,6,7,9,10
+ for octave in 4,5,6 ]
+oort.sprout(control)
+
+for _ in range(2):
+ oort.sprout(play)
\ No newline at end of file
diff --git a/pool/shard002/Python/0026267_test_objectevent.py b/pool/shard002/Python/0026267_test_objectevent.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5eca94b6bffbec7fb9cf7de8fee057a6fad1239
--- /dev/null
+++ b/pool/shard002/Python/0026267_test_objectevent.py
@@ -0,0 +1,86 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 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.
+#
+##############################################################################
+"""Object Event Tests
+
+$Id: test_objectevent.py 67630 2006-04-27 00:54:03Z jim $
+"""
+import unittest
+import zope.component.event
+from zope.testing import doctest
+
+from zope.app.container.contained import Contained, ObjectRemovedEvent
+from zope.app.container.interfaces import IContained, IObjectRemovedEvent
+from zope.app.container.sample import SampleContainer
+from zope.app.testing.placelesssetup import setUp, tearDown
+from zope.app.testing import ztapi
+
+class TestObjectEventNotifications(unittest.TestCase):
+
+ def setUp(self):
+ self.callbackTriggered = False
+ setUp()
+
+ def tearDown(self):
+ tearDown()
+
+ def testNotify(self):
+ events = []
+
+ def record(*args):
+ events.append(args)
+
+ ztapi.subscribe([IContained, IObjectRemovedEvent], None, record)
+
+ item = Contained()
+ event = ObjectRemovedEvent(item)
+ zope.component.event.objectEventNotify(event)
+ self.assertEqual([(item, event)], events)
+
+ def testNotifyNobody(self):
+ # Check that notify won't raise an exception in absence of
+ # of subscribers.
+ events = []
+ item = Contained()
+ evt = ObjectRemovedEvent(item)
+ zope.component.event.objectEventNotify(evt)
+ self.assertEqual([], events)
+
+ def testVeto(self):
+ zope.component.provideHandler(zope.component.event.objectEventNotify)
+ container = SampleContainer()
+ item = Contained()
+
+ # This will fire an event.
+ container['Fred'] = item
+
+ class Veto(Exception):
+ pass
+
+ def callback(item, event):
+ self.callbackTriggered = True
+ self.assertEqual(item, event.object)
+ raise Veto
+
+ ztapi.subscribe([IContained, IObjectRemovedEvent], None, callback)
+
+ # del container['Fred'] will fire an ObjectRemovedEvent event.
+ self.assertRaises(Veto, container.__delitem__, 'Fred')
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(TestObjectEventNotifications),
+ ))
+
+if __name__=='__main__':
+ unittest.main(defaultTest='test_suite')
diff --git a/pool/shard002/Python/0026272_cmd_run.py b/pool/shard002/Python/0026272_cmd_run.py
new file mode 100644
index 0000000000000000000000000000000000000000..3093faaa7b4b37989e401de8a5088600ee15e213
--- /dev/null
+++ b/pool/shard002/Python/0026272_cmd_run.py
@@ -0,0 +1,159 @@
+import sys
+import codecs
+
+from .exceptions import InvalidCommand
+from .task import Task
+from .control import TaskControl
+from .runner import Runner, MRunner
+from .reporter import REPORTERS
+from .cmd_base import DoitCmdBase
+
+
+# verbosity
+opt_verbosity = {'name':'verbosity',
+ 'short':'v',
+ 'long':'verbosity',
+ 'type':int,
+ 'default': None,
+ 'help':
+"""0 capture (do not print) stdout/stderr from task.
+1 capture stdout only.
+2 do not capture anything (print everything immediately).
+[default: 1]"""
+ }
+
+
+# select output file
+opt_outfile = {'name': 'outfile',
+ 'short':'o',
+ 'long': 'output-file',
+ 'type': str,
+ 'default': sys.stdout,
+ 'help':"write output into file [default: stdout]"
+ }
+
+
+# always execute task
+opt_always = {'name': 'always',
+ 'short': 'a',
+ 'long': 'always-execute',
+ 'type': bool,
+ 'default': False,
+ 'help': "always execute tasks even if up-to-date [default: "
+ "%(default)s]"
+ }
+
+# continue executing tasks even after a failure
+opt_continue = {'name': 'continue',
+ 'short': 'c',
+ 'long': 'continue',
+ 'inverse': 'no-continue',
+ 'type': bool,
+ 'default': False,
+ 'help': "continue executing tasks even after a failure "
+ "[default: %(default)s]"
+ }
+
+
+opt_num_process = {'name': 'num_process',
+ 'short': 'n',
+ 'long': 'process',
+ 'type': int,
+ 'default': 0,
+ 'help': "number of subprocesses"
+ "[default: %(default)s]"
+ }
+
+
+# reporter
+opt_reporter = {'name':'reporter',
+ 'short':'r',
+ 'long':'reporter',
+ 'type':str, #TODO type choice (limit the accepted strings)
+ 'default': 'default',
+ 'help':
+"""Choose output reporter. Available:
+'default': report output on console
+'executed-only': no output for skipped (up-to-date) and group tasks
+'json': output result in json format
+"""
+ }
+
+
+
+
+
+class Run(DoitCmdBase):
+ doc_purpose = "run tasks"
+ doc_usage = "[TASK/TARGET...]"
+ doc_description = None
+
+ cmd_options = (opt_always, opt_continue, opt_verbosity,
+ opt_reporter, opt_outfile, opt_num_process)
+
+ def _execute(self, outfile,
+ verbosity=None, always=False, continue_=False,
+ reporter='default', num_process=0):
+ """
+ @param reporter: (str) one of provided reporters or ...
+ (class) user defined reporter class (can only be specified
+ from DOIT_CONFIG - never from command line)
+ (reporter instance) - only used in unittests
+ """
+ # get tasks to be executed
+ # self.control is saved on instance to be used by 'auto' command
+ self.control = TaskControl(self.task_list)
+ self.control.process(self.sel_tasks)
+
+ # reporter
+ if isinstance(reporter, basestring):
+ if reporter not in REPORTERS:
+ msg = ("No reporter named '%s'."
+ " Type 'doit help run' to see a list "
+ "of available reporters.")
+ raise InvalidCommand(msg % reporter)
+ reporter_cls = REPORTERS[reporter]
+ else:
+ # user defined class
+ reporter_cls = reporter
+
+ # verbosity
+ if verbosity is None:
+ use_verbosity = Task.DEFAULT_VERBOSITY
+ else:
+ use_verbosity = verbosity
+ show_out = use_verbosity < 2 # show on error report
+
+ # outstream
+ if isinstance(outfile, basestring):
+ outstream = codecs.open(outfile, 'w', encoding='utf-8')
+ else: # outfile is a file-like object (like StringIO or sys.stdout)
+ outstream = outfile
+
+ # run
+ try:
+ # FIXME stderr will be shown twice in case of task error/failure
+ if isinstance(reporter_cls, type):
+ reporter_obj = reporter_cls(outstream, {'show_out':show_out,
+ 'show_err': True})
+ else: # also accepts reporter instances
+ reporter_obj = reporter_cls
+
+
+ if not MRunner.available():
+ num_process = 0
+ sys.stderr.write("WARNING: multiprocessing module not available, " +
+ "running on single process.")
+
+ if num_process == 0:
+ runner = Runner(self.dep_file, reporter_obj, continue_,
+ always, verbosity)
+ else:
+ runner = MRunner(self.dep_file, reporter_obj, continue_,
+ always, verbosity, num_process)
+
+ return runner.run_all(self.control.task_dispatcher())
+ finally:
+ if isinstance(outfile, str):
+ outstream.close()
+
diff --git a/pool/shard002/Python/0026273_test_t-test.py b/pool/shard002/Python/0026273_test_t-test.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a88b4f77fe65d420ab6c10be49a70360bcfae86
--- /dev/null
+++ b/pool/shard002/Python/0026273_test_t-test.py
@@ -0,0 +1,30 @@
+"""test_t-test.py
+Tests for the functions in the t-test.py
+
+Run with:
+ nosetests test_t-test.py
+"""
+from __future__ import print_function
+import os, sys
+import numpy as np
+from numpy.testing import assert_almost_equal, assert_array_equal
+
+#Append path to functions
+sys.path.append(os.path.join(os.path.dirname(__file__), "../functions/"))
+from t_stat import *
+
+def test_t_stat():
+ psychopathy = [11.416, 4.514, 12.204, 14.835,
+ 8.416, 6.563, 17.343, 13.02,
+ 15.19 , 11.902, 22.721, 22.324]
+ clammy = [0.389, 0.2 , 0.241, 0.463,
+ 4.585, 1.097, 1.642, 4.972,
+ 7.957, 5.585, 5.527, 6.964]
+ age = [22.5, 25.3, 24.6, 21.4,
+ 20.7, 23.3, 23.8, 21.7,
+ 21.3, 25.2, 24.6, 21.8]
+ X = np.column_stack((np.ones(12), clammy))
+ Y = np.asarray(psychopathy)
+ B, t, df, p = t_stat(Y, X)
+ assert_array_equal((np.around(t[1][:6],6),np.around(p[1][:6],6)),
+ ( [1.914389], [0.042295]))
diff --git a/pool/shard002/Python/0026274_store_controller.py b/pool/shard002/Python/0026274_store_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce7e61c2d72d9867385fb87ed19308b113fc2d6d
--- /dev/null
+++ b/pool/shard002/Python/0026274_store_controller.py
@@ -0,0 +1,35 @@
+import pyramid_handlers
+
+from blue_yellow_app.controllers.base_controller import BaseController
+from blue_yellow_app.services.albums_service import AlbumsService
+from blue_yellow_app.services.store_service import StoreService
+
+
+class StoreController(BaseController):
+ @pyramid_handlers.action()
+ def complete(self):
+ # {'stripeToken': 'tok_19aUhV4bdW93NdzOnsPOc8K4',
+ # 'stripeTokenType': 'card',
+ # 'stripeEmail': 'mikeckennedy@gmail.com',
+ # 'action': 'complete',
+ # 'id': 28}
+
+ album_id = int(self.data_dict.get('id', -1))
+ album = AlbumsService.get_album_by_id(album_id)
+
+ token = self.data_dict.get('stripeToken')
+ StoreService.purchase_album(self.logged_in_user, album, album.price, token)
+
+ # TODO: send email receipt to self.data_dict['stripeEmail']
+
+ self.redirect('/store/success/{}'.format(album.id))
+
+ @pyramid_handlers.action(renderer='templates/store/success.pt')
+ def success(self):
+ album_id = int(self.data_dict.get('id', -1))
+ album = AlbumsService.get_album_by_id(album_id)
+ return {'album': album}
+
+ @pyramid_handlers.action(renderer='templates/store/failed.pt')
+ def failed(self):
+ return {}
diff --git a/pool/shard002/Python/0026284_test_isoinfo.py b/pool/shard002/Python/0026284_test_isoinfo.py
new file mode 100644
index 0000000000000000000000000000000000000000..e73a84ce6535ab38683038dd3c8035442f9a05b9
--- /dev/null
+++ b/pool/shard002/Python/0026284_test_isoinfo.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2013-2015 Bastian Kleineidam
+#
+# 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 . import ArchiveTest
+from .. import needs_program
+
+class TestIsoinfo(ArchiveTest):
+
+ program = 'isoinfo'
+
+ @needs_program(program)
+ def test_isoinfo(self):
+ self.archive_list('t.iso')
+
+ @needs_program(program)
+ def test_isoinfo_file(self):
+ self.archive_list('t.iso.foo')
diff --git a/pool/shard002/Python/0026288_status_command.py b/pool/shard002/Python/0026288_status_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..6693eb31b91f881326b6c7d8a989f44e03bbcb67
--- /dev/null
+++ b/pool/shard002/Python/0026288_status_command.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+
+from cleo import InputOption
+from orator.migrations import Migrator, DatabaseMigrationRepository
+from .base_command import BaseCommand
+
+
+class StatusCommand(BaseCommand):
+
+ def configure(self):
+ super(StatusCommand, self).configure()
+
+ self.set_name('migrations:status')
+ self.set_description('Show a list of migrations up/down')
+ self.add_option('database', 'd', InputOption.VALUE_OPTIONAL,
+ 'The database connection to use')
+ self.add_option('path', 'p', InputOption.VALUE_OPTIONAL,
+ 'The path of migrations files to be executed.')
+
+ def execute(self, i, o):
+ """
+ Executes the command.
+
+ :type i: cleo.inputs.input.Input
+ :type o: cleo.outputs.output.Output
+ """
+ super(StatusCommand, self).execute(i, o)
+
+ database = i.get_option('database')
+ repository = DatabaseMigrationRepository(self._resolver, 'migrations')
+
+ migrator = Migrator(repository, self._resolver)
+
+ if not migrator.repository_exists():
+ return o.writeln('No migrations found')
+
+ self._prepare_database(migrator, database, i, o)
+
+ path = i.get_option('path')
+
+ if path is None:
+ path = self._get_migration_path()
+
+ ran = migrator.get_repository().get_ran()
+
+ migrations = []
+ for migration in migrator._get_migration_files(path):
+ if migration in ran:
+ migrations.append(['%s>' % migration, 'Yes'])
+ else:
+ migrations.append(['%s>' % migration, 'No>'])
+
+ if migrations:
+ table = self.get_helper('table')
+ table.set_headers(['Migration', 'Ran?'])
+ table.set_rows(migrations)
+ table.render(o)
+ else:
+ return o.writeln('No migrations found')
+
+ for note in migrator.get_notes():
+ o.writeln(note)
+
+ def _prepare_database(self, migrator, database, i, o):
+ migrator.set_connection(database)
diff --git a/pool/shard002/Python/0026293_middleware.py b/pool/shard002/Python/0026293_middleware.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bf0a7758a03ad9483c83d18165c6ff69581974f
--- /dev/null
+++ b/pool/shard002/Python/0026293_middleware.py
@@ -0,0 +1,163 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
+from copy import deepcopy
+
+from django.conf import settings
+from django.contrib import admin
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.six import string_types
+
+try:
+ from django.urls import resolve, Resolver404
+except ModuleNotFoundError:
+ # Deprecated since Django 1.10, removed in Django 2.0
+ from django.urls.urlresolvers import resolve, Resolver404
+
+try:
+ from django.utils.deprecation import MiddlewareMixin
+except ImportError:
+ # Not required for Django <= 1.9, see:
+ # https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware
+ MiddlewareMixin = object
+
+
+class ModelAdminReorder(MiddlewareMixin):
+
+ def init_config(self, request, app_list):
+ self.request = request
+ self.app_list = app_list
+
+ self.config = getattr(settings, 'ADMIN_REORDER', None)
+ if not self.config:
+ # ADMIN_REORDER settings is not defined.
+ raise ImproperlyConfigured('ADMIN_REORDER config is not defined.')
+
+ if not isinstance(self.config, (tuple, list)):
+ raise ImproperlyConfigured(
+ 'ADMIN_REORDER config parameter must be tuple or list. '
+ 'Got {config}'.format(config=self.config))
+
+ admin_index = admin.site.index(request)
+ try:
+ # try to get all installed models
+ app_list = admin_index.context_data['app_list']
+ except KeyError:
+ # use app_list from context if this fails
+ pass
+
+ # Flatten all models from apps
+ self.models_list = []
+ for app in app_list:
+ for model in app['models']:
+ model['model_name'] = self.get_model_name(
+ app['app_label'], model['object_name'])
+ self.models_list.append(model)
+
+ def get_app_list(self):
+ ordered_app_list = []
+ for app_config in self.config:
+ app = self.make_app(app_config)
+ if app:
+ ordered_app_list.append(app)
+ return ordered_app_list
+
+ def make_app(self, app_config):
+ if not isinstance(app_config, (dict, string_types)):
+ raise TypeError('ADMIN_REORDER list item must be '
+ 'dict or string. Got %s' % repr(app_config))
+
+ if isinstance(app_config, string_types):
+ # Keep original label and models
+ return self.find_app(app_config)
+ else:
+ return self.process_app(app_config)
+
+ def find_app(self, app_label):
+ for app in self.app_list:
+ if app['app_label'] == app_label:
+ return app
+
+ def get_model_name(self, app_name, model_name):
+ if '.' not in model_name:
+ model_name = '%s.%s' % (app_name, model_name)
+ return model_name
+
+ def process_app(self, app_config):
+ if 'app' not in app_config:
+ raise NameError('ADMIN_REORDER list item must define '
+ 'a "app" name. Got %s' % repr(app_config))
+
+ app = self.find_app(app_config['app'])
+ if app:
+ app = deepcopy(app)
+ # Rename app
+ if 'label' in app_config:
+ app['name'] = app_config['label']
+
+ # Process app models
+ if 'models' in app_config:
+ models_config = app_config.get('models')
+ models = self.process_models(models_config)
+ if models:
+ app['models'] = models
+ else:
+ return None
+ return app
+
+ def process_models(self, models_config):
+ if not isinstance(models_config, (dict, list, tuple)):
+ raise TypeError('"models" config for ADMIN_REORDER list '
+ 'item must be dict or list/tuple. '
+ 'Got %s' % repr(models_config))
+
+ ordered_models_list = []
+ for model_config in models_config:
+ model = None
+ if isinstance(model_config, dict):
+ model = self.process_model(model_config)
+ else:
+ model = self.find_model(model_config)
+
+ if model:
+ ordered_models_list.append(model)
+
+ return ordered_models_list
+
+ def find_model(self, model_name):
+ for model in self.models_list:
+ if model['model_name'] == model_name:
+ return model
+
+ def process_model(self, model_config):
+ # Process model defined as { model: 'model', 'label': 'label' }
+ for key in ('model', 'label', ):
+ if key not in model_config:
+ return
+ model = self.find_model(model_config['model'])
+ if model:
+ model['name'] = model_config['label']
+ return model
+
+ def process_template_response(self, request, response):
+ try:
+ url = resolve(request.path_info)
+ except Resolver404:
+ return response
+ if not url.app_name == 'admin' and \
+ url.url_name not in ['index', 'app_list']:
+ # current view is not a django admin index
+ # or app_list view, bail out!
+ return response
+
+ try:
+ app_list = response.context_data['app_list']
+ except KeyError:
+ # there is no app_list! nothing to reorder
+ return response
+
+ self.init_config(request, app_list)
+ ordered_app_list = self.get_app_list()
+ response.context_data['app_list'] = ordered_app_list
+ return response
diff --git a/pool/shard002/Python/0026294_pipeline_hof.py b/pool/shard002/Python/0026294_pipeline_hof.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f1054fa76a227e8c923a2db9a344d349d77e288
--- /dev/null
+++ b/pool/shard002/Python/0026294_pipeline_hof.py
@@ -0,0 +1,39 @@
+from pipeline_base import PipelineBlock
+
+class Filter(PipelineBlock):
+ """
+ Filter out data through this block by checking the truth of the given function.
+ """
+ def __init__(self, function):
+ self.function = function
+
+ def run(self, input_data):
+ return (element for element in input_data if self.function(element))
+
+
+class Fold(PipelineBlock):
+ """
+ Successively reduce inputs with the given binary function.
+ """
+ def __init__(self, function):
+ self.function = function
+
+ def run(self, input_data):
+ input_iter = iter(input_data)
+ x = next(input_iter)
+ for element in input_iter:
+ x = self.function(x, element)
+ return x
+
+
+class Map(PipelineBlock):
+ """
+ Map each item passing through this block using the given function.
+ """
+ def __init__(self, function):
+ self.function = function
+
+ def run(self, input_data):
+ return (self.function(element) for element in input_data)
+
+
diff --git a/pool/shard002/Python/0026296_simpletreemodel.py b/pool/shard002/Python/0026296_simpletreemodel.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a1c9cf22adfa5a60858d3076df1dfc81e8dd4af
--- /dev/null
+++ b/pool/shard002/Python/0026296_simpletreemodel.py
@@ -0,0 +1,212 @@
+#!/usr/bin/env python
+
+
+#############################################################################
+##
+## Copyright (C) 2013 Riverbank Computing Limited.
+## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+## All rights reserved.
+##
+## This file is part of the examples of PyQt.
+##
+## $QT_BEGIN_LICENSE:BSD$
+## You may use this file under the terms of the BSD license as follows:
+##
+## "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 Nokia Corporation and its Subsidiary(-ies) 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."
+## $QT_END_LICENSE$
+##
+#############################################################################
+
+
+from PyQt5.QtCore import QAbstractItemModel, QFile, QIODevice, QModelIndex, Qt
+from PyQt5.QtWidgets import QApplication, QTreeView
+
+import simpletreemodel_rc
+
+
+class TreeItem(object):
+ def __init__(self, data, parent=None):
+ self.parentItem = parent
+ self.itemData = data
+ self.childItems = []
+
+ def appendChild(self, item):
+ self.childItems.append(item)
+
+ def child(self, row):
+ return self.childItems[row]
+
+ def childCount(self):
+ return len(self.childItems)
+
+ def columnCount(self):
+ return len(self.itemData)
+
+ def data(self, column):
+ try:
+ return self.itemData[column]
+ except IndexError:
+ return None
+
+ def parent(self):
+ return self.parentItem
+
+ def row(self):
+ if self.parentItem:
+ return self.parentItem.childItems.index(self)
+
+ return 0
+
+
+class TreeModel(QAbstractItemModel):
+ def __init__(self, data, parent=None):
+ super(TreeModel, self).__init__(parent)
+
+ self.rootItem = TreeItem(("Title", "Summary"))
+ self.setupModelData(data.split('\n'), self.rootItem)
+
+ def columnCount(self, parent):
+ if parent.isValid():
+ return parent.internalPointer().columnCount()
+ else:
+ return self.rootItem.columnCount()
+
+ def data(self, index, role):
+ if not index.isValid():
+ return None
+
+ if role != Qt.DisplayRole:
+ return None
+
+ item = index.internalPointer()
+
+ return item.data(index.column())
+
+ def flags(self, index):
+ if not index.isValid():
+ return Qt.NoItemFlags
+
+ return Qt.ItemIsEnabled | Qt.ItemIsSelectable
+
+ def headerData(self, section, orientation, role):
+ if orientation == Qt.Horizontal and role == Qt.DisplayRole:
+ return self.rootItem.data(section)
+
+ return None
+
+ def index(self, row, column, parent):
+ if not self.hasIndex(row, column, parent):
+ return QModelIndex()
+
+ if not parent.isValid():
+ parentItem = self.rootItem
+ else:
+ parentItem = parent.internalPointer()
+
+ childItem = parentItem.child(row)
+ if childItem:
+ return self.createIndex(row, column, childItem)
+ else:
+ return QModelIndex()
+
+ def parent(self, index):
+ if not index.isValid():
+ return QModelIndex()
+
+ childItem = index.internalPointer()
+ parentItem = childItem.parent()
+
+ if parentItem == self.rootItem:
+ return QModelIndex()
+
+ return self.createIndex(parentItem.row(), 0, parentItem)
+
+ def rowCount(self, parent):
+ if parent.column() > 0:
+ return 0
+
+ if not parent.isValid():
+ parentItem = self.rootItem
+ else:
+ parentItem = parent.internalPointer()
+
+ return parentItem.childCount()
+
+ def setupModelData(self, lines, parent):
+ parents = [parent]
+ indentations = [0]
+
+ number = 0
+
+ while number < len(lines):
+ position = 0
+ while position < len(lines[number]):
+ if lines[number][position] != ' ':
+ break
+ position += 1
+
+ lineData = lines[number][position:].trimmed()
+
+ if lineData:
+ # Read the column data from the rest of the line.
+ columnData = [s for s in lineData.split('\t') if s]
+
+ if position > indentations[-1]:
+ # The last child of the current parent is now the new
+ # parent unless the current parent has no children.
+
+ if parents[-1].childCount() > 0:
+ parents.append(parents[-1].child(parents[-1].childCount() - 1))
+ indentations.append(position)
+
+ else:
+ while position < indentations[-1] and len(parents) > 0:
+ parents.pop()
+ indentations.pop()
+
+ # Append a new item to the current parent's list of children.
+ parents[-1].appendChild(TreeItem(columnData, parents[-1]))
+
+ number += 1
+
+
+if __name__ == '__main__':
+
+ import sys
+
+ app = QApplication(sys.argv)
+
+ f = QFile(':/default.txt')
+ f.open(QIODevice.ReadOnly)
+ model = TreeModel(f.readAll())
+ f.close()
+
+ view = QTreeView()
+ view.setModel(model)
+ view.setWindowTitle("Simple Tree Model")
+ view.show()
+ sys.exit(app.exec_())
diff --git a/pool/shard002/Python/0026300_hsts_header.py b/pool/shard002/Python/0026300_hsts_header.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbc5c7d7ae2a55fe46d3b1803902dbfc84e1cd0e
--- /dev/null
+++ b/pool/shard002/Python/0026300_hsts_header.py
@@ -0,0 +1,52 @@
+import requests
+import time
+from ..utils.log import log, INFO, ERROR, PASS
+from ..tests import TestWithDependency
+
+__all__ = ["hsts_header"]
+
+
+#####
+# Test : Check a Strict Transport Security Header is Present
+#####
+@TestWithDependency("HSTS_HEADER")
+def hsts_header(ISAAC_WEB, WAIT_DUR, **kwargs):
+ """Test if responses from Isaac contain a Strict Transport Security Header.
+
+ - 'ISAAC_WEB' is the string URL of the Isaac website to be tested.
+ """
+ time.sleep(WAIT_DUR)
+ try:
+ log(INFO, "Making direct HTTP request to '%s'" % ISAAC_WEB)
+ response = requests.get(ISAAC_WEB)
+ assert "Strict-Transport-Security" in response.headers, "No HSTS header present in response from '%s'!" % ISAAC_WEB
+ hsts_header = response.headers["Strict-Transport-Security"]
+ log(INFO, "HSTS header present in response: '%s'." % hsts_header)
+ hsts_directives = [p.strip() for p in hsts_header.split(";")]
+ n_hsts_directives = len(hsts_directives)
+ assert n_hsts_directives == 3, "Expected 3 directives in header, found %s!" % n_hsts_directives
+
+ assert any([d.startswith("max-age=") for d in hsts_directives]), "HSTS requires a max-age directive to be effective!"
+ assert "includeSubDomains" in hsts_directives, "Expected 'includeSubdomains' directive: not found!"
+ assert "preload" in hsts_directives, "Expected 'includeSubdomains' directive: not found!"
+ log(INFO, "HSTS header contains all required directives.")
+
+ max_age_directive = [d for d in hsts_directives if d.startswith("max-age=")][0]
+ max_age = int(max_age_directive.replace("max-age=", ""))
+ assert max_age > 60*60*24*365, "HSTS max-age should be greater than 1 year!"
+ log(INFO, "HSTS header contains suitable max-age directive.")
+
+ log(PASS, "Valid and sensible HSTS header found.")
+ return True
+ except AssertionError as e:
+ log(ERROR, e.message)
+ return False
+ except IndexError:
+ log(ERROR, "Can't access max-age directive; can't continue!")
+ return False
+ except ValueError:
+ log(ERROR, "Malformed max-age directive!")
+ return False
+ except IOError:
+ log(ERROR, "Cannot connect to '%s'; can't continue!" % ISAAC_WEB)
+ return False
diff --git a/pool/shard002/Python/0026303_pwb_tests.py b/pool/shard002/Python/0026303_pwb_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..94535f323277458db0fe4afdbf0193a7e98188e0
--- /dev/null
+++ b/pool/shard002/Python/0026303_pwb_tests.py
@@ -0,0 +1,82 @@
+# -*- coding: utf-8 -*-
+"""
+Test pwb.py.
+
+If pwb.py does not load python files as expected, more tests from coverage
+should be added locally.
+https://bitbucket.org/ned/coveragepy/src/default/tests/test_execfile.py
+"""
+#
+# (C) Pywikibot team, 2007-2014
+#
+# Distributed under the terms of the MIT license.
+#
+from __future__ import absolute_import, unicode_literals
+
+__version__ = '$Id$'
+
+import sys
+
+from tests import join_tests_path, create_path_func
+from tests.utils import execute, execute_pwb
+from tests.aspects import unittest, PwbTestCase
+
+join_pwb_tests_path = create_path_func(join_tests_path, 'pwb')
+
+
+class TestPwb(PwbTestCase):
+
+ """
+ Test pwb.py functionality.
+
+ This is registered as a Site test because it will not run
+ without a user-config.py
+ """
+
+ # site must be explicitly set for pwb tests. This test does not require
+ # network access, because tests/pwb/print_locals.py does not use
+ # handle_args, etc. so version.py doesnt talk on the network.
+ site = False
+ net = False
+
+ def _do_check(self, name):
+ package_name = 'tests.pwb.' + name
+ script_path = join_pwb_tests_path(name + '.py')
+
+ direct = execute([sys.executable, '-m', package_name])
+ vpwb = execute_pwb([script_path])
+ self.maxDiff = None
+ self.assertEqual(direct['stdout'], vpwb['stdout'])
+
+ return (direct, vpwb)
+
+ def test_env(self):
+ """
+ Test external environment of pywikibot.
+
+ Make sure the environment is not contaminated, and is the same as
+ the environment we get when directly running a script.
+ """
+ self._do_check('print_env')
+
+ def test_locals(self):
+ """
+ Test internal environment of pywikibot.
+
+ Make sure the environment is not contaminated, and is the same as
+ the environment we get when directly running a script.
+ """
+ self._do_check('print_locals')
+
+ def test_unicode(self):
+ """Test printing unicode in pywikibot."""
+ (direct, vpwb) = self._do_check('print_unicode')
+
+ self.assertEqual('Häuser', direct['stdout'].strip())
+ self.assertEqual('Häuser', direct['stderr'].strip())
+ self.assertEqual('Häuser', vpwb['stdout'].strip())
+ self.assertEqual('Häuser', vpwb['stderr'].strip())
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=10)
diff --git a/pool/shard002/Python/0026305_test_ec2utils.py b/pool/shard002/Python/0026305_test_ec2utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dceb7de1225a09a11026f6d00745ee9c249dff5
--- /dev/null
+++ b/pool/shard002/Python/0026305_test_ec2utils.py
@@ -0,0 +1,61 @@
+# Copyright 2014 - Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from nova.api.ec2 import ec2utils
+from nova import context
+from nova import objects
+from nova import test
+
+
+class EC2UtilsTestCase(test.TestCase):
+ def setUp(self):
+ self.ctxt = context.get_admin_context()
+ ec2utils.reset_cache()
+ super(EC2UtilsTestCase, self).setUp()
+
+ def test_get_int_id_from_snapshot_uuid(self):
+ smap = objects.EC2SnapshotMapping(self.ctxt, uuid='fake-uuid')
+ smap.create()
+ smap_id = ec2utils.get_int_id_from_snapshot_uuid(self.ctxt,
+ 'fake-uuid')
+ self.assertEqual(smap.id, smap_id)
+
+ def test_get_int_id_from_snapshot_uuid_creates_mapping(self):
+ smap_id = ec2utils.get_int_id_from_snapshot_uuid(self.ctxt,
+ 'fake-uuid')
+ smap = objects.EC2SnapshotMapping.get_by_id(self.ctxt, smap_id)
+ self.assertEqual('fake-uuid', smap.uuid)
+
+ def test_get_snapshot_uuid_from_int_id(self):
+ smap = objects.EC2SnapshotMapping(self.ctxt, uuid='fake-uuid')
+ smap.create()
+ smap_uuid = ec2utils.get_snapshot_uuid_from_int_id(self.ctxt, smap.id)
+ self.assertEqual(smap.uuid, smap_uuid)
+
+ def test_id_to_glance_id(self):
+ s3imap = objects.S3ImageMapping(self.ctxt, uuid='fake-uuid')
+ s3imap.create()
+ uuid = ec2utils.id_to_glance_id(self.ctxt, s3imap.id)
+ self.assertEqual(uuid, s3imap.uuid)
+
+ def test_glance_id_to_id(self):
+ s3imap = objects.S3ImageMapping(self.ctxt, uuid='fake-uuid')
+ s3imap.create()
+ s3imap_id = ec2utils.glance_id_to_id(self.ctxt, s3imap.uuid)
+ self.assertEqual(s3imap_id, s3imap.id)
+
+ def test_glance_id_to_id_creates_mapping(self):
+ s3imap_id = ec2utils.glance_id_to_id(self.ctxt, 'fake-uuid')
+ s3imap = objects.S3ImageMapping.get_by_id(self.ctxt, s3imap_id)
+ self.assertEqual('fake-uuid', s3imap.uuid)
diff --git a/pool/shard002/Python/0026311_result.py b/pool/shard002/Python/0026311_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..0920facb3f37e2c217dea704fb4a766e542a4a54
--- /dev/null
+++ b/pool/shard002/Python/0026311_result.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+
+class Result(object):
+ STATUS_ERROR = "error"
+ STATUS_SUCCESS = "success"
+ _default_code = 500
+
+ def __init__(self, status, code=_default_code, data={}, msg=""):
+ self._status = status
+ self._code = code
+ self._data = data
+ self._msg = msg
+
+ def status(self):
+ return self._status
+
+ def code(self):
+ return self._code
+
+ def data(self):
+ return self._data
+
+ def msg(self):
+ return self._msg
+
+ def setData(self, obj):
+ self._data = obj
+
+ def json(self):
+ return { "status": self._status, "code": self._code }
+
+class Error(Result):
+ def __init__(self, code, msg):
+ super(Error, self).__init__(status=Result.STATUS_ERROR, code=code, msg=msg)
+
+ def json(self):
+ return { "status": self._status, "code": self._code, "msg": self._msg }
+
+class Success(Result):
+ def __init__(self, data):
+ super(Success, self).__init__(status=Result.STATUS_SUCCESS, code=200, data=data)
+
+ def json(self):
+ return { "status": self._status, "code": self._code, "data": self._data }
diff --git a/pool/shard002/Python/0026313_renderer_test.py b/pool/shard002/Python/0026313_renderer_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb134f62566df184045f6811bde6bf263fb93044
--- /dev/null
+++ b/pool/shard002/Python/0026313_renderer_test.py
@@ -0,0 +1,46 @@
+"""Tests for the renderer."""
+
+import unittest
+import mock
+from grow.pods import pods
+from grow import storage
+from grow.common import bulk_errors
+from grow.rendering import render_controller
+from grow.rendering import renderer
+from grow.testing import testing
+
+
+class RendererTestCase(unittest.TestCase):
+ """Test the renderer."""
+
+ def setUp(self):
+ self.dir_path = testing.create_test_pod_dir()
+ self.pod = pods.Pod(self.dir_path, storage=storage.FileStorage)
+ self.render = renderer.Renderer()
+
+ def test_renderer(self):
+ """Renders the docs without errors."""
+ self.pod.router.add_all(use_cache=False)
+ routes = self.pod.router.routes
+ self.render.rendered_docs(self.pod, routes)
+
+ def test_renderer_sans_threading(self):
+ """Renders the docs without threading."""
+ self.pod.router.add_all(use_cache=False)
+ routes = self.pod.router.routes
+ self.render.rendered_docs(self.pod, routes, use_threading=False)
+
+ @mock.patch.object(render_controller.RenderDocumentController, 'render')
+ def test_render(self, mock_render):
+ """Renders the docs with errors."""
+ mock_render.side_effect = ValueError()
+
+ self.pod.router.add_all(use_cache=False)
+ routes = self.pod.router.routes
+
+ with self.assertRaises(bulk_errors.BulkErrors):
+ self.render.rendered_docs(self.pod, routes)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard002/Python/0026316_taskwarrior.py b/pool/shard002/Python/0026316_taskwarrior.py
new file mode 100644
index 0000000000000000000000000000000000000000..afef17d136bec0cdee25a96bea0251a813b09e40
--- /dev/null
+++ b/pool/shard002/Python/0026316_taskwarrior.py
@@ -0,0 +1,57 @@
+# -*- coding: utf-8 -*-
+"""
+Display currently active (started) taskwarrior tasks.
+
+Configuration parameters:
+ - cache_timeout : how often we refresh this module in seconds (5s default)
+
+Requires
+ - task
+
+@author James Smith http://jazmit.github.io/
+@license BSD
+"""
+
+# import your useful libs here
+from time import time
+from subprocess import check_output
+import json
+import shlex
+
+
+class Py3status:
+ """
+ """
+ # available configuration parameters
+ cache_timeout = 5
+
+ def taskWarrior(self, i3s_output_list, i3s_config):
+ command = 'task start.before:tomorrow status:pending export'
+ taskwarrior_output = check_output(shlex.split(command))
+ tasks_json = json.loads(taskwarrior_output.decode('utf-8'))
+
+ def describeTask(taskObj):
+ return str(taskObj['id']) + ' ' + taskObj['description']
+
+ result = ', '.join(map(describeTask, tasks_json))
+ response = {
+ 'cached_until': time() + self.cache_timeout,
+ 'full_text': result
+ }
+ return response
+
+
+if __name__ == "__main__":
+ """
+ Test this module by calling it directly.
+ """
+ from time import sleep
+ x = Py3status()
+ config = {
+ 'color_bad': '#FF0000',
+ 'color_degraded': '#FFFF00',
+ 'color_good': '#00FF00'
+ }
+ while True:
+ print(x.taskWarrior([], config))
+ sleep(1)
diff --git a/pool/shard002/Python/0026318_social_auth.py b/pool/shard002/Python/0026318_social_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..90aae6438034ddffdf47ee69af13e6c6f143f56c
--- /dev/null
+++ b/pool/shard002/Python/0026318_social_auth.py
@@ -0,0 +1,87 @@
+from social.exceptions import AuthAlreadyAssociated, AuthException, \
+ AuthForbidden
+
+
+def social_details(backend, response, *args, **kwargs):
+ return {'details': backend.get_user_details(response)}
+
+
+def social_uid(backend, details, response, *args, **kwargs):
+ return {'uid': backend.get_user_id(details, response)}
+
+
+def auth_allowed(backend, details, response, *args, **kwargs):
+ if not backend.auth_allowed(response, details):
+ raise AuthForbidden(backend)
+
+
+def social_user(backend, uid, user=None, *args, **kwargs):
+ provider = backend.name
+ social = backend.strategy.storage.user.get_social_auth(provider, uid)
+ if social:
+ if user and social.user != user:
+ msg = 'This {0} account is already in use.'.format(provider)
+ raise AuthAlreadyAssociated(backend, msg)
+ elif not user:
+ user = social.user
+ return {'social': social,
+ 'user': user,
+ 'is_new': user is None,
+ 'new_association': False}
+
+
+def associate_user(backend, uid, user=None, social=None, *args, **kwargs):
+ if user and not social:
+ try:
+ social = backend.strategy.storage.user.create_social_auth(
+ user, uid, backend.name
+ )
+ except Exception as err:
+ if not backend.strategy.storage.is_integrity_error(err):
+ raise
+ # Protect for possible race condition, those bastard with FTL
+ # clicking capabilities, check issue #131:
+ # https://github.com/omab/django-social-auth/issues/131
+ return social_user(backend, uid, user, *args, **kwargs)
+ else:
+ return {'social': social,
+ 'user': social.user,
+ 'new_association': True}
+
+
+def associate_by_email(backend, details, user=None, *args, **kwargs):
+ """
+ Associate current auth with a user with the same email address in the DB.
+
+ This pipeline entry is not 100% secure unless you know that the providers
+ enabled enforce email verification on their side, otherwise a user can
+ attempt to take over another user account by using the same (not validated)
+ email address on some provider. This pipeline entry is disabled by
+ default.
+ """
+ if user:
+ return None
+
+ email = details.get('email')
+ if email:
+ # Try to associate accounts registered with the same email address,
+ # only if it's a single object. AuthException is raised if multiple
+ # objects are returned.
+ users = list(backend.strategy.storage.user.get_users_by_email(email))
+ if len(users) == 0:
+ return None
+ elif len(users) > 1:
+ raise AuthException(
+ backend,
+ 'The given email address is associated with another account'
+ )
+ else:
+ return {'user': users[0]}
+
+
+def load_extra_data(backend, details, response, uid, user, *args, **kwargs):
+ social = kwargs.get('social') or \
+ backend.strategy.storage.user.get_social_auth(backend.name, uid)
+ if social:
+ extra_data = backend.extra_data(user, uid, response, details)
+ social.set_extra_data(extra_data)
diff --git a/pool/shard002/Python/0026322_yaml.py b/pool/shard002/Python/0026322_yaml.py
new file mode 100644
index 0000000000000000000000000000000000000000..81691cbc2ae75c88a289b17201f4d5ea067979a5
--- /dev/null
+++ b/pool/shard002/Python/0026322_yaml.py
@@ -0,0 +1,80 @@
+"""
+YAML serializer.
+
+Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__.
+"""
+
+import collections
+import decimal
+from io import StringIO
+
+import yaml
+
+from django.core.serializers.base import DeserializationError
+from django.core.serializers.python import (
+ Deserializer as PythonDeserializer, Serializer as PythonSerializer,
+)
+from django.db import models
+
+# Use the C (faster) implementation if possible
+try:
+ from yaml import CSafeLoader as SafeLoader
+ from yaml import CSafeDumper as SafeDumper
+except ImportError:
+ from yaml import SafeLoader, SafeDumper
+
+
+class DjangoSafeDumper(SafeDumper):
+ def represent_decimal(self, data):
+ return self.represent_scalar('tag:yaml.org,2002:str', str(data))
+
+ def represent_ordered_dict(self, data):
+ return self.represent_mapping('tag:yaml.org,2002:map', data.items())
+
+
+DjangoSafeDumper.add_representer(
+ decimal.Decimal, DjangoSafeDumper.represent_decimal)
+DjangoSafeDumper.add_representer(
+ collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict)
+
+
+class Serializer(PythonSerializer):
+ """Convert a queryset to YAML."""
+
+ internal_use_only = False
+
+ def handle_field(self, obj, field):
+ # A nasty special case: base YAML doesn't support serialization of time
+ # types (as opposed to dates or datetimes, which it does support). Since
+ # we want to use the "safe" serializer for better interoperability, we
+ # need to do something with those pesky times. Converting 'em to strings
+ # isn't perfect, but it's better than a "!!python/time" type which would
+ # halt deserialization under any other language.
+ if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None:
+ self._current[field.name] = str(getattr(obj, field.name))
+ else:
+ super().handle_field(obj, field)
+
+ def end_serialization(self):
+ yaml.dump(self.objects, self.stream,
+ Dumper=DjangoSafeDumper, **self.options)
+
+ def getvalue(self):
+ # Grandparent super
+ return super(PythonSerializer, self).getvalue()
+
+
+def Deserializer(stream_or_string, **options):
+ """Deserialize a stream or string of YAML data."""
+ if isinstance(stream_or_string, bytes):
+ stream_or_string = stream_or_string.decode()
+ if isinstance(stream_or_string, str):
+ stream = StringIO(stream_or_string)
+ else:
+ stream = stream_or_string
+ try:
+ yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options)
+ except (GeneratorExit, DeserializationError):
+ raise
+ except Exception as exc:
+ raise DeserializationError() from exc
diff --git a/pool/shard002/Python/0026326_batch_reports.py b/pool/shard002/Python/0026326_batch_reports.py
new file mode 100644
index 0000000000000000000000000000000000000000..6397d54adf2182be4a770ab6e6d4bb2811de979a
--- /dev/null
+++ b/pool/shard002/Python/0026326_batch_reports.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+# encoding: utf-8
+
+import sys
+import os
+
+path = os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))
+sys.path.append(path)
+os.environ['DJANGO_SETTINGS_MODULE'] = 'fixmystreet.settings'
+
+import datetime
+from datetime import datetime as dt
+from django.core.mail import send_mail
+from django.template.loader import render_to_string
+from apps.mainapp.models import Report
+from fixmystreet import settings
+
+
+reminder_email_count = 0
+councillor_email_count = 0
+#
+## send new reports to ward councillors
+#for ward in Ward.objects.all():
+# new_reports = ward.report_set.filter(ward=ward,is_confirmed=True,is_fixed=False,sent_at__isnull=True).order_by("-created_at")
+# if len(new_reports) > 0 :
+# subject = render_to_string("emails/batch_reports/new_reports/subject.txt",
+# {'ward': ward })
+# message = render_to_string("emails/batch_reports/new_reports/message.html",
+# {'new_reports': new_reports, 'ward': ward })
+#
+# msg = EmailMessage(subject, message,settings.EMAIL_FROM_USER,[ward.councillor.email, settings.ADMIN_EMAIL])
+# msg.content_subtype = "html" # Main content is now text/html
+# msg.send()
+#
+# print "sending report for ward " + ward.name
+# new_reports.update(sent_at=dt.now())
+# councillor_email_count += 1
+
+# send old reports that have not been updated
+one_month_ago = dt.today() - datetime.timedelta(days=31)
+reminder_reports = Report.objects.filter(is_confirmed=True, status='not-fixed', reminded_at__lte=one_month_ago,
+ updated_at__lte=one_month_ago).order_by("ward", "-created_at")
+
+for report in reminder_reports:
+ subject = render_to_string("emails/batch_reports/reminders/subject.txt",
+ {'report': report})
+ message = render_to_string("emails/batch_reports/reminders/message.txt",
+ {'report': report})
+
+ send_mail(subject, message, settings.EMAIL_FROM_USER, [report.first_update().email], fail_silently=False)
+
+ report.reminded_at = dt.now()
+ report.save()
+ reminder_email_count += 1
+
+# notify admin reports were run
+send_mail('Ward Summary Reports Run %s' % ( dt.now() ),
+ '%d Report Summaries Sent to Councillors\n%d Reminders Sent' % (
+ councillor_email_count, reminder_email_count ),
+ settings.EMAIL_FROM_USER, [settings.ADMIN_EMAIL], fail_silently=False)
+
diff --git a/pool/shard002/Python/0026334_launch.py b/pool/shard002/Python/0026334_launch.py
new file mode 100644
index 0000000000000000000000000000000000000000..092b2f6476e08e3024b709a19f28db18103a713f
--- /dev/null
+++ b/pool/shard002/Python/0026334_launch.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+from __future__ import division
+# import multiprocessing as mp
+# from time import sleep
+from Sounds import Sound_Func
+# from Speech import SphinxServer
+from Joystick import Joystick_Func
+from pygecko import FileStorage
+from hardware import HW_Func
+from multiprocessing import Process
+from chaos import Chaos_Func
+import time
+
+
+def main():
+ fs = FileStorage()
+ fs.readJson("net.json")
+
+ try:
+ hw = Process(target=HW_Func).start()
+ snd = Process(target=Sound_Func).start()
+ chaos = Process(target=Chaos_Func).start()
+ js = Process(target=Joystick_Func).start()
+
+ while True:
+ time.sleep(3)
+
+ except KeyboardInterrupt:
+ print('<<<<<<<< keyboard >>>>>>>>>>>')
+ if snd.is_alive():
+ snd.join(0.1)
+ snd.terminate()
+ if hw.is_alive():
+ hw.join(0.1)
+ hw.terminate()
+ if chaos.is_alive():
+ chaos.join()
+ chaos.terminate()
+ if js.is_alive():
+ js.join()
+ js.terminate()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard002/Python/0026335_Naca.py b/pool/shard002/Python/0026335_Naca.py
new file mode 100644
index 0000000000000000000000000000000000000000..50453fbfbe532e27800b02e8f6c4ddace29ff5ea
--- /dev/null
+++ b/pool/shard002/Python/0026335_Naca.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+
+def Naca_00XX(c, t, x_list):
+ """
+ Generates a simetric NACA airfoil.
+ Inputs:
+ :param c: chord
+ :param t: max thickness as a fraction of the chord.
+ :param x_list: points between 0 and c (chord lenght)
+
+ Returns dictionary with keys 'u'pper and 'l'ower
+
+ The Naca function can be found in: https://en.wikipedia.org/wiki/NACA_airfoil
+
+ Created on Wed Feb 03 12:50:52 2016
+
+ @author: Endryws and Pedro Leal
+ """
+ y_upper = []
+ y_lower = []
+ for x in x_list:
+ xc= x/c # Is just for increase speed and facilitate future changes.
+ a1 = 5*t*c
+ t1 = 0.2969*(math.sqrt(xc))
+ t2 = -0.1260*xc
+ t3 = -0.3516*(xc**2)
+ t4 = 0.2843*(xc**3)
+ t5 = -0.1015*(xc**4)
+ y = (a1*(t1+t2+t3+t4+t5))
+ y_upper.append(y)
+ y_lower.append(y*(-1)) # is just for pick the y axis
+ # negative numbers
+ y = {'u': y_upper, 'l':y_lower}
+ return y
+
+if __name__ == '__main__':
+ import matplotlib.pyplot as plt
+ import math
+
+ from airfoil_module import create_x
+
+ c = 1. #c is the chord length
+ t = 0.12 # is the maximum thickness as a fraction of the chord
+ #(t*100 = the last two nunbers of the NACA denomination)
+
+ number_of_points = 200
+
+ p = 0.5 #this variabel is here to force the points fall inside the model.
+
+ x_list = create_x(c, n = number_of_points, distribution = 'polar') # This function receives
+ # inicial point,finalpoint,
+ #number of therms between
+ # inicial and final point
+ y = Naca_00XX(c,t,x_list)
+
+
+ fig = plt.figure()
+
+ fig.add_subplot(111)
+ plt.scatter(x_list,y['u'])
+ plt.scatter(x_list,y['l'])
+
+
+ plt.grid()
+ plt.xlabel('x values')
+ plt.ylabel('y values')
\ No newline at end of file
diff --git a/pool/shard002/Python/0026340_forecast.py b/pool/shard002/Python/0026340_forecast.py
new file mode 100644
index 0000000000000000000000000000000000000000..35926d499f10cbf0c2b9daf1f28c99699caa901f
--- /dev/null
+++ b/pool/shard002/Python/0026340_forecast.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python
+
+import sys, urllib, urllib2, re, logging, json, uuid, ast, datetime, os, requests, time, collections
+from redten.shellprinting import lg, good, boom, mark, anmt, info
+from redten.redten_client import RedTenClient, ppj
+
+"""
+More documentation and samples:
+
+- Forecast: https://github.com/jay-johnson/sci-pype/blob/master/red10/Red10-SPY-Multi-Model-Price-Forecast.ipynb
+- Predictions with the IRIS dataset: https://github.com/jay-johnson/sci-pype/blob/master/red10/Red10-IRIS-Predictions.ipynb
+
+"""
+
+# Login to red10
+rt = RedTenClient()
+
+csv_file = ""
+rloc = ""
+sloc = ""
+
+ds_name = "SPY"
+if len(sys.argv) > 1:
+ ds_name = str(sys.argv[1]).upper()
+
+# What column do you want to predict values?
+target_column_name = "FClose"
+
+# possible values in the Target Column
+target_column_values = [ "GoodBuys", "BadBuys", "Not Finished" ]
+
+# What columns can the algorithms use for training and learning?
+feature_column_names = [ "FHigh", "FLow", "FOpen", "FClose", "FVolume" ]
+
+ignore_features = [ # Prune non-int/float columns as needed:
+ "Ticker",
+ "Date",
+ "FDate",
+ "FPrice",
+ "DcsnDate",
+ "Decision"
+ ]
+
+train_xgb = {
+ "learning_rate" : 0.20,
+ "num_estimators" : 50,
+ "sub_sample" : 0.20,
+ "col_sample_by_tree" : 0.90,
+ "col_sample_by_level" : 1.0,
+ "objective" : "reg:linear",
+ "max_depth" : 3,
+ "max_delta_step" : 0,
+ "min_child_weight" : 1,
+ "reg_alpha" : 0,
+ "reg_lambda" : 1,
+ "base_score" : 0.6,
+ "gamma" : 0,
+ "seed" : 42,
+ "silent" : True
+ }
+
+predict_row = {
+ "FHigh" : 5.4,
+ "FLow" : 3.4,
+ "FOpen" : 1.7,
+ "FClose" : 0.2,
+ "FVolume" : 0
+ }
+
+units_ahead_set = [ 5, 10, 15, 20, 25, 30 ]
+units_ahead_type = "Days"
+
+algo_name = "xgb-regressor"
+title = str(ds_name) + " Forecast v5 - " + str(rt.uni_key())
+desc = "Forecast simulation"
+label_column_name = target_column_name
+test_ratio = 0.1
+sample_filter_rules = {}
+
+# list of emails to send the analysis to on successful completion
+send_to_email = []
+
+# Allow a list of comma separated emails to be passed in
+# example: email1@email.com,email2@email.com
+# note no spaces between them
+if str(os.getenv("ENV_REDTEN_FORECAST_EMAILS", "")).strip().lstrip() != "":
+ send_to_email = str(os.getenv("ENV_REDTEN_FORECAST_EMAILS", "")).strip().lstrip().split(",")
+
+# allow the target dataset to load from the env for automation with docker
+if csv_file == "" and sloc == "" and rloc == "":
+ csv_file = str(os.getenv("ENV_REDTEN_CSV_FILE", "")).strip().lstrip()
+
+post_data = {
+ "predict_this_data" : predict_row,
+ "title" : title,
+ "desc" : desc,
+ "ds_name" : ds_name,
+ "feature_column_names" : feature_column_names,
+ "ignore_features" : ignore_features,
+ "csv_file" : csv_file,
+ "rloc" : rloc,
+ "sloc" : sloc,
+ "algo_name" : algo_name,
+ "test_ratio" : test_ratio,
+ "target_column_values" : target_column_values,
+ "target_column_name" : target_column_name,
+ "label_column_name" : label_column_name,
+ "user_id" : rt.get_uid(),
+ "train" : train_xgb,
+ "max_features" : 10,
+ "tracking_type" : "",
+ "units_ahead_set" : units_ahead_set,
+ "units_ahead_type" : units_ahead_type,
+ "prediction_type" : "Forecast",
+ "ml_type" : "Playbook-UnitsAhead",
+ "forecast_type" : "ETFPriceForecasting",
+ "forecast_version" : 5,
+ "valid_forecast_threshold" : 0.3,
+ "sample_filters" : sample_filter_rules,
+ "predict_units_back" : 90,
+ "bypass_trading_day" : 1,
+ "send_to_email" : send_to_email,
+ "version" : 1
+ }
+
+
+"""
+
+Wait on the job to finish
+
+"""
+
+anmt("Launching Job")
+
+job_data = {}
+job_report = {}
+job_res = {}
+job_response = rt.run_job(post_data=post_data)
+
+if job_response["status"] != "valid":
+ boom("Forecast job failed with error=" + str(job_response["status"]))
+ sys.exit(1)
+else:
+ if "id" not in job_response["data"]:
+ boom("Failed to create new forecast job")
+ sys.exit(1)
+ else:
+ job_id = job_response["data"]["id"]
+ job_status = job_response["data"]["status"]
+ lg("Started Forecast job=" + str(job_id) + " with current status=" + str(job_status))
+# end of if job was valid or not
+
+lg("Started Forecast=" + str(ds_name) + " job=" + str(job_id), 6)
+
+
+"""
+
+Wait on the job to finish
+
+"""
+
+
+if job_id == None:
+ boom("Failed to start a new job")
+else:
+ lg("Waiting on results", 6)
+ job_res = rt.wait_on_job(job_id)
+
+ if job_res["status"] != "SUCCESS":
+ boom("Job=" + str(job_id) + " failed with status=" + str(job_res["status"]) + " err=" + str(job_res["error"]))
+ else:
+ job_data = job_res["record"]
+ anmt("Job Report:")
+ lg(ppj(job_data), 5)
+# end of waiting
+
+
+"""
+
+Get Job Analysis
+
+"""
+
+
+job_report = {}
+if job_id == None:
+ boom("Failed to start a new job")
+else:
+ # Get the analysis, but do not auto-show the plots
+ job_report = rt.get_job_analysis(job_id, show_plots=False)
+ if len(job_report) == 0:
+ boom("Job=" + str(job_id) + " failed")
+ sys.exit(1)
+ else:
+ lg("")
+ # if the job failed
+# end of get job analysis
+
+
+"""
+
+Build Forecast Results
+
+"""
+
+lg("Building Forecast=" + str(ds_name) + " Results for job=" + str(job_id), 6)
+
+# Build the forecast accuracy dictionary from the analysis
+# and show the forecast dataframes
+acc_results = rt.build_forecast_results(job_report)
+for col in acc_results:
+ col_node = acc_results[col]
+
+ predictions_df = col_node["predictions_df"]
+ date_predictions_df = col_node["date_predictions_df"]
+ train_predictions_df = col_node["train_predictions_df"]
+
+ lg("--------------------------------------------------")
+ # for all columns in the accuracy dictionary:
+ lg("Column=" + str(col) + " accuracy=" + str(col_node["accuracy"]) + " mse=" + str(col_node["mse"]) + " num_predictions=" + str(len(col_node["date_predictions_df"].index)))
+ # end of header line
+
+ # show the timeseries forecast
+ lg(date_predictions_df.head(5), 6)
+
+ lg("")
+# end of showing prediction results
+
+
+
+"""
+
+Get Analysis Images
+
+"""
+
+lg("Getting Forecast=" + str(ds_name) + " Analysis Images for job=" + str(job_id), 6)
+
+# unless matplotlib is installed this will fail showing plots:
+job_res = rt.get_job_analysis(job_id, show_plots=False)
+
+sys.exit(0)
diff --git a/pool/shard002/Python/0026343_0001_initial.py b/pool/shard002/Python/0026343_0001_initial.py
new file mode 100644
index 0000000000000000000000000000000000000000..2edf56d94c243260e4c8f3e4ced3006da061509f
--- /dev/null
+++ b/pool/shard002/Python/0026343_0001_initial.py
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+from django.conf import settings
+import oioioi.base.fields
+import oioioi.participants.fields
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('contests', '0001_initial'),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Participant',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('status', oioioi.base.fields.EnumField(default=b'ACTIVE', max_length=64, choices=[(b'ACTIVE', 'Active'), (b'BANNED', 'Banned')])),
+ ('anonymous', models.BooleanField(default=False)),
+ ('contest', models.ForeignKey(to='contests.Contest')),
+ ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
+ ],
+ options={
+ },
+ bases=(models.Model,),
+ ),
+ migrations.CreateModel(
+ name='TestRegistration',
+ fields=[
+ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+ ('name', models.CharField(max_length=255)),
+ ('participant', oioioi.participants.fields.OneToOneBothHandsCascadingParticipantField(related_name='participants_testregistration', to='participants.Participant')),
+ ],
+ options={
+ 'abstract': False,
+ },
+ bases=(models.Model,),
+ ),
+ migrations.AlterUniqueTogether(
+ name='participant',
+ unique_together=set([('contest', 'user')]),
+ ),
+ ]
diff --git a/pool/shard002/Python/0026345_image_services.py b/pool/shard002/Python/0026345_image_services.py
new file mode 100644
index 0000000000000000000000000000000000000000..59b4ec015e3146c9fb0398f08db09e3c7810de92
--- /dev/null
+++ b/pool/shard002/Python/0026345_image_services.py
@@ -0,0 +1,85 @@
+# coding: utf-8
+#
+# Copyright 2016 The Oppia 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.
+
+"""Provides app identity services."""
+
+from __future__ import annotations
+
+import io
+
+from PIL import Image
+from typing import Tuple
+
+
+def _get_pil_image_dimensions(pil_image: Image) -> Tuple[int, int]:
+ """Gets the dimensions of the Pillow Image.
+
+ Args:
+ pil_image: Image. A file in the Pillow Image format.
+
+ Returns:
+ tuple(int, int). Returns height and width of the image.
+ """
+ width, height = pil_image.size
+ return height, width
+
+
+def get_image_dimensions(file_content: bytes) -> Tuple[int, int]:
+ """Gets the dimensions of the image with the given file_content.
+
+ Args:
+ file_content: str. The content of the file.
+
+ Returns:
+ tuple(int). Returns height and width of the image.
+ """
+ image = Image.open(io.BytesIO(file_content))
+ return _get_pil_image_dimensions(image)
+
+
+def compress_image(image_content: bytes, scaling_factor: float) -> bytes:
+ """Compresses the image by resizing the image with the scaling factor.
+
+ Args:
+ image_content: str. Content of the file to be compressed.
+ scaling_factor: float. The number by which the dimensions of the image
+ will be scaled. This is expected to be in the interval (0, 1].
+
+ Returns:
+ str. Returns the content of the compressed image.
+
+ Raises:
+ ValueError. Scaling factor is not in the interval (0, 1].
+ """
+ if scaling_factor > 1 or scaling_factor <= 0:
+ raise ValueError(
+ 'Scaling factor should be in the interval (0, 1], received %f.'
+ % scaling_factor)
+ image = Image.open(io.BytesIO(image_content))
+
+ image_format = image.format
+ height, width = _get_pil_image_dimensions(image)
+ new_width = int(width * scaling_factor)
+ new_height = int(height * scaling_factor)
+ new_image_dimensions = (new_width, new_height)
+
+ # NOTE: image.thumbnail() function does not work when the scale factor
+ # is greater than 1.
+ image.thumbnail(new_image_dimensions, Image.ANTIALIAS)
+ with io.BytesIO() as output:
+ image.save(output, format=image_format)
+ new_image_content = output.getvalue()
+ return new_image_content
diff --git a/pool/shard002/Python/0026347_domainvalidate.py b/pool/shard002/Python/0026347_domainvalidate.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b1fe4a547a4ce1917373859515fd85ac240fc6c
--- /dev/null
+++ b/pool/shard002/Python/0026347_domainvalidate.py
@@ -0,0 +1,24 @@
+"""EasyEngine domain validation module."""
+from urllib.parse import urlparse
+
+
+def ValidateDomain(url):
+ """
+ This function returns domain name removing http:// and https://
+ returns domain name only with or without www as user provided.
+ """
+
+ # Check if http:// or https:// present remove it if present
+ domain_name = url.split('/')
+ if 'http:' in domain_name or 'https:' in domain_name:
+ domain_name = domain_name[2]
+ else:
+ domain_name = domain_name[0]
+ www_domain_name = domain_name.split('.')
+ final_domain = ''
+ if www_domain_name[0] == 'www':
+ final_domain = '.'.join(www_domain_name[1:])
+ else:
+ final_domain = domain_name
+
+ return (final_domain, domain_name)
diff --git a/pool/shard002/Python/0026348_hashing.py b/pool/shard002/Python/0026348_hashing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab844151a42e4a807145ef61511d4a7d8414f13d
--- /dev/null
+++ b/pool/shard002/Python/0026348_hashing.py
@@ -0,0 +1,17 @@
+import hashlib
+import random
+
+
+NUMBER_OF_ITERATIONS = 100001
+
+
+def get_salt(user: bytes):
+ random.seed(user)
+ h = hashlib.sha256()
+ h.update(user)
+ return h.digest() + bytes(str(random.uniform(-1024.0, 1023.0)), encoding='utf8')
+
+
+def hash_password(password: bytes, user: bytes):
+ salt = get_salt(user)
+ return hashlib.pbkdf2_hmac('sha256', password, salt, NUMBER_OF_ITERATIONS)
diff --git a/pool/shard002/Python/0026355_plot_solutions.py b/pool/shard002/Python/0026355_plot_solutions.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f3608d0658aeca3c0a1d1e0ef86543620acf3ae
--- /dev/null
+++ b/pool/shard002/Python/0026355_plot_solutions.py
@@ -0,0 +1,27 @@
+from matplotlib import pyplot as plt
+import numpy as np
+
+
+def plot_line_expansion(edisgo_obj, timesteps):
+
+ pypsa_plot = edisgo_obj.to_pypsa(mode="mv", timesteps=timesteps)
+ bus_index = pypsa_plot.buses.index
+ pypsa_plot.buses.x.loc[
+ bus_index
+ ] = edisgo_obj.topology.mv_grid.buses_df.x.loc[bus_index]
+ pypsa_plot.buses.y.loc[
+ bus_index
+ ] = edisgo_obj.topology.mv_grid.buses_df.y.loc[bus_index]
+ line_colors = edisgo_obj.opf_results.lines.squeeze()
+ fig = plt.figure(figsize=(12, 8))
+ ax = plt.gca()
+ v = np.linspace(min(line_colors), max(line_colors), 101)
+ psa_plot = pypsa_plot.plot(
+ line_colors=line_colors, line_cmap=plt.cm.cool, ax=ax, geomap=False
+ )
+ cb = plt.colorbar(psa_plot[1])
+ cb.set_clim(vmin=v[0], vmax=v[-1])
+ cb.set_label("Number of installed lines")
+ plt.show()
+
+ return fig, ax
diff --git a/pool/shard002/Python/0026359_exceptions.py b/pool/shard002/Python/0026359_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb699f6ddddb08556b707367a3a4e10a01772daf
--- /dev/null
+++ b/pool/shard002/Python/0026359_exceptions.py
@@ -0,0 +1,98 @@
+import traceback
+
+from django.conf import settings
+from django.core.exceptions import PermissionDenied
+from django.core.signals import got_request_exception
+from django.http import Http404
+from django.utils.translation import gettext_lazy as _
+
+from rest_framework import exceptions
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.views import set_rollback
+
+
+class UnavailableForLegalReasons(exceptions.APIException):
+ status_code = status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
+ default_detail = _('Unavailable for legal reasons.')
+ default_code = 'unavailable_for_legal_reasons'
+
+
+def custom_exception_handler(exc, context=None):
+ """
+ Custom exception handler for DRF, which ensures every exception we throw
+ is caught, returned as a nice DRF Response, while still going to sentry
+ etc.
+
+ This is mostly copied from DRF exception handler, with the following
+ changes/additions:
+ - A condition preventing set_rollback() from being called in some cases
+ where we know there might be something to record in the database
+ - Handling of non-API exceptions, returning an 500 error that looks like an
+ API response, while still logging things to Sentry.
+ """
+ # If propagate is true, bail early.
+ if settings.DEBUG_PROPAGATE_EXCEPTIONS:
+ raise
+
+ if isinstance(exc, Http404):
+ exc = exceptions.NotFound()
+ elif isinstance(exc, PermissionDenied):
+ exc = exceptions.PermissionDenied()
+
+ if isinstance(exc, exceptions.APIException):
+ headers = {}
+ if getattr(exc, 'auth_header', None):
+ headers['WWW-Authenticate'] = exc.auth_header
+ if getattr(exc, 'wait', None):
+ headers['Retry-After'] = '%d' % exc.wait
+
+ if isinstance(exc.detail, (list, dict)):
+ data = exc.detail
+ code_or_codes = exc.get_codes()
+ else:
+ data = {'detail': exc.detail}
+ code_or_codes = exc.get_codes()
+
+ # If it's not a throttled/permission denied coming from a restriction,
+ # we can roll the current transaction back. Otherwise don't, we may
+ # need to record something in the database.
+ # Note: `code_or_codes` can be a string, or a list of strings, or even
+ # a dict of strings here, depending on what happened. Fortunately the
+ # only thing we care about is the most basic case, a string, we don't
+ # need to test for the rest.
+ if not isinstance(exc, exceptions.Throttled) and not (
+ isinstance(exc, exceptions.PermissionDenied)
+ and code_or_codes == 'permission_denied_restriction'
+ ):
+ set_rollback()
+ if isinstance(exc, UnavailableForLegalReasons):
+ url = 'https://www.mozilla.org/about/policy/transparency/'
+ headers['Link'] = f'<{url}>; rel="blocked-by"'
+ return Response(data, status=exc.status_code, headers=headers)
+ else:
+ # Not a DRF exception, we want to return an APIfied 500 error while
+ # still logging it to Sentry.
+ data = base_500_data()
+
+ # Send the got_request_exception signal so other apps like sentry
+ # are aware of the exception. The sender does not match what a real
+ # exception would do (we don't have access to the handler here) but it
+ # should not be an issue, what matters is the request.
+ request = context.get('request')
+ sender = context.get('view').__class__
+ got_request_exception.send(sender, request=request)
+
+ # Send the 500 response back.
+ response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+ return response
+
+
+def base_500_data():
+ # Start with a generic default error message.
+ data = {'detail': 'Internal Server Error'}
+
+ if settings.DEBUG:
+ data['traceback'] = traceback.format_exc()
+ return data
diff --git a/pool/shard002/Python/0026360_GenerateDataset.py b/pool/shard002/Python/0026360_GenerateDataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3f6b1a586cd6cee54dc0c1e610c86de4f37c72d
--- /dev/null
+++ b/pool/shard002/Python/0026360_GenerateDataset.py
@@ -0,0 +1,90 @@
+"""
+Simulate how Droplets will perform with Young's Model on Grid Graphs with different density
+
+Author: Yang Li
+Date: July 14, 2017
+
+# randomly generate N droplets with diameter = 4.5cm within a square
+ of length 60cm
+
+
+"""
+
+from PatternFormation import *
+
+# 'factor' value kind of means how much strength to push each activator againt each other
+def GenerateDataset(pattern_def, path_to, dens):
+
+ (patternType, activatorHeight, activatorWidth, inhibitorHeight, inhibitorWidth, factor) = pattern_def
+
+ lims = [27, 27]
+ step_size = 1.0/np.sqrt(dens)
+ xCoordinates = []
+ yCoordinates = []
+
+ ''' randomly generate a set of coordination, and make sure there are no duplicated ones
+ '''
+ for x in np.arange(0, lims[0]+1, step_size):
+ for y in np.arange(0, lims[1]+1, step_size):
+ xCoordinates.append(x)
+ yCoordinates.append(y)
+ print ("--> Coordination ready to go!")
+
+ num = len(xCoordinates)
+ ag = PatternFormation(num, activatorHeight, activatorWidth, inhibitorHeight, inhibitorWidth, patternType, factor)
+ ag.initDroplets(xCoordinates, yCoordinates)
+ ag.initCircles()
+ print ("--> Graph ready to go!")
+
+ imageSet = None
+ typeSet = None
+ for fi in np.arange(5, 10, 0.1):
+ for _ in range(100):
+ ag.resetDropletColors()
+ ag.factor = (float)('%.2f' % (-0.1*fi))
+ counter = 0
+ while ag.oneLoop() > 0:
+ counter += 1
+
+ # ag.drawPattern_Grid_BW('dens{}'.format(dens), lims, path_to)
+ print ("--> Done with drawing with factor", ag.factor)
+ # ag.saveData('dens{}'.format(dens), lims, path_to)
+ image, ptype = ag.getData()
+ if imageSet == None:
+ imageSet = image
+ typeSet = ptype
+ else:
+ imageSet = np.concatenate((imageSet, image), axis=0)
+ typeSet = np.concatenate((typeSet, ptype), axis=0)
+
+ print typeSet.shape
+ print imageSet.shape
+
+ data = {
+ 'image': imageSet,
+ 'type': typeSet }
+
+ filename = "{}/Type-{}-[{},{},{},{}].pkl".format(path_to, patternType, activatorHeight,activatorWidth,inhibitorHeight,inhibitorWidth)
+
+ pickle_file = open(filename, 'wb')
+ pickle.dump(data, pickle_file)
+ pickle_file.close()
+
+
+if __name__ == "__main__":
+ # path_to = "D:/Github/Data/turing_pattern/Aug8_gridGraph_square"
+ path_to = "/Users/Yang/Documents/Data/PatternFormation/Feb6_dataset"
+
+ # pattern_def_0 = (0, 2, 5, 6, 5, None)
+ pattern_def_1 = (0, 4, 10, 12, 10, None)
+ # pattern_def_1 = (1, 5, 2, 5, 6, -0.50)
+ pattern_def_2 = (2, 6, 6, 10, 10, None)
+
+ pattern_def_set = [pattern_def_1, pattern_def_2]
+ for pd in pattern_def_set:
+ for i in range(1, 2):
+ dens = i
+ print ("\n Start! -- [Pattern]:", pd, "[dens]:", dens)
+ t0 = time.time()
+ GenerateDataset(pd, path_to, dens)
+ print ("\n Done! -- [Pattern]:", pd, "[dens]:", dens, "[Time used]:", time.time()-t0)
diff --git a/pool/shard002/Python/0026371_settings.py b/pool/shard002/Python/0026371_settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..54b69816486a67d18b2ba12212f980d07f47771f
--- /dev/null
+++ b/pool/shard002/Python/0026371_settings.py
@@ -0,0 +1,21 @@
+import yaml
+
+from dataclasses import dataclass
+
+@dataclass
+class AppConfig:
+ environment: str = "development"
+ dbtype: str = ""
+ dbname: str = ""
+
+def get_settings() -> AppConfig:
+ """Get application settings from configuration file"""
+
+ with open('config/settings.yaml', 'r') as yml:
+ config = yaml.load(yml, Loader=yaml.FullLoader)['app']
+
+ return AppConfig(
+ environment=config['environment'],
+ dbtype=config['dbtype'],
+ dbname=config['dbname'],
+ )
diff --git a/pool/shard002/Python/0026377_utils.py b/pool/shard002/Python/0026377_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e89541b608d5766046197d104144f51f7813a5c
--- /dev/null
+++ b/pool/shard002/Python/0026377_utils.py
@@ -0,0 +1,105 @@
+import re
+import socket
+
+import tldextract
+
+from domains.models import IP, TLD, Domain, Subdomain
+from spyder.models import DiscoveryRelationship
+
+
+def extract_subdomain(url):
+ """
+ Receives a url and returns an object created by tldextract.
+ If there is no proper tldextract subdomain object, returns None.
+ If there is an IP, saves it.
+ :param url:
+ :return:
+ """
+ extract_result = tldextract.extract(url.lower())
+ # make sure we have a valid domain and TLD
+ if extract_result.domain and extract_result.suffix:
+ return extract_result
+ else:
+ # try to extract ip from url
+ if extract_result.domain:
+ ip_list = re.findall(r'[0-9]+(?:\.[0-9]+){3}', extract_result.domain)
+ if ip_list:
+ for ip in ip_list:
+ new_ip = IP.objects.get_or_create(ip=ip)
+ # return nothing
+ return None
+
+
+def import_subdomain(url, discovered_by=None):
+ """
+ Receives a url and saves the TLD/domain/subdomain.
+ If the subdomain isn't empty, also tries to save with an empty subdomain.
+ :param url:
+ :param discovered_by: the subdomain that pointed to the url
+ :return:
+ """
+
+ extract_result = extract_subdomain(url.lower())
+ if extract_result:
+ new_tld = TLD.objects.get_or_create(tld=extract_result.suffix)
+ new_domain = Domain.objects.get_or_create(tld=new_tld[0],
+ domain=extract_result.domain)
+ new_subdomain = Subdomain.objects.get_or_create(domain=new_domain[0],
+ subdomain=extract_result.subdomain)
+
+ # also create with empty subdomain
+ new_empty_subdomain = Subdomain.objects.get_or_create(domain=new_domain[0],
+ subdomain="")
+
+ if discovered_by:
+ new_discovery_relationship = DiscoveryRelationship.objects.get_or_create(
+ origin_subdomain=discovered_by,
+ destination_subdomain=new_subdomain[0])
+ new_discovery_relationship = DiscoveryRelationship.objects.get_or_create(
+ origin_subdomain=discovered_by,
+ destination_subdomain=new_empty_subdomain[0])
+
+ return new_subdomain[0]
+ else:
+ return None
+
+
+def get_ip(domain):
+ """
+ Returns the first IP address string that responds as the given domain name.
+ """
+ try:
+ return socket.gethostbyname(domain)
+ except Exception:
+ return False
+
+
+def get_ip_ex(domain):
+ """
+ Returns an array containing one or more IP address strings that respond as the
+ given domain name.
+ """
+ try:
+ return socket.gethostbyname_ex(domain)[2]
+ except Exception:
+ return False
+
+
+def get_host(ip):
+ """
+ Returns the 'True Host' name for a given IP address.
+ """
+ try:
+ return socket.gethostbyaddr(ip)[0]
+ except Exception:
+ return False
+
+
+def get_alias(domain):
+ """
+ Returns an array containing a list of aliases for the given domain.
+ """
+ try:
+ return socket.gethostbyname_ex(domain)[1]
+ except Exception:
+ return False
diff --git a/pool/shard002/Python/0026380_complete_tutorial.py b/pool/shard002/Python/0026380_complete_tutorial.py
new file mode 100644
index 0000000000000000000000000000000000000000..2543224ecdad3725ff4289741289a43253d4a430
--- /dev/null
+++ b/pool/shard002/Python/0026380_complete_tutorial.py
@@ -0,0 +1,181 @@
+import random
+
+from pokemongo_bot import logger
+from pokemongo_bot.base_task import BaseTask
+from pokemongo_bot.worker_result import WorkerResult
+from pokemongo_bot.human_behaviour import sleep
+
+
+
+class CompleteTutorial(BaseTask):
+
+ SUPPORTED_TASK_API_VERSION = 1
+
+ def initialize(self):
+ self.api = self.bot.api
+ self.nickname = self.config.get('nickname','')
+ self.team = self.config.get('team',0)
+ self.may_run = True
+
+ def should_run(self):
+ return self.may_run
+
+ def work(self):
+
+ if not self.should_run():
+ return WorkerResult.SUCCESS
+
+ # Only execute the worker once to avoid error loop
+ self.may_run = False
+
+ if self._check_tutorial_state():
+ return WorkerResult.SUCCESS
+ else:
+ return WorkerResult.ERROR
+
+ def _check_tutorial_state(self):
+ self._player=self.bot.player_data
+
+ tutorial_state = self._player.get('tutorial_state', [])
+ # LEGAL_SCREEN = 0
+ if not 0 in tutorial_state:
+ sleep(2)
+ if self._set_tutorial_state(0):
+ self.logger.info('Completed legal screen')
+ tutorial_state = self._player.get('tutorial_state', [])
+ else:
+ return False
+
+ # AVATAR_SELECTION = 1
+ if not 1 in tutorial_state:
+ sleep(7)
+ if self._set_avatar():
+ if self._set_tutorial_state(1):
+ self.logger.info('Completed avatar selection')
+ tutorial_state = self._player.get('tutorial_state', [])
+ else:
+ return False
+ else:
+ self.logger.error('Error during avatar selection')
+ return False
+
+ # POKEMON_CAPTURE = 3
+ if not 3 in tutorial_state:
+ sleep(10)
+ if self._encounter_tutorial():
+ self.logger.info('Completed first capture')
+ else:
+ self.logger.error('Error during first capture')
+ return False
+
+ # NAME_SELECTION = 4
+ if not 4 in tutorial_state:
+ if not self.nickname:
+ self.logger.info("No nickname defined in config")
+ return False
+
+ self.logger.info(u'Trying to set {} as nickname'.format(self.nickname))
+ sleep(5)
+ if self._set_nickname(self.nickname):
+ self._set_tutorial_state(4)
+ tutorial_state = self._player.get('tutorial_state', [])
+ else:
+ self.logger.error('Error trying to set nickname')
+ return False
+
+ # FIRST_TIME_EXPERIENCE_COMPLETE = 7
+ if not 7 in tutorial_state:
+ if self._set_tutorial_state(7):
+ self.logger.info('Completed first time experience')
+ else:
+ return False
+
+ return True
+
+ def _encounter_tutorial(self):
+ # You just need to call the API with the pokemon you choose
+ # Probably can't get MewTwo as first pokemon though
+ first_pokemon_id = random.choice([1, 4, 7])
+ response_dict = self.api.encounter_tutorial_complete(
+ pokemon_id=first_pokemon_id)
+ try:
+ if response_dict['responses']['ENCOUNTER_TUTORIAL_COMPLETE']['result'] == 1:
+ return True
+ else:
+ self.logger.error("Error during encouter tutorial")
+ return False
+ except KeyError:
+ self.logger.error("KeyError during encouter tutorial")
+ return False
+
+ def _random_avatar(self):
+ avatar= {}
+ # 0 = Male, 1 = Female
+ avatar['gender']=random.randint(0,1)
+ # What is the max value of each parameter ?
+ # Default is 0, anyway human player will stop
+ # at the first choices in general, so fully
+ # random on the whole avatar space is not the way to go either
+ avatar['skin']=random.randint(0,3)
+ avatar['hair']=random.randint(0,3)
+ avatar['shirt']=random.randint(0,3)
+ avatar['pants']=random.randint(0,3)
+ avatar['hat']=random.randint(0,3)
+ avatar['shoes']=random.randint(0,3)
+ avatar['eyes']=random.randint(0,3)
+ avatar['backpack']=random.randint(0,3)
+ return avatar
+
+ def _set_avatar(self):
+ avatar = self._random_avatar()
+ response_dict = self.api.set_avatar(player_avatar=avatar)
+ status = response_dict['responses']['SET_AVATAR']['status']
+ try:
+ if status == 1:
+ return True
+ else:
+ error_codes = {
+ 0: 'UNSET',
+ 1: 'SUCCESS',
+ 2: 'AVATAR_ALREADY_SET',
+ 3: 'FAILURE',
+ }
+ self.logger.error("Error during avatar selection : {}".format(error_codes[status]))
+ return False
+ except KeyError:
+ self.logger.error("KeyError during avatar selection")
+ return False
+
+ def _set_nickname(self, nickname):
+ response_dict = self.api.claim_codename(codename=nickname)
+ try:
+ result = response_dict['responses']['CLAIM_CODENAME']['status']
+ if result == 1:
+ self.logger.info(u'Name changed to {}'.format(nickname))
+ return True
+ else:
+ # Would be nice to get the text directly from the proto Enum
+ error_codes = {
+ 0: 'UNSET',
+ 1: 'SUCCESS',
+ 2: 'CODENAME_NOT_AVAILABLE',
+ 3: 'CODENAME_NOT_VALID',
+ 4: 'CURRENT_OWNER',
+ 5: 'CODENAME_CHANGE_NOT_ALLOWED'
+ }
+ self.logger.error(
+ u'Error while changing nickname : {}'.format(error_codes[result]))
+ return False
+ except KeyError:
+ return False
+
+ def _set_tutorial_state(self, completed):
+ response_dict = self.api.mark_tutorial_complete(tutorials_completed=[
+ completed], send_marketing_emails=False, send_push_notifications=False)
+ try:
+ self._player = response_dict['responses'][
+ 'MARK_TUTORIAL_COMPLETE']['player_data']
+ return response_dict['responses']['MARK_TUTORIAL_COMPLETE']['success']
+ except KeyError:
+ self.logger.error("KeyError while setting tutorial state")
+ return False
diff --git a/pool/shard002/Python/0026388_reqpart.py b/pool/shard002/Python/0026388_reqpart.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd4c54e2003f636f3769ce30e40842bcd3a582c4
--- /dev/null
+++ b/pool/shard002/Python/0026388_reqpart.py
@@ -0,0 +1,69 @@
+#
+# Chris Lumens
+#
+# Copyright 2015 Red Hat, Inc.
+#
+# This copyrighted material is made available to anyone wishing to use, modify,
+# copy, or redistribute it subject to the terms and conditions of the GNU
+# General Public License v.2. This program is distributed in the hope that it
+# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
+# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+# See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 51
+# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
+# trademarks that are incorporated in the source code or documentation are not
+# subject to the GNU General Public License and may only be used or replicated
+# with the express permission of Red Hat, Inc.
+#
+from pykickstart.base import KickstartCommand
+from pykickstart.errors import KickstartParseError, formatErrorMsg
+from pykickstart.options import KSOptionParser
+
+import gettext
+_ = lambda x: gettext.ldgettext("pykickstart", x)
+
+class F23_ReqPart(KickstartCommand):
+ removedKeywords = KickstartCommand.removedKeywords
+ removedAttrs = KickstartCommand.removedAttrs
+
+ def __init__(self, writePriority=100, *args, **kwargs):
+ KickstartCommand.__init__(self, writePriority, *args, **kwargs)
+ self.reqpart = kwargs.get("reqpart", False)
+ self.addBoot = kwargs.get("addBoot", False)
+
+ self.op = self._getParser()
+
+ def _getArgsAsStr(self):
+ retval = ""
+
+ if self.addBoot:
+ retval += " --add-boot"
+
+ return retval
+
+ def __str__(self):
+ retval = KickstartCommand.__str__(self)
+ if self.reqpart:
+ retval += "reqpart%s\n" % self._getArgsAsStr()
+ return retval
+
+ def _getParser(self):
+ op = KSOptionParser()
+ op.add_option("--add-boot", action="store_true", dest="addBoot", default=False)
+ return op
+
+ def parse(self, args):
+ # Using reqpart and autopart at the same time is not allowed.
+ if self.handler.autopart.seen:
+ errorMsg = _("The %s and reqpart commands can't be used at the same time") % \
+ "autopart"
+ raise KickstartParseError(formatErrorMsg(self.lineno, msg=errorMsg))
+
+ (opts, _extra) = self.op.parse_args(args=args, lineno=self.lineno)
+ self._setToSelf(self.op, opts)
+ self.reqpart = True
+ return self
+
+RHEL7_ReqPart = F23_ReqPart
diff --git a/pool/shard002/Python/0026393_rhev-keyring.py b/pool/shard002/Python/0026393_rhev-keyring.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e63a024d3526d6f75b6b8aa8fb9e885b0afd05f
--- /dev/null
+++ b/pool/shard002/Python/0026393_rhev-keyring.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+#
+# Author: Pablo Iranzo Gomez (Pablo.Iranzo@gmail.com)
+#
+# Description: Script for setting the keyring password for RHEV scripts
+#
+# Requires: python keyring
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, version 2 of the License.
+#
+# 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.
+
+import optparse
+
+from rhev_functions import *
+
+description = """
+RHEV-keyring is a script for mantaining the keyring used by rhev script for storing password
+
+"""
+
+# Option parsing
+p = optparse.OptionParser("rhev-clone.py [arguments]", description=description)
+p.add_option("-u", "--user", dest="username", help="Username to connect to RHEVM API", metavar="admin@internal",
+ default=False)
+p.add_option("-w", "--password", dest="password", help="Password to use with username", metavar="admin",
+ default=False)
+p.add_option("-W", action="store_true", dest="askpassword", help="Ask for password", metavar="admin", default=False)
+p.add_option('-q', "--query", action="store_true", dest="query", help="Query the values stored", default=False)
+
+(options, args) = p.parse_args()
+
+if options.askpassword:
+ options.password = getpass.getpass("Enter password: ")
+
+# keyring.set_password('redhat', 'kerberos', '')
+# remotepasseval = keyring.get_password('redhat', 'kerberos')
+
+if options.query:
+ print "Username: %s" % keyring.get_password('rhevm-utils', 'username')
+ print "Password: %s" % keyring.get_password('rhevm-utils', 'password')
+
+if options.username:
+ keyring.set_password('rhevm-utils', 'username', options.username)
+if options.password:
+ keyring.set_password('rhevm-utils', 'password', options.password)
diff --git a/pool/shard002/Python/0026412_to3008.py b/pool/shard002/Python/0026412_to3008.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6f0463b0e39eca7cf9e1cb613bab2eb632f115f
--- /dev/null
+++ b/pool/shard002/Python/0026412_to3008.py
@@ -0,0 +1,49 @@
+from Acquisition import aq_inner
+from Acquisition import aq_parent
+from Products.CMFCore.utils import getToolByName
+from Products.Archetypes.config import REFERENCE_CATALOG
+
+def upgrade(tool):
+ """Added bika.lims.analysisservice.edit.js
+ """
+
+ portal = aq_parent(aq_inner(tool))
+ setup = portal.portal_setup
+
+ # update affected tools
+ setup.runImportStepFromProfile('profile-bika.lims:default', 'jsregistry')
+
+ # apply new method/calculation data to old Analysis Services
+ portal = aq_parent(aq_inner(tool))
+ pc = getToolByName(portal, 'portal_catalog')
+ bsc = getToolByName(portal, 'bika_setup_catalog')
+ rc=getToolByName(portal, REFERENCE_CATALOG)
+ proxies = pc(portal_type="AnalysisService")
+ for proxy in proxies:
+ an = proxy.getObject()
+ rels = an.at_references.objectValues()
+ oldmethod = None
+ oldinstrument = None
+ oldcalc = None
+ for rel in rels:
+ if rel.relationship == 'AnalysisServiceCalculation':
+ oldcalc=rc.lookupObject(rel.targetUID)
+ elif rel.relationship == 'AnalysisServiceInstrument':
+ oldinstrument=rc.lookupObject(rel.targetUID)
+ elif rel.relationship == 'AnalysisServiceMethod':
+ oldmethod=rc.lookupObject(rel.targetUID)
+ if oldmethod and oldcalc and oldinstrument:
+ break
+
+ # Reset the method, instrument and calculations
+ if oldmethod:
+ an.Schema().getField('Methods').set(an, [oldmethod.UID(),])
+ an.Schema().getField('_Method').set(an, oldmethod.UID())
+ if oldinstrument:
+ an.Schema().getField('Instruments').set(an, [oldinstrument.UID(),])
+ an.Schema().getField('Instrument').set(an, oldinstrument.UID())
+ if oldcalc:
+ an.setUseDefaultCalculation(False);
+ an.Schema().getField('DeferredCalculation').set(an, oldcalc.UID())
+
+ return True
diff --git a/pool/shard002/Python/0026415_init__.py b/pool/shard002/Python/0026415_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdcd7447c89c65c4dbd06025030fdd491c024f7d
--- /dev/null
+++ b/pool/shard002/Python/0026415_init__.py
@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+"""
+.. module: switching
+
+Aquesta llibreria proveeix de les classes i mètodes necessaris pel switching
+
+"""
+import os
+
+__version__ = '2.12.2'
+
+_ROOT = os.path.abspath(os.path.dirname(__file__))
+
+
+def get_data(path):
+ filename = isinstance(path, (list, tuple)) and path[0] or path
+ return os.path.join(_ROOT, 'data', filename)
diff --git a/pool/shard002/Python/0026416_user_subscriptions_dal.py b/pool/shard002/Python/0026416_user_subscriptions_dal.py
new file mode 100644
index 0000000000000000000000000000000000000000..53793269cbe2003e33995e71675e72978eb0d50f
--- /dev/null
+++ b/pool/shard002/Python/0026416_user_subscriptions_dal.py
@@ -0,0 +1,34 @@
+#! /usr/bin/env python3
+
+# __author__ = "Praneesh Kataru"
+# __credits__ = []
+# __version__ = "0.1.1"
+# __maintainer__ = "Praneesh Kataru"
+# __email__ = "pranuvitmsse05@gmail.com"
+# __status__ = "Prototype"
+
+import json
+from os import path
+
+
+class UserSubscriptionsDAL:
+ db_exception = None
+ user_subscriptions = None
+
+ def __init__(self):
+ self.user_subscription_db_file = path.join(path.dirname(path.abspath(__file__)), 'database/UserSubscriptions.json')
+ try:
+ with open(self.user_subscription_db_file, 'r') as json_data:
+ self.user_subscriptions = json.load(json_data)
+ except Exception as general_exception:
+ self.db_exception = general_exception
+
+ def get_subscription_url_by_user_id(self, user_id):
+ """ Returns the subscription URL for stock quotes """
+ if user_id in self.user_subscriptions:
+ ret_subscribe_url = self.user_subscriptions[user_id]
+ else:
+ ret_subscribe_url = self.user_subscriptions['restofworld']
+ return self.db_exception, ret_subscribe_url
+
+
diff --git a/pool/shard002/Python/0026417_mrf_size.py b/pool/shard002/Python/0026417_mrf_size.py
new file mode 100644
index 0000000000000000000000000000000000000000..4786d5539433e2087aac858d39f19bf2cb135ffe
--- /dev/null
+++ b/pool/shard002/Python/0026417_mrf_size.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+#
+# 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.
+#
+#-------------------------------------------------------------------------------
+# Name: MRF_size
+# Purpose: Visualize an MRF size index content
+#
+# Author: luci6974
+#
+# Created: 30/07/2015
+# Copyright: (c) luci6974 2015-2017
+#-------------------------------------------------------------------------------
+
+'''Builds a GDAL vrt that visualizes the size of tiles in an MRF index'''
+#
+# Only trivial MRFs for now, flat files, default index name. Should be extended
+# to support all MRFs
+#
+# It creates a gdal VRT file with a pixel per tile, where the pixel value
+# is the size of the respective tile
+# This is very useful to understand the state of an MRF
+# Since most tiles are compressed, the size of the tile tends to be proportional
+# to the entropy (information) of the data within the tile.
+#
+
+import xml.etree.ElementTree as XML
+import sys
+import os.path as path
+
+def usage():
+ print('Takes one argument, a MRF file name, ' + \
+ 'builds a .vrt that contains the tile size info')
+
+def XMLprettify(elem, level=0):
+ 'XML prettifier'
+ i = "\n" + level*" "
+ if len(elem):
+ if not elem.text or not elem.text.strip():
+ elem.text = i + " "
+ if not elem.tail or not elem.tail.strip():
+ elem.tail = i
+ for elem in elem:
+ XMLprettify(elem, level+1)
+ if not elem.tail or not elem.tail.strip():
+ elem.tail = i
+ else:
+ if level and (not elem.tail or not elem.tail.strip()):
+ elem.tail = i
+
+def attr(node, key, default):
+ return default if node is None or node.get(key) is None else node.get(key)
+
+class PointXYZC(object):
+ def __init__(self, node, defaults = (-1, -1, 1, 1)):
+ key = 'x','y','z','c'
+ self.x, self.y, self.z, self.c = (
+ int(attr(node, key[i], defaults[i])) for i in range(4))
+
+ def __str__(self):
+ f = "PointXYZC ({p.x}, {p.y}, {p.z}, {p.c})"
+ return f.format(p = self)
+
+class BBOX(object):
+ def __init__(self, node, defaults):
+ key = 'minx', 'miny', 'maxx', 'maxy'
+ self.minx, self.miny, self.maxx, self.maxy = (
+ float(attr(node, key[i], defaults[i])) for i in range(4))
+
+ def __str__(self):
+ f = "BBOX ({p.minx}, {p.miny}, {p.maxx}, {p.maxy})"
+ return f.format(p = self)
+
+class MRF(object):
+ 'MRF metadata reader'
+ def __init__(self, name):
+ try:
+ root = XML.parse(name).getroot()
+ except:
+ raise "Can't parse " + name
+
+ if root.tag != 'MRF_META':
+ raise name + ' is not an MRF metadata file'
+
+ self.name = name
+ #Get the basic raster info
+ self.size = PointXYZC(root.find('Raster/Size'))
+ self.pagesize = PointXYZC(root.find('Raster/PageSize'),
+ (512, 512, 1, self.size.c))
+ self.projection = root.find('GeoTags/Projection').text
+ self.bbox = BBOX(root.find('GeoTags/BoundingBox'),
+ (0, 0, self.size.x, self.size.y))
+
+ def geotransform(self):
+ 'gdal style affine geotransform as a list'
+ return [
+ self.bbox.minx, (self.bbox.maxx - self.bbox.minx)/self.size.x, 0,
+ self.bbox.maxy, 0, (self.bbox.miny - self.bbox.maxy)/self.size.y]
+
+def VRT_Size(mrf):
+ 'Builds and returns a gdal VRT XML tree'
+ xsz = int (1 + (mrf.size.x-1) / mrf.pagesize.x)
+ ysz = int (1 + (mrf.size.y-1) / mrf.pagesize.y)
+ root = XML.Element('VRTDataset', {
+ 'rasterXSize':str(xsz),
+ 'rasterYSize':str(ysz)
+ })
+ XML.SubElement(root,'SRS').text = mrf.projection
+ gt = mrf.geotransform()
+ # Adjust for pagesize
+ gt[1] *= mrf.pagesize.x
+ gt[5] *= mrf.pagesize.y
+ XML.SubElement(root,'GeoTransform').text = ",".join((str(x) for x in gt))
+ bands = int(mrf.size.c / mrf.pagesize.c)
+ for band in range(bands):
+ xband = XML.SubElement(root, 'VRTRasterBand', {
+ 'band':str(band+1),
+ 'dataType':'UInt32',
+ 'subClass':'VRTRawRasterBand'
+ })
+ idxname = path.splitext(path.basename(mrf.name))[0] + '.idx'
+ XML.SubElement(xband,'SourceFilename', { 'relativetoVRT':"1" }).text =\
+ idxname
+ XML.SubElement(xband,'ImageOffset').text = str(12 + 16 * band)
+ XML.SubElement(xband,'PixelOffset').text = str(16 * bands)
+ XML.SubElement(xband,'LineOffset').text = str(16 * xsz * bands)
+ XML.SubElement(xband,'NoDataValue').text = '0'
+ XML.SubElement(xband,'ByteOrder').text = 'MSB'
+
+ return XML.ElementTree(root)
+
+def main():
+ if (len(sys.argv) != 2):
+ usage()
+ return
+ name = sys.argv[1]
+ outname = path.splitext(name)[0] + '_size.vrt'
+ vrt = VRT_Size(MRF(name))
+ XMLprettify(vrt.getroot())
+ vrt.write(outname)
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard002/Python/0026420_nrk.py b/pool/shard002/Python/0026420_nrk.py
new file mode 100644
index 0000000000000000000000000000000000000000..ecff3a676c25a712fc3fdd9b87586d6b6ed5f9f2
--- /dev/null
+++ b/pool/shard002/Python/0026420_nrk.py
@@ -0,0 +1,96 @@
+import logging
+import re
+from urllib.parse import urljoin
+
+from streamlink.plugin import Plugin, pluginmatcher
+from streamlink.plugin.api import validate
+from streamlink.stream.hls import HLSStream
+from streamlink.stream.http import HTTPStream
+
+log = logging.getLogger(__name__)
+
+
+@pluginmatcher(re.compile(
+ r"https?://(?:tv|radio)\.nrk\.no/(program|direkte|serie|podkast)(?:/.+)?/([^/]+)"
+))
+class NRK(Plugin):
+ _psapi_url = 'https://psapi.nrk.no'
+ # Program type to manifest type mapping
+ _program_type_map = {
+ 'direkte': 'channel',
+ 'serie': 'program',
+ 'program': 'program',
+ 'podkast': 'podcast',
+ }
+
+ _program_id_re = re.compile(r' 0:
+ assert padding_idx < self.num_embeddings, 'Padding_idx must be within num_embeddings'
+ elif padding_idx < 0:
+ assert padding_idx >= -self.num_embeddings, 'Padding_idx must be within num_embeddings'
+ padding_idx = self.num_embeddings + padding_idx
+ self.padding_idx = padding_idx
+ self.max_norm = max_norm
+ self.norm_type = norm_type
+ self.scale_grad_by_freq = scale_grad_by_freq
+ if _weight is None:
+ self.weight = nn.Parameter(torch.Tensor(num_embeddings, embedding_dim))
+ self.reset_parameters()
+ else:
+ assert list(_weight.shape) == [num_embeddings, embedding_dim], \
+ 'Shape of weight does not match num_embeddings and embedding_dim'
+ self.weight = nn.Parameter(_weight)
+ self.sparse = sparse
+
+ # quantization parameters
+ self.p = p
+ self.bits = bits
+ self.method = method
+ self.update_step = update_step
+ self.counter = 0
+
+ def reset_parameters(self):
+ nn.init.normal_(self.weight)
+ if self.padding_idx is not None:
+ with torch.no_grad():
+ self.weight[self.padding_idx].fill_(0)
+
+ def forward(self, input):
+ # train with QuantNoise and evaluate the fully quantized network
+ p = self.p if self.training else 1
+
+ # update parameters every 1000 iterations
+ if self.counter % self.update_step == 0:
+ self.scale = None
+ self.zero_point = None
+ self.counter += 1
+
+ # quantize weight
+ weight_quantized, self.scale, self.zero_point = emulate_int(
+ self.weight.detach(),
+ bits=self.bits,
+ method=self.method,
+ scale=self.scale,
+ zero_point=self.zero_point,
+ )
+
+ # mask to apply noise
+ mask = torch.zeros_like(self.weight)
+ mask.bernoulli_(1 - p)
+ noise = (weight_quantized - self.weight).masked_fill(mask.bool(), 0)
+
+ # using straight-through estimator (STE)
+ clamp_low = - self.scale * self.zero_point
+ clamp_high = self.scale * (2 ** self.bits - 1 - self.zero_point)
+ weight = torch.clamp(self.weight, clamp_low.item(), clamp_high.item()) + noise.detach()
+
+ # return output
+ output = F.embedding(
+ input, weight, self.padding_idx, self.max_norm,
+ self.norm_type, self.scale_grad_by_freq, self.sparse)
+ return output
+
+ def extra_repr(self):
+ s = '{num_embeddings}, {embedding_dim}'
+ if self.padding_idx is not None:
+ s += ', padding_idx={padding_idx}'
+ if self.max_norm is not None:
+ s += ', max_norm={max_norm}'
+ if self.norm_type != 2:
+ s += ', norm_type={norm_type}'
+ if self.scale_grad_by_freq is not False:
+ s += ', scale_grad_by_freq={scale_grad_by_freq}'
+ if self.sparse is not False:
+ s += ', sparse=True'
+ s += 'quant_noise={p}, bits={bits}, method={method}'
+ return s.format(**self.__dict__)
diff --git a/pool/shard002/Python/0026424_conf.py b/pool/shard002/Python/0026424_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd696c6a1142d7e8d3ac749c6310ff69c730c139
--- /dev/null
+++ b/pool/shard002/Python/0026424_conf.py
@@ -0,0 +1,323 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of Invenio.
+# Copyright (C) 2015 CERN.
+#
+# Invenio is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of the
+# License, or (at your option) any later version.
+#
+# Invenio is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Invenio; if not, write to the
+# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
+# MA 02111-1307, USA.
+#
+# In applying this license, CERN does not
+# waive the privileges and immunities granted to it by virtue of its status
+# as an Intergovernmental Organization or submit itself to any jurisdiction.
+
+from __future__ import print_function
+
+import sys
+import os
+import shlex
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+sys.path.insert(0, os.path.abspath('..'))
+sys.path.insert(0, os.path.abspath('_ext'))
+
+import ultramock
+ultramock.activate()
+
+# -- General configuration ------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.intersphinx',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'Invenio-Base'
+copyright = u'2015, CERN'
+author = u'CERN'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+
+# Get the version string. Cannot be done with import!
+g = {}
+with open(os.path.join('..', 'invenio_base', 'version.py'), 'rt') as fp:
+ exec(fp.read(), g)
+ version = g['__version__']
+
+# The full version, including alpha/beta/rc tags.
+release = version
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = []
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+#keep_warnings = False
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = False
+
+
+# -- Options for HTML output ----------------------------------------------
+on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
+
+# only set the theme when we are not on RTD
+if not on_rtd:
+ try:
+ import sphinx_rtd_theme
+ html_theme = "sphinx_rtd_theme"
+ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
+ except ImportError:
+ print("`sphinx_rtd_theme` not found, pip install it", file=sys.stderr)
+ html_theme = 'alabaster'
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# " v documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# Add any extra paths that contain custom files (such as robots.txt or
+# .htaccess) here, relative to this directory. These files are copied
+# directly to the root of the documentation.
+#html_extra_path = []
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
+# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
+#html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# Now only 'ja' uses this config value
+#html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+#html_search_scorer = 'scorer.js'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'invenio-base_namedoc'
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+
+# Latex figure (float) alignment
+#'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (master_doc, 'invenio-base.tex', u'invenio-base Documentation',
+ u'CERN', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (master_doc, 'invenio-base', u'invenio-base Documentation',
+ [author], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (master_doc, 'invenio-base', u'Invenio-Base Documentation',
+ author, 'invenio-base', 'Base package for building the Invenio application.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
+
+
+# Example configuration for intersphinx: refer to the Python standard library.
+intersphinx_mapping = {'https://docs.python.org/': None}
diff --git a/pool/shard002/Python/0026429_test_hold.py b/pool/shard002/Python/0026429_test_hold.py
new file mode 100644
index 0000000000000000000000000000000000000000..5158945053b75714d6a75bd09a096f654606f146
--- /dev/null
+++ b/pool/shard002/Python/0026429_test_hold.py
@@ -0,0 +1,92 @@
+# Copyright (C) 2011-2012 by the Free Software Foundation, Inc.
+#
+# This file is part of GNU Mailman.
+#
+# GNU Mailman 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.
+#
+# GNU Mailman is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# GNU Mailman. If not, see .
+
+"""Additional tests for the hold chain."""
+
+from __future__ import absolute_import, unicode_literals
+
+__metaclass__ = type
+__all__ = [
+ ]
+
+
+import unittest
+
+from zope.component import getUtility
+
+from mailman.app.lifecycle import create_list
+from mailman.chains.hold import autorespond_to_sender
+from mailman.interfaces.autorespond import IAutoResponseSet, Response
+from mailman.interfaces.usermanager import IUserManager
+from mailman.testing.helpers import configuration, get_queue_messages
+from mailman.testing.layers import ConfigLayer
+
+
+
+class TestAutorespond(unittest.TestCase):
+ """Test autorespond_to_sender()"""
+
+ layer = ConfigLayer
+
+ def setUp(self):
+ self._mlist = create_list('test@example.com')
+ # Python 2.7 has assertMultiLineEqual. Let this work without bounds.
+ self.maxDiff = None
+ self.eq = getattr(self, 'assertMultiLineEqual', self.assertEqual)
+
+ @configuration('mta', max_autoresponses_per_day=1)
+ def test_max_autoresponses_per_day(self):
+ # The last one we sent was the last one we should send today. Instead
+ # of sending an automatic response, send them the "no more today"
+ # message. Start by simulating a response having been sent to an
+ # address already.
+ anne = getUtility(IUserManager).create_address('anne@example.com')
+ response_set = IAutoResponseSet(self._mlist)
+ response_set.response_sent(anne, Response.hold)
+ # Trigger the sending of a "last response for today" using the default
+ # language (i.e. the mailing list's preferred language).
+ autorespond_to_sender(self._mlist, 'anne@example.com')
+ # So first, there should be one more hold response sent to the user.
+ self.assertEqual(response_set.todays_count(anne, Response.hold), 2)
+ # And the virgin queue should have the message in it.
+ messages = get_queue_messages('virgin')
+ self.assertEqual(len(messages), 1)
+ # Remove the variable headers.
+ message = messages[0].msg
+ self.assertTrue('message-id' in message)
+ del message['message-id']
+ self.assertTrue('date' in message)
+ del message['date']
+ self.eq(messages[0].msg.as_string(), """\
+MIME-Version: 1.0
+Content-Type: text/plain; charset="us-ascii"
+Content-Transfer-Encoding: 7bit
+Subject: Last autoresponse notification for today
+From: test-owner@example.com
+To: anne@example.com
+Precedence: bulk
+
+We have received a message from your address
+requesting an automated response from the test@example.com mailing
+list.
+
+The number we have seen today: 1. In order to avoid problems such as
+mail loops between email robots, we will not be sending you any
+further responses today. Please try again tomorrow.
+
+If you believe this message is in error, or if you have any questions,
+please contact the list owner at test-owner@example.com.""")
diff --git a/pool/shard002/Python/0026438_TextItem.py b/pool/shard002/Python/0026438_TextItem.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd0320c4423e9ab29ce7553d01882f14ac280f3
--- /dev/null
+++ b/pool/shard002/Python/0026438_TextItem.py
@@ -0,0 +1,218 @@
+import numpy as np
+from ..Qt import QtCore, QtGui
+from ..Point import Point
+from .. import functions as fn
+from .GraphicsObject import GraphicsObject
+
+
+class TextItem(GraphicsObject):
+ """
+ GraphicsItem displaying unscaled text (the text will always appear normal even inside a scaled ViewBox).
+ """
+ def __init__(self, text='', color=(200,200,200), html=None, anchor=(0,0),
+ border=None, fill=None, angle=0, rotateAxis=None):
+ """
+ ============== =================================================================================
+ **Arguments:**
+ *text* The text to display
+ *color* The color of the text (any format accepted by pg.mkColor)
+ *html* If specified, this overrides both *text* and *color*
+ *anchor* A QPointF or (x,y) sequence indicating what region of the text box will
+ be anchored to the item's position. A value of (0,0) sets the upper-left corner
+ of the text box to be at the position specified by setPos(), while a value of (1,1)
+ sets the lower-right corner.
+ *border* A pen to use when drawing the border
+ *fill* A brush to use when filling within the border
+ *angle* Angle in degrees to rotate text. Default is 0; text will be displayed upright.
+ *rotateAxis* If None, then a text angle of 0 always points along the +x axis of the scene.
+ If a QPointF or (x,y) sequence is given, then it represents a vector direction
+ in the parent's coordinate system that the 0-degree line will be aligned to. This
+ Allows text to follow both the position and orientation of its parent while still
+ discarding any scale and shear factors.
+ ============== =================================================================================
+
+
+ The effects of the `rotateAxis` and `angle` arguments are added independently. So for example:
+
+ * rotateAxis=None, angle=0 -> normal horizontal text
+ * rotateAxis=None, angle=90 -> normal vertical text
+ * rotateAxis=(1, 0), angle=0 -> text aligned with x axis of its parent
+ * rotateAxis=(0, 1), angle=0 -> text aligned with y axis of its parent
+ * rotateAxis=(1, 0), angle=90 -> text orthogonal to x axis of its parent
+ """
+
+ self.anchor = Point(anchor)
+ self.rotateAxis = None if rotateAxis is None else Point(rotateAxis)
+ #self.angle = 0
+ GraphicsObject.__init__(self)
+ self.textItem = QtGui.QGraphicsTextItem()
+ self.textItem.setParentItem(self)
+ self._lastTransform = None
+ self._lastScene = None
+ self._bounds = QtCore.QRectF()
+ if html is None:
+ self.setColor(color)
+ self.setText(text)
+ else:
+ self.setHtml(html)
+ self.fill = fn.mkBrush(fill)
+ self.border = fn.mkPen(border)
+ self.setAngle(angle)
+
+ def setText(self, text, color=None):
+ """
+ Set the text of this item.
+
+ This method sets the plain text of the item; see also setHtml().
+ """
+ if color is not None:
+ self.setColor(color)
+ self.setPlainText(text)
+
+ def setPlainText(self, text):
+ """
+ Set the plain text to be rendered by this item.
+
+ See QtGui.QGraphicsTextItem.setPlainText().
+ """
+ if text != self.toPlainText():
+ self.textItem.setPlainText(text)
+ self.updateTextPos()
+
+ def toPlainText(self):
+ return self.textItem.toPlainText()
+
+ def setHtml(self, html):
+ """
+ Set the HTML code to be rendered by this item.
+
+ See QtGui.QGraphicsTextItem.setHtml().
+ """
+ if self.toHtml() != html:
+ self.textItem.setHtml(html)
+ self.updateTextPos()
+
+ def toHtml(self):
+ return self.textItem.toHtml()
+
+ def setTextWidth(self, *args):
+ """
+ Set the width of the text.
+
+ If the text requires more space than the width limit, then it will be
+ wrapped into multiple lines.
+
+ See QtGui.QGraphicsTextItem.setTextWidth().
+ """
+ self.textItem.setTextWidth(*args)
+ self.updateTextPos()
+
+ def setFont(self, *args):
+ """
+ Set the font for this text.
+
+ See QtGui.QGraphicsTextItem.setFont().
+ """
+ self.textItem.setFont(*args)
+ self.updateTextPos()
+
+ def setAngle(self, angle):
+ self.angle = angle
+ self.updateTransform()
+
+ def setAnchor(self, anchor):
+ self.anchor = Point(anchor)
+ self.updateTextPos()
+
+ def setColor(self, color):
+ """
+ Set the color for this text.
+
+ See QtGui.QGraphicsItem.setDefaultTextColor().
+ """
+ self.color = fn.mkColor(color)
+ self.textItem.setDefaultTextColor(self.color)
+
+ def updateTextPos(self):
+ # update text position to obey anchor
+ r = self.textItem.boundingRect()
+ tl = self.textItem.mapToParent(r.topLeft())
+ br = self.textItem.mapToParent(r.bottomRight())
+ offset = (br - tl) * self.anchor
+ self.textItem.setPos(-offset)
+
+ ### Needed to maintain font size when rendering to image with increased resolution
+ #self.textItem.resetTransform()
+ ##self.textItem.rotate(self.angle)
+ #if self._exportOpts is not False and 'resolutionScale' in self._exportOpts:
+ #s = self._exportOpts['resolutionScale']
+ #self.textItem.scale(s, s)
+
+ def boundingRect(self):
+ return self.textItem.mapToParent(self.textItem.boundingRect()).boundingRect()
+
+ def viewTransformChanged(self):
+ # called whenever view transform has changed.
+ # Do this here to avoid double-updates when view changes.
+ self.updateTransform()
+
+ def paint(self, p, *args):
+ # this is not ideal because it requires the transform to be updated at every draw.
+ # ideally, we would have a sceneTransformChanged event to react to..
+ s = self.scene()
+ ls = self._lastScene
+ if s is not ls:
+ if ls is not None:
+ ls.sigPrepareForPaint.disconnect(self.updateTransform)
+ self._lastScene = s
+ if s is not None:
+ s.sigPrepareForPaint.connect(self.updateTransform)
+ self.updateTransform()
+ p.setTransform(self.sceneTransform())
+
+ if self.border.style() != QtCore.Qt.NoPen or self.fill.style() != QtCore.Qt.NoBrush:
+ p.setPen(self.border)
+ p.setBrush(self.fill)
+ p.setRenderHint(p.Antialiasing, True)
+ p.drawPolygon(self.textItem.mapToParent(self.textItem.boundingRect()))
+
+ def setVisible(self, v):
+ GraphicsObject.setVisible(self, v)
+ if v:
+ self.updateTransform()
+
+ def updateTransform(self):
+ if not self.isVisible():
+ return
+
+ # update transform such that this item has the correct orientation
+ # and scaling relative to the scene, but inherits its position from its
+ # parent.
+ # This is similar to setting ItemIgnoresTransformations = True, but
+ # does not break mouse interaction and collision detection.
+ p = self.parentItem()
+ if p is None:
+ pt = QtGui.QTransform()
+ else:
+ pt = p.sceneTransform()
+
+ if pt == self._lastTransform:
+ return
+
+ t = pt.inverted()[0]
+ # reset translation
+ t.setMatrix(t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), 0, 0, t.m33())
+
+ # apply rotation
+ angle = -self.angle
+ if self.rotateAxis is not None:
+ d = pt.map(self.rotateAxis) - pt.map(Point(0, 0))
+ a = np.arctan2(d.y(), d.x()) * 180 / np.pi
+ angle += a
+ t.rotate(angle)
+
+ self.setTransform(t)
+
+ self._lastTransform = pt
+
+ self.updateTextPos()
diff --git a/pool/shard002/Python/0026441_periodic_table_widget.py b/pool/shard002/Python/0026441_periodic_table_widget.py
new file mode 100644
index 0000000000000000000000000000000000000000..986a0745028d8eeb2db423e1b8100c2e89a7689d
--- /dev/null
+++ b/pool/shard002/Python/0026441_periodic_table_widget.py
@@ -0,0 +1,203 @@
+#
+# Project: MXCuBE
+# https://github.com/mxcube
+#
+# This file is part of MXCuBE software.
+#
+# MXCuBE 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.
+#
+# MXCuBE 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 MXCuBE. If not, see .
+
+PYMCA_IMPORTED = False
+try:
+ from PyMca5.PyMca import QPeriodicTable
+ PYMCA_IMPORTED = 5
+except BaseException:
+ try:
+ from PyMca import QPeriodicTable
+ PYMCA_IMPORTED = 4
+ except BaseException:
+ pass
+
+from gui.utils import QtImport
+
+
+__credits__ = ["MXCuBE collaboration"]
+__license__ = "LGPLv3+"
+
+
+class PeriodicTableWidget(QtImport.QWidget):
+
+ elementEdgeSelectedSignal = QtImport.pyqtSignal(str, str)
+
+ def __init__(self, parent=None, name=None, fl=0):
+
+ QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl))
+ if name is not None:
+ self.setObjectName(name)
+ self.selected_element = None
+ self.selected_edge = "L3"
+
+ # Signals ------------------------------------------------------------
+
+ # Slots ---------------------------------------------------------------
+
+ # Graphic elements ----------------------------------------------------
+ if PYMCA_IMPORTED:
+ self.periodic_table = CustomPeriodicTable(self)
+ else:
+ self.periodic_elements_combo = QtImport.QComboBox(self)
+ self.periodic_elements_combo.setFixedWidth(100)
+
+ self.edge_widget = QtImport.QWidget(self)
+ edge_label = QtImport.QLabel("Edge:", self.edge_widget)
+ self.edge_combo = QtImport.QComboBox(self.edge_widget)
+
+ # Layout --------------------------------------------------------------
+ _edge_hlayout = QtImport.QHBoxLayout(self.edge_widget)
+ if not PYMCA_IMPORTED:
+ _edge_hlayout.addWidget(self.periodic_elements_combo)
+ _edge_hlayout.addWidget(edge_label)
+ _edge_hlayout.addWidget(self.edge_combo)
+ _edge_hlayout.addStretch(0)
+ _edge_hlayout.setSpacing(2)
+ _edge_hlayout.setContentsMargins(0, 0, 0, 0)
+
+ _main_vlayout = QtImport.QVBoxLayout(self)
+ if PYMCA_IMPORTED:
+ _main_vlayout.addWidget(self.periodic_table, QtImport.Qt.AlignHCenter)
+ _main_vlayout.addWidget(self.edge_widget)
+ _main_vlayout.addStretch(0)
+ _main_vlayout.setSpacing(2)
+ _main_vlayout.setContentsMargins(2, 2, 2, 2)
+
+ # SizePolicies --------------------------------------------------------
+
+ # Qt signal/slot connections ------------------------------------------
+ if PYMCA_IMPORTED:
+ self.periodic_table.edgeSelectedSignal.connect(self.edge_selected)
+ else:
+ self.periodic_elements_combo.activated.connect(self.element_combo_activated)
+ self.edge_combo.addItem("K")
+ self.edge_combo.activated.connect(self.edge_combo_activated)
+ self.edge_combo.setEnabled(False)
+
+ # Other ---------------------------------------------------------------
+
+ def element_combo_activated(self, element):
+ self.selected_element = str(self.periodic_elements_combo.currentText())
+ self.selected_edge = str(self.edge_combo.currentText())
+ self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge)
+
+ def edge_selected(self, element, edge):
+ self.selected_element = str(element)
+ self.selected_edge = str(edge)
+ self.edge_widget.setEnabled(self.selected_edge != "K")
+
+ self.edge_combo.clear()
+ if edge == "K":
+ edge_list = "K"
+ else:
+ edge_list = ("L1", "L2", "L3")
+ for item in edge_list:
+ self.edge_combo.addItem(item)
+ self.edge_combo.setCurrentIndex(edge_list.index(item))
+ self.edge_combo.setEnabled(self.edge_combo.count() > 1)
+ self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge)
+
+ def set_current_element_edge(self, element, edge):
+ if PYMCA_IMPORTED:
+ self.periodic_table.table_element_clicked(element, edge)
+
+ def get_selected_element_edge(self):
+ return self.selected_element, self.selected_edge
+
+ def edge_combo_activated(self, item_index):
+ self.selected_edge = str(self.edge_combo.currentText())
+ self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge)
+
+ def set_elements(self, elements):
+ if PYMCA_IMPORTED:
+ self.periodic_table.setElements(elements)
+ else:
+ for element in elements:
+ self.periodic_elements_combo.addItem(element["symbol"])
+
+
+if PYMCA_IMPORTED:
+
+ class CustomPeriodicTable(QPeriodicTable.QPeriodicTable):
+
+ edgeSelectedSignal = QtImport.pyqtSignal(str, str)
+
+ def __init__(self, *args):
+ QPeriodicTable.QPeriodicTable.__init__(self, *args)
+
+ self.elements_dict = {}
+ if PYMCA_IMPORTED == 5:
+ self.sigElementClicked.connect(self.table_element_clicked)
+ else:
+ QtImport.QObject.connect(
+ self, QtImport.SIGNAL("elementClicked"), self.table_element_clicked
+ )
+ for b in self.eltButton:
+ self.eltButton[b].colors[0] = QtImport.QColor(QtImport.Qt.green)
+ self.eltButton[b].colors[1] = QtImport.QColor(QtImport.Qt.darkGreen)
+ self.eltButton[b].setEnabled(False)
+ for el in QPeriodicTable.Elements:
+ symbol = el[0]
+ self.elements_dict[symbol] = el
+
+ def elementEnter(self, symbol, z=None, name=None):
+ b = self.eltButton[symbol]
+ if b.isEnabled():
+ b.setCurrent(True)
+
+ def elementLeave(self, symbol):
+ b = self.eltButton[symbol]
+ if b.isEnabled():
+ b.setCurrent(False)
+
+ def table_element_clicked(self, symbol, energy=None):
+ if isinstance(symbol, tuple) and len(symbol) > 0:
+ symbol = symbol[0]
+
+ if energy is None:
+ energy = self.energies_dict[symbol]
+ self.setSelection((symbol,))
+ if energy is None:
+ energy = self.energies_dict[symbol]
+ else:
+ index = self.elements_dict[symbol][1]
+ name = self.elements_dict[symbol][4]
+ txt = "%s - %s (%s,%s)" % (symbol, energy, index, name)
+ self.eltLabel.setText(txt)
+ self.edgeSelectedSignal.emit(symbol, energy)
+ # self.widgetSynchronizeSignal([symbol, energy])
+
+ def setElements(self, elements):
+ self.energies_dict = {}
+ for b in self.eltButton:
+ self.eltButton[b].setEnabled(False)
+ first_element = None
+ for element in elements:
+ symbol = element["symbol"]
+ if first_element is None:
+ first_element = symbol
+ energy = element["energy"]
+ self.energies_dict[symbol] = energy
+ b = self.eltButton[symbol]
+ b.setEnabled(True)
+
+ def widgetSynchronize(self, state):
+ symbol = state[0]
+ self.tableElementChanged(symbol)
diff --git a/pool/shard002/Python/0026444_env.py b/pool/shard002/Python/0026444_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f793ff8b57b23ab0118c322adce7e866f034225
--- /dev/null
+++ b/pool/shard002/Python/0026444_env.py
@@ -0,0 +1,61 @@
+# 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 logging import config as log_config
+
+from alembic import context
+from oslo_db.sqlalchemy import enginefacade
+
+try:
+ # NOTE(whaom): This is to register the DB2 alembic code which
+ # is an optional runtime dependency.
+ from ibm_db_alembic.ibm_db import IbmDbImpl # noqa
+except ImportError:
+ pass
+
+from ironic.db.sqlalchemy import models
+
+# this is the Alembic Config object, which provides
+# access to the values within the .ini file in use.
+config = context.config
+
+# Interpret the config file for Python logging.
+# This line sets up loggers basically.
+log_config.fileConfig(config.config_file_name)
+
+# add your model's MetaData object here
+# for 'autogenerate' support
+# from myapp import mymodel
+target_metadata = models.Base.metadata
+
+# other values from the config, defined by the needs of env.py,
+# can be acquired:
+# my_important_option = config.get_main_option("my_important_option")
+# ... etc.
+
+
+def run_migrations_online():
+ """Run migrations in 'online' mode.
+
+ In this scenario we need to create an Engine
+ and associate a connection with the context.
+
+ """
+ engine = enginefacade.get_legacy_facade().get_engine()
+ with engine.connect() as connection:
+ context.configure(connection=connection,
+ target_metadata=target_metadata)
+ with context.begin_transaction():
+ context.run_migrations()
+
+
+run_migrations_online()
diff --git a/pool/shard002/Python/0026449_test_scatter_colormap.py b/pool/shard002/Python/0026449_test_scatter_colormap.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc883f74bec4ddf2cdbfef1da4099284e4da30dc
--- /dev/null
+++ b/pool/shard002/Python/0026449_test_scatter_colormap.py
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+#
+import helpers
+
+
+def plot():
+ from matplotlib import pyplot as plt
+ import numpy as np
+ fig = plt.figure()
+ np.random.seed(123)
+ plt.scatter(
+ np.random.randn(10),
+ np.random.randn(10),
+ np.random.rand(10)*90 + 10,
+ np.random.randn(10)
+ )
+ return fig
+
+
+def test():
+ phash = helpers.Phash(plot())
+ assert phash.phash == 'cf616c42e4ec738c', phash.get_details()
+ return
diff --git a/pool/shard002/Python/0026456_test_utils.py b/pool/shard002/Python/0026456_test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4f1cb727e9036096cb4f4cb4afcda33b332ae7b
--- /dev/null
+++ b/pool/shard002/Python/0026456_test_utils.py
@@ -0,0 +1,56 @@
+# coding: utf-8
+
+"""
+ django find&replace
+ ~~~~~~~~~~~~~~~
+
+ :copyleft: 2015 by find&replace team, see AUTHORS for more details.
+ :created: 2015 by JensDiemer.de
+ :license: GNU GPL v3 or above, see LICENSE for more details.
+"""
+
+from __future__ import absolute_import, print_function
+
+from pprint import pprint
+
+from django.db import models
+from django.test import SimpleTestCase
+
+from find_and_replace.model_fields import filter_model_fields, field_list2choices, \
+ field2dot_name
+
+
+class UtilsTest(SimpleTestCase):
+ def test(self):
+ filtered_fields = filter_model_fields(
+ app_labels = ("auth", "cms"),
+ model_fields = (
+ models.TextField,
+ models.CharField,
+ )
+ )
+ # pprint(filtered_fields)
+ # [,
+ # ,
+ # ,
+ # ...
+ # ,
+ # ]
+
+ field_choices = field_list2choices(filtered_fields)
+ pprint(field_choices)
+ # [(0, 'auth.Group.name'),
+ # (1, 'auth.Permission.codename'),
+ # (2, 'auth.Permission.name'),
+ # ...
+ # (30, 'cms.Title.title'),
+ # (31, 'cms.UserSettings.language')]
+
+ self.assertEqual(field2dot_name(filtered_fields[2]), 'auth.Permission.name')
+ self.assertEqual(field_choices[2][1], 'auth.Permission.name')
+
+ self.assertEqual(field2dot_name(filtered_fields[30]), 'cms.Title.title')
+ self.assertEqual(field_choices[30][1], 'cms.Title.title')
+
+ self.assertEqual(len(filtered_fields), 32)
+ self.assertEqual(len(field_choices), 32)
\ No newline at end of file
diff --git a/pool/shard002/Python/0026462_test_dep_getcpv.py b/pool/shard002/Python/0026462_test_dep_getcpv.py
new file mode 100644
index 0000000000000000000000000000000000000000..79c1514a1ce8655b7fc40156dcde65fa50390a21
--- /dev/null
+++ b/pool/shard002/Python/0026462_test_dep_getcpv.py
@@ -0,0 +1,37 @@
+# test_dep_getcpv.py -- Portage Unit Testing Functionality
+# Copyright 2006 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+
+from portage.tests import TestCase
+from portage.dep import dep_getcpv
+
+class DepGetCPV(TestCase):
+ """ A simple testcase for isvalidatom
+ """
+
+ def testDepGetCPV(self):
+
+ prefix_ops = [
+ "<", ">", "=", "~", "<=",
+ ">=", "!=", "!<", "!>", "!~"
+ ]
+
+ bad_prefix_ops = [">~", "<~", "~>", "~<"]
+ postfix_ops = [("=", "*"),]
+
+ cpvs = ["sys-apps/portage-2.1", "sys-apps/portage-2.1",
+ "sys-apps/portage-2.1"]
+ slots = [None, ":foo", ":2"]
+ for cpv in cpvs:
+ for slot in slots:
+ for prefix in prefix_ops:
+ mycpv = prefix + cpv
+ if slot:
+ mycpv += slot
+ self.assertEqual(dep_getcpv(mycpv), cpv)
+
+ for prefix, postfix in postfix_ops:
+ mycpv = prefix + cpv + postfix
+ if slot:
+ mycpv += slot
+ self.assertEqual(dep_getcpv(mycpv), cpv)
diff --git a/pool/shard002/Python/0026464_present_road.py b/pool/shard002/Python/0026464_present_road.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae8c8a08afa0a389e994f72115e927e5ce108daa
--- /dev/null
+++ b/pool/shard002/Python/0026464_present_road.py
@@ -0,0 +1,63 @@
+#!/usr/bin/python2.7
+
+import re
+
+cities = {}
+smallest_cost = 999999999
+biggest_cost = 0
+
+class city:
+ def __init__(self, name):
+ self.name = name
+ self.roads = {}
+
+ def __repr__(self):
+ return str(self.roads) + '\n'
+
+ def add_road(self, destination, cost):
+ self.roads[destination] = cost
+ if destination not in cities:
+ new_destination = city(destination)
+ cities[destination] = new_destination
+ new_destination.add_road(self.name, cost)
+ elif self.name not in cities[destination].get_destinations():
+ cities[destination].add_road(self.name, cost)
+
+ def get_destinations(self):
+ return list(self.roads.keys())
+
+ def get_road_cost(self, destination):
+ return self.roads[destination]
+
+def extremum_road_cost(cities_to_visit, current_city='', cost=0):
+ global smallest_cost
+ global biggest_cost
+
+ if len(cities_to_visit) == 0:
+ if cost < smallest_cost:
+ smallest_cost = cost
+ elif cost > biggest_cost:
+ biggest_cost = cost
+ else:
+ if current_city == '':
+ for first_city in cities_to_visit:
+ extremum_road_cost([x for x in cities_to_visit if x != first_city], first_city)
+ else:
+ for city in cities_to_visit:
+ extremum_road_cost([x for x in cities_to_visit if x != city], city, cost + cities[current_city].get_road_cost(city))
+
+with open('input.txt') as input_file:
+ regex = '^(\w+) \w+ (\w+) = (\d+)'
+ for line in input_file:
+ split_line = re.search(regex, line)
+ if split_line.group(1) not in cities:
+ new_city = city(split_line.group(1))
+
+ new_city.add_road(split_line.group(2), int(split_line.group(3)))
+ cities[split_line.group(1)] = new_city
+ else:
+ cities[split_line.group(1)].add_road(split_line.group(2), int(split_line.group(3)))
+
+extremum_road_cost(cities.keys())
+print 'shortest_path: ' + str(smallest_cost)
+print 'longest_path: ' + str(biggest_cost)
\ No newline at end of file
diff --git a/pool/shard002/Python/0026467_mac.py b/pool/shard002/Python/0026467_mac.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a5347dd4161b08b873a76ba799c9eb079de3c08
--- /dev/null
+++ b/pool/shard002/Python/0026467_mac.py
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+import re
+
+
+class Mac(object):
+ REGEXP = r'^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$'
+
+ def __init__(self, mac):
+ if type(mac) != str:
+ raise ValueError('Argument mac must be string')
+ if re.search(self.REGEXP, mac) is None:
+ raise ValueError('Argument mac must be valid mac')
+
+ self.mac = mac.lower()
+
+ def __str__(self, *args, **kwargs):
+ return self.mac
+
+ def __repr__(self):
+ return '"{}"'.format(str(self))
+
+ def __eq__(self, other):
+ return self.mac == other.mac
+
+ def __hash__(self):
+ return hash(self.mac)
+
+ @classmethod
+ def correct(cls, mac):
+ return cls(':'.join([mac[i:i+2].lower() for i in range(0, len(mac), 2)]))
+
+ @staticmethod
+ def raw(mac):
+ return mac.replace(":", "").upper()
diff --git a/pool/shard002/Python/0026469_acsncRunSupComp.py b/pool/shard002/Python/0026469_acsncRunSupComp.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fca2d89026e4bc5b5dcecce4b3b9954897f0f87
--- /dev/null
+++ b/pool/shard002/Python/0026469_acsncRunSupComp.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+#*******************************************************************************
+# ALMA - Atacama Large Millimiter Array
+# (c) Associated Universities Inc., 2002
+# (c) European Southern Observatory, 2002
+# Copyright by ESO (in the framework of the ALMA collaboration)
+# and Cosylab 2002, All rights reserved
+#
+# 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., 59 Temple Place, Suite 330, Boston,
+# MA 02111-1307 USA
+#
+# @(#) $Id: acsncTestConSup.py,v 1.6 2006/03/08 17:50:44 dfugate Exp $
+
+"""
+"""
+
+from Acspy.Clients.SimpleClient import PySimpleClient
+from sys import argv
+from time import sleep
+
+channel_name = str(argv[2])
+autoconnect = str(argv[3]) == 'autoreconnect'
+num_sec = int(argv[4])
+num_events = int(argv[5])
+sleep_val = int(argv[6])
+
+# in long numSec,in long numEvents,in long sleepVal
+
+# Make an instance of the PySimpleClient
+simpleClient = PySimpleClient()
+
+supplier = simpleClient.getComponent(argv[1])
+supplier.execTest(channel_name, autoconnect, num_sec, num_events, sleep_val)
+sleep(2)
+simpleClient.releaseComponent(argv[1])
diff --git a/pool/shard002/Python/0026472_MyState.py b/pool/shard002/Python/0026472_MyState.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd6e2634c7cfdfe9e6a6118ef87edfd38803170b
--- /dev/null
+++ b/pool/shard002/Python/0026472_MyState.py
@@ -0,0 +1,80 @@
+__author__ = 'Nicole'
+
+import json
+import random
+import time
+
+GREEN = 'green'
+CONSERVATIVE = 'conservative'
+LIBERAL = 'liberal'
+LIBERTARIAN = 'libertarian'
+MAX_CACHED_POINTS = 400
+
+STATES = [GREEN, CONSERVATIVE, LIBERAL, LIBERTARIAN]
+
+
+class MyStates:
+ def __init__(self):
+ self.currentStates = [CurrentStateOfParty(GREEN), CurrentStateOfParty(CONSERVATIVE), CurrentStateOfParty(LIBERAL), CurrentStateOfParty(LIBERTARIAN)]
+ self.newPoints = list()
+ self.existingPoints = list()
+ self.totalPoints = 0
+
+ def passStateToFrontEnd(self):
+ pointsToPass = list()
+ for point in self.newPoints:
+ self.existingPoints.append(point)
+ # serialize points:
+ pointsToPass.append(json.dumps(point.newPoint.exportToFrontEnd()))
+ # empty the old new points:
+ self.newPoints = list()
+ return {'newPoints': pointsToPass, 'timestamp': time.time()}
+
+ def addNewPoint(self, point):
+ self.newPoints.append(point)
+ state = self.getState(point.party)
+ self.totalPoints += 1
+ state.percentTotal = state.totalPoints / self.totalPoints
+ if self.totalPoints >= MAX_CACHED_POINTS:
+ self.existingPoints.pop(1)
+ self.totalPoints -= 1
+
+
+class CurrentStateOfParty:
+ def __init__(self, party):
+ self.party = party
+ self.percentTotal = 0
+ self.certainty = 0
+ self.positivity = 0
+ self.totalPoints = 0
+
+ def addNewPoint(self, point):
+ self.certainty = (self.certainty * self.totalPoints + point.newPoint.tendency) / (self.totalPoints + 1)
+ self.positivity = (self.positivity * self.totalPoints + point.positivity) / (self.totalPoints + 1)
+ self.totalPoints += 1
+
+ def exportToFrontEnd(self):
+ return {'party': self.party, 'percentTotal': self.percentTotal, 'certainty': self.certainty, 'positivity': self.positivity}
+
+ def exportRandomness(self):
+ return {'party': "conservative", 'percentTotal': random.randint(-60,60), 'certainty': random.randint(-60,60), 'positivity': random.randint(-60,60)}
+
+
+class StateOfPoint:
+ def __init__(self):
+ self.newPoint = NewPoint()
+ self.positivity = 0
+
+
+class NewPoint:
+ def __init__(self):
+ self.tendency = 0
+ self.lat = 0
+ self.long = 0
+ self.party = None
+
+ def exportToFrontEnd(self):
+ return {"lat": self.lat, "long": self.long, "tendency": self.tendency, "party": self.party}
+
+ def exportRandomness(self):
+ return {"lat": random.randint(-60,60), "long": random.randint(-60,60), "tendency": random.randint(-60,60), "party": random.randint(-60,60)}
\ No newline at end of file
diff --git a/pool/shard002/Python/0026476_json_harddisk_csv.py b/pool/shard002/Python/0026476_json_harddisk_csv.py
new file mode 100644
index 0000000000000000000000000000000000000000..98d4c1cce6e10d7179aeba24b85d3f2d6826283c
--- /dev/null
+++ b/pool/shard002/Python/0026476_json_harddisk_csv.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+# Copyright 2000-2019 Reciclanet Asociación Educativa-Reciclanet Hezkuntza Elkartea www.reciclanet.org
+#
+# 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 json
+import csv
+import os
+
+path_to_json = "./jsons/"
+
+try:
+ json_files = os.listdir(path_to_json)
+except FileNotFoundError:
+ print("No existe el directorio " + path_to_json + " con los archivos JSON")
+ exit()
+
+with open("discos_duros.csv", "a+") as computer:
+ csv_write_file = csv.writer(computer)
+ computer.seek(0)
+ csv_reader = csv.reader(computer)
+
+ for json_file in json_files:
+
+ with open(path_to_json + json_file, "r") as read_file:
+ data_file = json.load(read_file)
+
+ for index in data_file["components"]:
+ if index["@type"] == "HardDrive":
+
+ for row in csv_reader:
+ if row[2] == index["serialNumber"]:
+ print("El archivo/disco ya está procesado: porque coinciden los S/N")
+ break
+ else:
+ print("Añadiendo línea... S/N: " + index["serialNumber"] + ", Label: " + data_file["label"])
+
+ try:
+ hdd_manufacturer = index["manufacturer"]
+ except KeyError:
+ hdd_manufacturer = "-"
+
+ csv_write_file.writerow([
+ hdd_manufacturer,
+ index["model"],
+ index["serialNumber"],
+ "Sobrescritura",
+ str(index["size"] / 1000) + " GB",
+ "",
+ data_file["label"],
+ ])
+ break
+ else:
+ continue
diff --git a/pool/shard002/Python/0026484_Historia1.py b/pool/shard002/Python/0026484_Historia1.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b8ca15ee9f3e16b10c31056c738729d32bcbf03
--- /dev/null
+++ b/pool/shard002/Python/0026484_Historia1.py
@@ -0,0 +1,48 @@
+from Personagem import Personagem
+from Batalha import Batalha
+from Decisao import Decisao
+
+
+jogador = Personagem(input("Qual será o nome do seu personagem?\nR: "),100,100,100,100,100,100)
+monstro = Personagem("Demonio",10,10,10,10,10,10)
+batalha = Batalha()
+decisao = Decisao()
+print("""--------------------------------------------------
+%s era um jovem campones, vivia na tranquila vila de Edremor, quando
+tudo mudou! Ele encontrou uma espada, enterrada em uma pedra e uma estranha
+luz emanava dela, chamando-o para empunha-la, gritava em sua vontade, ecoava
+em sua mente as palavras USE-ME, foi então que ele decidiu tira-la da pedra.
+
+Assim começou sua jornada!
+--------------------------------------------------
+Na estrada para Ebalithur encontrou um %s, oque deseja fazer?
+--------------------------------------------------"""%(jogador.Nome,monstro.Nome))
+if decisao.AtacarOuFugir() == 'ATACAR':
+ ganhador = batalha.Normal(jogador,monstro)
+ if ganhador.Nome == jogador.Nome:
+ print("Com um golpe certeiro na garganta de seu oponente, %s mata o %s"%(jogador.Nome,monstro.Nome))
+ decisao.EscolherAtributoParaAumentar(3,ganhador)
+ else:
+ print("O jogador foi derrotado")
+else:
+ print("---------------------------------------------------")
+ print("O jogador fugiu em direção a floresta!")
+
+print("""--------------------------------------------------
+%s adentra a floresta, e lá se depara com dois caminhos um a sua direita,
+com vários galhos cheios de espinhos e um ar gelido como a brisa de inverno,
+o da esquerda era ensolarado e cheio de flores, porem uma estranha sensação
+lhe vinha no estomago ao olhar tambem para este caminho.
+--------------------------------------------------
+Qual caminho deseja seguir, direita ou esquerda?
+--------------------------------------------------"""%(jogador.Nome))
+direcaoEscolhida = decisao.Direcao(True,True,False,False,False,False)
+if direcaoEscolhida == "DIREITA":
+ print("Você escolheu a DIREITA")
+elif direcaoEscolhida == "ESQUERDA":
+ print("Você escolheu a ESQUERDA")
+else:
+ print("Erro na escolha da direção!")
+print("---------------------------------------------------")
+print("Fim de Jogo.")
+input("Pressione ENTER para finalizar")
diff --git a/pool/shard002/Python/0026487_endpoint.py b/pool/shard002/Python/0026487_endpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf7f5ad28178ef9912a6e5adf2ca2106ce484583
--- /dev/null
+++ b/pool/shard002/Python/0026487_endpoint.py
@@ -0,0 +1,45 @@
+# Copyright 2014-2015 Red Hat, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from oslo_config import cfg
+from oslo_log import log
+
+from ceilometer.agent import plugin_base as plugin
+from ceilometer.i18n import _LW
+
+LOG = log.getLogger(__name__)
+
+cfg.CONF.import_group('service_credentials', 'ceilometer.service')
+
+
+class EndpointDiscovery(plugin.DiscoveryBase):
+ """Discovery that supplies service endpoints.
+
+ This discovery should be used when the relevant APIs are not well suited
+ to dividing the pollster's work into smaller pieces than a whole service
+ at once. Example of this is the floating_ip pollster which calls
+ nova.floating_ips.list() and therefore gets all floating IPs at once.
+ """
+
+ @staticmethod
+ def discover(manager, param=None):
+ endpoints = manager.keystone.service_catalog.get_urls(
+ service_type=param,
+ endpoint_type=cfg.CONF.service_credentials.os_endpoint_type,
+ region_name=cfg.CONF.service_credentials.os_region_name)
+ if not endpoints:
+ LOG.warning(_LW('No endpoints found for service %s'),
+ "" if param is None else param)
+ return []
+ return endpoints
diff --git a/pool/shard002/Python/0026488_ExeBuilder.py b/pool/shard002/Python/0026488_ExeBuilder.py
new file mode 100644
index 0000000000000000000000000000000000000000..b92300bfd193c077f941dd23219f548f8b668504
--- /dev/null
+++ b/pool/shard002/Python/0026488_ExeBuilder.py
@@ -0,0 +1,150 @@
+__author__ = 'matth'
+import ctypes.util
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+if sys.version_info[0] == 2:
+ from .custom_py2exe_py2 import custom_py2exe
+else:
+ from .custom_py2exe_py3 import custom_py2exe
+
+
+def in_directory(f, directory):
+ #make both absolute
+ directory = os.path.join(os.path.abspath(directory), '')
+ f = os.path.abspath(f)
+
+ if sys.platform.startswith('win'):
+ directory = directory.lower()
+ f = f.lower()
+
+ #return true, if the common prefix of both is equal to directory
+ #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b
+ return os.path.commonprefix([f, directory]) == directory
+
+
+class ExeBuilder(object):
+
+ def __init__(self, dest_dir, script=None, module_name=None, module_exe_name=None, service_module=None, needs_admin=False, icon=None, console=True):
+ self.dest_dir = dest_dir
+ self.script = script
+ self.service_module = service_module
+ self.module_name = module_name
+ if service_module or module_name:
+ self.module_exe_base_name = os.path.splitext(module_exe_name)[0] if module_exe_name else (service_module or module_name).split('.')[-1]
+ else:
+ self.module_exe_base_name = None
+ self.needs_admin = needs_admin
+ self.icon = icon
+ self.console = console
+ self._tdir = None
+
+ def include_cwd_in_pythonpath(self):
+ return True
+
+ def include_pythoncom_and_pywintypes_in_pythonpath(self):
+ return True
+
+ def create_tmp_dir(self):
+ tdir = tempfile.mkdtemp(prefix="pyexebuild")
+ return tdir
+
+ def clean_up_tmp_dir(self, tdir):
+ pass
+
+ def get_extra_relative_path_elements(self):
+ e = []
+ # pywintypes and pythoncom have weird contortions to find DLLs: (look at the source in pywintypes.py)
+ # They also do something different if 'frozen' - which is the case when running from the exe
+ # We need to add the pywin32_system32 folder to the pythonpath:
+ if self.include_pythoncom_and_pywintypes_in_pythonpath():
+ e.append("Lib\\site-packages\\pywin32_system32")
+ return e
+
+ def build(self):
+ self._tdir = self.create_tmp_dir()
+ try:
+ custom_py2exe(self).build_exe()
+ python_dll_name = "Python%d%d.dll" % sys.version_info[:2]
+ self._copy_dll(python_dll_name)
+ if sys.version_info[0] == 3:
+ self._copy_dll("Python3.dll")
+ python_dll = ctypes.util.find_library(python_dll_name)
+ if not python_dll or not os.path.exists(python_dll):
+ raise Exception("Cannot find " + python_dll_name)
+ shutil.copy2(python_dll, self.dest_dir)
+ finally:
+ self.clean_up_tmp_dir(self._tdir)
+ self._tdir = None
+
+ def _copy_dll(self, dll_name):
+ dll = ctypes.util.find_library(dll_name)
+ if not dll or not os.path.exists(dll):
+ raise Exception("Cannot find " + dll_name)
+ shutil.copy2(dll, self.dest_dir)
+
+ def get_relative_built_in_python_path(self):
+ p = subprocess.check_output([self.get_python_executable(), "-S", "-s", "-E", "-c", "import sys; print(sys.path)"])
+ pythonpath = eval(p)
+
+ pythonpath = filter(
+ lambda p: os.path.isabs(p),
+ pythonpath)
+
+ pythonpath = filter(
+ lambda p: os.path.exists(p),
+ pythonpath)
+
+ pythonpath = filter(
+ lambda p: p.lower().rstrip('\\') == sys.prefix.lower().rstrip('\\') or in_directory(p, sys.prefix),
+ pythonpath)
+
+ pythonpath = [os.path.relpath(p, sys.prefix) for p in pythonpath]
+
+ return pythonpath
+
+ def get_python_executable(self):
+ return sys.executable
+
+ def get_code_snippet_to_set_sys_prefixes(self):
+ return r"""
+sys.prefix = %r
+sys.exec_prefix = %r
+""" % (sys.prefix, sys.exec_prefix)
+
+ def get_relative_lib_path(self):
+ """Returns path to python library files (usually /Lib/) relative to the executable"""
+ lib_path = os.path.join(sys.prefix, "Lib")
+ exe_path = self.dest_dir
+ relative_lib_path = os.path.relpath(lib_path, exe_path)
+ return relative_lib_path
+
+ def get_code_snippet_to_set_sys_path(self):
+ return r"""
+sys.path = %s[(sys.prefix if p == '.' else sys.prefix + "\\" + p) for p in %r]
+import site
+site.main() # Needed for Python 3.3 and up. Called automatically in 3.2 and below
+""" % (
+ ("[''] + " if self.include_cwd_in_pythonpath() else ""),
+ self.get_relative_built_in_python_path() + self.get_extra_relative_path_elements())
+
+
+if __name__ == '__main__':
+ default_dest_dir = os.path.join(os.path.dirname(sys.prefix), "bin")
+ import argparse
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--script',help='Define a script to be made into an executable')
+ parser.add_argument('--module-name',help='Specify a module that should be run using runpy (i.e. like python -m)')
+ parser.add_argument('--module-exe-name',help='Specify name of the exe to produce for a module based exe (service-module or module-name)')
+ parser.add_argument('--service-module', help='A module to make into a Windows service')
+ parser.add_argument('--dest-dir', help='Destination directory', default=default_dest_dir)
+ parser.add_argument('--icon', help='Icon to use for the executable', default=None)
+ parser.add_argument('--admin', action="store_true", default=False, help="If specified, the created exe will request Administrator privileges")
+ options = parser.parse_args(sys.argv[1:])
+ if not options.script and not options.service_module and not options.module_name:
+ parser.error("Must provide either a script, a module name or a service module name")
+ ExeBuilder(options.dest_dir, options.script, options.module_name, options.module_exe_name, options.service_module, options.admin, options.icon).build()
+
diff --git a/pool/shard002/Python/0026489_init__.py b/pool/shard002/Python/0026489_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b02b7b5bd91ee8828efea6c0fd1c9ee7dad56f61
--- /dev/null
+++ b/pool/shard002/Python/0026489_init__.py
@@ -0,0 +1,115 @@
+# Copyright 2018 Open Source Robotics Foundation, 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 rosidl_adapter.parser import parse_message_string
+from rosidl_adapter.resource import expand_template
+
+
+def convert_msg_to_idl(package_dir, package_name, input_file, output_dir):
+ assert package_dir.is_absolute()
+ assert not input_file.is_absolute()
+ assert input_file.suffix == '.msg'
+
+ abs_input_file = package_dir / input_file
+ print(f'Reading input file: {abs_input_file}')
+ abs_input_file = package_dir / input_file
+ content = abs_input_file.read_text(encoding='utf-8')
+ msg = parse_message_string(package_name, input_file.stem, content)
+
+ output_file = output_dir / input_file.with_suffix('.idl').name
+ abs_output_file = output_file.absolute()
+ print(f'Writing output file: {abs_output_file}')
+ data = {
+ 'pkg_name': package_name,
+ 'relative_input_file': input_file.as_posix(),
+ 'msg': msg,
+ }
+
+ expand_template('msg.idl.em', data, output_file, encoding='iso-8859-1')
+ return output_file
+
+
+MSG_TYPE_TO_IDL = {
+ 'bool': 'boolean',
+ 'byte': 'octet',
+ 'char': 'uint8',
+ 'int8': 'int8',
+ 'uint8': 'uint8',
+ 'int16': 'int16',
+ 'uint16': 'uint16',
+ 'int32': 'int32',
+ 'uint32': 'uint32',
+ 'int64': 'int64',
+ 'uint64': 'uint64',
+ 'float32': 'float',
+ 'float64': 'double',
+ 'string': 'string',
+ 'wstring': 'wstring',
+}
+
+
+def to_idl_literal(idl_type, value):
+ if idl_type[-1] == ']' or idl_type.startswith('sequence<'):
+ content = repr(tuple(value)).replace('\\', r'\\').replace('"', r'\"')
+ return f'"{content}"'
+
+ if 'boolean' == idl_type:
+ return 'TRUE' if value else 'FALSE'
+ if idl_type.startswith('string'):
+ return string_to_idl_string_literal(value)
+ if idl_type.startswith('wstring'):
+ return string_to_idl_wstring_literal(value)
+ return value
+
+
+def string_to_idl_string_literal(string):
+ """Convert string to character literal as described in IDL 4.2 section 7.2.6.3 ."""
+ estr = string.encode().decode('unicode_escape')
+ estr = estr.replace('"', r'\"')
+ return '"{0}"'.format(estr)
+
+
+def string_to_idl_wstring_literal(string):
+ return string_to_idl_string_literal(string)
+
+
+def get_include_file(base_type):
+ if base_type.is_primitive_type():
+ return None
+ return f'{base_type.pkg_name}/msg/{base_type.type}.idl'
+
+
+def get_idl_type(type_):
+ if isinstance(type_, str):
+ identifier = MSG_TYPE_TO_IDL[type_]
+ elif type_.is_primitive_type():
+ identifier = MSG_TYPE_TO_IDL[type_.type]
+ if (
+ identifier in ('string', 'wstring') and
+ type_.string_upper_bound is not None
+ ):
+ identifier += f'<{type_.string_upper_bound}>'
+ else:
+ identifier = f'{type_.pkg_name}::msg::{type_.type}'
+
+ if isinstance(type_, str) or not type_.is_array:
+ return identifier
+
+ if type_.is_fixed_size_array():
+ return f'{identifier}[{type_.array_size}]'
+
+ if not type_.is_upper_bound:
+ return f'sequence<{identifier}>'
+
+ return f'sequence<{identifier}, {type_.array_size}>'
diff --git a/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py b/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py
new file mode 100644
index 0000000000000000000000000000000000000000..6edb085019deb3b7361036686d4cb95b892f589f
--- /dev/null
+++ b/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py
@@ -0,0 +1,37 @@
+# ICE Revision: $Id$
+"""Analyzes lines with regular expressions and changes the phase if it fits"""
+
+import re
+
+from .GeneralLineAnalyzer import GeneralLineAnalyzer
+
+class PhaseChangerLineAnalyzer(GeneralLineAnalyzer):
+ """Parses lines for an arbitrary regular expression
+ and sets the phase if it fits
+ """
+
+
+ def __init__(self,
+ exp,
+ idNr=None):
+ """
+ :param name: name of the expression (needed for output
+ :param exp: that holds the phase name
+ :param idNr: number of the pattern group that is used as the phase name
+ """
+ GeneralLineAnalyzer.__init__(self,
+ doTimelines=False,
+ doFiles=False)
+
+ self.idNr=idNr
+ self.exp=re.compile(exp)
+ self.registerRegexp(self.exp)
+
+ def doAnalysis(self,line):
+ """Look for the pattern. If it matches set the phase name"""
+
+ m=self.exp.match(line.strip())
+ if m!=None:
+ self.setPhase(m.group(self.idNr))
+
+# Should work with Python3 and Python2
diff --git a/pool/shard002/Python/0026495_setup.py b/pool/shard002/Python/0026495_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..b74774698f67e47e0a08d992b725b0e5a87b32f5
--- /dev/null
+++ b/pool/shard002/Python/0026495_setup.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python
+# Copyright (c) 2012, 2013 Paul Tagliamonte
+#
+# 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 os
+import re
+import sys
+
+from setuptools import find_packages, setup
+
+PKG = "hua"
+VERSIONFILE = os.path.join(PKG, "version.py")
+verstr = "unknown"
+try:
+ verstrline = open(VERSIONFILE, "rt").read()
+except EnvironmentError:
+ pass # Okay, there is no version file.
+else:
+ VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]"
+ mo = re.search(VSRE, verstrline, re.M)
+ if mo:
+ __version__ = mo.group(1)
+ else:
+ msg = "if %s.py exists, it is required to be well-formed" % VERSIONFILE
+ raise RuntimeError(msg)
+
+long_description = """Hua is a Lisp to lua compiler. It gives lua
+simple and powerful meta programming ability."""
+
+install_requires = ['hy>=0.11.0', 'lupa>=1.1']
+if sys.version_info[:2] < (2, 7):
+ install_requires.append('argparse>=1.2.1')
+ install_requires.append('importlib>=1.0.2')
+if os.name == 'nt':
+ install_requires.append('pyreadline==2.0')
+
+setup(
+ name=PKG,
+ #version=__version__,
+ version="0.0.1",
+ install_requires=install_requires,
+ entry_points={
+ 'console_scripts': [
+ 'hua = hua.cmdline:hua_main',
+ 'huac = hua.cmdline:huac_main',
+ ]
+ },
+ packages=find_packages(exclude=['tests*']),
+ package_data={
+ 'hua.core': ['*.hy', '*.hua'],
+ },
+ author="Zhao Shenyang",
+ author_email="dev@zsy.im",
+ long_description=long_description,
+ description='Lisp to lua compiler.',
+ license="Expat",
+ url="",
+ platforms=['any'],
+ classifiers=[
+ "Development Status :: 2 - Pre-Alpha",
+ "Intended Audience :: Developers",
+ "License :: DFSG approved",
+ "License :: OSI Approved :: MIT License", # Really "Expat". Ugh.
+ "Operating System :: OS Independent",
+ "Programming Language :: Lisp",
+ "Programming Language :: lua",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2",
+ "Programming Language :: Python :: 2.6",
+ "Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.3",
+ "Programming Language :: Python :: 3.4",
+ "Topic :: Software Development :: Code Generators",
+ "Topic :: Software Development :: Compilers",
+ "Topic :: Software Development :: Libraries",
+ ]
+)
diff --git a/pool/shard002/Python/0026496_init__.py b/pool/shard002/Python/0026496_init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa50b92d7b9bf6f0d92a55f269ca9683c26e89c6
--- /dev/null
+++ b/pool/shard002/Python/0026496_init__.py
@@ -0,0 +1,38 @@
+# Copyright 2014-2015 Luc Saffre
+# This file is part of Lino Welfare.
+#
+# Lino Welfare is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Lino Welfare is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public
+# License along with Lino Welfare. If not, see
+# .
+"""
+This module is not actively used.
+"""
+
+from lino.api import ad
+
+from django.utils.translation import ugettext_lazy as _
+
+
+class Plugin(ad.Plugin):
+
+ verbose_name = _("Client projects")
+
+ def setup_config_menu(self, site, user_type, m):
+ m = m.add_menu(self.app_label, self.verbose_name)
+ m.add_action('projects.ProjectTypes')
+
+ def setup_explorer_menu(self, site, user_type, m):
+ m = m.add_menu(self.app_label, self.verbose_name)
+ m.add_action('projects.Projects')
+
+
diff --git a/pool/shard002/Python/0026498_convert_dict_to_c.py b/pool/shard002/Python/0026498_convert_dict_to_c.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4f89e8855f52ed518456fcdd1c1e83b83d7ec9b
--- /dev/null
+++ b/pool/shard002/Python/0026498_convert_dict_to_c.py
@@ -0,0 +1,47 @@
+## script to convert a lookup table of unicode characters from a javascript thing I found on
+## github into a lookup table that can be stored in the flash on the oggbox
+##
+## https://github.com/yvg/js-replace-diacritics/blob/master/replace-diacritics.js
+##
+
+fr = open("diacritical_marks_js.txt", "rb")
+
+d = fr.read()
+
+fr.close()
+
+fw = open("unicode_table.c", "wb")
+
+d = d.splitlines()
+cs = {}
+for line in d:
+ k,v = line.strip().split(":")
+ if k.strip("\'") == "":
+ k = "\x00"
+ v = v.strip("/[]ig,\\u")
+ v = v.split("\\u")
+ v = map(lambda x: int(x,16), v)
+
+ for c in v:
+ if(c > 127):
+ cs[c] = k
+
+keys = cs.keys()
+keys.sort()
+
+fw.write("#include \"unicode_table.h\"\n")
+fw.write("\n")
+fw.write("const int unicode_table_len = %d;\n" % len(keys))
+fw.write("\n")
+fw.write("const struct unicode_item unicode_table[] = {\n")
+for k in keys:
+ if len(cs[k]) == 1:
+ fw.write(" {%d, \"\\x%02x\"},\n" % (k, ord(cs[k])))
+ else:
+ fw.write(" {%d, \"\\x%02x\\x%02x\"},\n" % (k, ord(cs[k][0]), ord(cs[k][1])))
+
+print "Total characters:", len(cs)
+print "Highest value:", max(cs.keys())
+
+fw.write("};\n")
+fw.close()
\ No newline at end of file
diff --git a/pool/shard002/Python/0026501_conf.py b/pool/shard002/Python/0026501_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ba4b2b192ca82ff155bc8ddf66acdd9156bd9de
--- /dev/null
+++ b/pool/shard002/Python/0026501_conf.py
@@ -0,0 +1,207 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#
+# qpimage documentation build configuration file, created by
+# sphinx-quickstart on Tue Sep 26 17:55:31 2017.
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import os
+import os.path as op
+import sys
+
+import qpimage
+
+# include parent directory
+pdir = op.dirname(op.dirname(op.abspath(__file__)))
+sys.path.insert(0, pdir)
+# include extensions
+sys.path.append(op.abspath('extensions'))
+
+# RTD version
+if "READTHEDOCS_VERSION" in os.environ:
+ rtd_version = os.environ["READTHEDOCS_VERSION"]
+else:
+ rtd_version = "latest"
+# Used for linking to libraries in the qpimage universe
+rtd_link = "stable" if rtd_version != "latest" else "latest"
+
+# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#confval-autodoc_member_order
+# Order class attributes and functions in separate blocks
+autodoc_member_order = 'bysource'
+autoclass_content = 'both'
+
+# Display link to GitHub repo instead of doc on rtfd
+rst_prolog = """
+:github_url: https://github.com/RI-imaging/qpimage
+"""
+
+# -- General configuration ------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#
+# needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = ['sphinx.ext.autodoc',
+ 'sphinx.ext.autosummary',
+ 'sphinx.ext.graphviz',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.mathjax',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.napoleon',
+ 'sphinxcontrib.bibtex',
+ 'fancy_include',
+ 'github_changelog',
+ 'qpimage_defs',
+ ]
+
+# specify bibtex files (required for sphinxcontrib.bibtex>=2.0)
+bibtex_bibfiles = ['qpimage.bib']
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+#
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = 'qpimage'
+copyright = '2017, Paul Müller'
+author = 'Paul Müller'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+#
+# The full version, including alpha/beta/rc tags.
+# This gets 'version'
+version = qpimage.__version__
+release = version
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This patterns also effect to html_static_path and html_extra_path
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = False
+
+
+# -- Options for HTML output ----------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'sphinx_rtd_theme'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#
+# html_theme_options = {}
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+# html_static_path = ['_static']
+
+
+# -- Options for HTMLHelp output ------------------------------------------
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'qpimagedoc'
+
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+ # The paper size ('letterpaper' or 'a4paper').
+ #
+ # 'papersize': 'letterpaper',
+
+ # The font size ('10pt', '11pt' or '12pt').
+ #
+ # 'pointsize': '10pt',
+
+ # Additional stuff for the LaTeX preamble.
+ #
+ # 'preamble': '',
+
+ # Latex figure (float) alignment
+ #
+ # 'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (master_doc, 'qpimage.tex', 'qpimage Documentation',
+ 'Paul Müller', 'manual'),
+]
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (master_doc, 'qpimage', 'qpimage Documentation',
+ [author], 1)
+]
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (master_doc, 'qpimage', 'qpimage Documentation',
+ author, 'qpimage', 'Quantitative phase image management',
+ 'Scientific'),
+]
+
+
+# Example configuration for intersphinx: refer to the Python standard library.
+intersphinx_mapping = {
+ "python": ('https://docs.python.org/', None),
+ "numpy": ('http://docs.scipy.org/doc/numpy', None),
+ "scipy": ('https://docs.scipy.org/doc/scipy/reference/', None),
+ "skimage": ('http://scikit-image.org/docs/stable/', None),
+ "h5py": ('http://docs.h5py.org/en/stable/', None),
+ "lmfit": ('http://lmfit.github.io/lmfit-py/', None),
+ "nrefocus": ('http://nrefocus.readthedocs.io/en/'+rtd_link, None),
+ "drymass": ('http://drymass.readthedocs.io/en/'+rtd_link, None),
+ "qpsphere": ('http://qpsphere.readthedocs.io/en/'+rtd_link, None),
+ "qpformat": ('http://qpformat.readthedocs.io/en/'+rtd_link, None),
+ "cellsino": ('http://cellsino.readthedocs.io/en/'+rtd_link, None),
+}
diff --git a/pool/shard002/Python/0026508_cache_db.py b/pool/shard002/Python/0026508_cache_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc3eba810e53e5ad2290850ddea9945bf36f67d6
--- /dev/null
+++ b/pool/shard002/Python/0026508_cache_db.py
@@ -0,0 +1,50 @@
+import cache
+import db
+
+class Cache_Db:
+ mycache = None
+ def __init__(self, db_conn_details, cache_conn_details):
+ self.mydb = db.get_connection(db_conn_details)
+ self.mycache = cache.get_connection(cache_conn_details)
+
+
+ def insert(self, student):
+ print 'inserting <' + str(student) + '> into cache_db'
+ if self.mydb.insert(student.student_id, student) and \
+ self.mycache.insert(student.student_id, student):
+ return True
+ else: return False
+
+ def remove(self,student_id):
+ if self.mydb.remove(student_id) and self.mycache.remove(student_id):
+ return True
+ else:
+ return False
+
+ def get_by_id(self,student_id):
+ student = self.mycache.get_by_id(student_id)
+ if student == None:
+ student = self.mydb.get_by_id(student_id)
+ self.mycache.insert(student_id, student)
+ return student
+
+ """ Currently supports only cache!"""
+ def get_latest(self, num):
+ students = self.mycache.get_latest(num)
+ ## following code is needed only if we assume cache is not omnipotent
+ #if len(students) < num:
+ # students = db.get_latest(num)
+ # cache.upsert(students)
+ return students
+
+ """ Currently supports only db!"""
+ def get_by_attribute(self, attribute, value):
+ students = self.mydb.get_by_attribute(attribute, value)
+ return students
+
+ def _clear(self):
+ self.mydb._clear()
+ self.mycache._clear()
+
+def get_connection(db_conn_details, cache_conn_details):
+ return Cache_Db(db_conn_details, cache_conn_details)
diff --git a/pool/shard002/Python/0026509_html_soup.py b/pool/shard002/Python/0026509_html_soup.py
new file mode 100644
index 0000000000000000000000000000000000000000..7803655d48d777e3a75a874f98c0b96179ac8780
--- /dev/null
+++ b/pool/shard002/Python/0026509_html_soup.py
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Please note that the function 'make_request' is provided for your reference only.
+# You will not be able to to actually use it from within the Udacity web UI
+# All your changes should be in the 'extract_data' function
+
+from bs4 import BeautifulSoup
+import requests
+import json
+
+html_page = "page_source.html"
+
+
+def extract_data(page):
+ data = {"eventvalidation": "",
+ "viewstate": ""}
+ with open(page, "r") as html:
+ soup = BeautifulSoup(html)
+ _eventValid = soup.find(id="__EVENTVALIDATION")
+ data["eventvalidation"]=_eventValid["value"]
+ _viewState = soup.find(id="__VIEWSTATE")
+ data["viewstate"]=_viewState["value"]
+
+ return data
+
+
+def make_request(data):
+ eventvalidation = data["eventvalidation"]
+ viewstate = data["viewstate"]
+
+ r = requests.post("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2",
+ data={'AirportList': "BOS",
+ 'CarrierList': "VX",
+ 'Submit': 'Submit',
+ "__EVENTTARGET": "",
+ "__EVENTARGUMENT": "",
+ "__EVENTVALIDATION": eventvalidation,
+ "__VIEWSTATE": viewstate
+ })
+
+ return r.text
+
+
+def test():
+ data = extract_data(html_page)
+ assert data["eventvalidation"] != ""
+ assert data["eventvalidation"].startswith("/wEWjAkCoIj1ng0")
+ assert data["viewstate"].startswith("/wEPDwUKLTI")
+
+
+test()
\ No newline at end of file
diff --git a/pool/shard002/Python/0026512_compilemessages.py b/pool/shard002/Python/0026512_compilemessages.py
new file mode 100644
index 0000000000000000000000000000000000000000..483535ddf4512f211ca380b4b78ab02737ad90b3
--- /dev/null
+++ b/pool/shard002/Python/0026512_compilemessages.py
@@ -0,0 +1,122 @@
+from __future__ import print_function
+
+import os
+import re
+import ujson
+
+from typing import Any, Dict, List, Text
+
+from django.core.management.commands import compilemessages
+from django.conf import settings
+
+import polib
+
+from zerver.lib.i18n import with_language
+
+class Command(compilemessages.Command):
+
+ def handle(self, *args, **options):
+ # type: (*Any, **Any) -> None
+ if settings.PRODUCTION:
+ # HACK: When using upgrade-zulip-from-git, we're in a
+ # production environment where STATIC_ROOT will include
+ # past versions; this ensures we only process the current
+ # version
+ settings.STATIC_ROOT = os.path.join(settings.DEPLOY_ROOT, "static")
+ settings.LOCALE_PATHS = (os.path.join(settings.DEPLOY_ROOT, 'static/locale'),)
+ super(Command, self).handle(*args, **options)
+ self.extract_language_options()
+ self.create_language_name_map()
+
+ def create_language_name_map(self):
+ # type: () -> None
+ join = os.path.join
+ static_root = settings.STATIC_ROOT
+ path = join(static_root, 'locale', 'language_options.json')
+ output_path = join(static_root, 'locale', 'language_name_map.json')
+
+ with open(path, 'r') as reader:
+ languages = ujson.load(reader)
+ lang_list = []
+ for lang_info in languages['languages']:
+ name = lang_info['name']
+ lang_info['name'] = with_language(name, lang_info['code'])
+ lang_list.append(lang_info)
+
+ lang_list.sort(key=lambda lang: lang['name'])
+
+ with open(output_path, 'w') as output_file:
+ ujson.dump({'name_map': lang_list}, output_file, indent=4)
+
+ def get_po_filename(self, locale_path, locale):
+ # type: (Text, Text) -> Text
+ po_template = '{}/{}/LC_MESSAGES/django.po'
+ return po_template.format(locale_path, locale)
+
+ def get_json_filename(self, locale_path, locale):
+ # type: (Text, Text) -> Text
+ return "{}/{}/translations.json".format(locale_path, locale)
+
+ def extract_language_options(self):
+ # type: () -> None
+ locale_path = u"{}/locale".format(settings.STATIC_ROOT)
+ output_path = u"{}/language_options.json".format(locale_path)
+
+ data = {'languages': []} # type: Dict[str, List[Dict[str, Any]]]
+ lang_name_re = re.compile('"Language-Team: (.*?) \(')
+
+ locales = os.listdir(locale_path)
+ locales.append(u'en')
+ locales = list(set(locales))
+
+ for locale in locales:
+ info = {} # type: Dict[str, Any]
+ if locale == u'en':
+ data['languages'].append({
+ 'code': u'en',
+ 'name': u'English',
+ })
+ continue
+ filename = self.get_po_filename(locale_path, locale)
+ if not os.path.exists(filename):
+ continue
+
+ with open(filename, 'r') as reader:
+ result = lang_name_re.search(reader.read())
+ if result:
+ try:
+ name = result.group(1)
+ except Exception:
+ print("Problem in parsing {}".format(filename))
+ raise
+ else:
+ raise Exception("Unknown language %s" % (locale,))
+
+ percentage = self.get_translation_percentage(locale_path, locale)
+
+ info['name'] = name
+ info['code'] = locale
+ info['percent_translated'] = percentage
+
+ if info:
+ data['languages'].append(info)
+
+ with open(output_path, 'w') as writer:
+ ujson.dump(data, writer, indent=2)
+
+ def get_translation_percentage(self, locale_path, locale):
+ # type: (Text, Text) -> int
+
+ # backend stats
+ po = polib.pofile(self.get_po_filename(locale_path, locale))
+ not_translated = len(po.untranslated_entries())
+ total = len(po.translated_entries()) + not_translated
+
+ # frontend stats
+ with open(self.get_json_filename(locale_path, locale)) as reader:
+ for key, value in ujson.load(reader).items():
+ total += 1
+ if key == value:
+ not_translated += 1
+
+ return (total - not_translated) * 100 // total
diff --git a/pool/shard002/Python/0026526_gameobj_factor.py b/pool/shard002/Python/0026526_gameobj_factor.py
new file mode 100644
index 0000000000000000000000000000000000000000..6da2e060a5c7da926130dabd53323935665f86d2
--- /dev/null
+++ b/pool/shard002/Python/0026526_gameobj_factor.py
@@ -0,0 +1,174 @@
+# Flexlay - A Generic 2D Game Editor
+# Copyright (C) 2014 Ingo Ruhnke
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see .
+
+
+import csv
+import logging
+from collections import OrderedDict
+
+from flexlay import ObjectBrush, Config
+from .gameobj import *
+from .worldmap_object import *
+from .sprite import SuperTuxSprite
+
+
+def format_sprite_name(name):
+ """
+ sprite_name -> Sprite Name
+ """
+ name = name.replace("_", " ")
+ name = name.title()
+ return name
+
+
+class SuperTuxGameObjFactory:
+ """
+ identifier: section in the .stl file, used for load and save, most of the time, also for Drag&drop
+ sprite: used in the object selection and/or in the ObjMapSpriteObject
+ functor: creates the object
+
+ ObjectBrush(sprite, metadata)
+
+ See editor/supertux-editor/LevelObjects/Objects.cs
+ """
+ supertux_gui = None
+
+ def __init__(self):
+ GameObj.factory = self
+ self.objects = OrderedDict()
+ # List of (identifier, image, tag)
+ self.badguys = []
+ self.init_factories()
+
+ def create_gameobj_at(self, identifier, pos):
+ data = self.objects.get(identifier)
+ if data is None:
+ logging.warning("couldn't create: %r at %s" % (identifier, pos))
+ else:
+ _, constructor = data
+ obj = constructor()
+ obj.objmap_object.pos = pos
+ return obj
+
+ def create_gameobj(self, identifier, sexpr):
+ data = self.objects.get(identifier)
+ if data is None:
+ logging.warning("couldn't create: %r" % identifier)
+ else:
+ _, constructor = data
+ obj = constructor()
+ obj.read(sexpr)
+ obj.update()
+ return obj
+
+ def create_object_brushes(self):
+ """Creates Object Brushes for each sprite"""
+ # print("Creating object brushes...")
+ brushes = []
+ for identifier, (sprite, constructor) in self.objects.items():
+ if sprite is not None:
+ brush = ObjectBrush(SuperTuxSprite.from_file(os.path.join(Config.current.datadir, sprite)).get_sprite(),
+ identifier)
+ brushes.append(brush)
+ return brushes
+
+ def add_object(self, gameobj_class):
+ self.objects[gameobj_class.identifier] = (gameobj_class.sprite, gameobj_class)
+
+ def add_badguy(self, identifier, sprite, tag=None):
+ self.objects[identifier] = (sprite, lambda: BadGuy(identifier, sprite))
+ if tag:
+ self.badguys.append((identifier, sprite, tag))
+ else:
+ self.badguys.append((identifier, sprite))
+
+ def add_simple_object(self, identifier, sprite):
+ self.objects[identifier] = (sprite, lambda: SimpleObject(identifier, sprite))
+
+ def add_simple_tile(self, identifier, sprite):
+ self.objects[identifier] = (sprite, lambda: SimpleTileObject(identifier, sprite))
+
+ def add_particle_system(self, identifier, sprite, kind):
+ self.objects[identifier] = (sprite, lambda: ParticleSystem(kind, sprite))
+
+ def init_factories(self):
+ self.add_simple_object("point", "images/engine/editor/point.png")
+ self.add_simple_object("rock", "images/tiles/blocks/block11.png")
+ self.add_simple_object("heavycoin", "images/objects/coin/heavy_coin.png")
+
+ self.add_simple_tile("unstable_tile", "images/objects/unstable_tile/crumbling-1.png")
+
+ self.add_object(AmbientSound)
+ self.add_object(Background)
+ self.add_object(Camera)
+ self.add_object(Decal)
+ self.add_object(Dispenser)
+ self.add_object(SequenceTrigger)
+ self.add_object(ScriptTrigger)
+
+ self.add_object(BonusBlock)
+ self.add_object(Candle)
+ self.add_object(DartTrap)
+ self.add_object(Door)
+ self.add_object(GhostFlame)
+ self.add_object(Gradient)
+ self.add_object(InfoBlock)
+ self.add_object(InvisibleWall)
+ self.add_object(LevelTime)
+ self.add_object(Platform)
+ self.add_object(Powerup)
+ self.add_object(Pushbutton)
+ self.add_object(ResetPoint)
+ self.add_object(ScriptedObject)
+ self.add_object(SecretArea)
+ self.add_object(SpawnPoint)
+ self.add_object(Switch)
+ self.add_object(Torch)
+ self.add_object(Tux)
+ self.add_object(Trampoline)
+ self.add_object(WeakBlock)
+ self.add_object(WilloWisp)
+ self.add_object(Wind)
+
+ self.add_object(WorldmapLevel)
+ self.add_object(WorldmapSpawnpoint)
+ self.add_object(SpecialTile)
+
+ self.add_badguy("pneumatic-platform", "images/engine/editor/pneumaticplatform.png")
+ self.add_badguy("bicycle-platform", "images/engine/editor/bicycleplatform.png")
+ self.add_badguy("flying-platform", "images/objects/flying_platform/flying_platform.sprite")
+ self.add_badguy("hurting_platform", "images/objects/sawblade/sawblade.sprite")
+
+ self.add_particle_system("particles-clouds", "images/engine/editor/clouds.png", "clouds")
+ self.add_particle_system("particles-rain", "images/engine/editor/rain.png", "rain")
+ self.add_particle_system("particles-snow", "images/engine/editor/snow.png", "snow")
+
+ self.load_CSV()
+
+ def load_CSV(self):
+ with open('data/supertux/objects.csv', 'r') as csvfile:
+ reader = csv.reader(csvfile)
+ for row in reader:
+ identifier = row[0]
+ path = row[1]
+ name = format_sprite_name(identifier) if len(row) < 3 else row[2]
+ self.add_badguy(identifier, path)
+
+
+supertux_gameobj_factory = SuperTuxGameObjFactory()
+
+
+# EOF #
diff --git a/pool/shard002/Python/0026527_test_request_daily_builds.py b/pool/shard002/Python/0026527_test_request_daily_builds.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3c94e326ea7b94fecd33df4b4b3f2a04fc24cc0
--- /dev/null
+++ b/pool/shard002/Python/0026527_test_request_daily_builds.py
@@ -0,0 +1,50 @@
+# Copyright 2010-2012 Canonical Ltd. This software is licensed under the
+# GNU Affero General Public License version 3 (see the file LICENSE).
+
+"""Test the request_daily_builds script"""
+
+import transaction
+
+from lp.services.scripts.tests import run_script
+from lp.soyuz.enums import ArchivePurpose
+from lp.testing import TestCaseWithFactory
+from lp.testing.layers import ZopelessAppServerLayer
+
+
+class TestRequestDailyBuilds(TestCaseWithFactory):
+
+ layer = ZopelessAppServerLayer
+
+ def test_request_daily_builds(self):
+ """Ensure the request_daily_builds script requests daily builds."""
+ prod_branch = self.factory.makeProductBranch()
+ prod_recipe = self.factory.makeSourcePackageRecipe(
+ build_daily=True, is_stale=True, branches=[prod_branch])
+ pack_branch = self.factory.makePackageBranch()
+ pack_recipe = self.factory.makeSourcePackageRecipe(
+ build_daily=True, is_stale=True, branches=[pack_branch])
+ self.assertEqual(0, prod_recipe.pending_builds.count())
+ self.assertEqual(0, pack_recipe.pending_builds.count())
+ transaction.commit()
+ retcode, stdout, stderr = run_script(
+ 'cronscripts/request_daily_builds.py', [])
+ self.assertIn('Requested 2 daily builds.', stderr)
+ self.assertEqual(1, prod_recipe.pending_builds.count())
+ self.assertEqual(1, pack_recipe.pending_builds.count())
+ self.assertFalse(prod_recipe.is_stale)
+ self.assertFalse(pack_recipe.is_stale)
+
+ def test_request_daily_builds_oops(self):
+ """Ensure errors are handled cleanly."""
+ archive = self.factory.makeArchive(purpose=ArchivePurpose.COPY)
+ recipe = self.factory.makeSourcePackageRecipe(
+ daily_build_archive=archive, build_daily=True)
+ transaction.commit()
+ retcode, stdout, stderr = run_script(
+ 'cronscripts/request_daily_builds.py', [])
+ self.assertEqual(0, recipe.pending_builds.count())
+ self.assertIn('Requested 0 daily builds.', stderr)
+ self.oops_capture.sync()
+ self.assertEqual('NonPPABuildRequest', self.oopses[0]['type'])
+ self.assertEqual(
+ 1, len(self.oopses), "Too many OOPSes: %r" % (self.oopses,))
diff --git a/pool/shard002/Python/0026528_netcdf2tif.py b/pool/shard002/Python/0026528_netcdf2tif.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cf227bc170134b640ecd40fa50c75a13de49c55
--- /dev/null
+++ b/pool/shard002/Python/0026528_netcdf2tif.py
@@ -0,0 +1,127 @@
+"""Script to read NetCDF raster files, process and store as tif
+
+This requires scientific python
+"""
+
+import os
+import sys
+import numpy
+from Scientific.IO.NetCDF import NetCDFFile
+from safe.storage.raster import Raster
+from safe.storage.utilities import raster_geometry2geotransform
+
+
+def convert_netcdf2tif(filename, n):
+ """Convert netcdf to tif aggregating firsts n bands
+ """
+
+ if not isinstance(filename, basestring):
+ msg = 'Argument filename should be a string. I got %s' % filename
+ raise RuntimeError(msg)
+
+ basename, ext = os.path.splitext(filename)
+ msg = ('Expected NetCDF file with extension .nc - '
+ 'Instead I got %s' % filename)
+ if ext != '.nc':
+ raise RuntimeError(msg)
+
+ try:
+ n = int(n)
+ except:
+ msg = 'Argument N should be an integer. I got %s' % n
+ raise RuntimeError(msg)
+
+ print filename, n
+
+ # Read NetCDF file
+ fid = NetCDFFile(filename)
+ dimensions = fid.dimensions.keys()
+ variables = fid.variables.keys()
+
+ title = getattr(fid, 'title')
+ institution = getattr(fid, 'institution')
+ source = getattr(fid, 'source')
+ history = getattr(fid, 'history')
+ references = getattr(fid, 'references')
+ conventions = getattr(fid, 'Conventions')
+ coordinate_system = getattr(fid, 'coordinate_system')
+
+ print 'Read from %s' % filename
+ print 'Title: %s' % title
+ print 'Institution: %s' % institution
+ print 'Source: %s' % source
+ print 'History: %s' % history
+ print 'References: %s' % references
+ print 'Conventions: %s' % conventions
+ print 'Coordinate system: %s' % coordinate_system
+
+ print 'Dimensions: %s' % dimensions
+ print 'Variables: %s' % variables
+
+ # Get data
+ x = fid.variables['x'][:]
+ y = fid.variables['y'][:]
+ t = fid.variables['time'][:]
+ inundation_depth = fid.variables['Inundation_Depth'][:]
+
+ T = inundation_depth.shape[0] # Number of time steps
+ M = inundation_depth.shape[1] # Steps in the y direction
+ N = inundation_depth.shape[2] # Steps in the x direction
+
+ # Compute the max of the first n timesteps
+ A = numpy.zeros((M, N), dtype='float')
+ for i in range(n):
+ B = inundation_depth[i, :, :]
+ A = numpy.maximum(A, B)
+
+ geotransform = raster_geometry2geotransform(x, y)
+ print 'Geotransform', geotransform
+
+ # Write result to tif file
+ R = Raster(data=A,
+ projection="""PROJCS["DGN95 / Indonesia TM-3 zone 48.2",
+ GEOGCS["DGN95",
+ DATUM["Datum_Geodesi_Nasional_1995",
+ SPHEROID["WGS 84",6378137,298.257223563,
+ AUTHORITY["EPSG","7030"]],
+ TOWGS84[0,0,0,0,0,0,0],
+ AUTHORITY["EPSG","6755"]],
+ PRIMEM["Greenwich",0,
+ AUTHORITY["EPSG","8901"]],
+ UNIT["degree",0.01745329251994328,
+ AUTHORITY["EPSG","9122"]],
+ AUTHORITY["EPSG","4755"]],
+ UNIT["metre",1,
+ AUTHORITY["EPSG","9001"]],
+ PROJECTION["Transverse_Mercator"],
+ PARAMETER["latitude_of_origin",0],
+ PARAMETER["central_meridian",106.5],
+ PARAMETER["scale_factor",0.9999],
+ PARAMETER["false_easting",200000],
+ PARAMETER["false_northing",1500000],
+ AUTHORITY["EPSG","23834"],
+ AXIS["X",EAST],
+ AXIS["Y",NORTH]]""",
+ geotransform=geotransform,
+ keywords={'category': 'hazard',
+ 'subcategory': 'flood',
+ 'unit': 'm',
+ 'title': ('Hypothetical %d hour flood forecast '
+ 'in Jakarta' % n)})
+ R.write_to_file('%s_%d_hours.tif' % (basename, n))
+ print 'Success: %d hour forecast written to %s' % (n, R.filename)
+
+
+def usage():
+ s = 'python netcdf2tif.py .nc '
+ return s
+
+if __name__ == '__main__':
+
+ if len(sys.argv) != 3:
+ print usage()
+ else:
+ filename = sys.argv[1]
+ N = sys.argv[2]
+
+ convert_netcdf2tif(filename, N)
diff --git a/pool/shard002/Python/0026529_setup.py b/pool/shard002/Python/0026529_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b900659af3af7dbb286eafeeaa1e31d383c3ee2
--- /dev/null
+++ b/pool/shard002/Python/0026529_setup.py
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#This file is part of Tryton. The COPYRIGHT file at the top level of
+#this repository contains the full copyright notices and license terms.
+
+from setuptools import setup, find_packages
+import re
+
+info = eval(file('__tryton__.py').read())
+
+requires = ['BeautifulSoup < 3.1']
+for dep in info.get('depends', []):
+ if not re.match(r'(ir|res|workflow|webdav)(\W|$)', dep):
+ requires.append('trytond_' + dep)
+
+major_version, minor_version, _ = info.get('version', '0.0.1').split('.', 2)
+requires.append('trytond >= %s.%s' % (major_version, minor_version))
+requires.append('trytond < %s.%s' % (major_version, int(minor_version) + 1))
+
+setup(name='trytond_google_translate',
+ version=info.get('version', '0.0.1'),
+ description=info.get('description', ''),
+ author=info.get('author', ''),
+ author_email=info.get('email', ''),
+ url=info.get('website', ''),
+ download_url="http://downloads.tryton.org/" + \
+ info.get('version', '0.0.1').rsplit('.', 1)[0] + '/',
+ package_dir={'trytond.modules.google_translate': '.'},
+ packages=[
+ 'trytond.modules.google_translate',
+ ],
+ package_data={
+ 'trytond.modules.google_translate': info.get('xml', []) \
+ + info.get('translation', []),
+ },
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Environment :: Plugins',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: Financial and Insurance Industry',
+ 'Intended Audience :: Legal Industry',
+ 'Intended Audience :: Manufacturing',
+ 'License :: OSI Approved :: GNU General Public License (GPL)',
+ 'Natural Language :: English',
+ 'Natural Language :: French',
+ 'Natural Language :: German',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Office/Business',
+ ],
+ license='GPL-3',
+ install_requires=requires,
+ zip_safe=False,
+ entry_points="""
+ [trytond.modules]
+ google_translate = trytond.modules.google_translate
+ """,
+)
diff --git a/pool/shard002/Python/0026531_setup.py b/pool/shard002/Python/0026531_setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..e517d346f4bd11bdbae825df1b82ef49ebc113f7
--- /dev/null
+++ b/pool/shard002/Python/0026531_setup.py
@@ -0,0 +1,73 @@
+from setuptools import find_packages, setup, Extension
+import subprocess
+import sys
+import os
+
+def install_and_import(package):
+ import importlib
+ try:
+ importlib.import_module(package)
+ except ImportError:
+ import pip
+ pip.main(['install', package])
+ finally:
+ globals()[package] = importlib.import_module(package)
+
+# make sure numpy is installed, as we need numpy to compile the C extensions.
+# If numpy is not installed, automatically install it using pip.
+install_and_import('numpy')
+
+def generate_cython():
+ cwd = os.path.abspath(os.path.dirname(__file__))
+ print("Cythonizing sources")
+ p = subprocess.call([sys.executable, os.path.join(cwd,
+ 'build_tools',
+ 'cythonize.py'),
+ 'py_stringmatching'],
+ cwd=cwd)
+ if p != 0:
+ raise RuntimeError("Running cythonize failed!")
+
+
+if __name__ == "__main__":
+
+ no_frills = (len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or
+ sys.argv[1] in ('--help-commands',
+ 'egg_info', '--version',
+ 'clean')))
+
+ cwd = os.path.abspath(os.path.dirname(__file__))
+ if not os.path.exists(os.path.join(cwd, 'PKG-INFO')) and not no_frills:
+ # Generate Cython sources, unless building from source release
+ generate_cython()
+
+ # specify extensions that need to be compiled
+ extensions = [Extension("py_stringmatching.similarity_measure.cython_levenshtein",
+ ["py_stringmatching/similarity_measure/cython_levenshtein.c"],
+ include_dirs=[numpy.get_include()])]
+
+ # find packages to be included. exclude benchmarks.
+ packages = find_packages(exclude=["benchmarks"])
+
+ setup(
+ name='py_stringmatching',
+ version='0.1.1',
+ description='Python library for string matching.',
+ long_description="""
+ String matching is an important problem in many settings such as data integration, natural language processing,etc.
+ This package aims to implement most commonly used string matching measures.
+ """,
+ url='http://github.com/anhaidgroup/py_stringmatching',
+ author='Paul Suganthan G. C.',
+ author_email='paulgc@cs.wisc.edu',
+ license=['BSD'],
+ packages=packages,
+ install_requires=[
+ 'numpy >= 1.7.0',
+ 'six'
+ ],
+ ext_modules=extensions,
+ include_package_data=True,
+ zip_safe=False
+ )
+
diff --git a/pool/shard002/Python/0026534_testperf.py b/pool/shard002/Python/0026534_testperf.py
new file mode 100644
index 0000000000000000000000000000000000000000..7891eebba21ac5f84dfbcf1db82277b919ffb3ce
--- /dev/null
+++ b/pool/shard002/Python/0026534_testperf.py
@@ -0,0 +1,64 @@
+import unittest
+import numpy as np
+from .. import DataSet, perf, helpers
+
+class TestPerf(unittest.TestCase):
+ def setUp(self):
+ np.random.seed(1)
+ self.d = DataSet(
+ X=helpers.to_one_of_n([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0]),
+ Y=helpers.to_one_of_n([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]))
+
+ def test_class_loss(self):
+ d = self.d
+ targets = np.array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]).astype(bool)
+ d2 = DataSet(X=d.X + (0.1 * np.random.rand(*d.X.shape)), default=d)
+ np.testing.assert_equal(perf.class_loss(d), targets)
+ np.testing.assert_equal(perf.class_loss(d2), targets)
+
+ def test_accurracy(self):
+ self.assertEqual(perf.accuracy(self.d), (12 - 3) / 12.)
+
+ def test_conf_mat(self):
+ c = perf.conf_mat(self.d)
+ ct = np.array([[3, 1, 0], [0, 3, 1], [1, 0, 3]])
+ np.testing.assert_equal(c, ct)
+
+ def test_format_confusion_matrix(self):
+ c = perf.format_confmat(perf.conf_mat(self.d), self.d)
+ target = [['Label\\Pred.', 'class0', 'class1', 'class2'],
+ ['class0', 3, 1, 0],
+ ['class1', 0, 3, 1],
+ ['class2', 1, 0, 3]]
+ self.assertEqual(c, target)
+
+ def test_AUC(self):
+ d1 = DataSet(helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T,
+ helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T)
+ d0 = DataSet(helpers.to_one_of_n([1, 1, 0, 0, 0, 0]).T,
+ helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T)
+ dr = DataSet(helpers.to_one_of_n([1, 0, 1, 0, 1, 0]).T,
+ helpers.to_one_of_n([1, 1, 1, 1, 0, 0]).T)
+
+ self.assertEqual(perf.auc(d0), 0)
+ self.assertEqual(perf.auc(d1), 1)
+ self.assertEqual(perf.auc(dr), .5)
+
+ def test_mutinf(self):
+ d1 = DataSet(helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T,
+ helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T)
+ d0 = DataSet(helpers.to_one_of_n([1, 1, 1, 0, 0, 0]).T,
+ helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T)
+ dr = DataSet(helpers.to_one_of_n([1, 0, 1, 0, 1, 0]).T,
+ helpers.to_one_of_n([1, 1, 1, 1, 0, 0]).T)
+
+ self.assertAlmostEqual(perf.mutinf(d1), 1)
+ self.assertAlmostEqual(perf.mutinf(d0), 1)
+ self.assertAlmostEqual(perf.mutinf(dr), 0)
+
+ def test_mean_std(self):
+ ds = [DataSet(xs=np.random.rand(30, 2), ys=helpers.to_one_of_n(
+ np.arange(30) % 2).T) for i in range(20)]
+ m, s = perf.mean_std(perf.auc, ds)
+ self.assertAlmostEqual(m, 0.5, 1)
+ self.assertAlmostEqual(s, 0.1, 1)
diff --git a/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py b/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py
new file mode 100644
index 0000000000000000000000000000000000000000..34c627ebd5c88026031829a0ae93ca1a1c31ae1e
--- /dev/null
+++ b/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py
@@ -0,0 +1,180 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#
+# Copyright: (c) 2018, Mike Klebolt
+# 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: vmware_guest_tools_upgrade
+short_description: Module to upgrade VMTools
+version_added: 2.8
+description:
+ - This module upgrades the VMware Tools on Windows and Linux guests.
+requirements:
+ - "python >= 2.6"
+ - PyVmomi
+notes:
+ - In order to upgrade VMTools, please power on virtual machine before hand - either 'manually' or using module M(vmware_guest_powerstate).
+options:
+ name:
+ description:
+ - Name of the virtual machine to work with.
+ - This is required if C(UUID) is not supplied.
+ name_match:
+ description:
+ - If multiple virtual machines matching the name, use the first or last found.
+ default: 'first'
+ choices: ['first', 'last']
+ uuid:
+ description:
+ - UUID of the instance to manage if known, this is VMware's unique identifier.
+ - This is required if C(name) is not supplied.
+ folder:
+ description:
+ - Destination folder, absolute or relative path to find an existing guest.
+ - This is required, if C(name) is supplied.
+ - The folder should include the datacenter. ESX's datacenter is ha-datacenter
+ - 'Examples:'
+ - ' folder: /ha-datacenter/vm'
+ - ' folder: ha-datacenter/vm'
+ - ' folder: /datacenter1/vm'
+ - ' folder: datacenter1/vm'
+ - ' folder: /datacenter1/vm/folder1'
+ - ' folder: datacenter1/vm/folder1'
+ - ' folder: /folder1/datacenter1/vm'
+ - ' folder: folder1/datacenter1/vm'
+ - ' folder: /folder1/datacenter1/vm/folder2'
+ - ' folder: vm/folder2'
+ datacenter:
+ description:
+ - Destination datacenter where the virtual machine exists.
+ required: True
+extends_documentation_fragment: vmware.documentation
+author:
+ - Mike Klebolt (@MikeKlebolt)
+'''
+
+EXAMPLES = '''
+- name: Upgrade VMware Tools
+ vmware_guest_tools_upgrade:
+ hostname: "{{ vcenter_hostname }}"
+ username: "{{ vcenter_username }}"
+ password: "{{ vcenter_password }}"
+ datacenter: "{{ datacenter_name }}"
+ uuid: 421e4592-c069-924d-ce20-7e7533fab926
+ delegate_to: localhost
+'''
+
+RETURN = ''' # '''
+
+
+from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, wait_for_task
+from ansible.module_utils._text import to_native
+
+
+class PyVmomiHelper(PyVmomi):
+ def __init__(self, module):
+ super(PyVmomiHelper, self).__init__(module)
+
+ def upgrade_tools(self, vm):
+ result = {'failed': False, 'changed': False, 'msg': ''}
+ # Exit if VMware tools is already up to date
+ if vm.guest.toolsStatus == "toolsOk":
+ result.update(
+ changed=False,
+ msg="VMware tools is already up to date",
+ )
+ return result
+
+ # Fail if VM is not powered on
+ elif vm.summary.runtime.powerState != "poweredOn":
+ result.update(
+ failed=True,
+ msg="VM must be powered on to upgrade tools",
+ )
+ return result
+
+ # Fail if VMware tools is either not running or not installed
+ elif vm.guest.toolsStatus in ["toolsNotRunning", "toolsNotInstalled"]:
+ result.update(
+ failed=True,
+ msg="VMware tools is either not running or not installed",
+ )
+ return result
+
+ # If vmware tools is out of date, check major OS family
+ # Upgrade tools on Linux and Windows guests
+ elif vm.guest.toolsStatus == "toolsOld":
+ try:
+ if vm.guest.guestFamily in ["linuxGuest", "windowsGuest"]:
+ task = vm.UpgradeTools()
+ changed, err_msg = wait_for_task(task)
+ result.update(changed=changed, msg=to_native(err_msg))
+ else:
+ result.update(msg='Guest Operating System is other than Linux and Windows.')
+ return result
+ except Exception as exc:
+ result.update(
+ failed=True,
+ msg='Error while upgrading VMware tools %s' % to_native(exc),
+ )
+ return result
+ else:
+ result.update(
+ failed=True,
+ msg="VMware tools could not be upgraded",
+ )
+ return result
+
+
+def main():
+ argument_spec = vmware_argument_spec()
+ argument_spec.update(
+ name=dict(type='str'),
+ name_match=dict(type='str', choices=['first', 'last'], default='first'),
+ uuid=dict(type='str'),
+ folder=dict(type='str'),
+ datacenter=dict(type='str', required=True),
+ )
+ module = AnsibleModule(argument_spec=argument_spec,
+ required_one_of=[['name', 'uuid']])
+
+ if module.params['folder']:
+ # FindByInventoryPath() does not require an absolute path
+ # so we should leave the input folder path unmodified
+ module.params['folder'] = module.params['folder'].rstrip('/')
+
+ pyv = PyVmomiHelper(module)
+ # Check if the VM exists before continuing
+ vm = pyv.get_vm()
+
+ # VM already exists
+ if vm:
+ try:
+ result = pyv.upgrade_tools(vm)
+ if result['changed']:
+ module.exit_json(changed=result['changed'])
+ elif result['failed']:
+ module.fail_json(msg=result['msg'])
+ else:
+ module.exit_json(msg=result['msg'], changed=result['changed'])
+ except Exception as exc:
+ module.fail_json(msg='Unknown error: %s' % to_native(exc))
+ else:
+ module.fail_json(msg='Unable to find VM %s' % (module.params.get('uuid') or module.params.get('name')))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/pool/shard002/Python/0026538_gftools-gen-html.py b/pool/shard002/Python/0026538_gftools-gen-html.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b803f1a971594501077fc05c5bb6dae51a2a826
--- /dev/null
+++ b/pool/shard002/Python/0026538_gftools-gen-html.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+"""
+gftools gen-html aka diffbrowsers2.
+
+Generate html documents to proof a font family, or generate documents to
+diff two families.
+
+Examples:
+# Generate proofing documents for a single font
+gftools gen-html proof font1.ttf
+
+# Generate proofing documents for a family of fonts
+gftools gen-html proof font1.ttf font2.ttf font3.ttf
+
+# Output test pages to a dir
+gftools gen-html proof font1.ttf -o ~/Desktop/myFamily
+
+# Generate proofing documents and output images using Browserstack
+# (a subscription is required)
+gftools gen-html proof font1.ttf --imgs
+
+# Generate diff documents
+gftools gen-html diff -fb ./fonts_before/font1.ttf -fa ./fonts_after/font1.ttf
+"""
+from pkg_resources import resource_filename
+from gftools.html import HtmlProof, HtmlDiff
+import argparse
+
+
+def main():
+ html_templates_dir = resource_filename("gftools", "templates")
+
+ parser = argparse.ArgumentParser()
+ subparsers = parser.add_subparsers(
+ dest="command", required=True, metavar='"proof" or "diff"'
+ )
+
+ # Optional args which can be used in all subparsers
+ universal_options_parser = argparse.ArgumentParser(add_help=False)
+ universal_options_parser.add_argument(
+ "--pages",
+ nargs="+",
+ help="Choose which templates to populate. By default, all templates "
+ "are populated.",
+ )
+ universal_options_parser.add_argument(
+ "--pt-size", "-pt", help="Change pt size of document text", default=14
+ )
+ universal_options_parser.add_argument(
+ "--imgs",
+ action="store_true",
+ help="Output images using Browserstack.",
+ )
+ universal_options_parser.add_argument(
+ "--out", "-o", help="Output dir", default="diffbrowsers"
+ )
+ universal_options_parser.add_argument(
+ "--template-dir",
+ "-td",
+ help="HTML template directory. By default, gftools/templates is used.",
+ default=resource_filename("gftools", "templates"),
+ )
+
+ proof_parser = subparsers.add_parser(
+ "proof",
+ parents=[universal_options_parser],
+ help="Generate html proofing documents for a family",
+ )
+ proof_parser.add_argument("fonts", nargs="+")
+
+ diff_parser = subparsers.add_parser(
+ "diff",
+ parents=[universal_options_parser],
+ help="Generate html diff documents which compares two families. "
+ "Variable fonts can be compared against static fonts because we "
+ "match the fvar instances against the static fonts. To Match fonts "
+ "we use the font's name table records. For static fonts, the fullname "
+ "is used e.g 'Maven Pro Medium'. For variable fonts, the family name "
+ "+ fvar instance subfamilyname is used e.g 'Maven Pro' + 'Medium'.",
+ )
+ diff_parser.add_argument("--fonts-before", "-fb", nargs="+", required=True)
+ diff_parser.add_argument("--fonts-after", "-fa", nargs="+", required=True)
+
+ args = parser.parse_args()
+
+ if args.command == "proof":
+ html = HtmlProof(args.fonts, args.out, template_dir=args.template_dir)
+
+ elif args.command == "diff":
+ html = HtmlDiff(
+ args.fonts_before,
+ args.fonts_after,
+ args.out,
+ template_dir=args.template_dir,
+ )
+
+ html.build_pages(args.pages, pt_size=args.pt_size)
+
+ if args.imgs:
+ html.save_imgs()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pool/shard002/Python/0026539_log_reporter.py b/pool/shard002/Python/0026539_log_reporter.py
new file mode 100644
index 0000000000000000000000000000000000000000..58b27f69102410f0a0b34fc2e4acdb112082591f
--- /dev/null
+++ b/pool/shard002/Python/0026539_log_reporter.py
@@ -0,0 +1,88 @@
+from collections import deque
+from functools import wraps
+from threading import Condition, Event, Lock
+
+
+def chunked(buffer, chunk_size=4096):
+ """
+ Given a deque, chunk it up into ~chunk_size, but be aware of newline
+ termination as an intended goal.
+ """
+ result = ''
+ while buffer:
+ result += buffer.popleft()
+ while '\n' in result:
+ newline_pos = result.rfind('\n', 0, chunk_size)
+ if newline_pos == -1:
+ newline_pos = chunk_size
+ else:
+ newline_pos += 1
+ yield result[:newline_pos]
+ result = result[newline_pos:]
+
+ if result:
+ yield result
+
+
+def _locked(func):
+ @wraps(func)
+ def wrapped(self, *args, **kwargs):
+ with self.lock:
+ return func(self, *args, **kwargs)
+ return wrapped
+
+
+class ThreadSafeDeque(deque):
+ def __init__(self, *args, **kwargs):
+ self.lock = Lock()
+ super().__init__(*args, **kwargs)
+
+ append = _locked(deque.append)
+ appendleft = _locked(deque.appendleft)
+ clear = _locked(deque.clear)
+ extend = _locked(deque.extend)
+ extendleft = _locked(deque.extendleft)
+ pop = _locked(deque.pop)
+ popleft = _locked(deque.popleft)
+ remove = _locked(deque.remove)
+ reverse = _locked(deque.reverse)
+ rotate = _locked(deque.rotate)
+
+
+class LogReporter(object):
+ source = 'console'
+
+ def __init__(self, api, jobstep_id, source=None):
+ self.api = api
+ self.jobstep_id = jobstep_id
+ if source is not None:
+ self.source = source
+
+ self.buffer = ThreadSafeDeque()
+ self.done = Event()
+ self.cv = Condition()
+
+ def process(self):
+ with self.cv:
+ self.done.clear()
+ while not self.done.is_set() or self.buffer:
+ for chunk in chunked(self.buffer):
+ self.api.append_log(self.jobstep_id, {
+ 'text': chunk,
+ 'source': self.source,
+ })
+ if not self.done.is_set():
+ self.cv.wait(5)
+
+ def write(self, chunk):
+ with self.cv:
+ self.buffer.append(chunk)
+ self.cv.notifyAll()
+
+ def close(self):
+ with self.cv:
+ self.done.set()
+ self.cv.notifyAll()
+
+ def flush(self):
+ pass
diff --git a/pool/shard002/Python/0026541_darkamp.py b/pool/shard002/Python/0026541_darkamp.py
new file mode 100644
index 0000000000000000000000000000000000000000..51c845503a833ccfef8c85d17373854e34dd755d
--- /dev/null
+++ b/pool/shard002/Python/0026541_darkamp.py
@@ -0,0 +1,135 @@
+from twisted.internet.defer import gatherResults, maybeDeferred
+from twisted.protocols.amp import AMP, Command, Integer, String, Unicode
+
+class BranchLeafError(Exception):
+ """
+ You thought I was a branch.
+
+ FYI I am a leaf.
+ """
+
+class UnknownHashError(Exception):
+ """
+ The requested hash could not be found.
+
+ This probably isn't fatal.
+ """
+
+class Bai(Command):
+
+ arguments = []
+ response = []
+
+ requiresAnswer = False
+
+class CheckAPI(Command):
+
+ arguments = []
+ response = [("version", Integer())]
+
+class HazTree(Command):
+
+ arguments = [
+ ("hash", String()),
+ ("size", Integer()),
+ ]
+ response = [
+ ("first_hash", String()),
+ ("first_size", Integer()),
+ ("second_hash", String()),
+ ("second_size", Integer()),
+ ]
+ errors = {
+ BranchLeafError: "BRANCH_LEAF",
+ UnknownHashError: "UNKNOWN_HASH",
+ }
+
+class KThnxBai(Command):
+
+ arguments = []
+ response = []
+
+ requiresAnswer = False
+
+class SendPeze(Command):
+
+ arguments = [
+ ("hash", String()),
+ ("size", Integer()),
+ ("piece", Integer()),
+ ]
+ response = [
+ ("data", String()),
+ ]
+
+class Version(Command):
+
+ arguments = []
+ response = [("version", Unicode())]
+
+class DarkAMP(AMP):
+
+ remote_version = "Unknown"
+ remote_api = "Unknown"
+
+ def bai(self):
+ self.transport.loseConnection()
+ Bai.responder(bai)
+
+ def checkapi(self):
+ return {"version": 2}
+ CheckAPI.responder(checkapi)
+
+ def haztree(self, hash, size):
+ branch = self.factory.db.find_branch(hash, size)
+ if not branch:
+ raise UnknownHashError()
+ if branch.is_leaf:
+ raise BranchLeafError()
+ return {
+ "first_hash": branch.children[0].hash,
+ "first_size": branch.children[0].size,
+ "second_hash": branch.children[1].hash,
+ "second_size": branch.children[1].size,
+ }
+ HazTree.responder(haztree)
+
+ def kthnxbai(self):
+ self.callRemote(Bai)
+ self.transport.loseConnection()
+ KThnxBai.responder(kthnxbai)
+
+ def sendpeze(self, hash, size, piece):
+ d = maybeDeferred(self.factory.sendpeze, hash, size, piece)
+ @d.addCallback
+ def cb(data):
+ if data is None:
+ raise UnknownHashError("Couldn't find hash")
+ return {"data": data}
+ return d
+ SendPeze.responder(sendpeze)
+
+ def version(self):
+ return {"version": "Darklight pre-alpha"}
+ Version.responder(version)
+
+ def get_remote_info(self):
+ """
+ Get information about this connection.
+
+ Returns a Deferred which will fire with a tuple of API and version.
+ """
+
+ d1 = self.callRemote(CheckAPI)
+ @d1.addCallback
+ def cb1(d):
+ self.remote_api = d["version"]
+ return self.remote_api
+
+ d2 = self.callRemote(Version)
+ @d2.addCallback
+ def cb2(d):
+ self.remote_version = d["version"]
+ return self.remote_version
+
+ return gatherResults([d1, d2])
diff --git a/pool/shard002/Python/0026542_acceptance_tests.py b/pool/shard002/Python/0026542_acceptance_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebed4e9b4915a5a6642ca253d87d6fbedf57d984
--- /dev/null
+++ b/pool/shard002/Python/0026542_acceptance_tests.py
@@ -0,0 +1,40 @@
+import os.path
+import unittest
+import subprocess
+import logging
+
+logging.basicConfig(level=logging.INFO)
+
+php_interpreter = "php"
+python_interpreter = "python"
+if os.path.isfile("t/config.py"):
+ import config
+ php_interpreter = config.php
+ python_interpreter = config.python
+
+
+def comparison_factory(php_file_name):
+ def unit_test_actual(self):
+ subprocess.call([python_interpreter, "php2py.py", php_file_name])
+ php_result = subprocess.check_output([php_interpreter, php_file_name])
+ python_result = subprocess.check_output([python_interpreter, "php2py_run.py", php_file_name])
+ self.assertSequenceEqual(php_result.split(b"\n"), python_result.split(b"\n"))
+ return unit_test_actual
+
+
+class ComparisonTests(unittest.TestCase):
+ pass
+
+
+# TODO: autogeneration of list
+tests = [
+ "hello00",
+ "hello01",
+ "hello02",
+ "defines00",
+ "defines01",
+]
+for t in tests:
+ test_name = "test_{}".format(t)
+ php_file_name = "t/php/{}.php".format(t)
+ setattr(ComparisonTests, test_name, comparison_factory(php_file_name))
diff --git a/pool/shard002/Python/0026543_test_server.py b/pool/shard002/Python/0026543_test_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7e03855d943fc42bb20b648a9a8e7650e82d5b1
--- /dev/null
+++ b/pool/shard002/Python/0026543_test_server.py
@@ -0,0 +1,209 @@
+"""Tests for the HTTP server."""
+# -*- coding: utf-8 -*-
+# vim: set fileencoding=utf-8 :
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+import os
+import socket
+import tempfile
+import threading
+
+import pytest
+import requests
+import requests_unixsocket
+
+from .._compat import bton, ntob
+from .._compat import IS_MACOS
+from ..server import IS_UID_GID_RESOLVABLE, Gateway, HTTPServer
+from ..testing import (
+ ANY_INTERFACE_IPV4,
+ ANY_INTERFACE_IPV6,
+ EPHEMERAL_PORT,
+ get_server_client,
+)
+
+
+unix_only_sock_test = pytest.mark.skipif(
+ not hasattr(socket, 'AF_UNIX'),
+ reason='UNIX domain sockets are only available under UNIX-based OS',
+)
+
+
+non_macos_sock_test = pytest.mark.skipif(
+ IS_MACOS,
+ reason='Peercreds lookup does not work under macOS/BSD currently.',
+)
+
+
+@pytest.fixture
+def unix_sock_file():
+ """Check that bound UNIX socket address is stored in server."""
+ tmp_sock_fh, tmp_sock_fname = tempfile.mkstemp()
+
+ yield tmp_sock_fname
+
+ os.close(tmp_sock_fh)
+ os.unlink(tmp_sock_fname)
+
+
+def test_prepare_makes_server_ready():
+ """Check that prepare() makes the server ready, and stop() clears it."""
+ httpserver = HTTPServer(
+ bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT),
+ gateway=Gateway,
+ )
+
+ assert not httpserver.ready
+ assert not httpserver.requests._threads
+
+ httpserver.prepare()
+
+ assert httpserver.ready
+ assert httpserver.requests._threads
+ for thr in httpserver.requests._threads:
+ assert thr.ready
+
+ httpserver.stop()
+
+ assert not httpserver.requests._threads
+ assert not httpserver.ready
+
+
+def test_stop_interrupts_serve():
+ """Check that stop() interrupts running of serve()."""
+ httpserver = HTTPServer(
+ bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT),
+ gateway=Gateway,
+ )
+
+ httpserver.prepare()
+ serve_thread = threading.Thread(target=httpserver.serve)
+ serve_thread.start()
+
+ serve_thread.join(0.5)
+ assert serve_thread.is_alive()
+
+ httpserver.stop()
+
+ serve_thread.join(0.5)
+ assert not serve_thread.is_alive()
+
+
+@pytest.mark.parametrize(
+ 'ip_addr',
+ (
+ ANY_INTERFACE_IPV4,
+ ANY_INTERFACE_IPV6,
+ ),
+)
+def test_bind_addr_inet(http_server, ip_addr):
+ """Check that bound IP address is stored in server."""
+ httpserver = http_server.send((ip_addr, EPHEMERAL_PORT))
+
+ assert httpserver.bind_addr[0] == ip_addr
+ assert httpserver.bind_addr[1] != EPHEMERAL_PORT
+
+
+@unix_only_sock_test
+def test_bind_addr_unix(http_server, unix_sock_file):
+ """Check that bound UNIX socket address is stored in server."""
+ httpserver = http_server.send(unix_sock_file)
+
+ assert httpserver.bind_addr == unix_sock_file
+
+
+@pytest.mark.skip(reason="Abstract sockets don't work currently")
+@unix_only_sock_test
+def test_bind_addr_unix_abstract(http_server):
+ """Check that bound UNIX socket address is stored in server."""
+ unix_abstract_sock = b'\x00cheroot/test/socket/here.sock'
+ httpserver = http_server.send(unix_abstract_sock)
+
+ assert httpserver.bind_addr == unix_abstract_sock
+
+
+PEERCRED_IDS_URI = '/peer_creds/ids'
+PEERCRED_TEXTS_URI = '/peer_creds/texts'
+
+
+class _TestGateway(Gateway):
+ def respond(self):
+ req = self.req
+ conn = req.conn
+ req_uri = bton(req.uri)
+ if req_uri == PEERCRED_IDS_URI:
+ peer_creds = conn.peer_pid, conn.peer_uid, conn.peer_gid
+ self.send_payload('|'.join(map(str, peer_creds)))
+ return
+ elif req_uri == PEERCRED_TEXTS_URI:
+ self.send_payload('!'.join((conn.peer_user, conn.peer_group)))
+ return
+ return super(_TestGateway, self).respond()
+
+ def send_payload(self, payload):
+ req = self.req
+ req.status = b'200 OK'
+ req.ensure_headers_sent()
+ req.write(ntob(payload))
+
+
+@pytest.fixture
+def peercreds_enabled_server_and_client(http_server, unix_sock_file):
+ """Construct a test server with `peercreds_enabled`."""
+ httpserver = http_server.send(unix_sock_file)
+ httpserver.gateway = _TestGateway
+ httpserver.peercreds_enabled = True
+ return httpserver, get_server_client(httpserver)
+
+
+@unix_only_sock_test
+@non_macos_sock_test
+def test_peercreds_unix_sock(peercreds_enabled_server_and_client):
+ """Check that peercred lookup works when enabled."""
+ httpserver, testclient = peercreds_enabled_server_and_client
+
+ unix_base_uri = 'http+unix://{}'.format(
+ httpserver.bind_addr.replace('/', '%2F'),
+ )
+
+ expected_peercreds = os.getpid(), os.getuid(), os.getgid()
+ expected_peercreds = '|'.join(map(str, expected_peercreds))
+
+ with requests_unixsocket.monkeypatch():
+ peercreds_resp = requests.get(unix_base_uri + PEERCRED_IDS_URI)
+ peercreds_resp.raise_for_status()
+ assert peercreds_resp.text == expected_peercreds
+
+ peercreds_text_resp = requests.get(unix_base_uri + PEERCRED_TEXTS_URI)
+ assert peercreds_text_resp.status_code == 500
+
+
+@pytest.mark.skipif(
+ not IS_UID_GID_RESOLVABLE,
+ reason='Modules `grp` and `pwd` are not available '
+ 'under the current platform',
+)
+@unix_only_sock_test
+@non_macos_sock_test
+def test_peercreds_unix_sock_with_lookup(peercreds_enabled_server_and_client):
+ """Check that peercred resolution works when enabled."""
+ httpserver, testclient = peercreds_enabled_server_and_client
+ httpserver.peercreds_resolve_enabled = True
+
+ unix_base_uri = 'http+unix://{}'.format(
+ httpserver.bind_addr.replace('/', '%2F'),
+ )
+
+ import grp
+ import pwd
+ expected_textcreds = (
+ pwd.getpwuid(os.getuid()).pw_name,
+ grp.getgrgid(os.getgid()).gr_name,
+ )
+ expected_textcreds = '!'.join(map(str, expected_textcreds))
+ with requests_unixsocket.monkeypatch():
+ peercreds_text_resp = requests.get(unix_base_uri + PEERCRED_TEXTS_URI)
+ peercreds_text_resp.raise_for_status()
+ assert peercreds_text_resp.text == expected_textcreds
diff --git a/pool/shard002/Python/0026546_getBitcoinAddressDetails.py b/pool/shard002/Python/0026546_getBitcoinAddressDetails.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b188f025f0ac0f7c8329dec2215f91612f7b85e
--- /dev/null
+++ b/pool/shard002/Python/0026546_getBitcoinAddressDetails.py
@@ -0,0 +1,69 @@
+################################################################################
+#
+# Copyright 2015-2020 Félix Brezo and Yaiza Rubio
+#
+# This program is part of OSRFramework. You can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+#
+################################################################################
+
+
+import argparse
+import json
+import sys
+import urllib2
+
+
+def getBitcoinAddressDetails(address=None):
+ '''
+ Method that checks the presence of a Bitcoin Address in blockchain.info:
+{
+ "total_sent": 41301084,
+ "total_received": 52195147,
+ "final_balance": 10894063,
+ "address": "1APKyS2TEdFMjXjJfMCgavFtoWuv2QNXTw",
+ "hash160": "66f21efc754af07e87913db46bf24df2eb0d5075",
+...
+}
+
+ :param address: Bitcoin address to verify.
+
+ :return: Python structure for the json received. If nothing was found, it will return an empty dictionary.
+ '''
+ try:
+ apiURL = "https://blockchain.info/rawaddr/" + str(address)
+
+ # Accessing the HIBP API
+ data = urllib2.urlopen(apiURL).read()
+
+ # Reading the text data onto python structures
+ jsonData = json.loads(data)
+ return jsonData
+ except:
+ # No information was found, then we return a null entity
+ return {}
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description='A library that wraps the search about a Bitcoin address in blockchain.info.', prog='getBitcoinAddressDetails.py', epilog="", add_help=False)
+ # Adding the main options
+ # Defining the mutually exclusive group for the main options
+ parser.add_argument('-q', '--query', metavar='', action='store', help='query to be performed to blockchain.info.', required=True)
+
+ groupAbout = parser.add_argument_group('About arguments', 'Showing additional information about this program.')
+ groupAbout.add_argument('-h', '--help', action='help', help='shows this help and exists.')
+ groupAbout.add_argument('--version', action='version', version='%(prog)s 0.1.0', help='shows the version of the program and exists.')
+
+ args = parser.parse_args()
+
+ print(json.dumps(getBitcoinAddressDetails(address=args.query), indent=2))
diff --git a/pool/shard002/Python/0026547_func_fib_opt.py b/pool/shard002/Python/0026547_func_fib_opt.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab2effee43c29a6232cf6b61444e158d0f4b0de0
--- /dev/null
+++ b/pool/shard002/Python/0026547_func_fib_opt.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+# coding: utf-8
+#copyRight by heibanke
+import time
+
+def time_cost(f):
+ def _f(*arg, **kwarg):
+ start = time.clock()
+ a=f(*arg,**kwarg)
+ end = time.clock()
+ print f.__name__,"run cost time is ",end-start
+ return a
+ return _f
+
+
+def fib(n):
+ if n<=2:
+ return 1
+ else:
+ return fib(n-1)+fib(n-2)
+
+#@time_cost
+def fib_opt(n):
+ a,b,i=0,1,0
+
+ while i 2:
+ params = sys.argv[2:]
+ if os.path.exists(filename):
+ e.run_file(filename, params)
+
+
diff --git a/pool/shard002/Python/0026566_add_ms1_matrix.py b/pool/shard002/Python/0026566_add_ms1_matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..f08245e77eda0e3ce3912d92265c52cfe0699279
--- /dev/null
+++ b/pool/shard002/Python/0026566_add_ms1_matrix.py
@@ -0,0 +1,94 @@
+import os
+import pickle
+import numpy as np
+import sys
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings")
+
+import django
+django.setup()
+
+
+# This is to process files that have document names stored as mz_rt
+# it extracts the acutal mz and rt from the name and adds them to the metadata
+# This version works for multi-file experiments
+
+
+import jsonpickle
+import csv
+
+from basicviz.models import MultiFileExperiment,Experiment,Document,PeakSet,IntensityInstance
+
+if __name__ == '__main__':
+ multifile_experiment_name = sys.argv[1]
+ combined_file_name = sys.argv[2]
+
+ mfe = MultiFileExperiment.objects.get(name = multifile_experiment_name)
+ links = mfe.multilink_set.all()
+ print("Found {} links".format(len(links)))
+ experiments = [l.experiment for l in links]
+
+ raw_data = []
+ mz_list = []
+ rt_list = []
+ id_list = []
+ intensities = []
+ counts = []
+ count_hist = {}
+ with open(combined_file_name,'r') as f:
+ reader = csv.reader(f,delimiter='\t')
+ heads = reader.next()
+ for line in reader:
+ raw_data.append(line)
+ id = int(line[0])
+ mz = float(line[1])
+ rt = float(line[2])
+ new_intensity = [float(a) if not a=="" else 'nan' for a in line[3:]]
+ new_count = sum([1 for a in new_intensity if type(a) == float])
+ counts.append(new_count)
+ if new_count in count_hist:
+ count_hist[new_count] += 1
+ else:
+ count_hist[new_count] = 1
+ intensities.append(new_intensity)
+ mz_list.append(mz)
+ rt_list.append(rt)
+ id_list.append(id)
+
+ print("Loaded {} peaksets".format(len(raw_data)))
+ print("Diagnostics: intensities present:")
+ ch = zip(count_hist.keys(),count_hist.values())
+ ch = sorted(ch,key = lambda x: x[0])
+
+ for c,h in ch:
+ print(c,h)
+
+
+ # Hack the names about to make them match - this should be provided to the script
+ # to avoid errors...fix!
+
+ # MOdified for beer v urine where the names in the ms1 file are the start of the experiment names
+ experiment_match = {}
+ short_heads = []
+ for head in heads[3:]: # Iterate over the ms1 names
+ # s = head.split('_')
+ # new_name = s[0] + '_' + s[1] + '_' + s[2]
+ short_heads.append(head) # Use the full name from the file
+ match = [e for e in experiments if head in e.name]
+ experiment_match[head] = match[0]
+
+
+
+ print("Making the peakset objects")
+ for i,mz_value in enumerate(mz_list):
+ rt_value = rt_list[i]
+ new_peakset = PeakSet.objects.get_or_create(multifileexperiment = mfe,mz = mz_value,rt = rt_value,
+ original_file = combined_file_name,original_id = id_list[i])[0]
+ for j,intense in enumerate(intensities[i]):
+ if not intense == 'nan':
+ exper = experiment_match[short_heads[j]]
+ ii = IntensityInstance.objects.get_or_create(peakset = new_peakset,experiment = exper)[0]
+ ii.intensity = intense
+ ii.save()
+ if i%100 == 0:
+ print("Done: {}".format(i))
+
diff --git a/pool/shard002/Python/0026571_algorithm.py b/pool/shard002/Python/0026571_algorithm.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd7b1d2b65641706b548001998c5cc108c5b4362
--- /dev/null
+++ b/pool/shard002/Python/0026571_algorithm.py
@@ -0,0 +1,236 @@
+from __future__ import (absolute_import, division, print_function)
+from mantiddoc.directives.base import AlgorithmBaseDirective #pylint: disable=unused-import
+import os
+import re
+from six import iteritems
+
+REDIRECT_TEMPLATE = "redirect.html"
+
+DEPRECATE_USE_ALG_RE = re.compile(r"Use\s(([A-Z][a-zA-Z0-9]+)\s(version ([0-9])+)?)\s*instead.")
+
+# Maximum height in pixels a screenshot image
+# Any higher than this an an obvious gap starts to appear between the "Properties" header
+# and the rest
+SCREENSHOT_MAX_HEIGHT = 250
+
+#--------------------------------------------------------------------------
+class AlgorithmDirective(AlgorithmBaseDirective):
+
+ """
+ Inserts details of an algorithm by querying Mantid
+
+ Adds:
+ - A referenceable link for use with Sphinx ":ref:`` tags". If this is
+ the highest version of the algorithm being processed then a both
+ a versioned link is created and a non-versioned link
+ - A title
+ - A screenshot of the algorithm
+ - Table of contents
+
+ If the algorithms is deprecated then a warning is inserted.
+
+ It requires a SCREENSHOTS_DIR environment variable to be set to the
+ directory where a screenshot should be generated. If it is not set then
+ a RuntimeError occurs
+ """
+
+ required_arguments, optional_arguments = 0, 0
+
+ def execute(self):
+ """
+ Called by Sphinx when the ..algorithm:: directive is encountered
+ """
+ self._insert_pagetitle()
+ picture = self._create_screenshot()
+ self._insert_screenshot_link(picture)
+ self._insert_toc()
+ self._insert_deprecation_warning()
+
+ return []
+
+ def _insert_pagetitle(self):
+ """
+ Outputs a reference to the top of the algorithm's rst
+ of the form ".. _algm-AlgorithmName-vVersion:", so that
+ the page can be referenced using
+ :ref:`algm-AlgorithmName-version`. If this is the highest
+ version then it outputs a reference ".. _algm-AlgorithmName: instead
+
+ It then outputs a title for the page
+ """
+ from mantid.api import AlgorithmFactory
+
+ alg_name = self.algorithm_name()
+ version = self.algorithm_version()
+
+ # page reference must come directly before the title if it wants
+ # to be referenced without defining the link text. Here we put the
+ # specific version one first so that it always must be referenced
+ # using the full link text ":ref`LinkText `:"
+ self.add_rst(".. _algm-%s-v%d:\n\n" % (alg_name, version))
+ if AlgorithmFactory.highestVersion(alg_name) == version:
+ self.add_rst(".. _algm-%s:\n\n" % alg_name)
+
+ # title
+ title = "%s v%d" % (alg_name, version)
+ self.add_rst(self.make_header(title, True))
+ self.add_rst(u"\n.. index:: %s-v%d\n\n" % (alg_name, version))
+
+ def _insert_toc(self):
+ """
+ Outputs a title for the page
+ """
+ self.add_rst(".. contents:: Table of Contents\n :local:\n")
+
+ def _create_screenshot(self):
+ """
+ Creates a screenshot for the named algorithm in the "images/screenshots"
+ subdirectory.
+
+ The file will be named "algorithmname-vX_dlg.png", e.g. Rebin-v1_dlg.png
+
+ Returns:
+ screenshot: A mantiddoc.tools.Screenshot object
+ """
+ try:
+ screenshots_dir = self._screenshot_directory()
+ except RuntimeError:
+ return None
+
+ # Generate image
+ from mantiddoc.tools.screenshot import algorithm_screenshot
+ if not os.path.exists(screenshots_dir):
+ os.makedirs(screenshots_dir)
+
+ try:
+ picture = algorithm_screenshot(self.algorithm_name(), screenshots_dir, version=self.algorithm_version())
+ except RuntimeError as exc:
+ env = self.state.document.settings.env
+ env.warn(env.docname, "Unable to generate screenshot for '%s' - %s" % (self.algorithm_name(), str(exc)))
+ picture = None
+
+ return picture
+
+ def _insert_screenshot_link(self, picture):
+ """
+ Outputs an image link with a custom :class: style. The filename is
+ extracted from the path given and then a relative link to the
+ directory specified by the SCREENSHOTS_DIR environment variable from
+ the root source directory is formed.
+
+ Args:
+ picture (Screenshot): A Screenshot object
+ """
+ env = self.state.document.settings.env
+ format_str = ".. figure:: %s\n"\
+ " :class: screenshot\n"\
+ " :width: %dpx\n"\
+ " :align: right\n\n"\
+ " %s\n\n"
+
+ # Sphinx assumes that an absolute path is actually relative to the directory containing the
+ # conf.py file and a relative path is relative to the directory where the current rst file
+ # is located.
+ if picture:
+ screenshots_dir, filename = os.path.split(picture.imgpath)
+ # Find the width of the image
+ width, height = picture.width, picture.height
+
+ if height > SCREENSHOT_MAX_HEIGHT:
+ aspect_ratio = float(width)/height
+ width = int(SCREENSHOT_MAX_HEIGHT*aspect_ratio)
+ #endif
+
+ # relative path to image
+ rel_path = os.path.relpath(screenshots_dir, env.srcdir)
+ # This is a href link so is expected to be in unix style
+ rel_path = rel_path.replace("\\","/")
+ # stick a "/" as the first character so Sphinx computes relative location from source directory
+ path = "/" + rel_path + "/" + filename
+ else:
+ # use stock not found image
+ path = "/images/ImageNotFound.png"
+ width = 200
+
+ caption = "**" + self.algorithm_name() + "** dialog."
+ self.add_rst(format_str % (path, width, caption))
+
+ def _screenshot_directory(self):
+ """
+ Returns a full path where the screenshots should be generated. They are
+ put in a screenshots subdirectory of the main images directory in the source
+ tree. Sphinx then handles copying them to the final location
+
+ Arguments:
+ env (BuildEnvironment): Allows access to find the source directory
+
+ Returns:
+ str: A string containing a path to where the screenshots should be created. This will
+ be a filesystem path
+ """
+ try:
+ return os.environ["SCREENSHOTS_DIR"]
+ except:
+ raise RuntimeError("The '.. algorithm::' directive requires a SCREENSHOTS_DIR environment variable to be set.")
+
+ def _insert_deprecation_warning(self):
+ """
+ If the algorithm version is deprecated then construct a warning message
+ """
+ from mantid.api import DeprecatedAlgorithmChecker
+
+ checker = DeprecatedAlgorithmChecker(self.algorithm_name(), self.algorithm_version())
+ msg = checker.isDeprecated()
+ if len(msg) == 0:
+ return
+
+ # Check for message to use another algorithm an insert a link
+ match = DEPRECATE_USE_ALG_RE.search(msg)
+ if match is not None and len(match.groups()) == 4:
+ link_text = match.group(1)
+ alg_name = match.group(2)
+ version = match.group(4)
+ link = "algm-%s%s"
+ if version is not None:
+ link = link % (alg_name, "-v" + str(version))
+ else:
+ link = link % (alg_name, "")
+ replacement = "Use :ref:`%s <%s>` instead." % (link_text, link)
+ msg = DEPRECATE_USE_ALG_RE.sub(replacement, msg)
+ # endif
+
+ self.add_rst(".. warning:: %s" % msg)
+
+
+#------------------------------------------------------------------------------------------------------------
+
+def html_collect_pages(dummy_app):
+ """
+ Write out unversioned algorithm pages that redirect to the highest version of the algorithm
+ """
+ from mantid.api import AlgorithmFactory
+
+ template = REDIRECT_TEMPLATE
+ all_algs = AlgorithmFactory.getRegisteredAlgorithms(True)
+
+ for name, versions in iteritems(all_algs):
+ redirect_pagename = "algorithms/%s" % name
+ versions.sort()
+ highest_version = versions[-1]
+ target = "%s-v%d.html" % (name, highest_version)
+ context = {"name" : name, "target" : target}
+ yield (redirect_pagename, context, template)
+
+#------------------------------------------------------------------------------------------------------------
+
+def setup(app):
+ """
+ Setup the directives when the extension is activated
+
+ Args:
+ app: The main Sphinx application object
+ """
+ app.add_directive('algorithm', AlgorithmDirective)
+
+ # connect event html collection to handler
+ app.connect("html-collect-pages", html_collect_pages)
diff --git a/pool/shard002/Python/0026574_utils.py b/pool/shard002/Python/0026574_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d93296b36d1e53a2cacdad03e61238a3a26cd11
--- /dev/null
+++ b/pool/shard002/Python/0026574_utils.py
@@ -0,0 +1,28 @@
+import subprocess
+
+PACKAGE_DICT = {
+ 'pytraj': 'https://github.com/amber-md/pytraj',
+ 'cpptraj': 'https://github.com/amber-md/cpptraj',
+ 'parmed': 'https://github.com/parmed/parmed'
+}
+
+def get_version_from_github(package_name):
+ """
+ >>> get_version_from_github('pytraj')
+ v1.0.9
+ """
+ url = PACKAGE_DICT[package_name]
+ output = subprocess.check_output('git ls-remote --tags {}'.format(url).split())
+ tag_lines = output.decode().strip().split('\n')
+ versions_str = [tag_line.split('\t')[-1].split('/')[-1] for tag_line in tag_lines]
+ for index, version in enumerate(versions_str):
+ if version.startswith('v'):
+ if package_name in ['parmed']:
+ versions_str[index] = version.strip('v')
+ return sorted(versions_str)[-1]
+
+if __name__ == '__main__':
+ import sys
+ name = sys.argv[1].lower().strip()
+ name = name.strip('/')
+ print(get_version_from_github(name))
diff --git a/pool/shard002/Python/0026578_security-key-spaces.py b/pool/shard002/Python/0026578_security-key-spaces.py
new file mode 100644
index 0000000000000000000000000000000000000000..967603ce5a09279d1dc8ac35c7c4b32234726860
--- /dev/null
+++ b/pool/shard002/Python/0026578_security-key-spaces.py
@@ -0,0 +1,15 @@
+# Enter your code here. Read input from STDIN. Print output to STDOUT
+import sys
+arr=raw_input()
+e=int(raw_input())
+array=[]
+for i in range(0,len(arr)):
+ if(chr(ord(arr[i])+e)>'9'):
+ array.append(chr(ord(arr[i])+e-10))
+ elif(chr(ord(arr[i])+e)>'z'):
+ array.append(chr(ord(arr[i])+e-26))
+ else:
+ array.append(chr(ord(arr[i])+e))
+
+for i in range(0,len(arr)):
+ sys.stdout.write(array[i])
diff --git a/pool/shard002/Python/0026579_mslib.py b/pool/shard002/Python/0026579_mslib.py
new file mode 100644
index 0000000000000000000000000000000000000000..22683a74c22c96022ec01d97080d3aefb26bc069
--- /dev/null
+++ b/pool/shard002/Python/0026579_mslib.py
@@ -0,0 +1,64 @@
+"""SCons.Tool.mslib
+
+Tool-specific initialization for lib (MicroSoft library archiver).
+
+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 (c) 2001 - 2016 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+__revision__ = "src/engine/SCons/Tool/mslib.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
+
+import SCons.Defaults
+import SCons.Tool
+import SCons.Tool.msvs
+import SCons.Tool.msvc
+import SCons.Util
+
+from MSCommon import msvc_exists, msvc_setup_env_once
+
+def generate(env):
+ """Add Builders and construction variables for lib to an Environment."""
+ SCons.Tool.createStaticLibBuilder(env)
+
+ # Set-up ms tools paths
+ msvc_setup_env_once(env)
+
+ env['AR'] = 'lib'
+ env['ARFLAGS'] = SCons.Util.CLVar('/nologo')
+ env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES','$ARCOMSTR')}"
+ env['LIBPREFIX'] = ''
+ env['LIBSUFFIX'] = '.lib'
+
+def exists(env):
+ return msvc_exists()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4:
diff --git a/pool/shard002/Python/0026580_plugin.py b/pool/shard002/Python/0026580_plugin.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bc84a35b60c37d09aaca37f18c4716b8fa73d88
--- /dev/null
+++ b/pool/shard002/Python/0026580_plugin.py
@@ -0,0 +1,92 @@
+# Authored by Markus E.
+# https://github.com/mrksngl
+
+import datetime
+import logging
+import os
+import wordclock_tools.wordclock_colors as wcc
+import random
+
+
+class plugin:
+ """
+ A class to display the current time (default mode).
+ This default mode needs to be adapted to the hardware
+ layout of the wordclock (the choosen stencil) and is
+ the most essential time display mode of the wordclock.
+ """
+
+ def __init__(self, config):
+ """
+ Initializations for the startup of the current wordclock plugin
+ """
+ # Get plugin name (according to the folder, it is contained in)
+ self.name = os.path.dirname(__file__).split('/')[-1]
+ self.pretty_name = "Matrix with time"
+ self.description = "There is no spoon?"
+
+ self.purist = config.getboolean('plugin_time_default', 'purist')
+
+ self.bg_color = wcc.BLACK # default background color
+ self.word_color = wcc.WHITE # default word color
+ self.minute_color = wcc.WHITE # default minute color
+
+ self.threshold = 0.9
+
+ # Colors from black to green (and a bit gray-ish)
+ self.colors = []
+ for i in range(0, 8):
+ self.colors.append(wcc.Color(0, int(255.0 / 10 * i), 0))
+ self.colors.append(wcc.Color(50, 204, 30))
+ self.colors.append(wcc.Color(50, 230, 30))
+ self.colors.append(wcc.Color(80, 255, 60))
+
+ def run(self, wcd, wci):
+ """
+ Displays time until aborted by user interaction on pin button_return
+ """
+ # initialize rain start: set to end coordinate
+ rain = [20 for _ in range(0, 11)]
+ while True:
+ # Check if text needs to be displayed
+ if wcd.wst.ScrollText.checkIfScrollIsRequired(now):
+ wcd.showText(wcd.wst.scrolltext)
+
+ if not(wcc.scrollactive):
+ # Set background color
+ wcd.setColorToAll(self.bg_color, includeMinutes=True)
+ # Set current time
+ now = datetime.datetime.now()
+ # Returns indices, which represent the current time, when beeing illuminated
+ taw_indices = wcd.taw.get_time(now, self.purist)
+
+ wcd.setColorBy1DCoordinates(taw_indices, self.word_color)
+ wcd.setMinutes(now, self.minute_color)
+
+ for x, y in enumerate(rain):
+ if y == 20:
+ # reset y coordinate randomly
+ if random.random() > self.threshold:
+ rain[x] = 0
+ else:
+ # simple alpha blending using our predefined colors
+ y0 = max(y - 10, 0)
+ y1 = min(9, y)
+ ci = y0 - (y - 10)
+ for yi, yn in enumerate(range(y0, y1 + 1)):
+ color = self.colors[ci + yi]
+ wcd.setColorBy2DCoordinates(x, yn, color)
+ # advance y coordinate
+ rain[x] = y + 1
+
+ wcd.show()
+
+ event = wci.waitForEvent(0.1)
+ if event == wci.EVENT_BUTTON_RETURN \
+ or event == wci.EVENT_EXIT_PLUGIN \
+ or event == wci.EVENT_NEXT_PLUGIN_REQUESTED:
+ return
+ elif event == wci.EVENT_BUTTON_LEFT:
+ self.threshold = min(0.95, self.threshold + 0.05)
+ elif event == wci.EVENT_BUTTON_RIGHT:
+ self.threshold = max(0.7, self.threshold - 0.05)
diff --git a/pool/shard002/Python/0026581_gemcombineparam.py b/pool/shard002/Python/0026581_gemcombineparam.py
new file mode 100644
index 0000000000000000000000000000000000000000..f728fd93f52489b273963a6636c8571e536aac25
--- /dev/null
+++ b/pool/shard002/Python/0026581_gemcombineparam.py
@@ -0,0 +1,140 @@
+from astrodata.eti.pyrafetiparam import PyrafETIParam, IrafStdout
+from pyraf import iraf
+from astrodata.adutils import logutils
+
+log = logutils.get_logger(__name__)
+
+class GemcombineParam(PyrafETIParam):
+ """This class coordinates the ETI parameters as it pertains to the IRAF
+ task gemcombine directly.
+ """
+ rc = None
+ adinput = None
+ key = None
+ value = None
+ def __init__(self, rc=None, key=None, value=None):
+ """
+ :param rc: Used to store reduction information
+ :type rc: ReductionContext
+
+ :param key: A parameter name that is added as a dict key in prepare
+ :type key: any
+
+ :param value: A parameter value that is added as a dict value
+ in prepare
+ :type value: any
+ """
+ log.debug("GemcombineParam __init__")
+ PyrafETIParam.__init__(self, rc)
+ self.adinput = self.rc.get_inputs_as_astrodata()
+ self.key = key
+ self.value = value
+
+ def nonecheck(self, param=None):
+ if param is None or param == "None":
+ param = "none"
+ return param
+
+ def prepare(self):
+ log.debug("Gemcombine prepare()")
+ self.paramdict.update({self.key:self.value})
+
+
+class FlVardq(GemcombineParam):
+ rc = None
+ fl_vardq = None
+ def __init__(self, rc=None):
+ log.debug("FlVardq __init__")
+ GemcombineParam.__init__(self, rc)
+ self.fl_vardq = iraf.no
+ for ad in self.adinput:
+ if ad["VAR"]:
+ self.fl_vardq = iraf.yes
+ break
+
+ def prepare(self):
+ log.debug("FlVardq prepare()")
+ self.paramdict.update({"fl_vardq":self.fl_vardq})
+
+class FlDqprop(GemcombineParam):
+ rc = None
+ fl_dqprop = None
+ def __init__(self, rc=None):
+ log.debug("FlDqprop __init__")
+ GemcombineParam.__init__(self, rc)
+ self.fl_dqprop = iraf.no
+ for ad in self.adinput:
+ if ad["DQ"]:
+ self.fl_dqprop = iraf.yes
+ break
+
+ def prepare(self):
+ log.debug("FlDqprop prepare()")
+ self.paramdict.update({"fl_dqprop":self.fl_dqprop})
+
+class Masktype(GemcombineParam):
+ rc = None
+ masktype = None
+ def __init__(self, rc=None):
+ log.debug("Masktype __init__")
+ GemcombineParam.__init__(self, rc)
+ if rc["mask"]:
+ self.masktype = "goodvalue"
+ else:
+ self.masktype = "none"
+
+ def prepare(self):
+ log.debug("Masktype prepare()")
+ self.paramdict.update({"masktype":self.masktype})
+
+class Combine(GemcombineParam):
+ rc = None
+ operation = None
+ def __init__(self, rc=None):
+ log.debug("Combine __init__")
+ GemcombineParam.__init__(self, rc)
+ self.operation = self.nonecheck(rc["operation"])
+
+ def prepare(self):
+ log.debug("Combine prepare()")
+ self.paramdict.update({"combine":self.operation})
+
+class Nlow(GemcombineParam):
+ rc = None
+ nlow = None
+ def __init__(self, rc=None):
+ log.debug("Nlow __init__")
+ GemcombineParam.__init__(self, rc)
+ self.nlow = self.nonecheck(rc["nlow"])
+
+ def prepare(self):
+ log.debug("Nlow prepare()")
+ self.paramdict.update({"nlow":self.nlow})
+
+class Nhigh(GemcombineParam):
+ rc = None
+ nhigh = None
+ def __init__(self, rc=None):
+ log.debug("Nhigh __init__")
+ GemcombineParam.__init__(self, rc)
+ self.nhigh = self.nonecheck(rc["nhigh"])
+
+ def prepare(self):
+ log.debug("Nhigh prepare()")
+ self.paramdict.update({"nhigh":self.nhigh})
+
+class Reject(GemcombineParam):
+ rc = None
+ reject_method = None
+ def __init__(self, rc=None):
+ log.debug("Reject __init__")
+ GemcombineParam.__init__(self, rc)
+ self.reject_method = self.nonecheck(rc["reject_method"])
+
+ def prepare(self):
+ log.debug("Reject prepare()")
+ self.paramdict.update({"reject":self.reject_method})
+
+
+hardcoded_params = {'title':'DEFAULT','Stdout':IrafStdout(),'Stderr':IrafStdout()}
+
diff --git a/pool/shard002/Python/0026586_test_discover.py b/pool/shard002/Python/0026586_test_discover.py
new file mode 100644
index 0000000000000000000000000000000000000000..b66dc3418d47b493e0cf79a7637de85dbd736896
--- /dev/null
+++ b/pool/shard002/Python/0026586_test_discover.py
@@ -0,0 +1,54 @@
+# Copyright 2013 IBM Corp.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import os
+import sys
+
+from tempest.test_discover import plugins
+
+if sys.version_info >= (2, 7):
+ import unittest
+else:
+ import unittest2 as unittest
+
+
+def load_tests(loader, tests, pattern):
+ ext_plugins = plugins.TempestTestPluginManager()
+
+ suite = unittest.TestSuite()
+ base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
+ base_path = os.path.split(base_path)[0]
+ # Load local tempest tests
+ for test_dir in ['tempest/lis']:
+ full_test_dir = os.path.join(base_path, test_dir)
+ if not pattern:
+ suite.addTests(loader.discover(full_test_dir,
+ top_level_dir=base_path))
+ else:
+ suite.addTests(loader.discover(full_test_dir, pattern=pattern,
+ top_level_dir=base_path))
+
+ plugin_load_tests = ext_plugins.get_plugin_load_tests_tuple()
+ if not plugin_load_tests:
+ return suite
+
+ # Load any installed plugin tests
+ for plugin in plugin_load_tests:
+ test_dir, top_path = plugin_load_tests[plugin]
+ if not pattern:
+ suite.addTests(loader.discover(test_dir, top_level_dir=top_path))
+ else:
+ suite.addTests(loader.discover(test_dir, pattern=pattern,
+ top_level_dir=top_path))
+ return suite
diff --git a/pool/shard002/Python/0026588_test_inspector.py b/pool/shard002/Python/0026588_test_inspector.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb76a18a60c2c6100f15ba8ee9b4b6df7c08af1b
--- /dev/null
+++ b/pool/shard002/Python/0026588_test_inspector.py
@@ -0,0 +1,154 @@
+# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
+
+# Copyright 2020-2021 Florian Bruhin (The Compiler)
+#
+# This file is part of qutebrowser.
+#
+# qutebrowser 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.
+#
+# qutebrowser 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 qutebrowser. If not, see .
+
+import pytest
+
+from PyQt5.QtWidgets import QWidget
+
+from qutebrowser.browser import inspector
+from qutebrowser.misc import miscwidgets
+
+
+class FakeInspector(inspector.AbstractWebInspector):
+
+ def __init__(self,
+ inspector_widget: QWidget,
+ splitter: miscwidgets.InspectorSplitter,
+ win_id: int,
+ parent: QWidget = None) -> None:
+ super().__init__(splitter, win_id, parent)
+ self._set_widget(inspector_widget)
+ self._inspected_page = None
+ self.needs_recreate = False
+
+ def inspect(self, page):
+ self._inspected_page = page
+
+ def _needs_recreate(self):
+ return self.needs_recreate
+
+
+@pytest.fixture
+def webview_widget(blue_widget):
+ return blue_widget
+
+
+@pytest.fixture
+def inspector_widget(red_widget):
+ return red_widget
+
+
+@pytest.fixture
+def splitter(qtbot, webview_widget):
+ splitter = miscwidgets.InspectorSplitter(
+ win_id=0, main_webview=webview_widget)
+ qtbot.add_widget(splitter)
+ return splitter
+
+
+@pytest.fixture
+def fake_inspector(qtbot, splitter, inspector_widget,
+ state_config, mode_manager):
+ insp = FakeInspector(inspector_widget=inspector_widget,
+ splitter=splitter,
+ win_id=0)
+ qtbot.add_widget(insp)
+ return insp
+
+
+@pytest.mark.parametrize('position, splitter_count, window_visible', [
+ (inspector.Position.window, 1, True),
+ (inspector.Position.left, 2, False),
+ (inspector.Position.top, 2, False),
+])
+def test_set_position(position, splitter_count, window_visible,
+ fake_inspector, splitter):
+ fake_inspector.set_position(position)
+ assert splitter.count() == splitter_count
+ assert (fake_inspector.isWindow() and
+ fake_inspector.isVisible()) == window_visible
+
+
+def test_toggle_window(fake_inspector):
+ fake_inspector.set_position(inspector.Position.window)
+ for visible in [True, False, True]:
+ assert (fake_inspector.isWindow() and
+ fake_inspector.isVisible()) == visible
+ fake_inspector.toggle()
+
+
+def test_toggle_docked(fake_inspector, splitter, inspector_widget):
+ fake_inspector.set_position(inspector.Position.right)
+ splitter.show()
+ for visible in [True, False, True]:
+ assert inspector_widget.isVisible() == visible
+ fake_inspector.toggle()
+
+
+def test_implicit_toggling(fake_inspector, splitter, inspector_widget):
+ fake_inspector.set_position(inspector.Position.right)
+ splitter.show()
+ assert inspector_widget.isVisible()
+ fake_inspector.set_position(None)
+ assert not inspector_widget.isVisible()
+
+
+def test_position_saving(fake_inspector, state_config):
+ assert 'position' not in state_config['inspector']
+ fake_inspector.set_position(inspector.Position.left)
+ assert state_config['inspector']['position'] == 'left'
+
+
+@pytest.mark.parametrize('config_value, expected', [
+ (None, inspector.Position.right),
+ ('top', inspector.Position.top),
+])
+def test_position_loading(config_value, expected,
+ fake_inspector, state_config):
+ if config_value is None:
+ assert 'position' not in state_config['inspector']
+ else:
+ state_config['inspector']['position'] = config_value
+
+ fake_inspector.set_position(None)
+ assert fake_inspector._position == expected
+
+
+@pytest.mark.parametrize('hidden_again', [True, False])
+@pytest.mark.parametrize('needs_recreate', [True, False])
+def test_detach_after_toggling(hidden_again, needs_recreate,
+ fake_inspector, inspector_widget, splitter,
+ qtbot):
+ """Make sure we can still detach into a window after showing inline."""
+ fake_inspector.set_position(inspector.Position.right)
+ splitter.show()
+ assert inspector_widget.isVisible()
+
+ if hidden_again:
+ fake_inspector.toggle()
+ assert not inspector_widget.isVisible()
+
+ if needs_recreate:
+ fake_inspector.needs_recreate = True
+ with qtbot.waitSignal(fake_inspector.recreate):
+ fake_inspector.set_position(inspector.Position.window)
+ else:
+ with qtbot.assertNotEmitted(fake_inspector.recreate):
+ fake_inspector.set_position(inspector.Position.window)
+ assert fake_inspector.isVisible() and fake_inspector.isWindow()
diff --git a/pool/shard002/Python/0026599_sift.py b/pool/shard002/Python/0026599_sift.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3e97b525c5dd461ef36bb7a8816f926272a1cc4
--- /dev/null
+++ b/pool/shard002/Python/0026599_sift.py
@@ -0,0 +1,130 @@
+#encoding:utf-8
+
+from PIL import Image
+import os
+import cv2
+from numpy import *
+from pylab import *
+
+def read_features_from_file(imgname):
+ im = cv2.imread(imgname)
+ im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
+ sift = cv2.SIFT()
+
+ kp, desc = sift.detectAndCompute(im,None)
+ return kp, desc
+
+def plot_features(im,kp,circle=False):
+ """ show image with features. input: im (image as array),
+ locs (row, col, scale, orientation of each feature) """
+ if circle:
+ img=cv2.drawKeypoints(im,kp,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
+ else:
+ img=cv2.drawKeypoints(im,kp)
+
+ imshow(img)
+ axis('off')
+
+
+def match(desc1,desc2):
+ """ 对第一副图像的每个描述子,找到在第二幅图像中的匹配 OpenCV 版"""
+
+ dist_ratio = 0.6
+ desc1_size = desc1.shape
+
+ # BFMatcher with default params
+ bf = cv2.BFMatcher()
+ matches = bf.knnMatch(desc1,desc2, k=2)
+
+ # Apply ratio test
+ good = []
+ for m,n in matches:
+ if m.distance < dist_ratio*n.distance:
+ good.append(m)
+
+ # 仿照原书的输出
+ matchscores = zeros((desc1_size[0],1))
+ for m in good:
+ matchscores[m.queryIdx] = m.trainIdx
+
+ return matchscores
+
+
+def appendimages(im1,im2):
+ """ return a new image that appends the two images side-by-side."""
+
+ #select the image with the fewest rows and fill in enough empty rows
+ rows1 = im1.shape[0]
+ rows2 = im2.shape[0]
+
+ if rows1 < rows2:
+ im1 = concatenate((im1,zeros((rows2-rows1,im1.shape[1]))), axis=0)
+ elif rows1 > rows2:
+ im2 = concatenate((im2,zeros((rows1-rows2,im2.shape[1]))), axis=0)
+ #if none of these cases they are equal, no filling needed.
+
+ return concatenate((im1,im2), axis=1)
+
+
+def plot_matches(im1,im2,kp1,kp2,matchscores,show_below=True):
+ """ OpwnCV 版:
+ show a figure with lines joining the accepted matches
+ input: im1,im2 (images as arrays), locs1,locs2 (location of features),
+ matchscores (as output from 'match'), show_below (if images should be shown below). """
+
+ im3 = appendimages(im1,im2)
+ if show_below:
+ im3 = vstack((im3,im3))
+
+ # show image
+ imshow(im3)
+
+ # draw lines for matches
+ cols1 = im1.shape[1]
+ for i in range(len(matchscores)):
+ if matchscores[i] > 0:
+ pt1 = kp1[i].pt
+ pt2 = kp2[int(matchscores[i,0])].pt
+ plot([pt1[0],pt2[0]+cols1], [pt1[1], pt2[1]], 'c')
+ axis('off')
+
+
+def match_twosided(desc1,desc2):
+ """ two-sided symmetric version of match(). """
+
+ matches_12 = match(desc1,desc2)
+ matches_21 = match(desc2,desc1)
+
+ ndx_12 = matches_12.nonzero()[0]
+
+ #remove matches that are not symmetric
+ for n in ndx_12:
+ if matches_21[int(matches_12[n])] != n:
+ matches_12[n] = 0
+
+ return matches_12
+
+
+if __name__ == "__main__":
+
+ process_image('box.pgm','tmp.sift')
+ l,d = read_features_from_file('tmp.sift')
+
+ im = array(Image.open('box.pgm'))
+ figure()
+ plot_features(im,l,True)
+ gray()
+
+ process_image('scene.pgm','tmp2.sift')
+ l2,d2 = read_features_from_file('tmp2.sift')
+ im2 = array(Image.open('scene.pgm'))
+
+ m = match_twosided(d,d2)
+ figure()
+ plot_matches(im,im2,l,l2,m)
+
+ gray()
+ show()
+
+
+
diff --git a/pool/shard002/Python/0026600_test_btwix.py b/pool/shard002/Python/0026600_test_btwix.py
new file mode 100644
index 0000000000000000000000000000000000000000..feb2e864720c4edaa659b57d944c2c16a2220278
--- /dev/null
+++ b/pool/shard002/Python/0026600_test_btwix.py
@@ -0,0 +1,87 @@
+# -*- encoding: utf-8 -*-
+from ghosts.stringy.btwix import btwix, btwixes
+from ghosts.stringy.tests.major_general import major_general
+
+enz = '; '
+"""Default end string for the tests"""
+
+compleex = major_general.format(enz=enz)
+"""A complex string to test."""
+
+
+def test_btwix_simple():
+
+ simple = '
Hello
'
+
+ assert 'Hello' == btwix(simple, '
', '
', False)
+ assert simple == btwix(simple, '
', '
', True)
+
+
+def expected(starz, stwix, preappend):
+ """This returns the expected complete phrase of the test. Specify when your
+ `btwix` call has preappend==True.
+ """
+ if preappend:
+ return '{}{}{}'.format(starz, stwix, enz)
+ else:
+ return stwix
+
+
+def test_expected():
+
+ preappend = True
+ starz = 'know'
+ stwix = ' the kings of England'
+
+ assert expected(starz, stwix, preappend) == '{}{}{}'.format(starz, stwix, enz)
+ """The expected string will match the btwix string if correct: and
+ preappend starz and enz.
+ """
+
+ preappend = False
+ assert expected(starz, stwix, preappend) == stwix
+ """The expected string will match the btwix string if correct: and
+ preappend==False.
+ """
+
+
+def test_btwix_major_simple():
+
+ preappend = True
+ starz = 'know'
+ stwix = ' the kings of England'
+
+ assert btwix(compleex, starz, enz, preappend) == expected(starz, stwix, preappend)
+
+
+def test_btwix_major_array():
+
+ preappend = False
+ starz = 'quote'
+ stwixes = [
+ ' the fights historical',
+ ' in elegiacs all the crimes of Heliogabalus']
+
+ results = btwixes(compleex, starz, enz, preappend, 0)
+
+ assert results == stwixes
+
+
+
+def test_btwix_no_starz():
+
+ preappend = True
+ starz = ''
+ stwix = ' the kings of England'
+
+ assert btwix(compleex, starz, enz, preappend) == ''
+
+
+
+def test_btwix_no_enz():
+
+ preappend = True
+ starz = 'know'
+ stwix = ' the kings of England'
+
+ assert btwix(compleex, starz, '', preappend) == ''
diff --git a/pool/shard002/Python/0026603_test_gaussian_kde.py b/pool/shard002/Python/0026603_test_gaussian_kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..e76e6b58c41d15155edbde84b558aaf9abf409f1
--- /dev/null
+++ b/pool/shard002/Python/0026603_test_gaussian_kde.py
@@ -0,0 +1,63 @@
+"""Tests for Gaussian kernel density estimation."""
+import numpy
+import chaospy
+
+
+def test_gaussian_kde_1d_integration():
+ """Make sure that 1D distribution integration is correct."""
+ dist = chaospy.GaussianKDE([0, 1, 2])
+ t = numpy.mgrid[-2.6:4.6:2e5j]
+ scale = numpy.ptp(t)
+ assert numpy.isclose(numpy.mean(dist.pdf(t)*scale), 1.)
+ assert numpy.isclose(numpy.mean(t*dist.pdf(t)*scale), 1.)
+
+
+def test_gaussian_kde_2d_integration():
+ """Make sure that 2D distribution integration is correct."""
+ dist = chaospy.GaussianKDE([[0, 2], [2, 0]])
+ samples = dist.sample(1e4)
+ assert numpy.allclose(numpy.mean(samples, axis=-1), 1, rtol=1e-1)
+
+
+def test_gaussian_kde_rotation():
+ """Make sure rotation does not affect mapping."""
+ dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[0, 1, 2])
+ grid = numpy.mgrid[0.01:0.99:2j, 0.01:0.99:2j, 0.01:0.99:2j].reshape(3, 8)
+ inverse = dist.inv(grid)
+ assert numpy.allclose(dist.fwd(inverse), grid)
+ assert numpy.allclose(dist.pdf(inverse),
+ [2.550e-05, 2.553e-05, 2.553e-05, 2.552e-05,
+ 2.525e-05, 2.522e-05, 2.522e-05, 2.519e-05])
+ assert numpy.allclose(
+ inverse,
+ [[-1.38424, -1.38424, -1.38424, -1.38424, 3.19971, 3.19971, 3.19971, 3.19971],
+ [-1.31003, -1.31003, 3.31003, 3.31003, -1.48391, -1.48391, 1.48429, 1.48429],
+ [ 0.51571, 3.48391, -1.48391, 1.48413, -1.48391, 1.48429, -1.48391, 1.48429]],
+ rtol=1e-5,
+ )
+ dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[2, 1, 0])
+ inverse = dist.inv(grid)
+ assert numpy.allclose(dist.fwd(inverse), grid)
+ assert numpy.allclose(dist.pdf(inverse),
+ [2.550e-05, 2.525e-05, 2.553e-05, 2.522e-05,
+ 2.553e-05, 2.522e-05, 2.552e-05, 2.519e-05])
+ assert numpy.allclose(
+ inverse,
+ [[ 0.51571, -1.48391, -1.48391, -1.48391, 3.48391, 1.48429, 1.48413, 1.48429],
+ [-1.31003, -1.48391, 3.31003, 1.48429, -1.31003, -1.48391, 3.31003, 1.48429],
+ [-1.38424, 3.19971, -1.38424, 3.19971, -1.38424, 3.19971, -1.38424, 3.19971]],
+ rtol=1e-5,
+ )
+ dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[0, 2, 1])
+ inverse = dist.inv(grid)
+ assert numpy.allclose(dist.fwd(inverse), grid)
+ assert numpy.allclose(dist.pdf(inverse),
+ [2.550e-05, 2.553e-05, 2.553e-05, 2.552e-05,
+ 2.525e-05, 2.522e-05, 2.522e-05, 2.519e-05])
+ assert numpy.allclose(
+ inverse,
+ [[-1.38424, -1.38424, -1.38424, -1.38424, 3.19971, 3.19971, 3.19971, 3.19971],
+ [ 0.51571, -1.48391, 3.48391, 1.48413, -1.48391, -1.48391, 1.48429, 1.48429],
+ [-1.31003, 3.31003, -1.31003, 3.31003, -1.48391, 1.48429, -1.48391, 1.48429]],
+ rtol=1e-5,
+ )
diff --git a/pool/shard002/Python/0026614_test_bad_start.py b/pool/shard002/Python/0026614_test_bad_start.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb46a55b3912acc147c4a485421f9c7e4de29501
--- /dev/null
+++ b/pool/shard002/Python/0026614_test_bad_start.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python
+# Copyright (C) 2009-2014:
+# Gabes Jean, naparuba@gmail.com
+# Gerhard Lausser, Gerhard.Lausser@consol.de
+#
+# This file is part of Shinken.
+#
+# Shinken is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Shinken is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with Shinken. If not, see .
+
+#
+# This file is used to test reading and processing of config files
+#
+
+import os
+import tempfile
+import shutil
+
+from shinken_test import *
+
+import shinken.log as shinken_log
+
+from shinken.daemon import InvalidPidFile, InvalidWorkDir
+from shinken.http_daemon import PortNotFree
+
+from shinken.daemons.pollerdaemon import Poller
+from shinken.daemons.brokerdaemon import Broker
+from shinken.daemons.schedulerdaemon import Shinken
+from shinken.daemons.reactionnerdaemon import Reactionner
+from shinken.daemons.arbiterdaemon import Arbiter
+try:
+ import pwd, grp
+ from pwd import getpwnam
+ from grp import getgrnam
+
+
+ def get_cur_user():
+ return pwd.getpwuid(os.getuid()).pw_name
+
+ def get_cur_group():
+ return grp.getgrgid(os.getgid()).gr_name
+
+except ImportError, exp: # Like in nt system or Android
+ # temporary workaround:
+ def get_cur_user():
+ return os.getlogin()
+
+ def get_cur_group():
+ return os.getlogin()
+
+curdir = os.getcwd()
+
+daemons_config = {
+ Broker: "etc/core/daemons/brokerd.ini",
+ Poller: "etc/core/daemons/pollerd.ini",
+ Reactionner: "etc/core/daemons/reactionnerd.ini",
+ Shinken: "etc/core/daemons/schedulerd.ini",
+ Arbiter: ["etc/core/shinken.cfg"]
+}
+
+import random
+
+HIGH_PORT = random.randint(30000,65000)
+run = 0 # We will open some ports but not close them (yes it's not good) and
+# so we will open a range from a high port
+
+class template_Daemon_Bad_Start():
+
+ def setUp(self):
+ time_hacker.set_real_time()
+
+ def get_login_and_group(self, p):
+ try:
+ p.user = get_cur_user()
+ p.group = get_cur_group()
+ except OSError: # on some rare case, we can have a problem here
+ # so bypass it and keep default value
+ return
+
+ def create_daemon(self):
+ cls = self.daemon_cls
+ return cls(daemons_config[cls], False, True, False, None, '')
+
+
+ def get_daemon(self):
+ global run
+ os.chdir(curdir)
+ shinken_log.local_log = None # otherwise get some "trashs" logs..
+ d = self.create_daemon()
+
+ d.load_config_file()
+ d.http_backend = 'wsgiref'
+ d.port = HIGH_PORT + run # random high port, I hope no one is using it :)
+ run += 1
+ self.get_login_and_group(d)
+ return d
+
+
+ def test_bad_piddir(self):
+ print "Testing bad pidfile ..."
+ d = self.get_daemon()
+ d.workdir = tempfile.mkdtemp()
+ d.pidfile = os.path.join('/DONOTEXISTS', "daemon.pid")
+ prev_dir = os.getcwd()
+ self.assertRaises(InvalidPidFile, d.do_daemon_init_and_start, fake=True)
+ shutil.rmtree(d.workdir)
+ os.chdir(prev_dir)
+
+ def test_bad_workdir(self):
+ print("Testing bad workdir ... mypid=%d" % (os.getpid()))
+ d = self.get_daemon()
+ d.workdir = '/DONOTEXISTS'
+ prev_dir = os.getcwd()
+ self.assertRaises(InvalidWorkDir, d.do_daemon_init_and_start, fake=True)
+ d.do_stop()
+ os.chdir(prev_dir)
+
+ def test_port_not_free(self):
+ print("Testing port not free ... mypid=%d" % (os.getpid()))
+ d1 = self.get_daemon()
+ d1.workdir = tempfile.mkdtemp()
+ prev_dir = os.getcwd() # We have to remember where we are to get back after
+ d1.do_daemon_init_and_start(fake=True)
+ new_dir = os.getcwd() # We have to remember this one also
+ os.chdir(prev_dir)
+ os.unlink(os.path.join(new_dir, d1.pidfile)) ## so that second poller will not see first started poller
+ d2 = self.get_daemon()
+ d2.workdir = d1.workdir
+ # TODO: find a way in Pyro4 to get the port
+ if hasattr(d1.http_daemon, 'port'):
+ d2.port = d1.http_daemon.port
+ self.assertRaises(PortNotFree, d2.do_daemon_init_and_start, fake=True)
+ d2.do_stop()
+ d1.do_stop()
+ try:
+ os.unlink(d1.pidfile)
+ except Exception:
+ pass
+ if hasattr(d1, 'local_log'):
+ os.unlink(os.path.join(d1.workdir, d1.local_log))
+ shutil.rmtree(d1.workdir)
+ os.chdir(prev_dir) # Back to previous dir for next test!
+
+
+class Test_Broker_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
+ daemon_cls = Broker
+
+
+class Test_Scheduler_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
+ daemon_cls = Shinken
+
+
+class Test_Poller_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
+ daemon_cls = Poller
+
+
+class Test_Reactionner_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
+ daemon_cls = Reactionner
+
+
+class Test_Arbiter_Bad_Start(template_Daemon_Bad_Start, ShinkenTest):
+ daemon_cls = Arbiter
+
+ def create_daemon(self):
+ """ arbiter is always a bit special .. """
+ cls = self.daemon_cls
+ #Arbiter(config_files, is_daemon, do_replace, verify_only, debug, debug_file, profile)
+ return cls(daemons_config[cls], False, True, False, False, None, '')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/pool/shard002/Python/0026616_logfile.py b/pool/shard002/Python/0026616_logfile.py
new file mode 100644
index 0000000000000000000000000000000000000000..86475c811edeca48b9d64e4977df60cb4e853db5
--- /dev/null
+++ b/pool/shard002/Python/0026616_logfile.py
@@ -0,0 +1,98 @@
+# This file is part of Buildbot. Buildbot is free software: you can
+# redistribute it and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation, version 2.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+# details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 51
+# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Copyright Buildbot Team Members
+
+from __future__ import absolute_import
+from __future__ import print_function
+from future.utils import itervalues
+from future.utils import text_type
+
+from twisted.internet import defer
+from twisted.python import log
+
+from buildbot import util
+from buildbot.util import lineboundaries
+
+
+class FakeLogFile(object):
+
+ def __init__(self, name, step):
+ self.name = name
+ self.header = ''
+ self.stdout = ''
+ self.stderr = ''
+ self.lbfs = {}
+ self.finished = False
+ self.step = step
+ self.subPoint = util.subscription.SubscriptionPoint("%r log" % (name,))
+
+ def getName(self):
+ return self.name
+
+ def subscribe(self, callback):
+ log.msg("NOTE: fake logfile subscription never produces anything")
+ return self.subPoint.subscribe(callback)
+
+ def _getLbf(self, stream, meth):
+ try:
+ return self.lbfs[stream]
+ except KeyError:
+ def wholeLines(lines):
+ if not isinstance(lines, text_type):
+ lines = lines.decode('utf-8')
+ if self.name in self.step.logobservers:
+ for obs in self.step.logobservers[self.name]:
+ getattr(obs, meth)(lines)
+ lbf = self.lbfs[stream] = \
+ lineboundaries.LineBoundaryFinder(wholeLines)
+ return lbf
+
+ def addHeader(self, text):
+ self.header += text
+ self._getLbf('h', 'headerReceived').append(text)
+ return defer.succeed(None)
+
+ def addStdout(self, text):
+ self.stdout += text
+ self._getLbf('o', 'outReceived').append(text)
+ return defer.succeed(None)
+
+ def addStderr(self, text):
+ self.stderr += text
+ self._getLbf('e', 'errReceived').append(text)
+ return defer.succeed(None)
+
+ def isFinished(self):
+ return self.finished
+
+ def waitUntilFinished(self):
+ log.msg("NOTE: fake waitUntilFinished doesn't actually wait")
+ return defer.Deferred()
+
+ def flushFakeLogfile(self):
+ for lbf in itervalues(self.lbfs):
+ lbf.flush()
+
+ def finish(self):
+ self.flushFakeLogfile()
+ self.finished = True
+ return defer.succeed(None)
+
+ def fakeData(self, header='', stdout='', stderr=''):
+ if header:
+ self.header += header
+ if stdout:
+ self.stdout += stdout
+ if stderr:
+ self.stderr += stderr
diff --git a/pool/shard002/Python/0026617_splitter.py b/pool/shard002/Python/0026617_splitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec5512e8793819480bb3a4e52c807966b5882dcc
--- /dev/null
+++ b/pool/shard002/Python/0026617_splitter.py
@@ -0,0 +1,96 @@
+import astropy.table
+import numpy as np
+import pandas as pd
+
+def load(path,
+ x_cols=('psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z'),
+ y_col='redshift',
+ class_col='class',
+ class_val='Galaxy'):
+
+ # Cast x_cols to list so Pandas doesn't complain…
+ x_cols_l = list(x_cols)
+
+ if '.h5' in path or '.hdf' in path:
+ # We have an HDF5 file
+ data = pd.read_hdf(path)
+ return data, x_cols_l, y_col
+
+ elif '.fits' in path:
+ x_cols_l = ['umag', 'gmag', 'rmag', 'imag', 'zmag']
+ y_col = 'z'
+ dat = astropy.table.Table.read(path, format='fits')
+ data = dat.to_pandas()
+ data = data[x_cols_l + [y_col]]
+ return data, x_cols_l, y_col
+
+ else:
+ # We have a CSV file
+
+ data_iter = pd.read_csv(
+ path,
+ iterator=True,
+ chunksize=100000,
+ usecols=x_cols_l + [y_col, class_col])
+
+ # Filter out anything that is not a galaxy without loading the
+ # whole file into memory.
+ data = pd.concat(chunk[chunk[class_col] == class_val]
+ for chunk in data_iter)
+
+ return data[x_cols_l + [y_col]], x_cols_l, y_col
+
+
+def split(data, train_n, test_n):
+ data, x_cols, y_col = data
+
+ X_data = data[x_cols].as_matrix()
+ y_data = data[y_col].as_matrix()
+ assert X_data.shape[0] == y_data.shape[0] == data.shape[0]
+ assert X_data.shape[1] == data.shape[1] - 1
+ assert len(y_data.shape) == 1
+
+ # Shuffle data
+ indices = list(range(data.shape[0]))
+ np.random.seed(seed=12)
+ np.random.shuffle(indices)
+ X_data = X_data[indices]
+ y_data = y_data[indices]
+
+ train_X = X_data[:train_n]
+ test_X = X_data[train_n:train_n+test_n]
+ train_y = y_data[:train_n]
+ test_y = y_data[train_n:train_n+test_n]
+
+ assert train_X.shape == (train_n, len(x_cols))
+ assert train_y.shape == (train_n,)
+ assert test_X.shape == (test_n, len(x_cols))
+ assert test_y.shape == (test_n,)
+
+ return (train_X, train_y), (test_X, test_y)
+
+
+def save_as_hdf5(path, data):
+ data.to_hdf(path, '👀')
+
+
+if __name__ == '__main__':
+ # TODO: Use argparse if this gets any longer...
+
+ import sys
+ if len(sys.argv) == 3 and sys.argv[2] == '--test':
+ # Tiny test
+ data = load(sys.argv[1])
+ data = split(data, 2, 1)
+ print(data)
+ elif len(sys.argv) == 4 and sys.argv[2] == '--to-hdf5':
+ data, _, _ = load(sys.argv[1])
+ save_as_hdf5(sys.argv[3], data)
+ elif len(sys.argv) == 3 and sys.argv[2] == '--time':
+ from time import time
+ start_time = time()
+ data = load(sys.argv[1])
+ total_time = time() - start_time
+ print('Took {}s'.format(total_time))
+ else:
+ print('No options specified.')
diff --git a/pool/shard002/Python/0026624_conf.py b/pool/shard002/Python/0026624_conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e85615cf8a130425b97b505ec1507a9482d2ff3
--- /dev/null
+++ b/pool/shard002/Python/0026624_conf.py
@@ -0,0 +1,45 @@
+"""
+Get and process settings for django-OneTimePassword
+"""
+from django.conf import settings
+from importlib import import_module
+
+
+# Default settings
+
+OTP_TIME_SYNCHRONIZED_GENERATOR = 'django_OneTimePassword.generators.sha512TS'
+
+OTP_TIME_SYNCHRONIZED_OPTIONS = {
+ 'length': 6,
+ 'interval': 30,
+ 'dictionary': "abcdefghijklmnopqrstuvwxyz0123456789"
+}
+
+
+# Try get settings
+
+OTP_TIME_SYNCHRONIZED_GENERATOR = getattr(
+ settings,
+ 'OTP_TIME_SYNCHRONIZED_GENERATOR',
+ OTP_TIME_SYNCHRONIZED_GENERATOR
+)
+
+OTP_TIME_SYNCHRONIZED_OPTIONS = getattr(
+ settings,
+ 'OTP_TIME_SYNCHRONIZED_OPTIONS',
+ OTP_TIME_SYNCHRONIZED_OPTIONS
+)
+
+
+# Get password generatos
+
+OTP_TIME_SYNCHRONIZED_GENERATOR = getattr(
+ import_module('.'.join(OTP_TIME_SYNCHRONIZED_GENERATOR.split('.')[:-1])),
+ OTP_TIME_SYNCHRONIZED_GENERATOR.split('.')[-1]
+)
+
+# Instance generators
+
+OTP_TIME_SYNCHRONIZED = OTP_TIME_SYNCHRONIZED_GENERATOR(
+ **OTP_TIME_SYNCHRONIZED_OPTIONS
+)
diff --git a/pool/shard002/Python/0026625_utils.py b/pool/shard002/Python/0026625_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab5ccfbf0583539207d7c8de985429a418295bc8
--- /dev/null
+++ b/pool/shard002/Python/0026625_utils.py
@@ -0,0 +1,224 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright (c) 2011 OpenStack, 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.
+
+"""Compute-related Utilities and helpers."""
+
+import netaddr
+
+import nova.context
+from nova import db
+from nova import exception
+from nova import flags
+from nova import log
+from nova import network
+from nova.network import model as network_model
+from nova import notifications
+from nova.notifier import api as notifier_api
+from nova import utils
+
+
+FLAGS = flags.FLAGS
+LOG = log.getLogger(__name__)
+
+
+def notify_usage_exists(context, instance_ref, current_period=False,
+ ignore_missing_network_data=True,
+ system_metadata=None, extra_usage_info=None):
+ """Generates 'exists' notification for an instance for usage auditing
+ purposes.
+
+ :param current_period: if True, this will generate a usage for the
+ current usage period; if False, this will generate a usage for the
+ previous audit period.
+
+ :param ignore_missing_network_data: if True, log any exceptions generated
+ while getting network info; if False, raise the exception.
+ :param system_metadata: system_metadata DB entries for the instance,
+ if not None. *NOTE*: Currently unused here in trunk, but needed for
+ potential custom modifications.
+ :param extra_usage_info: Dictionary containing extra values to add or
+ override in the notification if not None.
+ """
+
+ audit_start, audit_end = notifications.audit_period_bounds(current_period)
+
+ bw = notifications.bandwidth_usage(instance_ref, audit_start,
+ ignore_missing_network_data)
+
+ if system_metadata is None:
+ try:
+ system_metadata = db.instance_system_metadata_get(
+ context, instance_ref.uuid)
+ except exception.NotFound:
+ system_metadata = {}
+
+ # add image metadata to the notification:
+ image_meta = notifications.image_meta(system_metadata)
+
+ extra_info = dict(audit_period_beginning=str(audit_start),
+ audit_period_ending=str(audit_end),
+ bandwidth=bw, image_meta=image_meta)
+
+ if extra_usage_info:
+ extra_info.update(extra_usage_info)
+
+ notify_about_instance_usage(context, instance_ref, 'exists',
+ system_metadata=system_metadata, extra_usage_info=extra_info)
+
+
+def legacy_network_info(network_model):
+ """
+ Return the legacy network_info representation of the network_model
+ """
+ def get_ip(ip):
+ if not ip:
+ return None
+ return ip['address']
+
+ def fixed_ip_dict(ip, subnet):
+ if ip['version'] == 4:
+ netmask = str(subnet.as_netaddr().netmask)
+ else:
+ netmask = subnet.as_netaddr()._prefixlen
+
+ return {'ip': ip['address'],
+ 'enabled': '1',
+ 'netmask': netmask,
+ 'gateway': get_ip(subnet['gateway'])}
+
+ def get_meta(model, key, default=None):
+ if 'meta' in model and key in model['meta']:
+ return model['meta'][key]
+ return default
+
+ def convert_routes(routes):
+ routes_list = []
+ for route in routes:
+ r = {'route': str(netaddr.IPNetwork(route['cidr']).network),
+ 'netmask': str(netaddr.IPNetwork(route['cidr']).netmask),
+ 'gateway': get_ip(route['gateway'])}
+ routes_list.append(r)
+ return routes_list
+
+ network_info = []
+ for vif in network_model:
+ if not vif['network'] or not vif['network']['subnets']:
+ continue
+ network = vif['network']
+
+ # NOTE(jkoelker) The legacy format only supports one subnet per
+ # network, so we only use the 1st one of each type
+ # NOTE(tr3buchet): o.O
+ v4_subnets = []
+ v6_subnets = []
+ for subnet in vif['network']['subnets']:
+ if subnet['version'] == 4:
+ v4_subnets.append(subnet)
+ else:
+ v6_subnets.append(subnet)
+
+ subnet_v4 = None
+ subnet_v6 = None
+
+ if v4_subnets:
+ subnet_v4 = v4_subnets[0]
+
+ if v6_subnets:
+ subnet_v6 = v6_subnets[0]
+
+ if not subnet_v4:
+ raise exception.NovaException(
+ message=_('v4 subnets are required for legacy nw_info'))
+
+ routes = convert_routes(subnet_v4['routes'])
+
+ should_create_bridge = get_meta(network, 'should_create_bridge',
+ False)
+ should_create_vlan = get_meta(network, 'should_create_vlan', False)
+ gateway = get_ip(subnet_v4['gateway'])
+ dhcp_server = get_meta(subnet_v4, 'dhcp_server')
+ network_dict = dict(bridge=network['bridge'],
+ id=network['id'],
+ cidr=subnet_v4['cidr'],
+ cidr_v6=subnet_v6['cidr'] if subnet_v6 else None,
+ vlan=get_meta(network, 'vlan'),
+ injected=get_meta(network, 'injected', False),
+ multi_host=get_meta(network, 'multi_host',
+ False),
+ bridge_interface=get_meta(network,
+ 'bridge_interface'))
+ # NOTE(tr3buchet): the 'ips' bit here is tricky, we support a single
+ # subnet but we want all the IPs to be there
+ # so we use the v4_subnets[0] and its IPs are first
+ # so that eth0 will be from subnet_v4, the rest of the
+ # IPs will be aliased eth0:1 etc and the gateways from
+ # their subnets will not be used
+ info_dict = dict(label=network['label'],
+ broadcast=str(subnet_v4.as_netaddr().broadcast),
+ mac=vif['address'],
+ vif_uuid=vif['id'],
+ rxtx_cap=get_meta(network, 'rxtx_cap', 0),
+ dns=[get_ip(ip) for ip in subnet_v4['dns']],
+ ips=[fixed_ip_dict(ip, subnet)
+ for subnet in v4_subnets
+ for ip in subnet['ips']],
+ should_create_bridge=should_create_bridge,
+ should_create_vlan=should_create_vlan,
+ dhcp_server=dhcp_server)
+ if routes:
+ info_dict['routes'] = routes
+
+ if gateway:
+ info_dict['gateway'] = gateway
+
+ if v6_subnets:
+ if subnet_v6['gateway']:
+ info_dict['gateway_v6'] = get_ip(subnet_v6['gateway'])
+ info_dict['ip6s'] = [fixed_ip_dict(ip, subnet_v6)
+ for ip in subnet_v6['ips']]
+
+ network_info.append((network_dict, info_dict))
+ return network_info
+
+
+def notify_about_instance_usage(context, instance, event_suffix,
+ network_info=None, system_metadata=None,
+ extra_usage_info=None, host=None):
+ """
+ Send a notification about an instance.
+
+ :param event_suffix: Event type like "delete.start" or "exists"
+ :param network_info: Networking information, if provided.
+ :param system_metadata: system_metadata DB entries for the instance,
+ if provided.
+ :param extra_usage_info: Dictionary containing extra values to add or
+ override in the notification.
+ :param host: Compute host for the instance, if specified. Default is
+ FLAGS.host
+ """
+
+ if not host:
+ host = FLAGS.host
+
+ if not extra_usage_info:
+ extra_usage_info = {}
+
+ usage_info = notifications.usage_from_instance(context, instance,
+ network_info, system_metadata, **extra_usage_info)
+
+ notifier_api.notify(context, 'compute.%s' % host,
+ 'compute.instance.%s' % event_suffix,
+ notifier_api.INFO, usage_info)
diff --git a/pool/shard002/Python/0026627_ppa.py b/pool/shard002/Python/0026627_ppa.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5283f82f2c648348e1f76b8242df9e2467f6a89
--- /dev/null
+++ b/pool/shard002/Python/0026627_ppa.py
@@ -0,0 +1,124 @@
+# Setup
+import time
+import webbrowser
+import md5
+import sys
+import hashlib
+import random
+from urllib2 import urlopen
+from yahoo_finance import Share
+
+
+# Makes the webbrowser command
+def open_link(link):
+ webbrowser.open(link)
+ speak("Opening web browser")
+ pause(2)
+
+# Makes the pause command
+def pause(seconds):
+ time.sleep(seconds)
+
+# Makes the speak command
+def speak(text):
+ print(text)
+
+# Makes the warning command
+def warning(warning_text):
+ print(warning_text)
+
+# Makes the sha1 encrypter command
+def encrypt_sha1(textsha1):
+ hash_objectsha1 = hashlib.sha1(textsha1)
+ hex_digsha1 = hash_objectsha1.hexdigest()
+ speak("Proccesing...")
+ speak(hex_digsha1)
+
+# Makes the sha224 encrypter command
+def encrypt_sha224(textsha224):
+ hash_objectsha224 = hashlib.sha224(textsha224)
+ hex_digsha224 = hash_objectsha224.hexdigest()
+ speak("Proccesing...")
+ speak(hex_digsha224)
+
+# Makes the sha256 encrypter command
+def encrypt_sha256(textsha256):
+ hash_objectsha256 = hashlib.sha256(textsha256)
+ hex_digsha256 = hash_objectsha256.hexdigest()
+ speak("Proccesing...")
+ speak(hex_digsha256)
+
+# Initializes the time and date
+time.ctime()
+current_time = time.strftime('%H:%M')
+current_date = time.strftime('%d %B %Y')
+
+speak("Hello! i am PAI, your owm personal assistant")
+
+# Main program
+var = 1
+while var == 1:
+ input = raw_input(">>>")
+ if input in {"help", "help me", }:
+ file = open('bin/commands.txt', 'r')
+ file_contents = file.read()
+ print (file_contents)
+ file.close()
+ elif input in {"exit", "kill", "escape"}:
+ speak("Killing PPA...")
+ sys.exit()
+ elif input in {"time", "the current time", "current time"}:
+ speak("The current time is " + current_time)
+ elif input in {"search", "google"}:
+ speak("What do you want to Google?")
+ google = raw_input(">>>")
+ google.replace(" ", "+")
+ open_link('https://www.google.nl/#q=' + google.replace(" ", "+"))
+ elif input in {"hello ppa", "hello", "hello!", "Hello PPA"}:
+ print("Hello human!")
+ elif input in {"date", "the current date", "current date"}:
+ print("The current date is " + current_date)
+ elif input in {"what is your favorite song?", "favorite song"}:
+ speak("I really like human music!")
+ pause(1)
+ speak("Let me show it to you!")
+ open_link('https://www.youtube.com/watch?v=q4k1IK_o59M')
+ elif input in {"im hungry", "i want to eat", "restaurant"}:
+ speak("What do you want to eat?")
+ eat = raw_input(">>>")
+ open_link('https://www.google.nl/maps/search/' + eat.replace(" ", "+"))
+ elif input in {"what is my ip?", "my ip", "ip", "what's my ip?", "whats my ip?", "whats my ip", "what is my ip"}:
+ ip = urlopen('http://ip.42.pl/raw').read()
+ speak(ip)
+ elif input in {"md5"}:
+ speak("What do you want to hash to MD5?")
+ md5_string = raw_input('>>>')
+ speak("proccesing...")
+ speak( md5.md5(md5_string).hexdigest() )
+ elif input in {"sha1"}:
+ speak("What do you want to encrypt?")
+ sha1_input = raw_input('>>>')
+ encrypt_sha1(sha1_input)
+ elif input in {"sha1"}:
+ speak("What do you want to encrypt?")
+ sha1_input = raw_input('>>>')
+ encrypt_sha1(sha1_input)
+ elif input in {"sha224"}:
+ speak("What do you want to encrypt?")
+ sha224_input = raw_input('>>>')
+ encrypt_sha224(sha224_input)
+ elif input in {"sha256"}:
+ speak("What do you want to encrypt?")
+ sha256_input = raw_input('>>>')
+ encrypt_sha256(sha256_input)
+ elif input in {"what is per?"}:
+ speak("A huge dumbass...")
+ pause(2)
+ speak("Take my word for it")
+ elif input in {"random", "random number"}:
+ mini = raw_input
+ print random.randrange(1,100)
+ elif input in {"stocks", "stock", "stock prices"}:
+
+ else:
+ warning("That is not a valid command")
diff --git a/pool/shard002/Python/0026628_util.py b/pool/shard002/Python/0026628_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b88a61e6423f8adba8037ef592fd58278b36b3
--- /dev/null
+++ b/pool/shard002/Python/0026628_util.py
@@ -0,0 +1,68 @@
+from django.utils.html import conditional_escape
+from django.utils.encoding import smart_unicode, StrAndUnicode, force_unicode
+from django.utils.safestring import mark_safe
+
+def flatatt(attrs):
+ """
+ Convert a dictionary of attributes to a single string.
+ The returned string will contain a leading space followed by key="value",
+ XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
+ If the passed dictionary is empty, then return an empty string.
+ """
+ return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()])
+
+class ErrorDict(dict, StrAndUnicode):
+ """
+ A collection of errors that knows how to display itself in various formats.
+
+ The dictionary keys are the field names, and the values are the errors.
+ """
+ def __unicode__(self):
+ return self.as_ul()
+
+ def as_ul(self):
+ if not self: return u''
+ return mark_safe(u'
%s
'
+ % ''.join([u'
%s%s
' % (k, force_unicode(v))
+ for k, v in self.items()]))
+
+ def as_text(self):
+ return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()])
+
+class ErrorList(list, StrAndUnicode):
+ """
+ A collection of errors that knows how to display itself in various formats.
+ """
+ def __unicode__(self):
+ return self.as_ul()
+
+ def as_ul(self):
+ if not self: return u''
+ return mark_safe(u'