Pendigard commited on
Commit
0fa7358
·
verified ·
1 Parent(s): d982068

Upload folder using huggingface_hub (part 97)

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/shard008/Python/0075157_calculate_angles.py +31 -0
  2. pool/shard008/Python/0075158_fakeData.py +32 -0
  3. pool/shard008/Python/0075159_hsvwheel.py +131 -0
  4. pool/shard008/Python/0075163_nuvpnconnection.py +258 -0
  5. pool/shard008/Python/0075164_impl.py +141 -0
  6. pool/shard008/Python/0075165_io_context.py +64 -0
  7. pool/shard008/Python/0075167_dummyActuator.py +74 -0
  8. pool/shard008/Python/0075169_db.py +73 -0
  9. pool/shard008/Python/0075172_updateloginprofile.py +45 -0
  10. pool/shard008/Python/0075173_bridge.py +108 -0
  11. pool/shard008/Python/0075174_plot.py +44 -0
  12. pool/shard008/Python/0075176_apod.py +153 -0
  13. pool/shard008/Python/0075177_1805eda2bbfa_added_prev_state_column.py +22 -0
  14. pool/shard008/Python/0075180_test_poll.py +157 -0
  15. pool/shard008/Python/0075188_init__.py +91 -0
  16. pool/shard008/Python/0075190_problem493.py +68 -0
  17. pool/shard008/Python/0075202_stats.py +49 -0
  18. pool/shard008/Python/0075203_admin.py +45 -0
  19. pool/shard008/Python/0075205_RDFfromDX.py +24 -0
  20. pool/shard008/Python/0075211_deb.py +26 -0
  21. pool/shard008/Python/0075214_test_management.py +126 -0
  22. pool/shard008/Python/0075219_0008_auto_20170526_1651.py +25 -0
  23. pool/shard008/Python/0075220_geomtype.py +87 -0
  24. pool/shard008/Python/0075222_views.py +209 -0
  25. pool/shard008/Python/0075225_gen-insertfile.py +67 -0
  26. pool/shard008/Python/0075228_views.py +60 -0
  27. pool/shard008/Python/0075231_express_route_service_providers_operations.py +102 -0
  28. pool/shard008/Python/0075233_swipe_theta.py +130 -0
  29. pool/shard008/Python/0075236_test_api_email_localization.py +100 -0
  30. pool/shard008/Python/0075241_classify.py +37 -0
  31. pool/shard008/Python/0075243_create_tokens.py +102 -0
  32. pool/shard008/Python/0075246_spider.py +107 -0
  33. pool/shard008/Python/0075250_avionics.py +164 -0
  34. pool/shard008/Python/0075254_database.py +28 -0
  35. pool/shard008/Python/0075256_bram.py +15 -0
  36. pool/shard008/Python/0075257_Recognizer.py +185 -0
  37. pool/shard008/Python/0075259_views.py +27 -0
  38. pool/shard008/Python/0075265_test_bayesian_blocks.py +146 -0
  39. pool/shard008/Python/0075266_basic_starts_with_op.py +36 -0
  40. pool/shard008/Python/0075269_exercisecollection_models.py +220 -0
  41. pool/shard008/Python/0075273_test_importers_github_api.py +234 -0
  42. pool/shard008/Python/0075274_learned_ddpg.py +66 -0
  43. pool/shard008/Python/0075275_LabelLineCurveFeature_v4.py +131 -0
  44. pool/shard008/Python/0075279_clustering_script.py +28 -0
  45. pool/shard008/Python/0075282_repository.py +146 -0
  46. pool/shard008/Python/0075283_module4.py +52 -0
  47. pool/shard008/Python/0075289_game_loop_basic.py +44 -0
  48. pool/shard008/Python/0075290_test_lint.py +160 -0
  49. pool/shard008/Python/0075292_archive_util.py +205 -0
  50. pool/shard008/Python/0075297_loggings.py +34 -0
pool/shard008/Python/0075157_calculate_angles.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Created on 25/9/2015
3
+
4
+ @author: victor
5
+ '''
6
+ import sys
7
+ import numpy
8
+ from prody.proteins.pdbfile import parsePDB
9
+ from prody.measure.measure import calcPhi, calcPsi
10
+
11
+ if __name__ == '__main__':
12
+ trajectory_path = sys.argv[1]
13
+
14
+ structure = parsePDB(trajectory_path)
15
+ all_angles = []
16
+ for i, coords in enumerate(structure.getCoordsets()):
17
+ angles = []
18
+ structure.setCoords(coords)
19
+ hv = structure.getHierView()
20
+ for residue in hv.iterResidues():
21
+ try:
22
+ angles.append(calcPhi(residue, radian=True))
23
+ except:
24
+ angles.append(0.)
25
+ try:
26
+ angles.append(calcPsi(residue, radian=True))
27
+ except:
28
+ angles.append(0.)
29
+ all_angles.append(angles)
30
+ all_angles = numpy.array(all_angles)
31
+ numpy.savetxt(sys.argv[1]+".ang", all_angles, fmt = "%.4f")
pool/shard008/Python/0075158_fakeData.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __author__ = 'Ash'
2
+ import numpy as np
3
+ import time
4
+ import http.client, urllib.parse
5
+ from pprint import pprint
6
+
7
+ API_KEY = "LZ3F1HB2ORCXOA9O"
8
+ n_spine = 8
9
+ fields = list(map(lambda x: "field"+x, map(str, range(1, 9))))
10
+ headers = {"Content-type": "application/x-www-form-urlencoded",
11
+ "Accept": "text/plain"}
12
+
13
+ def main():
14
+ period = np.arange(0, 2, 2/n_spine) * np.pi
15
+ while True:
16
+ for dt in period:
17
+ sensors = np.cos(period+dt)*5 + 25
18
+ data = dict(zip(fields, sensors))
19
+ data["key"] = API_KEY
20
+ params = urllib.parse.urlencode(data)
21
+ conn = http.client.HTTPConnection("api.thingspeak.com:80")
22
+ conn.request("POST", "/update", params, headers)
23
+ response = conn.getresponse()
24
+ print(response.status, response.reason)
25
+ #data = response.read()
26
+ conn.close()
27
+ time.sleep(15)
28
+
29
+
30
+
31
+ if __name__ == "__main__":
32
+ main()
pool/shard008/Python/0075159_hsvwheel.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of MyPaint.
2
+ # Copyright (C) 2012 by Andrew Chadwick <andrewc-git@piffle.org>
3
+ #
4
+ # This program is free software; you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation; either version 2 of the License, or
7
+ # (at your option) any later version.
8
+
9
+
10
+ """Hue, Saturation and Value wheel.
11
+ """
12
+
13
+ import math
14
+
15
+ from gui import gtk2compat
16
+ import gtk
17
+ from gtk import gdk
18
+ import cairo
19
+ from gettext import gettext as _
20
+
21
+ from adjbases import ColorAdjusterWidget
22
+ from adjbases import HueSaturationWheelAdjuster
23
+ from sliders import HSVValueSlider
24
+ from uicolor import HSVColor
25
+ from util import clamp
26
+ from combined import CombinedAdjusterPage
27
+
28
+
29
+ class HSVHueSaturationWheel (HueSaturationWheelAdjuster):
30
+ """Hue, Saturation and Value wheel.
31
+ """
32
+
33
+ STATIC_TOOLTIP_TEXT = _("HSV Hue and Saturation")
34
+
35
+ def __init__(self):
36
+ HueSaturationWheelAdjuster.__init__(self)
37
+ self.connect("scroll-event", self.__scroll_cb)
38
+ self.add_events(gdk.SCROLL_MASK)
39
+
40
+ def __scroll_cb(self, widget, event):
41
+ d = self.SCROLL_DELTA
42
+ if event.direction in (gdk.SCROLL_DOWN, gdk.SCROLL_LEFT):
43
+ d *= -1
44
+ col = HSVColor(color=self.get_managed_color())
45
+ v = clamp(col.v+d, 0.0, 1.0)
46
+ if col.v != v:
47
+ col.v = v
48
+ self.set_managed_color(col)
49
+ return True
50
+
51
+ def get_normalized_polar_pos_for_color(self, col):
52
+ col = HSVColor(color=col)
53
+ return col.s, col.h
54
+
55
+ def color_at_normalized_polar_pos(self, r, theta):
56
+ col = HSVColor(color=self.get_managed_color())
57
+ col.h = theta
58
+ col.s = r
59
+ return col
60
+
61
+
62
+ class HSVAdjusterPage (CombinedAdjusterPage):
63
+ """Page details for the HSV wheel.
64
+ """
65
+
66
+ def __init__(self):
67
+ table = gtk.Table(rows=1, columns=2)
68
+
69
+ self.__v_adj = HSVValueSlider()
70
+ self.__v_adj.vertical = True
71
+ self.__hs_adj = HSVHueSaturationWheel()
72
+
73
+ row = 0
74
+ xopts = gtk.FILL | gtk.EXPAND
75
+ yopts = gtk.FILL | gtk.EXPAND
76
+ v_align = gtk.Alignment(xalign=1, yalign=0, xscale=0, yscale=1)
77
+ v_align.add(self.__v_adj)
78
+ table.attach(v_align, 0, 1, row, row+1, gtk.FILL, yopts, 3, 3)
79
+ table.attach(self.__hs_adj, 1, 2, row, row+1, xopts, yopts, 3, 3)
80
+
81
+ self.__table = table
82
+
83
+ @classmethod
84
+ def get_page_icon_name(self):
85
+ return 'mypaint-tool-hsvwheel'
86
+
87
+ @classmethod
88
+ def get_page_title(self):
89
+ return _('HSV Wheel')
90
+
91
+ @classmethod
92
+ def get_page_description(self):
93
+ return _("Saturation and Value color changer.")
94
+
95
+ def get_page_widget(self):
96
+ frame = gtk.AspectFrame(obey_child=True)
97
+ frame.set_shadow_type(gtk.SHADOW_NONE)
98
+ frame.add(self.__table)
99
+ return frame
100
+
101
+ def set_color_manager(self, manager):
102
+ CombinedAdjusterPage.set_color_manager(self, manager)
103
+ self.__v_adj.set_color_manager(manager)
104
+ self.__hs_adj.set_color_manager(manager)
105
+
106
+
107
+ if __name__ == '__main__':
108
+ import os
109
+ import sys
110
+ from adjbases import ColorManager
111
+ mgr = ColorManager(prefs={}, datapath='.')
112
+ if len(sys.argv) > 1:
113
+ # Generate icons
114
+ mgr.set_color(HSVColor(0.0, 0.0, 0.8))
115
+ wheel = HSVHueSaturationWheel()
116
+ wheel.set_color_manager(mgr)
117
+ icon_name = HSVAdjusterPage.get_page_icon_name()
118
+ for dir_name in sys.argv[1:]:
119
+ wheel.save_icon_tree(dir_name, icon_name)
120
+ else:
121
+ # Interactive test
122
+ mgr.set_color(HSVColor(0.333, 0.6, 0.5))
123
+ page = HSVAdjusterPage()
124
+ page.set_color_manager(mgr)
125
+ window = gtk.Window()
126
+ window.add(page.get_page_widget())
127
+ window.set_title(os.path.basename(sys.argv[0]))
128
+ window.set_border_width(6)
129
+ window.connect("destroy", lambda *a: gtk.main_quit())
130
+ window.show_all()
131
+ gtk.main()
pool/shard008/Python/0075163_nuvpnconnection.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are met:
8
+ # * Redistributions of source code must retain the above copyright
9
+ # notice, this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright
11
+ # notice, this list of conditions and the following disclaimer in the
12
+ # documentation and/or other materials provided with the distribution.
13
+ # * Neither the name of the copyright holder nor the names of its contributors
14
+ # may be used to endorse or promote products derived from this software without
15
+ # specific prior written permission.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
21
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24
+ # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+
30
+
31
+ from .fetchers import NUMetadatasFetcher
32
+
33
+
34
+ from .fetchers import NUGlobalMetadatasFetcher
35
+
36
+ from bambou import NURESTObject
37
+
38
+
39
+ class NUVPNConnection(NURESTObject):
40
+ """ Represents a VPNConnection in the VSD
41
+
42
+ Notes:
43
+ Attaching this object to a WAN Service allows to extend its connectivity to and from external resources defined on your Data Center Edge Gateway.
44
+ """
45
+
46
+ __rest_name__ = "vpnconnection"
47
+ __resource_name__ = "vpnconnections"
48
+
49
+
50
+ ## Constants
51
+
52
+ CONST_ENTITY_SCOPE_GLOBAL = "GLOBAL"
53
+
54
+ CONST_ENTITY_SCOPE_ENTERPRISE = "ENTERPRISE"
55
+
56
+
57
+
58
+ def __init__(self, **kwargs):
59
+ """ Initializes a VPNConnection instance
60
+
61
+ Notes:
62
+ You can specify all parameters while calling this methods.
63
+ A special argument named `data` will enable you to load the
64
+ object from a Python dictionary
65
+
66
+ Examples:
67
+ >>> vpnconnection = NUVPNConnection(id=u'xxxx-xxx-xxx-xxx', name=u'VPNConnection')
68
+ >>> vpnconnection = NUVPNConnection(data=my_dict)
69
+ """
70
+
71
+ super(NUVPNConnection, self).__init__()
72
+
73
+ # Read/Write Attributes
74
+
75
+ self._name = None
76
+ self._last_updated_by = None
77
+ self._description = None
78
+ self._entity_scope = None
79
+ self._associated_wan_service_id = None
80
+ self._external_id = None
81
+
82
+ self.expose_attribute(local_name="name", remote_name="name", attribute_type=str, is_required=True, is_unique=False)
83
+ self.expose_attribute(local_name="last_updated_by", remote_name="lastUpdatedBy", attribute_type=str, is_required=False, is_unique=False)
84
+ self.expose_attribute(local_name="description", remote_name="description", attribute_type=str, is_required=False, is_unique=False)
85
+ self.expose_attribute(local_name="entity_scope", remote_name="entityScope", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL'])
86
+ self.expose_attribute(local_name="associated_wan_service_id", remote_name="associatedWANServiceID", attribute_type=str, is_required=False, is_unique=False)
87
+ self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True)
88
+
89
+
90
+ # Fetchers
91
+
92
+
93
+ self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
94
+
95
+
96
+ self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship="child")
97
+
98
+
99
+ self._compute_args(**kwargs)
100
+
101
+ # Properties
102
+
103
+ @property
104
+ def name(self):
105
+ """ Get name value.
106
+
107
+ Notes:
108
+ Name of the VPNConnect
109
+
110
+
111
+ """
112
+ return self._name
113
+
114
+ @name.setter
115
+ def name(self, value):
116
+ """ Set name value.
117
+
118
+ Notes:
119
+ Name of the VPNConnect
120
+
121
+
122
+ """
123
+ self._name = value
124
+
125
+
126
+ @property
127
+ def last_updated_by(self):
128
+ """ Get last_updated_by value.
129
+
130
+ Notes:
131
+ ID of the user who last updated the object.
132
+
133
+
134
+ This attribute is named `lastUpdatedBy` in VSD API.
135
+
136
+ """
137
+ return self._last_updated_by
138
+
139
+ @last_updated_by.setter
140
+ def last_updated_by(self, value):
141
+ """ Set last_updated_by value.
142
+
143
+ Notes:
144
+ ID of the user who last updated the object.
145
+
146
+
147
+ This attribute is named `lastUpdatedBy` in VSD API.
148
+
149
+ """
150
+ self._last_updated_by = value
151
+
152
+
153
+ @property
154
+ def description(self):
155
+ """ Get description value.
156
+
157
+ Notes:
158
+ A description of the VPNConnect
159
+
160
+
161
+ """
162
+ return self._description
163
+
164
+ @description.setter
165
+ def description(self, value):
166
+ """ Set description value.
167
+
168
+ Notes:
169
+ A description of the VPNConnect
170
+
171
+
172
+ """
173
+ self._description = value
174
+
175
+
176
+ @property
177
+ def entity_scope(self):
178
+ """ Get entity_scope value.
179
+
180
+ Notes:
181
+ Specify if scope of entity is Data center or Enterprise level
182
+
183
+
184
+ This attribute is named `entityScope` in VSD API.
185
+
186
+ """
187
+ return self._entity_scope
188
+
189
+ @entity_scope.setter
190
+ def entity_scope(self, value):
191
+ """ Set entity_scope value.
192
+
193
+ Notes:
194
+ Specify if scope of entity is Data center or Enterprise level
195
+
196
+
197
+ This attribute is named `entityScope` in VSD API.
198
+
199
+ """
200
+ self._entity_scope = value
201
+
202
+
203
+ @property
204
+ def associated_wan_service_id(self):
205
+ """ Get associated_wan_service_id value.
206
+
207
+ Notes:
208
+ Assosciated WAN Service
209
+
210
+
211
+ This attribute is named `associatedWANServiceID` in VSD API.
212
+
213
+ """
214
+ return self._associated_wan_service_id
215
+
216
+ @associated_wan_service_id.setter
217
+ def associated_wan_service_id(self, value):
218
+ """ Set associated_wan_service_id value.
219
+
220
+ Notes:
221
+ Assosciated WAN Service
222
+
223
+
224
+ This attribute is named `associatedWANServiceID` in VSD API.
225
+
226
+ """
227
+ self._associated_wan_service_id = value
228
+
229
+
230
+ @property
231
+ def external_id(self):
232
+ """ Get external_id value.
233
+
234
+ Notes:
235
+ External object ID. Used for integration with third party systems
236
+
237
+
238
+ This attribute is named `externalID` in VSD API.
239
+
240
+ """
241
+ return self._external_id
242
+
243
+ @external_id.setter
244
+ def external_id(self, value):
245
+ """ Set external_id value.
246
+
247
+ Notes:
248
+ External object ID. Used for integration with third party systems
249
+
250
+
251
+ This attribute is named `externalID` in VSD API.
252
+
253
+ """
254
+ self._external_id = value
255
+
256
+
257
+
258
+
pool/shard008/Python/0075164_impl.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #BEGIN_HEADER
2
+ from biokbase.userandjobstate.client import UserAndJobState
3
+ from biokbase.narrativejobproxy.NarrativeJobServiceClient import NarrativeJobService
4
+ import time
5
+ #END_HEADER
6
+
7
+
8
+ class NarrativeJobProxy:
9
+ '''
10
+ Module Name:
11
+ NarrativeJobProxy
12
+
13
+ Module Description:
14
+ Very simple proxy that reauthenticates requests to the user_and_job_state
15
+ service as the narrative user.
16
+
17
+ DO NOT DEPLOY PUBLICALLY
18
+ '''
19
+
20
+ ######## WARNING FOR GEVENT USERS #######
21
+ # Since asynchronous IO can lead to methods - even the same method -
22
+ # interrupting each other, you must be *very* careful when using global
23
+ # state. A method could easily clobber the state set by another while
24
+ # the latter method is running.
25
+ #########################################
26
+ #BEGIN_CLASS_HEADER
27
+ UPDATE_TOKEN_INTERVAL = 24 * 60 * 60 # 1 day in sec
28
+ # UPDATE_TOKEN_INTERVAL = 10
29
+
30
+ def _update_token(self):
31
+ if self._updating:
32
+ return
33
+ if (time.time() - self._updated_at < self.UPDATE_TOKEN_INTERVAL):
34
+ return
35
+ self._updating = True
36
+ print('Updating token at ' + str(time.time()))
37
+ try:
38
+ self._ujs = UserAndJobState(self._url, user_id=self._user,
39
+ password=self._pwd)
40
+ self._njs = NarrativeJobService(self._njs_url, user_id=self._user,
41
+ password=self._pwd)
42
+ self._updated_at = time.time()
43
+ finally: # otherwise token will never be updated
44
+ self._updating = False
45
+
46
+ #END_CLASS_HEADER
47
+
48
+ # config contains contents of config file in a hash or None if it couldn't
49
+ # be found
50
+ def __init__(self, config):
51
+ #BEGIN_CONSTRUCTOR
52
+ self._user = config.get('narrative_user')
53
+ self._pwd = config.get('narrative_user_pwd')
54
+ if not self._user or not self._pwd:
55
+ raise ValueError(
56
+ 'narrative user and/or narrative pwd missing from deploy.cfg')
57
+ self._url = config.get('ujs_url')
58
+ if not self._url:
59
+ raise ValueError('UJS url missing from deploy.cfg')
60
+ self._njs_url = config.get('njs_url')
61
+ if not self._njs_url:
62
+ raise ValueError('NJS url missing from deploy.cfg')
63
+ self._updated_at = - self.UPDATE_TOKEN_INTERVAL
64
+ self._updating = False
65
+ self._update_token()
66
+ #END_CONSTRUCTOR
67
+ pass
68
+
69
+ def ver(self, ctx):
70
+ # ctx is the context object
71
+ # return variables are: ver
72
+ #BEGIN ver
73
+ ver = '0.0.2'
74
+ #END ver
75
+
76
+ # At some point might do deeper type checking...
77
+ if not isinstance(ver, basestring):
78
+ raise ValueError('Method ver return value ' +
79
+ 'ver is not type basestring as required.')
80
+ # return the results
81
+ return [ver]
82
+
83
+ def get_detailed_error(self, ctx, job):
84
+ # ctx is the context object
85
+ # return variables are: error
86
+ #BEGIN get_detailed_error
87
+ self._update_token()
88
+ error = self._ujs.get_detailed_error(job)
89
+ #END get_detailed_error
90
+
91
+ # At some point might do deeper type checking...
92
+ if not isinstance(error, basestring):
93
+ raise ValueError('Method get_detailed_error return value ' +
94
+ 'error is not type basestring as required.')
95
+ # return the results
96
+ return [error]
97
+
98
+ def get_job_info(self, ctx, job):
99
+ # ctx is the context object
100
+ # return variables are: info
101
+ #BEGIN get_job_info
102
+ self._update_token()
103
+ info = self._ujs.get_job_info(job)
104
+ #END get_job_info
105
+
106
+ # At some point might do deeper type checking...
107
+ if not isinstance(info, list):
108
+ raise ValueError('Method get_job_info return value ' +
109
+ 'info is not type list as required.')
110
+ # return the results
111
+ return [info]
112
+
113
+ def check_app_state(self, ctx, job_id):
114
+ # ctx is the context object
115
+ # return variables are: returnVal
116
+ #BEGIN check_app_state
117
+ self._update_token()
118
+ returnVal = self._njs.check_app_state(job_id)
119
+ #END check_app_state
120
+
121
+ # At some point might do deeper type checking...
122
+ if not isinstance(returnVal, dict):
123
+ raise ValueError('Method check_app_state return value ' +
124
+ 'returnVal is not type dict as required.')
125
+ # return the results
126
+ return [returnVal]
127
+
128
+ def get_job_logs(self, ctx, params):
129
+ # ctx is the context object
130
+ # return variables are: returnVal
131
+ #BEGIN get_job_logs
132
+ self._update_token()
133
+ returnVal = self._njs.get_job_logs(params)
134
+ #END get_job_logs
135
+
136
+ # At some point might do deeper type checking...
137
+ if not isinstance(returnVal, dict):
138
+ raise ValueError('Method get_job_logs return value ' +
139
+ 'returnVal is not type dict as required.')
140
+ # return the results
141
+ return [returnVal]
pool/shard008/Python/0075165_io_context.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional, TYPE_CHECKING
3
+
4
+ from ray.rllib.utils.annotations import PublicAPI
5
+ from ray.rllib.utils.typing import TrainerConfigDict
6
+
7
+ if TYPE_CHECKING:
8
+ from ray.rllib.evaluation.sampler import SamplerInput
9
+ from ray.rllib.evaluation.rollout_worker import RolloutWorker
10
+
11
+
12
+ @PublicAPI
13
+ class IOContext:
14
+ """Class containing attributes to pass to input/output class constructors.
15
+
16
+ RLlib auto-sets these attributes when constructing input/output classes,
17
+ such as InputReaders and OutputWriters.
18
+ """
19
+
20
+ @PublicAPI
21
+ def __init__(
22
+ self,
23
+ log_dir: Optional[str] = None,
24
+ config: Optional[TrainerConfigDict] = None,
25
+ worker_index: int = 0,
26
+ worker: Optional["RolloutWorker"] = None,
27
+ ):
28
+ """Initializes a IOContext object.
29
+
30
+ Args:
31
+ log_dir: The logging directory to read from/write to.
32
+ config: The Trainer's main config dict.
33
+ worker_index (int): When there are multiple workers created, this
34
+ uniquely identifies the current worker. 0 for the local
35
+ worker, >0 for any of the remote workers.
36
+ worker: The RolloutWorker object reference.
37
+ """
38
+ self.log_dir = log_dir or os.getcwd()
39
+ self.config = config or {}
40
+ self.worker_index = worker_index
41
+ self.worker = worker
42
+
43
+ @PublicAPI
44
+ def default_sampler_input(self) -> Optional["SamplerInput"]:
45
+ """Returns the RolloutWorker's SamplerInput object, if any.
46
+
47
+ Returns None if the RolloutWorker has no SamplerInput. Note that local
48
+ workers in case there are also one or more remote workers by default
49
+ do not create a SamplerInput object.
50
+
51
+ Returns:
52
+ The RolloutWorkers' SamplerInput object or None if none exists.
53
+ """
54
+ return self.worker.sampler
55
+
56
+ @PublicAPI
57
+ @property
58
+ def input_config(self):
59
+ return self.config.get("input_config", {})
60
+
61
+ @PublicAPI
62
+ @property
63
+ def output_config(self):
64
+ return self.config.get("output_config", {})
pool/shard008/Python/0075167_dummyActuator.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ =========================================
4
+ dummyActuator.py - Dummy Actuator Handler
5
+ =========================================
6
+
7
+ Does nothing more than print the actuator name and state; for testing purposes.
8
+ """
9
+
10
+ import subprocess, os, time, socket
11
+ import sys
12
+
13
+ class actuatorHandler:
14
+ def __init__(self, proj, shared_data):
15
+ self.proj = proj
16
+ self.p_gui = None
17
+
18
+ def _stop(self):
19
+ if self.p_gui is not None:
20
+ print >>sys.__stderr__, "(SENS) Killing dummyactuator GUI..."
21
+ try:
22
+ self.p_gui.stdin.write(":QUIT\n")
23
+ self.p_gui.stdin.close()
24
+ except IOError:
25
+ # Probably already closed by user
26
+ pass
27
+
28
+ def setActuator(self, name, actuatorVal,initial):
29
+ """
30
+ Pretends to set actuator of name ``name`` to be in state ``val`` (bool).
31
+
32
+ name (string): Name of the actuator
33
+ """
34
+
35
+ if initial:
36
+ if self.p_gui is None:
37
+ # Prepare to receive initialization signal
38
+ host = 'localhost'
39
+ port = 23559
40
+ buf = 1024
41
+ addr = (host,port)
42
+
43
+ UDPSock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
44
+ UDPSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
45
+ try:
46
+ UDPSock.bind(addr)
47
+ except:
48
+ print "ERROR: Cannot bind to port. Try killing all Python processes and trying again."
49
+ return
50
+
51
+ # Create a subprocess
52
+ print "(SENS) Starting actuatorHandler window..."
53
+ self.p_gui = subprocess.Popen(["python", "-u", os.path.join(self.proj.ltlmop_root,"lib","handlers","share","_ActuatorHandler.py")], stderr=subprocess.PIPE, stdin=subprocess.PIPE)
54
+
55
+ data = ''
56
+ while "Hello!" not in data:
57
+ # Wait for and receive a message from the subwindow
58
+ try:
59
+ data,addrFrom = UDPSock.recvfrom(1024)
60
+ except socket.timeout:
61
+ print "Waiting for GUI..."
62
+ continue
63
+
64
+ UDPSock.close()
65
+
66
+ self.p_gui.stdin.write(name + ",init\n")
67
+ else:
68
+ if actuatorVal:
69
+ time.sleep(0.1) # Fake some time lag for the actuator to enable
70
+
71
+ self.p_gui.stdin.write("{},{}\n".format(name,int(actuatorVal)))
72
+
73
+ print "(ACT) Actuator %s is now %s!" % tuple(map(str, (name, actuatorVal)))
74
+
pool/shard008/Python/0075169_db.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from pathlib import Path
3
+ import sqlite3
4
+ import sys
5
+
6
+ import suxsom.sux
7
+
8
+ class DB():
9
+ def __init__(self, path=None):
10
+ if path is None:
11
+ path = self.default_path()
12
+
13
+ self.conn = sqlite3.connect(path)
14
+
15
+ def default_path(self):
16
+ return "suxsom.db"
17
+
18
+ def create_tables(self, d=None):
19
+ if d is None:
20
+ d=Path("SCHEMA")
21
+ for f in d.glob("*.sql"):
22
+ table = f.stem
23
+ print(f"creating table {table}", file=sys.stderr)
24
+ sql = f.read_text()
25
+ self.conn.execute(sql)
26
+
27
+ def find_sux_by_id(self, id):
28
+ c = self.conn.cursor()
29
+ c.execute("select * from sux where id = ?", (id, ))
30
+ rec = c.fetchone()
31
+ if rec is None:
32
+ return None
33
+ from pprint import pprint
34
+ pprint(rec)
35
+
36
+ def find_sux_by_name(self, owner, name):
37
+ c = self.conn.cursor()
38
+ c.execute("select * from sux where owner = ? and name = ?", (owner, name))
39
+ rec = c.fetchone()
40
+ if rec is None:
41
+ return None
42
+ o = suxsom.sux.sux(name, owner)
43
+ o.from_rec(rec)
44
+ return o
45
+
46
+ def save_sux(self, o):
47
+ o.set_last_modified()
48
+ if o.id is None:
49
+ print("creating sux")
50
+ self.conn.execute("""
51
+ insert into sux(name, owner, last_modified)
52
+ values (?, ?, ?)
53
+ """, (o.name, o.owner, o.last_modified))
54
+ c = self.conn.cursor()
55
+ c.execute("""
56
+ select id from sux
57
+ where name = ? and owner = ?
58
+ """, (o.name, o.owner))
59
+ o.id, = c.fetchone()
60
+ self.conn.commit()
61
+
62
+ # now the sux has an ID
63
+ self.conn.execute("""
64
+ update sux set name = ?, owner = ?, last_modified = ?
65
+ where id = ?
66
+ """, (o.name, o.owner, o.last_modified, o.id))
67
+ self.save_sux_metadata(o)
68
+ self.conn.commit()
69
+
70
+ return o.id
71
+
72
+ def save_sux_metadata(self, o):
73
+ pass
pool/shard008/Python/0075172_updateloginprofile.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2009-2013 Eucalyptus Systems, Inc.
2
+ #
3
+ # Redistribution and use of this software in source and binary forms,
4
+ # with or without modification, are permitted provided that the following
5
+ # conditions are met:
6
+ #
7
+ # Redistributions of source code must retain the above copyright notice,
8
+ # this list of conditions and the following disclaimer.
9
+ #
10
+ # Redistributions in binary form must reproduce the above copyright
11
+ # notice, this list of conditions and the following disclaimer in the
12
+ # documentation and/or other materials provided with the distribution.
13
+ #
14
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18
+ # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+
26
+ from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT
27
+ from euca2ools.util import prompt_for_password
28
+ from requestbuilder import Arg
29
+
30
+
31
+ class UpdateLoginProfile(IAMRequest):
32
+ DESCRIPTION = "Update a user's password"
33
+ ARGS = [Arg('-u', '--user-name', dest='UserName', metavar='USER',
34
+ required=True,
35
+ help='name of the user to change a password for (required)'),
36
+ Arg('-p', '--password', dest='Password',
37
+ help='''the new password. If unspecified, the new password
38
+ will be read from the console.'''),
39
+ AS_ACCOUNT]
40
+
41
+ def configure(self):
42
+ IAMRequest.configure(self)
43
+ if self.args['Password'] is None:
44
+ self.log.info('no password supplied; prompting')
45
+ self.params['Password'] = prompt_for_password()
pool/shard008/Python/0075173_bridge.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2013 GNS3 Technologies Inc.
4
+ #
5
+ # This program is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # This program is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU General Public License
16
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ """
19
+ Interface for Dynamips NIO bridge module ("nio_bridge").
20
+ http://github.com/GNS3/dynamips/blob/master/README.hypervisor#L538
21
+ """
22
+
23
+ import asyncio
24
+ from .device import Device
25
+
26
+
27
+ class Bridge(Device):
28
+
29
+ """
30
+ Dynamips bridge.
31
+
32
+ :param name: name for this bridge
33
+ :param node_id: Node instance identifier
34
+ :param project: Project instance
35
+ :param manager: Parent VM Manager
36
+ :param hypervisor: Dynamips hypervisor instance
37
+ """
38
+
39
+ def __init__(self, name, node_id, project, manager, hypervisor=None):
40
+
41
+ super().__init__(name, node_id, project, manager, hypervisor)
42
+ self._nios = []
43
+
44
+ @asyncio.coroutine
45
+ def create(self):
46
+
47
+ if self._hypervisor is None:
48
+ module_workdir = self.project.module_working_directory(self.manager.module_name.lower())
49
+ self._hypervisor = yield from self.manager.start_new_hypervisor(working_dir=module_workdir)
50
+
51
+ yield from self._hypervisor.send('nio_bridge create "{}"'.format(self._name))
52
+ self._hypervisor.devices.append(self)
53
+
54
+ @asyncio.coroutine
55
+ def set_name(self, new_name):
56
+ """
57
+ Renames this bridge.
58
+
59
+ :param new_name: New name for this bridge
60
+ """
61
+
62
+ yield from self._hypervisor.send('nio_bridge rename "{name}" "{new_name}"'.format(name=self._name,
63
+ new_name=new_name))
64
+
65
+ self._name = new_name
66
+
67
+ @property
68
+ def nios(self):
69
+ """
70
+ Returns all the NIOs member of this bridge.
71
+
72
+ :returns: nio list
73
+ """
74
+
75
+ return self._nios
76
+
77
+ @asyncio.coroutine
78
+ def delete(self):
79
+ """
80
+ Deletes this bridge.
81
+ """
82
+
83
+ if self._hypervisor and self in self._hypervisor.devices:
84
+ self._hypervisor.devices.remove(self)
85
+ if self._hypervisor and not self._hypervisor.devices:
86
+ yield from self._hypervisor.send('nio_bridge delete "{}"'.format(self._name))
87
+
88
+ @asyncio.coroutine
89
+ def add_nio(self, nio):
90
+ """
91
+ Adds a NIO as new port on this bridge.
92
+
93
+ :param nio: NIO instance to add
94
+ """
95
+
96
+ yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio))
97
+ self._nios.append(nio)
98
+
99
+ @asyncio.coroutine
100
+ def remove_nio(self, nio):
101
+ """
102
+ Removes the specified NIO as member of this bridge.
103
+
104
+ :param nio: NIO instance to remove
105
+ """
106
+
107
+ yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio))
108
+ self._nios.remove(nio)
pool/shard008/Python/0075174_plot.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import division
2
+ import sys
3
+ from matplotlib.pyplot import *
4
+ import numpy
5
+
6
+ def main(filename, outfilename):
7
+ data = numpy.genfromtxt(filename)
8
+
9
+ # plot the graph and save it
10
+ if filename == 'figure-1-data.txt':
11
+ suptitle('Memory allocated (log/log plot)')
12
+ ylabel('bytes of memory allocated')
13
+ elif filename == 'figure-2-data.txt':
14
+ suptitle('Memory written (log/log plot)')
15
+ ylabel('bytes of memory written')
16
+ xlabel('number of entries')
17
+
18
+ index = data[:,0]
19
+ series1 = data[:,1]
20
+ series2 = data[:,2]
21
+ series3 = data[:,3]
22
+ loglog(index, series1, '-', color='#cccccc', label='dense_hash_map (open addressing)')
23
+ loglog(index, series2, 'b-', label='open addressing')
24
+ loglog(index, series3, 'r-', label='Close table')
25
+ legend(loc='upper left')
26
+ savefig(outfilename, format='png')
27
+
28
+ # compute and print summary information about which is bigger
29
+ r1 = []
30
+ r2 = []
31
+ for i, _, s1, s2 in data:
32
+ if s1 > s2:
33
+ r1.append(s1/s2)
34
+ else:
35
+ r2.append(s2/s1)
36
+
37
+ r1avg = sum(r1)/len(r1) - 1 if len(r1) else 0
38
+ r2avg = sum(r2)/len(r2) - 1 if len(r2) else 0
39
+ r1f = len(r1)/len(data)
40
+ r2f = len(r2)/len(data)
41
+ print("Implementation 1 takes up more space {:.1%} of the time, by {:.1%}".format(r1f, r1avg))
42
+ print("Implementation 2 takes up more space {:.1%} of the time, by {:.1%}".format(r2f, r2avg))
43
+
44
+ main(sys.argv[1], sys.argv[2])
pool/shard008/Python/0075176_apod.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ try:
3
+ import urllib2
4
+ except:
5
+ print "[APOD] Install latest version of python2.7"
6
+ sys.exit()
7
+
8
+ try:
9
+ from bs4 import BeautifulSoup as bs
10
+ except:
11
+ print "[APOD] BeautifulSoup package required"
12
+ print "[APOD] please Install BeautifulSoup"
13
+ print "Go to https://pypi.python.org/pypi/beautifulsoup4"
14
+ sys.exit()
15
+
16
+ from time import strftime, time
17
+
18
+ from utils.Error_codes import Error_codes
19
+
20
+
21
+
22
+ class APOD_Downloader():
23
+ def __init__(self, error_codes):
24
+ self.BASE_URL = "http://apod.it"
25
+ self.error_codes = error_codes
26
+
27
+ def get_apod_url(self):
28
+ img = strftime("%y%m%d")
29
+ img_url = self.BASE_URL + "/" + img
30
+ return img_url
31
+
32
+ def get_image_url(self, img_url):
33
+ try:
34
+ req = urllib2.urlopen(img_url)
35
+
36
+ except urllib2.HTTPError, e:
37
+ print "[APOD] Failed to connect", e.getcode()
38
+ print "[APOD]",self.error_codes.error_code_status(e.getcode())
39
+ print "[APOD]", "Exiting..."
40
+ return selferror_codes.err["HTTPERR"]
41
+
42
+ except urllib2.URLError, e:
43
+ print "[APOD]", e.args[0]
44
+ print "[APOD]", "Internet Connection not working"
45
+ print "[APOD]", "Exiting..."
46
+ return self.error_codes.err["URLERR"]
47
+
48
+ # Reading the page source of the apod.nasa.gov page
49
+ page_html = req.read()
50
+ soup = bs(page_html, "html.parser")
51
+
52
+ images = soup.find_all("a")
53
+
54
+ # The second link is the image location
55
+ # for the higest resolution version
56
+ try:
57
+ image_location = images[1].get("href")
58
+ except:
59
+ return self.error_codes.err["NOIMG"]
60
+
61
+ # Sample Image location
62
+ # http://apod.nasa.gov/apod/image/1602/HeartCloud_Kunze_4650.jpg
63
+
64
+ full_res_image_url = "http://apod.nasa.gov/" + image_location
65
+ return full_res_image_url
66
+
67
+ def download_image(self, url):
68
+ file_name = url.split('/')[-1]
69
+ try:
70
+ u = urllib2.urlopen(url)
71
+ meta = u.info()
72
+ # meta info
73
+ # Server: WebServer/1.0
74
+ # Last-Modified: Sat, 13 Feb 2016 00:00:31 GMT
75
+ # ETag: "13b612a-fef4a-52b9b78d985c0"
76
+ # Accept-Ranges: bytes
77
+ # Keep-Alive: timeout=5, max=100
78
+ # Content-Type: image/jpeg
79
+ # Connection: close
80
+ # Date: Sun, 14 Feb 2016 12:33:23 GMT
81
+ # Age: 3378
82
+ # Content-Length: 1044298
83
+ file_size = int(meta.getheaders("Content-length")[0])
84
+ file_type = meta.getheaders("Content-Type")[0]
85
+
86
+ if (file_type != "image/jpeg"):
87
+ print "[APOD]", "The content hosted on apod.nasa.gov is not an image"
88
+ return self.error_codes.err["NOIMG"]
89
+ # Block size of each download packet is kept 4 KB
90
+ block_sz = 4096
91
+
92
+ # Stores the total file downloaded
93
+ file_dl = 0
94
+
95
+ #stating time of download
96
+ start_time = time()
97
+ running_time = start_time
98
+
99
+ # file name is same as the name of the image in the apod link
100
+ f = open(file_name, "wb")
101
+
102
+ while True:
103
+ buffer = u.read(block_sz)
104
+ if not buffer:
105
+ break
106
+ file_dl += len(buffer)
107
+ f.write(buffer)
108
+ curr_time = time()
109
+ if (curr_time - running_time >= 0.25):
110
+ print "[APOD] Downloaded %.2f KB of %.2f KB \r" %(file_dl / 1024.0, file_size / 1024.0),
111
+ running_time = curr_time
112
+ end_time = time()
113
+ f.close()
114
+ print
115
+
116
+ try:
117
+ # checking if the total size of the file downloaded and the actual size of the file
118
+ # are same or not, it not an assertion error is raised and the program exits
119
+ assert file_dl == file_size
120
+ except AssertionError:
121
+ print "[APOD]", "File download incomplete or corrupt, please try again"
122
+ print "[APOD]", "Exiting..."
123
+ return self.error_codes.err['INCOMPDL']
124
+
125
+ print "[APOD] Downloaded %.2f KB in %.2fs"%((file_size / 1024.0), (end_time - start_time))
126
+
127
+ except urllib2.HTTPError, e:
128
+ print "[APOD] Failed to connect", e.getcode()
129
+ print "[APOD]",self.error_codes.error_code_status(e.getcode())
130
+ print "[APOD]", "Exiting..."
131
+ return self.error_codes.err["HTTPERR"]
132
+
133
+ except urllib2.URLError, e:
134
+ print "[APOD]", e.args[0]
135
+ print "[APOD]", "Internet Connection not working"
136
+ print "[APOD]", "Exiting..."
137
+ return self.error_codes.err["URLERR"]
138
+
139
+ def apod_download(self):
140
+ apod_url = self.get_apod_url();
141
+ if (apod_url not in self.error_codes.get_error_list()):
142
+ img_url = self.get_image_url(apod_url)
143
+ if (img_url not in self.error_codes.get_error_list()):
144
+ self.download_image(img_url)
145
+ else:
146
+ return
147
+ else:
148
+ return
149
+
150
+ if __name__ == "__main__":
151
+ ec = Error_codes()
152
+ apod = APOD_Downloader(ec)
153
+ apod.apod_download()
pool/shard008/Python/0075177_1805eda2bbfa_added_prev_state_column.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Added prev_state column
2
+
3
+ Revision ID: 1805eda2bbfa
4
+ Revises: 1a29f9f5c21c
5
+ Create Date: 2014-04-24 09:19:56.308929
6
+
7
+ """
8
+
9
+ # revision identifiers, used by Alembic.
10
+ revision = '1805eda2bbfa'
11
+ down_revision = '1a29f9f5c21c'
12
+
13
+ from alembic import op
14
+ import sqlalchemy as sa
15
+
16
+
17
+ def upgrade():
18
+ op.add_column('tasks_history', sa.Column('prev_state', sa.Integer(), nullable=True))
19
+
20
+
21
+ def downgrade():
22
+ op.drop_column('tasks_history', 'prev_state')
pool/shard008/Python/0075180_test_poll.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Test case for the os.poll() function
2
+
3
+ import os, select, random, unittest
4
+ from test.test_support import TESTFN, run_unittest
5
+
6
+ try:
7
+ select.poll
8
+ except AttributeError:
9
+ raise unittest.SkipTest, "select.poll not defined -- skipping test_poll"
10
+
11
+
12
+ def find_ready_matching(ready, flag):
13
+ match = []
14
+ for fd, mode in ready:
15
+ if mode & flag:
16
+ match.append(fd)
17
+ return match
18
+
19
+ class PollTests(unittest.TestCase):
20
+
21
+ def test_poll1(self):
22
+ # Basic functional test of poll object
23
+ # Create a bunch of pipe and test that poll works with them.
24
+
25
+ p = select.poll()
26
+
27
+ NUM_PIPES = 12
28
+ MSG = " This is a test."
29
+ MSG_LEN = len(MSG)
30
+ readers = []
31
+ writers = []
32
+ r2w = {}
33
+ w2r = {}
34
+
35
+ for i in range(NUM_PIPES):
36
+ rd, wr = os.pipe()
37
+ p.register(rd)
38
+ p.modify(rd, select.POLLIN)
39
+ p.register(wr, select.POLLOUT)
40
+ readers.append(rd)
41
+ writers.append(wr)
42
+ r2w[rd] = wr
43
+ w2r[wr] = rd
44
+
45
+ bufs = []
46
+
47
+ while writers:
48
+ ready = p.poll()
49
+ ready_writers = find_ready_matching(ready, select.POLLOUT)
50
+ if not ready_writers:
51
+ raise RuntimeError, "no pipes ready for writing"
52
+ wr = random.choice(ready_writers)
53
+ os.write(wr, MSG)
54
+
55
+ ready = p.poll()
56
+ ready_readers = find_ready_matching(ready, select.POLLIN)
57
+ if not ready_readers:
58
+ raise RuntimeError, "no pipes ready for reading"
59
+ rd = random.choice(ready_readers)
60
+ buf = os.read(rd, MSG_LEN)
61
+ self.assertEqual(len(buf), MSG_LEN)
62
+ bufs.append(buf)
63
+ os.close(r2w[rd]) ; os.close( rd )
64
+ p.unregister( r2w[rd] )
65
+ p.unregister( rd )
66
+ writers.remove(r2w[rd])
67
+
68
+ self.assertEqual(bufs, [MSG] * NUM_PIPES)
69
+
70
+ def poll_unit_tests(self):
71
+ # returns NVAL for invalid file descriptor
72
+ FD = 42
73
+ try:
74
+ os.close(FD)
75
+ except OSError:
76
+ pass
77
+ p = select.poll()
78
+ p.register(FD)
79
+ r = p.poll()
80
+ self.assertEqual(r[0], (FD, select.POLLNVAL))
81
+
82
+ f = open(TESTFN, 'w')
83
+ fd = f.fileno()
84
+ p = select.poll()
85
+ p.register(f)
86
+ r = p.poll()
87
+ self.assertEqual(r[0][0], fd)
88
+ f.close()
89
+ r = p.poll()
90
+ self.assertEqual(r[0], (fd, select.POLLNVAL))
91
+ os.unlink(TESTFN)
92
+
93
+ # type error for invalid arguments
94
+ p = select.poll()
95
+ self.assertRaises(TypeError, p.register, p)
96
+ self.assertRaises(TypeError, p.unregister, p)
97
+
98
+ # can't unregister non-existent object
99
+ p = select.poll()
100
+ self.assertRaises(KeyError, p.unregister, 3)
101
+
102
+ # Test error cases
103
+ pollster = select.poll()
104
+ class Nope:
105
+ pass
106
+
107
+ class Almost:
108
+ def fileno(self):
109
+ return 'fileno'
110
+
111
+ self.assertRaises(TypeError, pollster.register, Nope(), 0)
112
+ self.assertRaises(TypeError, pollster.register, Almost(), 0)
113
+
114
+ # Another test case for poll(). This is copied from the test case for
115
+ # select(), modified to use poll() instead.
116
+
117
+ def test_poll2(self):
118
+ cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
119
+ p = os.popen(cmd, 'r')
120
+ pollster = select.poll()
121
+ pollster.register( p, select.POLLIN )
122
+ for tout in (0, 1000, 2000, 4000, 8000, 16000) + (-1,)*10:
123
+ fdlist = pollster.poll(tout)
124
+ if (fdlist == []):
125
+ continue
126
+ fd, flags = fdlist[0]
127
+ if flags & select.POLLHUP:
128
+ line = p.readline()
129
+ if line != "":
130
+ self.fail('error: pipe seems to be closed, but still returns data')
131
+ continue
132
+
133
+ elif flags & select.POLLIN:
134
+ line = p.readline()
135
+ if not line:
136
+ break
137
+ continue
138
+ else:
139
+ self.fail('Unexpected return value from select.poll: %s' % fdlist)
140
+ p.close()
141
+
142
+ def test_poll3(self):
143
+ # test int overflow
144
+ pollster = select.poll()
145
+ pollster.register(1)
146
+
147
+ self.assertRaises(OverflowError, pollster.poll, 1L << 64)
148
+
149
+ x = 2 + 3
150
+ if x != 5:
151
+ self.fail('Overflow must have occurred')
152
+
153
+ def test_main():
154
+ run_unittest(PollTests)
155
+
156
+ if __name__ == '__main__':
157
+ test_main()
pool/shard008/Python/0075188_init__.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render templates."""
2
+
3
+ from __future__ import absolute_import
4
+ from __future__ import division
5
+ from __future__ import print_function
6
+ from __future__ import unicode_literals
7
+
8
+ import os
9
+ import re
10
+ import stat # pylint: disable=wrong-import-order
11
+ import sys
12
+ import tempfile
13
+
14
+ import jinja2
15
+
16
+ if os.name == 'nt':
17
+ # Pylint warning unable to import because it is on Windows only
18
+ import win32api # pylint: disable=E0401
19
+ import win32con # pylint: disable=E0401
20
+
21
+
22
+ _EXEC_MODE = (stat.S_IRUSR |
23
+ stat.S_IRGRP |
24
+ stat.S_IROTH |
25
+ stat.S_IWUSR |
26
+ stat.S_IXUSR |
27
+ stat.S_IXGRP |
28
+ stat.S_IXOTH)
29
+
30
+
31
+ def render(template, **kwargs):
32
+ """Render template, adding new line in the end."""
33
+ return re.sub(
34
+ ' +',
35
+ ' ',
36
+ jinja2.Template(template).render(**kwargs)
37
+ ).lstrip() + '\n'
38
+
39
+
40
+ def generate_template(templatename, **kwargs):
41
+ """This renders a JINJA template as a generator.
42
+
43
+ The templates exist in our lib/python/treadmill/templates directory.
44
+
45
+ :param ``str`` templatename:
46
+ The name of the template file.
47
+ :param ``dict`` kwargs:
48
+ key/value passed into the template.
49
+ """
50
+ jinja_env = jinja2.Environment(loader=jinja2.PackageLoader('treadmill'))
51
+ template = jinja_env.get_template(templatename)
52
+ return template.generate(**kwargs)
53
+
54
+
55
+ def create_script(filename, templatename, mode=_EXEC_MODE, **kwargs):
56
+ """This Creates a file from a JINJA template.
57
+
58
+ The templates exist in our lib/python/treadmill/templates directory.
59
+
60
+ :param ``str`` filename:
61
+ Name of the file to generate.
62
+ :param ``str`` templatename:
63
+ The name of the template file.
64
+ :param ``int`` mode:
65
+ The mode for the file (Defaults to +x).
66
+ :param ``dict`` kwargs:
67
+ key/value passed into the template.
68
+ """
69
+ jinja_env = jinja2.Environment(loader=jinja2.PackageLoader('treadmill'))
70
+
71
+ filepath = os.path.dirname(filename)
72
+ with tempfile.NamedTemporaryFile(dir=filepath,
73
+ delete=False,
74
+ mode='w') as f:
75
+ data = jinja_env.get_template(templatename).render(**kwargs)
76
+ f.write(data)
77
+ if os.name == 'posix':
78
+ # cast to int required in order for default _EXEC_MODE to work
79
+ os.fchmod(f.fileno(), int(mode))
80
+
81
+ if sys.version_info[0] < 3:
82
+ # TODO: os.rename cannot replace on windows
83
+ # (use os.replace in python 3.4)
84
+ # copied from fs as utils cannot have this dependency
85
+ if os.name == 'nt':
86
+ win32api.MoveFileEx(f.name, filename,
87
+ win32con.MOVEFILE_REPLACE_EXISTING)
88
+ else:
89
+ os.rename(f.name, filename)
90
+ else:
91
+ os.replace(f.name, filename)
pool/shard008/Python/0075190_problem493.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Solution to Project Euler problem 493
3
+ # Copyright (c) Project Nayuki. All rights reserved.
4
+ #
5
+ # https://www.nayuki.io/page/project-euler-solutions
6
+ # https://github.com/nayuki/Project-Euler-solutions
7
+ #
8
+
9
+ import eulerlib, fractions, math
10
+
11
+
12
+ def compute():
13
+ NUM_COLORS = 7
14
+ BALLS_PER_COLOR = 10
15
+ NUM_PICKED = 20
16
+ DECIMALS = 9
17
+
18
+ numerator = [0]
19
+
20
+ def explore(remain, limit, history):
21
+ if remain == 0:
22
+ hist = list(history)
23
+ while len(hist) < NUM_COLORS:
24
+ hist.append(0)
25
+
26
+ histogram = [0] * (BALLS_PER_COLOR + 1)
27
+ for x in hist:
28
+ histogram[x] += 1
29
+
30
+ count = math.factorial(NUM_COLORS)
31
+ for x in histogram:
32
+ count = divide_exactly(count, math.factorial(x))
33
+
34
+ for x in hist:
35
+ count *= eulerlib.binomial(BALLS_PER_COLOR, x)
36
+
37
+ distinctcolors = len(history)
38
+ numerator[0] += count * distinctcolors
39
+
40
+ elif len(history) < NUM_COLORS:
41
+ for i in range(min(limit, remain), 0, -1):
42
+ history.append(i)
43
+ explore(remain - i, i, history)
44
+ history.pop()
45
+
46
+ explore(NUM_PICKED, BALLS_PER_COLOR, [])
47
+ denominator = eulerlib.binomial(NUM_COLORS * BALLS_PER_COLOR, NUM_PICKED)
48
+ ans = fractions.Fraction(numerator[0], denominator)
49
+ return format_fraction(ans, DECIMALS)
50
+
51
+
52
+ def format_fraction(val, digits):
53
+ if digits <= 0:
54
+ raise ValueError()
55
+ if val < 0:
56
+ return "-" + format_fraction(-val, digits)
57
+ s = str(round(val * 10**digits)).zfill(digits + 1)
58
+ return f"{s[:-digits]}.{s[-digits:]}"
59
+
60
+
61
+ def divide_exactly(x, y):
62
+ if x % y != 0:
63
+ raise ValueError("Not divisible")
64
+ return x // y
65
+
66
+
67
+ if __name__ == "__main__":
68
+ print(compute())
pool/shard008/Python/0075202_stats.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ :mod:`Tor2Web`
4
+ =====================================================
5
+
6
+ .. automodule:: Tor2Web
7
+ :synopsis: Stats routines
8
+
9
+ .. moduleauthor:: Arturo Filasto' <art@globaleaks.org>
10
+ .. moduleauthor:: Giovanni Pellerano <evilaliv3@globaleaks.org>
11
+
12
+ """
13
+
14
+ # -*- coding: utf-8 -*-
15
+
16
+
17
+ import json
18
+ from datetime import date, datetime, timedelta
19
+
20
+ from twisted.internet import reactor
21
+ from twisted.internet.task import deferLater
22
+
23
+
24
+ class T2WStats(dict):
25
+ def __init__(self):
26
+ dict.__init__(self)
27
+ self.yesterday_stats = ''
28
+
29
+ self.update_stats()
30
+
31
+ def update(self, key):
32
+ if key not in self:
33
+ self[key] = 0
34
+ self[key] += 1
35
+
36
+ def update_stats(self, run_again=True):
37
+ yesterday = date.today() - timedelta(1)
38
+ hidden_services = list()
39
+ for k in self:
40
+ hidden_services.append(({'id': k, 'access_count': self[k]}))
41
+
42
+ self.yesterday_stats = json.dumps({'date': yesterday.strftime('%Y-%m-%d'),
43
+ 'hidden_services': hidden_services})
44
+ self.clear()
45
+
46
+ next_time = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + \
47
+ timedelta(days=1)
48
+ next_delta = (next_time - datetime.now()).total_seconds()
49
+ deferLater(reactor, next_delta, self.update_stats)
pool/shard008/Python/0075203_admin.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from django.contrib import admin
3
+ from django import forms
4
+
5
+ from .models import PushNotification, Device
6
+
7
+
8
+ class PushNotificationForm(forms.ModelForm):
9
+ def clean(self):
10
+ body = self.cleaned_data.get('body')
11
+ try:
12
+ body = json.loads(body)
13
+ except ValueError:
14
+ raise forms.ValidationError('Body does not contain valid JSON')
15
+ return self.cleaned_data
16
+
17
+ class Meta:
18
+ model = PushNotification
19
+ fields = (
20
+ 'title', 'body', 'active', 'sent', 'filter_type', 'filter_user'
21
+ )
22
+
23
+
24
+ class PushNotificationAdmin(admin.ModelAdmin):
25
+ form = PushNotificationForm
26
+ list_display = (
27
+ 'title',
28
+ 'date_created',
29
+ 'active',
30
+ 'sent',
31
+ 'date_started',
32
+ 'date_finished'
33
+ )
34
+ list_filter = ('active', 'sent')
35
+ search_fields = ('title', )
36
+ readonly_fields = ('date_started', 'date_finished')
37
+
38
+
39
+ class DeviceAdmin(admin.ModelAdmin):
40
+ list_display = ('key', )
41
+ list_filter = ('user', )
42
+
43
+
44
+ admin.site.register(PushNotification, PushNotificationAdmin)
45
+ admin.site.register(Device, DeviceAdmin)
pool/shard008/Python/0075205_RDFfromDX.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import grid.grid as grid
3
+ import sys
4
+ print "# Input format: RDFfromDX.py <dxfilename> <x> <y> <z> <delta> <max> (concentration)"
5
+ print "If you input a concentration (particles per unit volume), the coordination number will also be printed in the 3rd column"
6
+
7
+ if len(sys.argv) < 6:
8
+ quit("Error, insufficient arguments")
9
+
10
+ dxfilename, x, y, z, delta, maxval = sys.argv[1:7]
11
+
12
+ concentration = False
13
+ if len(sys.argv) > 7:
14
+ concentration = float(sys.argv[7])
15
+
16
+ griddata = grid.dx2Grid(dxfilename)
17
+ if not concentration:
18
+ rdf = griddata.interpRDF([float(x),float(y),float(z)], float(delta), float(maxval))
19
+ for i, value in enumerate(rdf):
20
+ print i*float(delta), value
21
+ else:
22
+ rdf, coordnums = griddata.interpRDF([float(x),float(y),float(z)], float(delta), float(maxval), concentration)
23
+ for i, value in enumerate(rdf):
24
+ print i*float(delta), value, coordnums[i]
pool/shard008/Python/0075211_deb.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import commands
2
+
3
+ def run(c):
4
+ return commands.getstatusoutput(c)[0]
5
+
6
+ share_path = '/usr/share/'
7
+ etc_path = '/etc/'
8
+ bin_path = '/usr/bin/'
9
+
10
+ def build(dir, name, ver, desc, deps, provs):
11
+ run('mkdir ' + dir + 'DEBIAN')
12
+ if name == 'ajenti':
13
+ run('echo "#!/bin/sh\nupdate-rc.d ajenti start 2 3 4 5 . stop 0 1 6 .; /etc/init.d/ajenti restart" > %sDEBIAN/postinst'%dir)
14
+ run('echo "#!/bin/sh\nupdate-rc.d -f ajenti remove; exit 0" > %sDEBIAN/postrm'%dir)
15
+ run('chmod 755 %sDEBIAN/post*'%dir)
16
+ run('echo /etc/ajenti/ajenti.conf > %sDEBIAN/conffiles'%dir)
17
+
18
+ l = (name, ver, ', '.join(deps))
19
+ i = 'Package: %s\nPriority: optional\nSection: admin\nArchitecture: all\nVersion: %s\nDepends: %s\nMaintainer: Eugeny Pankov <john.pankov@gmail.com>\n' % l
20
+ if provs != []:
21
+ i += 'Provides: %s\n' % ', '.join(provs)
22
+ i += 'Description: %s\n' % desc
23
+ with open(dir + 'DEBIAN/control', 'w') as f:
24
+ f.write(i)
25
+
26
+ run('dpkg-deb -b ' + dir + ' out/' + name + '-' + ver + '.deb')
pool/shard008/Python/0075214_test_management.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015, Cisco Systems.
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 mock
16
+
17
+ from oslo_utils import importutils
18
+
19
+ from ironic.common import boot_devices
20
+ from ironic.common import exception
21
+ from ironic.conductor import task_manager
22
+ from ironic.drivers.modules.cimc import common
23
+ from ironic.tests.drivers.cimc import test_common
24
+
25
+ imcsdk = importutils.try_import('ImcSdk')
26
+
27
+
28
+ @mock.patch.object(common, 'cimc_handle', autospec=True)
29
+ class CIMCManagementTestCase(test_common.CIMCBaseTestCase):
30
+
31
+ def test_get_properties(self, mock_handle):
32
+ with task_manager.acquire(self.context, self.node.uuid,
33
+ shared=False) as task:
34
+ self.assertEqual(common.COMMON_PROPERTIES,
35
+ task.driver.management.get_properties())
36
+
37
+ @mock.patch.object(common, "parse_driver_info", autospec=True)
38
+ def test_validate(self, mock_driver_info, mock_handle):
39
+ with task_manager.acquire(self.context, self.node.uuid,
40
+ shared=False) as task:
41
+ task.driver.management.validate(task)
42
+ mock_driver_info.assert_called_once_with(task.node)
43
+
44
+ def test_get_supported_boot_devices(self, mock_handle):
45
+ with task_manager.acquire(self.context, self.node.uuid,
46
+ shared=False) as task:
47
+ expected = [boot_devices.PXE, boot_devices.DISK,
48
+ boot_devices.CDROM]
49
+ result = task.driver.management.get_supported_boot_devices(task)
50
+ self.assertEqual(sorted(expected), sorted(result))
51
+
52
+ def test_get_boot_device(self, mock_handle):
53
+ with task_manager.acquire(self.context, self.node.uuid,
54
+ shared=False) as task:
55
+ with mock_handle(task) as handle:
56
+ handle.xml_query.return_value.error_code = None
57
+ mock_dev = mock.MagicMock()
58
+ mock_dev.Order = 1
59
+ mock_dev.Rn = 'storage-read-write'
60
+ handle.xml_query().OutConfigs.child[0].child = [mock_dev]
61
+
62
+ device = task.driver.management.get_boot_device(task)
63
+ self.assertEqual(
64
+ {'boot_device': boot_devices.DISK, 'persistent': True},
65
+ device)
66
+
67
+ def test_get_boot_device_fail(self, mock_handle):
68
+ with task_manager.acquire(self.context, self.node.uuid,
69
+ shared=False) as task:
70
+ with mock_handle(task) as handle:
71
+ handle.xml_query.return_value.error_code = None
72
+ mock_dev = mock.MagicMock()
73
+ mock_dev.Order = 1
74
+ mock_dev.Rn = 'storage-read-write'
75
+ handle.xml_query().OutConfigs.child[0].child = [mock_dev]
76
+
77
+ device = task.driver.management.get_boot_device(task)
78
+
79
+ self.assertEqual(
80
+ {'boot_device': boot_devices.DISK, 'persistent': True},
81
+ device)
82
+
83
+ def test_set_boot_device(self, mock_handle):
84
+ with task_manager.acquire(self.context, self.node.uuid,
85
+ shared=False) as task:
86
+ with mock_handle(task) as handle:
87
+ handle.xml_query.return_value.error_code = None
88
+ task.driver.management.set_boot_device(task, boot_devices.DISK)
89
+ method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo")
90
+ method.Cookie = handle.cookie
91
+ method.Dn = "sys/rack-unit-1/boot-policy"
92
+ method.InHierarchical = "true"
93
+
94
+ config = imcsdk.Imc.ConfigConfig()
95
+
96
+ bootMode = imcsdk.ImcCore.ManagedObject('lsbootStorage')
97
+ bootMode.set_attr("access", 'read-write')
98
+ bootMode.set_attr("type", 'storage')
99
+ bootMode.set_attr("Rn", 'storage-read-write')
100
+ bootMode.set_attr("order", "1")
101
+
102
+ config.add_child(bootMode)
103
+ method.InConfig = config
104
+
105
+ handle.xml_query.assert_called_once_with(
106
+ method, imcsdk.WriteXmlOption.DIRTY)
107
+
108
+ def test_set_boot_device_fail(self, mock_handle):
109
+ with task_manager.acquire(self.context, self.node.uuid,
110
+ shared=False) as task:
111
+ with mock_handle(task) as handle:
112
+ method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo")
113
+ handle.xml_query.return_value.error_code = "404"
114
+
115
+ self.assertRaises(exception.CIMCException,
116
+ task.driver.management.set_boot_device,
117
+ task, boot_devices.DISK)
118
+
119
+ handle.xml_query.assert_called_once_with(
120
+ method, imcsdk.WriteXmlOption.DIRTY)
121
+
122
+ def test_get_sensors_data(self, mock_handle):
123
+ with task_manager.acquire(self.context, self.node.uuid,
124
+ shared=False) as task:
125
+ self.assertRaises(NotImplementedError,
126
+ task.driver.management.get_sensors_data, task)
pool/shard008/Python/0075219_0008_auto_20170526_1651.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by Django 1.10.5 on 2017-05-26 16:51
3
+ from __future__ import unicode_literals
4
+
5
+ from django.db import migrations, models
6
+
7
+
8
+ class Migration(migrations.Migration):
9
+
10
+ dependencies = [
11
+ ('roombookings', '0007_auto_20170328_1109'),
12
+ ]
13
+
14
+ operations = [
15
+ migrations.AddField(
16
+ model_name='bookinga',
17
+ name='title',
18
+ field=models.CharField(blank=True, max_length=523, null=True),
19
+ ),
20
+ migrations.AddField(
21
+ model_name='bookingb',
22
+ name='title',
23
+ field=models.CharField(blank=True, max_length=523, null=True),
24
+ ),
25
+ ]
pool/shard008/Python/0075220_geomtype.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.contrib.gis.gdal.error import GDALException
2
+ from django.utils import six
3
+
4
+
5
+ class OGRGeomType(object):
6
+ "Encapsulates OGR Geometry Types."
7
+
8
+ wkb25bit = -2147483648
9
+
10
+ # Dictionary of acceptable OGRwkbGeometryType s and their string names.
11
+ _types = {0: 'Unknown',
12
+ 1: 'Point',
13
+ 2: 'LineString',
14
+ 3: 'Polygon',
15
+ 4: 'MultiPoint',
16
+ 5: 'MultiLineString',
17
+ 6: 'MultiPolygon',
18
+ 7: 'GeometryCollection',
19
+ 100: 'None',
20
+ 101: 'LinearRing',
21
+ 1 + wkb25bit: 'Point25D',
22
+ 2 + wkb25bit: 'LineString25D',
23
+ 3 + wkb25bit: 'Polygon25D',
24
+ 4 + wkb25bit: 'MultiPoint25D',
25
+ 5 + wkb25bit: 'MultiLineString25D',
26
+ 6 + wkb25bit: 'MultiPolygon25D',
27
+ 7 + wkb25bit: 'GeometryCollection25D',
28
+ }
29
+ # Reverse type dictionary, keyed by lower-case of the name.
30
+ _str_types = {v.lower(): k for k, v in _types.items()}
31
+
32
+ def __init__(self, type_input):
33
+ "Figures out the correct OGR Type based upon the input."
34
+ if isinstance(type_input, OGRGeomType):
35
+ num = type_input.num
36
+ elif isinstance(type_input, six.string_types):
37
+ type_input = type_input.lower()
38
+ if type_input == 'geometry':
39
+ type_input = 'unknown'
40
+ num = self._str_types.get(type_input, None)
41
+ if num is None:
42
+ raise GDALException('Invalid OGR String Type "%s"' % type_input)
43
+ elif isinstance(type_input, int):
44
+ if type_input not in self._types:
45
+ raise GDALException('Invalid OGR Integer Type: %d' % type_input)
46
+ num = type_input
47
+ else:
48
+ raise TypeError('Invalid OGR input type given.')
49
+
50
+ # Setting the OGR geometry type number.
51
+ self.num = num
52
+
53
+ def __str__(self):
54
+ "Returns the value of the name property."
55
+ return self.name
56
+
57
+ def __eq__(self, other):
58
+ """
59
+ Does an equivalence test on the OGR type with the given
60
+ other OGRGeomType, the short-hand string, or the integer.
61
+ """
62
+ if isinstance(other, OGRGeomType):
63
+ return self.num == other.num
64
+ elif isinstance(other, six.string_types):
65
+ return self.name.lower() == other.lower()
66
+ elif isinstance(other, int):
67
+ return self.num == other
68
+ else:
69
+ return False
70
+
71
+ def __ne__(self, other):
72
+ return not (self == other)
73
+
74
+ @property
75
+ def name(self):
76
+ "Returns a short-hand string form of the OGR Geometry type."
77
+ return self._types[self.num]
78
+
79
+ @property
80
+ def django(self):
81
+ "Returns the Django GeometryField for this OGR Type."
82
+ s = self.name.replace('25D', '')
83
+ if s in ('LinearRing', 'None'):
84
+ return None
85
+ elif s == 'Unknown':
86
+ s = 'Geometry'
87
+ return s + 'Field'
pool/shard008/Python/0075222_views.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rest_framework.viewsets import ModelViewSet
2
+ from rest_framework.decorators import list_route, detail_route
3
+ from rest_framework.response import Response
4
+ from rest_framework.filters import DjangoFilterBackend, OrderingFilter
5
+
6
+ from . import serializers
7
+ from .permissions import UserPermission, CreateAndViewPermission
8
+ from ..models import (
9
+ Question,
10
+ Answer,
11
+ Comment,
12
+ Vote,
13
+ Tag
14
+ )
15
+
16
+
17
+ class QuestionViewSet(ModelViewSet):
18
+ queryset = Question.objects.all().order_by('votes')
19
+ permission_classes = [UserPermission]
20
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
21
+ filter_fields = ['author__email', 'author__first_name', 'author__last_name', 'title', 'content']
22
+
23
+ def get_serializer_class(self):
24
+ if self.action == 'create':
25
+ return serializers.CreateQuestionSerializer
26
+ if self.action == 'update':
27
+ return serializers.UpdateQuestionSerializer
28
+ return serializers.QuestionSerializer
29
+
30
+ @detail_route(methods=['post'])
31
+ def upvote(self, request, pk=None):
32
+ question = self.get_object()
33
+ request.user.vote_for_question(question, Vote.UP)
34
+ serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, question=question))
35
+ return Response(serializer.data)
36
+
37
+ @detail_route(methods=['post'])
38
+ def downvote(self, request, pk=None):
39
+ question = self.get_object()
40
+ request.user.vote_for_question(question, Vote.DOWN)
41
+ serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, question=question))
42
+ return Response(serializer.data)
43
+
44
+ @detail_route(methods=['get'])
45
+ def vote(self, request, pk=None, vote=None):
46
+ question = self.get_object()
47
+ try:
48
+ Vote.objects.get(voted_by=request.user, question=question)
49
+ obj = Vote.objects.get(voted_by=request.user, question=question)
50
+ return Response({
51
+ 'status': True,
52
+ 'question_id': question.id,
53
+ 'message': '{} has {}voted answer with id {}'.format(request.user, obj.vote, question.id),
54
+ 'vote': obj.vote,
55
+ 'total_votes': question.votes
56
+ })
57
+ except Vote.DoesNotExist:
58
+ return Response({
59
+ 'status': False,
60
+ 'question_id': question.id,
61
+ 'message': '{} has not voted for answer with id {}'.format(request.user, question.id),
62
+ 'vote': None,
63
+ 'total_votes': question.votes
64
+ })
65
+
66
+ @list_route(methods=['get'])
67
+ def popular(self, request):
68
+ popular_questions = Question.get_popular()
69
+
70
+ page = self.paginate_queryset(popular_questions)
71
+ if page is not None:
72
+ serializer = self.get_serializer(page, many=True)
73
+ return self.get_paginated_response(serializer.data)
74
+
75
+ serializer = self.get_serializer(popular_questions, many=True)
76
+ return Response(serializer.data)
77
+
78
+ @list_route(methods=['get'])
79
+ def latest(self, request):
80
+ latest_questions = Question.get_latest()
81
+
82
+ page = self.paginate_queryset(latest_questions)
83
+ if page is not None:
84
+ serializer = self.get_serializer(page, many=True)
85
+ return self.get_paginated_response(serializer.data)
86
+
87
+ serializer = self.get_serializer(latest_questions, many=True)
88
+ return Response(serializer.data)
89
+
90
+ @detail_route(methods=['get'])
91
+ def answers(self, request, pk=None):
92
+ question = self.get_object()
93
+ answers = question.answers.all().order_by('votes')
94
+ page = self.paginate_queryset(answers)
95
+ if page is not None:
96
+ serializer = serializers.AnswerSerializer(page, many=True, context={'request': request})
97
+ return self.get_paginated_response(serializer.data)
98
+
99
+ serializer = serializers.AnswerSerializer(answers, many=True, context={'request': request})
100
+ return Response(serializer.data)
101
+
102
+
103
+ class TagViewSet(ModelViewSet):
104
+ queryset = Tag.objects.all()
105
+ lookup_field = 'tag'
106
+ serializer_class = serializers.TagSerializer
107
+ permission_classes = [CreateAndViewPermission]
108
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
109
+ filter_fields = ['tag']
110
+
111
+ @list_route(methods=['get'])
112
+ def trending(self, request):
113
+ trending_tags = Tag.get_trending()
114
+
115
+ page = self.paginate_queryset(trending_tags)
116
+ if page is not None:
117
+ serializer = self.get_serializer(page, many=True)
118
+ return self.get_paginated_response(serializer.data)
119
+
120
+ serializer = self.get_serializer(trending_tags, many=True)
121
+ return Response(serializer.data)
122
+
123
+ @detail_route(methods=['get'])
124
+ def questions(self, request, tag=None):
125
+ tag = self.get_object()
126
+ questions = tag.questions.all()
127
+ page = self.paginate_queryset(questions)
128
+ if page is not None:
129
+ serializer = serializers.QuestionSerializer(page, many=True, context={'request': request})
130
+ return self.get_paginated_response(serializer.data)
131
+
132
+ serializer = serializers.QuestionSerializer(questions, many=True, context={'request': request})
133
+ return Response(serializer.data)
134
+
135
+
136
+ class AnswerViewSet(ModelViewSet):
137
+ queryset = Answer.objects.all().order_by('votes')
138
+ permission_classes = [UserPermission]
139
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
140
+ filter_fields = ['question__title', 'author__first_name', 'author__last_name', 'content', 'votes']
141
+
142
+ def get_serializer_class(self):
143
+ if self.action == 'create':
144
+ return serializers.CreateAnswerSerializer
145
+ if self.action == 'update':
146
+ return serializers.UpdateAnswerSerializer
147
+ return serializers.AnswerSerializer
148
+
149
+ @detail_route(methods=['post'])
150
+ def upvote(self, request, pk=None):
151
+ answer = self.get_object()
152
+ request.user.vote_for_answer(answer, Vote.UP)
153
+ serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, answer=answer))
154
+ return Response(serializer.data)
155
+
156
+ @detail_route(methods=['post'])
157
+ def downvote(self, request, pk=None):
158
+ answer = self.get_object()
159
+ request.user.vote_for_answer(answer, Vote.DOWN)
160
+ serializer = serializers.VoteSerializer(Vote.objects.get(voted_by=request.user, answer=answer))
161
+ return Response(serializer.data)
162
+
163
+ @detail_route(methods=['get'])
164
+ def vote(self, request, pk=None, vote=None):
165
+ answer = self.get_object()
166
+ try:
167
+ Vote.objects.get(voted_by=request.user, answer=answer)
168
+ obj = Vote.objects.get(voted_by=request.user, answer=answer)
169
+ return Response({
170
+ 'status': True,
171
+ 'answer_id': answer.id,
172
+ 'message': '{} has {}voted answer with id {}'.format(request.user, obj.vote, answer.id),
173
+ 'vote': obj.vote,
174
+ 'total_votes': answer.votes
175
+ })
176
+ except Vote.DoesNotExist:
177
+ return Response({
178
+ 'status': False,
179
+ 'answer_id': answer.id,
180
+ 'message': '{} has not voted for answer with id {}'.format(request.user, answer.id),
181
+ 'vote': None,
182
+ 'total_votes': answer.votes
183
+ })
184
+
185
+ @detail_route(methods=['get'])
186
+ def comments(self, request, pk=None):
187
+ answer = self.get_object()
188
+ comments = answer.comments.all()
189
+ page = self.paginate_queryset(comments)
190
+ if page is not None:
191
+ serializer = serializers.CommentSerializer(page, many=True, context={'request': request})
192
+ return self.get_paginated_response(serializer.data)
193
+
194
+ serializer = serializers.CommentSerializer(comments, many=True, context={'request': request})
195
+ return Response(serializer.data)
196
+
197
+
198
+ class CommentViewSet(ModelViewSet):
199
+ queryset = Comment.objects.all()
200
+ permission_classes = [UserPermission]
201
+ filter_backends = [DjangoFilterBackend, OrderingFilter]
202
+ filter_fields = ['content', 'author__first_name', 'author__last_name']
203
+
204
+ def get_serializer_class(self):
205
+ if self.action == 'create':
206
+ return serializers.CreateCommentSerializer
207
+ if self.action == 'update':
208
+ return serializers.UpdateCommentSerializer
209
+ return serializers.CommentSerializer
pool/shard008/Python/0075225_gen-insertfile.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # coding: utf-8
3
+
4
+ import sys, os.path, hashlib
5
+ from random import randint
6
+
7
+ reload(sys)
8
+ sys.setdefaultencoding( "utf-8" )
9
+
10
+ if len(sys.argv) != 2:
11
+ print "Az első paraméterben megadott névvel létrehozott fájlba írja az SQL INSERT-eket."
12
+ sys.exit()
13
+
14
+ outfile = sys.argv[1]
15
+ if os.path.isfile(outfile):
16
+ print "Már létezik a fájl, nem merek bele írni: %s" % outfile
17
+ sys.exit()
18
+
19
+ # A vezetékneveket beolvassuk az aVnev tömbbe
20
+ aVnev = open('csaladnev.txt').read().strip().split('\n')
21
+ nVnev = len(aVnev)
22
+
23
+ # A keresztneveket az aKnev-be
24
+ aKnev = []
25
+ for nap in open('keresztnev.txt').readlines():
26
+ try: aKnev += nap.strip().split(': ')[1].split()
27
+ except: pass
28
+ nKnev = len(aKnev)
29
+
30
+ # Az azonosítók kezdőértékei
31
+ nTanar, nDiak = 10, 10000
32
+
33
+ def sha(pw):
34
+ return hashlib.sha256(pw.encode('utf-8')).hexdigest()
35
+
36
+ tJelszo = sha('t');
37
+ dJelszo = sha('d');
38
+
39
+ nev = lambda: aVnev[randint(0, nVnev-1)] + ' ' + aKnev[randint(0, nKnev-1)]
40
+
41
+ osztalyok = open('OSZTALY').read().replace('\n', ';').split(';') # 'd10a;7. A;....'
42
+ # Minden második osztályazonosító
43
+ OSZTALY = dict( [ (osztalyok[i], osztalyok[i+1]) for i in range(0, len(osztalyok)-1, 2) ] )
44
+
45
+ tanarOUT = []
46
+ osztalyOUT = ['']
47
+ diakOUT = ['']
48
+
49
+ tFormat = "INSERT INTO Tanar (id, jelszo, tnev) VALUES (%d, '%s', '%s');"
50
+ for oid, onev in OSZTALY.items():
51
+ tanarOUT.append(tFormat % (nTanar, tJelszo, nev()))
52
+ osztalyOUT.append("INSERT INTO Osztaly (oszt, onev, ofo) VALUES ('%s', '%s', %d);" % (oid, onev, nTanar))
53
+
54
+ # minden osztályhoz felveszünk néhány diákot
55
+ for i in range(randint(25, 35)):
56
+ diakOUT.append("INSERT INTO Diak_base (id, jelszo, dnev, oszt) VALUES (%d, '%s', '%s', '%s');" % (nDiak, dJelszo, nev(), oid))
57
+ nDiak += 1
58
+ nTanar += 1
59
+
60
+ # még néhány tanárt hozzáadunk (eddig az osztályfőnökök vannak)
61
+ for i in range(randint(25, 35)):
62
+ tanarOUT.append(tFormat % (nTanar, tJelszo, nev()))
63
+ nTanar += 1
64
+
65
+ OUT = tanarOUT + osztalyOUT + diakOUT
66
+ open(outfile, 'w').write('\n'.join(OUT))
67
+
pool/shard008/Python/0075228_views.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from functools import wraps
4
+
5
+ from flask import Flask, jsonify, render_template, request, abort
6
+
7
+ from geophoto import app, models, oembed
8
+
9
+ basedir = os.path.dirname(os.path.abspath(__file__))
10
+ index_path = os.path.join(basedir,'static','index.html')
11
+
12
+ def spa(vfunc):
13
+ @wraps(vfunc)
14
+ def wrapper(*args, **kwargs):
15
+ if request.args.get('format') == 'json':
16
+ return vfunc(*args, **kwargs)
17
+ else:
18
+ return render_template('index.html')
19
+ return wrapper
20
+
21
+ @app.route("/")
22
+ def index():
23
+ return render_template('index.html')
24
+
25
+ @app.route("/photos")
26
+ @spa
27
+ def photos():
28
+ return jsonify(models.photos())
29
+
30
+ @app.route("/articles")
31
+ @spa
32
+ def articles():
33
+ return jsonify(models.articles())
34
+
35
+ @app.route("/articles/<key>")
36
+ @spa
37
+ def article(key):
38
+ return jsonify(models.article(key))
39
+
40
+ @app.route("/tags/<id>", methods=["GET",])
41
+ @spa
42
+ def tags(id):
43
+ return jsonify(models.tags(id))
44
+
45
+ @app.route("/services/oembed/", methods=["GET",])
46
+ def oembed_service():
47
+ fmt = request.args.get("format")
48
+ if fmt is None or fmt == 'json':
49
+ return jsonify(oembed.oembed(request.args.get('url')))
50
+ elif fmt == 'html':
51
+ return oembed.oembed(request.args.get('url'))
52
+ abort(500)
53
+
54
+ @app.route("/tags/<id>", methods=["POST",])
55
+ @spa
56
+ def add_tags(id):
57
+ try:
58
+ return jsonify(models.add_tags(id, request.get_json()))
59
+ except ValueError:
60
+ abort(409)
pool/shard008/Python/0075231_express_route_service_providers_operations.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # --------------------------------------------------------------------------
3
+ # Copyright (c) Microsoft Corporation. All rights reserved.
4
+ # Licensed under the MIT License. See License.txt in the project root for
5
+ # license information.
6
+ #
7
+ # Code generated by Microsoft (R) AutoRest Code Generator.
8
+ # Changes may cause incorrect behavior and will be lost if the code is
9
+ # regenerated.
10
+ # --------------------------------------------------------------------------
11
+
12
+ import uuid
13
+ from msrest.pipeline import ClientRawResponse
14
+ from msrestazure.azure_exceptions import CloudError
15
+
16
+ from .. import models
17
+
18
+
19
+ class ExpressRouteServiceProvidersOperations(object):
20
+ """ExpressRouteServiceProvidersOperations operations.
21
+
22
+ :param client: Client for service requests.
23
+ :param config: Configuration of service client.
24
+ :param serializer: An object model serializer.
25
+ :param deserializer: An objec model deserializer.
26
+ :ivar api_version: Client API version. Constant value: "2017-08-01".
27
+ """
28
+
29
+ models = models
30
+
31
+ def __init__(self, client, config, serializer, deserializer):
32
+
33
+ self._client = client
34
+ self._serialize = serializer
35
+ self._deserialize = deserializer
36
+ self.api_version = "2017-08-01"
37
+
38
+ self.config = config
39
+
40
+ def list(
41
+ self, custom_headers=None, raw=False, **operation_config):
42
+ """Gets all the available express route service providers.
43
+
44
+ :param dict custom_headers: headers that will be added to the request
45
+ :param bool raw: returns the direct response alongside the
46
+ deserialized response
47
+ :param operation_config: :ref:`Operation configuration
48
+ overrides<msrest:optionsforoperations>`.
49
+ :return: An iterator like instance of ExpressRouteServiceProvider
50
+ :rtype:
51
+ ~azure.mgmt.network.v2017_08_01.models.ExpressRouteServiceProviderPaged[~azure.mgmt.network.v2017_08_01.models.ExpressRouteServiceProvider]
52
+ :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
53
+ """
54
+ def internal_paging(next_link=None, raw=False):
55
+
56
+ if not next_link:
57
+ # Construct URL
58
+ url = '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders'
59
+ path_format_arguments = {
60
+ 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
61
+ }
62
+ url = self._client.format_url(url, **path_format_arguments)
63
+
64
+ # Construct parameters
65
+ query_parameters = {}
66
+ query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
67
+
68
+ else:
69
+ url = next_link
70
+ query_parameters = {}
71
+
72
+ # Construct headers
73
+ header_parameters = {}
74
+ header_parameters['Content-Type'] = 'application/json; charset=utf-8'
75
+ if self.config.generate_client_request_id:
76
+ header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
77
+ if custom_headers:
78
+ header_parameters.update(custom_headers)
79
+ if self.config.accept_language is not None:
80
+ header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
81
+
82
+ # Construct and send request
83
+ request = self._client.get(url, query_parameters)
84
+ response = self._client.send(
85
+ request, header_parameters, stream=False, **operation_config)
86
+
87
+ if response.status_code not in [200]:
88
+ exp = CloudError(response)
89
+ exp.request_id = response.headers.get('x-ms-request-id')
90
+ raise exp
91
+
92
+ return response
93
+
94
+ # Deserialize response
95
+ deserialized = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies)
96
+
97
+ if raw:
98
+ header_dict = {}
99
+ client_raw_response = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies, header_dict)
100
+ return client_raw_response
101
+
102
+ return deserialized
pool/shard008/Python/0075233_swipe_theta.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os, pickle, random, time
4
+ try:
5
+ os.remove('my_gp_module.pyc')
6
+ except OSError:
7
+ pass
8
+ import scipy as sp
9
+ from scipy.linalg import norm, eigh, inv, pinv, pinv2, pinvh
10
+ from my_gp_module import GaussianProcess
11
+
12
+ # --------------------------------------------
13
+ # Load all database
14
+ # --------------------------------------------
15
+ ttt = time.clock()
16
+ if not os.path.exists('qm7.pkl'): os.system('wget http://www.quantum-machine.org/data/qm7.pkl')
17
+ dataset = pickle.load(open('qm7.pkl','r'))
18
+
19
+ # --------------------------------------------
20
+ # Extract training data and test set
21
+ # --------------------------------------------
22
+ split = 1
23
+ N_models = 1
24
+
25
+ # P = dataset['P'][range(0,split)+range(split+1,5)].flatten()
26
+ P = dataset['P'][split + 1]
27
+ X = dataset['X'][P]
28
+ T = dataset['T'][P]
29
+ Ptest = dataset['P'][split]
30
+ Xtest = dataset['X'][Ptest]
31
+ Ttest = dataset['T'][Ptest]
32
+ print "TIMER load_data", time.clock() - ttt
33
+
34
+ # --------------------------------------------
35
+ # Extract feature(s) from training data and test set
36
+ # --------------------------------------------
37
+ # in this case, only sorted eigenvalues of Coulomb matrix
38
+ ttt = time.clock()
39
+ eigX = [(eigh(M, eigvals_only=True))[::-1] for M in X]
40
+ eigt = [(eigh(M, eigvals_only=True))[::-1] for M in Xtest]
41
+ print "TIMER eval_features", time.clock() - ttt
42
+
43
+ # Observations
44
+ y = T.ravel()
45
+
46
+ alpha = []
47
+ covmat = []
48
+ for theta0 in [10.0**i for i in sp.linspace(-2,5,7)]: # sp.linspace(1,1, N_models):
49
+ # Setup a Gaussian Process model
50
+ ttt = time.clock()
51
+ gp = GaussianProcess(corr='absolute_exponential', theta0=sp.asarray([theta0]),
52
+ nugget=1e-3, verbose=True, low_memory=False)
53
+
54
+ # Fit to data using Maximum Likelihood Estimation of the parameters
55
+ gp.fit(eigX, y)
56
+ print "TIMER teach", time.clock() - ttt
57
+
58
+ ttt = time.clock()
59
+ # # Make the prediction on training set
60
+ # y_pred, MSE = gp.predict(eigX, eval_MSE=True)
61
+ # sigma = sp.sqrt(MSE)
62
+ # print('\n training set:')
63
+ # print('MAE: %5.2f kcal/mol' % sp.absolute(y_pred-y).mean(axis=0))
64
+ # print('RMSE: %5.2f kcal/mol' % sp.square(y_pred-y).mean(axis=0)**.5)
65
+ # Make the prediction on test set
66
+ y_pred, MSE = gp.predict(eigt, eval_MSE=True)
67
+ sigma = sp.sqrt(MSE)
68
+ print('\n test set:')
69
+ print('MAE: %5.2f kcal/mol' % sp.absolute(y_pred-Ttest.ravel()).mean(axis=0))
70
+ print('RMSE: %5.2f kcal/mol' %sp.square(y_pred-Ttest.ravel()).mean(axis=0)**.5)
71
+ print "TIMER predict", time.clock() - ttt
72
+ alpha.append(gp.alpha)
73
+ covmat.append(gp.K)
74
+
75
+ print r"\alpha STD: %f" % (sp.std(gp.alpha) / sp.mean(sp.absolute(gp.alpha)))
76
+
77
+ print "\n", "-"*60, "\n"
78
+
79
+ # P = dataset['P'][range(0,split)+range(split+1,5)].flatten()
80
+ # X = dataset['X'][P]
81
+ # T = dataset['T'][P]
82
+ # print "TIMER load_data", time.clock() - ttt
83
+
84
+ # # --------------------------------------------
85
+ # # Extract feature(s) from training data
86
+ # # --------------------------------------------
87
+ # # in this case, only sorted eigenvalues of Coulomb matrix
88
+ # ttt = time.clock()
89
+ # eigX = [(eigh(M, eigvals_only=True))[::-1] for M in X]
90
+ # print "TIMER eval_features", time.clock() -ttt
91
+ # # --------------------------------------------
92
+ # # Generate distance matrix (currently it's only one for all)
93
+ # # --------------------------------------------
94
+ # ttt = time.clock()
95
+ # D = sp.zeros((len(eigX), len(eigX)))
96
+ # for i, v1 in enumerate(eigX):
97
+ # for j, v2 in enumerate(eigX[i:]):
98
+ # if i == j: D[i,j] = 0.0
99
+ # else:
100
+ # D[i,j] = norm(v1 - v2)
101
+ # D[j,i] = D[i,j]
102
+ # print "TIMER distance_matrix", time.clock() -ttt
103
+ # # --------------------------------------------
104
+ # # Generate multiple kernel matrices
105
+ # # --------------------------------------------
106
+ # list_k_I = []
107
+ # list_alphas_I = []
108
+ # for l in sp.linspace(0.01, 1,1):
109
+ # for reg_param in sp.linspace(0.01, 0.1,1):
110
+ # print "STATUS:", l, reg_param
111
+ # k_I = sp.exp(-D/l)
112
+ # list_k_I.append(k_I)
113
+ # # --------------------------------------------
114
+ # # Calculate regression coefficients
115
+ # # --------------------------------------------
116
+ # ttt = time.clock()
117
+ # inv_mat = inv(k_I + reg_param * sp.eye(len(eigX)))
118
+ # print "TIMER matrix_inversion", time.clock() -ttt
119
+ # alphas = sp.dot(inv_mat, T)
120
+ # list_alphas_I.append(alphas)
121
+ # sp.save("alphas_%.3f_%.3f.npy" % (l, reg_param), alphas)
122
+ # # --------------------------------------------
123
+ # # Predict something already known
124
+ # # --------------------------------------------
125
+ # print "TEST length scale: %.3f, regularisation parameter: %.3f" % (l, reg_param)
126
+ # for counter in range(5):
127
+ # idx = random.randint(0, len(eigX) - 1)
128
+ # eigt = eigX[idx]
129
+ # kt = [kernel(v1, eigt, l) for v1 in eigX]
130
+ # print "PREDICTION: %.3f, TARGET: %.3f" % (sp.dot(kt, alphas), T[idx])
pool/shard008/Python/0075236_test_api_email_localization.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Unit tests for the localization of emails sent by instructor.api methods.
4
+ """
5
+
6
+ from django.core import mail
7
+ from django.urls import reverse
8
+ from django.test.utils import override_settings
9
+ from nose.plugins.attrib import attr
10
+ from six import text_type
11
+
12
+ from courseware.tests.factories import InstructorFactory
13
+ from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
14
+ from openedx.core.djangoapps.user_api.preferences.api import delete_user_preference, set_user_preference
15
+ from student.models import CourseEnrollment
16
+ from student.tests.factories import UserFactory
17
+ from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
18
+ from xmodule.modulestore.tests.factories import CourseFactory
19
+
20
+
21
+ @attr(shard=1)
22
+ class TestInstructorAPIEnrollmentEmailLocalization(SharedModuleStoreTestCase):
23
+ """
24
+ Test whether the enroll, unenroll and beta role emails are sent in the
25
+ proper language, i.e: the student's language.
26
+ """
27
+ @classmethod
28
+ def setUpClass(cls):
29
+ super(TestInstructorAPIEnrollmentEmailLocalization, cls).setUpClass()
30
+ cls.course = CourseFactory.create()
31
+
32
+ def setUp(self):
33
+ super(TestInstructorAPIEnrollmentEmailLocalization, self).setUp()
34
+
35
+ # Platform language is English, instructor's language is Chinese,
36
+ # student's language is Esperanto, so the emails should all be sent in
37
+ # Esperanto.
38
+ self.instructor = InstructorFactory(course_key=self.course.id)
39
+ set_user_preference(self.instructor, LANGUAGE_KEY, 'zh-cn')
40
+ self.client.login(username=self.instructor.username, password='test')
41
+
42
+ self.student = UserFactory.create()
43
+ set_user_preference(self.student, LANGUAGE_KEY, 'eo')
44
+
45
+ def update_enrollement(self, action, student_email):
46
+ """
47
+ Update the current student enrollment status.
48
+ """
49
+ url = reverse('students_update_enrollment', kwargs={'course_id': text_type(self.course.id)})
50
+ args = {'identifiers': student_email, 'email_students': 'true', 'action': action, 'reason': 'testing'}
51
+ response = self.client.post(url, args)
52
+ return response
53
+
54
+ def check_outbox_is_esperanto(self):
55
+ """
56
+ Check that the email outbox contains exactly one message for which both
57
+ the message subject and body contain a certain Esperanto string.
58
+ """
59
+ return self.check_outbox(u"Ýöü hävé ßéén")
60
+
61
+ def check_outbox(self, expected_message):
62
+ """
63
+ Check that the email outbox contains exactly one message for which both
64
+ the message subject and body contain a certain string.
65
+ """
66
+ self.assertEqual(1, len(mail.outbox))
67
+ self.assertIn(expected_message, mail.outbox[0].subject)
68
+ self.assertIn(expected_message, mail.outbox[0].body)
69
+
70
+ def test_enroll(self):
71
+ self.update_enrollement("enroll", self.student.email)
72
+
73
+ self.check_outbox_is_esperanto()
74
+
75
+ def test_unenroll(self):
76
+ CourseEnrollment.enroll(
77
+ self.student,
78
+ self.course.id
79
+ )
80
+ self.update_enrollement("unenroll", self.student.email)
81
+
82
+ self.check_outbox_is_esperanto()
83
+
84
+ def test_set_beta_role(self):
85
+ url = reverse('bulk_beta_modify_access', kwargs={'course_id': text_type(self.course.id)})
86
+ self.client.post(url, {'identifiers': self.student.email, 'action': 'add', 'email_students': 'true'})
87
+
88
+ self.check_outbox_is_esperanto()
89
+
90
+ def test_enroll_unsubscribed_student(self):
91
+ # Student is unknown, so the platform language should be used
92
+ self.update_enrollement("enroll", "newuser@hotmail.com")
93
+ self.check_outbox("You have been")
94
+
95
+ @override_settings(LANGUAGE_CODE="eo")
96
+ def test_user_without_preference_receives_email_in_esperanto(self):
97
+ delete_user_preference(self.student, LANGUAGE_KEY)
98
+ self.update_enrollement("enroll", self.student.email)
99
+
100
+ self.check_outbox_is_esperanto()
pool/shard008/Python/0075241_classify.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Classifies image arguments as either cat or not
2
+
3
+ """
4
+
5
+ import json
6
+ import sys
7
+ import os
8
+
9
+ from skimage import io
10
+ from skimage import transform
11
+
12
+ from model import setup_model
13
+
14
+ # TODO: handle argument parsing in a sane manner
15
+
16
+ SIZE = (32, 32)
17
+ MODEL_FILE = "cat-classifier.tfl"
18
+
19
+ model = setup_model()
20
+
21
+ model.load(MODEL_FILE)
22
+
23
+ filenames = sys.argv[1:]
24
+
25
+ for filename in filenames:
26
+ filepath = os.path.abspath(filename)
27
+ try:
28
+ im = io.imread(filepath)
29
+ im = transform.resize(im, SIZE)
30
+ except ValueError:
31
+ print("Unable to load: {:s}".format(filepath), file=sys.stderr)
32
+ result = model.predict([im])
33
+ print(json.dumps({
34
+ "filepath": filepath,
35
+ "not_cat_score": result[0][0],
36
+ "cat_score": result[0][1]
37
+ }))
pool/shard008/Python/0075243_create_tokens.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optparse import make_option
2
+ import os.path
3
+ import requests
4
+ import json
5
+
6
+ from django.contrib.auth.models import User
7
+ from django.core.management import BaseCommand, CommandError
8
+ from rest_framework.authtoken.models import Token
9
+ from users.models import UserProfile
10
+ from orgs.models import Organization
11
+
12
+ class Command(BaseCommand):
13
+ help = 'Create initial user data for new installation, output the tokens required for the web.'
14
+ option_list = BaseCommand.option_list + (
15
+ make_option('--password',
16
+ action='store',
17
+ dest='pwd',
18
+ default=None,
19
+ help='Password for root user.'),
20
+ make_option('--test',
21
+ action='store_true',
22
+ dest='test_mode',
23
+ default=False,
24
+ help='Test mode. Do not update database.'),
25
+ make_option('--create',
26
+ action='store_true',
27
+ dest='create_mode',
28
+ default=False,
29
+ help='Create root user.'),
30
+ make_option('--token',
31
+ action='store',
32
+ dest='token',
33
+ default=None,
34
+ help='Set root user token.')
35
+ )
36
+
37
+ def print_users(self):
38
+ print 'Django users...'
39
+ for n,u in enumerate(User.objects.all(), start=1):
40
+ print 'Django User %d -----' % n
41
+ print 'user id:', u.id
42
+ print 'user name:', u.username
43
+ print 'is staff:', u.is_staff
44
+ print 'is superuser:', u.is_superuser
45
+
46
+
47
+ print 'API users...'
48
+ for n, u in enumerate(UserProfile.objects.all(), start=1):
49
+ print 'API User %d -----' % n
50
+ print 'user id:', u.id
51
+ print 'mnemonic:', u.mnemonic
52
+ print 'name:', u.name
53
+
54
+
55
+ def print_tokens(self):
56
+ """ Just print out the tokens, in a form that easily put
57
+ in a shell script.
58
+ """
59
+
60
+ for t in Token.objects.all():
61
+ res = User.objects.filter(id=t.user_id)
62
+ if len(res) == 1:
63
+ un = res[0].username
64
+ else:
65
+ un = 'n/a'
66
+ if un == 'admin':
67
+ print "export OCL_API_TOKEN='%s'" % t.key
68
+ if un == 'anonymous':
69
+ print "export OCL_ANON_API_TOKEN='%s'" % t.key
70
+
71
+
72
+ def handle(self, *args, **options):
73
+
74
+ create_mode = options['create_mode']
75
+ pwd = options['pwd']
76
+ token = options['token']
77
+
78
+ if create_mode:
79
+ if pwd is None:
80
+ raise CommandError('--password is required.')
81
+
82
+ superusers = User.objects.filter(username='root')
83
+
84
+ if not superusers:
85
+ UserProfile.objects.create(
86
+ user=User.objects.create_superuser('root', 'root@openconceptlab.org', password=pwd),
87
+ organizations=map(lambda o: o.id, Organization.objects.filter(created_by='root')),
88
+ mnemonic='root')
89
+ superusers = User.objects.filter(username='root')
90
+
91
+ superuser = superusers[0]
92
+
93
+ superuser.set_password(pwd)
94
+ superuser.save()
95
+
96
+ if token:
97
+ Token.objects.filter(user=superuser).delete()
98
+ Token.objects.create(user=superuser, key=token)
99
+
100
+ else:
101
+ self.print_tokens()
102
+
pool/shard008/Python/0075246_spider.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This file will crawl ComLaw and download the name and ComLawID of all legislation
3
+ # Starting in 2015 and working backwards to 1901
4
+ #
5
+ # For example - use like:
6
+ # python -u spider.py > legislation.txt
7
+ #
8
+ # You don't actually need to run this - I have included both the current legislative instruments
9
+ # and asmade in the repo:
10
+ # acts_current.txt
11
+ # acts_asmade.txt
12
+
13
+
14
+
15
+ import mechanize
16
+ import time
17
+
18
+
19
+ # AspNET *SIGH*
20
+ FORM_NAME = 'aspnetForm'
21
+
22
+ #Current Acts only...
23
+ BASE_CURRENT = 'https://www.comlaw.gov.au/Browse/Results/ByYearNumber/Acts/Current/{}/0'
24
+
25
+ #As made
26
+ BASE_ASMADE = 'https://www.comlaw.gov.au/Browse/Results/ByYearNumber/Acts/Asmade/{}/0'
27
+
28
+
29
+
30
+ class ComlawYear(object):
31
+
32
+ def __init__(self, year, BASE=BASE_CURRENT):
33
+ self.y = year
34
+ self.br = mechanize.Browser()
35
+ self.br.open(BASE.format(self.y))
36
+
37
+ print 'Opened first page of year {}'.format(year)
38
+ self.pages = 1
39
+
40
+ def get_page(self):
41
+
42
+
43
+ links = []
44
+
45
+ for l in self.br.links():
46
+ #Only get the links to legislation "LegBookmarks"
47
+ if ('class', 'LegBookmark') in l.attrs:
48
+
49
+ #Save the name of the legislation and its ComlawID
50
+ links.append((
51
+ l.text,
52
+ l.url.split('/')[-1]
53
+ ))
54
+
55
+ return links
56
+
57
+
58
+ def next_page(self):
59
+
60
+ # control = self.br.form.find_control(NEXT_PG_CONTROL)
61
+ self.br.select_form(FORM_NAME)
62
+
63
+ for c in self.br.form.controls:
64
+ if 'class' in c.attrs and c.attrs['class'] == 'rgPageNext':
65
+
66
+ #We've come to the end of the pages...
67
+ if 'onclick' in c.attrs and c.attrs['onclick'].startswith('return'):
68
+ return False
69
+ self.br.submit(c.name)
70
+ self.pages += 1
71
+ return True
72
+
73
+ return False
74
+
75
+ def get_all(self):
76
+
77
+ while True:
78
+
79
+ for l in self.get_page():
80
+ yield l
81
+
82
+ #be nice to the web server!
83
+ time.sleep(2)
84
+
85
+ if self.next_page() is False:
86
+ print 'Year {} had {} pages'.format(self.y, self.pages)
87
+ return
88
+
89
+
90
+
91
+ #Don't need to use this - checkout acts_asmade.txt and acts_current.txt in the repo!
92
+ if False:
93
+ year = 2015
94
+
95
+ while True:
96
+
97
+ y = ComlawYear(year)
98
+ for l in y.get_all():
99
+ print l
100
+ year -= 1
101
+
102
+ if year < 1901:
103
+ break
104
+
105
+ print 'Done'
106
+
107
+
pool/shard008/Python/0075250_avionics.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import logging
3
+ import sys
4
+ import time
5
+ import traceback
6
+ from tkinter import Listbox, LEFT, BOTH, Label, \
7
+ StringVar, NW, BooleanVar, DISABLED, NORMAL, X, NE
8
+
9
+ import krpc
10
+ from ttk import Checkbutton, Entry
11
+
12
+ from krcc_module import KRCCModule
13
+
14
+
15
+ # DECLARE_KRCC_MODULE
16
+ def load(root):
17
+ return AvionicsLogger(root)
18
+
19
+
20
+ class AvionicsLogger(KRCCModule):
21
+ def __init__(self, root):
22
+ super().__init__()
23
+ self.root = root
24
+ self.exception = None
25
+
26
+ self.list_string = StringVar()
27
+ self.listbox = Listbox(root, listvariable=self.list_string,
28
+ font='TkFixedFont', width=30)
29
+
30
+ self.write_cache = ''
31
+ self.logfile = None
32
+ self.enable_logging = BooleanVar()
33
+ self.enable_logging_checkbox = Checkbutton(
34
+ root, var=self.enable_logging, text='Enable logging',
35
+ command=self.enable_logging_changed)
36
+
37
+ self.logfile_label = Label(root, text='Logfile name:')
38
+ self.logfile_name = StringVar()
39
+ self.logfile_name_entry = Entry(root, textvar=self.logfile_name)
40
+
41
+ self.load()
42
+
43
+ def write(self, string):
44
+ if self.enable_logging.get() and self.logfile is None:
45
+ if self.logfile_name.get() == '':
46
+ self.logfile_name.set('logs/{}.log'.format(time.time()))
47
+ self.logfile = io.open(self.logfile_name.get(), 'a')
48
+ self.logfile.write(self.write_cache)
49
+ self.write_cache = ''
50
+ self.logfile.write(string)
51
+
52
+ def cache(self, string):
53
+ self.write_cache += string
54
+
55
+ def enable_logging_changed(self):
56
+ if not self.enable_logging.get():
57
+ self.logfile_name_entry.configure(state=NORMAL)
58
+ if self.logfile is not None:
59
+ self.logfile.close()
60
+ self.logfile = None
61
+ self.logfile_name.set('')
62
+ else:
63
+ self.logfile_name_entry.configure(state=DISABLED)
64
+
65
+ def establish_connection_and_run(self):
66
+ error = None
67
+ dots = 0
68
+ connection = None
69
+ while not self.terminate:
70
+ try:
71
+ if connection is None:
72
+ connection = krpc.connect(name=self.name)
73
+ self.run_with_connection(connection)
74
+ error = None
75
+ dots = 0
76
+ except Exception as e:
77
+ if error != e.args[0]:
78
+ error = e.args[0]
79
+ print('\n')
80
+ print(traceback.format_exc())
81
+ sys.stdout.write('Retrying')
82
+ if dots > 80:
83
+ dots = 0
84
+ sys.stdout.write('\n')
85
+ sys.stdout.write('.')
86
+ dots += 1
87
+ sys.stdout.flush()
88
+ time.sleep(1)
89
+ if connection is not None:
90
+ connection.close()
91
+
92
+ def run_with_connection(self, connection):
93
+ logging.debug('KRPC connection established')
94
+ vessel = connection.space_center.active_vessel
95
+ ref = vessel.orbit.body.reference_frame
96
+ flight = connection.add_stream(vessel.flight, ref)
97
+ floats = [
98
+ 'mean_altitude',
99
+ 'atmosphere_density',
100
+ 'ballistic_coefficient',
101
+ 'drag_coefficient',
102
+ ]
103
+ vectors = [
104
+ 'velocity',
105
+ ]
106
+ colon_pos_float = max([len(v) for v in floats])
107
+ colon_pos_vec = max([len(v) + 3 for v in vectors])
108
+ self.listbox.configure(width=max(colon_pos_float, colon_pos_vec) + 11)
109
+
110
+ # Write the log file header.
111
+ self.cache('time\t' + '\t'.join(floats) + '\t')
112
+ s = '{}\t' + '\t'.join('{{}}[{}]'.format(x) for x in [0, 1, 2])
113
+ self.cache('\t'.join(s.format(*(v for _ in [0, 1, 2, 3])) for v in vectors))
114
+ self.cache('\n')
115
+ log_sample_interval = 0.01
116
+ next_log_sample = time.time()
117
+ while not self.terminate:
118
+ values = [time.time()]
119
+ strings = []
120
+ for name in floats:
121
+ value = flight().__getattribute__(name)
122
+ values.append(value)
123
+ padding = colon_pos_float - len(name) + 9
124
+ format_string = '{{}}: {{:>{}.3f}}'.format(padding)
125
+ strings.append(format_string.format(name, value))
126
+ for name in vectors:
127
+ value = flight().__getattribute__(name)
128
+ magnitude = value[0]
129
+ padding = colon_pos_float - len(name) + 9
130
+ format_string = '{{}}: {{:>{}.3f}}'.format(padding)
131
+ strings.append(format_string.format(name, magnitude))
132
+ values.append(magnitude)
133
+ padding = colon_pos_vec - len(name) + 2
134
+ format_string = '{{}}[{{}}]: {{:>{}.3f}}'.format(padding)
135
+ for i in [0, 1, 2]:
136
+ values.append(value[i])
137
+ strings.append(format_string.format(name, i, value[i]))
138
+ if self.enable_logging.get() and time.time() > next_log_sample:
139
+ self.write('\t'.join(['{}'.format(v) for v in values]) + '\n')
140
+ next_log_sample = time.time() + log_sample_interval
141
+ self.list_string.set(tuple(strings))
142
+
143
+ def run(self):
144
+ try:
145
+ self.establish_connection_and_run()
146
+ self.logfile_name_entry.destroy()
147
+ self.logfile_label.destroy()
148
+ self.enable_logging_checkbox.destroy()
149
+ self.listbox.destroy()
150
+ except RuntimeError:
151
+ # Should only happen when KeyboardInterrupt is thrown in the MainThread.
152
+ pass
153
+ if self.logfile is not None:
154
+ self.logfile.close()
155
+
156
+ @property
157
+ def name(self):
158
+ return 'Avionics Logger'
159
+
160
+ def load(self):
161
+ self.listbox.pack(side=LEFT, fill=BOTH)
162
+ self.logfile_label.pack(side=LEFT, anchor=NW)
163
+ self.logfile_name_entry.pack(side=LEFT, anchor=NE, fill=X, expand=True)
164
+ self.enable_logging_checkbox.pack(side=LEFT, anchor=NW)
pool/shard008/Python/0075254_database.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from sqlite3 import connect, PARSE_DECLTYPES, Row, IntegrityError
4
+ from fcsite import app
5
+
6
+
7
+ def connect_db():
8
+ uri = app.config['DATABASE_URI']
9
+ db = connect(uri, detect_types=PARSE_DECLTYPES)
10
+ db.row_factory = Row
11
+ db.execute('PRAGMA foreign_keys = ON')
12
+ return db
13
+
14
+
15
+ def initialize():
16
+ db = connect_db()
17
+ with db:
18
+ __force_insert(db, """
19
+ INSERT INTO User (id, name, password, sex)
20
+ VALUES (-1, '---', '!@#$%^&*()', 1)""")
21
+ db.close()
22
+
23
+
24
+ def __force_insert(db, sql):
25
+ try:
26
+ db.execute(sql)
27
+ except IntegrityError:
28
+ pass
pool/shard008/Python/0075256_bram.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hwt.interfaces.std import BramPort
2
+ from hwt.synthesizer.shortcuts import toRtl
3
+ from hwtHdlParsers.unitFromHdl import UnitFromHdl
4
+
5
+
6
+ class Bram(UnitFromHdl):
7
+ _hdlSources = ["vhdl/dualportRAM.vhd"]
8
+ _intfClasses = [BramPort]
9
+
10
+ class BramSp(UnitFromHdl):
11
+ _hdlSources = ["vhdl/singleportRAM.vhd"]
12
+ _intfClasses = [BramPort]
13
+
14
+ if __name__ == "__main__":
15
+ print(toRtl(Bram()))
pool/shard008/Python/0075257_Recognizer.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # [The "BSD license"]
3
+ # Copyright (c) 2012 Terence Parr
4
+ # Copyright (c) 2012 Sam Harwell
5
+ # Copyright (c) 2014 Eric Vergnaud
6
+ # All rights reserved.
7
+ #
8
+ # Redistribution and use in source and binary forms, with or without
9
+ # modification, are permitted provided that the following conditions
10
+ # are met:
11
+ #
12
+ # 1. Redistributions of source code must retain the above copyright
13
+ # notice, this list of conditions and the following disclaimer.
14
+ # 2. Redistributions in binary form must reproduce the above copyright
15
+ # notice, this list of conditions and the following disclaimer in the
16
+ # documentation and/or other materials provided with the distribution.
17
+ # 3. The name of the author may not be used to endorse or promote products
18
+ # derived from this software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21
+ # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22
+ # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23
+ # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25
+ # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29
+ # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+ #
31
+ from antlr4.RuleContext import RuleContext
32
+ from antlr4.Token import Token
33
+ from antlr4.error.ErrorListener import ProxyErrorListener, ConsoleErrorListener
34
+
35
+ # need forward delcaration
36
+ RecognitionException = None
37
+
38
+ class Recognizer(object):
39
+
40
+ tokenTypeMapCache = dict()
41
+ ruleIndexMapCache = dict()
42
+
43
+ def __init__(self):
44
+ self._listeners = [ ConsoleErrorListener.INSTANCE ]
45
+ self._interp = None
46
+ self._stateNumber = -1
47
+
48
+ def extractVersion(self, version):
49
+ pos = version.find(".")
50
+ major = version[0:pos]
51
+ version = version[pos+1:]
52
+ pos = version.find(".")
53
+ if pos==-1:
54
+ pos = version.find("-")
55
+ if pos==-1:
56
+ pos = len(version)
57
+ minor = version[0:pos]
58
+ return major, minor
59
+
60
+ def checkVersion(self, toolVersion):
61
+ runtimeVersion = "4.5.2"
62
+ rvmajor, rvminor = self.extractVersion(runtimeVersion)
63
+ tvmajor, tvminor = self.extractVersion(toolVersion)
64
+ if rvmajor!=tvmajor or rvminor!=tvminor:
65
+ print("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion)
66
+
67
+ def addErrorListener(self, listener):
68
+ self._listeners.append(listener)
69
+
70
+ def removeErrorListener(self, listener):
71
+ self._listeners.remove(listener)
72
+
73
+ def removeErrorListeners(self):
74
+ self._listeners = []
75
+
76
+ def getTokenTypeMap(self):
77
+ tokenNames = self.getTokenNames()
78
+ if tokenNames is None:
79
+ from antlr4.error.Errors import UnsupportedOperationException
80
+ raise UnsupportedOperationException("The current recognizer does not provide a list of token names.")
81
+ result = self.tokenTypeMapCache.get(tokenNames, None)
82
+ if result is None:
83
+ result = zip( tokenNames, range(0, len(tokenNames)))
84
+ result["EOF"] = Token.EOF
85
+ self.tokenTypeMapCache[tokenNames] = result
86
+ return result
87
+
88
+ # Get a map from rule names to rule indexes.
89
+ #
90
+ # <p>Used for XPath and tree pattern compilation.</p>
91
+ #
92
+ def getRuleIndexMap(self):
93
+ ruleNames = self.getRuleNames()
94
+ if ruleNames is None:
95
+ from antlr4.error.Errors import UnsupportedOperationException
96
+ raise UnsupportedOperationException("The current recognizer does not provide a list of rule names.")
97
+ result = self.ruleIndexMapCache.get(ruleNames, None)
98
+ if result is None:
99
+ result = zip( ruleNames, range(0, len(ruleNames)))
100
+ self.ruleIndexMapCache[ruleNames] = result
101
+ return result
102
+
103
+ def getTokenType(self, tokenName:str):
104
+ ttype = self.getTokenTypeMap().get(tokenName, None)
105
+ if ttype is not None:
106
+ return ttype
107
+ else:
108
+ return Token.INVALID_TYPE
109
+
110
+
111
+ # What is the error header, normally line/character position information?#
112
+ def getErrorHeader(self, e:RecognitionException):
113
+ line = e.getOffendingToken().line
114
+ column = e.getOffendingToken().column
115
+ return "line "+line+":"+column
116
+
117
+
118
+ # How should a token be displayed in an error message? The default
119
+ # is to display just the text, but during development you might
120
+ # want to have a lot of information spit out. Override in that case
121
+ # to use t.toString() (which, for CommonToken, dumps everything about
122
+ # the token). This is better than forcing you to override a method in
123
+ # your token objects because you don't have to go modify your lexer
124
+ # so that it creates a new Java type.
125
+ #
126
+ # @deprecated This method is not called by the ANTLR 4 Runtime. Specific
127
+ # implementations of {@link ANTLRErrorStrategy} may provide a similar
128
+ # feature when necessary. For example, see
129
+ # {@link DefaultErrorStrategy#getTokenErrorDisplay}.
130
+ #
131
+ def getTokenErrorDisplay(self, t:Token):
132
+ if t is None:
133
+ return "<no token>"
134
+ s = t.text
135
+ if s is None:
136
+ if t.type==Token.EOF:
137
+ s = "<EOF>"
138
+ else:
139
+ s = "<" + str(t.type) + ">"
140
+ s = s.replace("\n","\\n")
141
+ s = s.replace("\r","\\r")
142
+ s = s.replace("\t","\\t")
143
+ return "'" + s + "'"
144
+
145
+ def getErrorListenerDispatch(self):
146
+ return ProxyErrorListener(self._listeners)
147
+
148
+ # subclass needs to override these if there are sempreds or actions
149
+ # that the ATN interp needs to execute
150
+ def sempred(self, localctx:RuleContext, ruleIndex:int, actionIndex:int):
151
+ return True
152
+
153
+ def precpred(self, localctx:RuleContext , precedence:int):
154
+ return True
155
+
156
+ @property
157
+ def state(self):
158
+ return self._stateNumber
159
+
160
+ # Indicate that the recognizer has changed internal state that is
161
+ # consistent with the ATN state passed in. This way we always know
162
+ # where we are in the ATN as the parser goes along. The rule
163
+ # context objects form a stack that lets us see the stack of
164
+ # invoking rules. Combine this and we have complete ATN
165
+ # configuration information.
166
+
167
+ @state.setter
168
+ def state(self, atnState:int):
169
+ self._stateNumber = atnState
170
+
171
+ del RecognitionException
172
+
173
+ import unittest
174
+ class Test(unittest.TestCase):
175
+
176
+ def testVersion(self):
177
+ major, minor = Recognizer().extractVersion("1.2")
178
+ self.assertEqual("1", major)
179
+ self.assertEqual("2", minor)
180
+ major, minor = Recognizer().extractVersion("1.2.3")
181
+ self.assertEqual("1", major)
182
+ self.assertEqual("2", minor)
183
+ major, minor = Recognizer().extractVersion("1.2-snapshot")
184
+ self.assertEqual("1", major)
185
+ self.assertEqual("2", minor)
pool/shard008/Python/0075259_views.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.views.generic import date_based
2
+ from blog.models import Post
3
+
4
+ def privileged_post_queryset(view_func):
5
+ def _wrapped_view(request, **kwargs):
6
+ if request.user.is_authenticated():
7
+ kwargs["queryset"] = Post.objects.all()
8
+ else:
9
+ kwargs["queryset"] = Post.objects.active()
10
+ return view_func(request, **kwargs)
11
+ return _wrapped_view
12
+
13
+ def homepage(request, **kwargs):
14
+ defaults = {
15
+ "date_field": "pub_date",
16
+ "num_latest": 3,
17
+ "template_name": "blog/homepage.html",
18
+ "template_object_name": "posts",
19
+ }
20
+ defaults.update(kwargs)
21
+ return date_based.archive_index(request, **defaults)
22
+ homepage = privileged_post_queryset(homepage)
23
+
24
+ object_detail = privileged_post_queryset(date_based.object_detail)
25
+ archive_day = privileged_post_queryset(date_based.archive_day)
26
+ archive_month = privileged_post_queryset(date_based.archive_month)
27
+ archive_year = privileged_post_queryset(date_based.archive_year)
pool/shard008/Python/0075265_test_bayesian_blocks.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from __future__ import (absolute_import, division, print_function,
4
+ unicode_literals)
5
+ import numpy as np
6
+ from numpy.testing import assert_allclose
7
+ from ...tests.helper import pytest
8
+ from .. import bayesian_blocks, RegularEvents
9
+
10
+
11
+ def test_single_change_point(rseed=0):
12
+ rng = np.random.RandomState(rseed)
13
+ x = np.concatenate([rng.rand(100),
14
+ 1 + rng.rand(200)])
15
+
16
+ bins = bayesian_blocks(x)
17
+
18
+ assert (len(bins) == 3)
19
+ assert_allclose(bins[1], 1, rtol=0.02)
20
+
21
+
22
+ def test_duplicate_events(rseed=0):
23
+ rng = np.random.RandomState(rseed)
24
+ t = rng.rand(100)
25
+ t[80:] = t[:20]
26
+
27
+ x = np.ones_like(t)
28
+ x[:20] += 1
29
+
30
+ bins1 = bayesian_blocks(t)
31
+ bins2 = bayesian_blocks(t[:80], x[:80])
32
+
33
+ assert_allclose(bins1, bins2)
34
+
35
+
36
+ def test_measures_fitness_homoscedastic(rseed=0):
37
+ rng = np.random.RandomState(rseed)
38
+ t = np.linspace(0, 1, 11)
39
+ x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
40
+ sigma = 0.05
41
+ x = x + sigma * rng.randn(len(x))
42
+
43
+ bins = bayesian_blocks(t, x, sigma, fitness='measures')
44
+
45
+ assert_allclose(bins, [0, 0.45, 0.55, 1])
46
+
47
+
48
+ def test_measures_fitness_heteroscedastic():
49
+ rng = np.random.RandomState(1)
50
+ t = np.linspace(0, 1, 11)
51
+ x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
52
+ sigma = 0.02 + 0.02 * rng.rand(len(x))
53
+ x = x + sigma * rng.randn(len(x))
54
+
55
+ bins = bayesian_blocks(t, x, sigma, fitness='measures')
56
+
57
+ assert_allclose(bins, [0, 0.45, 0.55, 1])
58
+
59
+
60
+ def test_regular_events():
61
+ rng = np.random.RandomState(0)
62
+ dt = 0.01
63
+ steps = np.concatenate([np.unique(rng.randint(0, 500, 100)),
64
+ np.unique(rng.randint(500, 1000, 200))])
65
+ t = dt * steps
66
+
67
+ # string fitness
68
+ bins1 = bayesian_blocks(t, fitness='regular_events', dt=dt)
69
+ assert (len(bins1) == 3)
70
+ assert_allclose(bins1[1], 5, rtol=0.05)
71
+
72
+ # class name fitness
73
+ bins2 = bayesian_blocks(t, fitness=RegularEvents, dt=dt)
74
+ assert_allclose(bins1, bins2)
75
+
76
+ # class instance fitness
77
+ bins3 = bayesian_blocks(t, fitness=RegularEvents(dt=dt))
78
+ assert_allclose(bins1, bins3)
79
+
80
+
81
+ def test_errors():
82
+ rng = np.random.RandomState(0)
83
+ t = rng.rand(100)
84
+
85
+ # x must be integer or None for events
86
+ with pytest.raises(ValueError):
87
+ bayesian_blocks(t, fitness='events', x=t)
88
+
89
+ # x must be binary for regular events
90
+ with pytest.raises(ValueError):
91
+ bayesian_blocks(t, fitness='regular_events', x=10 * t, dt=1)
92
+
93
+ # x must be specified for measures
94
+ with pytest.raises(ValueError):
95
+ bayesian_blocks(t, fitness='measures')
96
+
97
+ # sigma cannot be specified without x
98
+ with pytest.raises(ValueError):
99
+ bayesian_blocks(t, fitness='events', sigma=0.5)
100
+
101
+ # length of x must match length of t
102
+ with pytest.raises(ValueError):
103
+ bayesian_blocks(t, fitness='measures', x=t[:-1])
104
+
105
+ # repeated values in t fail when x is specified
106
+ t2 = t.copy()
107
+ t2[1] = t2[0]
108
+ with pytest.raises(ValueError):
109
+ bayesian_blocks(t2, fitness='measures', x=t)
110
+
111
+ # sigma must be broadcastable with x
112
+ with pytest.raises(ValueError):
113
+ bayesian_blocks(t, fitness='measures', x=t, sigma=t[:-1])
114
+
115
+
116
+ def test_fitness_function_results():
117
+ """Test results for several fitness functions"""
118
+ rng = np.random.RandomState(42)
119
+
120
+ # Event Data
121
+ t = rng.randn(100)
122
+ edges = bayesian_blocks(t, fitness='events')
123
+ assert_allclose(edges, [-2.6197451, -0.71094865, 0.36866702, 1.85227818])
124
+
125
+ # Event data with repeats
126
+ t[80:] = t[:20]
127
+ edges = bayesian_blocks(t, fitness='events', p0=0.01)
128
+ assert_allclose(edges, [-2.6197451, -0.47432431, -0.46202823, 1.85227818])
129
+
130
+ # Regular event data
131
+ dt = 0.01
132
+ t = dt * np.arange(1000)
133
+ x = np.zeros(len(t))
134
+ N = len(t) // 10
135
+ x[rng.randint(0, len(t), N)] = 1
136
+ x[rng.randint(0, len(t) // 2, N)] = 1
137
+ edges = bayesian_blocks(t, x, fitness='regular_events', dt=dt)
138
+ assert_allclose(edges, [0, 5.105, 9.99])
139
+
140
+ # Measured point data with errors
141
+ t = 100 * rng.rand(20)
142
+ x = np.exp(-0.5 * (t - 50) ** 2)
143
+ sigma = 0.1
144
+ x_obs = x + sigma * rng.randn(len(x))
145
+ edges = bayesian_blocks(t, x_obs, sigma, fitness='measures')
146
+ assert_allclose(edges, [4.360377, 48.456895, 52.597917, 99.455051])
pool/shard008/Python/0075266_basic_starts_with_op.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # encoding: utf-8
2
+ #
3
+ #
4
+ # This Source Code Form is subject to the terms of the Mozilla Public
5
+ # License, v. 2.0. If a copy of the MPL was not distributed with this file,
6
+ # You can obtain one at http:# mozilla.org/MPL/2.0/.
7
+ #
8
+ # Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
9
+ #
10
+ from __future__ import absolute_import, division, unicode_literals
11
+
12
+ from jx_base.expressions import BasicStartsWithOp as BasicStartsWithOp_, FALSE
13
+ from jx_elasticsearch.es52.painless.false_op import false_script
14
+ from jx_elasticsearch.es52.painless._utils import (
15
+ Painless,
16
+ empty_string_script,
17
+ )
18
+ from jx_elasticsearch.es52.painless.es_script import EsScript
19
+ from jx_elasticsearch.es52.painless.first_op import FirstOp
20
+ from mo_json import BOOLEAN
21
+
22
+
23
+ class BasicStartsWithOp(BasicStartsWithOp_):
24
+ def to_es_script(self, schema, not_null=False, boolean=False, many=True):
25
+ expr = Painless[FirstOp(self.value)].partial_eval().to_es_script(schema)
26
+ if expr is empty_string_script:
27
+ return false_script
28
+
29
+ prefix = Painless[self.prefix].to_es_script(schema).partial_eval()
30
+ return EsScript(
31
+ miss=FALSE,
32
+ type=BOOLEAN,
33
+ expr="(" + expr.expr + ").startsWith(" + prefix.expr + ")",
34
+ frum=self,
35
+ schema=schema,
36
+ )
pool/shard008/Python/0075269_exercisecollection_models.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.utils import timezone
2
+ from django.db import models
3
+ from django.dispatch import receiver
4
+ from django.db.models.signals import post_save
5
+ from django.urls import reverse
6
+ from django.utils.translation import gettext_lazy as _
7
+
8
+ from django.core.exceptions import ValidationError
9
+
10
+ from exercise.exercise_summary import UserExerciseSummary
11
+ from .exercise_models import BaseExercise, LearningObject
12
+ from .submission_models import Submission
13
+ from userprofile.models import UserProfile
14
+ from course.models import CourseInstance, CourseModule, LearningObjectCategory
15
+
16
+
17
+
18
+
19
+ class ExerciseCollection(BaseExercise):
20
+ # Submissions must persist even if the target course or category
21
+ # gets destroyed.
22
+ target_category = models.ForeignKey(
23
+ LearningObjectCategory,
24
+ verbose_name=_('LABEL_TARGET_CATEGORY'),
25
+ on_delete=models.SET_NULL,
26
+ null=True,
27
+ blank=True,
28
+ )
29
+
30
+ class Meta:
31
+ verbose_name = _('MODEL_NAME_EXERCISE_COLLECTION')
32
+ verbose_name_plural = _('MODEL_NAME_EXERCISE_COLLECTION_PLURAL')
33
+
34
+
35
+ # Clearing possible sources for erronous functionality
36
+ def clean(self):
37
+ super().clean()
38
+ errors = {}
39
+ if self.target_category.id == self.category.id:
40
+ errors['target_category'] = 'Cannot set own category as target category.'
41
+
42
+ if self.max_submissions != 1:
43
+ errors['max_submissions'] = 'Exercise Collection can have only 1 submission.'
44
+ if self.max_group_size != 1:
45
+ errors['max_group_size'] = 'Exercise Collection can have only 1 submitter'
46
+ if self.min_group_size != 1:
47
+ errors['min_group_size'] = 'Exercise Collection can have only 1 submitter'
48
+
49
+ if errors:
50
+ raise ValidationError(errors)
51
+
52
+ # Allows viewing of submissions
53
+ # Not actually user submittable
54
+ @property
55
+ def is_submittable(self):
56
+ return True
57
+
58
+
59
+ # Calculates the sum of best submissions in target category
60
+ #
61
+ # returns None:
62
+ # * Timing doesn't allow submissions
63
+ # * Target category doesn't have exercises with points
64
+ #
65
+ def get_points(self, user, no_scaling=False):
66
+ total_points = 0
67
+ tc_max_points = self.target_category_maxpoints
68
+ max_points = self.max_points
69
+
70
+ if tc_max_points == 0:
71
+ return None
72
+
73
+
74
+ timing, d1 = self.get_timing([user.userprofile],timezone.now())
75
+
76
+ if (timing == self.TIMING.CLOSED_AFTER or
77
+ timing == self.TIMING.ARCHIVED or
78
+ timing == self.TIMING.CLOSED_BEFORE or
79
+ timing == self.TIMING.UNOFFICIAL):
80
+ return None
81
+
82
+ for exercise in self.exercises:
83
+ summary = UserExerciseSummary(exercise, user)
84
+ if summary.best_submission is not None:
85
+ total_points += summary.best_submission.grade
86
+
87
+
88
+ if timing == self.TIMING.LATE:
89
+ total_points = round(total_points * (1 - self.course_module.late_submission_penalty))
90
+
91
+ if tc_max_points == max_points or no_scaling:
92
+ return total_points
93
+
94
+ total_points = total_points / (tc_max_points / max_points)
95
+
96
+ return total_points
97
+
98
+
99
+ # Used when staff forces regrading
100
+ def grade(self, request, submission):
101
+ self.check_submission(request.user, forced=True)
102
+
103
+
104
+ # Updates submission for ExerciseCollection
105
+ # Updated submission is saved only if grade has changed
106
+ # Parameters:
107
+ # * no_update: Doesn't update grade if submission exists
108
+ # * forced: Updates submission even if grade hasn't changed
109
+ #
110
+ def check_submission(self, user, no_update=False, forced=False):
111
+
112
+ if no_update and self.is_submitted(user) and not forced:
113
+ return
114
+
115
+ # Create new submission or use previous
116
+ if not self.is_submitted(user):
117
+ current_submission = Submission.objects.create(
118
+ exercise=self,
119
+ feedback="",
120
+ grade=-1,
121
+ )
122
+ current_submission.clean()
123
+ current_submission.save()
124
+ else:
125
+ submissions = self.get_submissions_for_student(user.userprofile)
126
+ current_submission = submissions[0]
127
+
128
+
129
+ new_grade = self.get_points(user)
130
+
131
+ if new_grade == current_submission.grade and not forced:
132
+ return
133
+
134
+
135
+ grading_data, feedback = self._generate_grading_data(user.userprofile)
136
+
137
+
138
+ current_submission.grade = new_grade
139
+ current_submission.submission_time = timezone.now()
140
+ current_submission.status = Submission.STATUS.READY
141
+ current_submission.submitters.set([user.userprofile])
142
+ current_submission.grading_data = grading_data
143
+ current_submission.feedback = feedback
144
+ current_submission.clean()
145
+ current_submission.save()
146
+
147
+
148
+
149
+ # Check if user has a submission for this exercise
150
+ def is_submitted(self, user):
151
+ return self.get_submissions_for_student(user.userprofile).count() > 0
152
+
153
+
154
+ # Property to access max_points in target category
155
+ @property
156
+ def target_category_maxpoints(self):
157
+ max_points = 0
158
+
159
+ for exercise in self.exercises:
160
+ max_points += exercise.max_points
161
+
162
+ return max_points
163
+
164
+
165
+ # Property to access exercises in target category
166
+ @property
167
+ def exercises(self):
168
+ return BaseExercise.objects.filter(
169
+ category=self.target_category
170
+ ).order_by('id')
171
+
172
+ # There are always submissions left from system's point of view
173
+ def one_has_submissions(self, students):
174
+ return True
175
+
176
+ # Generates feedback and grading_data
177
+ # Feedback is in HTML format
178
+ # grading_data is currently blank
179
+ def _generate_grading_data(self, profile):
180
+ feedback = ""
181
+ grading_data = ""
182
+
183
+ exercise_counter = 1
184
+ for exercise in self.exercises:
185
+
186
+ submission = UserExerciseSummary(exercise, profile.user).best_submission
187
+ if submission is None:
188
+ grade = 0
189
+ else:
190
+ grade = submission.grade
191
+
192
+ feedback += "Exercise {}: {}/{}\n Course: {} - {}\n Exercise: {}\n".format(
193
+ exercise_counter,
194
+ grade,
195
+ exercise.max_points,
196
+ exercise.category.course_instance.course.name,
197
+ exercise.category.course_instance.instance_name,
198
+ exercise.name,
199
+ )
200
+ exercise_counter += 1
201
+
202
+ feedback = "<pre>\n" + feedback + "\n</pre>\n"
203
+ return {"grading_data": grading_data}, feedback
204
+
205
+
206
+
207
+ # Updates submissions if new submission is in any ExerciseCollection's target category.
208
+ # ! Probably needs Cache-optimization
209
+ @receiver(post_save, sender=Submission)
210
+ def update_exercise_collection_submission(sender, instance, **kwargs):
211
+ collections = ExerciseCollection.objects.filter(target_category=instance.exercise.category)
212
+ if not collections:
213
+ return
214
+
215
+ profile = instance.submitters.first()
216
+ if not profile:
217
+ return
218
+
219
+ for collection in collections:
220
+ collection.check_submission(profile.user)
pool/shard008/Python/0075273_test_importers_github_api.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (C) 2014-present Taiga Agile LLC
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU Affero General Public License as
6
+ # published by the Free Software Foundation, either version 3 of the
7
+ # License, or (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU Affero General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU Affero General Public License
15
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+
17
+ import pytest
18
+ import json
19
+
20
+ from unittest import mock
21
+
22
+ from django.urls import reverse
23
+
24
+ from .. import factories as f
25
+ from taiga.importers import exceptions
26
+ from taiga.base.utils import json
27
+ from taiga.base import exceptions as exc
28
+
29
+
30
+ pytestmark = pytest.mark.django_db
31
+
32
+
33
+ def test_auth_url(client):
34
+ user = f.UserFactory.create()
35
+ client.login(user)
36
+
37
+ url = reverse("importers-github-auth-url")+"?uri=http://localhost:9001/project/new?from=github"
38
+
39
+ response = client.get(url, content_type="application/json")
40
+
41
+ assert response.status_code == 200
42
+ assert 'url' in response.data
43
+ assert response.data['url'] == "https://github.com/login/oauth/authorize?client_id=&scope=user,repo&redirect_uri=http://localhost:9001/project/new?from=github"
44
+
45
+ def test_authorize(client, settings):
46
+ user = f.UserFactory.create()
47
+ client.login(user)
48
+
49
+ authorize_url = reverse("importers-github-authorize")
50
+
51
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
52
+ GithubImporterMock.get_access_token.return_value = "token"
53
+ response = client.post(authorize_url, content_type="application/json", data=json.dumps({"code": "code"}))
54
+ assert GithubImporterMock.get_access_token.calledWith(
55
+ settings.IMPORTERS['github']['client_id'],
56
+ settings.IMPORTERS['github']['client_secret'],
57
+ "code"
58
+ )
59
+
60
+ assert response.status_code == 200
61
+ assert 'token' in response.data
62
+ assert response.data['token'] == "token"
63
+
64
+ def test_authorize_without_code(client):
65
+ user = f.UserFactory.create()
66
+ client.login(user)
67
+
68
+ authorize_url = reverse("importers-github-authorize")
69
+
70
+ response = client.post(authorize_url, content_type="application/json", data=json.dumps({}))
71
+
72
+ assert response.status_code == 400
73
+ assert 'token' not in response.data
74
+ assert '_error_message' in response.data
75
+ assert response.data['_error_message'] == "Code param needed"
76
+
77
+
78
+ def test_authorize_with_bad_verify(client, settings):
79
+ user = f.UserFactory.create()
80
+ client.login(user)
81
+
82
+ authorize_url = reverse("importers-github-authorize")
83
+
84
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
85
+ GithubImporterMock.get_access_token.side_effect = exceptions.InvalidAuthResult()
86
+ response = client.post(authorize_url, content_type="application/json", data=json.dumps({"code": "bad"}))
87
+ assert GithubImporterMock.get_access_token.calledWith(
88
+ settings.IMPORTERS['github']['client_id'],
89
+ settings.IMPORTERS['github']['client_secret'],
90
+ "bad"
91
+ )
92
+
93
+ assert response.status_code == 400
94
+ assert 'token' not in response.data
95
+ assert '_error_message' in response.data
96
+ assert response.data['_error_message'] == "Invalid auth data"
97
+
98
+
99
+ def test_import_github_list_users(client):
100
+ user = f.UserFactory.create()
101
+ client.login(user)
102
+
103
+ url = reverse("importers-github-list-users")
104
+
105
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
106
+ instance = mock.Mock()
107
+ instance.list_users.return_value = [
108
+ {"id": 1, "username": "user1", "full_name": "user1", "detected_user": None},
109
+ {"id": 2, "username": "user2", "full_name": "user2", "detected_user": None}
110
+ ]
111
+ GithubImporterMock.return_value = instance
112
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1}))
113
+
114
+ assert response.status_code == 200
115
+ assert response.data[0]["id"] == 1
116
+ assert response.data[1]["id"] == 2
117
+
118
+
119
+ def test_import_github_list_users_without_project(client):
120
+ user = f.UserFactory.create()
121
+ client.login(user)
122
+
123
+ url = reverse("importers-github-list-users")
124
+
125
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
126
+ instance = mock.Mock()
127
+ instance.list_users.return_value = [
128
+ {"id": 1, "username": "user1", "full_name": "user1", "detected_user": None},
129
+ {"id": 2, "username": "user2", "full_name": "user2", "detected_user": None}
130
+ ]
131
+ GithubImporterMock.return_value = instance
132
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"}))
133
+
134
+ assert response.status_code == 400
135
+
136
+
137
+ def test_import_github_list_users_with_problem_on_request(client):
138
+ user = f.UserFactory.create()
139
+ client.login(user)
140
+
141
+ url = reverse("importers-github-list-users")
142
+
143
+ with mock.patch('taiga.importers.github.importer.GithubClient') as GithubClientMock:
144
+ instance = mock.Mock()
145
+ instance.get.side_effect = exc.WrongArguments("Invalid Request")
146
+ GithubClientMock.return_value = instance
147
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1}))
148
+
149
+ assert response.status_code == 400
150
+
151
+
152
+ def test_import_github_list_projects(client):
153
+ user = f.UserFactory.create()
154
+ client.login(user)
155
+
156
+ url = reverse("importers-github-list-projects")
157
+
158
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
159
+ instance = mock.Mock()
160
+ instance.list_projects.return_value = ["project1", "project2"]
161
+ GithubImporterMock.return_value = instance
162
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"}))
163
+
164
+ assert response.status_code == 200
165
+ assert response.data[0] == "project1"
166
+ assert response.data[1] == "project2"
167
+
168
+
169
+ def test_import_github_list_projects_with_problem_on_request(client):
170
+ user = f.UserFactory.create()
171
+ client.login(user)
172
+
173
+ url = reverse("importers-github-list-projects")
174
+
175
+ with mock.patch('taiga.importers.github.importer.GithubClient') as GithubClientMock:
176
+ instance = mock.Mock()
177
+ instance.get.side_effect = exc.WrongArguments("Invalid Request")
178
+ GithubClientMock.return_value = instance
179
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"}))
180
+
181
+ assert response.status_code == 400
182
+
183
+
184
+ def test_import_github_project_without_project_id(client, settings):
185
+ settings.CELERY_ENABLED = True
186
+
187
+ user = f.UserFactory.create()
188
+ client.login(user)
189
+
190
+ url = reverse("importers-github-import-project")
191
+
192
+ with mock.patch('taiga.importers.github.tasks.GithubImporter') as GithubImporterMock:
193
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token"}))
194
+
195
+ assert response.status_code == 400
196
+ settings.CELERY_ENABLED = False
197
+
198
+
199
+ def test_import_github_project_with_celery_enabled(client, settings):
200
+ settings.CELERY_ENABLED = True
201
+
202
+ user = f.UserFactory.create()
203
+ project = f.ProjectFactory.create(slug="async-imported-project")
204
+ client.login(user)
205
+
206
+ url = reverse("importers-github-import-project")
207
+
208
+ with mock.patch('taiga.importers.github.tasks.GithubImporter') as GithubImporterMock:
209
+ instance = mock.Mock()
210
+ instance.import_project.return_value = project
211
+ GithubImporterMock.return_value = instance
212
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1}))
213
+
214
+ assert response.status_code == 202
215
+ assert "task_id" in response.data
216
+ settings.CELERY_ENABLED = False
217
+
218
+
219
+ def test_import_github_project_with_celery_disabled(client, settings):
220
+ user = f.UserFactory.create()
221
+ project = f.ProjectFactory.create(slug="imported-project")
222
+ client.login(user)
223
+
224
+ url = reverse("importers-github-import-project")
225
+
226
+ with mock.patch('taiga.importers.github.api.GithubImporter') as GithubImporterMock:
227
+ instance = mock.Mock()
228
+ instance.import_project.return_value = project
229
+ GithubImporterMock.return_value = instance
230
+ response = client.post(url, content_type="application/json", data=json.dumps({"token": "token", "project": 1}))
231
+
232
+ assert response.status_code == 200
233
+ assert "slug" in response.data
234
+ assert response.data['slug'] == "imported-project"
pool/shard008/Python/0075274_learned_ddpg.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ from models.abstract_model import AbstractModel
5
+ from reinforcement.ddpg.ddpg_reinforcement import DDPGReinforcement
6
+ from reinforcement.reinforcement_parameters import DDPGParameters
7
+
8
+
9
+ class LearnedDDPG(AbstractModel):
10
+ """
11
+ Represents a learned DDPG model. This is only an interface wrapper. Uses tensorflow internally.
12
+ """
13
+
14
+ def __init__(self, logdir):
15
+ """
16
+ Initializes tensorflow DDPG model, using specified directory.
17
+ :param logdir: Directory to tensorflow checkpoint.
18
+ """
19
+ self.metadata = None
20
+ for file in os.listdir(logdir):
21
+ if file.endswith(".json"):
22
+ with open(os.path.join(logdir, file), "r") as f:
23
+ self.metadata = json.load(f)
24
+ break
25
+
26
+ self.game = self.metadata["game"]
27
+ self.parameters = DDPGParameters.from_dict(self.metadata["parameters"])
28
+ self.ddpg = DDPGReinforcement(self.game, self.parameters)
29
+
30
+ # You can select "best" saved model, or "last" saved model
31
+ self.ddpg.load_checkpoint(os.path.join(logdir, "last"))
32
+
33
+ def get_new_instance(self, weights, game_config):
34
+ raise NotImplementedError
35
+
36
+ def evaluate(self, input, current_phase):
37
+ """
38
+ Evaluates the model result, using the specified input and current game phase.
39
+ :param input: Input for the model.
40
+ :param current_phase: Current game phase.
41
+ :return: Action.
42
+ """
43
+ action = self.ddpg.agent.play(input)
44
+
45
+
46
+ if len(self.ddpg.actions_count) > 1:
47
+ # Games with multiple phases
48
+ begin = sum(self.ddpg.actions_count[:current_phase])
49
+ end = begin + self.ddpg.actions_count[current_phase]
50
+ action = action[begin:end]
51
+
52
+ return action
53
+
54
+ def get_name(self):
55
+ """
56
+ Returns a string representation of the current model.
57
+ :return: a string representation of hte current model.
58
+ """
59
+ return "Learned DDPG Agent (Reinforcement Learning)"
60
+
61
+ def get_class_name(self):
62
+ """
63
+ Returns a class name of the current model.
64
+ :return: a class name of the current model.
65
+ """
66
+ return "LearnedDDPG"
pool/shard008/Python/0075275_LabelLineCurveFeature_v4.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import util as util
4
+
5
+
6
+ def roipoly(src, poly):
7
+ mask = np.zeros_like(src, dtype=np.uint8)
8
+
9
+ # overlay = util.normalize_depth(src, colormap=True)
10
+ # output = util.normalize_depth(src, colormap=True)
11
+ # alpha = 0.5
12
+
13
+ win = util.swap_indices(poly)
14
+ # print(win)
15
+
16
+ cv2.fillConvexPoly(mask, win, 255) # Create the ROI
17
+
18
+ # cv2.fillConvexPoly(overlay, win, (255, 255, 255))
19
+ # cv2.putText(overlay, "ROI Poly: alpha={}".format(alpha), (10, 30),
20
+ # cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
21
+ #
22
+ # cv2.addWeighted(overlay, alpha, output, 1 - alpha,
23
+ # 0, output)
24
+ res = src * mask
25
+
26
+ # print('mask1 count', np.count_nonzero(mask))
27
+ # cv2.namedWindow('roi poly', cv2.WINDOW_NORMAL)
28
+ # cv2.imshow('roi poly', output)
29
+ # cv2.waitKey(0)
30
+ # cv2.destroyAllWindows()
31
+ return res
32
+
33
+
34
+
35
+ def get_orientation(line, window_size):
36
+ dy = abs(line[0] - line[2])
37
+ dx = abs(line[1] - line[3])
38
+ # Vertical or horizontal line test
39
+ if dy > dx or dy == dx:
40
+ pt1 = [line[0], line[1] - window_size]
41
+ pt2 = [line[0], line[1] + window_size]
42
+ pt3 = [line[2], line[3] - window_size]
43
+ pt4 = [line[2], line[3] + window_size]
44
+ return pt1, pt2, pt3, pt4
45
+ else:
46
+ pt1 = [line[0] - window_size, line[1]]
47
+ pt2 = [line[0] + window_size, line[1]]
48
+ pt3 = [line[2] - window_size, line[3]]
49
+ pt4 = [line[2] + window_size, line[3]]
50
+ return pt1, pt2, pt3, pt4
51
+
52
+
53
+ def get_ordering(pt1, pt2, pt3, pt4):
54
+ temp1 = np.linalg.norm(np.subtract((np.add(pt1, pt3) / 2.0), (np.add(pt2, pt4) / 2.0)))
55
+ temp2 = np.linalg.norm(np.subtract((np.add(pt1, pt4) / 2.0), (np.add(pt2, pt3) / 2.0)))
56
+ res = np.array([pt1, pt3, pt4, pt2]) if temp1 > temp2 else np.array([pt1, pt4, pt3, pt2])
57
+ return [[int(i) for i in pt] for pt in res]
58
+
59
+
60
+ def classify_curves(src, curve_im, depth_im, list_lines, list_points, window_size):
61
+ im_size = src.shape
62
+ height = src.shape[0]
63
+ width = src.shape[1]
64
+ blank_image = np.zeros((height, width, 3), np.uint8)
65
+ img = util.normalize_depth(src, colormap=True)
66
+
67
+ res = []
68
+ for index, line in enumerate(list_lines):
69
+ # creates the bounds of the window
70
+ pt1, pt2, pt3, pt4 = get_orientation(line, window_size)
71
+
72
+ # For convenience, to see where the window is
73
+ cv2.line(img, (int(pt1[1]), int(pt1[0])), (int(pt2[1]), int(pt2[0])), (0, 0, 255), 1)
74
+ cv2.line(img, (int(pt3[1]), int(pt3[0])), (int(pt4[1]), int(pt4[0])), (0, 0, 255), 1)
75
+ cv2.line(img, (int(line[1]), int(line[0])), (int(line[3]), int(line[2])), (0, 255, 0), 1)
76
+
77
+ # creates a mask of the window
78
+ # on the curve and depth image
79
+ win = np.array(get_ordering(pt1, pt2, pt3, pt4))
80
+ maskC = roipoly(curve_im, win)
81
+
82
+ maskD = roipoly(depth_im, win)
83
+
84
+ # For comparison, get the contour
85
+ # points of this line
86
+ lx = [list_points[index]]
87
+ cntr_pts = []
88
+ for ii in lx:
89
+ r1, c1 = np.unravel_index([ii], im_size, order='F')
90
+ cntr_pts.append([c1[0], r1[0]])
91
+
92
+
93
+
94
+ """
95
+ mask5 = []
96
+ for i in temp_list:
97
+ # print(i[1], i[0])
98
+ mask5.append(src[i[1], i[0]])
99
+ mask5 = np.array(mask5)
100
+ # print('mask5', mask5)
101
+ # Eliminate zeros
102
+ mask5 = mask5[np.nonzero(mask5)]
103
+
104
+ # Average values in the mask
105
+ mask4_size = cv2.countNonZero(mask4)
106
+ a1 = 0 if cv2.countNonZero(mask4) == 0 else sum(src[np.nonzero(mask4)]) / mask4_size
107
+
108
+ # print('mask5', np.mean(mask5))
109
+ mask5_size = mask5.shape[0]
110
+ a2 = 0 if cv2.countNonZero(mask5) == 0 else np.mean(mask5)
111
+
112
+ # print('A1', a1, '\nA2', a2, '\n')
113
+
114
+ b1 = mask4_size * a1 - mask5_size * a2
115
+ try:
116
+ b11 = float(b1) / (cv2.countNonZero(mask4) - len(mask5))
117
+ except ZeroDivisionError:
118
+ b11 = float('nan')
119
+
120
+ # print('B11', b11)
121
+ if b11 < a2:
122
+ res.append(np.append(list_lines[index], [12]))
123
+ else:
124
+ res.append(np.append(list_lines[index], [13]))
125
+
126
+ #cv2.imshow('Points', img)
127
+ #cv2.waitKey(0)
128
+ #cv2.destroyAllWindows()
129
+
130
+ return np.asarray(res)
131
+ """
pool/shard008/Python/0075279_clustering_script.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from cosine_similarity import computeScores1
4
+ from edit_value_similarity import computeScores2
5
+ from indexer import index_from_json
6
+
7
+ index = "polar_geo"
8
+ output_file = "result_geo.csv"
9
+ computeScores1("geo", {"index": index}, output_file)
10
+
11
+ index = "polar"
12
+ output_file = "result_measurement.csv"
13
+ computeScores2("measurement", {"index": index}, output_file, is_all_key=False)
14
+
15
+ index = "polar_sweet"
16
+ output_file = "result_sweet.csv"
17
+ computeScores2("sweet", {"index": index}, output_file, is_all_key=False)
18
+
19
+ index = "polar_scholar"
20
+ output_file = "result_scholar.csv"
21
+ computeScores2("sweet", {"index": index}, output_file, is_all_key=False)
22
+
23
+ os.system("python edit-cosine-circle-packing.py result_measurement.csv circle_ms.json")
24
+ os.system("python edit-cosine-circle-packing.py result_geo.csv circle_geo.json")
25
+
26
+ os.system("python edit-cosine-circle-packing.py result_sweet.csv cirlce_sweet.json")
27
+ os.system("python edit-cosine-circle-packing.py result_scholar.csv circle_scholar.json")
28
+
pool/shard008/Python/0075282_repository.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implements Repos UI."""
2
+ from robottelo.constants import CHECKSUM_TYPE, REPO_TYPE
3
+ from robottelo.ui.base import Base, UIError
4
+ from robottelo.ui.locators import common_locators, locators, tab_locators
5
+
6
+
7
+ class Repos(Base):
8
+ """Manipulates Repos from UI."""
9
+ is_katello = True
10
+
11
+ def navigate_to_entity(self):
12
+ """Navigate to Repository entity tab"""
13
+ self.click(tab_locators['prd.tab_repos'])
14
+
15
+ def _search_locator(self):
16
+ """Specify locator for Repository entity search procedure"""
17
+ return locators['repo.select']
18
+
19
+ def create(self, name, gpg_key=None, http=False, url=None,
20
+ upstream_repo_name=None, repo_type=REPO_TYPE['yum'],
21
+ repo_checksum=CHECKSUM_TYPE['default']):
22
+ """Creates new repository from UI."""
23
+ self.click(locators['repo.new'])
24
+ self.text_field_update(common_locators['name'], name)
25
+ # label takes long time for 256 char test, hence timeout of 60 sec
26
+ self.wait_for_ajax(timeout=60)
27
+ if repo_type:
28
+ self.select(locators['repo.type'], repo_type)
29
+ repo_checksum_element = self.find_element(locators['repo.checksum'])
30
+ if repo_checksum_element:
31
+ self.select(locators['repo.checksum'], repo_checksum)
32
+ if gpg_key:
33
+ self.select(common_locators['gpg_key'], gpg_key)
34
+ if url:
35
+ self.text_field_update(locators['repo.url'], url)
36
+ if upstream_repo_name:
37
+ self.text_field_update(
38
+ locators['repo.upstream_name'], upstream_repo_name)
39
+ if http:
40
+ self.click(locators['repo.via_http'])
41
+ self.click(common_locators['create'])
42
+
43
+ def update(self, name, new_name=None, new_url=None, new_repo_checksum=None,
44
+ new_gpg_key=None, http=False, new_upstream_name=None):
45
+ """Updates repositories from UI."""
46
+ repo_element = self.search(name)
47
+ if repo_element is None:
48
+ raise UIError(
49
+ u'Unable to find the repository "{0}" for update.'.format(name)
50
+ )
51
+ repo_element.click()
52
+ self.wait_for_ajax()
53
+ if new_name:
54
+ self.click(locators['repo.name_edit'])
55
+ self.text_field_update(locators['repo.name_update'], new_name)
56
+ self.click(common_locators['save'])
57
+ if new_url:
58
+ self.click(locators['repo.url_edit'])
59
+ self.text_field_update(locators['repo.url_update'], new_url)
60
+ self.click(common_locators['save'])
61
+ if new_repo_checksum:
62
+ self.click(locators['repo.checksum_edit'])
63
+ self.select(locators['repo.checksum_update'], new_repo_checksum)
64
+ self.click(common_locators['save'])
65
+ if new_gpg_key:
66
+ self.click(locators['repo.gpg_key_edit'])
67
+ self.select(locators['repo.gpg_key_update'], new_gpg_key)
68
+ self.click(common_locators['save'])
69
+ if http:
70
+ self.click(locators['repo.via_http_edit'])
71
+ self.click(locators['repo.via_http_update'])
72
+ self.click(common_locators['save'])
73
+ if new_upstream_name:
74
+ self.click(locators['repo.upstream_edit'])
75
+ self.text_field_update(
76
+ locators['repo.upstream_update'], new_upstream_name)
77
+ self.click(common_locators['save'])
78
+
79
+ def delete(self, name, really=True):
80
+ """Delete a repository from UI."""
81
+ self.delete_entity(
82
+ name,
83
+ really,
84
+ locators['repo.remove'],
85
+ )
86
+
87
+ def search(self, element_name):
88
+ """Uses the search box to locate an element from a list of elements.
89
+ Repository entity is located inside of Product entity and has another
90
+ appearance, so it is necessary to use custom search there.
91
+
92
+ """
93
+ self.navigate_to_entity()
94
+ strategy, value = self._search_locator()
95
+ searchbox = self.wait_until_element(locators['repo.search'])
96
+ if searchbox:
97
+ searchbox.clear()
98
+ searchbox.send_keys(element_name)
99
+ element = self.wait_until_element((strategy, value % element_name))
100
+ return element
101
+
102
+ def discover_repo(self, url_to_discover, discovered_urls,
103
+ product, new_product=False, gpg_key=None):
104
+ """Discovers all repos from the given URL and creates selected repos.
105
+ Here if new_product=True; then it creates New Product instead of adding
106
+ repos under existing product.
107
+
108
+ """
109
+ self.click(locators['repo.repo_discover'])
110
+ self.text_field_update(locators['repo.discover_url'], url_to_discover)
111
+ self.click(locators['repo.discover_button'])
112
+ discover_cancel = self.wait_until_element(
113
+ locators['repo.cancel_discover'])
114
+ while discover_cancel:
115
+ discover_cancel = self.wait_until_element(
116
+ locators['repo.cancel_discover'])
117
+ for url in discovered_urls:
118
+ strategy, value = locators['repo.discovered_url_checkbox']
119
+ self.click((strategy, value % url))
120
+ self.click(locators['repo.create_selected'])
121
+ if new_product:
122
+ self.click(locators['repo.new_product'])
123
+ self.text_field_update(locators['repo.new_product_name'], product)
124
+ if gpg_key:
125
+ self.select(locators['repo.gpgkey_in_discover'], gpg_key)
126
+ else:
127
+ self.click(locators['repo.existing_product'])
128
+ self.select(locators['repo.select_exist_product'], product)
129
+ self.click(locators['repo.create'])
130
+
131
+ def validate_field(self, name, field_name, expected_field_value):
132
+ """Check that repository field has expected value"""
133
+ repo_element = self.search(name)
134
+ if repo_element is None:
135
+ raise UIError(
136
+ u'Unable to find the repo "{0}" for validation.'.format(name)
137
+ )
138
+ repo_element.click()
139
+ self.wait_for_ajax()
140
+ if field_name in [
141
+ 'checksum', 'errata', 'gpgkey', 'package_groups', 'packages',
142
+ 'upstream', 'url',
143
+ ]:
144
+ return (self.wait_until_element(locators[
145
+ 'repo.fetch_' + field_name]).text == expected_field_value)
146
+ return False
pool/shard008/Python/0075283_module4.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##############################################
2
+ # File Name: module4.py
3
+ # Version: 1.0
4
+ # Team No.: 24
5
+ # Team Name:
6
+ # Date: 4 Nov 15
7
+ ##############################################
8
+
9
+ import RPi.GPIO as GPIO
10
+ import time
11
+
12
+ print 'Press CTRL+C to exit the program'
13
+
14
+ GPIO.setmode(GPIO.BOARD)
15
+
16
+ GPIO.setup(11, GPIO.OUT)
17
+ GPIO.setup(13, GPIO.OUT)
18
+ GPIO.setup(15, GPIO.OUT)
19
+
20
+ RUNNING = True
21
+
22
+ try:
23
+ while RUNNING:
24
+
25
+ print 'Turn on red light\n'
26
+ GPIO.output(11, True)
27
+ time.sleep(2)
28
+ GPIO.output(11, False)
29
+
30
+ print 'Turn on orange light\n'
31
+ GPIO.output(13, True)
32
+ time.sleep(2)
33
+ GPIO.output(13, False)
34
+
35
+ print 'Turn on green light\n'
36
+ GPIO.output(15, True)
37
+ time.sleep(2)
38
+ GPIO.output(15, False)
39
+
40
+ # If CTRL+C is pressed the main loop is broken
41
+ except KeyboardInterrupt:
42
+ RUNNING = False
43
+ print "\nQuitting program."
44
+
45
+ # Actions under 'finally' will always be called, regardless of
46
+ # what stopped the program (be it an error or an interrupt)
47
+ finally:
48
+ # Stop and cleanup to finish cleanly so the pins
49
+ # are available to be used again
50
+ GPIO.cleanup()
51
+
52
+ print "\nProgram ended"
pool/shard008/Python/0075289_game_loop_basic.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from aiohttp import web
3
+
4
+ async def handle(request):
5
+ index = open("index.html", 'rb')
6
+ content = index.read()
7
+ return web.Response(body=content, content_type='text/html')
8
+
9
+
10
+ async def wshandler(request):
11
+ app = request.app
12
+ ws = web.WebSocketResponse()
13
+ await ws.prepare(request)
14
+ app["sockets"].append(ws)
15
+
16
+ while 1:
17
+ msg = await ws.receive()
18
+ if msg.tp == web.MsgType.text:
19
+ print("Got message %s" % msg.data)
20
+ ws.send_str("Pressed key code: {}".format(msg.data))
21
+ elif msg.tp == web.MsgType.close or\
22
+ msg.tp == web.MsgType.error:
23
+ break
24
+
25
+ app["sockets"].remove(ws)
26
+ print("Closed connection")
27
+ return ws
28
+
29
+ async def game_loop(app):
30
+ while 1:
31
+ for ws in app["sockets"]:
32
+ ws.send_str("game loop says: tick")
33
+ await asyncio.sleep(2)
34
+
35
+
36
+ app = web.Application()
37
+ app["sockets"] = []
38
+
39
+ asyncio.ensure_future(game_loop(app))
40
+
41
+ app.router.add_route('GET', '/connect', wshandler)
42
+ app.router.add_route('GET', '/', handle)
43
+
44
+ web.run_app(app)
pool/shard008/Python/0075290_test_lint.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Copyright (C) 2012-2016 - Oscar Campos <oscar.campos@member.fsf.org>
3
+ # This program is Free Software see LICENSE file for details
4
+
5
+ import sys
6
+
7
+ from handlers.python_lint_handler import PythonLintHandler
8
+
9
+ PYTHON3 = sys.version_info >= (3, 0)
10
+
11
+
12
+ class TestLint(object):
13
+ """Linting test suite
14
+ """
15
+
16
+ _lintable_code = '''
17
+ def f():
18
+ a = 1
19
+ [1 for a, b in [(1, 2)]]
20
+ '''
21
+
22
+ _lintable_docstring = '''
23
+ def f():
24
+ """This is a docst
25
+ ring"""'''
26
+
27
+ _import_validator_code = '''
28
+ import idontexists
29
+
30
+
31
+ def main():
32
+ idontexists('Hello World!')
33
+ '''
34
+
35
+ def setUp(self):
36
+ self._settings = {
37
+ 'use_pyflakes': False, 'use_pylint': False, 'use_pep257': False,
38
+ 'pep8': False, 'vapidate_imports': False
39
+ }
40
+
41
+ def test_pyflakes_lint(self):
42
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pyflakes)
43
+ self._settings['use_pyflakes'] = True
44
+ handler.lint(self._settings, self._lintable_code)
45
+
46
+ def test_pyflakes_ignore(self):
47
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pyflakes_ignore) # noqa
48
+ self._settings['use_pyflakes'] = True
49
+ self._settings['pyflakes_ignore'] = 'F841'
50
+
51
+ def test_pep8_lint(self):
52
+ self._settings['pep8'] = True
53
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8)
54
+ handler.lint(self._settings, self._lintable_code)
55
+
56
+ def test_pep8_ignores(self):
57
+ self._settings['pep8'] = True
58
+ self._settings['pep8_ignore'] = ['W293']
59
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8_ignores) # noqa
60
+ handler.lint(self._settings, self._lintable_code)
61
+
62
+ def test_pep8_max_line_lenght(self):
63
+ self._settings['pep8'] = True
64
+ self._settings['pep8_max_line_length'] = 120
65
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pep8_max_line_length) # noqa
66
+ handler.lint(self._settings, 'a = \'this is a very long string: {0}\'\n'.format('a' * 80)) # noqa
67
+
68
+ def test_pep257_lint(self):
69
+ self._settings['use_pep257'] = True
70
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pep257)
71
+ handler.lint(self._settings, self._lintable_docstring, '')
72
+
73
+ def test_pep257_ignores(self):
74
+ self._settings['use_pep257'] = True
75
+ self._settings['pep257_ignore'] = ['D100', 'D400', 'D209', 'D205', 'D401'] # noqa
76
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_pep257_ignores) # noqa
77
+ handler.lint(self._settings, self._lintable_docstring, '')
78
+
79
+ def test_import_validator(self):
80
+ self._settings['validate_imports'] = True
81
+ handler = PythonLintHandler('lint', None, 0, 0, self._check_validate_imports) # noqa
82
+ handler.lint(self._settings, self._import_validator_code, '')
83
+
84
+ def _check_pyflakes(self, result):
85
+ assert result['success'] is True
86
+ assert len(result['errors']) == 1
87
+ assert result['errors'][0]['level'] == 'W'
88
+ err = 'list comprehension redefines \'a\' from line 3' \
89
+ if not PYTHON3 else 'local variable \'a\' is assigned to but never used' # noqa
90
+ assert result['errors'][0]['raw_error'] == err
91
+ assert result['errors'][0]['underline_range'] is False
92
+ assert result['uid'] == 0
93
+ assert result['vid'] == 0
94
+
95
+ def _check_pep8(self, result):
96
+ assert result['success'] is True
97
+ assert len(result['errors']) == 2
98
+ error1 = result['errors'][0]
99
+ assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa
100
+ assert error1['level'] == 'V'
101
+ assert error1['underline_range'] is True
102
+ error2 = result['errors'][1]
103
+ assert error2['raw_error'] == '[V] PEP 8 (W293): blank line contains whitespace' # noqa
104
+ assert error2['level'] == 'V'
105
+ assert error2['underline_range'] is True
106
+ assert result['uid'] == 0
107
+ assert result['vid'] == 0
108
+
109
+ def _check_pep8_ignores(self, result):
110
+ assert result['success'] is True
111
+ assert len(result['errors']) == 1
112
+ error1 = result['errors'][0]
113
+ assert error1['raw_error'] == '[V] PEP 8 (W391): blank line at end of file' # noqa
114
+ assert error1['level'] == 'V'
115
+ assert error1['underline_range'] is True
116
+ assert result['uid'] == 0
117
+ assert result['vid'] == 0
118
+
119
+ def _check_pep8_max_line_length(self, result):
120
+ assert result['success'] is True
121
+ assert len(result['errors']) == 0
122
+ assert result['uid'] == 0
123
+ assert result['vid'] == 0
124
+
125
+ def _check_pyflakes_ignore(self, result):
126
+ assert result['success'] is True
127
+ assert len(result['errors']) == 0
128
+ assert result['uid'] == 0
129
+ assert result['vid'] == 0
130
+
131
+ def _check_pep257(self, result):
132
+ assert result['success'] is True
133
+ assert len(result['errors']) == 5
134
+ raw_errors = [r['raw_error'] for r in result['errors']]
135
+ assert '[V] PEP 257 (D100): Missing docstring in public module' in raw_errors # noqa
136
+ assert '[V] PEP 257 (D209): Multi-line docstring closing quotes should be on a separate line' in raw_errors # noqa
137
+ assert '[V] PEP 257 (D205): 1 blank line required between summary line and description (found 0)' in raw_errors # noqa
138
+ assert '[V] PEP 257 (D400): First line should end with a period (not \'t\')' in raw_errors # noqa
139
+ assert '[V] PEP 257 (D401): First line should be in imperative mood (\'Thi\', not \'This\')' in raw_errors # noqa
140
+
141
+ error1, error2, error3, error4, error5 = result['errors']
142
+ assert (error1['level'], error2['level'], error3['level'], error4['level'], error5['level']) == ('V', 'V', 'V', 'V', 'V') # noqa
143
+ assert result['uid'] == 0
144
+ assert result['vid'] == 0
145
+
146
+ def _check_pep257_ignores(self, result):
147
+ assert result['success'] is True
148
+ assert len(result['errors']) == 0
149
+ assert result['uid'] == 0
150
+ assert result['vid'] == 0
151
+
152
+ def _check_validate_imports(self, result):
153
+ assert result['success'] is True
154
+ assert len(result['errors']) == 1
155
+ assert result['errors'][0]['raw_error'] == "[E] ImportValidator (801): can't import idontexists" # noqa
156
+ assert result['errors'][0]['code'] == 801
157
+ assert result['errors'][0]['level'] == 'E'
158
+ assert result['errors'][0]['underline_range'] is True
159
+ assert result['uid'] == 0
160
+ assert result['vid'] == 0
pool/shard008/Python/0075292_archive_util.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for extracting common archive formats"""
2
+
3
+
4
+ __all__ = [
5
+ "unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",
6
+ "UnrecognizedFormat", "extraction_drivers", "unpack_directory",
7
+ ]
8
+
9
+ import zipfile, tarfile, os, shutil
10
+ from pkg_resources import ensure_directory
11
+ from distutils.errors import DistutilsError
12
+
13
+ class UnrecognizedFormat(DistutilsError):
14
+ """Couldn't recognize the archive type"""
15
+
16
+ def default_filter(src,dst):
17
+ """The default progress/filter callback; returns True for all files"""
18
+ return dst
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+ def unpack_archive(filename, extract_dir, progress_filter=default_filter,
43
+ drivers=None
44
+ ):
45
+ """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``
46
+
47
+ `progress_filter` is a function taking two arguments: a source path
48
+ internal to the archive ('/'-separated), and a filesystem path where it
49
+ will be extracted. The callback must return the desired extract path
50
+ (which may be the same as the one passed in), or else ``None`` to skip
51
+ that file or directory. The callback can thus be used to report on the
52
+ progress of the extraction, as well as to filter the items extracted or
53
+ alter their extraction paths.
54
+
55
+ `drivers`, if supplied, must be a non-empty sequence of functions with the
56
+ same signature as this function (minus the `drivers` argument), that raise
57
+ ``UnrecognizedFormat`` if they do not support extracting the designated
58
+ archive type. The `drivers` are tried in sequence until one is found that
59
+ does not raise an error, or until all are exhausted (in which case
60
+ ``UnrecognizedFormat`` is raised). If you do not supply a sequence of
61
+ drivers, the module's ``extraction_drivers`` constant will be used, which
62
+ means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that
63
+ order.
64
+ """
65
+ for driver in drivers or extraction_drivers:
66
+ try:
67
+ driver(filename, extract_dir, progress_filter)
68
+ except UnrecognizedFormat:
69
+ continue
70
+ else:
71
+ return
72
+ else:
73
+ raise UnrecognizedFormat(
74
+ "Not a recognized archive type: %s" % filename
75
+ )
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+ def unpack_directory(filename, extract_dir, progress_filter=default_filter):
84
+ """"Unpack" a directory, using the same interface as for archives
85
+
86
+ Raises ``UnrecognizedFormat`` if `filename` is not a directory
87
+ """
88
+ if not os.path.isdir(filename):
89
+ raise UnrecognizedFormat("%s is not a directory" % (filename,))
90
+
91
+ paths = {filename:('',extract_dir)}
92
+ for base, dirs, files in os.walk(filename):
93
+ src,dst = paths[base]
94
+ for d in dirs:
95
+ paths[os.path.join(base,d)] = src+d+'/', os.path.join(dst,d)
96
+ for f in files:
97
+ name = src+f
98
+ target = os.path.join(dst,f)
99
+ target = progress_filter(src+f, target)
100
+ if not target:
101
+ continue # skip non-files
102
+ ensure_directory(target)
103
+ f = os.path.join(base,f)
104
+ shutil.copyfile(f, target)
105
+ shutil.copystat(f, target)
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+ def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
125
+ """Unpack zip `filename` to `extract_dir`
126
+
127
+ Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
128
+ by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation
129
+ of the `progress_filter` argument.
130
+ """
131
+
132
+ if not zipfile.is_zipfile(filename):
133
+ raise UnrecognizedFormat("%s is not a zip file" % (filename,))
134
+
135
+ z = zipfile.ZipFile(filename)
136
+ try:
137
+ for info in z.infolist():
138
+ name = info.filename
139
+
140
+ # don't extract absolute paths or ones with .. in them
141
+ if name.startswith('/') or '..' in name:
142
+ continue
143
+
144
+ target = os.path.join(extract_dir, *name.split('/'))
145
+ target = progress_filter(name, target)
146
+ if not target:
147
+ continue
148
+ if name.endswith('/'):
149
+ # directory
150
+ ensure_directory(target)
151
+ else:
152
+ # file
153
+ ensure_directory(target)
154
+ data = z.read(info.filename)
155
+ f = open(target,'wb')
156
+ try:
157
+ f.write(data)
158
+ finally:
159
+ f.close()
160
+ del data
161
+ finally:
162
+ z.close()
163
+
164
+
165
+ def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
166
+ """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
167
+
168
+ Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
169
+ by ``tarfile.open()``). See ``unpack_archive()`` for an explanation
170
+ of the `progress_filter` argument.
171
+ """
172
+
173
+ try:
174
+ tarobj = tarfile.open(filename)
175
+ except tarfile.TarError:
176
+ raise UnrecognizedFormat(
177
+ "%s is not a compressed or uncompressed tar file" % (filename,)
178
+ )
179
+
180
+ try:
181
+ tarobj.chown = lambda *args: None # don't do any chowning!
182
+ for member in tarobj:
183
+ if member.isfile() or member.isdir():
184
+ name = member.name
185
+ # don't extract absolute paths or ones with .. in them
186
+ if not name.startswith('/') and '..' not in name:
187
+ dst = os.path.join(extract_dir, *name.split('/'))
188
+ dst = progress_filter(name, dst)
189
+ if dst:
190
+ if dst.endswith(os.sep):
191
+ dst = dst[:-1]
192
+ try:
193
+ tarobj._extract_member(member,dst) # XXX Ugh
194
+ except tarfile.ExtractError:
195
+ pass # chown/chmod/mkfifo/mknode/makedev failed
196
+ return True
197
+ finally:
198
+ tarobj.close()
199
+
200
+
201
+
202
+
203
+ extraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile
204
+
205
+
pool/shard008/Python/0075297_loggings.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'ONCE_PER',
3
+ ]
4
+
5
+ import sys
6
+ import threading
7
+
8
+ from .assertions import ASSERT
9
+
10
+ ASSERT(hasattr(sys, '_getframe'), 'expect sys._getframe')
11
+
12
+
13
+ def get_location(depth):
14
+ frame = sys._getframe(depth)
15
+ return frame.f_code.co_filename, frame.f_lineno
16
+
17
+
18
+ class OncePer:
19
+
20
+ def __init__(self):
21
+ self._lock = threading.Lock()
22
+ self._num_calls = {}
23
+
24
+ def __call__(self, period, log, *args, **kwargs):
25
+ location = get_location(2)
26
+ with self._lock:
27
+ num_calls = self._num_calls.setdefault(location, 0)
28
+ self._num_calls[location] = num_calls + 1
29
+ if num_calls % period != 0:
30
+ return
31
+ log(*args, **kwargs)
32
+
33
+
34
+ ONCE_PER = OncePer()