Pendigard commited on
Commit
c276642
·
verified ·
1 Parent(s): 65e2e79

Upload folder using huggingface_hub (part 27)

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/shard001/Python/0012539_ntp.py +51 -0
  2. pool/shard001/Python/0012540_filters.py +89 -0
  3. pool/shard001/Python/0012541_threading.py +22 -0
  4. pool/shard001/Python/0012547_product_catalog_rep_qty.py +153 -0
  5. pool/shard001/Python/0012548_popupmenu.py +153 -0
  6. pool/shard001/Python/0012551_source_mapper.py +171 -0
  7. pool/shard001/Python/0012552_managers.py +142 -0
  8. pool/shard001/Python/0012554_notifications.py +138 -0
  9. pool/shard001/Python/0012559_tests.py +111 -0
  10. pool/shard001/Python/0012562_message_parser.py +229 -0
  11. pool/shard001/Python/0012567_config.py +76 -0
  12. pool/shard001/Python/0012570_admin.py +98 -0
  13. pool/shard001/Python/0012576_objects.py +143 -0
  14. pool/shard001/Python/0012577_test_dbapi_compliance.py +98 -0
  15. pool/shard001/Python/0012583_0002_set_site_domain_and_name.py +40 -0
  16. pool/shard001/Python/0012590_bugcve.py +28 -0
  17. pool/shard001/Python/0012597_main.py +253 -0
  18. pool/shard001/Python/0012600_0001_initial.py +56 -0
  19. pool/shard001/Python/0012607_wsgi.py +28 -0
  20. pool/shard001/Python/0012608_init__.py +178 -0
  21. pool/shard001/Python/0012611_arguments.py +13 -0
  22. pool/shard001/Python/0012613_test_offload.py +75 -0
  23. pool/shard001/Python/0012614_SetJobLimit.py +37 -0
  24. pool/shard001/Python/0012615_lib.py +26 -0
  25. pool/shard001/Python/0012627_torrent.py +169 -0
  26. pool/shard001/Python/0012628_border_overaly.py +41 -0
  27. pool/shard001/Python/0012635_users.py +172 -0
  28. pool/shard001/Python/0012645_main.py +68 -0
  29. pool/shard001/Python/0012647_genicon.py +31 -0
  30. pool/shard001/Python/0012651_tinypng.py +29 -0
  31. pool/shard001/Python/0012652_retry_http.py +97 -0
  32. pool/shard001/Python/0012654_parse_timings.py +69 -0
  33. pool/shard001/Python/0012655_init__.py +91 -0
  34. pool/shard001/Python/0012658_query_results.py +167 -0
  35. pool/shard001/Python/0012665_requests.py +111 -0
  36. pool/shard001/Python/0012671_faucet_event.py +139 -0
  37. pool/shard001/Python/0012672_pyunit_colname_set_basic.py +22 -0
  38. pool/shard001/Python/0012674_test_example2.py +54 -0
  39. pool/shard001/Python/0012676_ping.py +16 -0
  40. pool/shard001/Python/0012678_models.py +79 -0
  41. pool/shard001/Python/0012689_models.py +115 -0
  42. pool/shard001/Python/0012693_drop_stale_gradient_optimizer.py +112 -0
  43. pool/shard001/Python/0012698_test_runner.py +65 -0
  44. pool/shard001/Python/0012703_lirc2raw.py +135 -0
  45. pool/shard001/Python/0012713_assigneddiscount.py +81 -0
  46. pool/shard001/Python/0012715_test_cli.py +111 -0
  47. pool/shard001/Python/0012716_config.py +296 -0
  48. pool/shard001/Python/0012723_main.py +71 -0
  49. pool/shard001/Python/0012726_launcher.py +23 -0
  50. pool/shard001/Python/0012730_filters.py +245 -0
pool/shard001/Python/0012539_ntp.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### This program is free software; you can redistribute it and/or modify
2
+ ## it under the terms of the GNU General Public License as published by
3
+ ## the Free Software Foundation; either version 2 of the License, or
4
+ ## (at your option) any later version.
5
+
6
+ ## This program is distributed in the hope that it will be useful,
7
+ ## but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ ## GNU General Public License for more details.
10
+
11
+ ## You should have received a copy of the GNU General Public License
12
+ ## along with this program; if not, write to the Free Software
13
+ ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
14
+
15
+ from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
16
+
17
+ class Ntp(Plugin):
18
+ """NTP related information
19
+ """
20
+
21
+ plugin_name = "ntp"
22
+
23
+ packages = ('ntp',)
24
+
25
+ def setup(self):
26
+ self.add_copy_specs([
27
+ "/etc/ntp.conf",
28
+ "/etc/ntp/step-tickers",
29
+ "/etc/ntp/ntpservers"
30
+ ])
31
+ self.add_cmd_output("ntptime")
32
+
33
+
34
+ class RedHatNtp(Ntp, RedHatPlugin):
35
+ """NTP related information for RedHat based distributions
36
+ """
37
+
38
+ def setup(self):
39
+ super(RedHatNtp, self).setup()
40
+ self.add_copy_spec("/etc/sysconfig/ntpd")
41
+ self.add_cmd_output("ntpstat")
42
+
43
+
44
+ class DebianNtp(Ntp, DebianPlugin, UbuntuPlugin):
45
+ """NTP related information for Debian based distributions
46
+ """
47
+
48
+ def setup(self):
49
+ super(DebianNtp, self).setup()
50
+ self.add_copy_spec('/etc/default/ntp')
51
+
pool/shard001/Python/0012540_filters.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2012 - 2013 Zarafa B.V.
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU Affero General Public License, version 3,
5
+ # as published by the Free Software Foundation with the following additional
6
+ # term according to sec. 7:
7
+ #
8
+ # According to sec. 7 of the GNU Affero General Public License, version
9
+ # 3, the terms of the AGPL are supplemented with the following terms:
10
+ #
11
+ # "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
12
+ # the Program under the AGPL does not imply a trademark license.
13
+ # Therefore any rights, title and interest in our trademarks remain
14
+ # entirely with us.
15
+ #
16
+ # However, if you propagate an unmodified version of the Program you are
17
+ # allowed to use the term "Zarafa" to indicate that you distribute the
18
+ # Program. Furthermore you may use our trademarks where it is necessary
19
+ # to indicate the intended purpose of a product or service provided you
20
+ # use it in accordance with honest practices in industrial or commercial
21
+ # matters. If you want to propagate modified versions of the Program
22
+ # under the name "Zarafa" or "Zarafa Server", you may only do so if you
23
+ # have a written permission by Zarafa B.V. (to acquire a permission
24
+ # please contact Zarafa at trademark@zarafa.com).
25
+ #
26
+ # The interactive user interface of the software displays an attribution
27
+ # notice containing the term "Zarafa" and/or the logo of Zarafa.
28
+ # Interactive user interfaces of unmodified and modified versions must
29
+ # display Appropriate Legal Notices according to sec. 5 of the GNU
30
+ # Affero General Public License, version 3, when you propagate
31
+ # unmodified or modified versions of the Program. In accordance with
32
+ # sec. 7 b) of the GNU Affero General Public License, version 3, these
33
+ # Appropriate Legal Notices must retain the logo of Zarafa or display
34
+ # the words "Initial Development by Zarafa" if the display of the logo
35
+ # is not reasonably feasible for technical reasons. The use of the logo
36
+ # of Zarafa in Legal Notices is allowed for unmodified and modified
37
+ # versions of the software.
38
+ #
39
+ # This program is distributed in the hope that it will be useful,
40
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
41
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42
+ # GNU Affero General Public License for more details.
43
+ #
44
+ # You should have received a copy of the GNU Affero General Public License
45
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
46
+
47
+
48
+ from datetime import datetime
49
+ import collections
50
+
51
+ from pumpkin.filters import _make_op # NOQA
52
+ from pumpkin.filters import contains # NOQA
53
+ from pumpkin.filters import endswith # NOQA
54
+ from pumpkin.filters import eq # NOQA
55
+ from pumpkin.filters import opand # NOQA
56
+ from pumpkin.filters import opnot # NOQA
57
+ from pumpkin.filters import opor # NOQA
58
+ from pumpkin.filters import present # NOQA
59
+ from pumpkin.filters import startswith # NOQA
60
+ from pumpkin.filters import unicode2str
61
+
62
+ from extfields import GeneralizedTimeField
63
+
64
+
65
+ SearchParams = collections.namedtuple('SearchParams', 'basedn filter')
66
+
67
+ _time_field = None
68
+ def get_time_field():
69
+ global _time_field
70
+ if not _time_field:
71
+ _time_field = GeneralizedTimeField(None)
72
+ return _time_field
73
+
74
+
75
+ @unicode2str
76
+ def gte(attr, value):
77
+ if isinstance(value, datetime):
78
+ time_field = get_time_field()
79
+ value = time_field.encode2str(value)[0]
80
+
81
+ return '(%s>=%s)' % (attr, value)
82
+
83
+ @unicode2str
84
+ def lte(attr, value):
85
+ if isinstance(value, datetime):
86
+ time_field = get_time_field()
87
+ value = time_field.encode2str(value)[0]
88
+
89
+ return '(%s<=%s)' % (attr, value)
pool/shard001/Python/0012541_threading.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from filament import patcher as _fil_patcher
2
+ from filament import _util as _fil_util
3
+ import _filament.timer as _fil_timer
4
+ from _filament.locking import *
5
+
6
+ __filament__ = {'patch':'threading'}
7
+
8
+ threading = _fil_patcher.get_original('threading')
9
+
10
+ class Timer(_fil_timer.Timer):
11
+ __doc__ = threading.Timer.__doc__
12
+
13
+ def __init__(self, interval, function, args=None, kwargs=None):
14
+ if args is None:
15
+ args = ()
16
+ if kwargs:
17
+ super(Timer, self).__init__(interval, function, *args, **kwargs)
18
+ else:
19
+ super(Timer, self).__init__(interval, function, *args)
20
+
21
+
22
+ _fil_util.copy_globals(threading, globals())
pool/shard001/Python/0012547_product_catalog_rep_qty.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ ##############################################################################
3
+ #
4
+ # Copyright (C) 2013 Bortolatto Ivan. ( ivan.bortolatto(at)didotech.com )
5
+ # Copyright (C) 2013 Didotech Inc. (<http://www.didotech.com>)
6
+ # All Rights Reserved
7
+ #
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU Affero General Public License as published
10
+ # by 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 Affero General Public License
19
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ #
21
+ ##############################################################################
22
+
23
+ import time
24
+ from report import report_sxw
25
+ import pooler
26
+ import pprint
27
+
28
+ from osv import osv, fields
29
+ import decimal_precision as dp
30
+
31
+ pp = pprint.PrettyPrinter(indent=4)
32
+
33
+ #try:
34
+ # from cStringIO import StringIO
35
+ # _hush_pyflakes = [ StringIO ]
36
+ #except ImportError:
37
+ # from StringIO import StringIO
38
+
39
+
40
+ class product_product(osv.osv):
41
+ _name = 'product.product'
42
+ _inherit = 'product.product'
43
+
44
+ def _product_price2(self, cr, uid, ids, name, arg, context=None):
45
+ res = {}
46
+ if context is None:
47
+ context = {}
48
+ quantity = context.get('quantity') or 1.0
49
+ pricelist = context.get('pricelist2', False)
50
+ if pricelist:
51
+ for id in ids:
52
+ try:
53
+ price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], id, quantity, context=context)[pricelist]
54
+ except:
55
+ price = 0.0
56
+ res[id] = price
57
+ for id in ids:
58
+ res.setdefault(id, 0.0)
59
+ return res
60
+
61
+ _columns = {
62
+ 'price2': fields.function(_product_price2, method=True, type='float', string='Pricelist', digits_compute=dp.get_precision('Sale Price')),
63
+ }
64
+
65
+ product_product()
66
+
67
+
68
+ class product_catalog_rep_qty(report_sxw.rml_parse):
69
+
70
+ def __init__(self, cr, uid, name, context):
71
+ super(product_catalog_rep_qty, self).__init__(cr, uid, name, context=context)
72
+ self.month = False
73
+ self.year = False
74
+
75
+ self.localcontext.update({
76
+ 'time': time,
77
+ 'get_categories': self.get_categories,
78
+ 'get_product': self.get_products,
79
+ 'get_pricelist_name': self.get_pricelist_name,
80
+ })
81
+
82
+ def setCat(self, cats):
83
+ lst = []
84
+ for cat in self.pool['product.category'].browse(self.cr, self.uid, cats):
85
+ if cat.id not in lst:
86
+ lst.append(cat.id)
87
+ for child_id in cat.child_id:
88
+ child_ids = self.setCat([child_id.id])
89
+ lst.extend(child_ids)
90
+ return lst
91
+
92
+ def get_pricelist_name(self, form, pricelist_id):
93
+ pricelist_data = self.pool['product.pricelist'].browse(self.cr, self.uid, form[pricelist_id][0])
94
+ return '%s (%s)' % (pricelist_data.name, pricelist_data.currency_id.name)
95
+
96
+ def get_products(self, c):
97
+ prod_tmpIDs = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', c), ])
98
+ prod_qty_ids = self.pool.get('product.product').search(self.cr, self.uid, [
99
+ ('product_tmpl_id', 'in', prod_tmpIDs),
100
+ ('sale_ok', '=', True),
101
+ ], order='name')
102
+ prod_ids = []
103
+ prod_qty_dicts = self.pool.get('product.product').read(self.cr, self.uid, prod_qty_ids, ['virtual_available'])
104
+ for prod_qty_dict in prod_qty_dicts:
105
+ if prod_qty_dict['virtual_available'] > 0:
106
+ prod_ids = prod_ids + [prod_qty_dict['id']]
107
+ price_context = {}
108
+ if self.pricelist_id not in ('', False, [], None):
109
+ price_context['pricelist'] = self.pricelist_id[0]
110
+ if self.pricelist_id2 not in ('', False, [], None):
111
+ price_context['pricelist2'] = self.pricelist_id2[0]
112
+ prods = self.pool.get('product.product').browse(self.cr, self.uid, prod_ids, context=price_context)
113
+ return prods
114
+
115
+ def get_categories(self, form):
116
+ category = form.get('category_id', False)
117
+ self.pricelist_id = form.get('pricelist_id', False)
118
+ self.pricelist_id2 = form.get('pricelist_id2', False)
119
+ lst = []
120
+ if not category:
121
+ return lst
122
+ lst = self.setCat([category])
123
+ cat_ids = self.pool.get('product.category').search(self.cr, self.uid, [('id', 'in', lst)])
124
+
125
+ tmpCat_ids = []
126
+ for cat in cat_ids:
127
+ prod_ids = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', cat)])
128
+ if len(prod_ids):
129
+ tmpCat_ids.append(cat)
130
+ cats = self.pool.get('product.category').browse(self.cr, self.uid, tmpCat_ids)
131
+ return_value = []
132
+ for catg in cats:
133
+ prod = self.get_products(catg.id)
134
+ if prod not in ('', False, [], None):
135
+ return_value = return_value + [catg]
136
+ return return_value
137
+
138
+ def _getProducts(self, category, lang):
139
+ prod_tmpIDs = self.pool.get('product.template').search(self.cr, self.uid, [('categ_id', '=', category)])
140
+ prod_ids = self.pool.get('product.product').search(self.cr, self.uid, [('product_tmpl_id', 'in', prod_tmpIDs)])
141
+ prods = self.pool.get('product.product').browse(self.cr, self.uid, prod_ids, context={'lang': lang})
142
+ return prods
143
+
144
+ def get_pricelist(self, a):
145
+ result = []
146
+ pooler.get_pool(self.cr.dbname).get('product.pricelist')
147
+ self.pricelist = a.get('pricelist_id', False)
148
+ return result
149
+
150
+ report_sxw.report_sxw('report.product.catalog.qty', 'product.product', 'addons/product_catalog_available/report/product_catalog_rep_qty.rml', parser=product_catalog_rep_qty, header=0)
151
+ report_sxw.report_sxw('report.product.catalog.qty2', 'product.product', 'addons/product_catalog_available/report/product_catalog_rep_qty2.rml', parser=product_catalog_rep_qty, header=0)
152
+
153
+ # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
pool/shard001/Python/0012548_popupmenu.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (C) 2011 Chris Dekter
4
+ #
5
+ # This program is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # This program is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU General Public License
16
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ import time, logging
19
+ from gi.repository import Gtk, Gdk
20
+
21
+ from autokey.configmanager import *
22
+ from autokey.model import Folder # TODO remove later
23
+
24
+ _logger = logging.getLogger("phrase-menu")
25
+
26
+ class PopupMenu(Gtk.Menu):
27
+ """
28
+ A popup menu that allows the user to select a phrase.
29
+ """
30
+
31
+ def __init__(self, service, folders=[], items=[], onDesktop=True, title=None):
32
+ Gtk.Menu.__init__(self)
33
+ #self.set_take_focus(ConfigManager.SETTINGS[MENU_TAKES_FOCUS])
34
+ self.__i = 1
35
+ self.service = service
36
+
37
+ if ConfigManager.SETTINGS[SORT_BY_USAGE_COUNT]:
38
+ _logger.debug("Sorting phrase menu by usage count")
39
+ folders.sort(key=lambda obj: obj.usageCount, reverse=True)
40
+ items.sort(key=lambda obj: obj.usageCount, reverse=True)
41
+ else:
42
+ _logger.debug("Sorting phrase menu by item name/title")
43
+ folders.sort(key=lambda obj: str(obj))
44
+ items.sort(key=lambda obj: str(obj))
45
+
46
+ if ConfigManager.SETTINGS[TRIGGER_BY_INITIAL]:
47
+ _logger.debug("Triggering menu item by first initial")
48
+ self.triggerInitial = 1
49
+ else:
50
+ _logger.debug("Triggering menu item by position in list")
51
+ self.triggerInitial = 0
52
+
53
+ if len(folders) == 1 and len(items) == 0 and onDesktop:
54
+ # Only one folder - create menu with just its folders and items
55
+ for folder in folders[0].folders:
56
+ menuItem = Gtk.MenuItem(label=self.__getMnemonic(folder.title, onDesktop))
57
+ menuItem.set_submenu(PopupMenu(service, folder.folders, folder.items, onDesktop))
58
+ menuItem.set_use_underline(True)
59
+ self.append(menuItem)
60
+
61
+ if len(folders[0].folders) > 0:
62
+ self.append(Gtk.SeparatorMenuItem())
63
+
64
+ self.__addItemsToSelf(folders[0].items, service, onDesktop)
65
+
66
+ else:
67
+ # Create phrase folder section
68
+ for folder in folders:
69
+ menuItem = Gtk.MenuItem(label=self.__getMnemonic(folder.title, onDesktop))
70
+ menuItem.set_submenu(PopupMenu(service, folder.folders, folder.items, False))
71
+ menuItem.set_use_underline(True)
72
+ self.append(menuItem)
73
+
74
+ if len(folders) > 0:
75
+ self.append(Gtk.SeparatorMenuItem())
76
+
77
+ self.__addItemsToSelf(items, service, onDesktop)
78
+
79
+ self.show_all()
80
+
81
+ def __getMnemonic(self, desc, onDesktop):
82
+ if 1 < 10 and '_' not in desc and onDesktop:
83
+ if self.triggerInitial:
84
+ ret = "%s" % (desc)
85
+ else:
86
+ ret = "_%d - %s" % (self.__i, desc)
87
+ self.__i += 1
88
+ return ret
89
+ else:
90
+ return desc
91
+
92
+ def show_on_desktop(self):
93
+ Gdk.threads_enter()
94
+ time.sleep(0.2)
95
+ self.popup(None, None, None, None, 1, 0)
96
+ Gdk.threads_leave()
97
+
98
+ def remove_from_desktop(self):
99
+ Gdk.threads_enter()
100
+ self.popdown()
101
+ Gdk.threads_leave()
102
+
103
+ def __addItemsToSelf(self, items, service, onDesktop):
104
+ # Create phrase section
105
+ if ConfigManager.SETTINGS[SORT_BY_USAGE_COUNT]:
106
+ items.sort(key=lambda obj: obj.usageCount, reverse=True)
107
+ else:
108
+ items.sort(key=lambda obj: str(obj))
109
+
110
+ i = 1
111
+ for item in items:
112
+ #if onDesktop:
113
+ # menuItem = Gtk.MenuItem(item.get_description(service.lastStackState), False)
114
+ #else:
115
+ menuItem = Gtk.MenuItem(label=self.__getMnemonic(item.description, onDesktop))
116
+ menuItem.connect("activate", self.__itemSelected, item)
117
+ menuItem.set_use_underline(True)
118
+ self.append(menuItem)
119
+
120
+ def __itemSelected(self, widget, item):
121
+ self.service.item_selected(item)
122
+
123
+ # Testing stuff - remove later ----
124
+
125
+ class MockPhrase:
126
+
127
+ def __init__(self, description):
128
+ self.description = description
129
+
130
+
131
+ class MockExpansionService:
132
+
133
+ def phrase_selected(self, event, phrase):
134
+ print phrase.description
135
+
136
+
137
+ if __name__ == "__main__":
138
+ Gdk.threads_init()
139
+
140
+ myFolder = PhraseFolder("Some phrases")
141
+ myFolder.add_phrase(MockPhrase("phrase 1"))
142
+ myFolder.add_phrase(MockPhrase("phrase 2"))
143
+ myFolder.add_phrase(MockPhrase("phrase 3"))
144
+
145
+ myPhrases = []
146
+ myPhrases.append(MockPhrase("phrase 1"))
147
+ myPhrases.append(MockPhrase("phrase 2"))
148
+ myPhrases.append(MockPhrase("phrase 3"))
149
+
150
+ menu = PhraseMenu(MockExpansionService(), [myFolder], myPhrases)
151
+ menu.show_on_desktop()
152
+
153
+ Gtk.main()
pool/shard001/Python/0012551_source_mapper.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2015 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
+ from collections import defaultdict
10
+
11
+ from pants.base.build_environment import get_buildroot
12
+ from pants.source.payload_fields import DeferredSourcesField
13
+
14
+
15
+ class SourceMapper(object):
16
+ """A utility for making a mapping of source files to targets that own them."""
17
+
18
+ def target_addresses_for_source(self, source):
19
+ raise NotImplementedError
20
+
21
+
22
+ class SpecSourceMapper(SourceMapper):
23
+ """
24
+ Uses sources specs to identify an owner target of a source.
25
+
26
+ Note: it doesn't check if a file exists.
27
+ """
28
+
29
+ def __init__(self, address_mapper, build_graph, stop_after_match=False):
30
+ """
31
+ :param AddressMapper address_mapper: An address mapper that can be used to populate the
32
+ `build_graph` with targets source mappings are needed for.
33
+ :param BuildGraph build_graph: The build graph to map sources from.
34
+ :param bool stop_after_match: If `True` a search will not traverse into parent directories once
35
+ an owner is identified.
36
+ """
37
+ self._stop_after_match = stop_after_match
38
+ self._build_graph = build_graph
39
+ self._address_mapper = address_mapper
40
+
41
+ def target_addresses_for_source(self, source):
42
+ result = []
43
+
44
+ root = get_buildroot()
45
+ path = source
46
+
47
+ # a top-level source has empty dirname, so do/while instead of straight while loop.
48
+ while path:
49
+ path = os.path.dirname(path)
50
+ candidate = self._address_mapper.get_build_file(relpath=path, must_exist=False)
51
+ if candidate.file_exists():
52
+ result.extend(list(self._find_targets_for_source(source, candidate.family())))
53
+ if self._stop_after_match and len(result) > 0:
54
+ break
55
+
56
+ return result
57
+
58
+ def _find_targets_for_source(self, source, build_files):
59
+ for build_file in build_files:
60
+ for address in self._address_mapper.addresses_in_spec_path(build_file.spec_path):
61
+ self._build_graph.inject_address_closure(address)
62
+ target = self._build_graph.get_target(address)
63
+ sources = target.payload.get_field('sources')
64
+ if sources and not isinstance(sources, DeferredSourcesField) and sources.matches(source):
65
+ yield address
66
+ if address.build_file.relpath == source:
67
+ yield address
68
+ if target.has_resources:
69
+ for resource in target.resources:
70
+ """
71
+ :type resource: pants.build_graph.resources.Resources
72
+ """
73
+ if resource.payload.sources.matches(source):
74
+ yield address
75
+
76
+
77
+ class LazySourceMapper(SourceMapper):
78
+ """
79
+ This attempts to avoid loading more than needed by lazily searching for and loading BUILD files
80
+ adjacent to or in parent directories (up to the buildroot) of a source to construct a (partial)
81
+ mapping of sources to owning targets.
82
+
83
+ If in stop-after-match mode, a search will not traverse into parent directories once an owner
84
+ is identified. THIS MAY FAIL TO FIND ADDITIONAL OWNERS in parent directories, or only find them
85
+ when other sources are also mapped first, which cause those owners to be loaded. Some repositories
86
+ may be able to use this to avoid expensive walks, but others may need to prefer correctness.
87
+
88
+ A LazySourceMapper reuses computed mappings and only searches a given path once as
89
+ populating the BuildGraph is expensive, so in general there should only be one instance of it.
90
+ """
91
+
92
+ def __init__(self, address_mapper, build_graph, stop_after_match=False):
93
+ """Initialize LazySourceMapper.
94
+
95
+ :param AddressMapper address_mapper: An address mapper that can be used to populate the
96
+ `build_graph` with targets source mappings are needed for.
97
+ :param BuildGraph build_graph: The build graph to map sources from.
98
+ :param bool stop_after_match: If `True` a search will not traverse into parent directories once
99
+ an owner is identified.
100
+ """
101
+ self._stop_after_match = stop_after_match
102
+ self._build_graph = build_graph
103
+ self._address_mapper = address_mapper
104
+ self._source_to_address = defaultdict(set)
105
+ self._mapped_paths = set()
106
+ self._searched_sources = set()
107
+
108
+ def _find_owners(self, source):
109
+ """Searches for BUILD files adjacent or above a source in the file hierarchy.
110
+ - Walks up the directory tree until it reaches a previously searched path.
111
+ - Stops after looking in the buildroot.
112
+
113
+ If self._stop_after_match is set, stops searching once a source is mapped, even if the parent
114
+ has yet to be searched. See class docstring for discussion.
115
+
116
+ :param str source: The source at which to start the search.
117
+ """
118
+ # Bail instantly if a source has already been searched
119
+ if source in self._searched_sources:
120
+ return
121
+ self._searched_sources.add(source)
122
+
123
+ root = get_buildroot()
124
+ path = os.path.dirname(source)
125
+
126
+ # a top-level source has empty dirname, so do/while instead of straight while loop.
127
+ walking = True
128
+ while walking:
129
+ # It is possible
130
+ if path not in self._mapped_paths:
131
+ candidate = self._address_mapper.get_build_file(relpath=path, must_exist=False)
132
+ if candidate.file_exists():
133
+ self._map_sources_from_family(candidate.family())
134
+ self._mapped_paths.add(path)
135
+ elif not self._stop_after_match:
136
+ # If not in stop-after-match mode, once a path is seen visited, all parents can be assumed.
137
+ return
138
+
139
+ # See class docstring
140
+ if self._stop_after_match and source in self._source_to_address:
141
+ return
142
+
143
+ walking = bool(path)
144
+ path = os.path.dirname(path)
145
+
146
+ def _map_sources_from_family(self, build_files):
147
+ """Populate mapping of source to owning addresses with targets from given BUILD files.
148
+
149
+ :param iterable<BuildFile> build_files: a family of BUILD files from which to map sources.
150
+ """
151
+ for build_file in build_files:
152
+ for address in self._address_mapper.addresses_in_spec_path(build_file.spec_path):
153
+ self._build_graph.inject_address_closure(address)
154
+ target = self._build_graph.get_target(address)
155
+ if target.has_resources:
156
+ for resource in target.resources:
157
+ for item in resource.sources_relative_to_buildroot():
158
+ self._source_to_address[item].add(target.address)
159
+
160
+ for target_source in target.sources_relative_to_buildroot():
161
+ self._source_to_address[target_source].add(target.address)
162
+ if not target.is_synthetic:
163
+ self._source_to_address[target.address.build_file.relpath].add(target.address)
164
+
165
+ def target_addresses_for_source(self, source):
166
+ """Attempt to find targets which own a source by searching up directory structure to buildroot.
167
+
168
+ :param string source: The source to look up.
169
+ """
170
+ self._find_owners(source)
171
+ return self._source_to_address[source]
pool/shard001/Python/0012552_managers.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # This module contains all the Proxy manager classes for use with the MIT
4
+ # Core Concept Catalog (MC3) Handcar service.
5
+
6
+ from dlkit.abstract_osid.proxy import managers as abc_proxy_managers
7
+ from ..osid import managers as osid_managers
8
+ from .. import profile
9
+ from ..primitives import Id, DisplayText, Type
10
+ from ..type.objects import TypeList
11
+ from ..osid.osid_errors import NullArgument, OperationFailed, Unimplemented
12
+
13
+
14
+ class ProxyProfile(abc_proxy_managers.ProxyProfile, osid_managers.OsidProfile):
15
+ """The ``ProxyProfile`` describes the interoperability among proxy services."""
16
+
17
+ def supports_proxy(self):
18
+ """Tests if a proxy session is supported.
19
+
20
+ :return: ``true`` if proxy is supported ``,`` ``false`` otherwise
21
+ :rtype: ``boolean``
22
+
23
+ *compliance: mandatory -- This method must be implemented.*
24
+
25
+ """
26
+ return 'supports_proxy' in profile.SUPPORTS
27
+
28
+ def get_proxy_record_types(self):
29
+ """Gets the supported ``Proxy`` record interface types.
30
+
31
+ :return: a list containing the supported ``Proxy`` record types
32
+ :rtype: ``osid.type.TypeList``
33
+
34
+ *compliance: mandatory -- This method must be implemented.*
35
+
36
+ """
37
+ from ..type.objects import TypeList
38
+ return TypeList([])
39
+
40
+ proxy_record_types = property(fget=get_proxy_record_types)
41
+
42
+ def supports_proxy_record_type(self, proxy_record_type):
43
+ """Tests if the given ``Proxy`` record interface type is supported.
44
+
45
+ :param proxy_record_type: a ``Type`` indicating a ``Proxy`` record type
46
+ :type proxy_record_type: ``osid.type.Type``
47
+ :return: ``true`` if the given type is supported, ``false`` otherwise
48
+ :rtype: ``boolean``
49
+ :raise: ``NullArgument`` -- ``proxy_record_type`` is ``null``
50
+
51
+ *compliance: mandatory -- This method must be implemented.*
52
+
53
+ """
54
+ return proxy_record_type in self.get_proxy_record_types()
55
+
56
+ def get_proxy_condition_record_types(self):
57
+ """Gets the supported ``ProxyCondition`` record interface types.
58
+
59
+ :return: a list containing the supported ``ProxyCondition`` record types
60
+ :rtype: ``osid.type.TypeList``
61
+
62
+
63
+ *compliance: mandatory -- This method must be implemented.*
64
+
65
+ """
66
+ return TypeList(profile.PROXY_CONDITION_RECORD_TYPES)
67
+
68
+ proxy_condition_record_types = property(fget=get_proxy_condition_record_types)
69
+
70
+ def supports_proxy_condition_record_type(self, proxy_condition_record_type):
71
+ """Tests if the given ``ProxyCondition`` record interface type is supported.
72
+
73
+ :param proxy_condition_record_type: a ``Type`` indicating a ``ProxyCondition`` record type
74
+ :type proxy_condition_record_type: ``osid.type.Type``
75
+ :return: ``true`` if the given type is supported, ``false`` otherwise
76
+ :rtype: ``boolean``
77
+ :raise: ``NullArgument`` -- ``proxy_condition_record_type`` is ``null``
78
+
79
+ *compliance: mandatory -- This method must be implemented.*
80
+
81
+ """
82
+ return proxy_condition_record_type in self.get_proxy_condition_record_types()
83
+
84
+
85
+ class ProxyManager(abc_proxy_managers.ProxyManager, osid_managers.OsidManager, ProxyProfile):
86
+ """The proxy manager provides access to proxy sessions and provides interoperability tests for various aspects of this service.
87
+
88
+ The sessions included in this manager are:
89
+
90
+ * ``ProxySession:`` a session to acquire proxy interfaces
91
+ """
92
+
93
+ def get_proxy_session(self):
94
+ """Gets a ``ProxySession`` which is responsible for acquiring authentication credentials on behalf of a service client.
95
+
96
+ :return: a proxy session for this service
97
+ :rtype: ``osid.proxy.ProxySession``
98
+ :raise: ``OperationFailed`` -- unable to complete request
99
+ :raise: ``Unimplemented`` -- ``supports_proxy()`` is ``false``
100
+
101
+ *compliance: optional -- This method must be implemented if ``supports_proxy()`` is ``true``.*
102
+
103
+ """
104
+ if not self.supports_proxy():
105
+ raise Unimplemented()
106
+ try:
107
+ from . import sessions
108
+ except ImportError:
109
+ raise # OperationFailed()
110
+ try:
111
+ session = sessions.ProxySession()
112
+ except AttributeError:
113
+ raise # OperationFailed()
114
+ return session
115
+
116
+ proxy_session = property(fget=get_proxy_session)
117
+
118
+
119
+ class ProxyProxyManager(abc_proxy_managers.ProxyProxyManager, osid_managers.OsidProxyManager, ProxyProfile):
120
+ """The proxy proxy manager provides access to proxy sessions and provides interoperability tests for various aspects of this service.
121
+
122
+ Methods in this manager support the passing of a ``Proxy``. The
123
+ sessions included in this manager are:
124
+
125
+ * ``ProxySession:`` a session to acquire proxies
126
+ """
127
+
128
+ def get_proxy_session(self, proxy):
129
+ """Gets the ``OsidSession`` associated with the ``ProxySession`` using the supplied ``Proxy``.
130
+
131
+ :param proxy: proxy
132
+ :type proxy: ``osid.proxy.Proxy``
133
+ :return: a ``ProxySession``
134
+ :rtype: ``osid.proxy.ProxySession``
135
+ :raise: ``NullArgument`` -- ``proxy`` is ``null``
136
+ :raise: ``OperationFailed`` -- unable to complete request
137
+ :raise: ``Unimplemented`` -- ``supports_proxy()`` is ``false``
138
+
139
+ *compliance: optional -- This method must be implemented if ``supports_proxy()`` is ``true``.*
140
+
141
+ """
142
+ raise Unimplemented()
pool/shard001/Python/0012554_notifications.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Mirantis Inc.
2
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
3
+ # not use this file except in compliance with the License. You may obtain
4
+ # a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11
+ # License for the specific language governing permissions and limitations
12
+ # under the License.
13
+
14
+ from oslo.config import cfg
15
+ import oslo.messaging
16
+
17
+ from ceilometer import plugin
18
+ from ceilometer import sample
19
+
20
+ OPTS = [
21
+ cfg.StrOpt('keystone_control_exchange',
22
+ default='keystone',
23
+ help="Exchange name for Keystone notifications."),
24
+ ]
25
+
26
+
27
+ cfg.CONF.register_opts(OPTS)
28
+
29
+ SERVICE = 'identity'
30
+
31
+
32
+ class _Base(plugin.NotificationBase):
33
+ """Convert identity notification into Samples."""
34
+
35
+ resource_type = None
36
+ resource_name = None
37
+
38
+ @staticmethod
39
+ def get_targets(conf):
40
+ """Return a sequence of oslo.messaging.Target
41
+
42
+ Sequence defining the exchange and topics to be connected for this
43
+ plugin.
44
+ """
45
+ return [oslo.messaging.Target(topic=topic,
46
+ exchange=conf.keystone_control_exchange)
47
+ for topic in conf.notification_topics]
48
+
49
+
50
+ class IdentityCRUD(_Base):
51
+ def process_notification(self, message):
52
+ yield sample.Sample.from_notification(
53
+ name=message['event_type'],
54
+ type=sample.TYPE_DELTA,
55
+ unit=self.resource_type,
56
+ volume=1,
57
+ resource_id=message['payload']['resource_info'],
58
+ user_id=None,
59
+ project_id=None,
60
+ message=message)
61
+
62
+
63
+ class User(IdentityCRUD):
64
+
65
+ resource_type = 'user'
66
+ resource_name = '%s.%s' % (SERVICE, resource_type)
67
+
68
+ @property
69
+ def event_types(self):
70
+ return ['%s.*' % self.resource_name]
71
+
72
+
73
+ class Group(IdentityCRUD):
74
+
75
+ resource_type = 'group'
76
+ resource_name = '%s.%s' % (SERVICE, resource_type)
77
+
78
+ @property
79
+ def event_types(self):
80
+ return ['%s.*' % self.resource_name]
81
+
82
+
83
+ class Project(IdentityCRUD):
84
+
85
+ resource_type = 'project'
86
+ resource_name = '%s.%s' % (SERVICE, resource_type)
87
+
88
+ @property
89
+ def event_types(self):
90
+ return ['%s.*' % self.resource_name]
91
+
92
+
93
+ class Role(IdentityCRUD):
94
+
95
+ resource_type = 'role'
96
+ resource_name = '%s.%s' % (SERVICE, resource_type)
97
+
98
+ @property
99
+ def event_types(self):
100
+ return ['%s.*' % self.resource_name]
101
+
102
+
103
+ class Trust(IdentityCRUD):
104
+
105
+ resource_type = 'OS-TRUST:trust'
106
+ resource_name = '%s.%s' % (SERVICE, resource_type)
107
+
108
+ @property
109
+ def event_types(self):
110
+ return [
111
+ '%s.created' % self.resource_name,
112
+ '%s.deleted' % self.resource_name,
113
+ ]
114
+
115
+
116
+ class Authenticate(_Base):
117
+ """Convert identity authentication notifications into Samples."""
118
+
119
+ resource_type = 'authenticate'
120
+ event_name = '%s.%s' % (SERVICE, resource_type)
121
+
122
+ def process_notification(self, message):
123
+ outcome = message['payload']['outcome']
124
+ meter_name = '%s.%s.%s' % (SERVICE, self.resource_type, outcome)
125
+
126
+ yield sample.Sample.from_notification(
127
+ name=meter_name,
128
+ type=sample.TYPE_DELTA,
129
+ unit='user',
130
+ volume=1,
131
+ resource_id=message['payload']['initiator']['id'],
132
+ user_id=message['payload']['initiator']['id'],
133
+ project_id=None,
134
+ message=message)
135
+
136
+ @property
137
+ def event_types(self):
138
+ return [self.event_name]
pool/shard001/Python/0012559_tests.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf import settings
2
+ from django.db import connection, DEFAULT_DB_ALIAS
3
+ from django.test import TestCase, skipUnlessDBFeature
4
+ from django.utils import functional
5
+
6
+ from models import Reporter, Article
7
+
8
+ #
9
+ # The introspection module is optional, so methods tested here might raise
10
+ # NotImplementedError. This is perfectly acceptable behavior for the backend
11
+ # in question, but the tests need to handle this without failing. Ideally we'd
12
+ # skip these tests, but until #4788 is done we'll just ignore them.
13
+ #
14
+ # The easiest way to accomplish this is to decorate every test case with a
15
+ # wrapper that ignores the exception.
16
+ #
17
+ # The metaclass is just for fun.
18
+ #
19
+
20
+ def ignore_not_implemented(func):
21
+ def _inner(*args, **kwargs):
22
+ try:
23
+ return func(*args, **kwargs)
24
+ except NotImplementedError:
25
+ return None
26
+ functional.update_wrapper(_inner, func)
27
+ return _inner
28
+
29
+ class IgnoreNotimplementedError(type):
30
+ def __new__(cls, name, bases, attrs):
31
+ for k,v in attrs.items():
32
+ if k.startswith('test'):
33
+ attrs[k] = ignore_not_implemented(v)
34
+ return type.__new__(cls, name, bases, attrs)
35
+
36
+ class IntrospectionTests(TestCase):
37
+ __metaclass__ = IgnoreNotimplementedError
38
+
39
+ def test_table_names(self):
40
+ tl = connection.introspection.table_names()
41
+ self.assert_(Reporter._meta.db_table in tl,
42
+ "'%s' isn't in table_list()." % Reporter._meta.db_table)
43
+ self.assert_(Article._meta.db_table in tl,
44
+ "'%s' isn't in table_list()." % Article._meta.db_table)
45
+
46
+ def test_django_table_names(self):
47
+ cursor = connection.cursor()
48
+ cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);');
49
+ tl = connection.introspection.django_table_names()
50
+ cursor.execute("DROP TABLE django_ixn_test_table;")
51
+ self.assert_('django_ixn_testcase_table' not in tl,
52
+ "django_table_names() returned a non-Django table")
53
+
54
+ def test_installed_models(self):
55
+ tables = [Article._meta.db_table, Reporter._meta.db_table]
56
+ models = connection.introspection.installed_models(tables)
57
+ self.assertEqual(models, set([Article, Reporter]))
58
+
59
+ def test_sequence_list(self):
60
+ sequences = connection.introspection.sequence_list()
61
+ expected = {'table': Reporter._meta.db_table, 'column': 'id'}
62
+ self.assert_(expected in sequences,
63
+ 'Reporter sequence not found in sequence_list()')
64
+
65
+ def test_get_table_description_names(self):
66
+ cursor = connection.cursor()
67
+ desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
68
+ self.assertEqual([r[0] for r in desc],
69
+ [f.column for f in Reporter._meta.fields])
70
+
71
+ def test_get_table_description_types(self):
72
+ cursor = connection.cursor()
73
+ desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
74
+ self.assertEqual(
75
+ [datatype(r[1], r) for r in desc],
76
+ ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
77
+ )
78
+
79
+ # Regression test for #9991 - 'real' types in postgres
80
+ @skipUnlessDBFeature('has_real_datatype')
81
+ def test_postgresql_real_type(self):
82
+ cursor = connection.cursor()
83
+ cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
84
+ desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
85
+ cursor.execute('DROP TABLE django_ixn_real_test_table;')
86
+ self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
87
+
88
+ def test_get_relations(self):
89
+ cursor = connection.cursor()
90
+ relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
91
+
92
+ # Older versions of MySQL don't have the chops to report on this stuff,
93
+ # so just skip it if no relations come back. If they do, though, we
94
+ # should test that the response is correct.
95
+ if relations:
96
+ # That's {field_index: (field_index_other_table, other_table)}
97
+ self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
98
+
99
+ def test_get_indexes(self):
100
+ cursor = connection.cursor()
101
+ indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
102
+ self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
103
+
104
+
105
+ def datatype(dbtype, description):
106
+ """Helper to convert a data type into a string."""
107
+ dt = connection.introspection.get_field_type(dbtype, description)
108
+ if type(dt) is tuple:
109
+ return dt[0]
110
+ else:
111
+ return dt
pool/shard001/Python/0012562_message_parser.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #
3
+ # Copyright 2007 Google Inc.
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
+
19
+ """Describe ProtoRPC Messages in JSON Schema.
20
+
21
+ Add protorpc.message subclasses to MessageTypeToJsonSchema and get a JSON
22
+ Schema description of all the messages.
23
+ """
24
+
25
+
26
+ import re
27
+
28
+ from protorpc import message_types
29
+ from protorpc import messages
30
+
31
+ __all__ = ['MessageTypeToJsonSchema']
32
+
33
+
34
+ class MessageTypeToJsonSchema(object):
35
+ """Describe ProtoRPC messages in JSON Schema.
36
+
37
+ Add protorpc.message subclasses to MessageTypeToJsonSchema and get a JSON
38
+ Schema description of all the messages. MessageTypeToJsonSchema handles
39
+ all the types of fields that can appear in a message.
40
+ """
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+ __FIELD_TO_SCHEMA_TYPE_MAP = {
49
+ messages.IntegerField: {messages.Variant.INT32: ('integer', 'int32'),
50
+ messages.Variant.INT64: ('string', 'int64'),
51
+ messages.Variant.UINT32: ('integer', 'uint32'),
52
+ messages.Variant.UINT64: ('string', 'uint64'),
53
+ messages.Variant.SINT32: ('integer', 'int32'),
54
+ messages.Variant.SINT64: ('string', 'int64'),
55
+ None: ('integer', 'int64')},
56
+ messages.FloatField: {messages.Variant.FLOAT: ('number', 'float'),
57
+ messages.Variant.DOUBLE: ('number', 'double'),
58
+ None: ('number', 'float')},
59
+ messages.BooleanField: ('boolean', None),
60
+ messages.BytesField: ('string', 'byte'),
61
+ message_types.DateTimeField: ('string', 'date-time'),
62
+ messages.StringField: ('string', None),
63
+ messages.MessageField: ('object', None),
64
+ messages.EnumField: ('string', None),
65
+ }
66
+
67
+ __DEFAULT_SCHEMA_TYPE = ('string', None)
68
+
69
+ def __init__(self):
70
+
71
+ self.__schemas = {}
72
+
73
+
74
+ self.__normalized_names = {}
75
+
76
+ def add_message(self, message_type):
77
+ """Add a new message.
78
+
79
+ Args:
80
+ message_type: protorpc.message.Message class to be parsed.
81
+
82
+ Returns:
83
+ string, The JSON Schema id.
84
+
85
+ Raises:
86
+ KeyError if the Schema id for this message_type would collide with the
87
+ Schema id of a different message_type that was already added.
88
+ """
89
+ name = self.__normalized_name(message_type)
90
+ if name not in self.__schemas:
91
+
92
+ self.__schemas[name] = None
93
+ schema = self.__message_to_schema(message_type)
94
+ self.__schemas[name] = schema
95
+ return name
96
+
97
+ def ref_for_message_type(self, message_type):
98
+ """Returns the JSON Schema id for the given message.
99
+
100
+ Args:
101
+ message_type: protorpc.message.Message class to be parsed.
102
+
103
+ Returns:
104
+ string, The JSON Schema id.
105
+
106
+ Raises:
107
+ KeyError: if the message hasn't been parsed via add_message().
108
+ """
109
+ name = self.__normalized_name(message_type)
110
+ if name not in self.__schemas:
111
+ raise KeyError('Message has not been parsed: %s', name)
112
+ return name
113
+
114
+ def schemas(self):
115
+ """Returns the JSON Schema of all the messages.
116
+
117
+ Returns:
118
+ object: JSON Schema description of all messages.
119
+ """
120
+ return self.__schemas.copy()
121
+
122
+ def __normalized_name(self, message_type):
123
+ """Normalized schema name.
124
+
125
+ Generate a normalized schema name, taking the class name and stripping out
126
+ everything but alphanumerics, and camel casing the remaining words.
127
+ A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
128
+
129
+ Args:
130
+ message_type: protorpc.message.Message class being parsed.
131
+
132
+ Returns:
133
+ A string, the normalized schema name.
134
+
135
+ Raises:
136
+ KeyError if a collision is found between normalized names.
137
+ """
138
+
139
+
140
+ name = message_type.definition_name()
141
+
142
+ split_name = re.split(r'[^0-9a-zA-Z]', name)
143
+ normalized = ''.join(
144
+ part[0].upper() + part[1:] for part in split_name if part)
145
+
146
+ previous = self.__normalized_names.get(normalized)
147
+ if previous:
148
+ if previous != name:
149
+ raise KeyError('Both %s and %s normalize to the same schema name: %s' %
150
+ (name, previous, normalized))
151
+ else:
152
+ self.__normalized_names[normalized] = name
153
+
154
+ return normalized
155
+
156
+ def __message_to_schema(self, message_type):
157
+ """Parse a single message into JSON Schema.
158
+
159
+ Will recursively descend the message structure
160
+ and also parse other messages references via MessageFields.
161
+
162
+ Args:
163
+ message_type: protorpc.messages.Message class to parse.
164
+
165
+ Returns:
166
+ An object representation of the schema.
167
+ """
168
+ name = self.__normalized_name(message_type)
169
+ schema = {
170
+ 'id': name,
171
+ 'type': 'object',
172
+ }
173
+ if message_type.__doc__:
174
+ schema['description'] = message_type.__doc__
175
+ properties = {}
176
+ for field in message_type.all_fields():
177
+ descriptor = {}
178
+
179
+
180
+
181
+ type_info = {}
182
+
183
+ if type(field) == messages.MessageField:
184
+ field_type = field.type().__class__
185
+ type_info['$ref'] = self.add_message(field_type)
186
+ if field_type.__doc__:
187
+ descriptor['description'] = field_type.__doc__
188
+ else:
189
+ schema_type = self.__FIELD_TO_SCHEMA_TYPE_MAP.get(
190
+ type(field), self.__DEFAULT_SCHEMA_TYPE)
191
+
192
+
193
+ if isinstance(schema_type, dict):
194
+ variant_map = schema_type
195
+ variant = getattr(field, 'variant', None)
196
+ if variant in variant_map:
197
+ schema_type = variant_map[variant]
198
+ else:
199
+
200
+ schema_type = variant_map[None]
201
+ type_info['type'] = schema_type[0]
202
+ if schema_type[1]:
203
+ type_info['format'] = schema_type[1]
204
+
205
+ if type(field) == messages.EnumField:
206
+ sorted_enums = sorted([enum_info for enum_info in field.type],
207
+ key=lambda enum_info: enum_info.number)
208
+ type_info['enum'] = [enum_info.name for enum_info in sorted_enums]
209
+
210
+ if field.required:
211
+ descriptor['required'] = True
212
+
213
+ if field.default:
214
+ if type(field) == messages.EnumField:
215
+ descriptor['default'] = str(field.default)
216
+ else:
217
+ descriptor['default'] = field.default
218
+
219
+ if field.repeated:
220
+ descriptor['items'] = type_info
221
+ descriptor['type'] = 'array'
222
+ else:
223
+ descriptor.update(type_info)
224
+
225
+ properties[field.name] = descriptor
226
+
227
+ schema['properties'] = properties
228
+
229
+ return schema
pool/shard001/Python/0012567_config.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This file contains all of the configuration values for the application.
17
+ Update this file with the values for your specific Google Cloud project.
18
+ You can create and manage projects at https://console.developers.google.com
19
+ """
20
+
21
+ import os
22
+
23
+ # The secret key is used by Flask to encrypt session cookies.
24
+ SECRET_KEY = 'secret'
25
+
26
+ # There are three different ways to store the data in the application.
27
+ # You can choose 'datastore', 'cloudsql', or 'mongodb'. Be sure to
28
+ # configure the respective settings for the one you choose below.
29
+ # You do not have to configure the other data backends. If unsure, choose
30
+ # 'datastore' as it does not require any additional configuration.
31
+ DATA_BACKEND = 'datastore'
32
+
33
+ # Google Cloud Project ID. This can be found on the 'Overview' page at
34
+ # https://console.developers.google.com
35
+ PROJECT_ID = 'your-project-id'
36
+
37
+ # CloudSQL & SQLAlchemy configuration
38
+ # Replace the following values the respective values of your Cloud SQL
39
+ # instance.
40
+ CLOUDSQL_USER = 'root'
41
+ CLOUDSQL_PASSWORD = 'your-cloudsql-password'
42
+ CLOUDSQL_DATABASE = 'bookshelf'
43
+ # Set this value to the Cloud SQL connection name, e.g.
44
+ # "project:region:cloudsql-instance".
45
+ # You must also update the value in app.yaml.
46
+ CLOUDSQL_CONNECTION_NAME = 'your-cloudsql-connection-name'
47
+
48
+ # The CloudSQL proxy is used locally to connect to the cloudsql instance.
49
+ # To start the proxy, use:
50
+ #
51
+ # $ cloud_sql_proxy -instances=your-connection-name=tcp:3306
52
+ #
53
+ # Alternatively, you could use a local MySQL instance for testing.
54
+ LOCAL_SQLALCHEMY_DATABASE_URI = (
55
+ 'mysql+pymysql://{user}:{password}@localhost/{database}').format(
56
+ user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD,
57
+ database=CLOUDSQL_DATABASE)
58
+
59
+ # When running on App Engine a unix socket is used to connect to the cloudsql
60
+ # instance.
61
+ LIVE_SQLALCHEMY_DATABASE_URI = (
62
+ 'mysql+pymysql://{user}:{password}@localhost/{database}'
63
+ '?unix_socket=/cloudsql/{connection_name}').format(
64
+ user=CLOUDSQL_USER, password=CLOUDSQL_PASSWORD,
65
+ database=CLOUDSQL_DATABASE, connection_name=CLOUDSQL_CONNECTION_NAME)
66
+
67
+ if os.environ.get('GAE_APPENGINE_HOSTNAME'):
68
+ SQLALCHEMY_DATABASE_URI = LIVE_SQLALCHEMY_DATABASE_URI
69
+ else:
70
+ SQLALCHEMY_DATABASE_URI = LOCAL_SQLALCHEMY_DATABASE_URI
71
+
72
+ # Mongo configuration
73
+ # If using mongolab, the connection URI is available from the mongolab control
74
+ # panel. If self-hosting on compute engine, replace the values below.
75
+ MONGO_URI = \
76
+ 'mongodb://user:password@host:27017/database'
pool/shard001/Python/0012570_admin.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import flask
2
+ from flask import request
3
+ from app import app, db
4
+ from themes import ThemeManager
5
+ from app.models import User, Post, Category
6
+ from app.forms import LoginForm, PostForm, CategoryForm
7
+ from app.manager import ModelManager
8
+
9
+ Theme = ThemeManager.get_theme(app.config['THEME'])
10
+
11
+ @app.route('/admin/')
12
+ def admin_index():
13
+ user = User.get_current_user()
14
+ if user is None:
15
+ return flask.redirect(flask.url_for('admin_login'))
16
+ try:
17
+ page = int(request.args.get('page', 1))
18
+ except ValueError:
19
+ page = 1
20
+
21
+ return flask.render_template(Theme.get_template(page='admin_index'),
22
+ manager=ModelManager,
23
+ page=page)
24
+
25
+
26
+ @app.route('/admin/login/', methods=['GET', 'POST'])
27
+ def admin_login():
28
+ user = User.get_current_user()
29
+ if user is not None:
30
+ return flask.redirect(flask.url_for('admin_index'))
31
+
32
+ login_form = LoginForm()
33
+
34
+ if request.method == 'POST' and login_form.validate_on_submit():
35
+ # Actually check if we have such a user in the db
36
+ existing_user, error = User.authenticate(login_form.email.data,
37
+ login_form.password.data)
38
+
39
+ if existing_user:
40
+ existing_user.login()
41
+ return flask.redirect(flask.url_for('admin_index'))
42
+
43
+ login_form.email.errors.append('Invalid username or password')
44
+
45
+ return flask.render_template(Theme.get_template(page='admin_login'),
46
+ manager=ModelManager, form=login_form)
47
+
48
+
49
+ @app.route('/admin/logout/', methods=['GET', 'POST'])
50
+ def admin_logout():
51
+ User.logout()
52
+ return flask.redirect(flask.url_for('admin_login'))
53
+
54
+
55
+ @app.route('/admin/categories', methods=['GET', 'POST'])
56
+ def admin_categories():
57
+ category_form = CategoryForm()
58
+
59
+ if request.method == 'POST' and category_form.validate_on_submit():
60
+ category = Category(name=request.form['category_name'])
61
+
62
+ db.session.add(category)
63
+ db.session.commit()
64
+ db.session.flush()
65
+ flask.flash('Your category has been created', 'success')
66
+
67
+ return flask.render_template(Theme.get_template(page='admin_categories'),
68
+ manager=ModelManager, form=category_form)
69
+
70
+
71
+ @app.route('/admin/post/add/', methods=['GET', 'POST'])
72
+ def admin_add_post():
73
+ form = PostForm()
74
+
75
+ if request.method == 'POST' and form.validate_on_submit():
76
+ post = Post(title=request.form['title'],
77
+ content=request.form['content'],
78
+ summary=request.form['summary'])
79
+
80
+ post.author_id = ModelManager.current_user().id
81
+ post.category_id = form.category.data
82
+
83
+ post.before_save()
84
+
85
+ db.session.add(post)
86
+ db.session.commit()
87
+ db.session.flush()
88
+ flask.flash('Your post has been created', 'success')
89
+
90
+ return flask.render_template(Theme.get_template(page='admin_add_post'),
91
+ manager=ModelManager,
92
+ post_form=form)
93
+
94
+ @app.route('/admin/post/<id>/', methods=['GET', 'POST'])
95
+ def admin_detail_post(id):
96
+ return flask.render_template(Theme.get_template(page='admin_detail_post'),
97
+ manager=ModelManager,
98
+ post_id=id)
pool/shard001/Python/0012576_objects.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError
2
+ from queries import Queries
3
+ from object import Object
4
+
5
+
6
+ class Objects(Queries):
7
+ def __repr__(self):
8
+ return self._execute_query()
9
+
10
+ def __unicode__(self):
11
+ return self._execute_query()
12
+
13
+ def __str__(self):
14
+ return str(self._execute_query())
15
+
16
+ def __len__(self):
17
+ return len(self._execute_query())
18
+
19
+ def __getitem__(self, item):
20
+ return self._execute_query()[item]
21
+
22
+ def __bool__(self):
23
+ return self._execute_query()
24
+
25
+ def __nonzero__(self):
26
+ return bool(self._execute_query())
27
+
28
+ def __contains__(self, item):
29
+ return item in self._execute_query()
30
+
31
+ def __iter__(self):
32
+ for item in self._execute_query():
33
+ yield item
34
+
35
+ def __getattr__(self, item):
36
+ structure = self._storage_read()['structure']
37
+ if item in structure:
38
+ return self._execute_query().__getattribute__(item)
39
+ else:
40
+ raise AttributeError('Object has no attribute \'%s\'' % item)
41
+
42
+ def __setattr__(self, key, value):
43
+ if key == 'id':
44
+ raise AttributeError('\'id\' is non-editable field')
45
+ else:
46
+ return super(Objects, self).__setattr__(key, value)
47
+
48
+ def create(self, **kwargs):
49
+ """
50
+ Create row in the storage (method return's created object)
51
+ :param kwargs:
52
+ :return:
53
+ """
54
+ storage = self._storage_read()
55
+ kwargs['id'] = storage['last_id'] + 1
56
+ row = list()
57
+
58
+ for k, v in kwargs.items():
59
+ if k not in storage['structure']:
60
+ structure = str(', '.join(storage['structure'][1:]))
61
+ raise FieldError('The column "%s" is absent in storage structure! '
62
+ 'You have: %s' % (k, structure))
63
+
64
+ for field in storage['structure']:
65
+ if field not in kwargs.keys():
66
+ raise FieldError('Field "%s" is missed!' % field)
67
+ else:
68
+ row.append(kwargs[field])
69
+
70
+ storage = self._storage_read()
71
+ storage['data'].append(row)
72
+ storage['last_id'] += 1
73
+
74
+ self._storage_write(storage)
75
+ return Object(self.request, self.session_name, *row)
76
+
77
+ def clear(self):
78
+ self._storage_clear()
79
+
80
+ def get(self, **kwargs):
81
+ """
82
+ Get row from storage by fields values
83
+ :param kwargs:
84
+ :return:
85
+ """
86
+ self.filter(**kwargs)
87
+ result = self._execute_query()
88
+ if len(result) == 0:
89
+ raise ObjectDoesNotExist
90
+ elif len(result) > 1:
91
+ raise MultipleObjectsReturned('Change your get-query or use filter.')
92
+
93
+ return result[0]
94
+
95
+ def all(self):
96
+ """
97
+ Get all rows from storage
98
+ :return:
99
+ """
100
+ self._add_query('all')
101
+ return self
102
+
103
+ def filter(self, **rules):
104
+ """
105
+ Get filtered rows from storage by fields values
106
+ :param rules:
107
+ :return:
108
+ """
109
+ self._add_query('filter', rules)
110
+ return self
111
+
112
+ def exclude(self, **rules):
113
+ """
114
+ Get filtered rows from storage by exclude fields values
115
+ :param rules:
116
+ :return:
117
+ """
118
+ self._add_query('exclude', rules)
119
+ return self
120
+
121
+ def order_by(self, *rules):
122
+ """
123
+ Query response ordering
124
+ :return:
125
+ """
126
+ self._add_query('order_by', rules)
127
+ return self
128
+
129
+ def count(self):
130
+ """
131
+ Get rows count
132
+ :return:
133
+ """
134
+ self._add_query('count')
135
+ return self
136
+
137
+ def exists(self):
138
+ """
139
+ Check element existing
140
+ :return:
141
+ """
142
+ self._add_query('exists')
143
+ return self
pool/shard001/Python/0012577_test_dbapi_compliance.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Cloudera Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ """
17
+ This test module simply wraps _dbapi20_tests.py, which ensure that our
18
+ PEP 249 implementation is compliant.
19
+ """
20
+
21
+
22
+ from __future__ import absolute_import, print_function
23
+
24
+ import pytest
25
+
26
+ import impala.dbapi
27
+ from impala.tests.util import ImpylaTestEnv
28
+ from impala.util import (
29
+ _random_id, force_drop_impala_database, force_drop_hive_database)
30
+ # must import the module, rather than the class, per comment in module
31
+ from impala.tests import _dbapi20_tests
32
+
33
+
34
+ ENV = ImpylaTestEnv()
35
+ tmp_db = _random_id('tmp_impyla_dbapi_')
36
+ hive = ENV.auth_mech == 'PLAIN'
37
+
38
+
39
+ @pytest.mark.connect
40
+ class ImpalaDBAPI20Test(_dbapi20_tests.DatabaseAPI20Test):
41
+ driver = impala.dbapi
42
+ connect_kw_args = {'host': ENV.host,
43
+ 'port': ENV.port,
44
+ 'auth_mechanism': ENV.auth_mech,
45
+ 'database': tmp_db}
46
+
47
+ ddl1 = 'create table {0}booze (name string)'.format(
48
+ _dbapi20_tests.DatabaseAPI20Test.table_prefix)
49
+ ddl2 = 'create table {0}barflys (name string)'.format(
50
+ _dbapi20_tests.DatabaseAPI20Test.table_prefix)
51
+
52
+ @classmethod
53
+ def setUpClass(cls):
54
+ con = cls.driver.connect(host=ENV.host, port=ENV.port,
55
+ auth_mechanism=ENV.auth_mech)
56
+ cur = con.cursor()
57
+ cur.execute('CREATE DATABASE {0}'.format(tmp_db))
58
+ cur.close()
59
+ con.close()
60
+
61
+ @classmethod
62
+ def tearDownClass(cls):
63
+ con = cls.driver.connect(host=ENV.host, port=ENV.port,
64
+ auth_mechanism=ENV.auth_mech)
65
+ cur = con.cursor()
66
+ if hive:
67
+ force_drop_hive_database(cur, tmp_db)
68
+ else:
69
+ force_drop_impala_database(cur, tmp_db)
70
+ cur.close()
71
+ con.close()
72
+
73
+ def test_nextset(self):
74
+ pass
75
+
76
+ def test_setoutputsize(self):
77
+ pass
78
+
79
+ # The following tests fail against Hive. We override them so we can skip on
80
+ # Hive, and otherwise execute the superclass version.
81
+
82
+ HIVE_STRING_ESCAPE_ERROR = 'HIVE-11723'
83
+
84
+ @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR)
85
+ def test_execute(self):
86
+ super(ImpalaDBAPI20Test, self).test_execute()
87
+
88
+ @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR)
89
+ def test_executemany(self):
90
+ super(ImpalaDBAPI20Test, self).test_executemany()
91
+
92
+ @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR)
93
+ def test_setinputsizes(self):
94
+ super(ImpalaDBAPI20Test, self).test_setinputsizes()
95
+
96
+ @pytest.mark.skipif(hive, reason=HIVE_STRING_ESCAPE_ERROR)
97
+ def test_setoutputsize_basic(self):
98
+ super(ImpalaDBAPI20Test, self).test_setoutputsize_basic()
pool/shard001/Python/0012583_0002_set_site_domain_and_name.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import unicode_literals
3
+
4
+ from django.conf import settings
5
+ from django.db import models, migrations
6
+
7
+
8
+ def update_site_forward(apps, schema_editor):
9
+ """Set site domain and name."""
10
+ Site = apps.get_model("sites", "Site")
11
+ Site.objects.update_or_create(
12
+ id=settings.SITE_ID,
13
+ defaults={
14
+ "domain": "appagoo.com",
15
+ "name": "Appagoo"
16
+ }
17
+ )
18
+
19
+
20
+ def update_site_backward(apps, schema_editor):
21
+ """Revert site domain and name to default."""
22
+ Site = apps.get_model("sites", "Site")
23
+ Site.objects.update_or_create(
24
+ id=settings.SITE_ID,
25
+ defaults={
26
+ "domain": "example.com",
27
+ "name": "example.com"
28
+ }
29
+ )
30
+
31
+
32
+ class Migration(migrations.Migration):
33
+
34
+ dependencies = [
35
+ ('sites', '0001_initial'),
36
+ ]
37
+
38
+ operations = [
39
+ migrations.RunPython(update_site_forward, update_site_backward),
40
+ ]
pool/shard001/Python/0012590_bugcve.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2009 Canonical Ltd. This software is licensed under the
2
+ # GNU Affero General Public License version 3 (see the file LICENSE).
3
+
4
+ __metaclass__ = type
5
+ __all__ = ['BugCve']
6
+
7
+ from sqlobject import ForeignKey
8
+ from zope.interface import implements
9
+
10
+ from lp.bugs.interfaces.bugcve import IBugCve
11
+ from lp.services.database.sqlbase import SQLBase
12
+
13
+
14
+ class BugCve(SQLBase):
15
+ """A table linking bugs and CVE entries."""
16
+
17
+ implements(IBugCve)
18
+
19
+ _table = 'BugCve'
20
+
21
+ # db field names
22
+ bug = ForeignKey(dbName='bug', foreignKey='Bug', notNull=True)
23
+ cve = ForeignKey(dbName='cve', foreignKey='Cve', notNull=True)
24
+
25
+ @property
26
+ def target(self):
27
+ """See IBugLink."""
28
+ return self.cve
pool/shard001/Python/0012597_main.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import collections
5
+ import os
6
+ import StringIO
7
+
8
+ import jinja2
9
+ import webapp2
10
+ from PIL import Image
11
+
12
+ from google.appengine.api import memcache
13
+ from google.appengine.api import users
14
+ from google.appengine.ext import ndb
15
+
16
+ import meme
17
+
18
+
19
+ TODO = None
20
+
21
+ JINJA_ENV = jinja2.Environment(
22
+ loader=jinja2.FileSystemLoader(
23
+ os.path.join(os.path.dirname(__file__), 'templates')),
24
+ extensions=['jinja2.ext.autoescape'])
25
+
26
+ MEME_TEMPLATES = collections.OrderedDict([
27
+ ('happyboy', 'happyboy.jpeg'),
28
+ ('rapperboy', 'rapperboy.jpeg'),
29
+ ('realappengine', 'realappengine.jpeg'),
30
+ ('shrugging', 'shrugging.jpeg'),
31
+ ('bathing', 'bathing.jpeg'),
32
+ ])
33
+
34
+ DEFAULT_TEMPLATE = 'happyboy.jpeg'
35
+
36
+ IMAGE_DIR = 'images'
37
+
38
+ MEME_FONTS = collections.OrderedDict([
39
+ ('mikachan', 'mikachan.ttf'),
40
+ ('FreeSerif', 'FreeSerif.ttf'),
41
+ ])
42
+
43
+ DEFAULT_FONT = 'FreeSerif.ttf'
44
+
45
+ FONT_DIR = 'fonts'
46
+
47
+ THUMBNAIL_SIZE = (400, 400)
48
+
49
+ PAGE_SIZE = 40
50
+
51
+ MEMCACHE_RECENT_KEY = 'recent'
52
+
53
+
54
+ def get_login_logout_context(target_url):
55
+ """Returns nickname, link url and link text for the common_header.html."""
56
+ user = users.get_current_user()
57
+ if user:
58
+ nickname = user.nickname()
59
+ link_text = 'Logout'
60
+ link_url = users.create_logout_url(target_url)
61
+ else:
62
+ nickname = 'Anonymous user'
63
+ link_text = 'Login'
64
+ link_url = users.create_login_url(target_url)
65
+ return nickname, link_url, link_text
66
+
67
+
68
+ class MainHandler(webapp2.RequestHandler):
69
+ """A handler for showing an HTML form."""
70
+
71
+ def get(self):
72
+ """Render an HTML form for creating Memes."""
73
+ template = JINJA_ENV.get_template('index.html')
74
+ nickname, link_url, link_text = get_login_logout_context(
75
+ self.request.uri)
76
+ context = {
77
+ 'templates': MEME_TEMPLATES,
78
+ 'fonts': MEME_FONTS,
79
+ 'nickname': nickname,
80
+ 'link_text': link_text,
81
+ 'link_url': link_url
82
+ }
83
+ self.response.out.write(template.render(context))
84
+
85
+
86
+ class ImageHandler(webapp2.RequestHandler):
87
+ """A handler for rendering and saving Memes."""
88
+
89
+ def render_meme(self):
90
+ """Renders an image with given HTTP parameters.
91
+
92
+ Returns:
93
+ A rendered Image object.
94
+ """
95
+ meme_template = self.request.get('meme_template')
96
+ image = Image.open(os.path.join(IMAGE_DIR,
97
+ MEME_TEMPLATES.get(meme_template, DEFAULT_TEMPLATE)))
98
+ meme_font = self.request.get('meme_font')
99
+ font_file = os.path.join(FONT_DIR,
100
+ MEME_FONTS.get(meme_font, DEFAULT_FONT))
101
+ upper_text = self.request.get('upper_text')
102
+ upper_text_align = self.request.get('upper_text_align', meme.MIDDLE)
103
+ middle_text = self.request.get('middle_text')
104
+ middle_text_align = self.request.get('middle_text_align', meme.MIDDLE)
105
+ lower_text = self.request.get('lower_text')
106
+ lower_text_align = self.request.get('lower_text_align', meme.MIDDLE)
107
+ if upper_text:
108
+ meme.draw_text(image, meme.TOP, upper_text_align, upper_text,
109
+ font_file=font_file)
110
+ if middle_text:
111
+ meme.draw_text(image, meme.MIDDLE, middle_text_align, middle_text,
112
+ font_file=font_file)
113
+ if lower_text:
114
+ meme.draw_text(image, meme.BOTTOM, lower_text_align, lower_text,
115
+ font_file=font_file)
116
+ return image
117
+
118
+ def get(self):
119
+ """A handler for rendering a preview image."""
120
+ image = self.render_meme()
121
+ self.response.headers['Content-Type'] = 'image/jpg'
122
+ image.save(self.response.out, 'JPEG')
123
+
124
+ def post(self):
125
+ """A handler for save the meme."""
126
+ image = self.render_meme()
127
+ new_meme = meme.Meme()
128
+ user = users.get_current_user()
129
+ if user:
130
+ new_meme.owner = user
131
+ output = StringIO.StringIO()
132
+ thumbnail_output = StringIO.StringIO()
133
+ image.save(output, "JPEG")
134
+ image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)
135
+ image.save(thumbnail_output, "JPEG")
136
+ new_meme.image = output.getvalue()
137
+ new_meme.thumbnail = thumbnail_output.getvalue()
138
+ output.close()
139
+ thumbnail_output.close()
140
+ new_meme.put()
141
+ # step-3
142
+ # It is important to delete the cache here for recent query.
143
+ # Otherwise, the 'Recent' page will keep serving an old list.
144
+ memcache.delete(MEMCACHE_RECENT_KEY)
145
+ self.redirect("/meme/{}".format(new_meme.key.id()), abort=True)
146
+
147
+
148
+ class MemeHandler(webapp2.RequestHandler):
149
+ """A handler for rendering an HTML page of a particular meme."""
150
+
151
+ def get(self, meme_id):
152
+ """Renders an HTML page of a Meme with a given id.
153
+
154
+ Raises a 404 error when entity not found.
155
+
156
+ Args:
157
+ meme_id: id of Meme entity extracted from the URL path.
158
+ """
159
+ target = meme.Meme.get_by_id(long(meme_id))
160
+ if target is None:
161
+ self.abort(404)
162
+ nickname, link_url, link_text = get_login_logout_context(
163
+ self.request.uri)
164
+ template = JINJA_ENV.get_template('meme.html')
165
+ if target.owner:
166
+ owner_nickname = target.owner.nickname()
167
+ else:
168
+ owner_nickname = 'Anonymous user'
169
+ context = {
170
+ 'nickname': nickname,
171
+ 'link_url': link_url,
172
+ 'link_text': link_text,
173
+ 'meme_owner': owner_nickname,
174
+ 'meme_id': target.key.id(),
175
+ 'meme_created_date': target.created_at,
176
+ }
177
+ self.response.write(template.render(context))
178
+
179
+
180
+ class MemeImageHandler(webapp2.RequestHandler):
181
+ """A handler for serving an image of a particular meme."""
182
+
183
+ def get(self, mode, meme_id):
184
+ """Serves an image of a particular meme.
185
+
186
+ Raises a 404 error when entity not found.
187
+
188
+ Args:
189
+ mode: 'image' or 'thumbnail', extracted from the URL path.
190
+ meme_id: id of Meme entity extracted from the URL path.
191
+ """
192
+ target = meme.Meme.get_by_id(long(meme_id))
193
+ if target is None:
194
+ self.abort(404)
195
+ self.response.headers['Content-Type'] = 'image/jpeg'
196
+ if mode == 'image':
197
+ self.response.write(target.image)
198
+ else:
199
+ self.response.write(target.thumbnail)
200
+
201
+
202
+ class MemeListingHandler(webapp2.RequestHandler):
203
+ """A handler for listing recent memes."""
204
+
205
+ def get(self, mode):
206
+ """Display a list of memes according to given conditions.
207
+
208
+ The condition is given by the URL. Currently only 'recent' and
209
+ 'mine' are implemented.
210
+ """
211
+ if mode == 'recent':
212
+ meme_keys = memcache.get(MEMCACHE_RECENT_KEY)
213
+ if meme_keys is not None:
214
+ memes = ndb.get_multi(meme_keys)
215
+ else:
216
+ # step-3
217
+ # Complete the query object. We want meme.Meme
218
+ # objects ordered by the created_at in a descending
219
+ # order.
220
+ query = meme.Meme.query().order(-meme.Meme.created_at)
221
+ memes = query.fetch(PAGE_SIZE)
222
+ memcache.set(MEMCACHE_RECENT_KEY, [m.key for m in memes])
223
+ title = 'Recent memes'
224
+ elif mode == 'mine':
225
+ user = users.get_current_user()
226
+ if user is None:
227
+ self.redirect(users.create_login_url(self.request.uri),
228
+ abort=True)
229
+ query = meme.Meme.query(meme.Meme.owner==user)\
230
+ .order(-meme.Meme.created_at)
231
+ title = 'Your memes'
232
+ memes = query.fetch(PAGE_SIZE)
233
+ nickname, link_url, link_text = get_login_logout_context(
234
+ self.request.uri)
235
+ template = JINJA_ENV.get_template('list_meme.html')
236
+ context = {
237
+ 'title': title,
238
+ 'nickname': nickname,
239
+ 'link_url': link_url,
240
+ 'link_text': link_text,
241
+ 'memes': memes,
242
+ }
243
+ self.response.write(template.render(context))
244
+
245
+
246
+ APPLICATION = webapp2.WSGIApplication([
247
+ ('/', MainHandler),
248
+ ('/preview', ImageHandler),
249
+ ('/create_meme', ImageHandler),
250
+ ('/meme/(\d+)', MemeHandler),
251
+ ('/(image|thumbnail)/(\d+)', MemeImageHandler),
252
+ ('/(recent|mine)', MemeListingHandler),
253
+ ], debug=True)
pool/shard001/Python/0012600_0001_initial.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by Django 1.11 on 2017-11-09 17:54
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
+ ('core', '0011_text_format'),
17
+ ]
18
+
19
+ operations = [
20
+ migrations.CreateModel(
21
+ name='Achievement',
22
+ fields=[
23
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
24
+ ('name', models.CharField(max_length=255)),
25
+ ('description', models.TextField(blank=True)),
26
+ ('points', models.PositiveIntegerField()),
27
+ ('icon_path', models.CharField(max_length=255)),
28
+ ('created_at', models.DateTimeField(auto_now_add=True)),
29
+ ('updated_at', models.DateTimeField(auto_now=True)),
30
+ ('amount', models.IntegerField(blank=True, default=None, null=True)),
31
+ ('author', models.CharField(blank=True, default=None, max_length=255, null=True)),
32
+ ('origin', models.CharField(blank=True, default=None, max_length=255, null=True)),
33
+ ('contest', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Contest')),
34
+ ('problem', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Problem')),
35
+ ],
36
+ options={
37
+ 'db_table': 'achievements',
38
+ 'get_latest_by': 'created_at',
39
+ },
40
+ ),
41
+ migrations.CreateModel(
42
+ name='UserAchievement',
43
+ fields=[
44
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
45
+ ('earned_at', models.DateTimeField(blank=True, null=True)),
46
+ ('created_at', models.DateTimeField(auto_now_add=True)),
47
+ ('updated_at', models.DateTimeField(auto_now=True)),
48
+ ('achievement', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='achievements.Achievement')),
49
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
50
+ ],
51
+ options={
52
+ 'db_table': 'user_achievements',
53
+ 'get_latest_by': 'created_at',
54
+ },
55
+ ),
56
+ ]
pool/shard001/Python/0012607_wsgi.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os,sys
2
+ virtenv = os.path.expanduser('~') + '/virtenv/'
3
+ virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
4
+ try:
5
+ exec(open(virtualenv).read(), dict(__file__=virtualenv))
6
+ except IOError:
7
+ pass
8
+
9
+ sys.path.append(os.path.expanduser('~'))
10
+ sys.path.append(os.path.expanduser('~') + '/ROOT/')
11
+
12
+ from werkzeug.serving import run_simple
13
+ from werkzeug.wsgi import DispatcherMiddleware
14
+
15
+ from quokka import create_app, create_api
16
+
17
+ application = DispatcherMiddleware(create_app(), {
18
+ '/api': create_api()
19
+ })
20
+
21
+ if __name__ == "__main__":
22
+ run_simple(
23
+ '0.0.0.0',
24
+ 5000,
25
+ application,
26
+ use_reloader=True,
27
+ use_debugger=True
28
+ )
pool/shard001/Python/0012608_init__.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##############################################################################
2
+ #
3
+ # Copyright (c) 2001, 2002 Zope Corporation and Contributors.
4
+ # All Rights Reserved.
5
+ #
6
+ # This software is subject to the provisions of the Zope Public License,
7
+ # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8
+ # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9
+ # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10
+ # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11
+ # FOR A PARTICULAR PURPOSE.
12
+ #
13
+ ##############################################################################
14
+ """Unique id utility.
15
+
16
+ This utility assigns unique integer ids to objects and allows lookups
17
+ by object and by id.
18
+
19
+ This functionality can be used in cataloging.
20
+
21
+ $Id: __init__.py 69786 2006-08-26 18:06:12Z philikon $
22
+ """
23
+ import random
24
+ from BTrees import IOBTree, OIBTree
25
+ from ZODB.interfaces import IConnection
26
+ from persistent import Persistent
27
+
28
+ from zope.event import notify
29
+ from zope.interface import implements
30
+ from zope.security.proxy import removeSecurityProxy
31
+ from zope.location.interfaces import ILocation
32
+ from zope.component import adapter, getAllUtilitiesRegisteredFor
33
+
34
+ from zope.app.container.interfaces import IObjectRemovedEvent
35
+ from zope.app.container.interfaces import IObjectAddedEvent
36
+ from zope.app.container.contained import Contained
37
+ from zope.app.keyreference.interfaces import IKeyReference, NotYet
38
+
39
+ from zope.app.intid.interfaces import IIntIds
40
+ from zope.app.intid.interfaces import IntIdRemovedEvent
41
+ from zope.app.intid.interfaces import IntIdAddedEvent
42
+
43
+ class IntIds(Persistent, Contained):
44
+ """This utility provides a two way mapping between objects and
45
+ integer ids.
46
+
47
+ IKeyReferences to objects are stored in the indexes.
48
+ """
49
+ implements(IIntIds)
50
+
51
+ _v_nextid = None
52
+
53
+ _randrange = random.randrange
54
+
55
+ def __init__(self):
56
+ self.ids = OIBTree.OIBTree()
57
+ self.refs = IOBTree.IOBTree()
58
+
59
+ def __len__(self):
60
+ return len(self.ids)
61
+
62
+ def items(self):
63
+ return list(self.refs.items())
64
+
65
+ def __iter__(self):
66
+ return self.refs.iterkeys()
67
+
68
+ def getObject(self, id):
69
+ return self.refs[id]()
70
+
71
+ def queryObject(self, id, default=None):
72
+ r = self.refs.get(id)
73
+ if r is not None:
74
+ return r()
75
+ return default
76
+
77
+ def getId(self, ob):
78
+ try:
79
+ key = IKeyReference(ob)
80
+ except (NotYet, TypeError):
81
+ raise KeyError(ob)
82
+
83
+ try:
84
+ return self.ids[key]
85
+ except KeyError:
86
+ raise KeyError(ob)
87
+
88
+ def queryId(self, ob, default=None):
89
+ try:
90
+ return self.getId(ob)
91
+ except KeyError:
92
+ return default
93
+
94
+ def _generateId(self):
95
+ """Generate an id which is not yet taken.
96
+
97
+ This tries to allocate sequential ids so they fall into the
98
+ same BTree bucket, and randomizes if it stumbles upon a
99
+ used one.
100
+ """
101
+ while True:
102
+ if self._v_nextid is None:
103
+ self._v_nextid = self._randrange(0, 2**31)
104
+ uid = self._v_nextid
105
+ self._v_nextid += 1
106
+ if uid not in self.refs:
107
+ return uid
108
+ self._v_nextid = None
109
+
110
+ def register(self, ob):
111
+ # Note that we'll still need to keep this proxy removal.
112
+ ob = removeSecurityProxy(ob)
113
+ key = IKeyReference(ob)
114
+
115
+ if key in self.ids:
116
+ return self.ids[key]
117
+ uid = self._generateId()
118
+ self.refs[uid] = key
119
+ self.ids[key] = uid
120
+ return uid
121
+
122
+ def unregister(self, ob):
123
+ # Note that we'll still need to keep this proxy removal.
124
+ ob = removeSecurityProxy(ob)
125
+ key = IKeyReference(ob, None)
126
+ if key is None:
127
+ return
128
+
129
+ uid = self.ids[key]
130
+ del self.refs[uid]
131
+ del self.ids[key]
132
+
133
+
134
+ @adapter(ILocation, IObjectRemovedEvent)
135
+ def removeIntIdSubscriber(ob, event):
136
+ """A subscriber to ObjectRemovedEvent
137
+
138
+ Removes the unique ids registered for the object in all the unique
139
+ id utilities.
140
+ """
141
+ utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds))
142
+ if utilities:
143
+ key = IKeyReference(ob, None)
144
+ # Register only objects that adapt to key reference
145
+ if key is not None:
146
+ # Notify the catalogs that this object is about to be removed.
147
+ notify(IntIdRemovedEvent(ob, event))
148
+ for utility in utilities:
149
+ try:
150
+ utility.unregister(key)
151
+ except KeyError:
152
+ pass
153
+
154
+ @adapter(ILocation, IObjectAddedEvent)
155
+ def addIntIdSubscriber(ob, event):
156
+ """A subscriber to ObjectAddedEvent
157
+
158
+ Registers the object added in all unique id utilities and fires
159
+ an event for the catalogs.
160
+ """
161
+ utilities = tuple(getAllUtilitiesRegisteredFor(IIntIds))
162
+ if utilities: # assert that there are any utilites
163
+ key = IKeyReference(ob, None)
164
+ # Register only objects that adapt to key reference
165
+ if key is not None:
166
+ for utility in utilities:
167
+ utility.register(key)
168
+ # Notify the catalogs that this object was added.
169
+ notify(IntIdAddedEvent(ob, event))
170
+
171
+ # BBB
172
+ UniqueIdUtility = IntIds
173
+ import zope.app.keyreference.persistent
174
+ ReferenceToPersistent = (
175
+ zope.app.keyreference.persistent.KeyReferenceToPersistent)
176
+ import sys
177
+ sys.modules['zope.app.uniqueid'] = sys.modules['zope.app.intid']
178
+ del sys
pool/shard001/Python/0012611_arguments.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ if len(sys.argv) > 1:
4
+
5
+ print('The following arguments were provided: {}'.format(*sys.argv[1:]))
6
+
7
+ for c, arg in enumerate(sys.argv[1:]):
8
+
9
+ description = input('Please give the description of input {0} with value {1}: '.format(c, arg))
10
+ print('input number {0}, with value {1} is a {2} '.format(str(c), arg, description))
11
+ else:
12
+ print('No argument was given to me, byebye now.')
13
+
pool/shard001/Python/0012613_test_offload.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import unittest
4
+
5
+ from framework import VppTestCase, VppTestRunner
6
+ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
7
+
8
+
9
+ class TestOffload(VppTestCase):
10
+ """ Offload Unit Test Cases """
11
+
12
+ @classmethod
13
+ def setUpClass(cls):
14
+ super(TestOffload, cls).setUpClass()
15
+
16
+ @classmethod
17
+ def tearDownClass(cls):
18
+ super(TestOffload, cls).tearDownClass()
19
+
20
+ def setUp(self):
21
+ super(TestOffload, self).setUp()
22
+
23
+ def tearDown(self):
24
+ super(TestOffload, self).tearDown()
25
+
26
+ def test_offload_unittest(self):
27
+ """ Checksum Offload Test """
28
+ cmds = ["loop create",
29
+ "set int ip address loop0 11.22.33.1/24",
30
+ "set int state loop0 up",
31
+ "loop create",
32
+ "set int ip address loop1 11.22.34.1/24",
33
+ "set int state loop1 up",
34
+ "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44",
35
+ "packet-generator new {\n"
36
+ " name s0\n"
37
+ " limit 100\n"
38
+ " size 128-128\n"
39
+ " interface loop0\n"
40
+ " tx-interface loop1\n"
41
+ " node loop1-output\n"
42
+ " buffer-flags ip4 offload\n"
43
+ " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n"
44
+ " data {\n"
45
+ " IP4: 1.2.3 -> dead.0000.0001\n"
46
+ " UDP: 11.22.33.44 -> 11.22.34.44\n"
47
+ " ttl 2 checksum 13\n"
48
+ " UDP: 1234 -> 2345\n"
49
+ " checksum 11\n"
50
+ " incrementing 114\n"
51
+ " }\n"
52
+ "}",
53
+ "trace add pg-input 1",
54
+ "pa en",
55
+ "show error"]
56
+
57
+ for cmd in cmds:
58
+ r = self.vapi.cli_return_response(cmd)
59
+ if r.retval != 0:
60
+ if hasattr(r, 'reply'):
61
+ self.logger.info(cmd + " FAIL reply " + r.reply)
62
+ else:
63
+ self.logger.info(cmd + " FAIL retval " + str(r.retval))
64
+
65
+ r = self.vapi.cli_return_response("show trace")
66
+ self.assertTrue(r.retval == 0)
67
+ self.assertTrue(hasattr(r, 'reply'))
68
+ rv = r.reply
69
+ look_here = rv.find('ethernet-input')
70
+ self.assertFalse(look_here == -1)
71
+ bad_checksum_index = rv[look_here:].find('should be')
72
+ self.assertTrue(bad_checksum_index == -1)
73
+
74
+ if __name__ == '__main__':
75
+ unittest.main(testRunner=VppTestRunner)
pool/shard001/Python/0012614_SetJobLimit.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###############################################################
2
+ # Imports
3
+ ###############################################################
4
+ from Deadline.Events import *
5
+ from Deadline.Scripting import *
6
+
7
+
8
+ ###############################################################
9
+ # This is the function called by Deadline to get an instance of the Draft event listener.
10
+ ###############################################################
11
+ def GetDeadlineEventListener():
12
+ return SetJobLimitListener()
13
+
14
+
15
+ def CleanupDeadlineEventListener(eventListener):
16
+ eventListener.Cleanup()
17
+
18
+
19
+ ###############################################################
20
+ # The event listener class.
21
+ ###############################################################
22
+ class SetJobLimitListener (DeadlineEventListener):
23
+ def __init__(self):
24
+ self.OnJobSubmittedCallback += self.OnJobSubmitted
25
+
26
+ def Cleanup(self):
27
+ del self.OnJobSubmittedCallback
28
+
29
+ def OnJobSubmitted(self, job):
30
+ limitNames = self.GetConfigEntry("JobLimits").split(',')
31
+
32
+ for limitName in job.JobLimitGroups:
33
+ if limitName.lower() not in limitNames:
34
+ limitNames.append(limitName)
35
+
36
+ job.SetJobLimitGroups(limitNames)
37
+ RepositoryUtils.SaveJob(job)
pool/shard001/Python/0012615_lib.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import array
2
+ from itertools import zip_longest
3
+
4
+ def grouper(iterable, n, fillvalue=None):
5
+ '''Collect data into fixed-length chunks or blocks
6
+
7
+ grouper([1,2,3,4,5], 2, 0) --> [1,2] [3,4] [5,0]
8
+ '''
9
+ args = [iter(iterable)] * n
10
+ return zip_longest(*args, fillvalue=fillvalue)
11
+
12
+ def arrayify(source_list):
13
+ dest_array = array.array('I')
14
+ dests_array = array.array('I')
15
+ j = 0
16
+ for i in range(len(source_list)):
17
+ items = source_list[i]
18
+ dest_array.append(j)
19
+ dests_array.append(len(items))
20
+ dests_array.extend(items)
21
+ j += 1 + len(items)
22
+ return (dest_array, dests_array)
23
+
24
+ def make_inverse(mapping): return dict((y,x) for (x,y) in mapping.items())
25
+ def make_array_inverse(arraylist): return dict((x,n) for (n,x) in enumerate(arraylist))
26
+
pool/shard001/Python/0012627_torrent.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This program is free software: you can redistribute it and/or modify
2
+ # it under the terms of the GNU General Public License as published by
3
+ # the Free Software Foundation, either version 3 of the License, or
4
+ # (at your option) any later version.
5
+ #
6
+ # This program is distributed in the hope that it will be useful
7
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ # GNU General Public License for more details
10
+ # http://www.gnu.org/licenses/gpl-3.0.txt
11
+
12
+ from . import _mixin as mixin
13
+ from .. import CmdError
14
+ from ... import objects
15
+ from ...completion import candidates
16
+ from ..base import torrent as base
17
+ from ._table import TERMSIZE, print_table
18
+
19
+ from ...logging import make_logger # isort:skip
20
+ log = make_logger(__name__)
21
+
22
+
23
+ class AddTorrentsCmd(base.AddTorrentsCmdbase,
24
+ mixin.make_request):
25
+ provides = {'cli'}
26
+
27
+ @classmethod
28
+ def completion_candidates_posargs(cls, args):
29
+ """Complete positional arguments"""
30
+ # Use current working directory as base
31
+ return candidates.fs_path(args.curarg.before_cursor,
32
+ base='.',
33
+ glob=r'*.torrent')
34
+
35
+
36
+ class TorrentDetailsCmd(base.TorrentDetailsCmdbase,
37
+ mixin.make_request, mixin.select_torrents):
38
+ provides = {'cli'}
39
+
40
+ async def display_details(self, torrent_id):
41
+ from ...views.details import SECTIONS
42
+ needed_keys = set(('name',))
43
+ for _section in SECTIONS:
44
+ for _item in _section['items']:
45
+ needed_keys.update(_item.needed_keys)
46
+
47
+ response = await self.make_request(
48
+ objects.srvapi.torrent.torrents((torrent_id,), keys=needed_keys),
49
+ quiet=True)
50
+ if not response.torrents:
51
+ raise CmdError()
52
+ else:
53
+ torrent = response.torrents[0]
54
+
55
+ if TERMSIZE.columns is None:
56
+ self._machine_readable(torrent)
57
+ else:
58
+ self._human_readable(torrent)
59
+
60
+ def _human_readable(self, torrent):
61
+ from ...views.details import SECTIONS
62
+
63
+ label_width = max(len(item.label)
64
+ for section in SECTIONS
65
+ for item in section['items'])
66
+
67
+ for i,section in enumerate(SECTIONS):
68
+ if i != 0:
69
+ print() # Newline between sections
70
+ print('\033[1m' + section['title'].upper() + '\033[0m')
71
+ for item in section['items']:
72
+ print(' %s: %s' % (item.label.rjust(label_width), item.human_readable(torrent)))
73
+
74
+ def _machine_readable(self, torrent):
75
+ from ...views.details import SECTIONS
76
+ for section in SECTIONS:
77
+ for item in section['items']:
78
+ print('%s\t%s' % (item.label.lower(), item.machine_readable(torrent)))
79
+
80
+
81
+ class ListTorrentsCmd(base.ListTorrentsCmdbase,
82
+ mixin.make_request, mixin.select_torrents,
83
+ mixin.only_supported_columns):
84
+ provides = {'cli'}
85
+
86
+ async def make_torrent_list(self, tfilter, sort, columns):
87
+ from ...views.torrent import COLUMNS as TORRENT_COLUMNS
88
+
89
+ # Remove columns that aren't supported by CLI interface (e.g. 'marked')
90
+ columns = self.only_supported_columns(columns, TORRENT_COLUMNS)
91
+
92
+ # Get needed keys
93
+ if tfilter is None:
94
+ keys = set(sort.needed_keys)
95
+ else:
96
+ keys = set(sort.needed_keys + tfilter.needed_keys)
97
+
98
+ # Get wanted torrents and sort them
99
+ for colname in columns:
100
+ keys.update(TORRENT_COLUMNS[colname].needed_keys)
101
+ response = await self.make_request(
102
+ objects.srvapi.torrent.torrents(tfilter, keys=keys),
103
+ quiet=True)
104
+ torrents = sort.apply(response.torrents)
105
+
106
+ # Show table of found torrents
107
+ if torrents:
108
+ print_table(torrents, columns, TORRENT_COLUMNS)
109
+ else:
110
+ raise CmdError()
111
+
112
+
113
+ class TorrentMagnetURICmd(base.TorrentMagnetURICmdbase,
114
+ mixin.select_torrents):
115
+ provides = {'cli'}
116
+
117
+ def display_uris(self, uris):
118
+ for uri in uris:
119
+ print(uri)
120
+
121
+
122
+ class MoveTorrentsCmd(base.MoveTorrentsCmdbase,
123
+ mixin.make_request, mixin.select_torrents):
124
+ provides = {'cli'}
125
+
126
+ @classmethod
127
+ async def completion_candidates_posargs(cls, args):
128
+ """Complete positional arguments"""
129
+ if args.curarg_index == 1:
130
+ log.debug('Getting torrent filter candidates from %r', candidates.torrent_filter)
131
+ return await candidates.torrent_filter(args.curarg)
132
+ elif args.curarg_index == 2:
133
+ return candidates.fs_path(args.curarg.before_cursor,
134
+ base=objects.cfg['srv.path.complete'],
135
+ directories_only=True)
136
+
137
+
138
+ class RemoveTorrentsCmd(base.RemoveTorrentsCmdbase,
139
+ mixin.make_request, mixin.select_torrents, mixin.ask_yes_no):
140
+ provides = {'cli'}
141
+
142
+ async def show_list_of_hits(self, tfilter):
143
+ import sys
144
+ if sys.stdout.isatty():
145
+ cmd = 'ls --sort name %s' % tfilter
146
+ await objects.cmdmgr.run_async(cmd)
147
+
148
+ def remove_list_of_hits(self):
149
+ pass
150
+
151
+
152
+ class RenameCmd(base.RenameCmdbase,
153
+ mixin.make_request, mixin.select_torrents, mixin.select_files):
154
+ provides = {'cli'}
155
+
156
+
157
+ class StartTorrentsCmd(base.StartTorrentsCmdbase,
158
+ mixin.make_request, mixin.select_torrents):
159
+ provides = {'cli'}
160
+
161
+
162
+ class StopTorrentsCmd(base.StopTorrentsCmdbase,
163
+ mixin.make_request, mixin.select_torrents):
164
+ provides = {'cli'}
165
+
166
+
167
+ class VerifyTorrentsCmd(base.VerifyTorrentsCmdbase,
168
+ mixin.make_request, mixin.select_torrents):
169
+ provides = {'cli'}
pool/shard001/Python/0012628_border_overaly.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ===============================================================================
2
+ # Copyright 2011 Jake Ross
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ===============================================================================
16
+
17
+
18
+ # ============= enthought library imports =======================
19
+ from __future__ import absolute_import
20
+ from chaco.api import AbstractOverlay
21
+
22
+
23
+ # ============= standard library imports ========================
24
+
25
+ # ============= local library imports ==========================
26
+
27
+
28
+ class BorderOverlay(AbstractOverlay):
29
+ def overlay(self, component, gc, view_bounds=None, mode="normal"):
30
+ """ """
31
+ # print component.outer_bounds, component.outer_position
32
+ gc.set_stroke_color((0, 1, 0))
33
+ x, y = component.outer_position
34
+ w, h = component.outer_bounds
35
+ gc.rect(x - 3, y - 3, w + 6, h + 6)
36
+
37
+ gc.stroke_path()
38
+
39
+
40
+ # ============= views ===================================
41
+ # ============= EOF ====================================
pool/shard001/Python/0012635_users.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Views related to Users, Auth & UserProfiles
2
+ #
3
+ # This file is part of thesubnetwork
4
+ # (parts of the file based on my.gpodder.org)
5
+ #
6
+ # thesubnetwork is free software: you can redistribute it and/or modify it
7
+ # under the terms of the GNU Affero General Public License as published by
8
+ # the Free Software Foundation, either version 3 of the License, or (at your
9
+ # option) any later version.
10
+ #
11
+ # thesubnetwork is distributed in the hope that it will be useful, but
12
+ # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13
+ # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
14
+ # License for more details.
15
+ #
16
+ # You should have received a copy of the GNU Affero General Public License
17
+ # along with thesubnetwork. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ from django.shortcuts import render_to_response
21
+ from django.http import HttpResponseRedirect
22
+ from django.contrib.auth import authenticate, login
23
+ from django.contrib.auth.models import User
24
+ from django.contrib.auth.decorators import login_required
25
+ from django.template.defaultfilters import slugify
26
+ from django.template import RequestContext
27
+ from thesubnetwork.users.models import UserProfile
28
+ from thesubnetwork.web.forms import RestorePasswordForm
29
+ from django.contrib.sites.models import Site
30
+ from django.conf import settings
31
+ from thesubnetwork.decorators import manual_gc, allowed_methods
32
+ from django.utils.translation import ugettext as _
33
+ from registration.models import RegistrationProfile
34
+ import string
35
+ import random
36
+
37
+
38
+ from thesubnetwork.web.forms import ResendActivationForm
39
+
40
+ def login_user(request):
41
+ # Do not show login page for already-logged-in users
42
+ if request.user.is_authenticated():
43
+ return HttpResponseRedirect("/")
44
+
45
+ if 'user' not in request.POST or 'pwd' not in request.POST:
46
+ if request.GET.get('restore_password', False):
47
+ form = RestorePasswordForm()
48
+ else:
49
+ form = None
50
+
51
+ return render_to_response('login.html', {
52
+ 'url': Site.objects.get_current(),
53
+ 'next': request.GET.get('next', ''),
54
+ 'restore_password_form': form,
55
+ }, context_instance=RequestContext(request))
56
+
57
+ username = request.POST['user']
58
+ password = request.POST['pwd']
59
+ user = authenticate(username=username, password=password)
60
+
61
+ if user is None:
62
+ return render_to_response('login.html', {
63
+ 'error_message': _('Wrong username or password.'),
64
+ 'next': request.POST.get('next', ''),
65
+ }, context_instance=RequestContext(request))
66
+
67
+ if not user.is_active:
68
+
69
+ p = UserProfile.objects.get_or_create(user=user)
70
+
71
+ if p.deleted:
72
+ return render_to_response('login.html', {
73
+ 'error_message': _('You have deleted your account, but you can register again')
74
+ }, context_instance=RequestContext(request))
75
+
76
+ else:
77
+ return render_to_response('login.html', {
78
+ 'error_message': _('Please activate your account first.'),
79
+ 'activation_needed': True,
80
+ }, context_instance=RequestContext(request))
81
+
82
+ login(request, user)
83
+
84
+ if 'next' in request.POST and request.POST['next'] and request.POST['next'] != '/login/':
85
+ return HttpResponseRedirect(request.POST['next'])
86
+
87
+ return HttpResponseRedirect("/")
88
+
89
+ def get_user(username, email):
90
+ if username:
91
+ return User.objects.get(username=username)
92
+ elif email:
93
+ return User.objects.get(email=email)
94
+ else:
95
+ raise User.DoesNotExist('neither username nor email provided')
96
+
97
+ @allowed_methods(['POST'])
98
+ def restore_password(request):
99
+ form = RestorePasswordForm(request.POST)
100
+ if not form.is_valid():
101
+ return HttpResponseRedirect('/login/')
102
+
103
+ try:
104
+ user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])
105
+
106
+ except User.DoesNotExist:
107
+ error_message = _('User does not exist.')
108
+ return render_to_response('password_reset_failed.html', {
109
+ 'error_message': error_message
110
+ }, context_instance=RequestContext(request))
111
+
112
+ site = Site.objects.get_current()
113
+ pwd = "".join(random.sample(string.letters + string.digits, 8))
114
+ subject = _('Reset password for your account on %s') % site
115
+ message = _('Here is your new password for your account %(username)s on %(site)s: %(password)s') % {'username': user.username, 'site': site, 'password': pwd}
116
+ user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)
117
+ user.set_password(pwd)
118
+ user.save()
119
+ return render_to_response('password_reset.html', context_instance=RequestContext(request))
120
+
121
+
122
+ @manual_gc
123
+ @allowed_methods(['GET', 'POST'])
124
+ def resend_activation(request):
125
+
126
+ if request.method == 'GET':
127
+ form = ResendActivationForm()
128
+ return render_to_response('registration/resend_activation.html', {
129
+ 'form': form,
130
+ }, context_instance=RequestContext(request))
131
+
132
+ site = Site.objects.get_current()
133
+ form = ResendActivationForm(request.POST)
134
+
135
+ try:
136
+ if not form.is_valid():
137
+ raise ValueError(_('Invalid Username entered'))
138
+
139
+ try:
140
+ user = get_user(form.cleaned_data['username'], form.cleaned_data['email'])
141
+ except User.DoesNotExist:
142
+ raise ValueError(_('User does not exist.'))
143
+
144
+ p = UserProfile.objects.get_or_create(user=user)
145
+ if p.deleted:
146
+ raise ValueError(_('You have deleted your account, but you can regster again.'))
147
+
148
+ try:
149
+ profile = RegistrationProfile.objects.get(user=user)
150
+ except RegistrationProfile.DoesNotExist:
151
+ profile = RegistrationProfile.objects.create_profile(user)
152
+
153
+ if profile.activation_key == RegistrationProfile.ACTIVATED:
154
+ user.is_active = True
155
+ user.save()
156
+ raise ValueError(_('Your account already has been activated. Go ahead and log in.'))
157
+
158
+ elif profile.activation_key_expired():
159
+ raise ValueError(_('Your activation key has expired. Please try another username, or retry with the same one tomorrow.'))
160
+
161
+ except ValueError, e:
162
+ return render_to_response('registration/resend_activation.html', {
163
+ 'form': form,
164
+ 'error_message' : e
165
+ }, context_instance=RequestContext(request))
166
+
167
+
168
+
169
+ profile.send_activation_email(site)
170
+
171
+ return render_to_response('registration/resent_activation.html', context_instance=RequestContext(request))
172
+
pool/shard001/Python/0012645_main.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google 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
+
15
+ """Prediction server that uses a trained policy to give predicted actions."""
16
+ import os
17
+
18
+ from fastapi import FastAPI
19
+ from fastapi import Request
20
+
21
+ import tensorflow as tf
22
+ import tf_agents
23
+
24
+
25
+ app = FastAPI()
26
+ _model = tf.compat.v2.saved_model.load(os.environ["AIP_STORAGE_URI"])
27
+
28
+
29
+ @app.get(os.environ["AIP_HEALTH_ROUTE"], status_code=200)
30
+ def health():
31
+ """Handles server health check requests.
32
+
33
+ Returns:
34
+ An empty dict.
35
+ """
36
+ return {}
37
+
38
+
39
+ @app.post(os.environ["AIP_PREDICT_ROUTE"])
40
+ async def predict(request: Request):
41
+ """Handles prediction requests.
42
+
43
+ Unpacks observations in prediction requests and queries the trained policy for
44
+ predicted actions.
45
+
46
+ Args:
47
+ request: Incoming prediction requests that contain observations.
48
+
49
+ Returns:
50
+ A dict with the key `predictions` mapping to a list of predicted actions
51
+ corresponding to each observation in the prediction request.
52
+ """
53
+ body = await request.json()
54
+ instances = body["instances"]
55
+
56
+ predictions = []
57
+ for index, instance in enumerate(instances):
58
+ # Unpack request body and reconstruct TimeStep. Rewards default to 0.
59
+ batch_size = len(instance["observation"])
60
+ time_step = tf_agents.trajectories.restart(
61
+ observation=instance["observation"],
62
+ batch_size=tf.convert_to_tensor([batch_size]))
63
+ policy_step = _model.action(time_step)
64
+
65
+ predictions.append(
66
+ {f"PolicyStep {index}": policy_step.action.numpy().tolist()})
67
+
68
+ return {"predictions": predictions}
pool/shard001/Python/0012647_genicon.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!@PYTHON@
2
+ import os
3
+ import sys
4
+ import tempfile
5
+
6
+ base = os.path.splitext (os.path.split (sys.argv[1])[1])[0]
7
+ input = os.path.abspath (sys.argv[1])
8
+ output = os.path.abspath (sys.argv[2])
9
+ program_name= os.path.split (sys.argv[0])[1]
10
+
11
+ dir = tempfile.mktemp (program_name)
12
+ os.mkdir (dir, 0777)
13
+ os.chdir(dir)
14
+
15
+ def system (c):
16
+ print c
17
+ if os.system (c):
18
+ raise 'barf'
19
+
20
+ outputs = []
21
+ for sz in [48,32,16] :
22
+
23
+ for depth in [24,8]:
24
+ out = '%(base)s-%(sz)d-%(depth)d.png' % locals()
25
+ system ('convert -depth %(depth)d -sample %(sz)d %(input)s %(out)s' %
26
+ locals ())
27
+ outputs.append (out)
28
+
29
+ system('icotool --output %s --create %s' % (output, ' '.join (outputs)))
30
+ system('rm -rf %(dir)s' % locals())
31
+
pool/shard001/Python/0012651_tinypng.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ from os.path import dirname
3
+ from urllib.request import Request, urlopen
4
+ from base64 import b64encode
5
+ import sys
6
+
7
+ key = "3lHn_dVjmmU_PqoGiQblVCyvtiXbWCQB"
8
+ input = sys.argv[1]
9
+ output = sys.argv[1] + "-tiny.png"
10
+
11
+ request = Request("https://api.tinypng.com/shrink", open(input, "rb").read())
12
+
13
+ cafile = None
14
+ # Uncomment below if you have trouble validating our SSL certificate.
15
+ # Download cacert.pem from: http://curl.haxx.se/ca/cacert.pem
16
+ # cafile = dirname(__file__) + "/cacert.pem"
17
+
18
+ auth = b64encode(bytes("api:" + key, "ascii")).decode("ascii")
19
+ request.add_header("Authorization", "Basic %s" % auth)
20
+
21
+ response = urlopen(request, cafile = cafile)
22
+ if response.status == 201:
23
+ # Compression was successful, retrieve output from Location header.
24
+ result = urlopen(response.getheader("Location"), cafile = cafile).read()
25
+ open(output, "wb").write(result)
26
+ else:
27
+ # Something went wrong! You can parse the JSON body for details.
28
+ print("Compression failed")
29
+
pool/shard001/Python/0012652_retry_http.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014-2015 Zuercher Hochschule fuer Angewandte Wissenschaften
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
+ __author__ = 'andy'
17
+
18
+ import requests
19
+ from retrying import retry
20
+
21
+ from config import CONFIG
22
+ from log import LOG
23
+
24
+
25
+ WAIT = CONFIG.get('cloud_controller', 'wait_time', 2000)
26
+ ATTEMPTS = CONFIG.get('cloud_controller', 'max_attempts', 5)
27
+
28
+
29
+ def retry_if_http_error(exception):
30
+ """
31
+ Defines which type of exceptions allow for a retry of the request
32
+
33
+ :param exception: the raised exception
34
+ :return: True if retrying the request is possible
35
+ """
36
+ error = False
37
+ if isinstance(exception, requests.HTTPError):
38
+ if exception.response.status_code == 503:
39
+ LOG.info('Requesting retry: response code: ' + str(exception.response.status_code))
40
+ LOG.error('Exception: ' + exception.__repr__())
41
+ error = True
42
+ elif isinstance(exception, requests.ConnectionError):
43
+ LOG.info('Requesting retry: ConnectionError')
44
+ LOG.error('Exception: ' + exception.__repr__())
45
+ error = True
46
+ return error
47
+
48
+
49
+ @retry(retry_on_exception=retry_if_http_error, wait_fixed=WAIT, stop_max_attempt_number=ATTEMPTS)
50
+ def http_retriable_request(verb, url, headers={}, authenticate=False, params={}):
51
+ """
52
+ Sends an HTTP request, with automatic retrying in case of HTTP Errors 500 or ConnectionErrors
53
+ _http_retriable_request('POST', 'http://cc.cloudcomplab.ch:8888/app/', headers={'Content-Type': 'text/occi', [...]}
54
+ , authenticate=True)
55
+ :param verb: [POST|PUT|GET|DELETE] HTTP keyword
56
+ :param url: The URL to use.
57
+ :param headers: Headers of the request
58
+ :param kwargs: May contain authenticate=True parameter, which is used to make requests requiring authentication,
59
+ e.g. CC requests
60
+ :return: result of the request
61
+ """
62
+ LOG.debug(verb + ' on ' + url + ' with headers ' + headers.__repr__())
63
+
64
+ auth = ()
65
+ if authenticate:
66
+ user = CONFIG.get('cloud_controller', 'user')
67
+ pwd = CONFIG.get('cloud_controller', 'pwd')
68
+ auth = (user, pwd)
69
+
70
+ if verb in ['POST', 'DELETE', 'GET', 'PUT']:
71
+ try:
72
+ r = None
73
+ if verb == 'POST':
74
+ if authenticate:
75
+ r = requests.post(url, headers=headers, auth=auth, params=params)
76
+ else:
77
+ r = requests.post(url, headers=headers, params=params)
78
+ elif verb == 'DELETE':
79
+ if authenticate:
80
+ r = requests.delete(url, headers=headers, auth=auth, params=params)
81
+ else:
82
+ r = requests.delete(url, headers=headers, params=params)
83
+ elif verb == 'GET':
84
+ if authenticate:
85
+ r = requests.get(url, headers=headers, auth=auth, params=params)
86
+ else:
87
+ r = requests.get(url, headers=headers, params=params)
88
+ elif verb == 'PUT':
89
+ if authenticate:
90
+ r = requests.put(url, headers=headers, auth=auth, params=params)
91
+ else:
92
+ r = requests.put(url, headers=headers, params=params)
93
+ r.raise_for_status()
94
+ return r
95
+ except requests.HTTPError as err:
96
+ LOG.error('HTTP Error: should do something more here!' + err.message)
97
+ raise err
pool/shard001/Python/0012654_parse_timings.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import math
4
+
5
+ def createTableHeader(methods):
6
+ #print "\\begin{table}[ht!]"
7
+ #print "\\caption{XXX}"
8
+ #print "\\label{tab:runtimes}"
9
+ #print "\\centering"
10
+ print "\\begin{tabular}{l c r r r }"
11
+ print "\\toprule"
12
+ print "File & {} \\\\ ".format( " & ".join(methods) )
13
+ print "\\midrule"
14
+
15
+ def convertToTime(sec):
16
+ if sec == None:
17
+ t1_s = "XXX"
18
+ else:
19
+ h = int(sec) / 3600
20
+ t1_s = "{}h".format(h) if h > 0 else ""
21
+ m = (int(sec) - h * 3600) / 60
22
+ t1_s += "{}m".format(m) if m > 0 else "00"
23
+ sec = int(math.ceil(sec - h * 3600 - m * 60))
24
+ t1_s += "{}s".format(sec)
25
+ return t1_s
26
+
27
+ def createTableRow(file, t1, t2, t3):
28
+ t1_s = convertToTime(t1)
29
+ t2_s = convertToTime(t2)
30
+ t3_s = convertToTime(t3)
31
+ print "{} & {} & {} & {} \\\\".format(file, t1_s, t2_s, t3_s)
32
+
33
+ def createTableFooter():
34
+ print "\\bottomrule"
35
+ print "\\end{tabular}"
36
+ print "\\end{table}"
37
+
38
+ def parseLogForTime(log_path):
39
+ if not os.path.isfile(log_path):
40
+ # print "Can't find log", log_path
41
+ return None
42
+ with open(log_path, "r") as f:
43
+ for line in f:
44
+ if "Elapsed (wall clock)" in line:
45
+ t = line.strip().split()[-1]
46
+ time_parts = t.split(":")
47
+ sec = 0
48
+ for p in time_parts[:-1]:
49
+ sec = sec * 60 + int(p) * 60
50
+ sec += float(time_parts[-1])
51
+ return sec
52
+ return None
53
+
54
+ FILES=["SRR445718", "SRR1294122", "P_aeruginosa_PAO1", "K562_cytosol_LID8465_TopHat_v2", "NA12878_S1"]
55
+ methods=["Referee","Deez","Quip -r"]
56
+ DIR = sys.argv[1]
57
+ createTableHeader(methods)
58
+ for file in FILES:
59
+ ref_log = DIR + "/" + file + ".comp.log"
60
+ deez_log = DIR + "/" + file + ".dz_comp.log"
61
+ quip_log = DIR + "/" + file + ".quip.log"
62
+
63
+ ref_time = parseLogForTime(ref_log)
64
+ deez_time = parseLogForTime(deez_log)
65
+ quip_time = parseLogForTime(quip_log)
66
+
67
+ createTableRow(file, ref_time, deez_time, quip_time)
68
+
69
+ createTableFooter()
pool/shard001/Python/0012655_init__.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .availability_zones import AvailabilityZonesV2
2
+ from .extensions import ExtensionsV2, ExtensionV2
3
+ from .extra_specs import ExtraSpecsFlavorV2
4
+ from .dns import DNSDomainsV2, DNSDomainEntryV2
5
+ from .flavors import FlavorV2, FlavorsV2, FlavorsDetailV2
6
+ from .floating_ips import OSFloatingIpsV2
7
+ from .keypairs import KeypairsV2, KeypairV2
8
+ from .limits import LimitsV2
9
+ from .quota_sets import OSQuotaSetsV2
10
+ from .servers import ServerV2, ServersV2, ServersDetailV2, ServerActionV2
11
+ from .server_ips import ServerIpsV2, ServerIpsNetworkV2
12
+ from .security_groups import OSSecurityGroupsV2
13
+ from .usage import UsageV2
14
+ from .volumes import OSVolumeAttachmentsV2
15
+ from .networks import OSNetworksV2, OSNetworkV2
16
+ from .instance_actions import InstanceActionsV2, InstanceActionV2
17
+ from .index import IndexV2
18
+
19
+ from jumpgate.image.drivers.sl import ImageV1, ImagesV2
20
+
21
+ from jumpgate.common.sl import add_hooks
22
+
23
+
24
+ def setup_routes(app, disp):
25
+ # V3 Routes
26
+ # None currently supported
27
+
28
+ # V2 Routes
29
+ disp.set_handler('index', IndexV2(app))
30
+ disp.set_handler('v2_index', IndexV2(app))
31
+
32
+ flavor = FlavorV2(app)
33
+ flavors = FlavorsV2(app)
34
+ flavors_detail = FlavorsDetailV2(app)
35
+
36
+ disp.set_handler('v2_availability_zone', AvailabilityZonesV2())
37
+ disp.set_handler('v2_availability_zone_detail', AvailabilityZonesV2())
38
+
39
+ disp.set_handler('v2_extensions', ExtensionsV2())
40
+ disp.set_handler('v2_extension', ExtensionV2())
41
+
42
+ disp.set_handler('v2_os_extra_specs_flavor', ExtraSpecsFlavorV2())
43
+
44
+ disp.set_handler('v2_flavor', flavor)
45
+ disp.set_handler('v2_flavors', flavors)
46
+ disp.set_handler('v2_flavors_detail', flavors_detail)
47
+
48
+ disp.set_handler('v2_os_floating_ip_dns', DNSDomainsV2())
49
+ disp.set_handler('v2_os_floating_ip_dns_domain_entry', DNSDomainEntryV2())
50
+
51
+ disp.set_handler('v2_limits', LimitsV2())
52
+
53
+ disp.set_handler('v2_os_floating_ips', OSFloatingIpsV2())
54
+
55
+ disp.set_handler('v2_os_tenant_networks', OSNetworksV2())
56
+ disp.set_handler('v2_os_tenant_network', OSNetworkV2())
57
+ disp.set_handler('v2_os_networks', OSNetworksV2())
58
+ disp.set_handler('v2_os_network', OSNetworkV2())
59
+
60
+ disp.set_handler('v2_os_keypair', KeypairV2())
61
+ disp.set_handler('v2_os_keypairs', KeypairsV2())
62
+
63
+ disp.set_handler('v2_os_quota_sets', OSQuotaSetsV2())
64
+ disp.set_handler('v2_os_tenant_quota_sets', OSQuotaSetsV2())
65
+
66
+ disp.set_handler('v2_os_server_security_groups', OSSecurityGroupsV2())
67
+ disp.set_handler('v2_os_security_groups', OSSecurityGroupsV2())
68
+
69
+ disp.set_handler('v2_os_volume_attachments', OSVolumeAttachmentsV2())
70
+
71
+ disp.set_handler('v2_server', ServerV2(app))
72
+ disp.set_handler('v2_servers', ServersV2(app))
73
+ disp.set_handler('v2_servers_detail', ServersDetailV2(app))
74
+ disp.set_handler('v2_server_action', ServerActionV2(app))
75
+ disp.set_handler('v2_os_instance_actions', InstanceActionsV2())
76
+ disp.set_handler('v2_os_instance_action', InstanceActionV2())
77
+
78
+ disp.set_handler('v2_server_ips', ServerIpsV2())
79
+ disp.set_handler('v2_server_ips_network', ServerIpsNetworkV2())
80
+
81
+ disp.set_handler('v2_tenant_flavor', flavor)
82
+ disp.set_handler('v2_tenant_flavors', flavors)
83
+ disp.set_handler('v2_tenant_flavors_detail', flavors_detail)
84
+
85
+ disp.set_handler('v2_tenant_usage', UsageV2())
86
+
87
+ disp.set_handler('v2_image', ImageV1(app))
88
+ disp.set_handler('v2_images', ImagesV2(app))
89
+ disp.set_handler('v2_images_detail', ImagesV2(app))
90
+
91
+ add_hooks(app)
pool/shard001/Python/0012658_query_results.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import numbers
4
+ import re
5
+ import sqlite3
6
+
7
+ from dateutil import parser
8
+
9
+ from redash import models
10
+ from redash.permissions import has_access, not_view_only
11
+ from redash.query_runner import (TYPE_BOOLEAN, TYPE_DATETIME, TYPE_FLOAT,
12
+ TYPE_INTEGER, TYPE_STRING, BaseQueryRunner,
13
+ register)
14
+ from redash.utils import JSONEncoder
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class PermissionError(Exception):
20
+ pass
21
+
22
+
23
+ def _guess_type(value):
24
+ if value == '' or value is None:
25
+ return TYPE_STRING
26
+
27
+ if isinstance(value, numbers.Integral):
28
+ return TYPE_INTEGER
29
+
30
+ if isinstance(value, float):
31
+ return TYPE_FLOAT
32
+
33
+ if unicode(value).lower() in ('true', 'false'):
34
+ return TYPE_BOOLEAN
35
+
36
+ try:
37
+ parser.parse(value)
38
+ return TYPE_DATETIME
39
+ except (ValueError, OverflowError):
40
+ pass
41
+
42
+ return TYPE_STRING
43
+
44
+
45
+ def extract_query_ids(query):
46
+ queries = re.findall(r'(?:join|from)\s+query_(\d+)', query, re.IGNORECASE)
47
+ return [int(q) for q in queries]
48
+
49
+
50
+ def _load_query(user, query_id):
51
+ query = models.Query.get_by_id(query_id)
52
+
53
+ if user.org_id != query.org_id:
54
+ raise PermissionError("Query id {} not found.".format(query.id))
55
+
56
+ if not has_access(query.data_source.groups, user, not_view_only):
57
+ raise PermissionError(u"You are not allowed to execute queries on {} data source (used for query id {}).".format(
58
+ query.data_source.name, query.id))
59
+
60
+ return query
61
+
62
+
63
+ def create_tables_from_query_ids(user, connection, query_ids):
64
+ for query_id in set(query_ids):
65
+ query = _load_query(user, query_id)
66
+
67
+ results, error = query.data_source.query_runner.run_query(
68
+ query.query_text, user)
69
+
70
+ if error:
71
+ raise Exception(
72
+ "Failed loading results for query id {}.".format(query.id))
73
+
74
+ results = json.loads(results)
75
+ table_name = 'query_{query_id}'.format(query_id=query_id)
76
+ create_table(connection, table_name, results)
77
+
78
+
79
+ def fix_column_name(name):
80
+ return name.replace(':', '_').replace('.', '_').replace(' ', '_')
81
+
82
+
83
+ def create_table(connection, table_name, query_results):
84
+ columns = [column['name']
85
+ for column in query_results['columns']]
86
+ safe_columns = [fix_column_name(column) for column in columns]
87
+
88
+ column_list = ", ".join(safe_columns)
89
+ create_table = u"CREATE TABLE {table_name} ({column_list})".format(
90
+ table_name=table_name, column_list=column_list)
91
+ logger.debug("CREATE TABLE query: %s", create_table)
92
+ connection.execute(create_table)
93
+
94
+ insert_template = u"insert into {table_name} ({column_list}) values ({place_holders})".format(
95
+ table_name=table_name,
96
+ column_list=column_list,
97
+ place_holders=','.join(['?'] * len(columns)))
98
+
99
+ for row in query_results['rows']:
100
+ values = [row.get(column) for column in columns]
101
+ connection.execute(insert_template, values)
102
+
103
+
104
+ class Results(BaseQueryRunner):
105
+ noop_query = 'SELECT 1'
106
+
107
+ @classmethod
108
+ def configuration_schema(cls):
109
+ return {
110
+ "type": "object",
111
+ "properties": {
112
+ }
113
+ }
114
+
115
+ @classmethod
116
+ def annotate_query(cls):
117
+ return False
118
+
119
+ @classmethod
120
+ def name(cls):
121
+ return "Query Results (Beta)"
122
+
123
+ def run_query(self, query, user):
124
+ connection = sqlite3.connect(':memory:')
125
+
126
+ query_ids = extract_query_ids(query)
127
+ create_tables_from_query_ids(user, connection, query_ids)
128
+
129
+ cursor = connection.cursor()
130
+
131
+ try:
132
+ cursor.execute(query)
133
+
134
+ if cursor.description is not None:
135
+ columns = self.fetch_columns(
136
+ [(i[0], None) for i in cursor.description])
137
+
138
+ rows = []
139
+ column_names = [c['name'] for c in columns]
140
+
141
+ for i, row in enumerate(cursor):
142
+ for j, col in enumerate(row):
143
+ guess = _guess_type(col)
144
+
145
+ if columns[j]['type'] is None:
146
+ columns[j]['type'] = guess
147
+ elif columns[j]['type'] != guess:
148
+ columns[j]['type'] = TYPE_STRING
149
+
150
+ rows.append(dict(zip(column_names, row)))
151
+
152
+ data = {'columns': columns, 'rows': rows}
153
+ error = None
154
+ json_data = json.dumps(data, cls=JSONEncoder)
155
+ else:
156
+ error = 'Query completed but it returned no data.'
157
+ json_data = None
158
+ except KeyboardInterrupt:
159
+ connection.cancel()
160
+ error = "Query cancelled by user."
161
+ json_data = None
162
+ finally:
163
+ connection.close()
164
+ return json_data, error
165
+
166
+
167
+ register(Results)
pool/shard001/Python/0012665_requests.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import datetime
3
+
4
+
5
+ @enum.unique
6
+ class Status(enum.IntEnum):
7
+ PENDING = 0
8
+ INVALID = enum.auto()
9
+ FRESH = enum.auto()
10
+ DONE = enum.auto()
11
+
12
+
13
+ # TODO:
14
+ # - filter results by status
15
+ # - create a result for every submitted request
16
+ # - handle results assignment for requests that have pending results - delete pending results that become obsolete
17
+
18
+ class Request(object):
19
+ def __init__(self, person_id, request_id=None):
20
+ self.person_id = person_id
21
+ self.id = request_id
22
+
23
+ def __hash__(self):
24
+ return hash((self.id, self.person_id))
25
+
26
+
27
+ class IWantRequest(Request):
28
+ def __init__(self, person_id, activity, deadline,
29
+ activity_start, activity_duration_seconds):
30
+ super().__init__(person_id)
31
+ self.activity = activity
32
+
33
+ self.deadline = deadline
34
+ self.activity_start = activity_start
35
+ self.activity_duration = activity_duration_seconds
36
+
37
+ self.resolved_by = None
38
+
39
+ def __hash__(self):
40
+ return hash((super().__hash__(),
41
+ self.activity, self.deadline,
42
+ self.activity_start, self.activity_duration))
43
+
44
+ def __eq__(self, rhs):
45
+ result = True
46
+ # If two requests differ just by having different resolved_by
47
+ # result ID, they are still the same requests.
48
+ if (
49
+ False
50
+ or self.id != rhs.id
51
+ or self.person_id != rhs.person_id
52
+ or self.activity != rhs.activity
53
+ or self.deadline != rhs.deadline
54
+ or self.activity_start != rhs.activity_start
55
+ or self.activity_duration != rhs.activity_duration
56
+ ):
57
+ result = False
58
+ return result
59
+
60
+ @property
61
+ def activity_end(self):
62
+ return self.activity_start + datetime.timedelta(seconds=self.activity_duration)
63
+
64
+ def is_active_now(self):
65
+ return self.is_active_by(datetime.datetime.today())
66
+
67
+ def is_active_by(self, by_the_time):
68
+ return by_the_time < self.deadline
69
+
70
+ def overlaps_with(self, other_request):
71
+ overlaps = (self.activity_end > other_request.activity_start
72
+ and self.activity_start < other_request.activity_end)
73
+ return overlaps
74
+
75
+ # TODO: Find a more descriptive name
76
+ def conflicts_with(self, other_request):
77
+ overlaps = self.overlaps_with(other_request)
78
+ conflicts = (self is not other_request
79
+ and self.person_id == other_request.person_id
80
+ and overlaps)
81
+ return conflicts
82
+
83
+
84
+ class CancellationRequest(Request):
85
+ def __init__(self, person_id, cancelling_request_id):
86
+ super().__init__(person_id)
87
+ self.cancelling_request_id = cancelling_request_id
88
+
89
+
90
+ class Result(object):
91
+ def __init__(self, uid, requests_ids: set, deadline: datetime.datetime):
92
+ self.id = uid
93
+ self.requests_ids = requests_ids
94
+ self.deadline = deadline
95
+ self.status = Status.PENDING
96
+
97
+ def __hash__(self):
98
+ return hash((super().__hash__(),
99
+ self.id, frozenset(self.requests_ids),
100
+ self.deadline))
101
+
102
+ def __eq__(self, rhs):
103
+ result = True
104
+ if (
105
+ False
106
+ or self.id != rhs.id
107
+ or self.requests_ids != rhs.requests_ids
108
+ or self.deadline != rhs.deadline
109
+ ):
110
+ result = False
111
+ return result
pool/shard001/Python/0012671_faucet_event.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FAUCET event notification."""
2
+
3
+ # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
4
+ # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer.
5
+ # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
6
+ # Copyright (C) 2015--2019 The Contributors
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ import json
21
+ import os
22
+ import socket
23
+ import time
24
+ from contextlib import contextmanager
25
+
26
+ import eventlet
27
+
28
+ from os_ken.lib import hub
29
+ from os_ken.lib.hub import StreamServer
30
+
31
+
32
+ class NonBlockLock:
33
+ """Non blocking lock that can be used as a context manager."""
34
+
35
+ def __init__(self):
36
+ self._lock = eventlet.semaphore.Semaphore()
37
+
38
+ @contextmanager
39
+ def acquire_nonblock(self):
40
+ """Attempt to acquire a lock."""
41
+ result = self._lock.acquire(blocking=False)
42
+ yield result
43
+ if result:
44
+ self.release()
45
+
46
+ def release(self):
47
+ """Release lock when done."""
48
+ self._lock.release()
49
+
50
+
51
+ class FaucetEventNotifier:
52
+ """Event notification, via Unix domain socket."""
53
+
54
+ def __init__(self, socket_path, metrics, logger):
55
+ self.logger = logger
56
+ self.socket_path = self.check_path(socket_path)
57
+ self.metrics = metrics
58
+ self.event_id = 0
59
+ self.thread = None
60
+ self.lock = NonBlockLock()
61
+ self.event_q = eventlet.queue.Queue(120)
62
+
63
+ def start(self):
64
+ """Start socket server."""
65
+ if self.socket_path:
66
+ stream_server = StreamServer((self.socket_path, None), self._loop).serve_forever
67
+ self.thread = hub.spawn(stream_server)
68
+ self.thread.name = 'event'
69
+ return self.thread
70
+
71
+ def _loop(self, sock, _addr):
72
+ """Serve events."""
73
+ with self.lock.acquire_nonblock() as result:
74
+ if not result:
75
+ self.logger.info('multiple event clients not supported')
76
+ else:
77
+ self.logger.info('event client connected')
78
+ while True:
79
+ event = self.event_q.get()
80
+ event_bytes = bytes(
81
+ '\n'.join((json.dumps(event, default=str), '')).encode('UTF-8'))
82
+ try:
83
+ sock.sendall(event_bytes)
84
+ except (socket.error, IOError) as err:
85
+ self.logger.info('event client disconnected: %s', err)
86
+ break
87
+ try:
88
+ sock.close()
89
+ except (socket.error, IOError):
90
+ pass
91
+
92
+ def get_event(self):
93
+ assert self.thread is None, 'not allowed with async _loop'
94
+ return None if self.event_q.empty() else self.event_q.get()
95
+
96
+ def notify(self, dp_id, dp_name, event_dict):
97
+ """Notify of an event."""
98
+ assert isinstance(event_dict, dict)
99
+ self.event_id += 1
100
+ event = {
101
+ 'version': 1,
102
+ 'time': time.time(),
103
+ 'dp_id': dp_id,
104
+ 'dp_name': dp_name,
105
+ 'event_id': self.event_id,
106
+ }
107
+ for header_key in list(event):
108
+ assert header_key not in event_dict
109
+ event.update(event_dict)
110
+ self.metrics.faucet_event_id.set(event['event_id'])
111
+ if self.event_q.full():
112
+ self.event_q.get()
113
+ self.event_q.put(event)
114
+
115
+ def check_path(self, socket_path):
116
+ """Check that socket_path is valid."""
117
+ if not socket_path:
118
+ return None
119
+ socket_path = os.path.abspath(socket_path)
120
+ socket_dir = os.path.dirname(socket_path)
121
+ # Create parent directories that don't exist.
122
+ if not os.path.exists(socket_dir):
123
+ try:
124
+ os.makedirs(socket_dir)
125
+ except (PermissionError) as err: # pytype: disable=name-error
126
+ self.logger.error('Unable to create event socket directory: %s', err)
127
+ return None
128
+ # Check directory permissions.
129
+ if not os.access(socket_dir, os.R_OK | os.W_OK | os.X_OK):
130
+ self.logger.error('Incorrect permissions set on socket directory %s', socket_dir)
131
+ return None
132
+ # Remove stale socket file.
133
+ if os.path.exists(socket_path):
134
+ try:
135
+ os.remove(socket_path)
136
+ except (PermissionError) as err: # pytype: disable=name-error
137
+ self.logger.error('Unable to remove old socket: %s', err)
138
+ return None
139
+ return socket_path
pool/shard001/Python/0012672_pyunit_colname_set_basic.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.insert(1, "../../")
3
+ import h2o
4
+
5
+ def colname_set_basic(ip,port):
6
+
7
+
8
+
9
+ print "Uploading iris data..."
10
+
11
+ no_headers = h2o.upload_file(h2o.locate("smalldata/iris/iris.csv"))
12
+ headers_and = h2o.upload_file(h2o.locate("smalldata/iris/iris_header.csv"))
13
+
14
+ print no_headers.names()
15
+ print headers_and.names()
16
+
17
+ no_headers.setNames(headers_and.names())
18
+ assert no_headers.names() == headers_and.names(), "Expected the same column names but got {0} and {1}".\
19
+ format(no_headers.names(), headers_and.names())
20
+
21
+ if __name__ == "__main__":
22
+ h2o.run_test(sys.argv, colname_set_basic)
pool/shard001/Python/0012674_test_example2.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ import subprocess
5
+ from unittest import TestCase
6
+ from boutiques import __file__ as bfile
7
+ import boutiques as bosh
8
+
9
+
10
+ class TestExample2(TestCase):
11
+
12
+ def get_examples_dir(self):
13
+ return os.path.join(os.path.dirname(bfile),
14
+ "schema", "examples")
15
+
16
+ def test_example2_no_exec(self):
17
+ example2_dir = os.path.join(self.get_examples_dir(), "example2")
18
+ ret = bosh.execute("simulate",
19
+ os.path.join(example2_dir,
20
+ "example2.json"),
21
+ "-i",
22
+ os.path.join(example2_dir,
23
+ "invocation.json"))
24
+ assert(ret.stdout != ""
25
+ and ret.stderr == ""
26
+ and ret.exit_code == 0
27
+ and ret.error_message == "")
28
+
29
+ def test_example2_exec(self):
30
+ example2_dir = os.path.join(self.get_examples_dir(), "example2")
31
+ ret = bosh.execute("launch",
32
+ os.path.join(example2_dir, "example2.json"),
33
+ os.path.join(example2_dir, "invocation.json"))
34
+ print(ret)
35
+ assert(ret.stdout == ""
36
+ and ret.stderr == ""
37
+ and ret.exit_code == 0
38
+ and ret.error_message == "")
39
+
40
+ ret = bosh.execute("launch",
41
+ os.path.join(example2_dir, "example2.json"),
42
+ "-x",
43
+ os.path.join(example2_dir, "invocation.json"))
44
+ print(ret)
45
+ assert(ret.stdout == ""
46
+ and ret.stderr == ""
47
+ and ret.exit_code == 0
48
+ and ret.error_message == "")
49
+
50
+ def test_example2_no_exec_random(self):
51
+ example2_dir = os.path.join(self.get_examples_dir(), "example2")
52
+ self.assertFalse(bosh.execute("simulate",
53
+ os.path.join(example2_dir,
54
+ "example2.json")).exit_code)
pool/shard001/Python/0012676_ping.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def read_file(ipfile):
2
+ with open(ipfile, 'r') as fd:
3
+ lines = fd.readlines()
4
+ ips = []
5
+ for line in lines:
6
+ ips.append(line.strip())
7
+ return ips
8
+
9
+ def ping():
10
+ return ''
11
+
12
+ def main():
13
+ print 'derp'
14
+
15
+ if __name__ == '__main__':
16
+ main()
pool/shard001/Python/0012678_models.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.db import models
2
+
3
+
4
+ class Game(models.Model):
5
+ BOARD_GAME = 'B'
6
+ RPG = 'R'
7
+ TYPE_CHOICES = ((BOARD_GAME, 'Board game'), (RPG, 'Role-playing game'))
8
+ geek_id = models.IntegerField(null=True)
9
+ name = models.CharField(max_length=255)
10
+ type = models.CharField(max_length=1, choices=TYPE_CHOICES,
11
+ default=BOARD_GAME)
12
+
13
+ def geek_url(self):
14
+ if not self.geek_id:
15
+ return None
16
+ if self.type == self.RPG:
17
+ return "https://rpggeek.com/rpgitem/" + str(self.geek_id)
18
+ else:
19
+ return "https://boardgamegeek.com/boardgame/" + str(self.geek_id)
20
+
21
+
22
+ def __str__(self):
23
+ return self.name
24
+
25
+
26
+ class Variant(models.Model):
27
+ game = models.ForeignKey(Game, on_delete=models.DO_NOTHING)
28
+ description = models.CharField(max_length=255)
29
+
30
+ def __str__(self):
31
+ return str((self.game, self.description))
32
+
33
+
34
+ class Faction(models.Model):
35
+ game = models.ForeignKey(Game, on_delete=models.DO_NOTHING)
36
+ name = models.CharField(max_length=255)
37
+
38
+ def __str__(self):
39
+ return str((self.game, self.name))
40
+
41
+
42
+ class Play(models.Model):
43
+ game = models.ForeignKey(Game, on_delete=models.DO_NOTHING)
44
+ minutes = models.IntegerField(null=True, blank=True)
45
+ date = models.DateField(null=True, blank=True)
46
+ virtual = models.BooleanField(default=False)
47
+ variant = models.ForeignKey(Variant, null=True, blank=True,
48
+ on_delete=models.DO_NOTHING)
49
+ comments = models.CharField(null=True, blank=True, max_length=255)
50
+
51
+ def __str__(self):
52
+ return str((self.id, self.game, self.date))
53
+
54
+
55
+ class Player(models.Model):
56
+ MALE = 'M'
57
+ FEMALE = 'F'
58
+ OTHER = 'O'
59
+ GENDER_CHOICES = (
60
+ (MALE, 'Male'),
61
+ (FEMALE, 'Female'),
62
+ (OTHER, 'Other'))
63
+ name = models.CharField(max_length=255)
64
+ birth_date = models.DateField(null=True, blank=True)
65
+ gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)
66
+
67
+ def __str__(self):
68
+ return self.name
69
+
70
+
71
+ class Team(models.Model):
72
+ play = models.ForeignKey(Play, on_delete=models.DO_NOTHING)
73
+ players = models.ManyToManyField(Player)
74
+ factions = models.ManyToManyField(Faction, blank=True)
75
+ points = models.IntegerField(null=True, blank=True)
76
+ winner = models.NullBooleanField(null=True)
77
+
78
+ def __str__(self):
79
+ return str((self.play, self.points, self.winner))
pool/shard001/Python/0012689_models.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import datetime
3
+ from hashlib import sha1
4
+ from django.conf import settings
5
+ from django.utils.translation import ugettext_lazy as _
6
+ from django.db import models
7
+ from django.core.mail import send_mail
8
+ from django.core.urlresolvers import reverse
9
+ from django.template.loader import render_to_string
10
+ from django.contrib.auth.models import User
11
+ from django.contrib.sites.models import get_current_site
12
+
13
+
14
+ class EmailConfirmation(models.Model):
15
+ user = models.ForeignKey(User,
16
+ related_name='email_confirmations',
17
+ editable=False)
18
+ email = models.EmailField(_('e-mail address'))
19
+ key = models.CharField(_('confirmation key'),
20
+ max_length=40,
21
+ editable=False)
22
+ last_sent = models.DateTimeField(_('last time confirmation was sent'),
23
+ null=True)
24
+
25
+ def __unicode__(self):
26
+ return self.email
27
+
28
+ def save(self, *args, **kwargs):
29
+ if not self.key:
30
+ salt = sha1(str(random.random())).hexdigest()[:5]
31
+ self.key = sha1(salt+self.user.username).hexdigest()
32
+ super(EmailConfirmation, self).save(*args, **kwargs)
33
+
34
+ def send(self, request, update_timestamp=True):
35
+ """
36
+ Sends a confirmation message to the user optionally updating
37
+ last_sent timestamp.
38
+ """
39
+ site = get_current_site(request)
40
+ context = {
41
+ 'confirmation': self,
42
+ 'confirmation_url': '%s://%s%s' % (
43
+ 'https' if request.is_secure() else 'http',
44
+ site.domain,
45
+ reverse('accounts.confirm_email',
46
+ kwargs={'key': self.key})
47
+ )
48
+ }
49
+ subject = render_to_string(
50
+ 'accounts/email_confirmation_subject.j.txt', context)
51
+ message = render_to_string(
52
+ 'accounts/email_confirmation_message.j.txt', context)
53
+ email = send_mail(subject, message,
54
+ settings.DEFAULT_FROM_EMAIL,
55
+ [self.email])
56
+ if update_timestamp:
57
+ self.last_sent = datetime.datetime.utcnow()
58
+ self.save()
59
+ return email
60
+
61
+ def confirm(self, key):
62
+ if self.key == key:
63
+ self.delete()
64
+ return True
65
+ return False
66
+
67
+
68
+ class PasswordReset(models.Model):
69
+ user = models.ForeignKey(User,
70
+ related_name='password_resets',
71
+ editable=False)
72
+ key = models.CharField(_('reset key'),
73
+ max_length=40,
74
+ editable=False)
75
+ last_sent = models.DateTimeField(_('last time reset email was sent'),
76
+ null=True)
77
+
78
+ def __unicode__(self):
79
+ return self.key
80
+
81
+ def save(self, *args, **kwargs):
82
+ if not self.key:
83
+ salt = sha1(str(random.random())).hexdigest()[:5]
84
+ self.key = sha1(salt+self.user.username).hexdigest()
85
+ super(PasswordReset, self).save(*args, **kwargs)
86
+
87
+ def send(self, request, update_timestamp=True):
88
+ """
89
+ Sends a password reset message to the user optionally updating
90
+ last_sent timestamp.
91
+ """
92
+ site = get_current_site(request)
93
+ context = {
94
+ 'reset': self,
95
+ 'reset_url': '%s://%s%s' % (
96
+ 'https' if request.is_secure() else 'http',
97
+ site.domain,
98
+ reverse('accounts.password_reset_confirm',
99
+ kwargs={'key': self.key})
100
+ )
101
+ }
102
+ subject = render_to_string(
103
+ 'accounts/password_reset_subject.j.txt', context)
104
+ message = render_to_string(
105
+ 'accounts/password_reset_message.j.txt', context)
106
+ email = send_mail(subject, message,
107
+ settings.DEFAULT_FROM_EMAIL,
108
+ [self.user.email])
109
+ if update_timestamp:
110
+ self.last_sent = datetime.datetime.utcnow()
111
+ self.save()
112
+ return email
113
+
114
+ def verify(self, key):
115
+ return self.key == key
pool/shard001/Python/0012693_drop_stale_gradient_optimizer.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+
16
+ """Wrapper optimizer for checking and dropping stale gradients."""
17
+
18
+ from __future__ import absolute_import
19
+ from __future__ import division
20
+ from __future__ import print_function
21
+
22
+ from tensorflow.python.framework import dtypes
23
+ from tensorflow.python.framework import ops
24
+ from tensorflow.python.ops import control_flow_ops
25
+ from tensorflow.python.ops import gen_array_ops
26
+ from tensorflow.python.ops import gen_math_ops
27
+ from tensorflow.python.ops import init_ops
28
+ from tensorflow.python.ops import math_ops
29
+ from tensorflow.python.ops import variable_scope
30
+ from tensorflow.python.summary import summary
31
+ from tensorflow.python.training import optimizer
32
+ from tensorflow.python.training import training_util
33
+
34
+
35
+ class DropStaleGradientOptimizer(optimizer.Optimizer):
36
+ """Wrapper optimizer that checks and drops stale gradient.
37
+
38
+ This optimizer records the global step for each worker before computing
39
+ gradients and compares it with the global step at the time of applying the
40
+ gradients. If the difference is larger than a threshold, it will drop all
41
+ the computed gradients.
42
+ """
43
+
44
+ def __init__(self,
45
+ opt,
46
+ staleness,
47
+ use_locking=False,
48
+ name="DropStaleGradient"):
49
+ """Constructs a new DropStaleGradientOptimizer.
50
+
51
+ Args:
52
+ opt: The actual optimizer that will be used to compute and apply the
53
+ gradients. Must be one of the Optimizer classes.
54
+ staleness: The maximum staleness allowed for the optimizer.
55
+ use_locking: If `True` use locks for clip update operations.
56
+ name: Optional name prefix for the operations created when applying
57
+ gradients. Defaults to "DropStaleGradient".
58
+ """
59
+ super(DropStaleGradientOptimizer, self).__init__(use_locking, name)
60
+ self._opt = opt
61
+ self._staleness = staleness
62
+
63
+ def compute_gradients(self, loss, *args, **kwargs):
64
+ # Record current global step for worker.
65
+ with ops.colocate_with(loss):
66
+ self._local_step = training_util.get_global_step() + 0
67
+
68
+ with ops.control_dependencies([self._local_step]):
69
+ loss = gen_array_ops.identity(loss)
70
+ return self._opt.compute_gradients(loss, *args, **kwargs)
71
+
72
+ def get_slot(self, *args, **kwargs):
73
+ return self._opt.get_slot(*args, **kwargs)
74
+
75
+ def get_slot_names(self, *args, **kwargs):
76
+ return self._opt.get_slot_names(*args, **kwargs)
77
+
78
+ def apply_gradients(self, grads_and_vars, global_step=None, name=None):
79
+ gradients = []
80
+ # Number of stale gradients.
81
+ stale_counter = variable_scope.get_variable(
82
+ "stale_counter", [],
83
+ initializer=init_ops.zeros_initializer(),
84
+ trainable=False)
85
+
86
+ def _AcceptGradientOp():
87
+ with ops.control_dependencies(
88
+ [self._opt.apply_gradients(
89
+ grads_and_vars, global_step=global_step, name=name)]):
90
+ return gen_array_ops.identity(0.0)
91
+
92
+ def _DropGradientOp():
93
+ return gen_array_ops.identity(1.0)
94
+
95
+ for grad_and_var in grads_and_vars:
96
+ grad = grad_and_var[0]
97
+ if isinstance(grad, ops.Tensor):
98
+ gradients.append(grad)
99
+ else:
100
+ gradients.append(grad.op)
101
+
102
+ with ops.control_dependencies(gradients), ops.colocate_with(global_step):
103
+ staleness = gen_array_ops.reshape(
104
+ global_step - self._local_step, shape=())
105
+ conditional_update = stale_counter.assign_add(control_flow_ops.cond(
106
+ gen_math_ops.less_equal(staleness, self._staleness),
107
+ _AcceptGradientOp, _DropGradientOp))
108
+
109
+ summary.scalar(
110
+ "Gradient staleness percentage",
111
+ stale_counter / (math_ops.cast(global_step + 1, dtypes.float32)))
112
+ return conditional_update
pool/shard001/Python/0012698_test_runner.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
3
+ #
4
+ # Use of this source code is governed by a BSD-style license
5
+ # that can be found in the LICENSE file in the root of the source
6
+ # tree. An additional intellectual property rights grant can be found
7
+ # in the file PATENTS. All contributing project authors may
8
+ # be found in the AUTHORS file in the root of the source tree.
9
+
10
+ """
11
+ Runs tests on Android devices.
12
+
13
+ This script exists to avoid WebRTC being broken by changes in the Chrome Android
14
+ test execution toolchain. It also conveniently sets the CHECKOUT_SOURCE_ROOT
15
+ environment variable.
16
+ """
17
+
18
+ import os
19
+ import sys
20
+
21
+ SCRIPT_DIR = os.path.dirname(__file__)
22
+ SRC_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir,
23
+ os.pardir))
24
+ CHROMIUM_BUILD_ANDROID_DIR = os.path.join(SRC_DIR, 'build', 'android')
25
+ sys.path.insert(0, CHROMIUM_BUILD_ANDROID_DIR)
26
+
27
+
28
+ import test_runner # pylint: disable=W0406
29
+ from pylib.gtest import gtest_test_instance
30
+
31
+ def main():
32
+ # Set our own paths to the .isolate files.
33
+ # pylint: disable=protected-access
34
+ gtest_test_instance._DEFAULT_ISOLATE_FILE_PATHS.update({
35
+ 'audio_decoder_unittests':
36
+ 'webrtc/modules/audio_decoder_unittests.isolate',
37
+ 'common_audio_unittests':
38
+ 'webrtc/common_audio/common_audio_unittests.isolate',
39
+ 'common_video_unittests':
40
+ 'webrtc/common_video/common_video_unittests.isolate',
41
+ 'libjingle_peerconnection_unittest':
42
+ 'talk/libjingle_peerconnection_unittest.isolate',
43
+ 'modules_tests': 'webrtc/modules/modules_tests.isolate',
44
+ 'modules_unittests': 'webrtc/modules/modules_unittests.isolate',
45
+ 'rtc_unittests': 'webrtc/rtc_unittests.isolate',
46
+ 'system_wrappers_unittests':
47
+ 'webrtc/system_wrappers/system_wrappers_unittests.isolate',
48
+ 'test_support_unittests': 'webrtc/test/test_support_unittests.isolate',
49
+ 'tools_unittests': 'webrtc/tools/tools_unittests.isolate',
50
+ 'video_capture_tests':
51
+ 'webrtc/modules/video_capture/video_capture_tests.isolate',
52
+ 'video_engine_tests': 'webrtc/video_engine_tests.isolate',
53
+ 'voice_engine_unittests':
54
+ 'webrtc/voice_engine/voice_engine_unittests.isolate',
55
+ 'webrtc_nonparallel_tests': 'webrtc/webrtc_nonparallel_tests.isolate',
56
+ 'webrtc_perf_tests': 'webrtc/webrtc_perf_tests.isolate',
57
+ })
58
+ # Override environment variable to make it possible for the scripts to find
59
+ # the root directory (our symlinking of the Chromium build toolchain would
60
+ # otherwise make them fail to do so).
61
+ os.environ['CHECKOUT_SOURCE_ROOT'] = SRC_DIR
62
+ return test_runner.main()
63
+
64
+ if __name__ == '__main__':
65
+ sys.exit(main())
pool/shard001/Python/0012703_lirc2raw.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright (C) 2011 Woelfware
3
+
4
+ '''Parser to convert lirc config files to BluMote config files.
5
+
6
+ Usage: lirc2bm.py <infile>
7
+ '''
8
+
9
+ import os.path
10
+ import sys
11
+
12
+ parser_ver = '0.1'
13
+
14
+ class lirc2raw():
15
+ def __init__(self):
16
+ '''Initialize the lirc2raw object with code parameters and buttons.'''
17
+ self.remote_kw = { # key words for costructing the button codes
18
+ 'name' : 'name',
19
+ 'bits' : 'bits',
20
+ 'header' : 'header',
21
+ 'one' : 'one',
22
+ 'zero' : 'zero',
23
+ 'ptrail' : 'ptrail',
24
+ 'gap' : 'gap'}
25
+ self.code_kw = { # keys that can be automatically assigned
26
+ '0' : '0', 'zero' : '0', 'KEY_0' : '1',
27
+ '1' : '1', 'one' : '1', 'KEY_1' : '1',
28
+ '2' : '2', 'two' : '2', 'KEY_2' : '1',
29
+ '3' : '3', 'three' : '3', 'KEY_3' : '1',
30
+ '4' : '4', 'four' : '4', 'KEY_4' : '1',
31
+ '5' : '5', 'five' : '5', 'KEY_5' : '1',
32
+ '6' : '6', 'six' : '6', 'KEY_6' : '1',
33
+ '7' : '7', 'seven' : '7', 'KEY_7' : '1',
34
+ '8' : '8', 'eight' : '8', 'KEY_8' : '1',
35
+ '9' : '9', 'nine' : '9', 'KEY_9' : '1',
36
+ 'PLAY' : 'PLAY',
37
+ 'PAUSE' : 'PAUSE',
38
+ 'STOP' : 'STOP',
39
+ 'FORWARD' : 'FORWARD',
40
+ 'REVERSE' : 'REVERSE',
41
+ 'SKIP+' : 'SKIP+',
42
+ 'SKIP-' : 'SKIP-',
43
+ 'MENU' : 'MENU',
44
+ 'UP' : 'UP', 'KEY_UP' : 'UP',
45
+ 'DOWN' : 'DOWN', 'KEY_DOWN' : 'DOWN',
46
+ 'LEFT' : 'LEFT', 'KEY_LEFT' : 'LEFT',
47
+ 'RIGHT' : 'RIGHT', 'KEY_RIGHT' : 'RIGHT'}
48
+
49
+
50
+ def parse(self, fh):
51
+ '''Parse an LIRC remote config file.'''
52
+ remote = {'attributes' : {}, 'codes' : {}}
53
+ begin_remote = False
54
+ begin_codes = False
55
+
56
+ for line in fh:
57
+ if line.startswith('#'):
58
+ continue
59
+
60
+ words = line.split()
61
+ if not words:
62
+ continue
63
+
64
+ if begin_codes:
65
+ if ' '.join(words[:2]) == 'end codes':
66
+ begin_codes = False
67
+ elif words[0] in self.code_kw.keys():
68
+ # automatically assign codes for known buttons
69
+ try:
70
+ remote['codes'][self.code_kw[words[0]]] = '0x{:X}'.format(int(words[1]))
71
+ except ValueError:
72
+ remote['codes'][self.code_kw[words[0]]] = '0x{:X}'.format(int(words[1], 16))
73
+ else:
74
+ # store codes in the database for buttons
75
+ # that could be used in an activity
76
+ try:
77
+ remote['codes'][words[0]] = '0x{:X}'.format(int(words[1]))
78
+ except ValueError:
79
+ remote['codes'][words[0]] = '0x{:X}'.format(int(words[1], 16))
80
+ elif begin_remote:
81
+ if words[:2] == ['end', 'remote']:
82
+ begin_remote = False
83
+ elif ' '.join(words[:2]) == 'begin codes':
84
+ begin_codes = True
85
+ elif words[0] in self.remote_kw.keys():
86
+ try:
87
+ remote['attributes'][self.remote_kw[words[0]]] = [int(i) for i in words[1:]]
88
+ except ValueError:
89
+ remote['attributes'][self.remote_kw[words[0]]] = ' '.join(words[1:])
90
+ elif ' '.join(words[:2]) == 'begin remote':
91
+ begin_remote = True
92
+
93
+ return remote
94
+
95
+ def write_raw_config(self, remote, fin_name, fout_name):
96
+ '''Write the BluMote raw config file.'''
97
+ fout = open(fout_name, 'w')
98
+
99
+ # file header
100
+ fout.write('# This file was automatically generated with {} ver {}'
101
+ ' using {} from the LIRC project.\n'.format(os.path.basename(__file__),
102
+ parser_ver, fin_name))
103
+
104
+ for key, code in sorted(remote['codes'].items()):
105
+ fout.write('{}\n'.format(key))
106
+ code = int(code, 16)
107
+
108
+ fout.write('\t{}\n'.format(remote['attributes']['header'][0]))
109
+ fout.write('\t{}\n'.format(remote['attributes']['header'][1]))
110
+
111
+ for bit in range(remote['attributes']['bits'][0]):
112
+ if ((code >> (remote['attributes']['bits'][0] - bit - 1)) & 1):
113
+ # '1'
114
+ fout.write('\t{}\n'.format(remote['attributes']['one'][0]))
115
+ fout.write('\t{}\n'.format(remote['attributes']['one'][1]))
116
+ else:
117
+ # '0'
118
+ fout.write('\t{}\n'.format(remote['attributes']['zero'][0]))
119
+ fout.write('\t{}\n'.format(remote['attributes']['zero'][1]))
120
+
121
+ fout.write('\t{}\n'.format(remote['attributes']['ptrail'][0]))
122
+ fout.write('\t{}\n'.format(remote['attributes']['gap'][0]))
123
+
124
+ fout.close()
125
+
126
+ if __name__ == '__main__':
127
+ if len(sys.argv) != 2:
128
+ print(__doc__)
129
+ sys.exit(1)
130
+
131
+ parser = lirc2raw()
132
+ with open(sys.argv[1]) as fin:
133
+ remote = parser.parse(fin)
134
+ fin_name = os.path.basename(sys.argv[1])
135
+ parser.write_raw_config(remote, fin_name, fin_name + '.bmraw')
pool/shard001/Python/0012713_assigneddiscount.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ This code was generated by Codezu.
4
+
5
+ Changes to this file may cause incorrect behavior and will be lost if
6
+ the code is regenerated.
7
+ """
8
+
9
+
10
+ from mozurestsdk.mozuclient import default as default_client
11
+ from mozurestsdk.mozuurl import MozuUrl;
12
+ from mozurestsdk.urllocation import UrlLocation
13
+ from mozurestsdk.apicontext import ApiContext;
14
+
15
+ class AssignedDiscount(object):
16
+ def __init__(self, apiContext: ApiContext = None, mozuClient = None):
17
+ self.client = mozuClient or default_client();
18
+ if (apiContext is not None):
19
+ self.client.withApiContext(apiContext);
20
+ else:
21
+ self.client.withApiContext(ApiContext());
22
+
23
+ def getAssignedDiscounts(self,couponSetCode):
24
+ """ Retrieves the discountIds of any assigned discounts for the specified coupon set.
25
+
26
+ Args:
27
+ | couponSetCode (string) - The unique identifier of the coupon set.
28
+
29
+ Returns:
30
+ | array of AssignedDiscount
31
+
32
+ Raises:
33
+ | ApiException
34
+
35
+ """
36
+
37
+ url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts", "GET", UrlLocation.TenantPod, False);
38
+ url.formatUrl("couponSetCode", couponSetCode);
39
+ self.client.withResourceUrl(url).execute();
40
+ return self.client.result();
41
+
42
+
43
+
44
+ def assignDiscount(self,assignedDiscount, couponSetCode):
45
+ """ Assigns or associates an existing discount to a specified coupon set. Use the couponSetCode parameter to specify the coupon set.
46
+
47
+ Args:
48
+ | assignedDiscount(assignedDiscount) - The details of the discount assigned to the coupon set.
49
+ | couponSetCode (string) - The unique identifier of the coupon set.
50
+
51
+ Raises:
52
+ | ApiException
53
+
54
+ """
55
+
56
+ url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts", "POST", UrlLocation.TenantPod, False);
57
+ url.formatUrl("couponSetCode", couponSetCode);
58
+ self.client.withResourceUrl(url).withBody(assignedDiscount).execute();
59
+
60
+
61
+
62
+ def unAssignDiscount(self,couponSetCode, discountId):
63
+ """ Unassigns or disassociates the specified discount with the specified coupon set.
64
+
65
+ Args:
66
+ | couponSetCode (string) - The unique identifier of the coupon set.
67
+ | discountId (int) - discountId parameter description DOCUMENT_HERE
68
+
69
+ Raises:
70
+ | ApiException
71
+
72
+ """
73
+
74
+ url = MozuUrl("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts/{discountId}", "DELETE", UrlLocation.TenantPod, False);
75
+ url.formatUrl("couponSetCode", couponSetCode);
76
+ url.formatUrl("discountId", discountId);
77
+ self.client.withResourceUrl(url).execute();
78
+
79
+
80
+
81
+
pool/shard001/Python/0012715_test_cli.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import collections
3
+ import os
4
+ import subprocess
5
+ import yaml
6
+ import shutil
7
+
8
+ from conda_smithy import cli
9
+
10
+ _thisdir = os.path.abspath(os.path.dirname(__file__))
11
+
12
+ InitArgs = collections.namedtuple('ArgsObject', ('recipe_directory',
13
+ 'feedstock_directory'))
14
+
15
+ RegenerateArgs = collections.namedtuple('ArgsObject', ('commit',
16
+ 'feedstock_directory',
17
+ 'no_check_uptodate',
18
+ 'exclusive_config_file'))
19
+
20
+
21
+ def test_init(py_recipe):
22
+ """This is the command that takes the initial staged-recipe folder and turns it into a
23
+ feedstock"""
24
+ # actual parser doesn't matter. It's used for initialization only
25
+ parser = argparse.ArgumentParser()
26
+ subparser = parser.add_subparsers()
27
+ init_obj = cli.Init(subparser)
28
+ recipe = py_recipe.recipe
29
+ # expected args object has
30
+ args = InitArgs(recipe_directory=os.path.join(recipe, 'recipe'),
31
+ feedstock_directory=os.path.join(recipe, '{package.name}-feedstock'))
32
+ init_obj(args)
33
+ destination = os.path.join(recipe, 'py-test-feedstock')
34
+ assert os.path.isdir(destination)
35
+
36
+
37
+ def test_init_multiple_output_matrix(testing_workdir):
38
+ parser = argparse.ArgumentParser()
39
+ subparser = parser.add_subparsers()
40
+ init_obj = cli.Init(subparser)
41
+ regen_obj = cli.Regenerate(subparser)
42
+ recipe = os.path.join(_thisdir, 'recipes', 'multiple_outputs')
43
+ feedstock_dir = os.path.join(testing_workdir, 'multiple-outputs-test-feedstock')
44
+ args = InitArgs(recipe_directory=recipe,
45
+ feedstock_directory=feedstock_dir)
46
+ init_obj(args)
47
+ # Ignore conda-forge-pinning for this test, as the test relies on conda-forge-pinning
48
+ # not being present
49
+ args = RegenerateArgs(feedstock_directory=feedstock_dir,
50
+ commit=False,
51
+ no_check_uptodate=True,
52
+ exclusive_config_file="recipe/conda_build_config.yaml")
53
+ regen_obj(args)
54
+ matrix_dir = os.path.join(feedstock_dir, '.ci_support')
55
+ # the matrix should be consolidated among all outputs, as well as the top-level
56
+ # reqs. Only the top-level reqs should have indedependent config files,
57
+ # though - loops within outputs are contained in those top-level configs.
58
+ assert len(os.listdir(matrix_dir)) == 13
59
+ linux_libpng16 = os.path.join(matrix_dir, 'linux_libpng1.6libpq9.5.yaml')
60
+ assert os.path.isfile(linux_libpng16)
61
+ with open(linux_libpng16) as f:
62
+ config = yaml.load(f)
63
+ assert config['libpng'] == ['1.6']
64
+ assert config['libpq'] == ['9.5']
65
+ # this is a zipped key, but it's not used, so it shouldn't show up
66
+ assert 'libtiff' not in config
67
+ assert 'zip_keys' not in config or not any('libtiff' in group for group in config['zip_keys'])
68
+ # this is a variable only for one of the outputs
69
+ assert config['jpeg'] == ['8', '9']
70
+ # this is in conda_build_config.yaml, but is a transitive dependency. It should
71
+ # not show up in the final configs.
72
+ assert 'zlib' not in config
73
+
74
+
75
+ def test_regenerate(py_recipe, testing_workdir):
76
+ parser = argparse.ArgumentParser()
77
+ subparser = parser.add_subparsers()
78
+ regen_obj = cli.Regenerate(subparser)
79
+ recipe = py_recipe.recipe
80
+ feedstock_dir = os.path.join(_thisdir, 'recipes', 'click-test-feedstock')
81
+ dest_dir = os.path.join(testing_workdir, 'click-test-feedstock')
82
+ shutil.copytree(feedstock_dir, dest_dir)
83
+ subprocess.call('git init'.split(), cwd=dest_dir)
84
+ subprocess.call('git add *'.split(), cwd=dest_dir)
85
+ subprocess.call('git commit -m "init"'.split(), cwd=dest_dir)
86
+ matrix_folder = os.path.join(dest_dir, '.ci_support')
87
+
88
+ # original rendering was with py27, 36, no target_platform
89
+ assert len(os.listdir(matrix_folder)) == 7
90
+
91
+ # Ignore conda-forge-pinning for this test, as the test relies on conda-forge-pinning
92
+ # not being present
93
+ args = RegenerateArgs(feedstock_directory=dest_dir,
94
+ commit=False,
95
+ no_check_uptodate=True,
96
+ exclusive_config_file=os.path.join(recipe, 'config.yaml'))
97
+
98
+ regen_obj(args)
99
+
100
+ # should add 2, as the config.yaml adds in target_platform
101
+ assert len(os.listdir(matrix_folder)) == 9
102
+
103
+ # reduce the python matrix and make sure the matrix files reflect the change
104
+ args = RegenerateArgs(feedstock_directory=dest_dir,
105
+ commit=False,
106
+ no_check_uptodate=True,
107
+ exclusive_config_file=os.path.join(recipe, 'short_config.yaml'))
108
+ regen_obj(args)
109
+
110
+ # one py ver, no target_platform (tests that older configs don't stick around)
111
+ assert len(os.listdir(matrix_folder)) == 4
pool/shard001/Python/0012716_config.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ try:
4
+ # Python 2.7
5
+ from collections import OrderedDict
6
+ except:
7
+ # Python 2.6
8
+ from gluon.contrib.simplejson.ordered_dict import OrderedDict
9
+
10
+ from gluon import current
11
+ from gluon.storage import Storage
12
+
13
+ def config(settings):
14
+ """
15
+ Template settings: 'Skeleton' designed to be copied to quickly create
16
+ custom templates
17
+
18
+ All settings which are to configure a specific template are located
19
+ here. Deployers should ideally not need to edit any other files outside
20
+ of their template folder.
21
+ """
22
+
23
+ T = current.T
24
+
25
+ #settings.base.system_name = T("Sahana Skeleton")
26
+ #settings.base.system_name_short = T("Sahana")
27
+
28
+ # PrePopulate data
29
+ #settings.base.prepopulate = ("skeleton", "default/users")
30
+ settings.base.prepopulate += ("skeleton", "default/users")
31
+
32
+ # Theme (folder to use for views/layout.html)
33
+ #settings.base.theme = "skeleton"
34
+
35
+ # Authentication settings
36
+ # Should users be allowed to register themselves?
37
+ #settings.security.self_registration = False
38
+ # Do new users need to verify their email address?
39
+ #settings.auth.registration_requires_verification = True
40
+ # Do new users need to be approved by an administrator prior to being able to login?
41
+ #settings.auth.registration_requires_approval = True
42
+ #settings.auth.registration_requests_organisation = True
43
+
44
+ # Approval emails get sent to all admins
45
+ settings.mail.approver = "ADMIN"
46
+
47
+ # Restrict the Location Selector to just certain countries
48
+ # NB This can also be over-ridden for specific contexts later
49
+ # e.g. Activities filtered to those of parent Project
50
+ #settings.gis.countries = ("US",)
51
+ # Uncomment to display the Map Legend as a floating DIV
52
+ settings.gis.legend = "float"
53
+ # Uncomment to Disable the Postcode selector in the LocationSelector
54
+ #settings.gis.postcode_selector = False # @ToDo: Vary by country (include in the gis_config!)
55
+ # Uncomment to show the Print control:
56
+ # http://eden.sahanafoundation.org/wiki/UserGuidelines/Admin/MapPrinting
57
+ #settings.gis.print_button = True
58
+
59
+ # L10n settings
60
+ # Languages used in the deployment (used for Language Toolbar & GIS Locations)
61
+ # http://www.loc.gov/standards/iso639-2/php/code_list.php
62
+ #settings.L10n.languages = OrderedDict([
63
+ # ("ar", "العربية"),
64
+ # ("bs", "Bosanski"),
65
+ # ("en", "English"),
66
+ # ("fr", "Français"),
67
+ # ("de", "Deutsch"),
68
+ # ("el", "ελληνικά"),
69
+ # ("es", "Español"),
70
+ # ("it", "Italiano"),
71
+ # ("ja", "日本語"),
72
+ # ("km", "ភាសាខ្មែរ"),
73
+ # ("ko", "한국어"),
74
+ # ("ne", "नेपाली"), # Nepali
75
+ # ("prs", "دری"), # Dari
76
+ # ("ps", "پښتو"), # Pashto
77
+ # ("pt", "Português"),
78
+ # ("pt-br", "Português (Brasil)"),
79
+ # ("ru", "русский"),
80
+ # ("tet", "Tetum"),
81
+ # ("tl", "Tagalog"),
82
+ # ("tr", "Türkçe"),
83
+ # ("ur", "اردو"),
84
+ # ("vi", "Tiếng Việt"),
85
+ # ("zh-cn", "中文 (简体)"),
86
+ # ("zh-tw", "中文 (繁體)"),
87
+ #])
88
+ # Default language for Language Toolbar (& GIS Locations in future)
89
+ #settings.L10n.default_language = "en"
90
+ # Uncomment to Hide the language toolbar
91
+ #settings.L10n.display_toolbar = False
92
+ # Default timezone for users
93
+ #settings.L10n.utc_offset = "+0100"
94
+ # Number formats (defaults to ISO 31-0)
95
+ # Decimal separator for numbers (defaults to ,)
96
+ settings.L10n.decimal_separator = "."
97
+ # Thousands separator for numbers (defaults to space)
98
+ settings.L10n.thousands_separator = ","
99
+ # Uncomment this to Translate Layer Names
100
+ #settings.L10n.translate_gis_layer = True
101
+ # Uncomment this to Translate Location Names
102
+ #settings.L10n.translate_gis_location = True
103
+ # Uncomment this to Translate Organisation Names/Acronyms
104
+ #settings.L10n.translate_org_organisation = True
105
+ # Finance settings
106
+ #settings.fin.currencies = {
107
+ # "EUR" : "Euros",
108
+ # "GBP" : "Great British Pounds",
109
+ # "USD" : "United States Dollars",
110
+ #}
111
+ #settings.fin.currency_default = "USD"
112
+
113
+ # Security Policy
114
+ # http://eden.sahanafoundation.org/wiki/S3AAA#System-widePolicy
115
+ # 1: Simple (default): Global as Reader, Authenticated as Editor
116
+ # 2: Editor role required for Update/Delete, unless record owned by session
117
+ # 3: Apply Controller ACLs
118
+ # 4: Apply both Controller & Function ACLs
119
+ # 5: Apply Controller, Function & Table ACLs
120
+ # 6: Apply Controller, Function, Table ACLs and Entity Realm
121
+ # 7: Apply Controller, Function, Table ACLs and Entity Realm + Hierarchy
122
+ # 8: Apply Controller, Function, Table ACLs, Entity Realm + Hierarchy and Delegations
123
+ #
124
+ #settings.security.policy = 7 # Organisation-ACLs
125
+
126
+ # -------------------------------------------------------------------------
127
+ # Comment/uncomment modules here to disable/enable them
128
+ # Modules menu is defined in modules/eden/menu.py
129
+ settings.modules = OrderedDict([
130
+ # Core modules which shouldn't be disabled
131
+ ("default", Storage(
132
+ name_nice = T("Home"),
133
+ restricted = False, # Use ACLs to control access to this module
134
+ access = None, # All Users (inc Anonymous) can see this module in the default menu & access the controller
135
+ module_type = None # This item is not shown in the menu
136
+ )),
137
+ ("admin", Storage(
138
+ name_nice = T("Administration"),
139
+ #description = "Site Administration",
140
+ restricted = True,
141
+ access = "|1|", # Only Administrators can see this module in the default menu & access the controller
142
+ module_type = None # This item is handled separately for the menu
143
+ )),
144
+ ("appadmin", Storage(
145
+ name_nice = T("Administration"),
146
+ #description = "Site Administration",
147
+ restricted = True,
148
+ module_type = None # No Menu
149
+ )),
150
+ ("errors", Storage(
151
+ name_nice = T("Ticket Viewer"),
152
+ #description = "Needed for Breadcrumbs",
153
+ restricted = False,
154
+ module_type = None # No Menu
155
+ )),
156
+ #("sync", Storage(
157
+ # name_nice = T("Synchronization"),
158
+ # #description = "Synchronization",
159
+ # restricted = True,
160
+ # access = "|1|", # Only Administrators can see this module in the default menu & access the controller
161
+ # module_type = None # This item is handled separately for the menu
162
+ #)),
163
+ #("tour", Storage(
164
+ # name_nice = T("Guided Tour Functionality"),
165
+ # module_type = None,
166
+ #)),
167
+ #("translate", Storage(
168
+ # name_nice = T("Translation Functionality"),
169
+ # #description = "Selective translation of strings based on module.",
170
+ # module_type = None,
171
+ #)),
172
+ ("gis", Storage(
173
+ name_nice = T("Map"),
174
+ #description = "Situation Awareness & Geospatial Analysis",
175
+ restricted = True,
176
+ module_type = 6, # 6th item in the menu
177
+ )),
178
+ ("pr", Storage(
179
+ name_nice = T("Person Registry"),
180
+ #description = "Central point to record details on People",
181
+ restricted = True,
182
+ access = "|1|", # Only Administrators can see this module in the default menu (access to controller is possible to all still)
183
+ module_type = 10
184
+ )),
185
+ ("org", Storage(
186
+ name_nice = T("Organizations"),
187
+ #description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities',
188
+ restricted = True,
189
+ module_type = 1
190
+ )),
191
+ #("hrm", Storage(
192
+ # name_nice = T("Staff"),
193
+ # #description = "Human Resources Management",
194
+ # restricted = True,
195
+ # module_type = 2,
196
+ #)),
197
+ #("vol", Storage(
198
+ # name_nice = T("Volunteers"),
199
+ # #description = "Human Resources Management",
200
+ # restricted = True,
201
+ # module_type = 2,
202
+ #)),
203
+ #("cms", Storage(
204
+ # name_nice = T("Content Management"),
205
+ # #description = "Content Management System",
206
+ # restricted = True,
207
+ # module_type = 10,
208
+ #)),
209
+ #("doc", Storage(
210
+ # name_nice = T("Documents"),
211
+ # #description = "A library of digital resources, such as photos, documents and reports",
212
+ # restricted = True,
213
+ # module_type = 10,
214
+ #)),
215
+ #("msg", Storage(
216
+ # name_nice = T("Messaging"),
217
+ # #description = "Sends & Receives Alerts via Email & SMS",
218
+ # restricted = True,
219
+ # # The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules.
220
+ # module_type = None,
221
+ #)),
222
+ #("supply", Storage(
223
+ # name_nice = T("Supply Chain Management"),
224
+ # #description = "Used within Inventory Management, Request Management and Asset Management",
225
+ # restricted = True,
226
+ # module_type = None, # Not displayed
227
+ #)),
228
+ #("inv", Storage(
229
+ # name_nice = T("Warehouses"),
230
+ # #description = "Receiving and Sending Items",
231
+ # restricted = True,
232
+ # module_type = 4
233
+ #)),
234
+ #("asset", Storage(
235
+ # name_nice = T("Assets"),
236
+ # #description = "Recording and Assigning Assets",
237
+ # restricted = True,
238
+ # module_type = 5,
239
+ #)),
240
+ # Vehicle depends on Assets
241
+ #("vehicle", Storage(
242
+ # name_nice = T("Vehicles"),
243
+ # #description = "Manage Vehicles",
244
+ # restricted = True,
245
+ # module_type = 10,
246
+ #)),
247
+ #("req", Storage(
248
+ # name_nice = T("Requests"),
249
+ # #description = "Manage requests for supplies, assets, staff or other resources. Matches against Inventories where supplies are requested.",
250
+ # restricted = True,
251
+ # module_type = 10,
252
+ #)),
253
+ #("project", Storage(
254
+ # name_nice = T("Projects"),
255
+ # #description = "Tracking of Projects, Activities and Tasks",
256
+ # restricted = True,
257
+ # module_type = 2
258
+ #)),
259
+ #("cr", Storage(
260
+ # name_nice = T("Shelters"),
261
+ # #description = "Tracks the location, capacity and breakdown of victims in Shelters",
262
+ # restricted = True,
263
+ # module_type = 10
264
+ #)),
265
+ #("hms", Storage(
266
+ # name_nice = T("Hospitals"),
267
+ # #description = "Helps to monitor status of hospitals",
268
+ # restricted = True,
269
+ # module_type = 10
270
+ #)),
271
+ #("dvr", Storage(
272
+ # name_nice = T("Disaster Victim Registry"),
273
+ # #description = "Allow affected individuals & households to register to receive compensation and distributions",
274
+ # restricted = True,
275
+ # module_type = 10,
276
+ #)),
277
+ #("event", Storage(
278
+ # name_nice = T("Events"),
279
+ # #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).",
280
+ # restricted = True,
281
+ # module_type = 10,
282
+ #)),
283
+ #("transport", Storage(
284
+ # name_nice = T("Transport"),
285
+ # restricted = True,
286
+ # module_type = 10,
287
+ #)),
288
+ #("stats", Storage(
289
+ # name_nice = T("Statistics"),
290
+ # #description = "Manages statistics",
291
+ # restricted = True,
292
+ # module_type = None,
293
+ #)),
294
+ ])
295
+
296
+ # END =========================================================================
pool/shard001/Python/0012723_main.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys,tty,termios,time
2
+ import RPi.GPIO as GPIO
3
+
4
+ LEFT_PIN = 26
5
+ RIGHT_PIN = 16
6
+ STATUS_PIN = 13
7
+
8
+ class _Getch:
9
+ def __call__(self):
10
+ fd = sys.stdin.fileno()
11
+ old_settings = termios.tcgetattr(fd)
12
+ try:
13
+ tty.setraw(sys.stdin.fileno())
14
+ ch = sys.stdin.read(1)
15
+ finally:
16
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
17
+ return ch
18
+
19
+ def forward():
20
+ GPIO.output(LEFT_PIN, True)
21
+ time.sleep(0.1)
22
+ GPIO.output(RIGHT_PIN, True)
23
+
24
+ def left():
25
+ GPIO.output(LEFT_PIN, True)
26
+ GPIO.output(RIGHT_PIN, False)
27
+
28
+ def right():
29
+ GPIO.output(LEFT_PIN, False)
30
+ GPIO.output(RIGHT_PIN, True)
31
+
32
+ def stop():
33
+ GPIO.output((LEFT_PIN, RIGHT_PIN), False)
34
+
35
+ def get():
36
+ inkey = _Getch()
37
+ while(1):
38
+ k=inkey()
39
+ if k!='':break
40
+
41
+ if k == 'w':
42
+ forward()
43
+ elif k == 'a':
44
+ left()
45
+ elif k == 'd':
46
+ right()
47
+ elif k == 's':
48
+ stop()
49
+ elif k == 'p':
50
+ return False
51
+
52
+ return True
53
+
54
+ def main():
55
+ print "Hello Spider"
56
+
57
+ GPIO.setmode(GPIO.BCM)
58
+ GPIO.setup(LEFT_PIN, GPIO.OUT)
59
+ GPIO.setup(RIGHT_PIN, GPIO.OUT)
60
+ GPIO.setup(STATUS_PIN, GPIO.OUT)
61
+
62
+ GPIO.output(STATUS_PIN, True)
63
+ while get():
64
+ print "Still Running"
65
+
66
+ print "Exiting"
67
+ GPIO.output(STATUS_PIN, False)
68
+ GPIO.cleanup()
69
+
70
+ if __name__=='__main__':
71
+ main()
pool/shard001/Python/0012726_launcher.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import Tkinter as tk
3
+
4
+ from lib import config
5
+ #from lib import cheats
6
+ from lib import module
7
+ from lib import game
8
+
9
+ def show_module():
10
+ x = module.file.read()
11
+ return
12
+ def set_module_native():
13
+ module.file.write(module.native() )
14
+ def set_module_viking():
15
+ module.file.write(module.viking_conquest() )
16
+ def set_module_napoleonic():
17
+ module.file.write(module.napoleonic_wars() )
18
+
19
+ root = tk.Tk()
20
+ root.title("Bley-Bley Launcher")
21
+
22
+
23
+ root.mainloop()
pool/shard001/Python/0012730_filters.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.interpolate import CubicSpline
3
+
4
+ from hrv.rri import RRi
5
+ from hrv.utils import _create_time_info
6
+
7
+
8
+ __all__ = ['quotient', 'moving_average', 'moving_median', 'threshold_filter']
9
+
10
+
11
+ def quotient(rri):
12
+ """
13
+ Remove ectopic beats which the variation of two consecutive values
14
+ exceeds 20%
15
+
16
+ Parameters
17
+ ----------
18
+ rri : array_like
19
+ sequence containing the RRi series
20
+
21
+ Returns
22
+ -------
23
+ results : RRi array
24
+ instance of the RRi class containing the filtered RRi values
25
+
26
+ See Also
27
+ -------
28
+ moving_median, moving_averange, threshold_filter
29
+
30
+ References
31
+ ----------
32
+ - Piskorski J, Guzik P. Filtering poincare plots.
33
+ Comput Methods Sci Technol. 2005;11(1):39–48.
34
+
35
+ Examples
36
+ --------
37
+ >>> from hrv.filters import quotient
38
+ >>> from hrv.sampledata import load_noisy_rri
39
+ >>> noisy_rri = load_noisy_rri()
40
+ >>> quotient(noisy_rri)
41
+ RRi array([904., 913., 937., ..., 704., 805., 808.])
42
+ """
43
+ # TODO: Receive option to replaced outliers with stats
44
+ # functions (i.e mean, median etc)
45
+ # TODO: Receive option to re-create time array with cumsum of filtered rri
46
+ # TODO: Receive threshold value
47
+
48
+ if isinstance(rri, RRi):
49
+ rri_time = rri.time
50
+ rri = rri.values
51
+ else:
52
+ rri = np.array(rri)
53
+ rri_time = _create_time_info(rri)
54
+
55
+ L = len(rri) - 1
56
+
57
+ indices = np.where(
58
+ (rri[: L - 1] / rri[1:L] < 0.8)
59
+ | (rri[: L - 1] / rri[1:L] > 1.2)
60
+ | (rri[1:L] / rri[: L - 1] < 0.8)
61
+ | (rri[1:L] / rri[: L - 1] > 1.2)
62
+ )
63
+
64
+ rri_filt, time_filt = np.delete(rri, indices), np.delete(rri_time, indices)
65
+ return RRi(rri_filt, time_filt)
66
+
67
+
68
+ def moving_average(rri, order=3):
69
+ """
70
+ Low-pass filter. Replace each RRi value by the average of its ⌊N/2⌋
71
+ neighbors. The first and the last ⌊N/2⌋ RRi values are not filtered
72
+
73
+ Parameters
74
+ ----------
75
+ rri : array_like
76
+ sequence containing the RRi series
77
+ order : int, optional
78
+ Strength of the filter. Number of adjacent RRi values used to calculate
79
+ the average value to replace the current RRi. Defaults to 3.
80
+
81
+ .. math::
82
+ considering movinge average of order equal to 3:
83
+ RRi[j] = sum(RRi[j-2] + RRi[j-1] + RRi[j+1] + RRi[j+2]) / 3
84
+
85
+ Returns
86
+ -------
87
+ results : RRi array
88
+ instance of the RRi class containing the filtered RRi values
89
+
90
+ See Also
91
+ -------
92
+ moving_median, threshold_filter, quotient
93
+
94
+ Examples
95
+ --------
96
+ >>> from hrv.filters import moving_average
97
+ >>> from hrv.sampledata import load_noisy_rri
98
+ >>> noisy_rri = load_noisy_rri()
99
+ >>> moving_average(noisy_rri)
100
+ RRi array([904., 918., 941.66666667, ..., 732.66666667, 772.33333, 808.])
101
+
102
+ """
103
+ return _moving_function(rri, order, np.mean)
104
+
105
+
106
+ def moving_median(rri, order=3):
107
+ """
108
+ Low-pass filter. Replace each RRi value by the median of its ⌊N/2⌋
109
+ neighbors. The first and the last ⌊N/2⌋ RRi values are not filtered
110
+
111
+ Parameters
112
+ ----------
113
+ rri : array_like
114
+ sequence containing the RRi series
115
+ order : int, optional
116
+ Strength of the filter. Number of adjacent RRi values used to calculate
117
+ the median value to replace the current RRi. Defaults to 3.
118
+
119
+ .. math::
120
+ considering movinge average of order equal to 3:
121
+ RRi[j] = np.median([RRi[j-2], RRi[j-1], RRi[j+1], RRi[j+2]])
122
+
123
+ Returns
124
+ -------
125
+ results : RRi array
126
+ instance of the RRi class containing the filtered RRi values
127
+
128
+ See Also
129
+ -------
130
+ moving_average, threshold_filter, quotient
131
+
132
+ Examples
133
+ --------
134
+ >>> from hrv.filters import moving_average
135
+ >>> from hrv.sampledata import load_noisy_rri
136
+ >>> noisy_rri = load_noisy_rri()
137
+ >>> moving_median(noisy_rri)
138
+ RRi array([904., 913., 937., ..., 704., 805., 808.])
139
+ """
140
+ return _moving_function(rri, order, np.median)
141
+
142
+
143
+ def threshold_filter(rri, threshold="medium", local_median_size=5):
144
+ """
145
+ Low-pass filter. Inspired by the threshold-based artifact correction
146
+ algorithm offered by Kubios®. To elect outliers in the tachogram series,
147
+ each RRi is compared to the median value of local RRi (default N=5).
148
+ All the RRi which the difference is greater than the local median value
149
+ plus a threshold is replaced by cubic spline interpolated RRi.
150
+
151
+ Parameters
152
+ ----------
153
+ rri : array_like
154
+ sequence containing the RRi series
155
+ threshold : str or int, optional
156
+ Strength of the filter. If str will be translated to a threshold
157
+ in miliseconds according to the dict below. If int, it is considered
158
+ the threshold in miliseconds. Defaults to 'medium' (250ms)
159
+ - Very Low: 450ms
160
+ - Low: 350ms
161
+ - Medium: 250ms
162
+ - Strong: 150ms
163
+ - Very Strong: 50ms
164
+ local_median_size : int, optional
165
+ Number of RRi values considered to caculate a local median to be
166
+ compared with each RRi value
167
+
168
+ .. math::
169
+ considering the threshold equal to 'medium' and local_median_size
170
+ equal to 5:
171
+ local median RRi = np.median([RRi[j-5], RRi[j-4], RRi[j-3],
172
+ RRi[j-2], RRi[j-1]])
173
+ - Ectopic beat, if abs(RRi[j] - local median RRi) > 250
174
+ - Normal beat, if abs(RRi[j] - local median RRi) <= 250
175
+
176
+ Returns
177
+ -------
178
+ results : RRi array
179
+ instance of the RRi class containing the filtered and cubic
180
+ interpolated RRi values
181
+
182
+ See Also
183
+ -------
184
+ moving_average, threshold_filter, quotient
185
+
186
+ Examples
187
+ --------
188
+ >>> from hrv.filters import moving_average
189
+ >>> from hrv.sampledata import load_noisy_rri
190
+ >>> noisy_rri = load_noisy_rri()
191
+ >>> threshold_filter(noisy_rri)
192
+ RRi array([904., 913., 937., ..., 704., 805., 808.])
193
+ """
194
+ # TODO: DRY
195
+ if isinstance(rri, RRi):
196
+ rri_time = rri.time
197
+ rri = rri.values
198
+ else:
199
+ rri_time = _create_time_info(rri)
200
+
201
+ # Filter strength inspired in Kubios threshold based artifact correction
202
+ strength = {
203
+ "very low": 450,
204
+ "low": 350,
205
+ "medium": 250,
206
+ "strong": 150,
207
+ "very strong": 50,
208
+ }
209
+ threshold = strength[threshold] if threshold in strength else threshold
210
+
211
+ n_rri = len(rri)
212
+ rri_to_remove = []
213
+ # Apply filter in the beginning later
214
+ for j in range(local_median_size, n_rri):
215
+ slice_ = slice(j - local_median_size, j)
216
+ if rri[j] > (np.median(rri[slice_]) + threshold):
217
+ rri_to_remove.append(j)
218
+
219
+ first_idx = list(range(local_median_size + 1))
220
+ for j in range(local_median_size):
221
+ slice_ = [f for f in first_idx if not f == j]
222
+ if abs(rri[j] - np.median(rri[slice_])) > threshold:
223
+ rri_to_remove.append(j)
224
+
225
+ rri_temp = [r for idx, r in enumerate(rri) if idx not in rri_to_remove]
226
+ time_temp = [t for idx, t in enumerate(rri_time) if idx not in rri_to_remove]
227
+ cubic_spline = CubicSpline(time_temp, rri_temp)
228
+ return RRi(cubic_spline(rri_time), rri_time)
229
+
230
+
231
+ def _moving_function(rri, order, func):
232
+ if isinstance(rri, RRi):
233
+ rri_time = rri.time
234
+ rri = rri.values
235
+ else:
236
+ rri_time = _create_time_info(rri)
237
+
238
+ offset = int(order / 2)
239
+
240
+ # TODO: Implemente copy method for RRi class
241
+ filt_rri = np.array(rri.copy(), dtype=np.float64)
242
+ for i in range(offset, len(rri) - offset, 1):
243
+ filt_rri[i] = func(rri[i - offset : i + offset + 1])
244
+
245
+ return RRi(filt_rri, rri_time)