Pendigard commited on
Commit
5a021c7
·
verified ·
1 Parent(s): 2aa1ec3

Upload folder using huggingface_hub (part 77)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. pool/shard006/Python/0057587_dnsimple.py +42 -0
  2. pool/shard006/Python/0057590_joystick.py +81 -0
  3. pool/shard006/Python/0057591_tests.py +101 -0
  4. pool/shard006/Python/0057592_init__.py +66 -0
  5. pool/shard006/Python/0057597_base.py +57 -0
  6. pool/shard006/Python/0057598_test_configuration.py +21 -0
  7. pool/shard006/Python/0057604_test_hinge.py +138 -0
  8. pool/shard006/Python/0057605_stats_randint.py +21 -0
  9. pool/shard006/Python/0057607_foomodulegen4.py +76 -0
  10. pool/shard006/Python/0057610_shell.py +130 -0
  11. pool/shard006/Python/0057612_node_power_control.py +52 -0
  12. pool/shard006/Python/0057613_init__.py +48 -0
  13. pool/shard006/Python/0057617_MySQLInitial.py +42 -0
  14. pool/shard006/Python/0057619_playerdb.py +86 -0
  15. pool/shard006/Python/0057620_test_model_chat_analysis.py +137 -0
  16. pool/shard006/Python/0057630_principals.py +53 -0
  17. pool/shard006/Python/0057631_FingerprintUtils.py +112 -0
  18. pool/shard006/Python/0057632_etl.py +64 -0
  19. pool/shard006/Python/0057637_utils.py +22 -0
  20. pool/shard006/Python/0057641_link_finder.py +34 -0
  21. pool/shard006/Python/0057645_sql.py +9 -0
  22. pool/shard006/Python/0057649_read.py +26 -0
  23. pool/shard006/Python/0057651_euler38.py +50 -0
  24. pool/shard006/Python/0057652_spacy-nlp.py +122 -0
  25. pool/shard006/Python/0057655_app_initialization_test.py +51 -0
  26. pool/shard006/Python/0057662_filediff_comment.py +56 -0
  27. pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py +115 -0
  28. pool/shard006/Python/0057664_rest-server-v2.py +118 -0
  29. pool/shard006/Python/0057665_word_extractor.py +75 -0
  30. pool/shard006/Python/0057667_Choice.py +48 -0
  31. pool/shard006/Python/0057668_hog_template.py +232 -0
  32. pool/shard006/Python/0057670_test_image_lst.py +142 -0
  33. pool/shard006/Python/0057672_rating.py +15 -0
  34. pool/shard006/Python/0057673_get_build_status.py +33 -0
  35. pool/shard006/Python/0057675_EurostagState.py +118 -0
  36. pool/shard006/Python/0057680_pluginmanager.py +49 -0
  37. pool/shard006/Python/0057683_routing_metal.py +31 -0
  38. pool/shard006/Python/0057685_rootramfs.py +175 -0
  39. pool/shard006/Python/0057686_gotoread.py +35 -0
  40. pool/shard006/Python/0057692_mongodb_parameter.py +216 -0
  41. pool/shard006/Python/0057693_test_bigip_profile_udp.py +119 -0
  42. pool/shard006/Python/0057699_user.py +127 -0
  43. pool/shard006/Python/0057703_example_1.py +100 -0
  44. pool/shard006/Python/0057706_basehandlers.py +68 -0
  45. pool/shard006/Python/0057707_RiCIMU.py +148 -0
  46. pool/shard006/Python/0057709_test_fetch.py +216 -0
  47. pool/shard006/Python/0057718_gmusic.py +60 -0
  48. pool/shard006/Python/0057719_graphSim.py +77 -0
  49. pool/shard006/Python/0057724_plot_gait.py +270 -0
  50. pool/shard006/Python/0057730_screenshot.py +91 -0
pool/shard006/Python/0057587_dnsimple.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Updater for https://dnsimple.com/ compatible dyndns services.
4
+
5
+ This module depends on the python package dnsimple-dyndns from
6
+ https://pypi.python.org/pypi/dnsimple-dyndns
7
+ If installed, dyndnsc will be able to utilize it.
8
+
9
+ Since dnsimple.com is a paid service, I have not had a chance to test this yet.
10
+ """
11
+
12
+ import logging
13
+
14
+ from dnsimple_dyndns import DNSimple # @UnresolvedImport pylint: disable=import-error
15
+
16
+ from .base import UpdateProtocol
17
+
18
+ LOG = logging.getLogger(__name__)
19
+
20
+
21
+ class UpdateProtocolDnsimple(UpdateProtocol):
22
+ """Protocol handler for https://dnsimple.com/ ."""
23
+
24
+ configuration_key = "dnsimple"
25
+
26
+ def __init__(self, hostname, key, url=None, **kwargs):
27
+ """Initialize."""
28
+ self._recordname, _, self._domain = hostname.partition(".")
29
+ self.hostname = hostname
30
+ self.handler = DNSimple(domain=self._domain,
31
+ domain_token=key)
32
+ if url is not None:
33
+ # The url must be a format string like this:
34
+ # 'https://dnsimple.com/domains/%s/records'
35
+ self.handler._baseurl = url % self._domain
36
+
37
+ super(UpdateProtocolDnsimple, self).__init__()
38
+
39
+ def update(self, ip):
40
+ """Update the IP on the remote service."""
41
+ return self.handler.update_record(name=self._recordname,
42
+ address=ip)
pool/shard006/Python/0057590_joystick.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import pygame
4
+ import sys
5
+
6
+ import multiprocessing
7
+ import Queue #needed separately for the Empty exception
8
+ import time, datetime
9
+
10
+ class JoystickProcess(multiprocessing.Process):
11
+ def __init__(self, outputqueue):
12
+ multiprocessing.Process.__init__(self)
13
+ self.outputqueue = outputqueue
14
+ self.exit = multiprocessing.Event()
15
+ self.sleeping = multiprocessing.Event()
16
+
17
+ def shutdown(self):
18
+ self.exit.set()
19
+
20
+ def sleep(self):
21
+ self.sleeping.set()
22
+
23
+ def wake(self):
24
+ self.sleeping.clear()
25
+
26
+ def run(self):
27
+ try:
28
+ pygame.init()
29
+ self.j = pygame.joystick.Joystick(0)
30
+ self.j.init()
31
+ print 'Found Joystick: ', self.j.get_name()
32
+ sys.stdout.flush()
33
+
34
+ except Exception, e:
35
+ print "exception in joystick:", e
36
+ self.sleep()
37
+ time.sleep(0.1)
38
+ sys.stdout.flush()
39
+
40
+ while not self.exit.is_set():
41
+
42
+ if self.sleeping.is_set():
43
+ time.sleep(0.1)
44
+ continue
45
+
46
+ data = self.get()
47
+
48
+ if (data is not None):
49
+ tstamp = datetime.datetime.now()
50
+ try:
51
+ self.outputqueue.put((tstamp, data), False)
52
+ except Queue.Full:
53
+ continue
54
+
55
+ def get(self):
56
+ out = []
57
+ pygame.event.pump()
58
+
59
+ #Read input from joysticks
60
+ for i in range(self.j.get_numaxes()):
61
+ out.append(self.j.get_axis(i))
62
+
63
+ #Read input from buttons
64
+ for i in range(self.j.get_numbuttons()):
65
+ out.append(self.j.get_button(i))
66
+
67
+ return out
68
+
69
+ if __name__ == '__main__':
70
+
71
+ q = multiprocessing.Queue(maxsize=1)
72
+ j = JoystickProcess(q)
73
+ j.start()
74
+
75
+ while(1):
76
+ try:
77
+ tstamp, data = q.get(False)
78
+ print tstamp, data
79
+ sys.stdout.flush()
80
+ except Queue.Empty:
81
+ pass
pool/shard006/Python/0057591_tests.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django_dynamic_fixture import G
2
+
3
+ from fluent_contents.plugins.rawhtml.models import RawHtmlItem
4
+
5
+ from icekit import models
6
+ from icekit.page_types.layout_page.models import LayoutPage
7
+ from icekit.utils import fluent_contents
8
+
9
+
10
+ from .. import base_tests
11
+
12
+
13
+ class PagesAPITests(base_tests._BaseAPITestCase):
14
+ API_NAME = 'page-api'
15
+ API_IS_PUBLIC_READ = True
16
+
17
+ def setUp(self):
18
+ super(PagesAPITests, self).setUp()
19
+
20
+ self.layout_1 = G(
21
+ models.Layout,
22
+ template_name='icekit/layouts/default.html',
23
+ )
24
+ self.layoutpage_1 = LayoutPage.objects.create(
25
+ author=self.superuser,
26
+ title='Test LayoutPage',
27
+ layout=self.layout_1,
28
+ )
29
+ self.content_instance_1 = fluent_contents.create_content_instance(
30
+ RawHtmlItem,
31
+ self.layoutpage_1,
32
+ html='<b>test 1</b>'
33
+ )
34
+ self.content_instance_2 = fluent_contents.create_content_instance(
35
+ RawHtmlItem,
36
+ self.layoutpage_1,
37
+ html='<b>test 2</b>'
38
+ )
39
+ self.content_instance_3 = fluent_contents.create_content_instance(
40
+ RawHtmlItem,
41
+ self.layoutpage_1,
42
+ html='<b>test 3</b>'
43
+ )
44
+
45
+ def test_list_pages_with_get_and_filtered_fields(self):
46
+ self.layoutpage_1.publish()
47
+ response = self.client.get(self.listing_url() + '?fields=title')
48
+ self.assertEqual(200, response.status_code)
49
+ self.assertEqual(
50
+ {
51
+ 'count': 1,
52
+ 'next': None,
53
+ 'previous': None,
54
+ 'results': [{
55
+ 'title': 'Test LayoutPage',
56
+ }]
57
+ },
58
+ response.data)
59
+
60
+ def test_page_api(self):
61
+ self.layoutpage_1.publish()
62
+ for j in range(20):
63
+ published_layoutpage = LayoutPage.objects.create(
64
+ author=self.superuser,
65
+ title='Test LayoutPage %s' % j,
66
+ layout=self.layout_1,
67
+ )
68
+ published_layoutpage.publish()
69
+
70
+ LayoutPage.objects.create(
71
+ author=self.superuser,
72
+ title='Draft LayoutPage %s' % j,
73
+ layout=self.layout_1,
74
+ )
75
+
76
+ response = self.client.get(self.listing_url())
77
+ self.assertEqual(response.status_code, 200)
78
+ self.assertEqual(len(response.data['results']), 5)
79
+ self.assertEqual(response.data['count'], 21)
80
+ response = self.client.get(self.detail_url(self.layoutpage_1.id))
81
+ self.assertEqual(response.status_code, 404)
82
+ response = self.client.get(
83
+ self.detail_url(self.layoutpage_1.get_published().id))
84
+ self.assertEqual(response.status_code, 200)
85
+ self.assertEqual(len(response.data), 6)
86
+ for key in response.data.keys():
87
+ if key is not 'content':
88
+ self.assertEqual(
89
+ response.data[key],
90
+ getattr(self.layoutpage_1.get_published(), key))
91
+ self.assertEqual(len(response.data['content']), 3)
92
+ for number, item in enumerate(response.data['content'], 1):
93
+ self.assertEqual(
94
+ item['content'],
95
+ getattr(self, 'content_instance_%s' % number).html)
96
+
97
+ def test_api_user_permissions_are_correct(self):
98
+ self.layoutpage_1.publish()
99
+ page_published_id = self.layoutpage_1.get_published().pk
100
+ self.assert_api_user_permissions_are_correct(
101
+ page_published_id, models.Layout)
pool/shard006/Python/0057592_init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from flask import Flask
4
+
5
+ from samantha import config
6
+
7
+ # configure Flask
8
+ app = Flask(__name__)
9
+ app.secret_key = os.urandom(32)
10
+
11
+ #
12
+ # Configure SQLAlchemy
13
+ # @see http://flask.pocoo.org/docs/0.10/patterns/sqlalchemy/
14
+ #
15
+ from sqlalchemy import create_engine
16
+ from sqlalchemy.orm import scoped_session, sessionmaker
17
+ from sqlalchemy.ext.declarative import declarative_base
18
+
19
+ engine = create_engine(
20
+ config.get('SQLALCHEMY_DATABASE_URI'),
21
+ convert_unicode=True
22
+ )
23
+ session = scoped_session(
24
+ sessionmaker(
25
+ autocommit=False,
26
+ autoflush=False,
27
+ bind=engine
28
+ )
29
+ )
30
+ Base = declarative_base()
31
+ Base.query = session.query_property()
32
+
33
+
34
+ @app.teardown_appcontext
35
+ def shutdown_session(exception=None):
36
+ session.remove()
37
+
38
+
39
+ #
40
+ # Configure Celery
41
+ # @see http://flask.pocoo.org/docs/0.10/patterns/celery/
42
+ #
43
+ from celery import Celery
44
+
45
+
46
+ def make_celery(app):
47
+ celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
48
+ celery.conf.update(app.config)
49
+ TaskBase = celery.Task
50
+
51
+ class ContextTask(TaskBase):
52
+ abstract = True
53
+
54
+ def __call__(self, *args, **kwargs):
55
+ with app.app_context():
56
+ return TaskBase.__call__(self, *args, **kwargs)
57
+
58
+ celery.Task = ContextTask
59
+ return celery
60
+
61
+ app.config.update(
62
+ CELERY_BROKER_URL=config.get('CELERY_BROKER_URL'),
63
+ CELERY_RESULT_BACKEND=config.get('CELERY_BROKER_URL'),
64
+ CELERY_ACCEPT_CONTENT=config.get('CELERY_ACCEPT_CONTENT').split(',')
65
+ )
66
+ celery = make_celery(app)
pool/shard006/Python/0057597_base.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+ from __future__ import division
3
+ from __future__ import absolute_import
4
+ from builtins import object
5
+
6
+
7
+ def not_implemented(method):
8
+ raise NotImplementedError("Provider does not support '%s' "
9
+ "method." % method)
10
+
11
+
12
+ class BaseProviderBuilder(object):
13
+ def build(self, region=None):
14
+ not_implemented("build")
15
+
16
+
17
+ class BaseProvider(object):
18
+ def get_stack(self, stack_name, *args, **kwargs):
19
+ # pylint: disable=unused-argument
20
+ not_implemented("get_stack")
21
+
22
+ def create_stack(self, *args, **kwargs):
23
+ # pylint: disable=unused-argument
24
+ not_implemented("create_stack")
25
+
26
+ def update_stack(self, *args, **kwargs):
27
+ # pylint: disable=unused-argument
28
+ not_implemented("update_stack")
29
+
30
+ def destroy_stack(self, *args, **kwargs):
31
+ # pylint: disable=unused-argument
32
+ not_implemented("destroy_stack")
33
+
34
+ def get_stack_status(self, stack_name, *args, **kwargs):
35
+ # pylint: disable=unused-argument
36
+ not_implemented("get_stack_status")
37
+
38
+ def get_outputs(self, stack_name, *args, **kwargs):
39
+ # pylint: disable=unused-argument
40
+ not_implemented("get_outputs")
41
+
42
+ def get_output(self, stack_name, output):
43
+ # pylint: disable=unused-argument
44
+ return self.get_outputs(stack_name)[output]
45
+
46
+
47
+ class Template(object):
48
+ """A value object that represents a CloudFormation stack template, which
49
+ could be optionally uploaded to s3.
50
+
51
+ Presence of the url attribute indicates that the template was uploaded to
52
+ S3, and the uploaded template should be used for CreateStack/UpdateStack
53
+ calls.
54
+ """
55
+ def __init__(self, url=None, body=None):
56
+ self.url = url
57
+ self.body = body
pool/shard006/Python/0057598_test_configuration.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from paste.deploy.loadwsgi import appconfig
4
+
5
+ from testery.tests import TestCase
6
+
7
+
8
+ class TestConfiguration(TestCase):
9
+ """Check that the ini files track the same configuration types."""
10
+
11
+ def setUp(self):
12
+ super(TestConfiguration, self).setUp()
13
+ here = os.path.dirname(__file__)
14
+ self.project_root = os.path.abspath(os.path.join(here, '..', '..'))
15
+
16
+ def test_development_ini(self):
17
+ test_ini = os.path.join(self.project_root, 'test.ini')
18
+ test_settings = appconfig('config:' + test_ini)
19
+ dev_ini = os.path.join(self.project_root, 'development.ini')
20
+ dev_settings = appconfig('config:' + dev_ini)
21
+ self.assertEqual(test_settings.keys(), dev_settings.keys())
pool/shard006/Python/0057604_test_hinge.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy
4
+ import six
5
+
6
+ import chainer
7
+ from chainer.backends import cuda
8
+ from chainer import functions
9
+ from chainer import gradient_check
10
+ from chainer import testing
11
+ from chainer.testing import attr
12
+
13
+
14
+ @testing.parameterize(*testing.product_dict(
15
+ [{'dtype': numpy.float16,
16
+ 'forward_options': {'rtol': 3e-3, 'atol': 3e-3},
17
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
18
+ {'dtype': numpy.float32,
19
+ 'forward_options': {},
20
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
21
+ {'dtype': numpy.float64,
22
+ 'forward_options': {},
23
+ 'backward_options': {'rtol': 1e-1, 'atol': 1e-1}},
24
+ ],
25
+ [{'reduce': 'no'},
26
+ {'reduce': 'mean'},
27
+ ],
28
+ [{'norm': 'L1'},
29
+ {'norm': 'L2'},
30
+ ],
31
+ [{'label_dtype': numpy.int8},
32
+ {'label_dtype': numpy.int16},
33
+ {'label_dtype': numpy.int32},
34
+ {'label_dtype': numpy.int64},
35
+ ],
36
+ ))
37
+ class TestHinge(unittest.TestCase):
38
+
39
+ def setUp(self):
40
+ self._config_user = chainer.using_config('dtype', self.dtype)
41
+ self._config_user.__enter__()
42
+
43
+ shape = (10, 5)
44
+ self.x = numpy.random.uniform(-1, 1, shape).astype(self.dtype)
45
+ # Avoid values around -1.0 for stability
46
+ self.x[numpy.logical_and(-1.01 < self.x, self.x < -0.99)] = 0.5
47
+ self.t = numpy.random.randint(
48
+ 0, shape[1], shape[:1]).astype(self.label_dtype)
49
+ if self.reduce == 'no':
50
+ self.gy = numpy.random.uniform(
51
+ -1, 1, self.x.shape).astype(self.dtype)
52
+
53
+ def tearDown(self):
54
+ self._config_user.__exit__(None, None, None)
55
+
56
+ def check_forward(self, x_data, t_data):
57
+ x_val = chainer.Variable(x_data)
58
+ t_val = chainer.Variable(t_data)
59
+ loss = functions.hinge(x_val, t_val, self.norm, self.reduce)
60
+ if self.reduce == 'mean':
61
+ self.assertEqual(loss.data.shape, ())
62
+ else:
63
+ self.assertEqual(loss.data.shape, self.x.shape)
64
+ self.assertEqual(loss.data.dtype, self.dtype)
65
+ loss_value = cuda.to_cpu(loss.data)
66
+
67
+ # Compute expected value
68
+ for i in six.moves.range(self.x.shape[0]):
69
+ self.x[i, self.t[i]] *= -1
70
+ for i in six.moves.range(self.x.shape[0]):
71
+ for j in six.moves.range(self.x.shape[1]):
72
+ self.x[i, j] = max(0, 1.0 + self.x[i, j])
73
+ if self.norm == 'L1':
74
+ loss_expect = self.x
75
+ elif self.norm == 'L2':
76
+ loss_expect = self.x ** 2
77
+ if self.reduce == 'mean':
78
+ loss_expect = numpy.sum(loss_expect) / self.x.shape[0]
79
+
80
+ testing.assert_allclose(
81
+ loss_expect, loss_value, **self.forward_options)
82
+
83
+ def test_forward_cpu(self):
84
+ self.check_forward(self.x, self.t)
85
+
86
+ @attr.gpu
87
+ def test_forward_gpu(self):
88
+ self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
89
+
90
+ def check_backward(self, x_data, t_data):
91
+ def f(x, t):
92
+ return functions.hinge(x, t, self.norm)
93
+
94
+ gradient_check.check_backward(
95
+ f, (x_data, t_data), None, dtype='d', **self.backward_options)
96
+
97
+ def test_backward_cpu(self):
98
+ self.check_backward(self.x, self.t)
99
+
100
+ @attr.gpu
101
+ def test_backward_gpu(self):
102
+ self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t))
103
+
104
+
105
+ class TestHingeInvalidOption(unittest.TestCase):
106
+
107
+ def setUp(self):
108
+ self.x = numpy.random.uniform(-1, 1, (10, 5)).astype(numpy.float32)
109
+ self.t = numpy.random.randint(0, 5, (10,)).astype(numpy.int32)
110
+
111
+ def check_invalid_norm_option(self, xp):
112
+ x = xp.asarray(self.x)
113
+ t = xp.asarray(self.t)
114
+ with self.assertRaises(NotImplementedError):
115
+ functions.hinge(x, t, 'invalid_norm', 'mean')
116
+
117
+ def test_invalid_norm_option_cpu(self):
118
+ self.check_invalid_norm_option(numpy)
119
+
120
+ @attr.gpu
121
+ def test_invalid_norm_option_gpu(self):
122
+ self.check_invalid_norm_option(cuda.cupy)
123
+
124
+ def check_invalid_reduce_option(self, xp):
125
+ x = xp.asarray(self.x)
126
+ t = xp.asarray(self.t)
127
+ with self.assertRaises(ValueError):
128
+ functions.hinge(x, t, 'L1', 'invalid_option')
129
+
130
+ def test_invalid_reduce_option_cpu(self):
131
+ self.check_invalid_reduce_option(numpy)
132
+
133
+ @attr.gpu
134
+ def test_invalid_reduce_option_gpu(self):
135
+ self.check_invalid_reduce_option(cuda.cupy)
136
+
137
+
138
+ testing.run_module(__name__, __file__)
pool/shard006/Python/0057605_stats_randint.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """stats_randint.py: Demonstrate how ``scipy.stats.randint`` works.
3
+ """
4
+ from scipy.stats import randint
5
+
6
+ # pylint: disable=invalid-name
7
+
8
+ # Define a dice model.
9
+ low = 1
10
+ high = 7
11
+ dice = randint(low, high)
12
+
13
+ # Compute moments.
14
+ mean, var, skew, kurt = dice.stats(moments='mvsk')
15
+
16
+ print(f"mean: {float(mean):.3f}")
17
+ print(f"median: {dice.median():.3f}")
18
+ print(f"var: {float(var):.3f}")
19
+ print(f"skew: {float(skew):.3f}")
20
+ print(f"kurt: {float(kurt):.3f}")
21
+ print(f"std: {dice.std():.3f}") # Or np.sqrt(var).
pool/shard006/Python/0057607_foomodulegen4.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+ from __future__ import unicode_literals, print_function
3
+
4
+ import sys
5
+ import os.path
6
+
7
+ import pybindgen
8
+ from pybindgen.module import MultiSectionFactory
9
+ from pybindgen import (FileCodeSink)
10
+
11
+ import foomodulegen_split
12
+ import foomodulegen_common
13
+
14
+
15
+ class MyMultiSectionFactory(MultiSectionFactory):
16
+
17
+ def __init__(self, main_file_name):
18
+ self.main_file_name = main_file_name
19
+ self.main_sink = FileCodeSink(open(main_file_name, "wt"))
20
+ self.header_name = "foomodule4.h"
21
+ header_file_name = os.path.join(os.path.dirname(self.main_file_name), self.header_name)
22
+ self.header_sink = FileCodeSink(open(header_file_name, "wt"))
23
+ self.section_sinks = {}
24
+
25
+ def get_section_code_sink(self, section_name):
26
+ if section_name == '__main__':
27
+ return self.main_sink
28
+ try:
29
+ return self.section_sinks[section_name]
30
+ except KeyError:
31
+ file_name = os.path.join(os.path.dirname(self.main_file_name), "%s.cc" % section_name)
32
+ sink = FileCodeSink(open(file_name, "wt"))
33
+ self.section_sinks[section_name] = sink
34
+ return sink
35
+
36
+ def get_main_code_sink(self):
37
+ return self.main_sink
38
+
39
+ def get_common_header_code_sink(self):
40
+ return self.header_sink
41
+
42
+ def get_common_header_include(self):
43
+ return '"%s"' % self.header_name
44
+
45
+ def close(self):
46
+ self.header_sink.file.close()
47
+ self.main_sink.file.close()
48
+ for sink in self.section_sinks.values():
49
+ sink.file.close()
50
+
51
+ def my_module_gen():
52
+ out = MyMultiSectionFactory(sys.argv[1])
53
+ root_module = foomodulegen_split.module_init()
54
+ root_module.add_exception('exception', foreign_cpp_namespace='std', message_rvalue='%(EXC)s.what()')
55
+ foomodulegen_common.customize_module_pre(root_module)
56
+
57
+ foomodulegen_split.register_types(root_module)
58
+ foomodulegen_split.register_methods(root_module)
59
+ foomodulegen_split.register_functions(root_module)
60
+ foomodulegen_common.customize_module(root_module)
61
+
62
+ root_module.generate(out)
63
+
64
+ out.close()
65
+
66
+
67
+
68
+ if __name__ == '__main__':
69
+ try:
70
+ import cProfile as profile
71
+ except ImportError:
72
+ my_module_gen()
73
+ else:
74
+ print("** running under profiler", file=sys.stderr)
75
+ profile.run('my_module_gen()', 'foomodulegen4.pstat')
76
+
pool/shard006/Python/0057610_shell.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import re
4
+ import types
5
+ import logging
6
+ import subprocess
7
+
8
+ from ..exceptions import (ExecuteRuntimeError, ScriptRuntimeError,
9
+ NetworkError)
10
+ from .strings import mask_string
11
+
12
+
13
+ block_fmt = ("\n============= %(title)s ==========\n%(content)s\n"
14
+ "======== END OF %(title)s ========")
15
+
16
+
17
+ def execute(cmd, workdir=None, can_fail=True, mask_list=None,
18
+ use_shell=False, log=True):
19
+ """
20
+ Runs shell command cmd. If can_fail is set to False
21
+ ExecuteRuntimeError is raised if command returned non-zero return
22
+ code. Otherwise
23
+ """
24
+ mask_list = mask_list or []
25
+ repl_list = [("'", "'\\''")]
26
+
27
+ if not isinstance(cmd, types.StringType):
28
+ import pipes
29
+ masked = ' '.join((pipes.quote(i) for i in cmd))
30
+ else:
31
+ masked = cmd
32
+ masked = mask_string(masked, mask_list, repl_list)
33
+ if log:
34
+ logging.info("Executing command:\n%s" % masked)
35
+
36
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
37
+ stderr=subprocess.PIPE, cwd=workdir,
38
+ shell=use_shell, close_fds=True)
39
+ out, err = proc.communicate()
40
+ masked_out = mask_string(out, mask_list, repl_list)
41
+ masked_err = mask_string(err, mask_list, repl_list)
42
+ if log:
43
+ logging.debug(block_fmt % {'title': 'STDOUT', 'content': masked_out})
44
+
45
+ if proc.returncode:
46
+ if log:
47
+ logging.debug(block_fmt % {'title': 'STDERR',
48
+ 'content': masked_err})
49
+ if can_fail:
50
+ msg = 'Failed to execute command: %s' % masked_out
51
+ raise ExecuteRuntimeError(msg, stdout=out, stderr=err)
52
+ return proc.returncode, out
53
+
54
+
55
+ class ScriptRunner(object):
56
+ _pkg_search = 'rpm -q --whatprovides'
57
+
58
+ def __init__(self, ip=None):
59
+ self.script = []
60
+ self.ip = ip
61
+
62
+ def append(self, s):
63
+ self.script.append(s)
64
+
65
+ def clear(self):
66
+ self.script = []
67
+
68
+ def execute(self, can_fail=True, mask_list=None, log=True):
69
+ mask_list = mask_list or []
70
+ repl_list = [("'", "'\\''")]
71
+ script = "\n".join(self.script)
72
+
73
+ masked = mask_string(script, mask_list, repl_list)
74
+ if log:
75
+ logging.info("[%s] Executing script:\n%s" %
76
+ (self.ip or 'localhost', masked))
77
+
78
+ _PIPE = subprocess.PIPE # pylint: disable=E1101
79
+ if self.ip:
80
+ cmd = ["ssh", "-o", "StrictHostKeyChecking=no",
81
+ "-o", "UserKnownHostsFile=/dev/null",
82
+ "root@%s" % self.ip, "bash -x"]
83
+ else:
84
+ cmd = ["bash", "-x"]
85
+ obj = subprocess.Popen(cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE,
86
+ close_fds=True, shell=False)
87
+
88
+ script = "function t(){ exit $? ; } \n trap t ERR \n" + script
89
+ out, err = obj.communicate(script)
90
+ masked_out = mask_string(out, mask_list, repl_list)
91
+ masked_err = mask_string(err, mask_list, repl_list)
92
+ if log:
93
+ logging.debug(block_fmt % {'title': 'STDOUT',
94
+ 'content': masked_out})
95
+
96
+ if obj.returncode:
97
+ if log:
98
+ logging.debug(block_fmt % {'title': 'STDERR',
99
+ 'content': masked_err})
100
+ if can_fail:
101
+ pattern = (r'^ssh\:')
102
+ if re.search(pattern, err):
103
+ raise NetworkError(masked_err, stdout=out, stderr=err)
104
+ else:
105
+ msg = 'Failed to run remote script: %s' % masked_out
106
+ raise ScriptRuntimeError(msg, stdout=out, stderr=err)
107
+ return obj.returncode, out
108
+
109
+ def template(self, src, dst, varsdict):
110
+ with open(src) as fp:
111
+ content = fp.read() % varsdict
112
+ self.append("cat > %s <<- EOF\n%s\nEOF\n" % (dst, content))
113
+
114
+ def if_not_exists(self, path, command):
115
+ self.append("[ -e %s ] || %s" % (path, command))
116
+
117
+ def if_exists(self, path, command):
118
+ self.append("[ -e %s ] && %s" % (path, command))
119
+
120
+ def if_installed(self, pkg, command):
121
+ self.append("%s %s && %s" % (self._pkg_search, pkg, command))
122
+
123
+ def if_not_installed(self, pkg, command):
124
+ self.append("%s %s || %s" % (self._pkg_search, pkg, command))
125
+
126
+ def chown(self, target, uid, gid):
127
+ self.append("chown %s:%s %s" % (uid, gid, target))
128
+
129
+ def chmod(self, target, mode):
130
+ self.append("chmod %s %s" % (mode, target))
pool/shard006/Python/0057612_node_power_control.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+ # -*- mode: python; coding: utf-8 -*-
3
+ # Copyright 2018 the HERA Collaboration
4
+ # Licensed under the 2-clause BSD license.
5
+
6
+ """script to control power of node elements (snaps, fem, pam)
7
+
8
+ """
9
+
10
+ from hera_mc import mc, cm_utils, node
11
+
12
+ valid_part_names = list(node.power_command_part_dict.keys())
13
+
14
+ if __name__ == '__main__':
15
+ parser = mc.get_mc_argument_parser()
16
+ parser.description = """Power on or off node elements (snaps, fem, pam)"""
17
+ parser.add_argument('nodes', help="list of nodes to command "
18
+ "(integers, comma-separated, no spaces) or 'active'")
19
+ parser.add_argument('parts', help="list of parts to command "
20
+ "(comma-separated, no spaces) or 'all'."
21
+ " Valid part names are: " + ' ,'.join(valid_part_names) + ".")
22
+ parser.add_argument('command', help="command: 'on' or 'off'.")
23
+ parser.add_argument('--address', help="address for node server", default=None)
24
+ parser.add_argument('--dryrun', help="just print the list of NodePowerCommand "
25
+ "objects, do not issue the power commands or log them "
26
+ "to the database' [False]", action='store_true')
27
+ parser.add_argument('--testing', help="Testing: do not use anything that "
28
+ "requires connection to nodes (implies dryrun)' [False]",
29
+ action='store_true')
30
+
31
+ args = parser.parse_args()
32
+ db = mc.connect_to_mc_db(args)
33
+ session = db.sessionmaker()
34
+
35
+ if args.nodes.lower() == 'active':
36
+ from hera_mc import node
37
+ node_list = node.get_node_list(nodeServerAddress=args.address)
38
+ else:
39
+ node_list = cm_utils.listify(args.nodes)
40
+ node_list = [int(node) for node in node_list]
41
+
42
+ parts_list = cm_utils.listify(args.parts)
43
+
44
+ for nodeID in node_list:
45
+ command_list = session.node_power_command(nodeID, parts_list, args.command,
46
+ nodeServerAddress=args.address,
47
+ dryrun=args.dryrun,
48
+ testing=args.testing)
49
+ if args.testing or args.dryrun:
50
+ for cmd in command_list:
51
+ print(cmd)
52
+ session.commit()
pool/shard006/Python/0057613_init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+
3
+ import re
4
+ import sys
5
+ import argparse
6
+
7
+ from .litran import LIT
8
+
9
+ __name__ = "litcm"
10
+ __doc__ = "Language Identification and Transliteration system for Indian Languages in Roman script code mixed with English"
11
+ __author__ = "Irshad Ahmad"
12
+ __version__ = "1.0.0"
13
+ __license__ = "MIT"
14
+ __maintainer__ = "Irshad Ahmad"
15
+ __email__ = "irshad.bhat@research.iiit.ac.in"
16
+ __status__ = "Beta"
17
+ __all__ = ["litran", "indictrans", "wxILP", "main", "blm_models", "decision_trees", "extras"]
18
+
19
+ def main():
20
+ all_tags = ['ben', 'eng', 'guj', 'hin', 'kan', 'mal', 'tam', 'tel']
21
+ lang_help = 'Any language combination from the set: [%s]' %'|'.join(all_tags)
22
+ parser = argparse.ArgumentParser(prog="litcm", description="Language Identification & Transliteration in Code-Mixing")
23
+ parser.add_argument('--v', action='version', version="%(prog)s 1.0")
24
+ parser.add_argument('--i', metavar='input', dest="INFILE", type=argparse.FileType('r'), default=sys.stdin, help="<input-file>")
25
+ parser.add_argument('--o', metavar='output', dest="OUTFILE", type=argparse.FileType('w'), default=sys.stdout, help="<output-file>")
26
+ parser.add_argument('--l', metavar='languages', dest='lang_tags', nargs='+', help=lang_help)
27
+ parser.add_argument('--t', dest='flag', action='store_true', help="set this flag for back-transliteration of Indic words")
28
+
29
+ args = parser.parse_args()
30
+
31
+ if args.lang_tags:
32
+ labels = [tag.lower() for tag in args.lang_tags]
33
+ assert len(labels) >= 2
34
+ assert set(labels).issubset(set(all_tags))
35
+ else:
36
+ labels = ['hin', 'eng']
37
+
38
+ lit = LIT(labels, transliteration=args.flag)
39
+ for line in args.INFILE:
40
+ if not line.strip():
41
+ args.OUTFILE.write('\n')
42
+ continue
43
+ litsen = lit.identify(line)
44
+ args.OUTFILE.write("%s\n" %litsen)
45
+
46
+ #close files
47
+ args.INFILE.close()
48
+ args.OUTFILE.close()
pool/shard006/Python/0057617_MySQLInitial.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Open Connectome Project (http://openconnecto.me)
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import MySQLdb
16
+ import sys
17
+
18
+ # Edit the following:
19
+ # MySQLPass - MySQL root user password
20
+ # password_here - the password for user(in this case brain) specified in the settings_secret.py file
21
+
22
+ def setup(MySQLPass, BrainPass):
23
+
24
+ # Assuming ocpdjango (from settings_secret.py)
25
+
26
+ db = MySQLdb.connect("localhost","root",MySQLPass)
27
+ cursor = db.cursor()
28
+
29
+ # Create database for OCP
30
+ cursor.execute("create database ocpdjango;")
31
+
32
+ # Create users for OCP
33
+ cursor.execute("create user 'brain'@'localhost' identified by '" + BrainPass + "';")
34
+ cursor.execute("grant all privileges on *.* to 'brain'@'localhost' with grant option;")
35
+
36
+ cursor.execute("create user 'brain'@'%' identified by '" + BrainPass + "';")
37
+ cursor.execute("grant all privileges on *.* to 'brain'@'%' with grant option;")
38
+
39
+ db.close()
40
+
41
+ if __name__ == '__main__':
42
+ setup(*sys.argv[1:])
pool/shard006/Python/0057619_playerdb.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Player datablock generator, written to test an experimental super-2046 DB count
3
+ patch.
4
+ """
5
+
6
+ import sys
7
+ import math
8
+
9
+ class PseudoNumber:
10
+ _value = None
11
+ _digits = None
12
+ _decimal_value = None
13
+ _converted = None
14
+
15
+ def __init__(self, digits=None, value=None):
16
+ self._digits = digits
17
+ self._decimal_value = int(value)
18
+
19
+ self.convert()
20
+
21
+ def convert(self):
22
+ self._value = ''
23
+
24
+ if (self._decimal_value == 0):
25
+ self._value = self._digits[0]
26
+ return self._value
27
+
28
+ digit_count = len(self._digits) - 1
29
+
30
+ start_power = int(math.ceil(self._decimal_value / digit_count))
31
+ temporary = int(self._decimal_value)
32
+ for current_power in reversed(range(start_power + 1)):
33
+ for current_index, current_digit in enumerate(reversed(self._digits)):
34
+ actual_index = digit_count - current_index
35
+ actual_value = actual_index * pow(digit_count + 1, current_power)
36
+ if (actual_value <= temporary and actual_value != 0):
37
+ temporary -= actual_value
38
+ self._value += self._digits[actual_index % (digit_count + 1)]
39
+
40
+ if (temporary <= 0):
41
+ for power in range(current_power):
42
+ self._value += self._digits[0]
43
+ return self._value
44
+
45
+ return self._value
46
+
47
+ def __repr__(self):
48
+ return self.convert()
49
+
50
+ def __str__(self):
51
+ return self._value
52
+
53
+ def __int__(self):
54
+ return self._decimal_value
55
+
56
+ def __add__(self, other):
57
+ return PseudoNumber(self._digits, self._decimal_value + other)
58
+
59
+ class Application:
60
+ def main(self):
61
+ if (len(sys.argv) != 3):
62
+ print("Usage: %s <file count> <count>" % sys.argv[0])
63
+ return
64
+
65
+ datablock_count = int(sys.argv[2])
66
+ file_count = int(sys.argv[1])
67
+ datablock_iterations = datablock_count / file_count
68
+ current_digit = PseudoNumber('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 0)
69
+
70
+ for file_iteration in range(file_count):
71
+ with open("out%u.cs" % file_iteration, "w") as handle:
72
+ handle.write("// Total Count: %u\n" % datablock_iterations)
73
+ for current_datablock_iteration in range(datablock_iterations):
74
+ handle.write("// Datablock #%u\n" % current_datablock_iteration)
75
+ handle.write("datablock PlayerData(%sMaleBiodermArmor) : LightMaleHumanArmor\n" % str(current_digit))
76
+ handle.write("{\n")
77
+ handle.write("\tshapeFile = \"bioderm_light.dts\";\n")
78
+ handle.write("};\n\n")
79
+
80
+ current_digit += 1
81
+
82
+ handle.write("exec(\"scripts/out%u.cs\");" % (file_iteration + 1))
83
+
84
+
85
+ if __name__ == "__main__":
86
+ Application().main()
pool/shard006/Python/0057620_test_model_chat_analysis.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # This source code is licensed under the MIT license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ """
7
+ Test the analysis code for the model chat task.
8
+ """
9
+
10
+ import glob
11
+ import os
12
+
13
+ import pytest
14
+ from pytest_regressions.file_regression import FileRegressionFixture
15
+
16
+ import parlai.utils.testing as testing_utils
17
+
18
+
19
+ try:
20
+
21
+ from parlai.crowdsourcing.tasks.model_chat.analysis.compile_results import (
22
+ ModelChatResultsCompiler,
23
+ )
24
+ from parlai.crowdsourcing.utils.tests import check_stdout
25
+
26
+ class TestCompileResults:
27
+ """
28
+ Test the analysis code for the model chat task.
29
+ """
30
+
31
+ # Dictionary of cases to test, as well as flags to use with those cases
32
+ CASES = {'basic': '--problem-buckets None', 'with_personas_and_buckets': ''}
33
+
34
+ @pytest.fixture(scope="module")
35
+ def setup_teardown(self):
36
+ """
37
+ Call code to set up and tear down tests.
38
+
39
+ Run this only once because we'll be running all analysis code before
40
+ checking any results.
41
+ """
42
+
43
+ outputs = {}
44
+
45
+ for case, flag_string in self.CASES.items():
46
+
47
+ # Paths
48
+ analysis_samples_folder = os.path.join(
49
+ os.path.dirname(os.path.abspath(__file__)), 'analysis_samples', case
50
+ )
51
+ analysis_outputs_folder = os.path.join(
52
+ os.path.dirname(os.path.abspath(__file__)),
53
+ 'test_model_chat_analysis',
54
+ )
55
+ outputs[f'{case}__expected_stdout_path'] = os.path.join(
56
+ analysis_outputs_folder, f'{case}__test_stdout.txt'
57
+ )
58
+
59
+ prefixes = ['results', 'worker_results']
60
+
61
+ with testing_utils.tempdir() as tmpdir:
62
+
63
+ # Run analysis
64
+ with testing_utils.capture_output() as output:
65
+ arg_string = f"""\
66
+ --results-folders {analysis_samples_folder}
67
+ --output-folder {tmpdir} \
68
+ {flag_string}
69
+ """
70
+ parser_ = ModelChatResultsCompiler.setup_args()
71
+ args_ = parser_.parse_args(arg_string.split())
72
+ ModelChatResultsCompiler(vars(args_)).compile_and_save_results()
73
+ stdout = output.getvalue()
74
+
75
+ # Define output structure
76
+ filtered_stdout = '\n'.join(
77
+ [
78
+ line
79
+ for line in stdout.split('\n')
80
+ if not line.endswith('.csv')
81
+ ]
82
+ )
83
+ # Don't track lines that record where a file was saved to, because
84
+ # filenames are timestamped
85
+ outputs[f'{case}__stdout'] = filtered_stdout
86
+ for prefix in prefixes:
87
+ results_path = list(
88
+ glob.glob(os.path.join(tmpdir, f'{prefix}_*'))
89
+ )[0]
90
+ with open(results_path) as f:
91
+ outputs[f'{case}__{prefix}'] = f.read()
92
+
93
+ yield outputs
94
+ # All code after this will be run upon teardown
95
+
96
+ def test_stdout(self, setup_teardown):
97
+ """
98
+ Check the output against what it should be.
99
+ """
100
+ outputs = setup_teardown
101
+ for case in self.CASES.keys():
102
+ check_stdout(
103
+ actual_stdout=outputs[f'{case}__stdout'],
104
+ expected_stdout_path=outputs[f'{case}__expected_stdout_path'],
105
+ )
106
+
107
+ def test_results_file(
108
+ self, setup_teardown, file_regression: FileRegressionFixture
109
+ ):
110
+ """
111
+ Check the results file against what it should be.
112
+
113
+ We don't use DataFrameRegression fixture because the results might include
114
+ non-numeric data.
115
+ """
116
+ for case in self.CASES.keys():
117
+ prefix = f'{case}__results'
118
+ outputs = setup_teardown
119
+ file_regression.check(outputs[prefix], basename=prefix)
120
+
121
+ def test_worker_results_file(
122
+ self, setup_teardown, file_regression: FileRegressionFixture
123
+ ):
124
+ """
125
+ Check the worker_results file against what it should be.
126
+
127
+ We don't use DataFrameRegression fixture because the results might include
128
+ non-numeric data.
129
+ """
130
+ for case in self.CASES.keys():
131
+ prefix = f'{case}__worker_results'
132
+ outputs = setup_teardown
133
+ file_regression.check(outputs[prefix], basename=prefix)
134
+
135
+
136
+ except ImportError:
137
+ pass
pool/shard006/Python/0057630_principals.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of Indico.
2
+ # Copyright (C) 2002 - 2021 CERN
3
+ #
4
+ # Indico is free software; you can redistribute it and/or
5
+ # modify it under the terms of the MIT License; see the
6
+ # LICENSE file for more details.
7
+
8
+ from sqlalchemy.ext.declarative import declared_attr
9
+
10
+ from indico.core.db import db
11
+ from indico.core.db.sqlalchemy.principals import PrincipalPermissionsMixin, PrincipalType
12
+ from indico.core.db.sqlalchemy.util.models import auto_table_args
13
+ from indico.util.string import format_repr
14
+
15
+
16
+ class EventPrincipal(PrincipalPermissionsMixin, db.Model):
17
+ __tablename__ = 'principals'
18
+ principal_backref_name = 'in_event_acls'
19
+ principal_for = 'Event'
20
+ unique_columns = ('event_id',)
21
+ allow_emails = True
22
+ allow_networks = True
23
+ allow_event_roles = True
24
+ allow_category_roles = True
25
+ allow_registration_forms = True
26
+
27
+ @declared_attr
28
+ def __table_args__(cls):
29
+ permissions = "ARRAY['paper_editing', 'slides_editing', 'poster_editing']"
30
+ condition = 'type NOT IN ({}, {}) OR (NOT (permissions::text[] && {}))'.format(
31
+ PrincipalType.local_group, PrincipalType.multipass_group, permissions
32
+ )
33
+ group_perm_constraint = db.CheckConstraint(condition, 'disallow_group_editor_permissions')
34
+ return (group_perm_constraint,) + auto_table_args(cls, schema='events')
35
+
36
+ #: The ID of the acl entry
37
+ id = db.Column(
38
+ db.Integer,
39
+ primary_key=True
40
+ )
41
+ #: The ID of the associated event
42
+ event_id = db.Column(
43
+ db.Integer,
44
+ db.ForeignKey('events.events.id'),
45
+ nullable=False,
46
+ index=True
47
+ )
48
+
49
+ # relationship backrefs:
50
+ # - event (Event.acl_entries)
51
+
52
+ def __repr__(self):
53
+ return format_repr(self, 'id', 'event_id', 'principal', read_access=False, full_access=False, permissions=[])
pool/shard006/Python/0057631_FingerprintUtils.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # $Id$
2
+ #
3
+ # Copyright (C) 2009 Greg Landrum
4
+ # All Rights Reserved
5
+ #
6
+ from __future__ import print_function
7
+ from rdkit.six.moves import cPickle
8
+ from rdkit.six import iterkeys
9
+ from rdkit import DataStructs,Chem
10
+ from rdkit import Chem
11
+
12
+ similarityMethods={'RDK':DataStructs.ExplicitBitVect,
13
+ 'AtomPairs':DataStructs.IntSparseIntVect,
14
+ 'TopologicalTorsions':DataStructs.LongSparseIntVect,
15
+ 'Pharm2D':DataStructs.SparseBitVect,
16
+ 'Gobbi2D':DataStructs.SparseBitVect,
17
+ 'Morgan':DataStructs.UIntSparseIntVect
18
+ }
19
+ supportedSimilarityMethods=list(iterkeys(similarityMethods))
20
+
21
+
22
+ class LayeredOptions:
23
+ loadLayerFlags=0xFFFFFFFF
24
+ searchLayerFlags=0x7
25
+ minPath=1
26
+ maxPath=6
27
+ fpSize=1024
28
+ wordSize=32
29
+ nWords=fpSize//wordSize
30
+ @staticmethod
31
+ def GetFingerprint(mol,query=True):
32
+ if query:
33
+ flags=LayeredOptions.searchLayerFlags
34
+ else:
35
+ flags=LayeredOptions.loadLayerFlags
36
+ return Chem.LayeredFingerprint(mol,layerFlags=flags,
37
+ minPath=LayeredOptions.minPath,maxPath=LayeredOptions.maxPath,
38
+ fpSize=LayeredOptions.fpSize)
39
+ @staticmethod
40
+ def GetWords(mol,query=True):
41
+ txt = LayeredOptions.GetFingerprint(mol,query=query).ToBitString()
42
+ words = [int(txt[x:x+32],2) for x in range(0,len(txt),32)]
43
+ return words
44
+
45
+ @staticmethod
46
+ def GetQueryText(mol,query=True):
47
+ words = LayeredOptions.GetWords(mol,query=query)
48
+ colqs = []
49
+ for idx,word in enumerate(words):
50
+ if not word:
51
+ continue
52
+ idx = idx+1
53
+ colqs.append('%(word)d&Col_%(idx)d=%(word)d'%locals())
54
+ return ' and '.join(colqs)
55
+
56
+
57
+
58
+ def BuildSigFactory(options=None,fdefFile=None,
59
+ bins=[(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,100)],
60
+ skipFeats=('LumpedHydrophobe','ZnBinder')):
61
+ if options:
62
+ fdefFile = options.fdefFile
63
+ if not fdefFile:
64
+ raise ValueError('bad fdef file')
65
+ from rdkit.Chem import ChemicalFeatures
66
+ from rdkit.Chem.Pharm2D import SigFactory
67
+ featFactory = ChemicalFeatures.BuildFeatureFactory(fdefFile)
68
+ sigFactory = SigFactory.SigFactory(featFactory,
69
+ skipFeats=skipFeats,
70
+ trianglePruneBins=False)
71
+ sigFactory.SetBins(bins)
72
+ return sigFactory
73
+
74
+ def BuildAtomPairFP(mol):
75
+ from rdkit.Chem.AtomPairs import Pairs
76
+ fp=Pairs.GetAtomPairFingerprintAsIntVect(mol)
77
+ fp._sumCache = fp.GetTotalVal()
78
+ return fp
79
+ def BuildTorsionsFP(mol):
80
+ from rdkit.Chem.AtomPairs import Torsions
81
+ fp=Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol)
82
+ fp._sumCache = fp.GetTotalVal()
83
+ return fp
84
+ def BuildRDKitFP(mol):
85
+ fp=Chem.RDKFingerprint(mol,nBitsPerHash=1)
86
+ return fp
87
+ def BuildPharm2DFP(mol):
88
+ global sigFactory
89
+ from rdkit.Chem.Pharm2D import Generate
90
+ try:
91
+ fp=Generate.Gen2DFingerprint(mol,sigFactory)
92
+ except IndexError:
93
+ print('FAIL:',Chem.MolToSmiles(mol,True))
94
+ raise
95
+ return fp
96
+ def BuildMorganFP(mol):
97
+ from rdkit.Chem import rdMolDescriptors
98
+ fp = rdMolDescriptors.GetMorganFingerprint(mol,2)
99
+ fp._sumCache = fp.GetTotalVal()
100
+ return fp
101
+
102
+ def DepickleFP(pkl,similarityMethod):
103
+ if not isinstance(pkl,(bytes,str)):
104
+ pkl = str(pkl)
105
+ try:
106
+ klass=similarityMethods[similarityMethod]
107
+ fp = klass(pkl)
108
+ except:
109
+ import traceback
110
+ traceback.print_exc()
111
+ fp = cPickle.loads(pkl)
112
+ return fp
pool/shard006/Python/0057632_etl.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/opt/zenoss/bin/python
2
+ DEBUG_flag=False
3
+
4
+ import os
5
+ import sys
6
+ import re
7
+ import urllib2
8
+ import json
9
+ import time
10
+ import datetime
11
+
12
+ def help():
13
+ print "Usage:"
14
+ print "etl.py -url=YOUR_HOSTNAME -component=YOUR_COMPONENT_NAME -t=MAX_TIME_SINCE_LAST_UPDATE_IN_MINUTES"
15
+ sys.exit(3)
16
+
17
+ if (len(sys.argv) == 4):
18
+ args_str = sys.argv[1] +" "+ sys.argv[2] +" "+ sys.argv[3]
19
+ args_str = args_str.lower()
20
+ if ("-url=" in args_str and "-component=" in args_str and "-t=" in args_str):
21
+ url_str = "http://" + sys.argv[1].replace("-url=","") + "/api/component/"
22
+ component_str = sys.argv[2].replace("-component=","")
23
+ time_str = sys.argv[3].replace("-t=", "")
24
+ if DEBUG_flag:
25
+ print url_str+component_str, component_str, time_str
26
+ try:
27
+ request = urllib2.urlopen(url_str+component_str)
28
+ content = request.read()
29
+ ### Here is the main part of code ###
30
+ json_dict = json.loads(content)
31
+ status = json_dict["status"].lower()
32
+ if (status == "ok"):
33
+ #Here we should check the time since last update
34
+ time_from_json = time.strptime(json_dict["updated"], "%Y-%m-%d %H:%M:%S")
35
+ time_now = time.localtime()
36
+ time_from_json = datetime.datetime(*time_from_json[0:6])
37
+ time_now = datetime.datetime(*time_now[0:6])
38
+ time_delta = time_now - time_from_json
39
+ if DEBUG_flag:
40
+ print time_from_json
41
+ print time_now
42
+ print time_delta.seconds
43
+ print time_delta.days
44
+ if (time_delta.days > 0 or ((time_delta.seconds/60) > int(time_str)) ):
45
+ print "WARNING - Time since last update is greater than %s minutes" % str(time_str)
46
+ sys.exit(1)
47
+ else:
48
+ print "OK - Time since last update is less than %s minutes" % str(time_str)
49
+ sys.exit(0)
50
+ else:
51
+ message = json_dict["message"]
52
+ print 'CRITICAL - %s' % (message)
53
+ sys.exit(2)
54
+ #####################################
55
+ except (urllib2.URLError, urllib2.HTTPError), e:
56
+ print 'CRITICAL - %s' % (e)
57
+ sys.exit(2)
58
+ else:
59
+ print "UNKNOWN - Wrong arguments"
60
+ help()
61
+ sys.exit(3)
62
+ else:
63
+ print "UNKNOWN - Not enough arguments"
64
+ sys.exit(3)
pool/shard006/Python/0057637_utils.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # This file is part of Shuup.
3
+ #
4
+ # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
5
+ #
6
+ # This source code is licensed under the AGPLv3 license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+ from shuup_tests.utils import replace_urls
9
+
10
+
11
+ def get_admin_only_urls():
12
+ from django.conf.urls import patterns, url, include
13
+ from shuup.admin.urls import get_urls
14
+ class FauxUrlPatternsModule:
15
+ urlpatterns = get_urls()
16
+
17
+ return patterns('',
18
+ url(r'^sa/', include(FauxUrlPatternsModule, namespace="shuup_admin", app_name="shuup_admin")),
19
+ )
20
+
21
+ def admin_only_urls():
22
+ return replace_urls(get_admin_only_urls())
pool/shard006/Python/0057641_link_finder.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+ from HTMLParser import HTMLParser
3
+ from urllib2 import Request, urlopen
4
+ from urlparse import urljoin
5
+
6
+ class LinkFinder(HTMLParser):
7
+ def handle_starttag(self, tag, attrs):
8
+ if tag == 'a':
9
+ for (key, value) in attrs:
10
+ if key == 'href':
11
+ newUrl = urljoin(self.baseUrl, value)
12
+ self.links = self.links + [newUrl]
13
+
14
+ def getLinks(self, url):
15
+ self.links = []
16
+ self.baseUrl = url
17
+ response = urlopen(url)
18
+ try:
19
+ htmlBytes = response.read()
20
+ htmlString = htmlBytes.decode("utf-8")
21
+ self.feed(htmlString)
22
+ return list(set(self.links))
23
+ except Exception as e:
24
+ print(e)
25
+ return []
26
+
27
+ def spider(url, maxPages):
28
+ parser = LinkFinder()
29
+ for link in parser.getLinks(url=url):
30
+ print(link)
31
+
32
+ if __name__ == "__main__":
33
+ ## running ...
34
+ spider(url="http://eu.battle.net/wow/en/", maxPages=10)
pool/shard006/Python/0057645_sql.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+
3
+ with sqlite3.connect("blog.db") as connection:
4
+ c = connection.cursor()
5
+ c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
6
+ c.execute('INSERT INTO posts VALUES("Good", "I\'m good.")')
7
+ c.execute('INSERT INTO posts VALUES("Well", "I\'m well.")')
8
+ c.execute('INSERT INTO posts VALUES("Excellent", "I\'m excellent.")')
9
+ c.execute('INSERT INTO posts VALUES("Okay", "I\'m okay.")')
pool/shard006/Python/0057649_read.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Read the light level from a GPIO pin on a raspberry pi
4
+ # Must be used with GPIO 0.3.1a or later - earlier verions
5
+ # are not fast enough!
6
+
7
+ import time
8
+
9
+ class readLight:
10
+ def instantiate(self, input_gpio):
11
+ self.gpio = input_gpio
12
+ #self.gpio.setmode(self.gpio.BCM)
13
+ self.RCPIN = 38
14
+
15
+ def get_light_level(self):
16
+ reading = 0
17
+ self.gpio.setup(self.RCPIN, self.gpio.OUT)
18
+ self.gpio.output(self.RCPIN, self.gpio.LOW)
19
+ # 10 milliseconds
20
+ time.sleep(0.01)
21
+
22
+ self.gpio.setup(self.RCPIN, self.gpio.IN)
23
+ # This takes about 1 millisecond per loop cycle
24
+ while (self.gpio.input(self.RCPIN) == self.gpio.LOW):
25
+ reading += 1
26
+ return reading
pool/shard006/Python/0057651_euler38.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #coding=utf-8
2
+ dig='123456789'
3
+
4
+ result=[]
5
+ results=[]
6
+ for i in range(5000,9999):
7
+ tmp=str(i)+str(i*2)
8
+ flag=True
9
+ for j in dig:
10
+ if j not in tmp:
11
+ flag=False
12
+ if flag:
13
+ result.append(i)
14
+ results.append(int(tmp))
15
+
16
+ for i in range(100,333):
17
+ tmp=str(i)+str(i*2)+str(i*3)
18
+ flag=True
19
+ for j in dig:
20
+ if j not in tmp or len(tmp)!=9:
21
+ flag=False
22
+ break
23
+ if flag:
24
+ result.append(i)
25
+ results.append(int(tmp))
26
+
27
+ for i in range(10,34):
28
+ tmp=str(i)+str(i*2)+str(i*3)+str(i*4)
29
+ flag=True
30
+ for j in dig:
31
+ if j not in tmp or len(tmp)!=9:
32
+ flag=False
33
+ break
34
+ if flag:
35
+ result.append(i)
36
+ results.append(int(tmp))
37
+
38
+ for i in range(1,10):
39
+ tmp=str(i)+str(i*2)+str(i*3)+str(i*4)+str(i*5)
40
+ flag=True
41
+ for j in dig:
42
+ if j not in tmp or len(tmp)!=9:
43
+ flag=False
44
+ break
45
+ if flag:
46
+ result.append(i)
47
+ results.append(int(tmp))
48
+ print result
49
+ print results
50
+ print max(results)
pool/shard006/Python/0057652_spacy-nlp.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ from spacy.en import English
5
+
6
+ #INSTANTIATE SPACY PARSER
7
+ nlp = English()
8
+
9
+ def token_process(file_in):
10
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
11
+ _doc = nlp(file_in)
12
+ return _doc
13
+
14
+ def sent_process(file_in):
15
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
16
+ _doc = nlp(file_in)
17
+ _sents = _doc.sents
18
+ return _sents
19
+
20
+ def pos_process(file_in):
21
+ _pos_tagged = []
22
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
23
+ _doc = nlp(file_in)
24
+ # _doc = _doc.decode("utf-8")
25
+ # _doc = _doc.encode("ascii", "ignore")
26
+ for token in _doc:
27
+ token_pos = '{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.pos_)
28
+ _pos_tagged.append(token_pos)
29
+ return _pos_tagged
30
+
31
+ def lemma_process(file_in):
32
+ _lemmas = []
33
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
34
+ _doc = nlp(file_in)
35
+ for token in _doc:
36
+ token_lemma = '{}/{}/{}'.format(token.orth_.encode("ascii", "ignore"), token.lemma_.encode("ascii", "ignore"), token.pos_)
37
+ _lemmas.append(token_lemma)
38
+ return _lemmas
39
+
40
+ def ner_process(file_in):
41
+ _ner_tagged = []
42
+ _doc = nlp(file_in)
43
+ #_doc = nlp(unicode(file_in, encoding="utf-8"))
44
+ for token in _doc:
45
+ if token.ent_type_ != "":
46
+ token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, '_')
47
+ else:
48
+ token_ner = '{}/{}/{}/{}'.format(token.orth_.encode('ascii', 'ignore'), token.lemma_.encode("ascii", "ignore"), token.pos_, token.ent_type_)
49
+ _ner_tagged.append(token_ner)
50
+ return _ner_tagged
51
+
52
+ def main():
53
+ doc = []
54
+ sents = []
55
+ pos_tagged = []
56
+ lemmas = []
57
+ ner_tagged = []
58
+
59
+ file = ''
60
+ #Read file without line breaks
61
+ with open(sys.argv[1], 'r') as _file:
62
+ file = _file.read().replace('\n', ' ')
63
+
64
+ file = unicode(file, encoding="utf-8")
65
+
66
+ if file == '':
67
+ print 'File not read properly'
68
+ sys.exit()
69
+
70
+ if sys.argv[-1] == 'tokenize':
71
+ doc = token_process(file)
72
+ for token in doc:
73
+ print token
74
+
75
+ elif sys.argv[-1] == 'sent_split':
76
+ sents = sent_process(file)
77
+ for sent in sents:
78
+ print sent
79
+
80
+ elif sys.argv[-1] == 'pos_tag':
81
+ pos_tagged = pos_process(file)
82
+ for pos in pos_tagged:
83
+ print pos
84
+
85
+ elif sys.argv[-1] == 'lemmatize':
86
+ lemmas = lemma_process(file)
87
+ for lemma in lemmas:
88
+ print lemma
89
+
90
+ elif sys.argv[-1] == 'ner_tag':
91
+ ner_tagged = ner_process(file)
92
+ for ner in ner_tagged:
93
+ print ner
94
+
95
+ #BEGIN PREPROCESSING EXECUTION
96
+ main()
97
+
98
+ #TO KEEP LINE BREAKS
99
+ #with open('/Users/stc1563/programming/research/test-cases/_raw/lemmaCase-v6.txt', 'r') as f:
100
+ # strIn=f.read();
101
+ # for line in f:
102
+ # tokenSents = nlp(unicode(line,encoding="utf-8"))
103
+ # for span in tokenSents.sents:
104
+ # sent = ''.join(tokenSents[i].string for i in range(span.start, span.end)).strip()
105
+ # sents.append(sent)
106
+
107
+ #spacy parser creates tokens objects with callable methods that return nlp component results
108
+ #tokens = nlp(unicode(strIn,encoding="utf-8"))
109
+
110
+ #Sents property returns spans
111
+ #Spans have indices into original string
112
+ #where each index value returns a token
113
+ #SENTENCE SPLITTING
114
+ #for span in tokens.sents:
115
+ ##go from the start to the end of the span, returning each token in the sentence
116
+ ##combine each token using join()
117
+ # sent = ''.join(tokens[i].string for i in range(span.start, span.end)).strip()
118
+ # sents.append(sent)
119
+ #for sentence in sents:
120
+ # tokenCount+=1
121
+ # print '{}'.format(sentence.encode('ascii', 'ignore'))
122
+ #END SENTENCE SPLITTING
pool/shard006/Python/0057655_app_initialization_test.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from superdesk.tests import TestCase
2
+ from .app_initialize import AppInitializeWithDataCommand
3
+ from .app_scaffold_data import AppScaffoldDataCommand
4
+ from superdesk import get_resource_service
5
+
6
+
7
+ class AppInitializeWithDataCommandTestCase(TestCase):
8
+
9
+ def setUp(self):
10
+ super().setUp()
11
+
12
+ def test_app_initialization(self):
13
+ with self.app.app_context():
14
+ command = AppInitializeWithDataCommand()
15
+ result = command.run()
16
+ self.assertEquals(result, 0)
17
+
18
+ def test_app_initialization_multiple_loads(self):
19
+ with self.app.app_context():
20
+ command = AppInitializeWithDataCommand()
21
+ result = command.run()
22
+ self.assertEquals(result, 0)
23
+ result = command.run()
24
+ self.assertEquals(result, 0)
25
+
26
+ def data_scaffolding_test(self):
27
+ with self.app.app_context():
28
+ command = AppInitializeWithDataCommand()
29
+ result = command.run()
30
+ self.assertEquals(result, 0)
31
+
32
+ service = get_resource_service('text_archive')
33
+ docs = [{
34
+ 'type': 'text',
35
+ 'abstract': 'test abstract {}'.format(x),
36
+ 'headline': 'test headline {}'.format(x),
37
+ 'body_html': 'test long story body {}'.format(x)
38
+ } for x in range(0, 40)]
39
+ service.post(docs)
40
+
41
+ stories_per_desk = 2
42
+ existing_desks = 1
43
+ command = AppScaffoldDataCommand()
44
+ result = command.run(stories_per_desk)
45
+ self.assertEquals(result, 0)
46
+
47
+ cursor = get_resource_service('desks').get_from_mongo(None, {})
48
+ self.assertEquals(cursor.count(), existing_desks)
49
+
50
+ cursor = get_resource_service('archive').get_from_mongo(None, {})
51
+ self.assertEquals(cursor.count(), existing_desks * stories_per_desk)
pool/shard006/Python/0057662_filediff_comment.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from djblets.util.decorators import augment_method_from
2
+
3
+ from reviewboard.webapi.resources.base_diff_comment import \
4
+ BaseDiffCommentResource
5
+
6
+
7
+ class FileDiffCommentResource(BaseDiffCommentResource):
8
+ """Provides information on comments made on a particular per-file diff.
9
+
10
+ The list of comments cannot be modified from this resource. It's meant
11
+ purely as a way to see existing comments that were made on a diff. These
12
+ comments will span all public reviews.
13
+ """
14
+ allowed_methods = ('GET',)
15
+ policy_id = 'diff_comment'
16
+ model_parent_key = 'filediff'
17
+ uri_object_key = None
18
+
19
+ mimetype_list_resource_name = 'file-diff-comments'
20
+ mimetype_item_resource_name = 'file-diff-comment'
21
+
22
+ def get_queryset(self, request, diff_revision, filediff_id,
23
+ *args, **kwargs):
24
+ """Returns a queryset for Comment models.
25
+
26
+ This filters the query for comments on the specified review request
27
+ and made on the specified diff revision, which are either public or
28
+ owned by the requesting user.
29
+
30
+ If the queryset is being used for a list of comment resources,
31
+ then this can be further filtered by passing ``?interdiff-revision=``
32
+ on the URL to match the given interdiff revision, and
33
+ ``?line=`` to match comments on the given line number.
34
+ """
35
+ q = super(FileDiffCommentResource, self).get_queryset(
36
+ request, *args, **kwargs)
37
+ return q.filter(filediff__diffset__revision=diff_revision,
38
+ filediff=filediff_id)
39
+
40
+ @augment_method_from(BaseDiffCommentResource)
41
+ def get_list(self, request, diff_revision=None, *args, **kwargs):
42
+ """Returns the list of comments on a file in a diff.
43
+
44
+ This list can be filtered down by using the ``?line=`` and
45
+ ``?interdiff-revision=``.
46
+
47
+ To filter for comments that start on a particular line in the file,
48
+ using ``?line=``.
49
+
50
+ To filter for comments that span revisions of diffs, you can specify
51
+ the second revision in the range using ``?interdiff-revision=``.
52
+ """
53
+ pass
54
+
55
+
56
+ filediff_comment_resource = FileDiffCommentResource()
pool/shard006/Python/0057663_test_protocol_rdp_tpkt.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (c) 2014 Sylvain Peyrefitte
3
+ #
4
+ # This file is part of rdpy.
5
+ #
6
+ # rdpy is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ """
21
+ unit test for rdpy.protocol.rdp.tpkt module
22
+ """
23
+
24
+ import os, sys
25
+ # Change path so we find rdpy
26
+ sys.path.insert(1, os.path.join(sys.path[0], '..'))
27
+
28
+ import unittest
29
+ import rdpy.protocol.rdp.tpkt as tpkt
30
+ import rdpy.core.type as type
31
+ import rdpy.core.error as error
32
+
33
+ class TPKTTest(unittest.TestCase):
34
+ """
35
+ @summary: test case for tpkt layer (RDP)
36
+ """
37
+
38
+ class TPKT_PASS(Exception):
39
+ pass
40
+
41
+ class TPKT_FAIL(Exception):
42
+ pass
43
+
44
+ def test_tpkt_layer_connect(self):
45
+ """
46
+ @summary: test forward connect event to presentation layer
47
+ """
48
+ class Presentation(object):
49
+ def connect(self):
50
+ raise TPKTTest.TPKT_PASS()
51
+
52
+ layer = tpkt.TPKT(Presentation())
53
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.connect)
54
+
55
+ def test_tpkt_layer_recv(self):
56
+ """
57
+ @summary: test receive in classic case
58
+ """
59
+ class Presentation(object):
60
+ def connect(self):
61
+ pass
62
+ def recv(self, data):
63
+ data.readType(type.String("test_tpkt_layer_recv", constant = True))
64
+ raise TPKTTest.TPKT_PASS()
65
+
66
+ message = type.String("test_tpkt_layer_recv")
67
+
68
+ s = type.Stream()
69
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_X224), type.UInt8(), type.UInt16Be(type.sizeof(message) + 4), message))
70
+
71
+ layer = tpkt.TPKT(Presentation())
72
+ layer.connect()
73
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
74
+
75
+ def test_tpkt_layer_recv_fastpath(self):
76
+ """
77
+ @summary: test receive in fastpath case
78
+ """
79
+ class FastPathLayer(tpkt.IFastPathListener):
80
+ def setFastPathSender(self, fastPathSender):
81
+ pass
82
+ def recvFastPath(self, secFlag, fastPathS):
83
+ fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath", constant = True))
84
+ raise TPKTTest.TPKT_PASS()
85
+
86
+ message = type.String("test_tpkt_layer_recv_fastpath")
87
+
88
+ s = type.Stream()
89
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt8(type.sizeof(message) + 2), message))
90
+
91
+ layer = tpkt.TPKT(None)
92
+ layer.initFastPath(FastPathLayer())
93
+ layer.connect()
94
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
95
+
96
+ def test_tpkt_layer_recv_fastpath_ext_length(self):
97
+ """
98
+ @summary: test receive in fastpath case with extended length
99
+ """
100
+ class FastPathLayer(tpkt.IFastPathListener):
101
+ def setFastPathSender(self, fastPathSender):
102
+ pass
103
+ def recvFastPath(self, secflag, fastPathS):
104
+ fastPathS.readType(type.String("test_tpkt_layer_recv_fastpath_ext_length", constant = True))
105
+ raise TPKTTest.TPKT_PASS()
106
+
107
+ message = type.String("test_tpkt_layer_recv_fastpath_ext_length")
108
+
109
+ s = type.Stream()
110
+ s.writeType((type.UInt8(tpkt.Action.FASTPATH_ACTION_FASTPATH), type.UInt16Be((type.sizeof(message) + 3) | 0x8000), message))
111
+
112
+ layer = tpkt.TPKT(None)
113
+ layer.initFastPath(FastPathLayer())
114
+ layer.connect()
115
+ self.assertRaises(TPKTTest.TPKT_PASS, layer.dataReceived, s.getvalue())
pool/shard006/Python/0057664_rest-server-v2.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!flask/bin/python
2
+
3
+ """Alternative version of the ToDo RESTful server implemented using the
4
+ Flask-RESTful extension."""
5
+
6
+ from flask import Flask, jsonify, abort, make_response
7
+ from flask.ext.restful import Api, Resource, reqparse, fields, marshal
8
+ from flask.ext.httpauth import HTTPBasicAuth
9
+
10
+ app = Flask(__name__, static_url_path="")
11
+ api = Api(app)
12
+ auth = HTTPBasicAuth()
13
+
14
+
15
+ @auth.get_password
16
+ def get_password(username):
17
+ if username == 'miguel':
18
+ return 'python'
19
+ return None
20
+
21
+
22
+ @auth.error_handler
23
+ def unauthorized():
24
+ # return 403 instead of 401 to prevent browsers from displaying the default
25
+ # auth dialog
26
+ return make_response(jsonify({'message': 'Unauthorized access'}), 403)
27
+
28
+ tasks = [
29
+ {
30
+ 'id': 1,
31
+ 'title': u'Buy groceries',
32
+ 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
33
+ 'done': False
34
+ },
35
+ {
36
+ 'id': 2,
37
+ 'title': u'Learn Python',
38
+ 'description': u'Need to find a good Python tutorial on the web',
39
+ 'done': False
40
+ }
41
+ ]
42
+
43
+ task_fields = {
44
+ 'title': fields.String,
45
+ 'description': fields.String,
46
+ 'done': fields.Boolean,
47
+ 'uri': fields.Url('task')
48
+ }
49
+
50
+
51
+ class TaskListAPI(Resource):
52
+ decorators = [auth.login_required]
53
+
54
+ def __init__(self):
55
+ self.reqparse = reqparse.RequestParser()
56
+ self.reqparse.add_argument('title', type=str, required=True,
57
+ help='No task title provided',
58
+ location='json')
59
+ self.reqparse.add_argument('description', type=str, default="",
60
+ location='json')
61
+ super(TaskListAPI, self).__init__()
62
+
63
+ def get(self):
64
+ return {'tasks': [marshal(task, task_fields) for task in tasks]}
65
+
66
+ def post(self):
67
+ args = self.reqparse.parse_args()
68
+ task = {
69
+ 'id': tasks[-1]['id'] + 1,
70
+ 'title': args['title'],
71
+ 'description': args['description'],
72
+ 'done': False
73
+ }
74
+ tasks.append(task)
75
+ return {'task': marshal(task, task_fields)}, 201
76
+
77
+
78
+ class TaskAPI(Resource):
79
+ decorators = [auth.login_required]
80
+
81
+ def __init__(self):
82
+ self.reqparse = reqparse.RequestParser()
83
+ self.reqparse.add_argument('title', type=str, location='json')
84
+ self.reqparse.add_argument('description', type=str, location='json')
85
+ self.reqparse.add_argument('done', type=bool, location='json')
86
+ super(TaskAPI, self).__init__()
87
+
88
+ def get(self, id):
89
+ task = [task for task in tasks if task['id'] == id]
90
+ if len(task) == 0:
91
+ abort(404)
92
+ return {'task': marshal(task[0], task_fields)}
93
+
94
+ def put(self, id):
95
+ task = [task for task in tasks if task['id'] == id]
96
+ if len(task) == 0:
97
+ abort(404)
98
+ task = task[0]
99
+ args = self.reqparse.parse_args()
100
+ for k, v in args.items():
101
+ if v is not None:
102
+ task[k] = v
103
+ return {'task': marshal(task, task_fields)}
104
+
105
+ def delete(self, id):
106
+ task = [task for task in tasks if task['id'] == id]
107
+ if len(task) == 0:
108
+ abort(404)
109
+ tasks.remove(task[0])
110
+ return {'result': True}
111
+
112
+
113
+ api.add_resource(TaskListAPI, '/todo/api/v1.0/tasks', endpoint='tasks')
114
+ api.add_resource(TaskAPI, '/todo/api/v1.0/tasks/<int:id>', endpoint='task')
115
+
116
+
117
+ if __name__ == '__main__':
118
+ app.run(debug=True)
pool/shard006/Python/0057665_word_extractor.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of Boomer Core.
2
+ #
3
+ # Boomer Core is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # Boomer Core is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with Boomer Core. If not, see <http://www.gnu.org/licenses/>.
15
+ #
16
+ # Forked from Mycroft Core on 2017-07-29
17
+
18
+ from speech_recognition import AudioData
19
+
20
+ __author__ = 'jdorleans'
21
+
22
+
23
+ class WordExtractor:
24
+ SILENCE_SECS = 0.1
25
+ PRECISION_RATE = 0.01
26
+
27
+ def __init__(self, audio, recognizer, metrics):
28
+ self.audio = audio
29
+ self.recognizer = recognizer
30
+ self.audio_size = len(self.audio.frame_data)
31
+ self.delta = int(self.audio_size / 2)
32
+ self.begin = 0
33
+ self.end = self.audio_size
34
+ self.precision = int(self.audio_size * self.PRECISION_RATE)
35
+ self.silence_data = self.create_silence(self.SILENCE_SECS,
36
+ self.audio.sample_rate,
37
+ self.audio.sample_width)
38
+ self.metrics = metrics
39
+
40
+ def __add(self, is_begin, value):
41
+ if is_begin:
42
+ self.begin += value
43
+ else:
44
+ self.end += value
45
+
46
+ def __calculate_marker(self, is_begin):
47
+ dt = self.delta
48
+ sign = 1 if is_begin else -1
49
+
50
+ while dt > self.precision:
51
+ self.__add(is_begin, dt * sign)
52
+ segment = self.audio.frame_data[self.begin:self.end]
53
+ found = self.recognizer.is_recognized(segment, self.metrics)
54
+ if not found:
55
+ self.__add(is_begin, dt * -sign)
56
+ dt = int(dt / 2)
57
+
58
+ def calculate_range(self):
59
+ self.__calculate_marker(False)
60
+ self.__calculate_marker(True)
61
+
62
+ @staticmethod
63
+ def create_silence(seconds, sample_rate, sample_width):
64
+ return '\0' * int(seconds * sample_rate * sample_width)
65
+
66
+ def get_audio_data_before(self):
67
+ byte_data = self.audio.frame_data[0:self.begin] + self.silence_data
68
+ return AudioData(byte_data, self.audio.sample_rate,
69
+ self.audio.sample_width)
70
+
71
+ def get_audio_data_after(self):
72
+ byte_data = self.silence_data + self.audio.frame_data[self.end:
73
+ self.audio_size]
74
+ return AudioData(byte_data, self.audio.sample_rate,
75
+ self.audio.sample_width)
pool/shard006/Python/0057667_Choice.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ from CommandTemplate import CommandTemplate
4
+
5
+
6
+ class Command(CommandTemplate):
7
+ triggers = ['choice', 'choose']
8
+ helptext = "Helps you make a choice between options in a comma-separated list"
9
+
10
+ possibleReplies = ["Hmm, I'd go with {}", "Out of those, {} sounds the least bad", "{}, obviously",
11
+ "Let's go with... {}. No wait! No, yeah, that one", "I don't know! *rolls dice* Seems you should go for {}",
12
+ "Pick {0}, pick {0}!", "Eh, {} will do", "Why not {}?", "The first one! The last one! {}!", "Just pick {}"]
13
+
14
+ def pickRandomReply(self):
15
+ #Based on a suggestion by ekimekim
16
+ while True:
17
+ #Shuffle the list initially
18
+ random.shuffle(self.possibleReplies)
19
+ #Then just feed a reply every time one is requested. Once we run out, the list is reshuffled, ready to start again
20
+ for reply in self.possibleReplies:
21
+ yield reply
22
+
23
+ def execute(self, message):
24
+ """
25
+ :type message: IrcMessage.IrcMessage
26
+ """
27
+ replytext = None
28
+ if message.messagePartsLength == 0:
29
+ replytext = "My choice would be to provide me with some choices, preferably separated by commas"
30
+ else:
31
+ if ';' in message.message:
32
+ choices = message.message.split(';')
33
+ elif ',' in message.message:
34
+ choices = message.message.split(',')
35
+ else:
36
+ choices = message.messageParts
37
+ #Remove all the empty choices from the list
38
+ choices = filter(bool, choices)
39
+ if len(choices) == 0:
40
+ replytext = "That's just an empty list of choices... I'll pick nothing then"
41
+ elif len(choices) == 1:
42
+ replytext = "Ooh, that's a tough one. I'd go with the first option, seeing as there is only one"
43
+ else:
44
+ #Make a new random generator with the choices as seed, so every time you ask the bot to make a choice from the same list, it picks the same outcome
45
+ choice = random.Random(tuple(sorted(choices))).choice(choices).strip()
46
+ #Pick a random reply sentence, and then add in the previously picked choice, enclosed in quotes
47
+ replytext = self.pickRandomReply().next().format('"' + choice + '"')
48
+ message.bot.sendMessage(message.source, replytext)
pool/shard006/Python/0057668_hog_template.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Game of Hog."""
2
+
3
+ from dice import four_sided, six_sided, make_test_dice
4
+ from ucb import main, trace, log_current_line, interact
5
+
6
+ GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
7
+
8
+ ######################
9
+ # Phase 1: Simulator #
10
+ ######################
11
+
12
+ def roll_dice(num_rolls, dice=six_sided):
13
+ """Roll DICE for NUM_ROLLS times. Return either the sum of the outcomes,
14
+ or 1 if a 1 is rolled (Pig out). This calls DICE exactly NUM_ROLLS times.
15
+
16
+ num_rolls: The number of dice rolls that will be made; at least 1.
17
+ dice: A zero-argument function that returns an integer outcome.
18
+ """
19
+ # These assert statements ensure that num_rolls is a positive integer.
20
+ assert type(num_rolls) == int, 'num_rolls must be an integer.'
21
+ assert num_rolls > 0, 'Must roll at least once.'
22
+ "*** YOUR CODE HERE ***"
23
+
24
+ def take_turn(num_rolls, opponent_score, dice=six_sided):
25
+ """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free bacon).
26
+
27
+ num_rolls: The number of dice rolls that will be made.
28
+ opponent_score: The total score of the opponent.
29
+ dice: A function of no args that returns an integer outcome.
30
+ """
31
+ assert type(num_rolls) == int, 'num_rolls must be an integer.'
32
+ assert num_rolls >= 0, 'Cannot roll a negative number of dice.'
33
+ assert num_rolls <= 10, 'Cannot roll more than 10 dice.'
34
+ assert opponent_score < 100, 'The game should be over.'
35
+ "*** YOUR CODE HERE ***"
36
+ edits
37
+
38
+ def select_dice(score, opponent_score):
39
+ """Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a
40
+ multiple of 7, in which case select four-sided dice (Hog wild).
41
+ """
42
+ "*** YOUR CODE HERE ***"
43
+
44
+ def bid_for_start(bid0, bid1, goal=GOAL_SCORE):
45
+ """Given the bids BID0 and BID1 of each player, returns three values:
46
+
47
+ - the starting score of player 0
48
+ - the starting score of player 1
49
+ - the number of the player who rolls first (0 or 1)
50
+ """
51
+ assert bid0 >= 0 and bid1 >= 0, "Bids should be non-negative!"
52
+ assert type(bid0) == int and type(bid1) == int, "Bids should be integers!"
53
+
54
+ # The buggy code is below:
55
+ if bid0 == bid1:
56
+ return 0, goal, goal
57
+ if bid0 == bid1 - 5:
58
+ return 0, 0, 0
59
+ if bid1 == bid0 + 5:
60
+ return 10, 0, 1
61
+ if bid1 > bid0:
62
+ return bid1, bid0, 0
63
+ else:
64
+ return bid0, bid1, 1
65
+
66
+ def other(who):
67
+ """Return the other player, for a player WHO numbered 0 or 1.
68
+
69
+ >>> other(0)
70
+ 1
71
+ >>> other(1)
72
+ 0
73
+ """
74
+ return 1 - who
75
+
76
+ def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
77
+ """Simulate a game and return the final scores of both players, with
78
+ Player 0's score first, and Player 1's score second.
79
+
80
+ A strategy is a function that takes two total scores as arguments
81
+ (the current player's score, and the opponent's score), and returns a
82
+ number of dice that the current player will roll this turn.
83
+
84
+ strategy0: The strategy function for Player 0, who plays first
85
+ strategy1: The strategy function for Player 1, who plays second
86
+ score0 : The starting score for Player 0
87
+ score1 : The starting score for Player 1
88
+ """
89
+ who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
90
+ "*** YOUR CODE HERE ***"
91
+ return score0, score1 # You may want to change this line.
92
+
93
+ #######################
94
+ # Phase 2: Strategies #
95
+ #######################
96
+
97
+ def always_roll(n):
98
+ """Return a strategy that always rolls N dice.
99
+
100
+ A strategy is a function that takes two total scores as arguments
101
+ (the current player's score, and the opponent's score), and returns a
102
+ number of dice that the current player will roll this turn.
103
+
104
+ >>> strategy = always_roll(5)
105
+ >>> strategy(0, 0)
106
+ 5
107
+ >>> strategy(99, 99)
108
+ 5
109
+ """
110
+ def strategy(score, opponent_score):
111
+ return n
112
+ return strategy
113
+
114
+ # Experiments
115
+
116
+ def make_averaged(fn, num_samples=1000):
117
+ """Return a function that returns the average_value of FN when called.
118
+
119
+ To implement this function, you will have to use *args syntax, a new Python
120
+ feature introduced in this project. See the project description.
121
+
122
+ >>> dice = make_test_dice(3, 1, 5, 6)
123
+ >>> averaged_dice = make_averaged(dice, 1000)
124
+ >>> averaged_dice()
125
+ 3.75
126
+ >>> make_averaged(roll_dice, 1000)(2, dice)
127
+ 6.0
128
+
129
+ In this last example, two different turn scenarios are averaged.
130
+ - In the first, the player rolls a 3 then a 1, receiving a score of 1.
131
+ - In the other, the player rolls a 5 and 6, scoring 11.
132
+ Thus, the average value is 6.0.
133
+ """
134
+ "*** YOUR CODE HERE ***"
135
+
136
+ def max_scoring_num_rolls(dice=six_sided):
137
+ """Return the number of dice (1 to 10) that gives the highest average turn
138
+ score by calling roll_dice with the provided DICE. Assume that dice always
139
+ return positive outcomes.
140
+
141
+ >>> dice = make_test_dice(3)
142
+ >>> max_scoring_num_rolls(dice)
143
+ 10
144
+ """
145
+ "*** YOUR CODE HERE ***"
146
+
147
+ def winner(strategy0, strategy1):
148
+ """Return 0 if strategy0 wins against strategy1, and 1 otherwise."""
149
+ score0, score1 = play(strategy0, strategy1)
150
+ if score0 > score1:
151
+ return 0
152
+ else:
153
+ return 1
154
+
155
+ def average_win_rate(strategy, baseline=always_roll(5)):
156
+ """Return the average win rate (0 to 1) of STRATEGY against BASELINE."""
157
+ win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
158
+ win_rate_as_player_1 = make_averaged(winner)(baseline, strategy)
159
+ return (win_rate_as_player_0 + win_rate_as_player_1) / 2 # Average results
160
+
161
+ def run_experiments():
162
+ """Run a series of strategy experiments and report results."""
163
+ if True: # Change to False when done finding max_scoring_num_rolls
164
+ six_sided_max = max_scoring_num_rolls(six_sided)
165
+ print('Max scoring num rolls for six-sided dice:', six_sided_max)
166
+ four_sided_max = max_scoring_num_rolls(four_sided)
167
+ print('Max scoring num rolls for four-sided dice:', four_sided_max)
168
+
169
+ if False: # Change to True to test always_roll(8)
170
+ print('always_roll(8) win rate:', average_win_rate(always_roll(8)))
171
+
172
+ if False: # Change to True to test bacon_strategy
173
+ print('bacon_strategy win rate:', average_win_rate(bacon_strategy))
174
+
175
+ if False: # Change to True to test swap_strategy
176
+ print('swap_strategy win rate:', average_win_rate(swap_strategy))
177
+
178
+ if False: # Change to True to test final_strategy
179
+ print('final_strategy win rate:', average_win_rate(final_strategy))
180
+
181
+ "*** You may add additional experiments as you wish ***"
182
+
183
+ # Strategies
184
+
185
+ def bacon_strategy(score, opponent_score, margin=8, num_rolls=5):
186
+ """This strategy rolls 0 dice if that gives at least MARGIN points,
187
+ and rolls NUM_ROLLS otherwise.
188
+ """
189
+ "*** YOUR CODE HERE ***"
190
+ return None # Replace this statement
191
+
192
+ def swap_strategy(score, opponent_score, margin=8, num_rolls=5):
193
+ """This strategy rolls 0 dice when it would result in a beneficial swap and
194
+ rolls NUM_ROLLS if it would result in a harmful swap. It also rolls
195
+ 0 dice if that gives at least MARGIN points and rolls
196
+ NUM_ROLLS otherwise.
197
+ """
198
+ "*** YOUR CODE HERE ***"
199
+ return None # Replace this statement
200
+
201
+
202
+ def final_strategy(score, opponent_score):
203
+ """Write a brief description of your final strategy.
204
+
205
+ *** YOUR DESCRIPTION HERE ***
206
+ """
207
+ "*** YOUR CODE HERE ***"
208
+ return 5 # Replace this statement
209
+
210
+
211
+ ##########################
212
+ # Command Line Interface #
213
+ ##########################
214
+
215
+ # Note: Functions in this section do not need to be changed. They use features
216
+ # of Python not yet covered in the course.
217
+
218
+
219
+ @main
220
+ def run(*args):
221
+ """Read in the command-line argument and calls corresponding functions.
222
+
223
+ This function uses Python syntax/techniques not yet covered in this course.
224
+ """
225
+ import argparse
226
+ parser = argparse.ArgumentParser(description="Play Hog")
227
+ parser.add_argument('--run_experiments', '-r', action='store_true',
228
+ help='Runs strategy experiments')
229
+ args = parser.parse_args()
230
+
231
+ if args.run_experiments:
232
+ run_experiments()
pool/shard006/Python/0057670_test_image_lst.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===============================================================================
2
+ # Copyright 2017 dgketchum
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ===============================================================================
16
+
17
+ import os
18
+ import unittest
19
+ from fiona import open as fopen
20
+ from rasterio import open as rasopen
21
+
22
+ from sat_image.image import Landsat8, Landsat5, Landsat7
23
+
24
+
25
+ class TestImageLST5(unittest.TestCase):
26
+ def setUp(self):
27
+ self.dir_name_LT5 = 'tests/data/ssebop_test/lt5/041_025/2000/LT50410252000194AAA01'
28
+ self.l5 = Landsat5(self.dir_name_LT5)
29
+ self.lst = self.l5.land_surface_temp()
30
+ self.lst_raster_path = os.path.join(self.dir_name_LT5, 'lst5_test.tif')
31
+ self.l5.save_array(self.lst, self.lst_raster_path)
32
+ self.point_file = 'tests/data/points/041_025_CA_Let_points.shp'
33
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lt5/041_025/2000/',
34
+ 'LT50410252000194AAA01',
35
+ 'LT50410252000194AAA01_LST_EEF.tif')
36
+
37
+ def test_surface_temps(self):
38
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
39
+ eef_raster=self.eef_lst_raster,
40
+ points=self.point_file)
41
+ for key, val in points_dict.items():
42
+ eef = val['eef_lst']
43
+ lst = val['lst_found']
44
+ ratio = eef / lst
45
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
46
+ key, ratio))
47
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
48
+ os.remove(self.lst_raster_path)
49
+
50
+
51
+ class TestImageLST7(unittest.TestCase):
52
+ def setUp(self):
53
+ self.dir_name_LT7 = 'tests/data/ssebop_test/le7/041_025/2000/LE70410252000234PAC00'
54
+ self.l7 = Landsat7(self.dir_name_LT7)
55
+ self.lst = self.l7.land_surface_temp()
56
+ self.lst_raster_path = os.path.join(self.dir_name_LT7, 'lst7_test.tif')
57
+ self.l7.save_array(self.lst, self.lst_raster_path)
58
+ self.point_file = 'tests/data/points/041_025_CA_Let_points.shp'
59
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/le7/041_025/2000',
60
+ 'LE70410252000234PAC00/LE70410252000234PAC00_LST_EEF.tif')
61
+
62
+ def test_surface_temps(self):
63
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
64
+ eef_raster=self.eef_lst_raster,
65
+ points=self.point_file)
66
+ for key, val in points_dict.items():
67
+ eef = val['eef_lst']
68
+ lst = val['lst_found']
69
+ ratio = eef / lst
70
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
71
+ key, ratio))
72
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
73
+ os.remove(self.lst_raster_path)
74
+
75
+
76
+ class TestImageLST8(unittest.TestCase):
77
+ def setUp(self):
78
+ self.dir_name_LT8 = 'tests/data/ssebop_test/lc8/038_027/2014/LC80380272014227LGN01'
79
+ self.l8 = Landsat8(self.dir_name_LT8)
80
+ self.lst = self.l8.land_surface_temp()
81
+ # self.lst_raster_path = os.path.join(self.dir_name_LT8, 'lst8_test.tif')
82
+ self.lst_raster_path = '/data01/images/sandbox/lst8_test.tif'
83
+ self.l8.save_array(self.lst, self.lst_raster_path)
84
+ self.point_file = 'tests/data/points/038_027_US_Mj_points.shp'
85
+ self.eef_lst_raster = os.path.join('tests/data/ssebop_test/lc8/038_027',
86
+ '2014/LC80380272014227LGN01/LC80380272014227LGN01_LST_EEF.tif')
87
+
88
+ def test_surface_temps(self):
89
+ points_dict = raster_point_extract(lst_raster=self.lst_raster_path,
90
+ eef_raster=self.eef_lst_raster,
91
+ points=self.point_file)
92
+ for key, val in points_dict.items():
93
+ eef = val['eef_lst']
94
+ lst = val['lst_found']
95
+ ratio = eef / lst
96
+ print('Ratio at {} of EEFlux:LST calculated is {}.'.format(
97
+ key, ratio))
98
+ self.assertAlmostEqual(ratio, 1.0, delta=0.01)
99
+ os.remove(self.lst_raster_path)
100
+
101
+
102
+ # ===================== ANCILLARY FUNCTIONS =================================
103
+
104
+ def raster_point_extract(lst_raster, eef_raster, points):
105
+ point_data = {}
106
+ with fopen(points, 'r') as src:
107
+ for feature in src:
108
+ try:
109
+ name = feature['properties']['Name']
110
+ except KeyError:
111
+ name = feature['properties']['FID']
112
+ point_data[name] = {'coords': feature['geometry']['coordinates']}
113
+
114
+ with rasopen(lst_raster, 'r') as src:
115
+ lst_arr = src.read()
116
+ lst_arr = lst_arr.reshape(lst_arr.shape[1], lst_arr.shape[2])
117
+ lst_affine = src.transform
118
+
119
+ with rasopen(eef_raster, 'r') as src:
120
+ eef_lst = src.read()
121
+ eef_lst = eef_lst.reshape(eef_lst.shape[1], eef_lst.shape[2])
122
+ eef_affine = src.transform
123
+
124
+ for key, val in point_data.items():
125
+ x, y, z = val['coords']
126
+ col, row = ~lst_affine * (x, y)
127
+ val = lst_arr[int(row), int(col)]
128
+ point_data[key]['lst_found'] = val
129
+ point_data[key]['lst_row_col'] = int(row), int(col)
130
+
131
+ col, row = ~eef_affine * (x, y)
132
+ val = eef_lst[int(row), int(col)]
133
+ point_data[key]['eef_lst'] = val
134
+ point_data[key]['eef_row_col'] = int(row), int(col)
135
+
136
+ return point_data
137
+
138
+
139
+ if __name__ == '__main__':
140
+ unittest.main()
141
+
142
+ # ===============================================================================
pool/shard006/Python/0057672_rating.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ import json
3
+ from django.http import HttpResponse
4
+ from feedhoos.folder.models.folder import FolderModel
5
+
6
+
7
+ def execute(request):
8
+ "folderのratingを変更する。"
9
+ folder_id = request.POST["id"]
10
+ rating = request.POST["rating"]
11
+ folder_model = FolderModel.objects.get(pk=folder_id)
12
+ folder_model.rating = int(rating)
13
+ folder_model.save()
14
+ response_json = json.dumps({"msg": "OK"}, ensure_ascii=False, skipkeys=True)
15
+ return HttpResponse(response_json, content_type='application/json')
pool/shard006/Python/0057673_get_build_status.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Gets the build status of specific Bamboo builds from Jut's Bamboo instance
4
+
5
+ import requests
6
+
7
+ # The list of builds we're interested in
8
+ builds = ["CAM-AMT", "CAM-CMT","CAM-SMOKE","CAM-IMT","CAM-QUAM","CAM-JUM","CAM-VIM","CAM-EAM","CAM-SMT"]
9
+ #builds = ["CAM-PMT"]
10
+ build_results = []
11
+
12
+ # Get the status of each build and add it to the build_results list
13
+ for build in builds:
14
+ r = requests.get('https://jut-io.atlassian.net/builds/rest/api/latest/result/' + build + '-latest.json', auth=('robot','mrroboto'))
15
+ build_results.append(r.json()['buildState'])
16
+ print r.json()['buildState']
17
+
18
+ resultfile = open('/Users/davidcook/code/scratch/build-status-leds/build_status_display/data/build_results.txt', 'w+')
19
+
20
+ failed_count = 0
21
+
22
+ # Count the number of builds that failed
23
+ for result in build_results:
24
+ if result == "Failed":
25
+ failed_count += 1
26
+
27
+ # If any of the builds failed, write Failed to the file. If they all passed, write Successful
28
+ if failed_count > 0:
29
+ resultfile.write("Failed\n")
30
+ else:
31
+ resultfile.write("Successful\n")
32
+
33
+ resultfile.close()
pool/shard006/Python/0057675_EurostagState.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2016, Pierre Saikaly (saikalypierre@gmail.com)
4
+
5
+ # This Source Code Form is subject to the terms of the Mozilla Public
6
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
7
+ # You can obtain one at http://mozilla.org/MPL/2.0/.
8
+
9
+ #===========================#
10
+ # created on 07 sept 2016
11
+ #===========================#
12
+
13
+ # Import Python dependencies :
14
+ # ----------------------------
15
+ import os
16
+ import sys
17
+ import time
18
+ import argparse
19
+
20
+ # Script :
21
+ # --------
22
+ def CheckEurostagState(folder):
23
+ """
24
+ Reads eurostagOutputFile and check if the situation at the beginning is stable
25
+ or unstable
26
+ Inputs :
27
+ - eurostagOutputFile : file.out containing the informations
28
+ Outputs :
29
+ - 0 -> Situation is stable
30
+ - 1 -> Situation is unstable
31
+ Used in :
32
+ - main
33
+ """
34
+
35
+ etat = "ETAT D'EQUILIBRE A 0.10000D-02 VERIFIE POUR LES EQUATIONS MACHINE"
36
+ etat2 = "ETAT D'EQUILIBRE A 0.10000D-02 NON VERIFIE DANS LES EQUATIONS SUIVANTES"
37
+ eurostagOutputFile = os.path.join(folder,"sim_pre_fault.out")
38
+
39
+
40
+
41
+ # Checking Eurostag status :
42
+ # --------------------------
43
+ if etat in open(eurostagOutputFile, 'U').read():
44
+ # Eurostag returns stable
45
+ status = 0
46
+ else:
47
+ # Eurostag returns unstable :
48
+ # ---------------------------
49
+ equi_value = []
50
+ with open(eurostagOutputFile, 'U') as outfile:
51
+ lines = outfile.readlines()
52
+ for i, line in enumerate(lines):
53
+ if etat2 in line:
54
+ k = i+5
55
+ while (lines[k]!="1\n" and lines[k]!="\n"):
56
+ machine_name = lines[k].split()[0]
57
+ value_line = lines[k].split()[-2]
58
+ value_real = float(value_line.split("D")[0])*10**int(value_line.split("D")[1])
59
+ if (abs(value_real) > 0.01):
60
+ with open('ecart_groupe.csv','a') as egf:
61
+ egf.write(folder + ';' + machine_name + ';' + str(value_real) + '\n')
62
+ equi_value.append(abs(value_real))
63
+ k += 1
64
+ # Checking tolerance :
65
+ # --------------------
66
+ if (len(equi_value) > 0):
67
+ if (max(equi_value) < 0.01):
68
+ status = 0 # Stable state within tolerance
69
+ else:
70
+ status = 1 # Unstable state
71
+
72
+ else:
73
+ status = 0 # Stable state
74
+
75
+ return status
76
+
77
+ def main():
78
+ """
79
+ Get list of eurostag simulation folders and check if thoses situations are
80
+ stable or not. The outputs are stored in eurostag_status.txt file
81
+ """
82
+
83
+ # Creating output file :
84
+ # ----------------------
85
+ print "Beginning writing outputs for folders in directory..."
86
+
87
+ with open('eurostag_status.txt','w') as f:
88
+ f.write("# " + time.strftime("%d/%m/%y") + "\n")
89
+
90
+ with open('ecart_groupe.csv','w') as egf:
91
+ egf.write(time.strftime("%d/%m/%y") + "\n")
92
+ egf.write("Situations;groupe;valeur\n")
93
+
94
+ # Checking folders and writing output :
95
+ # -------------------------------------
96
+ with open('eurostag_status.txt','a') as f:
97
+ for folder in os.listdir('.'):
98
+ if folder.startswith('itesla_eurostag_stabilization_'):
99
+ f.write(folder + " " + str(CheckEurostagState(folder)) + '\n')
100
+
101
+ print "Done writing outputs in eurostag_status.txt"
102
+ print "Done analysis in ecart_groupe.csv"
103
+
104
+ if __name__=='__main__':
105
+
106
+ parser = argparse.ArgumentParser(description='Check eurostag status of working directory of specific folder')
107
+ parser.add_argument('-p','--eur_path', help='path of eurostag folder', required=False)
108
+ args = parser.parse_args()
109
+
110
+ if (args.eur_path):
111
+ with open('ecart_groupe.csv','w') as egf:
112
+ egf.write(time.strftime("%d/%m/%y") + "\n")
113
+ egf.write("Situations;groupe;valeur\n")
114
+
115
+ print args.eur_path, ' ', CheckEurostagState(args.eur_path)
116
+ print "Done analysis in ecart_groupe.csv"
117
+ else:
118
+ main()
pool/shard006/Python/0057680_pluginmanager.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ '''
4
+ @author: nick
5
+ '''
6
+
7
+ import imp
8
+ import os
9
+ import logging
10
+
11
+ class PluginManager():
12
+
13
+ def __init__(self, directory):
14
+ self.pluginDirs = [directory]
15
+ self.plugins = {}
16
+ self.logger = logging.getLogger('picsort')
17
+
18
+ def addDirectory(self, directory):
19
+ self.pluginDirs.append(directory)
20
+
21
+
22
+ def getPlugin(self, name):
23
+ return self.plugins[name]
24
+
25
+
26
+ def listPlugins(self):
27
+ plugins = []
28
+
29
+ for directory in self.pluginDirs:
30
+ if os.path.exists(directory):
31
+ for f in os.listdir(directory):
32
+ if f.endswith(".py") and not f == "__init__.py":
33
+ plugins.append(os.path.join(directory, f))
34
+ else:
35
+ self.logger.warn("directory not exists: {}".format(directory))
36
+
37
+ return plugins
38
+
39
+
40
+ def loadPlugins(self):
41
+
42
+ for plugin in self.listPlugins():
43
+ try:
44
+ name, _ = os.path.splitext(os.path.split(plugin)[1])
45
+
46
+ submodule = imp.load_source(name, plugin)
47
+ self.plugins[name] = submodule
48
+ except Exception, e:
49
+ self.logger.error(e)
pool/shard006/Python/0057683_routing_metal.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FIXME: electrical connections should ignore port orientation
3
+ """
4
+
5
+ import gdsfactory as gf
6
+
7
+
8
+ if __name__ == "__main__":
9
+
10
+ c = gf.Component("mzi_with_pads")
11
+ c1 = c << gf.components.mzi_phase_shifter_top_heater_metal(length_x=70)
12
+ c2 = c << gf.components.pad_array90(columns=2)
13
+
14
+ c2.ymin = c1.ymax + 20
15
+ c2.x = 0
16
+ c1.x = 0
17
+
18
+ ports1 = c1.get_ports_list(width=11)
19
+ ports2 = c2.get_ports_list()
20
+
21
+ routes = gf.routing.get_bundle(
22
+ ports1=ports1,
23
+ ports2=ports2,
24
+ cross_section=gf.cross_section.metal1,
25
+ width=5,
26
+ bend=gf.components.wire_corner,
27
+ )
28
+ for route in routes:
29
+ c.add(route.references)
30
+
31
+ c.show()
pool/shard006/Python/0057685_rootramfs.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+
3
+
4
+ __author__ = 'volodja'
5
+
6
+
7
+ import os
8
+ import re
9
+ import sys
10
+
11
+
12
+ def printList(name, list_):
13
+ print(name + ":")
14
+ for row in list_:
15
+ print(str(row).replace("\n", ""))
16
+
17
+
18
+ def executeShellCommand(command):
19
+ print("exec: " + command)
20
+ result_pipe = os.popen(command)
21
+ result_ = result_pipe.readlines()
22
+ result = []
23
+ for line in result_:
24
+ result.append(line.replace('\n', ''))
25
+ return result
26
+
27
+
28
+ def readFSTab():
29
+ file_fstab = open("/etc/fstab")
30
+ #file_fstab = open("/etc/fstab.1")
31
+ fstab_text = file_fstab.readlines()
32
+ fstab = []
33
+ file_fstab.close()
34
+
35
+ for line in fstab_text:
36
+ if line[0] != "#":
37
+ fstab_line = re.split(r"\s+", line.replace("\n", "").replace("UUID=", ""))
38
+ fstab.append(fstab_line)
39
+
40
+ #printList("fstab", fstab)
41
+ return fstab
42
+
43
+
44
+ def mountSyncFSTab():
45
+ fstab = readFSTab()
46
+ mount = executeShellCommand("mount")
47
+
48
+ #print "fstab: " + str(fstab)
49
+ #print("mount: " + str(mount))
50
+
51
+ fstab_to_mount = []
52
+ for row_fstab in fstab:
53
+ if len(row_fstab) < 2:
54
+ continue
55
+ is_need_mount = True
56
+ if row_fstab[1] == "/":
57
+ mount_point = "/ram/sync"
58
+ else:
59
+ mount_point = "/ram/sync" + row_fstab[1]
60
+ for row_mount in mount:
61
+ if len(row_fstab) > 1 and (row_fstab[0][0:4] != "/ram" or (row_fstab[0][0:4] == "/ram" and row_mount.split(" ")[2] == mount_point)):
62
+ is_need_mount = False
63
+ break
64
+ if is_need_mount:
65
+ fstab_to_mount.append(row_fstab)
66
+
67
+ #print "fstab_to_mount = " + str(fstab_to_mount)
68
+ #exit(0)
69
+ for row_fstab in fstab_to_mount:
70
+ mount = executeShellCommand("mkdir -p /ram/sync" + row_fstab[1] + " && mount -t " + row_fstab[2] +
71
+ " /dev/disk/by-uuid/" + row_fstab[0][4:] + " /ram/sync" + row_fstab[1] + " || echo 'mount fail'")
72
+ if len(mount) > 0:
73
+ print("error: " + str(mount))
74
+ exit(1)
75
+
76
+
77
+ def umountSyncFSTab():
78
+ #fstab = readFSTab()
79
+ mount = executeShellCommand("mount")
80
+ fstab_to_umount = []
81
+ is_was_root = False
82
+
83
+ for row_mount in mount:
84
+ mount_point = str(row_mount.split(" ")[2])
85
+ if mount_point[0:9] == "/ram/sync":
86
+ if len(mount_point) > 9:
87
+ fstab_to_umount.append(mount_point)
88
+ else:
89
+ is_was_root = True
90
+ if is_was_root:
91
+ fstab_to_umount.append("/ram/sync")
92
+
93
+ for row_umount in fstab_to_umount:
94
+ umount = executeShellCommand("umount " + row_umount)
95
+ if len(umount) > 0:
96
+ print("error: " + str(umount))
97
+ exit(1)
98
+
99
+
100
+ def syncCommand(args, command_, is_reverse = False):
101
+ paths = []
102
+
103
+ for row_args in args:
104
+ if row_args != "--exclude":
105
+ paths.append(os.path.abspath(row_args))
106
+
107
+ if is_reverse:
108
+ src = "/ram/sync" + paths[0]
109
+ dst = paths[0]
110
+ else:
111
+ src = paths[0]
112
+ dst = "/ram/sync" + paths[0]
113
+
114
+
115
+ if os.path.isdir(paths[0]):
116
+ src = src + "/"
117
+
118
+ del paths[0]
119
+
120
+ #user_name = getpass.getuser()
121
+ command = command_ + " "
122
+ command = command + "--exclude '*/.gvfs' "
123
+ command = command + "--exclude '/run/user/*/gvfs' "
124
+ command = command + "--exclude '/media' "
125
+ command = command + "--exclude '/mnt' "
126
+ command = command + "--exclude '/dev' "
127
+ command = command + "--exclude '/sys' "
128
+ command = command + "--exclude '/proc' "
129
+ command = command + "--exclude '/selinux' "
130
+ command = command + "--exclude '/ram' "
131
+ command = command + "--exclude '/boot' "
132
+
133
+
134
+ for row_paths in paths:
135
+ command = command + "--exclude '" + row_paths + "' "
136
+
137
+ command = command + "\"" + src + "\" \"" + dst + "\" | grep -v 'xfer#' | grep -v 'xfr#' > /dev/tty && sync"
138
+ rsync = executeShellCommand(command)
139
+ #printList(command_, rsync)
140
+
141
+
142
+ def syncPath(args):
143
+ syncCommand(args, "rsync --progress --delete -a")
144
+
145
+
146
+ def diffPath(args):
147
+ syncCommand(args, "diff -r")
148
+
149
+
150
+ def resetPath(args):
151
+ syncCommand(args, "rsync --progress --delete -a", True)
152
+
153
+
154
+ if len(sys.argv) >= 3 and sys.argv[1] == "--sync":
155
+ mountSyncFSTab()
156
+ syncPath(sys.argv[2:])
157
+ umountSyncFSTab()
158
+ exit(0)
159
+
160
+ if len(sys.argv) >= 3 and sys.argv[1] == "--reset":
161
+ mountSyncFSTab()
162
+ resetPath(sys.argv[2:])
163
+ umountSyncFSTab()
164
+ exit(0)
165
+
166
+ if len(sys.argv) >= 3 and sys.argv[1] == "--diff":
167
+ mountSyncFSTab()
168
+ diffPath(sys.argv[2:])
169
+ umountSyncFSTab()
170
+ exit(0)
171
+
172
+
173
+ print("usage: rootramfs --sync sync_path [exclude_path1] [exclude_path2] ...")
174
+ print("usage: rootramfs --reset sync_path [exclude_path1] [exclude_path2] ...")
175
+ print("usage: rootramfs --diff sync_path [exclude_path1] [exclude_path2] ...")
pool/shard006/Python/0057686_gotoread.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scrapy.selector import Selector
2
+ from scrapy.linkextractors import LinkExtractor
3
+ from scrapy.spiders import CrawlSpider, Rule
4
+ from crawlers.items import MagazineItem
5
+
6
+ import urllib.parse
7
+
8
+ class GotoreadSpider(CrawlSpider):
9
+ name = 'gotoread'
10
+ allowed_domains = ['gotoread.com']
11
+ start_urls = ['http://www.gotoread.com/scatalog3687.html',
12
+ 'http://www.gotoread.com/scatalog3078.html',
13
+ 'http://www.gotoread.com/scatalog3063.html',
14
+ 'http://www.gotoread.com/scatalog3010.html',
15
+ 'http://www.gotoread.com/scatalog3117.html',
16
+ 'http://www.gotoread.com/scatalog3533.html',
17
+ 'http://www.gotoread.com/scatalog3482.html',
18
+ 'http://www.gotoread.com/scatalog3477.html'
19
+ ]
20
+
21
+ rules = (
22
+ Rule(LinkExtractor(allow=r'/mag/\d+/$'), callback='parse_item', follow=False),
23
+ )
24
+
25
+ def parse_item(self, response):
26
+ sel = Selector(response)
27
+ i = MagazineItem()
28
+ i['name'] = sel.xpath("//div[@class='ProName']/h1/text()").extract()
29
+ i['description'] = sel.xpath("//div[@class='content box-line word']").extract()
30
+ i['price'] = sel.xpath("//em/del/text()").extract()[0]
31
+ i['category'] = sel.xpath("//div[@id='DaoHang']/a/text()").extract()[-1]
32
+ imgurl = sel.xpath("//img[@id='magcoverpic']/@src").extract()[0]
33
+ absurl = urlparse.urljoin("http://www.gotoread.com/", imgurl.strip())
34
+ i['image_urls'] = [absurl]
35
+ return i
pool/shard006/Python/0057692_mongodb_parameter.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # (c) 2016, Loic Blot <loic.blot@unix-experience.fr>
5
+ # Sponsored by Infopro Digital. http://www.infopro-digital.com/
6
+ # Sponsored by E.T.A.I. http://www.etai.fr/
7
+ #
8
+ # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
+
10
+ from __future__ import absolute_import, division, print_function
11
+ __metaclass__ = type
12
+
13
+
14
+ ANSIBLE_METADATA = {'metadata_version': '1.1',
15
+ 'status': ['preview'],
16
+ 'supported_by': 'community'}
17
+
18
+
19
+ DOCUMENTATION = '''
20
+ ---
21
+ module: mongodb_parameter
22
+ short_description: Change an administrative parameter on a MongoDB server.
23
+ description:
24
+ - Change an administrative parameter on a MongoDB server.
25
+ version_added: "2.1"
26
+ options:
27
+ login_user:
28
+ description:
29
+ - The username used to authenticate with
30
+ login_password:
31
+ description:
32
+ - The password used to authenticate with
33
+ login_host:
34
+ description:
35
+ - The host running the database
36
+ default: localhost
37
+ login_port:
38
+ description:
39
+ - The port to connect to
40
+ default: 27017
41
+ login_database:
42
+ description:
43
+ - The database where login credentials are stored
44
+ replica_set:
45
+ description:
46
+ - Replica set to connect to (automatically connects to primary for writes)
47
+ database:
48
+ description:
49
+ - The name of the database to add/remove the user from
50
+ required: true
51
+ ssl:
52
+ description:
53
+ - Whether to use an SSL connection when connecting to the database
54
+ type: bool
55
+ default: 'no'
56
+ param:
57
+ description:
58
+ - MongoDB administrative parameter to modify
59
+ required: true
60
+ value:
61
+ description:
62
+ - MongoDB administrative parameter value to set
63
+ required: true
64
+ param_type:
65
+ description:
66
+ - Define the parameter value (str, int)
67
+ default: str
68
+
69
+ notes:
70
+ - Requires the pymongo Python package on the remote host, version 2.4.2+. This
71
+ can be installed using pip or the OS package manager. @see http://api.mongodb.org/python/current/installation.html
72
+ requirements: [ "pymongo" ]
73
+ author: "Loic Blot (@nerzhul)"
74
+ '''
75
+
76
+ EXAMPLES = '''
77
+ # Set MongoDB syncdelay to 60 (this is an int)
78
+ - mongodb_parameter:
79
+ param: syncdelay
80
+ value: 60
81
+ param_type: int
82
+ '''
83
+
84
+ RETURN = '''
85
+ before:
86
+ description: value before modification
87
+ returned: success
88
+ type: string
89
+ after:
90
+ description: value after modification
91
+ returned: success
92
+ type: string
93
+ '''
94
+
95
+ import os
96
+ import traceback
97
+
98
+ try:
99
+ from pymongo.errors import ConnectionFailure
100
+ from pymongo.errors import OperationFailure
101
+ from pymongo import version as PyMongoVersion
102
+ from pymongo import MongoClient
103
+ except ImportError:
104
+ try: # for older PyMongo 2.2
105
+ from pymongo import Connection as MongoClient
106
+ except ImportError:
107
+ pymongo_found = False
108
+ else:
109
+ pymongo_found = True
110
+ else:
111
+ pymongo_found = True
112
+
113
+ from ansible.module_utils.basic import AnsibleModule
114
+ from ansible.module_utils.six.moves import configparser
115
+ from ansible.module_utils._text import to_native
116
+
117
+
118
+ # =========================================
119
+ # MongoDB module specific support methods.
120
+ #
121
+
122
+ def load_mongocnf():
123
+ config = configparser.RawConfigParser()
124
+ mongocnf = os.path.expanduser('~/.mongodb.cnf')
125
+
126
+ try:
127
+ config.readfp(open(mongocnf))
128
+ creds = dict(
129
+ user=config.get('client', 'user'),
130
+ password=config.get('client', 'pass')
131
+ )
132
+ except (configparser.NoOptionError, IOError):
133
+ return False
134
+
135
+ return creds
136
+
137
+
138
+ # =========================================
139
+ # Module execution.
140
+ #
141
+
142
+ def main():
143
+ module = AnsibleModule(
144
+ argument_spec=dict(
145
+ login_user=dict(default=None),
146
+ login_password=dict(default=None, no_log=True),
147
+ login_host=dict(default='localhost'),
148
+ login_port=dict(default=27017, type='int'),
149
+ login_database=dict(default=None),
150
+ replica_set=dict(default=None),
151
+ param=dict(default=None, required=True),
152
+ value=dict(default=None, required=True),
153
+ param_type=dict(default="str", choices=['str', 'int']),
154
+ ssl=dict(default=False, type='bool'),
155
+ )
156
+ )
157
+
158
+ if not pymongo_found:
159
+ module.fail_json(msg='the python pymongo module is required')
160
+
161
+ login_user = module.params['login_user']
162
+ login_password = module.params['login_password']
163
+ login_host = module.params['login_host']
164
+ login_port = module.params['login_port']
165
+ login_database = module.params['login_database']
166
+
167
+ replica_set = module.params['replica_set']
168
+ ssl = module.params['ssl']
169
+
170
+ param = module.params['param']
171
+ param_type = module.params['param_type']
172
+ value = module.params['value']
173
+
174
+ # Verify parameter is coherent with specified type
175
+ try:
176
+ if param_type == 'int':
177
+ value = int(value)
178
+ except ValueError:
179
+ module.fail_json(msg="value '%s' is not %s" % (value, param_type))
180
+
181
+ try:
182
+ if replica_set:
183
+ client = MongoClient(login_host, int(login_port), replicaset=replica_set, ssl=ssl)
184
+ else:
185
+ client = MongoClient(login_host, int(login_port), ssl=ssl)
186
+
187
+ if login_user is None and login_password is None:
188
+ mongocnf_creds = load_mongocnf()
189
+ if mongocnf_creds is not False:
190
+ login_user = mongocnf_creds['user']
191
+ login_password = mongocnf_creds['password']
192
+ elif login_password is None or login_user is None:
193
+ module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided')
194
+
195
+ if login_user is not None and login_password is not None:
196
+ client.admin.authenticate(login_user, login_password, source=login_database)
197
+
198
+ except ConnectionFailure as e:
199
+ module.fail_json(msg='unable to connect to database: %s' % to_native(e), exception=traceback.format_exc())
200
+
201
+ db = client.admin
202
+
203
+ try:
204
+ after_value = db.command("setParameter", **{param: value})
205
+ except OperationFailure as e:
206
+ module.fail_json(msg="unable to change parameter: %s" % to_native(e), exception=traceback.format_exc())
207
+
208
+ if "was" not in after_value:
209
+ module.exit_json(changed=True, msg="Unable to determine old value, assume it changed.")
210
+ else:
211
+ module.exit_json(changed=(value != after_value["was"]), before=after_value["was"],
212
+ after=value)
213
+
214
+
215
+ if __name__ == '__main__':
216
+ main()
pool/shard006/Python/0057693_test_bigip_profile_udp.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright: (c) 2017, F5 Networks Inc.
4
+ # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
+
6
+ from __future__ import (absolute_import, division, print_function)
7
+ __metaclass__ = type
8
+
9
+ import os
10
+ import json
11
+ import pytest
12
+ import sys
13
+
14
+ if sys.version_info < (2, 7):
15
+ pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
16
+
17
+ from ansible.module_utils.basic import AnsibleModule
18
+
19
+ try:
20
+ from library.modules.bigip_profile_udp import ApiParameters
21
+ from library.modules.bigip_profile_udp import ModuleParameters
22
+ from library.modules.bigip_profile_udp import ModuleManager
23
+ from library.modules.bigip_profile_udp import ArgumentSpec
24
+
25
+ # In Ansible 2.8, Ansible changed import paths.
26
+ from test.units.compat import unittest
27
+ from test.units.compat.mock import Mock
28
+
29
+ from test.units.modules.utils import set_module_args
30
+ except ImportError:
31
+ from ansible.modules.network.f5.bigip_profile_udp import ApiParameters
32
+ from ansible.modules.network.f5.bigip_profile_udp import ModuleParameters
33
+ from ansible.modules.network.f5.bigip_profile_udp import ModuleManager
34
+ from ansible.modules.network.f5.bigip_profile_udp import ArgumentSpec
35
+
36
+ # Ansible 2.8 imports
37
+ from units.compat import unittest
38
+ from units.compat.mock import Mock
39
+
40
+ from units.modules.utils import set_module_args
41
+
42
+
43
+ fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
44
+ fixture_data = {}
45
+
46
+
47
+ def load_fixture(name):
48
+ path = os.path.join(fixture_path, name)
49
+
50
+ if path in fixture_data:
51
+ return fixture_data[path]
52
+
53
+ with open(path) as f:
54
+ data = f.read()
55
+
56
+ try:
57
+ data = json.loads(data)
58
+ except Exception:
59
+ pass
60
+
61
+ fixture_data[path] = data
62
+ return data
63
+
64
+
65
+ class TestParameters(unittest.TestCase):
66
+ def test_module_parameters(self):
67
+ args = dict(
68
+ name='foo',
69
+ parent='bar',
70
+ idle_timeout='500',
71
+ datagram_load_balancing=False
72
+ )
73
+
74
+ p = ModuleParameters(params=args)
75
+ assert p.name == 'foo'
76
+ assert p.parent == '/Common/bar'
77
+ assert p.idle_timeout == 500
78
+ assert p.datagram_load_balancing is False
79
+
80
+ def test_api_parameters(self):
81
+ args = load_fixture('load_ltm_profile_udp_1.json')
82
+ p = ApiParameters(params=args)
83
+ assert p.name == 'foo'
84
+ assert p.idle_timeout == 60
85
+
86
+
87
+ class TestManager(unittest.TestCase):
88
+
89
+ def setUp(self):
90
+ self.spec = ArgumentSpec()
91
+
92
+ def test_create(self, *args):
93
+ # Configure the arguments that would be sent to the Ansible module
94
+ set_module_args(dict(
95
+ name='foo',
96
+ parent='bar',
97
+ idle_timeout=500,
98
+ datagram_load_balancing=True,
99
+ provider=dict(
100
+ server='localhost',
101
+ password='password',
102
+ user='admin'
103
+ )
104
+ ))
105
+
106
+ module = AnsibleModule(
107
+ argument_spec=self.spec.argument_spec,
108
+ supports_check_mode=self.spec.supports_check_mode
109
+ )
110
+ mm = ModuleManager(module=module)
111
+
112
+ # Override methods to force specific logic in the module to happen
113
+ mm.exists = Mock(return_value=False)
114
+ mm.create_on_device = Mock(return_value=True)
115
+
116
+ results = mm.exec_module()
117
+
118
+ assert results['changed'] is True
119
+ assert results['idle_timeout'] == 500
pool/shard006/Python/0057699_user.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ sentry.models.user
3
+ ~~~~~~~~~~~~~~~~~~
4
+
5
+ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
6
+ :license: BSD, see LICENSE for more details.
7
+ """
8
+ from __future__ import absolute_import
9
+
10
+ import warnings
11
+
12
+ from django.contrib.auth.models import AbstractBaseUser, UserManager
13
+ from django.db import IntegrityError, models, transaction
14
+ from django.utils import timezone
15
+ from django.utils.translation import ugettext_lazy as _
16
+
17
+ from sentry.db.models import BaseManager, BaseModel, BoundedAutoField
18
+
19
+
20
+ class UserManager(BaseManager, UserManager):
21
+ pass
22
+
23
+
24
+ class User(BaseModel, AbstractBaseUser):
25
+ id = BoundedAutoField(primary_key=True)
26
+ username = models.CharField(_('username'), max_length=128, unique=True)
27
+ # this column is called first_name for legacy reasons, but it is the entire
28
+ # display name
29
+ name = models.CharField(_('name'), max_length=200, blank=True,
30
+ db_column='first_name')
31
+ email = models.EmailField(_('email address'), blank=True)
32
+ is_staff = models.BooleanField(
33
+ _('staff status'), default=False,
34
+ help_text=_('Designates whether the user can log into this admin '
35
+ 'site.'))
36
+ is_active = models.BooleanField(
37
+ _('active'), default=True,
38
+ help_text=_('Designates whether this user should be treated as '
39
+ 'active. Unselect this instead of deleting accounts.'))
40
+ is_superuser = models.BooleanField(
41
+ _('superuser status'), default=False,
42
+ help_text=_('Designates that this user has all permissions without '
43
+ 'explicitly assigning them.'))
44
+ is_managed = models.BooleanField(
45
+ _('managed'), default=False,
46
+ help_text=_('Designates whether this user should be treated as '
47
+ 'managed. Select this to disallow the user from '
48
+ 'modifying their account (username, password, etc).'))
49
+
50
+ date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
51
+
52
+ objects = UserManager(cache_fields=['pk'])
53
+
54
+ USERNAME_FIELD = 'username'
55
+ REQUIRED_FIELDS = ['email']
56
+
57
+ class Meta:
58
+ app_label = 'sentry'
59
+ db_table = 'auth_user'
60
+ verbose_name = _('user')
61
+ verbose_name_plural = _('users')
62
+
63
+ def delete(self):
64
+ if self.username == 'sentry':
65
+ raise Exception('You cannot delete the "sentry" user as it is required by Sentry.')
66
+ return super(User, self).delete()
67
+
68
+ def save(self, *args, **kwargs):
69
+ if not self.username:
70
+ self.username = self.email
71
+ return super(User, self).save(*args, **kwargs)
72
+
73
+ def has_perm(self, perm_name):
74
+ warnings.warn('User.has_perm is deprecated', DeprecationWarning)
75
+ return self.is_superuser
76
+
77
+ def has_module_perms(self, app_label):
78
+ warnings.warn('User.has_module_perms is deprecated', DeprecationWarning)
79
+ return self.is_superuser
80
+
81
+ def get_display_name(self):
82
+ return self.name or self.email or self.username
83
+
84
+ def get_full_name(self):
85
+ return self.name
86
+
87
+ def get_short_name(self):
88
+ return self.username
89
+
90
+ def merge_to(from_user, to_user):
91
+ # TODO: we could discover relations automatically and make this useful
92
+ from sentry.models import (
93
+ AuditLogEntry, Activity, AuthIdentity, GroupBookmark,
94
+ OrganizationMember, UserOption
95
+ )
96
+
97
+ for obj in OrganizationMember.objects.filter(user=from_user):
98
+ try:
99
+ with transaction.atomic():
100
+ obj.update(user=to_user)
101
+ except IntegrityError:
102
+ pass
103
+ for obj in GroupBookmark.objects.filter(user=from_user):
104
+ try:
105
+ with transaction.atomic():
106
+ obj.update(user=to_user)
107
+ except IntegrityError:
108
+ pass
109
+ for obj in UserOption.objects.filter(user=from_user):
110
+ try:
111
+ with transaction.atomic():
112
+ obj.update(user=to_user)
113
+ except IntegrityError:
114
+ pass
115
+
116
+ Activity.objects.filter(
117
+ user=from_user,
118
+ ).update(user=to_user)
119
+ AuditLogEntry.objects.filter(
120
+ actor=from_user,
121
+ ).update(actor=to_user)
122
+ AuditLogEntry.objects.filter(
123
+ target_user=from_user,
124
+ ).update(target_user=to_user)
125
+ AuthIdentity.objects.filter(
126
+ user=from_user,
127
+ ).update(user=to_user)
pool/shard006/Python/0057703_example_1.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python2
2
+
3
+ import subprocess
4
+ import atexit
5
+ import sys
6
+ from math import pi
7
+ from chips.api.api import Chip, Stimulus, Response, Wire, Component
8
+
9
+ #try:
10
+ from matplotlib import pyplot
11
+ #except ImportError:
12
+ #print "You need matplotlib to run this script!"
13
+ #exit(0)
14
+
15
+ def test():
16
+
17
+ chip = Chip("square_root")
18
+
19
+ test_in = Stimulus(chip, "input", "float", [i*0.1 for i in range(100)])
20
+ test_out = Response(chip, "output", "float")
21
+
22
+ #create a filter component using the C code
23
+ sqrt = Component("sqrt.c")
24
+
25
+ #add an instance to the chip
26
+ sqrt(
27
+ chip,
28
+ inputs = {
29
+ "x":test_in,
30
+ },
31
+ outputs = {
32
+ "sqrt_x":test_out,
33
+ },
34
+ )
35
+
36
+ #run the simulation
37
+ chip.simulation_reset()
38
+ while len(test_out) < 100:
39
+ chip.simulation_step()
40
+
41
+ pyplot.plot(list(test_in), list(test_out))
42
+ pyplot.xlim(0, 10.1)
43
+ pyplot.title("Square Root of x")
44
+ pyplot.xlabel("x")
45
+ pyplot.ylabel("$\\sqrt{x}$")
46
+ pyplot.savefig("../docs/source/examples/images/example_1.png")
47
+ pyplot.show()
48
+
49
+ def indent(lines):
50
+ return "\n ".join(lines.splitlines())
51
+
52
+ def generate_docs():
53
+
54
+ documentation = """
55
+
56
+ Calculate Square Root using Newton's Method
57
+ ===========================================
58
+
59
+ In this example, we calculate the sqrt of a number using `Newton's method
60
+ <http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number>`_.
61
+ The problem of finding the square root can be expressed as:
62
+
63
+ .. math::
64
+
65
+ n = x^2
66
+
67
+ Which can be rearranged as:
68
+
69
+ .. math::
70
+
71
+ f(x) = x^2 - n
72
+
73
+ Using Newton's method, we can find numerically the approximate point at which
74
+ :math:`f(x) = 0`. Repeated applications of the following expression yield
75
+ increasingly accurate approximations of the Square root:
76
+
77
+ .. math::
78
+
79
+ f(x_k) = x_{k-1} - \\frac{{x_{k-1}}^2 - n}{2x_{k-1}}
80
+
81
+ Turning this into a practical solution, the following code calculates the square
82
+ root of a floating point number. An initial approximation is refined using
83
+ Newton's method until further refinements agree to within a small degree.
84
+
85
+ .. code-block:: c
86
+
87
+ %s
88
+
89
+ Note that the code isn't entirely robust, and cannot handle special cases such
90
+ as Nans, infinities or negative numbers. A simple test calculates
91
+ :math:`\\sqrt{x}` where :math:`-10 < x < 10`.
92
+
93
+ .. image:: images/example_1.png
94
+
95
+ """%indent(open("sqrt.c").read())
96
+
97
+ document = open("../docs/source/examples/example_1.rst", "w").write(documentation)
98
+
99
+ test()
100
+ generate_docs()
pool/shard006/Python/0057706_basehandlers.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from google.appengine.ext import ndb
3
+ from google.appengine.api import users
4
+
5
+ import webapp2
6
+ from webapp2_extras import jinja2
7
+
8
+
9
+ class BaseHandler(webapp2.RequestHandler):
10
+ """
11
+ All other handlers will extend this handler
12
+ """
13
+
14
+ def __init__(self, request, response):
15
+ self.initialize(request, response)
16
+ self.is_admin = users.is_current_user_admin()
17
+ self.login_url = users.create_login_url(self.request.uri)
18
+ self.logout_url = users.create_logout_url(webapp2.uri_for('home'))
19
+
20
+ self.jinja2_context = {
21
+ 'request': self.request,
22
+ 'user': self.current_user,
23
+ 'is_admin': self.is_admin,
24
+ 'login_url': self.login_url,
25
+ 'logout_url': self.logout_url
26
+ }
27
+
28
+ @webapp2.cached_property
29
+ def jinja2(self):
30
+ return jinja2.get_jinja2(app=self.app)
31
+
32
+ @webapp2.cached_property
33
+ def current_user(self):
34
+ user = users.get_current_user()
35
+ if user:
36
+ user.key = ndb.Key('User', user.user_id())
37
+ return user
38
+
39
+ def render_response(self, _template, **context):
40
+ ctx = self.jinja2_context.copy()
41
+ ctx.update(context)
42
+ rv = self.jinja2.render_template(_template, **ctx)
43
+ self.response.write(rv)
44
+
45
+ def render_response_string(self, template_string, **context):
46
+ ctx = self.jinja2_context.copy()
47
+ ctx.update(context)
48
+ self.response.write(self.jinja2.environment.from_string(
49
+ template_string).render(**ctx))
50
+
51
+
52
+ class UserHandler(BaseHandler):
53
+ def dispatch(self):
54
+ if not self.current_user:
55
+ return self.redirect(self.login_url)
56
+
57
+ return super(UserHandler, self).dispatch()
58
+
59
+
60
+ class AdminHandler(BaseHandler):
61
+ def dispatch(self):
62
+ if not self.current_user:
63
+ return self.redirect(self.login_url)
64
+
65
+ if not self.is_admin:
66
+ self.abort(403, detail="You need admin privileges to access this URL.")
67
+
68
+ super(AdminHandler, self).dispatch()
pool/shard006/Python/0057707_RiCIMU.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from threading import Thread
3
+ import rospy
4
+ import rostopic
5
+ from BAL.Handlers.keepAliveHandler import KeepAliveHandler
6
+ from BAL.Header.Requests.PublishRequest import PublishRequest
7
+ from BAL.Header.Requests.imuRequest import IMURequest
8
+ from BAL.Header.Response.ParamBuildResponse import IMU
9
+
10
+ __author__ = 'tom1231'
11
+ from rospy import Publisher, Service
12
+ from sensor_msgs.msg import Imu, MagneticField
13
+ from BAL.Interfaces.Device import Device
14
+ from tf.transformations import euler_from_quaternion, quaternion_from_euler
15
+ from geometry_msgs.msg import Quaternion
16
+ from math import pi
17
+ from ric_board.srv._calibIMU import calibIMU, calibIMURequest
18
+ from ric_board.msg._imuCalib import imuCalib
19
+
20
+ CALIB_ID = 1
21
+ PUB_ID = 2
22
+
23
+ class RiCIMU(Device):
24
+ def __init__(self, param, output):
25
+ Device.__init__(self, param.getIMUName(), output)
26
+ self._frameId = param.getIMUFrameId()
27
+ self._angle = param.getIMUOrientation()
28
+ self._pub = Publisher('%s_AGQ' % self._name, Imu, queue_size=param.getIMUPubHz())
29
+ self._pubMag = Publisher('%s_M' % self._name, MagneticField, queue_size=param.getIMUPubHz())
30
+ self._pubCalib = Publisher('/imu_calib_publisher', imuCalib, queue_size=param.getIMUPubHz())
31
+ Service('/imu_Calibration', calibIMU, self.serviceCallBack)
32
+ self._haveRightToPublish = False
33
+ self._calib = False
34
+ self._xMax = 0.0
35
+ self._yMax = 0.0
36
+ self._zMax = 0.0
37
+ self._xMin = 0.0
38
+ self._yMin = 0.0
39
+ self._zMin = 0.0
40
+ #KeepAliveHandler('%s_AGQ' % self._name, Imu)
41
+
42
+ def getType(self):
43
+ return IMU
44
+
45
+ def serviceCallBack(self, request):
46
+ validStatus = True
47
+
48
+ if request.status == calibIMURequest.START_CALIB:
49
+ rospy.loginfo("Calibration begin")
50
+ self._output.write(IMURequest(calibIMURequest.START_CALIB).dataTosend())
51
+ self._calib = True
52
+
53
+ self._xMax = request.xMax
54
+ self._yMax = request.yMax
55
+ self._zMax = request.zMax
56
+ self._xMin = request.xMin
57
+ self._yMin = request.yMin
58
+ self._zMin = request.zMin
59
+
60
+ elif request.status == calibIMURequest.STOP_CALIB:
61
+ rospy.loginfo("Calibration end")
62
+ self._output.write(IMURequest(calibIMURequest.STOP_CALIB).dataTosend())
63
+ rospy.loginfo("Calibration setting saved")
64
+ self._calib = False
65
+
66
+ else:
67
+ validStatus = False
68
+ return {'ack': validStatus}
69
+
70
+ def publish(self, data):
71
+ if not self._calib and data.getImuMsgId() == PUB_ID:
72
+ q = data.getOrientation()
73
+ roll, pitch, yaw = euler_from_quaternion((q.y, q.z, q.w, q.x))
74
+ #array = quaternion_from_euler(yaw + (self._angle * pi / 180), roll, pitch)
75
+ #array = quaternion_from_euler(yaw + (self._angle * pi / 180), -1 (roll - 180), -1 * pitch)
76
+ array = quaternion_from_euler((yaw + (self._angle * pi / 180)), roll, -1 * pitch)
77
+ res = Quaternion()
78
+ res.w = array[0]
79
+ res.x = array[1]
80
+ res.y = array[2]
81
+ res.z = array[3]
82
+
83
+ msg = Imu()
84
+ msg.header.frame_id = self._frameId
85
+ msg.header.stamp = rospy.get_rostime()
86
+ msg.orientation = res
87
+ msg.linear_acceleration = data.getAcceleration()
88
+ msg.angular_velocity = data.getVelocity()
89
+
90
+ magMsg = MagneticField()
91
+ magMsg.header.frame_id = self._frameId
92
+ magMsg.header.stamp = rospy.get_rostime()
93
+ magMsg.magnetic_field = data.getMagnetometer()
94
+
95
+ self._pub.publish(msg)
96
+ self._pubMag.publish(magMsg)
97
+
98
+ elif data.getImuMsgId() == CALIB_ID:
99
+ x, y, z = data.getValues()
100
+ msg = imuCalib()
101
+
102
+ if x > self._xMax:
103
+ self._xMax = x
104
+ if x < self._xMin:
105
+ self._xMin = x
106
+
107
+ if y > self._yMax:
108
+ self._yMax = y
109
+ if y < self._yMin:
110
+ self._yMin = y
111
+
112
+ if z > self._zMax:
113
+ self._zMax = z
114
+ if z < self._zMin:
115
+ self._zMin = z
116
+
117
+
118
+ msg.x.data = x
119
+ msg.x.max = self._xMax
120
+ msg.x.min = self._xMin
121
+
122
+ msg.y.data = y
123
+ msg.y.max = self._yMax
124
+ msg.y.min = self._yMin
125
+
126
+ msg.z.data = z
127
+ msg.z.max = self._zMax
128
+ msg.z.min = self._zMin
129
+
130
+ self._pubCalib.publish(msg)
131
+
132
+ def checkForSubscribers(self):
133
+ try:
134
+ subCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pub.name)).group(0).split(': ')[1]
135
+ subMagCheck = re.search('Subscribers:.*', rostopic.get_info_text(self._pubMag.name)).group(0).split(': ')[1]
136
+ subCalibCheck = \
137
+ re.search('Subscribers:.*', rostopic.get_info_text(self._pubCalib.name)).group(0).split(': ')[1]
138
+
139
+ if not self._haveRightToPublish and (subCheck == '' or subMagCheck == '' or subCalibCheck == ''):
140
+ self._output.write(PublishRequest(IMU, 0, True).dataTosend())
141
+ self._haveRightToPublish = True
142
+
143
+ elif self._haveRightToPublish and (
144
+ subCheck == 'None' and subMagCheck == 'None' and subCalibCheck == 'None'):
145
+ self._output.write(PublishRequest(IMU, 0, False).dataTosend())
146
+ self._haveRightToPublish = False
147
+ except:
148
+ pass
pool/shard006/Python/0057709_test_fetch.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright (c) 2012 Cloudera, Inc. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+
17
+ import pytest
18
+ import re
19
+ from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session
20
+ from TCLIService import TCLIService
21
+
22
+ # Simple test to make sure all the HS2 types are supported for both the row and
23
+ # column-oriented versions of the HS2 protocol.
24
+ class TestFetch(HS2TestSuite):
25
+ def __verify_result_precision_scale(self, t, precision, scale):
26
+ # This should be DECIMAL_TYPE but how do I get that in python
27
+ assert t.typeDesc.types[0].primitiveEntry.type == 15
28
+ p = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['precision']
29
+ s = t.typeDesc.types[0].primitiveEntry.typeQualifiers.qualifiers['scale']
30
+ assert p.i32Value == precision
31
+ assert s.i32Value == scale
32
+
33
+ @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1)
34
+ def test_alltypes_v1(self):
35
+ execute_statement_req = TCLIService.TExecuteStatementReq()
36
+ execute_statement_req.sessionHandle = self.session_handle
37
+
38
+ execute_statement_req.statement =\
39
+ "SELECT * FROM functional.alltypessmall ORDER BY id LIMIT 1"
40
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
41
+ HS2TestSuite.check_response(execute_statement_resp)
42
+ results = self.fetch(execute_statement_resp.operationHandle,
43
+ TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1)
44
+ assert len(results.results.rows) == 1
45
+ self.close(execute_statement_resp.operationHandle)
46
+
47
+ execute_statement_req.statement =\
48
+ "SELECT d1,d5 FROM functional.decimal_tbl ORDER BY d1 LIMIT 1"
49
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
50
+ HS2TestSuite.check_response(execute_statement_resp)
51
+ results = self.fetch(execute_statement_resp.operationHandle,
52
+ TCLIService.TFetchOrientation.FETCH_NEXT, 1, 1)
53
+ assert len(results.results.rows) == 1
54
+
55
+ # Verify the result schema is what we expect. The result has 2 columns, the
56
+ # first is decimal(9,0) and the second is decimal(10,5)
57
+ metadata_resp = self.result_metadata(execute_statement_resp.operationHandle)
58
+ column_types = metadata_resp.schema.columns
59
+ assert len(column_types) == 2
60
+ self.__verify_result_precision_scale(column_types[0], 9, 0)
61
+ self.__verify_result_precision_scale(column_types[1], 10, 5)
62
+
63
+ self.close(execute_statement_resp.operationHandle)
64
+
65
+ def __query_and_fetch(self, query):
66
+ execute_statement_req = TCLIService.TExecuteStatementReq()
67
+ execute_statement_req.sessionHandle = self.session_handle
68
+ execute_statement_req.statement = query
69
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
70
+ HS2TestSuite.check_response(execute_statement_resp)
71
+
72
+ fetch_results_req = TCLIService.TFetchResultsReq()
73
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
74
+ fetch_results_req.maxRows = 1024
75
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
76
+ HS2TestSuite.check_response(fetch_results_resp)
77
+
78
+ return fetch_results_resp
79
+
80
+ def __column_results_to_string(self, columns):
81
+ """Quick-and-dirty way to get a readable string to compare the output of a
82
+ columnar-oriented query to its expected output"""
83
+ formatted = ""
84
+ num_rows = 0
85
+ # Determine the number of rows by finding the type of the first column
86
+ for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES:
87
+ typed_col = getattr(columns[0], col_type)
88
+ if typed_col != None:
89
+ num_rows = len(typed_col.values)
90
+ break
91
+
92
+ for i in xrange(num_rows):
93
+ row = []
94
+ for c in columns:
95
+ for col_type in HS2TestSuite.HS2_V6_COLUMN_TYPES:
96
+ typed_col = getattr(c, col_type)
97
+ if typed_col != None:
98
+ indicator = ord(typed_col.nulls[i / 8])
99
+ if indicator & (1 << (i % 8)):
100
+ row.append("NULL")
101
+ else:
102
+ row.append(str(typed_col.values[i]))
103
+ break
104
+ formatted += (", ".join(row) + "\n")
105
+ return (num_rows, formatted)
106
+
107
+ @needs_session()
108
+ def test_alltypes_v6(self):
109
+ """Test that a simple select statement works for all types"""
110
+ fetch_results_resp = self.__query_and_fetch(
111
+ "SELECT *, NULL from functional.alltypes ORDER BY id LIMIT 1")
112
+
113
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
114
+ assert num_rows == 1
115
+ assert result == \
116
+ "0, True, 0, 0, 0, 0, 0.0, 0.0, 01/01/09, 0, 2009-01-01 00:00:00, 2009, 1, NULL\n"
117
+
118
+ # Decimals
119
+ fetch_results_resp = self.__query_and_fetch(
120
+ "SELECT * from functional.decimal_tbl LIMIT 1")
121
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
122
+ assert result == ("1234, 2222, 1.2345678900, "
123
+ "0.12345678900000000000000000000000000000, 12345.78900, 1\n")
124
+
125
+ # VARCHAR
126
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('str' AS VARCHAR(3))")
127
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
128
+ assert result == "str\n"
129
+
130
+ # CHAR not inlined
131
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(140))")
132
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
133
+ assert result == "car" + (" " * 137) + "\n"
134
+
135
+ # CHAR inlined
136
+ fetch_results_resp = self.__query_and_fetch("SELECT CAST('car' AS CHAR(5))")
137
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
138
+ assert result == "car \n"
139
+
140
+ @needs_session()
141
+ def test_show_partitions(self):
142
+ """Regression test for IMPALA-1330"""
143
+ for query in ["SHOW PARTITIONS functional.alltypes",
144
+ "SHOW TABLE STATS functional.alltypes"]:
145
+ fetch_results_resp = self.__query_and_fetch(query)
146
+ num_rows, result = \
147
+ self.__column_results_to_string(fetch_results_resp.results.columns)
148
+ assert num_rows == 25
149
+ # Match whether stats are computed or not
150
+ assert re.match(
151
+ r"2009, 1, -?\d+, -?\d+, \d*\.?\d+KB, NOT CACHED, TEXT", result) is not None
152
+
153
+ @needs_session()
154
+ def test_show_column_stats(self):
155
+ fetch_results_resp = self.__query_and_fetch("SHOW COLUMN STATS functional.alltypes")
156
+ num_rows, result = self.__column_results_to_string(fetch_results_resp.results.columns)
157
+ assert num_rows == 13
158
+ assert re.match(r"id, INT, -?\d+, -?\d+, (NULL|\d+), 4.0", result) is not None
159
+
160
+ @needs_session(TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1)
161
+ def test_execute_select_v1(self):
162
+ """Test that a simple select statement works in the row-oriented protocol"""
163
+ execute_statement_req = TCLIService.TExecuteStatementReq()
164
+ execute_statement_req.sessionHandle = self.session_handle
165
+ execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes"
166
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
167
+ HS2TestSuite.check_response(execute_statement_resp)
168
+
169
+ fetch_results_req = TCLIService.TFetchResultsReq()
170
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
171
+ fetch_results_req.maxRows = 100
172
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
173
+ HS2TestSuite.check_response(fetch_results_resp)
174
+
175
+ assert len(fetch_results_resp.results.rows) == 1
176
+ assert fetch_results_resp.results.startRowOffset == 0
177
+
178
+ try:
179
+ assert not fetch_results_resp.hasMoreRows
180
+ except AssertionError:
181
+ pytest.xfail("IMPALA-558")
182
+
183
+ @needs_session()
184
+ def test_select_null(self):
185
+ """Regression test for IMPALA-1370, where NULL literals would appear as strings where
186
+ they should be booleans"""
187
+ execute_statement_req = TCLIService.TExecuteStatementReq()
188
+ execute_statement_req.sessionHandle = self.session_handle
189
+ execute_statement_req.statement = "select null"
190
+ execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
191
+ HS2TestSuite.check_response(execute_statement_resp)
192
+
193
+ # Check that the expected type is boolean (for compatibility with Hive, see also
194
+ # IMPALA-914)
195
+ get_result_metadata_req = TCLIService.TGetResultSetMetadataReq()
196
+ get_result_metadata_req.operationHandle = execute_statement_resp.operationHandle
197
+ get_result_metadata_resp = \
198
+ self.hs2_client.GetResultSetMetadata(get_result_metadata_req)
199
+ col = get_result_metadata_resp.schema.columns[0]
200
+ assert col.typeDesc.types[0].primitiveEntry.type == TCLIService.TTypeId.BOOLEAN_TYPE
201
+
202
+ # Check that the actual type is boolean
203
+ fetch_results_req = TCLIService.TFetchResultsReq()
204
+ fetch_results_req.operationHandle = execute_statement_resp.operationHandle
205
+ fetch_results_req.maxRows = 1
206
+ fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
207
+ HS2TestSuite.check_response(fetch_results_resp)
208
+ assert fetch_results_resp.results.columns[0].boolVal is not None
209
+
210
+ assert self.__column_results_to_string(
211
+ fetch_results_resp.results.columns) == (1, "NULL\n")
212
+
213
+ @needs_session()
214
+ def test_compute_stats(self):
215
+ """Exercise the child query path"""
216
+ self.__query_and_fetch("compute stats functional.alltypes")
pool/shard006/Python/0057718_gmusic.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gmusicapi import Mobileclient
2
+ import getpass
3
+
4
+ class GpmSession(object):
5
+ # Private Variables
6
+
7
+ # Public Variables
8
+ api = None
9
+ logged_in = False
10
+ songs = None
11
+ playlists = None
12
+
13
+ # Constructor with optionally passed credentials
14
+ # Omit credentials if you want to handle login, include for prompts from this module
15
+ def __init__(self, email=None, pw=None):
16
+ self.api = Mobileclient()
17
+ if not email and not pw == None:
18
+ email = input("Please enter an email address tied to a GPM account: ")
19
+ pw = getpass.getpass("Please enter the password associated with %s " % email)
20
+ self.logged_in = self.api.login(email, pw, Mobileclient.FROM_MAC_ADDRESS) # As per api protocol
21
+ if self.logged_in:
22
+ print("Google Play Music login successful")
23
+ else:
24
+ print("Google Play Music login failed")
25
+
26
+ def init(self, songs = True, playlists = True):
27
+ if songs:
28
+ self.songs = self.api.get_all_songs()
29
+ if playlists:
30
+ self.playlists = self.api.get_all_playlists()
31
+
32
+ def get_song_stream(self, title, artist=None):
33
+ print(not self.songs)
34
+ if not self.songs:
35
+ self.init(True, False)
36
+ song = next(iter((track for track in self.songs if self._filter_condition(track, title, artist)) or []), None)
37
+ if song:
38
+ return self.api.get_stream_url(song["id"])
39
+ else:
40
+ return None
41
+
42
+
43
+ def _filter_condition(self, song_obj, search_title, search_artist):
44
+ result = True
45
+ if search_title:
46
+ result = result & (song_obj["title"].lower().strip() == search_title.lower().strip())
47
+ if search_artist:
48
+ result = result & (song_obj["artist"].lower().strip() == search_artist.lower().strip())
49
+ return result
50
+
51
+ def main():
52
+ session = GpmSession()
53
+ while not session.logged_in:
54
+ session = GpmSession()
55
+ session.init()
56
+ print(session.get_song_stream("Dirty Laundry", "Bitter Sweet"))
57
+ print(session.get_song_stream("1940"))
58
+
59
+ if __name__ == "__main__":
60
+ main()
pool/shard006/Python/0057719_graphSim.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #This program will run and graph the simulation, comparing serial and parallel
2
+ import sys
3
+ import ConfigParser
4
+ from subprocess import call
5
+ #If not the independent variable, these values will be used
6
+ MOLECULES = 2112
7
+ SIZE = 40
8
+ STEPS = 10000
9
+ DENSITY = .033 #the density of water
10
+ #function to change the time steps in demoConfiguration.txt
11
+ def changeConfigFile(timeSteps, molecules, size):
12
+ f = open('resources/demo.config','r')
13
+ lines = f.readlines()
14
+ lines[1] = str(size) + '\n'
15
+ lines[2] = str(size) + '\n'
16
+ lines[3] = str(size) + '\n'
17
+ lines[9] = str(timeSteps) + '\n'
18
+ lines[11] = str(molecules) + '\n'
19
+ f.close()
20
+ f = open('resources/demo.config','w')
21
+ for item in lines:
22
+ f.write(item)
23
+ f.close()
24
+ #function to get the run-time from the last run
25
+ def getRunTime():
26
+ config = ConfigParser.RawConfigParser()
27
+ config.read('run.results')
28
+ line = config.get('Results','Run-Time')
29
+ line = line.split()
30
+ return line[0]
31
+ #function to print out the help information
32
+ def printHelp():
33
+ print "***HELP***"
34
+ print "Usage: python graphing/graphSim.py xaxis interval"
35
+ print "xaxis is what parameter should be on the xaxis: 'steps', 'size', or 'density"
36
+ print "interval is the xvalues separated by spaces"
37
+ print "density is in number of molecules/volume"
38
+ print "Example: python graphing/graphSim density .01 .02 .03 .04\n"
39
+ #Begin program
40
+ input = sys.argv
41
+ #check for invalud inputs
42
+ if len(input) < 3:
43
+ printHelp()
44
+ exit(0)
45
+ input.remove("graphing/graphSim.py")
46
+ xaxis = input.pop(0)
47
+ if xaxis != "steps" and xaxis != "size" and xaxis != "density":
48
+ print "Error: invalid format"
49
+ printHelp()
50
+ exit(0)
51
+ #capitalize for ease of printing
52
+ xaxis = xaxis.capitalize()
53
+ #run simulation and prepare output
54
+ f = open('graphing/simResults.txt', 'w')
55
+ f.write(xaxis + '\tSerial\tParallel\n')
56
+ for i in input:
57
+ if xaxis == "Steps":
58
+ changeConfigFile(i, MOLECULES, SIZE)
59
+ if xaxis == "Size":
60
+ changeConfigFile(STEPS, int(i)*int(i)*int(i)*DENSITY, i)
61
+ if xaxis == "Density":
62
+ changeConfigFile(STEPS, float(i)*SIZE*SIZE*SIZE, SIZE)
63
+ f.write(i+'\t')
64
+ call(["./bin/metrosim", "resources/demo.config", "-s"])
65
+ f.write(getRunTime()+'\t')
66
+ call(["./bin/metrosim", "resources/demo.config", "-p"])
67
+ f.write(getRunTime()+'\n')
68
+ f.close()
69
+ #set up gnuplot
70
+ f = open('graphing/gnuplotScript','w')
71
+ f.write("set terminal png\nset output 'graph.png'\nset key left top\n")
72
+ f.write("set title 'Serial/Parallel Time Comparison'\n")
73
+ f.write("set ylabel 'Time (s)'\nset xlabel '" + xaxis)
74
+ f.write("'\nplot 'graphing/simResults.txt' using 1:2 w lp title 'Serial', 'graphing/simResults.txt' using 1:3 w lp title 'Parallel'")
75
+ f.close()
76
+ #call gnuplot
77
+ call(["gnuplot", "graphing/gnuplotScript"])
pool/shard006/Python/0057724_plot_gait.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ ====================
4
+ Gait (steps) example
5
+ ====================
6
+ In this example, we use DiCoDiLe on an open dataset of gait (steps) IMU
7
+ time-series to discover patterns in the data. We will then use those to attempt
8
+ to detect steps and compare our findings with the ground truth.
9
+ """
10
+
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+
14
+ ###############################################################################
15
+ # # Retrieve trial data
16
+
17
+ from dicodile.data.gait import get_gait_data
18
+
19
+ trial = get_gait_data(subject=6, trial=1)
20
+
21
+ ###############################################################################
22
+ # Let’s have a look at the data for one trial.
23
+
24
+ trial.keys()
25
+
26
+ ###############################################################################
27
+ # We get a dictionary whose keys are metadata items, plus a ‘data’ key that
28
+ # contains a numpy array with the trial time series for each sensor axis, at
29
+ # 100 Hz resolution.
30
+
31
+ # right foot acceleration (vertical)
32
+ plt.plot(trial['data']['RAV'])
33
+
34
+ ###############################################################################
35
+ # Let’s look at a small portion of the series for both feet, overlaid on the
36
+ # same plot.
37
+
38
+ fig, ax = plt.subplots()
39
+ ax.plot(trial['data']['LAV'][5000:5800],
40
+ label='left foot vertical acceleration')
41
+ ax.plot(trial['data']['RAV'][5000:5800],
42
+ label='right foot vertical acceleration')
43
+ ax.set_xlabel('time (x10ms)')
44
+ ax.set_ylabel('acceleration ($m.s^{-2}$)')
45
+ ax.legend()
46
+
47
+ ###############################################################################
48
+ # We can see the alternating left and right foot movements.
49
+ #
50
+ # In the rest of this example, we will only use the right foot vertical
51
+ # acceleration.
52
+
53
+ ###############################################################################
54
+ # # Convolutional Dictionary Learning
55
+
56
+ ###############################################################################
57
+ # Now, let’s use "dicodile" as solver_z to learn patterns from the data and
58
+ # reconstruct the signal from a sparse representation.
59
+ #
60
+ # First, we initialize a dictionary from parts of the signal:
61
+
62
+ X = trial['data']['RAV'].to_numpy()
63
+
64
+ # reshape X to (n_trials, n_channels, n_times)
65
+ X = X.reshape(1, 1, *X.shape)
66
+
67
+ print(X.shape)
68
+
69
+ ###############################################################################
70
+ # Note the use of reshape to shape the signal as per alphacsc requirements: the
71
+ # shape of the signal should be (n_trials, n_channels, n_times). Here, we have
72
+ # a single-channel time series so it is (1, 1, n_times).
73
+
74
+ from alphacsc.init_dict import init_dictionary
75
+
76
+ # set dictionary size
77
+ n_atoms = 8
78
+
79
+ # set individual atom (patch) size.
80
+ n_times_atom = 200
81
+
82
+ D_init = init_dictionary(X,
83
+ n_atoms=8,
84
+ n_times_atom=200,
85
+ rank1=False,
86
+ window=True,
87
+ D_init='chunk',
88
+ random_state=60)
89
+
90
+ print(D_init.shape)
91
+
92
+ ""
93
+ from alphacsc import BatchCDL
94
+
95
+ cdl = BatchCDL(
96
+ # Shape of the dictionary
97
+ n_atoms,
98
+ n_times_atom,
99
+ rank1=False,
100
+ uv_constraint='auto',
101
+ # Number of iteration for the alternate minimization and cvg threshold
102
+ n_iter=3,
103
+ # number of workers to be used for dicodile
104
+ n_jobs=4,
105
+ # solver for the z-step
106
+ solver_z='dicodile',
107
+ solver_z_kwargs={'max_iter': 10000},
108
+ window=True,
109
+ D_init=D_init,
110
+ random_state=60)
111
+
112
+ res = cdl.fit(X)
113
+
114
+ ""
115
+ from dicodile.utils.viz import display_dictionaries
116
+
117
+ D_hat = res._D_hat
118
+
119
+ fig = display_dictionaries(D_init, D_hat)
120
+
121
+ ###############################################################################
122
+ # # Signal reconstruction
123
+
124
+ ###############################################################################
125
+ # Now, let's reconstruct the original signal.
126
+
127
+ from alphacsc.utils import construct_X_multi
128
+
129
+ z_hat = res._z_hat
130
+
131
+ X_hat = construct_X_multi(z_hat, D_hat)
132
+
133
+ ###############################################################################
134
+ # Plot a small part of the original and reconstructed signals
135
+
136
+ fig_hat, ax_hat = plt.subplots()
137
+ ax_hat.plot(X[0][0][5000:5800],
138
+ label='right foot vertical acceleration (ORIGINAL)')
139
+ ax_hat.plot(X_hat[0][0][5000:5800],
140
+ label='right foot vertical acceleration (RECONSTRUCTED)')
141
+ ax_hat.set_xlabel('time (x10ms)')
142
+ ax_hat.set_ylabel('acceleration ($m.s^{-2}$)')
143
+ ax_hat.legend()
144
+
145
+ ###############################################################################
146
+ # Check that our representation is indeed sparse:
147
+
148
+
149
+ np.count_nonzero(z_hat)
150
+
151
+ ###############################################################################
152
+ # Besides our visual check, a measure of how closely we’re reconstructing the
153
+ # original signal is the (normalized) cross-correlation. Let’s compute this:
154
+
155
+ np.correlate(X[0][0], X_hat[0][0]) / np.sqrt(
156
+ np.correlate(X[0][0], X[0][0]) * np.correlate(X_hat[0][0], X_hat[0][0])
157
+ )
158
+
159
+ ###############################################################################
160
+ # # Multichannel signals
161
+
162
+ ###############################################################################
163
+ # DiCoDiLe works just as well with multi-channel signals. The gait dataset
164
+ # contains 16 signals (8 for each foot), in the rest of this tutorial, we’ll
165
+ # use three of those.
166
+
167
+ # Left foot Vertical acceleration, Y rotation and X acceleration
168
+ channels = ['LAV', 'LRY', 'LAX']
169
+
170
+ ###############################################################################
171
+ # Let’s look at a small portion of multi-channel data
172
+
173
+ colors = plt.rcParams["axes.prop_cycle"]()
174
+ mc_fig, mc_ax = plt.subplots(len(channels), sharex=True)
175
+
176
+ for ax, chan in zip(mc_ax, channels):
177
+ ax.plot(trial['data'][chan][5000:5800],
178
+ label=chan, color=next(colors)["color"])
179
+ mc_fig.legend(loc="upper center")
180
+
181
+ ###############################################################################
182
+ # Let’s put the data in shape for alphacsc: (n_trials, n_channels, n_times)
183
+
184
+ X_mc_subset = trial['data'][channels].to_numpy().T
185
+
186
+ X_mc_subset = X_mc_subset.reshape(1, *X_mc_subset.shape)
187
+
188
+ print(X_mc_subset.shape)
189
+
190
+ ###############################################################################
191
+ # Initialize the dictionary (note that the call is identical to the
192
+ # single-channel version)
193
+
194
+ D_init_mc = init_dictionary(
195
+ X_mc_subset, n_atoms=8, n_times_atom=200, rank1=False,
196
+ window=True, D_init='chunk', random_state=60
197
+ )
198
+
199
+ print(D_init_mc.shape)
200
+
201
+ ###############################################################################
202
+ # And run DiCoDiLe (note that the call is identical to the single-channel
203
+ # version here as well)
204
+
205
+ from alphacsc import BatchCDL
206
+
207
+ cdl = BatchCDL(
208
+ # Shape of the dictionary
209
+ n_atoms,
210
+ n_times_atom,
211
+ rank1=False,
212
+ uv_constraint='auto',
213
+ # Number of iteration for the alternate minimization and cvg threshold
214
+ n_iter=3,
215
+ # number of workers to be used for dicodile
216
+ n_jobs=4,
217
+ # solver for the z-step
218
+ solver_z='dicodile',
219
+ solver_z_kwargs={'max_iter': 10000},
220
+ window=True,
221
+ D_init=D_init_mc,
222
+ random_state=60)
223
+
224
+ res = cdl.fit(X_mc_subset)
225
+
226
+ ###############################################################################
227
+ # # Signal reconstruction (multichannel)
228
+
229
+ ###############################################################################
230
+ # Now, let’s reconstruct the original signal
231
+
232
+ from alphacsc.utils import construct_X_multi
233
+
234
+ z_hat_mc = res._z_hat
235
+
236
+ D_hat_mc = res._D_hat
237
+
238
+ X_hat_mc = construct_X_multi(z_hat_mc, D_hat_mc)
239
+
240
+ ###############################################################################
241
+ # Let’s visually compare a small part of the original and reconstructed signal
242
+ # along with the activations.
243
+
244
+ z_hat_mc.shape
245
+
246
+ ""
247
+ viz_start_idx = 4000
248
+ viz_end_idx = 5800
249
+ viz_chan = 2
250
+
251
+ max_abs = np.max(np.abs(z_hat_mc), axis=-1)
252
+ max_abs = max_abs.reshape(z_hat_mc.shape[1], 1)
253
+ z_hat_normalized = z_hat_mc / max_abs
254
+
255
+ fig_hat_mc, ax_hat_mc = plt.subplots(2, figsize=(12, 8))
256
+
257
+ # plot original and constructed
258
+ ax_hat_mc[0].plot(X_mc_subset[0][viz_chan][viz_start_idx:viz_end_idx],
259
+ label='ORIGINAL')
260
+ ax_hat_mc[0].plot(X_hat_mc[0][viz_chan][viz_start_idx:viz_end_idx],
261
+ label='RECONSTRUCTED')
262
+
263
+ ax_hat_mc[0].set_xlabel('time (x10ms)')
264
+ ax_hat_mc[0].legend()
265
+
266
+ # plot activations
267
+ for idx in range(z_hat_normalized.shape[1]):
268
+ ax_hat_mc[1].stem(z_hat_normalized[0][idx][viz_start_idx:viz_end_idx],
269
+ linefmt=f"C{idx}-",
270
+ markerfmt=f"C{idx}o")
pool/shard006/Python/0057730_screenshot.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 The Chromium Authors. All rights reserved.
2
+ # Use of this source code is governed by a BSD-style license that can be
3
+ # found in the LICENSE file.
4
+
5
+ from __future__ import absolute_import
6
+ import datetime
7
+ import logging
8
+ import os
9
+ import random
10
+ import tempfile
11
+
12
+ import py_utils
13
+ from py_utils import cloud_storage # pylint: disable=import-error
14
+ from telemetry.util import image_util
15
+ from telemetry.internal.util import file_handle
16
+
17
+
18
+ def TryCaptureScreenShot(platform, tab=None, timeout=None):
19
+ """ If the platform or tab supports screenshot, attempt to take a screenshot
20
+ of the current browser.
21
+
22
+ Args:
23
+ platform: current platform
24
+ tab: browser tab if available
25
+ timeout: An float denoting the number of seconds to wait for a successful
26
+ screenshot. If set to None, only attempts once.
27
+
28
+ Returns:
29
+ file handle of the tempoerary file path for the screenshot if
30
+ present, None otherwise.
31
+ """
32
+ try:
33
+ if platform.CanTakeScreenshot():
34
+ tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
35
+ tf.close()
36
+ try:
37
+ py_utils.WaitFor(lambda: platform.TakeScreenshot(tf.name), timeout or 0)
38
+ except py_utils.TimeoutException:
39
+ logging.warning('Did not succeed in screenshot capture')
40
+ return file_handle.FromTempFile(tf)
41
+ if tab and tab.IsAlive() and tab.screenshot_supported:
42
+ tf = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
43
+ tf.close()
44
+ image = tab.Screenshot()
45
+ image_util.WritePngFile(image, tf.name)
46
+ return file_handle.FromTempFile(tf)
47
+ logging.warning(
48
+ 'Either tab has crashed or browser does not support taking tab '
49
+ 'screenshot. Skip taking screenshot on failure.')
50
+ return None
51
+ except Exception as e: # pylint: disable=broad-except
52
+ logging.warning('Exception when trying to capture screenshot: %s', repr(e))
53
+ return None
54
+
55
+
56
+ def TryCaptureScreenShotAndUploadToCloudStorage(platform, tab=None):
57
+ """ If the platform or tab supports screenshot, attempt to take a screenshot
58
+ of the current browser. If present it uploads this local path to cloud
59
+ storage and returns the URL of the cloud storage path.
60
+
61
+ Args:
62
+ platform: current platform
63
+ tab: browser tab if available
64
+
65
+ Returns:
66
+ url of the cloud storage path if screenshot is present, None otherwise
67
+ """
68
+ fh = TryCaptureScreenShot(platform, tab)
69
+ if fh is not None:
70
+ return _UploadScreenShotToCloudStorage(fh)
71
+
72
+ return None
73
+
74
+ def _GenerateRemotePath(fh):
75
+ return ('browser-screenshot_%s-%s%-d%s' %
76
+ (fh.id, datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
77
+ random.randint(1, 100000), fh.extension))
78
+
79
+ def _UploadScreenShotToCloudStorage(fh):
80
+ """ Upload the given screenshot image to cloud storage and return the
81
+ cloud storage url if successful.
82
+ """
83
+ try:
84
+ return cloud_storage.Insert(cloud_storage.TELEMETRY_OUTPUT,
85
+ _GenerateRemotePath(fh), fh.GetAbsPath())
86
+ except cloud_storage.CloudStorageError as err:
87
+ logging.error('Cloud storage error while trying to upload screenshot: %s',
88
+ repr(err))
89
+ return '<Missing link>'
90
+ finally: # Must clean up screenshot file if exists.
91
+ os.remove(fh.GetAbsPath())