Pendigard commited on
Commit
8699b3a
·
verified ·
1 Parent(s): 15316da

Upload folder using huggingface_hub (part 18)

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/shard000/Python/0007510_save.py +42 -0
  2. pool/shard000/Python/0007513_netconns.py +114 -0
  3. pool/shard000/Python/0007515_torrent_tests.py +76 -0
  4. pool/shard000/Python/0007520_dbutils.py +65 -0
  5. pool/shard000/Python/0007523_crypto.py +88 -0
  6. pool/shard000/Python/0007526_bmn-fastaLenDistribOverlap.py +96 -0
  7. pool/shard000/Python/0007527_letters.py +147 -0
  8. pool/shard000/Python/0007528_test_auth_saml2.py +176 -0
  9. pool/shard000/Python/0007533_update_illinois.py +42 -0
  10. pool/shard000/Python/0007542_workspaceSymbol.py +53 -0
  11. pool/shard000/Python/0007547_setup.py +37 -0
  12. pool/shard000/Python/0007548_estemplateresponsewriter.py +116 -0
  13. pool/shard000/Python/0007550_0043_meta_update_project_links_and_machinerequest_new_version_membership.py +23 -0
  14. pool/shard000/Python/0007554_test_vtk_file_reader.py +63 -0
  15. pool/shard000/Python/0007558_init__.py +123 -0
  16. pool/shard000/Python/0007563_init__.py +62 -0
  17. pool/shard000/Python/0007564_test_consumers.py +216 -0
  18. pool/shard000/Python/0007579_tasks.py +110 -0
  19. pool/shard000/Python/0007583_variable_replace_test.py +56 -0
  20. pool/shard000/Python/0007594_judge.py +133 -0
  21. pool/shard000/Python/0007595_test_fact.py +58 -0
  22. pool/shard000/Python/0007596_test_loadables.py +113 -0
  23. pool/shard000/Python/0007601_setup.py +89 -0
  24. pool/shard000/Python/0007604_dummy.py +147 -0
  25. pool/shard000/Python/0007608_wrappers.py +168 -0
  26. pool/shard000/Python/0007611_widgets.py +219 -0
  27. pool/shard000/Python/0007612_protected_entities_radio_astronomy_sites.py +107 -0
  28. pool/shard000/Python/0007614_pyunit_expr_show.py +28 -0
  29. pool/shard000/Python/0007615_nss_http_server.py +106 -0
  30. pool/shard000/Python/0007617_sms_settings.py +108 -0
  31. pool/shard000/Python/0007618_setup.py +101 -0
  32. pool/shard000/Python/0007619_test_events.py +113 -0
  33. pool/shard000/Python/0007621_ScreenBlocksTest.py +48 -0
  34. pool/shard000/Python/0007623_first.py +25 -0
  35. pool/shard000/Python/0007624_get_redirected_url.py +55 -0
  36. pool/shard000/Python/0007625_pyminer.py +252 -0
  37. pool/shard000/Python/0007628_config.py +55 -0
  38. pool/shard000/Python/0007631_bluedump.py +39 -0
  39. pool/shard000/Python/0007632_getpathart.py +120 -0
  40. pool/shard000/Python/0007635_update_collection.py +117 -0
  41. pool/shard000/Python/0007640_get_completions_test.py +45 -0
  42. pool/shard000/Python/0007644_test_model_serializer_deserialize_fk.py +66 -0
  43. pool/shard000/Python/0007647_INIFILE.py +76 -0
  44. pool/shard000/Python/0007651_1138_01_01_SimpleGIS.py +116 -0
  45. pool/shard000/Python/0007654_071_simplify_path.py +40 -0
  46. pool/shard000/Python/0007657_cmakemakecp.py +54 -0
  47. pool/shard000/Python/0007659_server.py +139 -0
  48. pool/shard000/Python/0007664_news.py +140 -0
  49. pool/shard000/Python/0007667_rest_api_helper.py +238 -0
  50. pool/shard000/Python/0007668_grove_temp.py +20 -0
pool/shard000/Python/0007510_save.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+
4
+
5
+ class savedparser:
6
+
7
+ def __init__(self, saved_path: str):
8
+
9
+ if not os.path.isfile(saved_path):
10
+ raise FileNotFoundError
11
+
12
+ self.saved_path = saved_path
13
+
14
+ def parse(self):
15
+
16
+ with open(self.saved_path, 'r') as save_file:
17
+ articles = json.load(save_file)
18
+
19
+ return articles
20
+
21
+ def insert(self, article: dict):
22
+
23
+ with open(self.saved_path) as save_file:
24
+ articles = json.load(save_file)
25
+
26
+ ids_old = [a['id'] for a in articles]
27
+
28
+ if article['id'] not in ids_old:
29
+ articles = [article] + articles
30
+
31
+ with open(self.saved_path, 'w') as save_file:
32
+ json.dump(articles, save_file)
33
+
34
+ def remove(self, num: int=1):
35
+
36
+ with open(self.saved_path) as save_file:
37
+ articles = json.load(save_file)
38
+
39
+ articles = articles[:num-1] + articles[num:]
40
+
41
+ with open(self.saved_path, 'w') as save_file:
42
+ json.dump(articles, save_file)
pool/shard000/Python/0007513_netconns.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Volatility
2
+ # Copyright (C) 2007-2013 Volatility Foundation
3
+ #
4
+ # This file is part of Volatility.
5
+ #
6
+ # Volatility is free software; you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation; either version 2 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # Volatility is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with Volatility. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ """
21
+ @author: Andrew Case
22
+ @license: GNU General Public License 2.0
23
+ @contact: atcuno@gmail.com
24
+ @organization:
25
+ """
26
+
27
+ import volatility.obj as obj
28
+ import volatility.plugins.mac.common as common
29
+ from volatility.renderers import TreeGrid
30
+ from volatility.renderers.basic import Address
31
+
32
+ class mac_network_conns(common.AbstractMacCommand):
33
+ """ Lists network connections from kernel network structures """
34
+
35
+ # in_pcblookup_hash - bsd/netinet/in_pcb.c
36
+ def _walk_pcb_hash(self, proto_pcbinfo):
37
+ pcb_hash = obj.Object("Array", offset = proto_pcbinfo.hashbase, vm = self.addr_space, targetType = "Pointer", count = proto_pcbinfo.hashmask + 1)
38
+
39
+ for pcb_ent in pcb_hash:
40
+ head = pcb_ent.dereference_as("inpcbhead")
41
+
42
+ if not head:
43
+ continue
44
+
45
+ inpcb = head.lh_first.dereference_as("inpcb")
46
+
47
+ while inpcb:
48
+ yield inpcb
49
+ inpcb = inpcb.inp_hash.le_next
50
+
51
+ # in_pcblookup_hash - bsd/netinet/in_pcb.c
52
+ def _walk_pcb_list(self, proto_pcbinfo):
53
+ inpcb = proto_pcbinfo.listhead.lh_first.dereference_as("inpcb")
54
+
55
+ while inpcb:
56
+ yield inpcb
57
+ inpcb = inpcb.inp_list.le_next
58
+
59
+ def _walk_pcb_entries(self, inpcbinfo_addr):
60
+ pcbs = {}
61
+
62
+ inpcbinfo = obj.Object("inpcbinfo", offset = inpcbinfo_addr, vm = self.addr_space)
63
+
64
+ for pcbinfo in self._walk_pcb_list(inpcbinfo):
65
+ pcbs[pcbinfo.obj_offset] = pcbinfo
66
+
67
+ for pcbinfo in self._walk_pcb_hash(inpcbinfo):
68
+ pcbs[pcbinfo.obj_offset] = pcbinfo
69
+
70
+ for pcbinfo in pcbs.values():
71
+ (lip, lport, rip, rport) = pcbinfo.ipv4_info()
72
+ yield (pcbinfo, lip, lport, rip, rport)
73
+
74
+ def calculate(self):
75
+ common.set_plugin_members(self)
76
+
77
+ entries = []
78
+
79
+ tcbinfo_addr = self.addr_space.profile.get_symbol("_tcbinfo")
80
+ udbinfo_addr = self.addr_space.profile.get_symbol("_udbinfo")
81
+ ripdbinfo_addr = self.addr_space.profile.get_symbol("_ripcbinfo")
82
+
83
+ info_addrs = [("TCP", tcbinfo_addr), ("UDP", udbinfo_addr), ("RAW", ripdbinfo_addr)]
84
+
85
+ for (proto_str, info_addr) in info_addrs:
86
+ for (pcbinfo, lip, lport, rip, rport) in self._walk_pcb_entries(info_addr):
87
+ if proto_str == "TCP":
88
+ state = pcbinfo.get_tcp_state()
89
+ else:
90
+ state = ""
91
+ yield (proto_str, pcbinfo, lip, lport, rip, rport, state)
92
+
93
+ def unified_output(self, data):
94
+ return TreeGrid([("Offset (V)", Address),
95
+ ("Protocol", str),
96
+ ("Local IP", str),
97
+ ("Local Port", int),
98
+ ("Remote IP", str),
99
+ ("Remote Port", int),
100
+ ("State", str),
101
+ ], self.generator(data))
102
+
103
+ def generator(self, data):
104
+ for (proto, pcb, lip, lport, rip, rport, state) in data:
105
+ yield(0, [
106
+ Address(pcb.obj_offset),
107
+ str(proto),
108
+ str(lip),
109
+ int(lport),
110
+ str(rip),
111
+ int(rport),
112
+ str(state),
113
+ ])
114
+
pool/shard000/Python/0007515_torrent_tests.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import sickchill.logger
4
+ from sickchill import settings
5
+ from sickchill.oldbeard.providers import bitcannon, rarbg
6
+ from sickchill.tv import TVEpisode, TVShow
7
+ from tests import test_lib as test
8
+
9
+
10
+ class TorrentBasicTests(test.SickChillTestDBCase):
11
+ """
12
+ Test torrents
13
+ """
14
+ @classmethod
15
+ def setUpClass(cls):
16
+ cls.shows = []
17
+
18
+ show = TVShow(1, 121361)
19
+ show.name = "Italian Works"
20
+ show.episodes = []
21
+ episode = TVEpisode(show, 5, 10)
22
+ episode.name = "Pines of Rome"
23
+ episode.scene_season = 5
24
+ episode.scene_episode = 10
25
+ show.episodes.append(episode)
26
+ cls.shows.append(show)
27
+
28
+ def test_bitcannon(self):
29
+ """
30
+ Test bitcannon
31
+ """
32
+ provider = bitcannon.Provider()
33
+ provider.custom_url = "" # true testing requires a valid URL here (e.g., "http://localhost:3000/")
34
+ provider.api_key = ""
35
+
36
+ if provider.custom_url:
37
+
38
+ search_strings_list = provider.get_episode_search_strings(self.shows[0].episodes[0]) # [{'Episode': ['Italian Works S05E10']}]
39
+ for search_strings in search_strings_list:
40
+ provider.search(search_strings) # {'Episode': ['Italian Works S05E10']}
41
+
42
+ return True
43
+
44
+ @unittest.skip('Only run this manually')
45
+ def test_search(self):
46
+ """
47
+ Test searching, using rarbg
48
+ """
49
+ settings.CPU_PRESET = 'LOW'
50
+ provider = rarbg.Provider()
51
+ results = provider.search({'Episode': ['The Mandalorian S01E08']})
52
+ self.assertTrue(results)
53
+ self.assertIn('Mandalorian', results[0]['title'])
54
+
55
+ results = provider.search({'RSS': ['']})
56
+ self.assertTrue(results)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ print("==================")
61
+ print("STARTING - Torrent Basic TESTS")
62
+ print("==================")
63
+ print("######################################################################")
64
+
65
+ def override_log(msg, *args, **kwargs):
66
+ """Override the SickChill logger so we can see the debug output from providers"""
67
+ _ = args, kwargs
68
+ print(msg)
69
+
70
+ sickchill.logger.info = override_log
71
+ sickchill.logger.debug = override_log
72
+ sickchill.logger.error = override_log
73
+ sickchill.logger.warning = override_log
74
+
75
+ SUITE = unittest.TestLoader().loadTestsFromTestCase(TorrentBasicTests)
76
+ unittest.TextTestRunner(verbosity=2).run(SUITE)
pool/shard000/Python/0007520_dbutils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #encoding: utf-8
2
+
3
+ import MySQLdb
4
+
5
+ import gconf
6
+
7
+
8
+ def execute_fetch_sql(sql, args=(), fetch=True):
9
+ return execute_sql(sql, args, fetch)
10
+
11
+ def execute_commit_sql(sql, args=(), fetch=False):
12
+ return execute_sql(sql, args, fetch)
13
+
14
+
15
+ def execute_sql(sql, args=(), fetch=True):
16
+ _conn = None
17
+ _cur = None
18
+ _count = 0
19
+ _rt_list = []
20
+ try:
21
+ _conn = MySQLdb.connect(host=gconf.MYSQL_HOST, port=gconf.MYSQL_PORT, \
22
+ user=gconf.MYSQL_USER, passwd=gconf.MYSQL_PASSWD, \
23
+ db=gconf.MYSQL_DB, charset=gconf.MYSQL_CHARSET)
24
+
25
+ #_conn.autocommit(True) #autocommit
26
+ _cur = _conn.cursor()
27
+ _count = _cur.execute(sql, args)
28
+ if fetch:
29
+ _rt_list = _cur.fetchall()
30
+ else:
31
+ _conn.commit() #commit, 和autocommit任选其一
32
+ except BaseException as e:
33
+ print e
34
+ finally:
35
+ if _cur:
36
+ _cur.close()
37
+ if _conn:
38
+ _conn.close()
39
+ return _count, _rt_list
40
+
41
+ def bulker_commit_sql(sql, args_list=[]):
42
+ _conn = None
43
+ _cur = None
44
+ _count = 0
45
+ _rt_list = []
46
+ try:
47
+ _conn = MySQLdb.connect(host=gconf.MYSQL_HOST, port=gconf.MYSQL_PORT, \
48
+ user=gconf.MYSQL_USER, passwd=gconf.MYSQL_PASSWD, \
49
+ db=gconf.MYSQL_DB, charset=gconf.MYSQL_CHARSET)
50
+
51
+ #_conn.autocommit(True) #autocommit
52
+ _cur = _conn.cursor()
53
+ for _args in args_list:
54
+ print sql, _args
55
+ _count += _cur.execute(sql, _args)
56
+ _conn.commit() #commit, 和autocommit任选其一
57
+ except BaseException as e:
58
+ print e
59
+ finally:
60
+ if _cur:
61
+ _cur.close()
62
+ if _conn:
63
+ _conn.close()
64
+
65
+ return _count, _rt_list
pool/shard000/Python/0007523_crypto.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ #
3
+ # Copyright 2016 F5 Networks 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
+ """BIG-IP® system config module
18
+
19
+ REST URI
20
+ ``http://localhost/mgmt/tm/sys/config``
21
+
22
+ GUI Path
23
+ N/A
24
+
25
+ REST Kind
26
+ ``tm:sys:config:*``
27
+ """
28
+
29
+ from f5.bigip.resource import Collection
30
+ from f5.bigip.resource import OrganizingCollection
31
+ from f5.bigip.resource import Resource
32
+
33
+
34
+ class Crypto(OrganizingCollection):
35
+ def __init__(self, sys):
36
+ super(Crypto, self).__init__(sys)
37
+ self._meta_data['allowed_lazy_attributes'] = [
38
+ Certs,
39
+ Keys
40
+ ]
41
+
42
+
43
+ class Keys(Collection):
44
+ def __init__(self, crypto):
45
+ super(Keys, self).__init__(crypto)
46
+ self._meta_data['allowed_lazy_attributes'] = [
47
+ Key
48
+ ]
49
+ self._meta_data['attribute_registry'] =\
50
+ {'tm:sys:crypto:key:keystate': Key}
51
+
52
+ def install_key(self, certfilename, keyfilename):
53
+ payload =\
54
+ {"from-local-file": "/var/config/rest/downloads/%s" % keyfilename,
55
+ "command": "install",
56
+ "name": certfilename[:-4]}
57
+ self._meta_data['icr_session'].post(self._meta_data['uri'],
58
+ json=payload)
59
+
60
+
61
+ class Key(Resource):
62
+ def __init__(self, keys):
63
+ super(Key, self).__init__(keys)
64
+ self._meta_data['required_json_kind'] = 'tm:sys:crypto:key:keystate'
65
+
66
+
67
+ class Certs(Collection):
68
+ def __init__(self, crypto):
69
+ super(Certs, self).__init__(crypto)
70
+ self._meta_data['allowed_lazy_attributes'] = [
71
+ Cert
72
+ ]
73
+ self._meta_data['attribute_registry'] =\
74
+ {'tm:sys:crypto:cert:certstate': Cert}
75
+
76
+ def install_cert(self, certfilename):
77
+ payload =\
78
+ {"from-local-file": "/var/config/rest/downloads/%s" % certfilename,
79
+ "command": "install",
80
+ "name": certfilename[:-4]}
81
+ self._meta_data['icr_session'].post(self._meta_data['uri'],
82
+ json=payload)
83
+
84
+
85
+ class Cert(Resource):
86
+ def __init__(self, certs):
87
+ super(Cert, self).__init__(certs)
88
+ self._meta_data['required_json_kind'] = 'tm:sys:crypto:cert:certstate'
pool/shard000/Python/0007526_bmn-fastaLenDistribOverlap.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ ###
3
+
4
+
5
+ import string
6
+ import copy
7
+ import sys
8
+ from Bio import SeqIO
9
+ from StringIO import StringIO
10
+ import random
11
+
12
+ fastafile1 = sys.argv[1]
13
+ fastafile2 = sys.argv[2]
14
+ seqs1=[]
15
+ seqs2=[]
16
+ sizes1=[]
17
+
18
+ handle1 = open(fastafile1)
19
+ for seq_record in SeqIO.parse(handle1, "fasta"):
20
+ sizes1.append(len(seq_record.seq))
21
+ seqs1.append(seq_record)
22
+
23
+ handle1.close()
24
+
25
+ handle2 = open(fastafile2)
26
+ sizes2 = [len(seq_record.seq) for seq_record in SeqIO.parse(handle2, "fasta")]
27
+
28
+ handle2.close()
29
+
30
+
31
+ def uniq(seq):
32
+ keys = {}
33
+ for e in seq:
34
+ keys[e] = 1
35
+ return keys.keys()
36
+
37
+ allSizes=uniq(sizes1+sizes2)
38
+
39
+
40
+
41
+ distrib1={}
42
+ for i in allSizes:
43
+ distrib1[i]=0
44
+
45
+ distrib2=copy.deepcopy(distrib1)
46
+ distribCounter1=copy.deepcopy(distrib1)
47
+ distribCounter2=copy.deepcopy(distrib1)
48
+
49
+ for i in sizes1:
50
+ distrib1[i]+=1
51
+
52
+ for j in sizes2:
53
+ distrib2[j]+=1
54
+
55
+ distribCommon={}
56
+ for i in allSizes:
57
+ if min(distrib1[i],distrib2[i])!=0:
58
+ distribCommon[i]=min(distrib1[i],distrib2[i])
59
+
60
+ random.shuffle(seqs1)
61
+
62
+ handleout1 = open(fastafile1+".overlap", "w")
63
+
64
+ for i in seqs1:
65
+ seqsize=len(i.seq)
66
+ if distribCommon.has_key(seqsize):
67
+ if distribCounter1[seqsize] < distribCommon[seqsize]:
68
+ SeqIO.write(i, handleout1, "fasta")
69
+ distribCounter1[seqsize]+=1
70
+
71
+ handleout1.close()
72
+
73
+ handle2r = open(fastafile2)
74
+ for seq_record in SeqIO.parse(handle2r, "fasta"):
75
+ seqs2.append(seq_record)
76
+ handle2r.close()
77
+
78
+ random.shuffle(seqs2)
79
+
80
+ handleout2 = open(fastafile2+".overlap", "w")
81
+
82
+ for i in seqs2:
83
+ seqsize=len(i.seq)
84
+ if distribCommon.has_key(seqsize):
85
+ if distribCounter2[seqsize] < distribCommon[seqsize]:
86
+ SeqIO.write(i, handleout2, "fasta")
87
+ distribCounter2[seqsize]+=1
88
+
89
+ handleout2.close()
90
+
91
+
92
+
93
+
94
+
95
+
96
+
pool/shard000/Python/0007527_letters.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """This file is part of the prometeo project.
4
+
5
+ This program is free software: you can redistribute it and/or modify it
6
+ under the terms of the GNU Lesser General Public License as published by the
7
+ Free Software Foundation, either version 3 of the License, or (at your
8
+ option) any later version.
9
+
10
+ This program is distributed in the hope that it will be useful, but WITHOUT
11
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
+ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13
+ more details.
14
+
15
+ You should have received a copy of the GNU Lesser General Public License
16
+ along with this program. If not, see <http://www.gnu.org/licenses/>
17
+ """
18
+
19
+ __author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>'
20
+ __copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi'
21
+ __version__ = '0.0.5'
22
+
23
+ from django.utils.translation import ugettext_lazy as _
24
+ from django.shortcuts import render_to_response, get_object_or_404
25
+ from django.core.urlresolvers import reverse
26
+ from django.views.generic.simple import redirect_to
27
+ from django.views.generic import list_detail, create_update
28
+ from django.template import RequestContext
29
+ from django.contrib import messages
30
+
31
+ from prometeo.core.auth.decorators import obj_permission_required as permission_required
32
+ from prometeo.core.views import filtered_list_detail
33
+ from prometeo.documents.models import *
34
+ from prometeo.documents.forms import *
35
+ from prometeo.documents.views import *
36
+ from prometeo.products.forms import ProductEntryFormset
37
+
38
+ from ..models import *
39
+ from ..forms import *
40
+
41
+ def _get_letter(request, *args, **kwargs):
42
+ note_id = kwargs.get('note_id', None)
43
+ if note_id:
44
+ return get_object_or_404(Letter, id=note_id)
45
+ id = kwargs.get('id', None)
46
+ if id:
47
+ return get_object_or_404(Letter, id=id)
48
+ return None
49
+
50
+ @permission_required('partners.view_letter')
51
+ def letter_list(request, page=0, paginate_by=10, **kwargs):
52
+ """Shows a letter list.
53
+ """
54
+ return filtered_list_detail(
55
+ request,
56
+ Document.objects.get_for_content(Letter),
57
+ fields=['code', 'author', 'created', 'owner'],
58
+ page=page,
59
+ paginate_by=paginate_by,
60
+ template_name='partners/letter_list.html',
61
+ **kwargs
62
+ )
63
+
64
+ @permission_required('partners.add_letter')
65
+ def letter_add(request, **kwargs):
66
+ """Adds a new letter.
67
+ """
68
+ letter = Letter()
69
+ doc = Document(author=request.user, content_object=letter)
70
+
71
+ if request.method == 'POST':
72
+ dform = DocumentForm(request.POST, instance=doc)
73
+ form = LetterForm(request.POST, instance=letter)
74
+ if form.is_valid() and dform.is_valid():
75
+ form.save()
76
+ doc.content_object = letter
77
+ dform.save()
78
+ messages.success(request, _("The letter was created successfully."))
79
+ return redirect_to(request, url=doc.get_absolute_url())
80
+ else:
81
+ dform = DocumentForm(instance=doc)
82
+ form = LetterForm(instance=letter)
83
+
84
+ return render_to_response('partners/letter_edit.html', RequestContext(request, {'form': form, 'dform': dform, 'object': doc}))
85
+
86
+ @permission_required('partners.view_letter', _get_letter)
87
+ def letter_detail(request, id, page=None, **kwargs):
88
+ """Shows letter details.
89
+ """
90
+ object_list = Document.objects.get_for_content(Letter)
91
+
92
+ return list_detail.object_detail(
93
+ request,
94
+ object_id=object_list.get(object_id=id).pk,
95
+ queryset=object_list,
96
+ extra_context={
97
+ 'object_list': object_list,
98
+ },
99
+ template_name=kwargs.pop('template_name', 'partners/letter_detail.html'),
100
+ **kwargs
101
+ )
102
+
103
+ @permission_required('partners.change_letter', _get_letter)
104
+ def letter_edit(request, id, **kwargs):
105
+ """Edits a letter.
106
+ """
107
+ doc = get_object_or_404(Document.objects.get_for_content(Letter), object_id=id)
108
+ letter = doc.content_object
109
+
110
+ if request.method == 'POST':
111
+ dform = DocumentForm(request.POST, instance=doc)
112
+ form = LetterForm(request.POST, instance=letter)
113
+ if form.is_valid() and dform.is_valid():
114
+ form.save()
115
+ dform.save()
116
+ messages.success(request, _("The letter was updated successfully."))
117
+ return redirect_to(request, url=doc.get_absolute_url())
118
+ else:
119
+ dform = DocumentForm(instance=doc)
120
+ form = LetterForm(instance=letter)
121
+
122
+ return render_to_response('partners/letter_edit.html', RequestContext(request, {'form': form, 'dform': dform, 'object': doc}))
123
+
124
+ @permission_required('partners.delete_letter', _get_letter)
125
+ def letter_delete(request, id, **kwargs):
126
+ """Deletes a letter.
127
+ """
128
+ return create_update.delete_object(
129
+ request,
130
+ model=Document,
131
+ object_id=Document.objects.get_for_content(Letter).get(object_id=id).pk,
132
+ post_delete_redirect=reverse('letter_list'),
133
+ template_name='partners/letter_delete.html',
134
+ **kwargs
135
+ )
136
+
137
+ @permission_required('partners.view_letter', _get_letter)
138
+ def letter_hardcopies(request, id, page=0, paginate_by=10, **kwargs):
139
+ """Shows letter hard copies.
140
+ """
141
+ return hardcopy_list(request, Document.objects.get_for_content(Letter).get(object_id=id).pk, page, paginate_by, **kwargs)
142
+
143
+ @permission_required('partners.change_letter', _get_letter)
144
+ def letter_add_hardcopy(request, id, **kwargs):
145
+ """Adds an hard copy to the given document.
146
+ """
147
+ return hardcopy_add(request, Document.objects.get_for_content(Letter).get(object_id=id).pk, **kwargs)
pool/shard000/Python/0007528_test_auth_saml2.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import six
4
+ import pytest
5
+ import base64
6
+ import mock
7
+ from exam import fixture
8
+ from six.moves.urllib.parse import urlencode, urlparse, parse_qs
9
+
10
+ from django.conf import settings
11
+ from django.core.urlresolvers import reverse
12
+
13
+ from sentry.auth.providers.saml2 import SAML2Provider, Attributes, HAS_SAML2
14
+ from sentry.models import AuthProvider
15
+ from sentry.testutils import AuthProviderTestCase
16
+ from sentry.testutils.helpers import Feature
17
+
18
+
19
+ dummy_provider_config = {
20
+ 'idp': {
21
+ 'entity_id': 'https://example.com/saml/metadata/1234',
22
+ 'x509cert': 'foo_x509_cert',
23
+ 'sso_url': 'http://example.com/sso_url',
24
+ 'slo_url': 'http://example.com/slo_url',
25
+ },
26
+ 'attribute_mapping': {
27
+ Attributes.IDENTIFIER: 'user_id',
28
+ Attributes.USER_EMAIL: 'email',
29
+ Attributes.FIRST_NAME: 'first_name',
30
+ Attributes.LAST_NAME: 'last_name',
31
+ },
32
+ }
33
+
34
+
35
+ class DummySAML2Provider(SAML2Provider):
36
+ def get_saml_setup_pipeline(self):
37
+ return []
38
+
39
+ def build_config(self, state):
40
+ return dummy_provider_config
41
+
42
+
43
+ @pytest.mark.skipif(not HAS_SAML2, reason='SAML2 library is not installed')
44
+ class AuthSAML2Test(AuthProviderTestCase):
45
+ provider = DummySAML2Provider
46
+ provider_name = 'saml2_dummy'
47
+
48
+ def setUp(self):
49
+ self.user = self.create_user('rick@onehundredyears.com')
50
+ self.org = self.create_organization(owner=self.user, name='saml2-org')
51
+ self.auth_provider = AuthProvider.objects.create(
52
+ provider=self.provider_name,
53
+ config=dummy_provider_config,
54
+ organization=self.org,
55
+ )
56
+
57
+ # The system.url-prefix, which is used to generate absolute URLs, must
58
+ # have a TLD for the SAML2 library to consider the URL generated for
59
+ # the ACS endpoint valid.
60
+ self.url_prefix = settings.SENTRY_OPTIONS.get('system.url-prefix')
61
+
62
+ settings.SENTRY_OPTIONS.update({
63
+ 'system.url-prefix': 'http://testserver.com',
64
+ })
65
+
66
+ super(AuthSAML2Test, self).setUp()
67
+
68
+ def tearDown(self):
69
+ # restore url-prefix config
70
+ settings.SENTRY_OPTIONS.update({
71
+ 'system.url-prefix': self.url_prefix,
72
+ })
73
+
74
+ super(AuthSAML2Test, self).tearDown()
75
+
76
+ @fixture
77
+ def login_path(self):
78
+ return reverse('sentry-auth-organization', args=['saml2-org'])
79
+
80
+ @fixture
81
+ def acs_path(self):
82
+ return reverse('sentry-auth-organization-saml-acs', args=['saml2-org'])
83
+
84
+ @fixture
85
+ def setup_path(self):
86
+ return reverse('sentry-organization-auth-settings', args=['saml2-org'])
87
+
88
+ def test_redirects_to_idp(self):
89
+ resp = self.client.post(self.login_path, {'init': True})
90
+
91
+ assert resp.status_code == 302
92
+ redirect = urlparse(resp.get('Location', ''))
93
+ query = parse_qs(redirect.query)
94
+
95
+ assert redirect.path == '/sso_url'
96
+ assert 'SAMLRequest' in query
97
+
98
+ def accept_auth(self, **kargs):
99
+ saml_response = self.load_fixture('saml2_auth_response.xml')
100
+ saml_response = base64.b64encode(saml_response)
101
+
102
+ # Disable validation of the SAML2 mock response
103
+ is_valid = 'onelogin.saml2.response.OneLogin_Saml2_Response.is_valid'
104
+
105
+ with mock.patch(is_valid, return_value=True):
106
+ return self.client.post(self.acs_path, {'SAMLResponse': saml_response}, **kargs)
107
+
108
+ def test_auth_sp_initiated(self):
109
+ # Start auth process from SP side
110
+ self.client.post(self.login_path, {'init': True})
111
+ auth = self.accept_auth()
112
+
113
+ assert auth.status_code == 200
114
+ assert auth.context['existing_user'] == self.user
115
+
116
+ def test_auth_idp_initiated(self):
117
+ auth = self.accept_auth()
118
+
119
+ assert auth.status_code == 200
120
+ assert auth.context['existing_user'] == self.user
121
+
122
+ def test_auth_setup(self):
123
+ self.auth_provider.delete()
124
+ self.login_as(self.user)
125
+
126
+ data = {'init': True, 'provider': self.provider_name}
127
+
128
+ with Feature(['organizations:sso', 'organizations:sso-saml2']):
129
+ setup = self.client.post(self.setup_path, data)
130
+
131
+ assert setup.status_code == 302
132
+ redirect = urlparse(setup.get('Location', ''))
133
+ assert redirect.path == '/sso_url'
134
+
135
+ auth = self.accept_auth(follow=True)
136
+
137
+ messages = map(lambda m: six.text_type(m), auth.context['messages'])
138
+
139
+ assert len(messages) == 2
140
+ assert messages[0] == 'You have successfully linked your account to your SSO provider.'
141
+ assert messages[1].startswith('SSO has been configured for your organization')
142
+
143
+ def test_auth_idp_initiated_no_provider(self):
144
+ self.auth_provider.delete()
145
+ auth = self.accept_auth(follow=True)
146
+
147
+ assert auth.status_code == 200
148
+
149
+ messages = map(lambda m: six.text_type(m), auth.context['messages'])
150
+ assert len(messages) == 1
151
+ assert messages[0] == 'The organization does not exist or does not have SAML SSO enabled.'
152
+
153
+ def test_saml_metadata(self):
154
+ path = reverse('sentry-auth-organization-saml-metadata', args=['saml2-org'])
155
+ resp = self.client.get(path)
156
+
157
+ assert resp.status_code == 200
158
+ assert resp.get('content-type') == 'text/xml'
159
+
160
+ def test_logout_request(self):
161
+ saml_request = self.load_fixture('saml2_slo_request.xml')
162
+ saml_request = base64.b64encode(saml_request)
163
+
164
+ self.login_as(self.user)
165
+
166
+ path = reverse('sentry-auth-organization-saml-sls', args=['saml2-org'])
167
+ path = path + '?' + urlencode({'SAMLRequest': saml_request})
168
+ resp = self.client.get(path)
169
+
170
+ assert resp.status_code == 302
171
+
172
+ redirect = urlparse(resp.get('Location', ''))
173
+ query = parse_qs(redirect.query)
174
+
175
+ assert redirect.path == '/slo_url'
176
+ assert 'SAMLResponse' in query
pool/shard000/Python/0007533_update_illinois.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+
4
+
5
+ from spider import *
6
+
7
+ class IllinoisSpider(Spider):
8
+
9
+ def __init__(self):
10
+ Spider.__init__(self)
11
+ self.school = 'illinois'
12
+
13
+ def doWork(self):
14
+
15
+ file_name = self.get_file_name('eecs', self.school)
16
+ file_lines = self.countFileLineNum(file_name)
17
+ f = self.open_db(file_name + ".tmp")
18
+ self.count = 0
19
+
20
+ r = requests.get('http://ws.engr.illinois.edu/courses/list.asp?mode=timetable&unit=1434&profile=/courses/profile/&groupby=term&term=120151&type=~ind')
21
+ text = r.text
22
+ text = text.replace("document.write('", '').replace("');", '').replace("\\", '')
23
+ soup = BeautifulSoup(text)
24
+ for div in soup.find_all('div', class_='extCourse'):
25
+ sp = BeautifulSoup(div.prettify())
26
+ courseNum = sp.find('div', class_='extCourseRubric').text.replace(' ', '').strip()
27
+ title = sp.find('div', class_='extCourseTitle').text.strip()
28
+ link = 'http://cs.illinois.edu/courses/profile/' + courseNum
29
+ print courseNum + ' ' + title
30
+ self.count += 1
31
+ self.write_db(f, courseNum, title, link)
32
+
33
+ self.close_db(f)
34
+ if file_lines != self.count and self.count > 0:
35
+ self.do_upgrade_db(file_name)
36
+ print "before lines: " + str(file_lines) + " after update: " + str(self.count) + " \n\n"
37
+ else:
38
+ self.cancel_upgrade(file_name)
39
+ print "no need upgrade\n"
40
+
41
+ start = IllinoisSpider()
42
+ start.doWork()
pool/shard000/Python/0007542_workspaceSymbol.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os import path
2
+ import sys
3
+
4
+ from .base import Base
5
+
6
+ sys.path.insert(0, path.dirname(path.dirname(__file__)))
7
+
8
+ from common import ( # isort:skip # noqa: I100 E402
9
+ convert_symbols_to_candidates,
10
+ SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX,
11
+ highlight_setup,
12
+ )
13
+
14
+
15
+ class Source(Base):
16
+ def __init__(self, vim):
17
+ super().__init__(vim)
18
+ self.vim = vim
19
+
20
+ self.name = 'workspaceSymbol'
21
+ self.kind = 'file'
22
+
23
+ def highlight(self):
24
+ highlight_setup(self, SYMBOL_CANDIDATE_HIGHLIGHT_SYNTAX)
25
+
26
+ def gather_candidates(self, context):
27
+ context['is_interactive'] = True
28
+ prefix = context['input']
29
+ bufnr = context['bufnr']
30
+
31
+ # This a hack to get around the fact that LanguageClient APIs
32
+ # work in the context of the active buffer, when filtering results
33
+ # interactively, the denite buffer is the active buffer and it doesn't
34
+ # have a language server asscosiated with it.
35
+ # We just switch to the buffer that initiated the denite transaction
36
+ # and execute the command from it. This should be changed when we
37
+ # have a better way to run requests out of the buffer.
38
+ # See issue#674
39
+ current_buffer = self.vim.current.buffer.number
40
+ if current_buffer != bufnr:
41
+ self.vim.command("tabedit %")
42
+ self.vim.command(
43
+ "execute 'noautocmd keepalt buffer' {}".format(bufnr))
44
+ result = self.vim.funcs.LanguageClient_runSync(
45
+ 'LanguageClient#workspace_symbol', prefix, {}) or []
46
+ if current_buffer != bufnr:
47
+ self.vim.command("tabclose")
48
+
49
+ candidates = convert_symbols_to_candidates(
50
+ result,
51
+ pwd=self.vim.funcs.getcwd())
52
+
53
+ return candidates
pool/shard000/Python/0007547_setup.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: UTF-8 -*-
2
+
3
+ from distutils.core import setup
4
+
5
+ # http://stackoverflow.com/a/7071358/735926
6
+ import re
7
+ VERSIONFILE='omitempty/__init__.py'
8
+ verstrline = open(VERSIONFILE, 'rt').read()
9
+ VSRE = r'^__version__\s+=\s+[\'"]([^\'"]+)[\'"]'
10
+ mo = re.search(VSRE, verstrline, re.M)
11
+ if mo:
12
+ verstr = mo.group(1)
13
+ else:
14
+ raise RuntimeError("Unable to find version string in %s." % VERSIONFILE)
15
+
16
+ setup(
17
+ name='omitempty',
18
+ version=verstr,
19
+ author='Baptiste Fontaine',
20
+ author_email='b@ptistefontaine.fr',
21
+ packages=['omitempty'],
22
+ url='https://github.com/bfontaine/omitempty',
23
+ license=open('LICENSE', 'r').read(),
24
+ description='enums for Python',
25
+ long_description="""\
26
+ omitempty is a Golang's omitempty equivalent for Python""",
27
+ classifiers=[
28
+ 'License :: OSI Approved :: MIT License',
29
+ 'Programming Language :: Python :: 2.6',
30
+ 'Programming Language :: Python :: 2.7',
31
+ 'Programming Language :: Python :: 3.3',
32
+ 'Programming Language :: Python :: 3.4',
33
+ 'Programming Language :: Python :: 3.5',
34
+ 'Intended Audience :: Developers',
35
+ 'Operating System :: OS Independent',
36
+ ],
37
+ )
pool/shard000/Python/0007548_estemplateresponsewriter.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import *
2
+ import logging
3
+ import urllib
4
+ import json
5
+ from collections import OrderedDict
6
+
7
+ from edge.httputility import HttpUtility
8
+ from edge.writer.templateresponsewriter import TemplateResponseWriter
9
+
10
+ class ESTemplateResponseWriter(TemplateResponseWriter):
11
+ def __init__(self, configFilePath, requiredParams = None):
12
+ super(ESTemplateResponseWriter, self).__init__(configFilePath, requiredParams)
13
+ self.searchParameters = {}
14
+ self.variables = {}
15
+ self.facet = False
16
+ self.facetDefs = {}
17
+ self.contentType = 'application/xml'
18
+
19
+ def get(self, requestHandler):
20
+ super(ESTemplateResponseWriter, self).get(requestHandler)
21
+
22
+ startIndex = 0
23
+ try:
24
+ startIndex = requestHandler.get_argument('startIndex')
25
+ self.searchParameters['startIndex'] = startIndex
26
+ except:
27
+ pass
28
+
29
+ entriesPerPage = self._configuration.getint('solr', 'entriesPerPage')
30
+ try:
31
+ entriesPerPage = requestHandler.get_argument('itemsPerPage')
32
+ maxEntriesPerPage = self._configuration.getint('solr', 'maxEntriesPerPage')
33
+ if (int(entriesPerPage) > maxEntriesPerPage):
34
+ entriesPerPage = maxEntriesPerPage
35
+ self.searchParameters['itemsPerPage'] = entriesPerPage
36
+ except:
37
+ pass
38
+
39
+ try:
40
+ if requestHandler.get_argument('pretty').lower() == 'true':
41
+ self.pretty = True
42
+ self.searchParameters['pretty'] = 'true'
43
+ except:
44
+ pass
45
+
46
+ parameters = {}
47
+ for parameter in self._configuration.get('solr', 'parameters').split(','):
48
+ try:
49
+ value = requestHandler.get_arguments(parameter)
50
+ if len(value) == 1:
51
+ parameters[parameter] = value[0]
52
+ self.searchParameters[parameter] = value[0]
53
+ elif len(value) > 0:
54
+ parameters[parameter] = value
55
+ self.searchParameters[parameter] = value
56
+ except:
57
+ pass
58
+
59
+ facets = {}
60
+ if self._configuration.has_option('solr', 'facets'):
61
+ self.facetDefs = json.loads(self._configuration.get('solr', 'facets'), object_pairs_hook=OrderedDict)
62
+ for facet in self.facetDefs.keys():
63
+ try:
64
+ value = requestHandler.get_arguments(facet)
65
+ if len(value) > 0:
66
+ facets[self.facetDefs[facet]] = value
67
+ self.searchParameters[facet] = value
68
+ except:
69
+ pass
70
+
71
+ try:
72
+ self._getResponse(startIndex, entriesPerPage, parameters, facets)
73
+ except:
74
+ logging.exception('Failed to get solr response.')
75
+
76
+ def _urlEncodeSolrQueryValue(self, value):
77
+ return urllib.quote('"'+value+'"')
78
+
79
+ def _onResponse(self, response):
80
+ logging.debug(response)
81
+ if response.error:
82
+ self._handleException(str(response.error))
83
+ else:
84
+ self._writeResponse(response.body)
85
+
86
+ def _writeResponse(self, responseText):
87
+ searchText = ''
88
+ if 'keyword' in self.variables:
89
+ searchText = self.variables['keyword']
90
+ try:
91
+ openSearchResponse = self._generateOpenSearchResponse(
92
+ responseText,
93
+ searchText,
94
+ self._configuration.get('service', 'url') + self.requestHandler.request.path,
95
+ self.searchParameters,
96
+ self.pretty
97
+ )
98
+ self.requestHandler.set_header("Content-Type", self.contentType)
99
+ self.requestHandler.set_header('Access-Control-Allow-Origin', '*')
100
+ self.requestHandler.write(openSearchResponse)
101
+ self.requestHandler.finish()
102
+ except BaseException as exception:
103
+ self._handleException(str(exception))
104
+
105
+ def _getResponse(self, startIndex, entriesPerPage, parameters, facets):
106
+ query = self._constructQuery(startIndex, entriesPerPage, parameters, facets)
107
+ url = self._configuration.get('solr', 'datasetUrl')
108
+
109
+ httpUtility = HttpUtility()
110
+ httpUtility.getResponse(url+'/_search/?'+query, self._onResponse)
111
+
112
+ def _generateOpenSearchResponse(self, solrResponse, searchText, searchUrl, searchParams, pretty):
113
+ pass
114
+
115
+ def _constructQuery(self, startIndex, entriesPerPage, parameters, facets):
116
+ pass
pool/shard000/Python/0007550_0043_meta_update_project_links_and_machinerequest_new_version_membership.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import unicode_literals
3
+
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('core', '0042_add_external_link_and_project_resources'),
11
+ ]
12
+
13
+ operations = [
14
+ migrations.AlterField(
15
+ model_name='machinerequest',
16
+ name='new_version_membership',
17
+ field=models.ManyToManyField(to='core.Group', blank=True),
18
+ ),
19
+ migrations.AlterModelTable(
20
+ name='projectexternallink',
21
+ table='project_links',
22
+ ),
23
+ ]
pool/shard000/Python/0007554_test_vtk_file_reader.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2015, Enthought, Inc.
2
+ # License: BSD Style.
3
+
4
+ # Standard library imports.
5
+ import unittest
6
+
7
+ # External library imports
8
+ import vtk
9
+
10
+ # Enthought library imports
11
+ from mayavi.sources.vtk_file_reader import VTKFileReader
12
+
13
+ # Local imports.
14
+ from .common import get_example_data
15
+
16
+ vtk_major_version = vtk.vtkVersion.GetVTKMajorVersion()
17
+ vtk_minor_version = vtk.vtkVersion.GetVTKMinorVersion()
18
+
19
+ class TestVTKFileReader(unittest.TestCase):
20
+ def setUp(self):
21
+ # Read a VTK data file.
22
+ self.src = VTKFileReader()
23
+
24
+ def tearDown(self):
25
+ """For necessary clean up, automatically called by TestCase
26
+ after the test methods have been invoked"""
27
+ self.src = None
28
+ return
29
+
30
+ def check(self, n_points, n_cells):
31
+ """Do the actual testing."""
32
+ output = self.src.outputs[0]
33
+ self.assertEqual(output.number_of_points, n_points)
34
+ self.assertEqual(output.number_of_cells, n_cells)
35
+
36
+ def test_structured_points_file(self):
37
+ self.src.initialize(get_example_data('texThres2.vtk'))
38
+ self.check(128, 127)
39
+
40
+ def test_rectiliner_grid_file(self):
41
+ self.src.initialize(get_example_data('RectGrid2.vtk'))
42
+ self.check(17061, 14720)
43
+
44
+ def test_polydata_file(self):
45
+ self.src.initialize(get_example_data('polyEx.vtk'))
46
+ self.check(8, 6)
47
+
48
+ def test_structured_grid_file(self):
49
+ self.src.initialize(get_example_data('SampleStructGrid.vtk'))
50
+ self.check(24000, 21489)
51
+
52
+ @unittest.skipIf(vtk_major_version == 5 and vtk_minor_version < 10,
53
+ "This test is probably broken in VTK < 5.10")
54
+ def test_unstructured_grid_file(self):
55
+ self.src.initialize(get_example_data('UGridEx.vtk'))
56
+ self.check(27, 12)
57
+
58
+ def test_field_file(self):
59
+ self.src.initialize(get_example_data('fieldfile.vtk'))
60
+ self.check(18, 3)
61
+
62
+ if __name__ == '__main__':
63
+ unittest.main()
pool/shard000/Python/0007558_init__.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google Inc. 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
+ # shared resources and global variables
16
+ from tailbone import AppError
17
+ from tailbone import PREFIX
18
+ from tailbone import as_json
19
+ from tailbone import BreakError
20
+ from tailbone import config
21
+ from tailbone import DEBUG
22
+ from tailbone import restful
23
+
24
+ import re
25
+ import urllib
26
+ import webapp2
27
+
28
+ HAS_PIL = True
29
+ try:
30
+ import PIL
31
+ from google.appengine.api.images import delete_serving_url
32
+ from google.appengine.api.images import get_serving_url_async
33
+ except:
34
+ HAS_PIL = False
35
+
36
+ from google.appengine.ext.ndb import blobstore
37
+ from google.appengine.ext import blobstore as bs
38
+ from google.appengine.ext.webapp import blobstore_handlers
39
+ from google.appengine.api import lib_config
40
+
41
+ class _ConfigDefaults(object):
42
+ CLOUDSTORE = None
43
+
44
+ _config = lib_config.register('tailboneFiles', _ConfigDefaults.__dict__)
45
+
46
+
47
+ re_image = re.compile(r"image/(png|jpeg|jpg|webp|gif|bmp|tiff|ico)", re.IGNORECASE)
48
+
49
+
50
+ class BlobInfo(blobstore.BlobInfo):
51
+ def to_dict(self, *args, **kwargs):
52
+ result = super(BlobInfo, self).to_dict(*args, **kwargs)
53
+ result["Id"] = str(self.key())
54
+ return result
55
+
56
+
57
+ def blob_info_to_dict(blob_info):
58
+ d = {}
59
+ for prop in ["content_type", "creation", "filename", "size"]:
60
+ d[prop] = getattr(blob_info, prop)
61
+ key = blob_info.key()
62
+ if HAS_PIL and re_image.match(blob_info.content_type):
63
+ d["image_url"] = get_serving_url_async(key)
64
+ d["Id"] = str(key)
65
+ return d
66
+
67
+
68
+ class FilesHandler(blobstore_handlers.BlobstoreDownloadHandler):
69
+
70
+ @as_json
71
+ def get(self, key):
72
+ if key == "": # query
73
+ if not config.is_current_user_admin():
74
+ raise AppError("User must be administrator.")
75
+ return restful.query(self, BlobInfo)
76
+ elif key == "create":
77
+ #, gs_bucket_name=_config.CLOUDSTORE)
78
+ return {
79
+ "upload_url": blobstore.create_upload_url("/api/files/upload")
80
+ }
81
+ key = str(urllib.unquote(key))
82
+ blob_info = bs.BlobInfo.get(key)
83
+ if blob_info:
84
+ self.send_blob(blob_info)
85
+ raise BreakError
86
+ else:
87
+ self.error(404)
88
+ return {"error": "File not found with key " + key}
89
+
90
+ @as_json
91
+ def post(self, _):
92
+ raise AppError("You must make a GET call to /api/files/create to get a POST url.")
93
+
94
+ @as_json
95
+ def put(self, _):
96
+ raise AppError("PUT is not supported for the files api.")
97
+
98
+ @as_json
99
+ def delete(self, key):
100
+ if not config.is_current_user_admin():
101
+ raise AppError("User must be administrator.")
102
+ key = blobstore.BlobKey(str(urllib.unquote(key)))
103
+ blob_info = BlobInfo.get(key)
104
+ if blob_info:
105
+ blob_info.delete()
106
+ if HAS_PIL and re_image.match(blob_info.content_type):
107
+ delete_serving_url(key)
108
+ return {}
109
+ else:
110
+ self.error(404)
111
+ return {"error": "File not found with key " + key}
112
+
113
+
114
+ class FilesUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
115
+ @as_json
116
+ def post(self):
117
+ return [blob_info_to_dict(b) for b in self.get_uploads()]
118
+
119
+
120
+ app = webapp2.WSGIApplication([
121
+ (r"{}files/upload".format(PREFIX), FilesUploadHandler),
122
+ (r"{}files/?(.*)".format(PREFIX), FilesHandler),
123
+ ], debug=DEBUG)
pool/shard000/Python/0007563_init__.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (c) 2006 Jan-Klaas Kollhof
3
+
4
+ This file is part of jsonrpc.
5
+
6
+ jsonrpc is free software; you can redistribute it and/or modify
7
+ it under the terms of the GNU Lesser General Public License as published by
8
+ the Free Software Foundation; either version 2.1 of the License, or
9
+ (at your option) any later version.
10
+
11
+ This software is distributed in the hope that it will be useful,
12
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ GNU Lesser General Public License for more details.
15
+
16
+ You should have received a copy of the GNU Lesser General Public License
17
+ along with this software; if not, write to the Free Software
18
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
+ """
20
+
21
+ from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote
22
+ import sys, os
23
+ import Cookie
24
+
25
+ def read_data():
26
+ try:
27
+ contLen=int(os.environ['CONTENT_LENGTH'])
28
+ data = sys.stdin.read(contLen)
29
+ except:
30
+ data = ""
31
+ return data
32
+
33
+ def write_data(data, cookies):
34
+ if not isinstance(data, list):
35
+ data = [data]
36
+ data = "\n".join(data)
37
+ response = "Content-Type: text/plain\n"
38
+ if cookies:
39
+ response += cookies+"\n"
40
+ response += "Content-Length: %d\n\n" % len(data)
41
+ response += data
42
+
43
+ #on windows all \n are converted to \r\n if stdout is a terminal and
44
+ # is not set to binary mode :(
45
+ #this will then cause an incorrect Content-length.
46
+ #I have only experienced this problem with apache on Win so far.
47
+ if sys.platform == "win32":
48
+ import msvcrt
49
+ msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
50
+ #put out the response
51
+ sys.stdout.write(response)
52
+
53
+ class CGIJSONRPCService(JSONRPCServiceBase):
54
+ def set_cookies(self, c):
55
+ self._cookies = c
56
+
57
+ def __call__(self):
58
+ self._cookies = Cookie.SmartCookie()
59
+ self._cookies.load(os.environ.get('HTTP_COOKIE', ''))
60
+ d = read_data() # TODO: handle partial data
61
+ write_data(self.process(d), self._cookies.output())
62
+
pool/shard000/Python/0007564_test_consumers.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2014 Rackspace, 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
12
+ # implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import copy
16
+
17
+ from testtools import testcase
18
+
19
+ from functionaltests.api import base
20
+ from functionaltests.api.v1.behaviors import consumer_behaviors
21
+ from functionaltests.api.v1.behaviors import container_behaviors
22
+ from functionaltests.api.v1.behaviors import secret_behaviors
23
+ from functionaltests.api.v1.models import consumer_model
24
+ from functionaltests.api.v1.models import container_models
25
+ from functionaltests.api.v1.models import secret_models
26
+
27
+ create_secret_data = {
28
+ "name": "AES key",
29
+ "expiration": "2018-02-28T19:14:44.180394",
30
+ "algorithm": "aes",
31
+ "bit_length": 256,
32
+ "mode": "cbc",
33
+ "payload": "gF6+lLoF3ohA9aPRpt+6bQ==",
34
+ "payload_content_type": "application/octet-stream",
35
+ "payload_content_encoding": "base64",
36
+ }
37
+
38
+ default_consumer_data = {
39
+ "name": "consumername",
40
+ "URL": "consumerURL"
41
+ }
42
+
43
+ create_container_data = {
44
+ "name": "containername",
45
+ "type": "generic",
46
+ "secret_refs": [
47
+ {
48
+ "name": "secret1",
49
+ },
50
+ {
51
+ "name": "secret2",
52
+ }
53
+ ]
54
+ }
55
+
56
+
57
+ class ConsumersTestCase(base.TestCase):
58
+ default_data = default_consumer_data
59
+
60
+ def _create_a_secret(self):
61
+ secret_model = secret_models.SecretModel(**create_secret_data)
62
+ resp, secret_ref = self.secret_behaviors.create_secret(secret_model)
63
+ self.assertEqual(resp.status_code, 201)
64
+ self.assertIsNotNone(secret_ref)
65
+
66
+ return secret_ref
67
+
68
+ def setUp(self):
69
+ super(ConsumersTestCase, self).setUp()
70
+ self.secret_behaviors = secret_behaviors.SecretBehaviors(self.client)
71
+ self.container_behaviors = container_behaviors.ContainerBehaviors(
72
+ self.client
73
+ )
74
+ self.consumer_behaviors = consumer_behaviors.ConsumerBehaviors(
75
+ self.client
76
+ )
77
+
78
+ self.consumer_data = copy.deepcopy(self.default_data)
79
+
80
+ # Set up two secrets
81
+ secret_ref_1 = self._create_a_secret()
82
+ secret_ref_2 = self._create_a_secret()
83
+
84
+ # Create a container with our secrets
85
+ create_container_data['secret_refs'][0]['secret_ref'] = secret_ref_1
86
+ create_container_data['secret_refs'][1]['secret_ref'] = secret_ref_2
87
+ container_model = container_models.ContainerModel(
88
+ **create_container_data
89
+ )
90
+
91
+ resp, container_ref = self.container_behaviors.create_container(
92
+ container_model
93
+ )
94
+ self.assertEqual(resp.status_code, 201)
95
+ self.assertIsNotNone(container_ref)
96
+ self.container_ref = container_ref
97
+
98
+ def tearDown(self):
99
+ self.secret_behaviors.delete_all_created_secrets()
100
+ super(ConsumersTestCase, self).tearDown()
101
+
102
+ @testcase.attr('positive')
103
+ def test_create_consumer_defaults(self):
104
+ """Covers consumer creation.
105
+
106
+ All of the data needed to create the consumer is provided in a
107
+ single POST.
108
+ """
109
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
110
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
111
+ test_model, self.container_ref)
112
+
113
+ self.assertEqual(resp.status_code, 200)
114
+ self.assertIsNotNone(consumer_data)
115
+
116
+ @testcase.attr('positive')
117
+ def test_get_consumer_defaults(self):
118
+ """Tests getting a list of consumers for a container."""
119
+ # Create first consumer
120
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
121
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
122
+ test_model, self.container_ref)
123
+
124
+ self.assertEqual(resp.status_code, 200)
125
+ self.assertIsNotNone(consumer_data)
126
+
127
+ # Create second consumer
128
+ test_model.name = "consumername2"
129
+ test_model.URL = "consumerURL2"
130
+
131
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
132
+ test_model, self.container_ref)
133
+
134
+ self.assertEqual(resp.status_code, 200)
135
+ self.assertIsNotNone(consumer_data)
136
+
137
+ # Get list of consumers
138
+ resp, consumers, nref, pref = self.consumer_behaviors.get_consumers(
139
+ self.container_ref
140
+ )
141
+ self.assertEqual(resp.status_code, 200)
142
+ self.assertIn("consumername", consumers[0].name)
143
+ self.assertIn("consumername2", consumers[1].name)
144
+
145
+ @testcase.attr('positive')
146
+ def test_delete_consumer_defaults(self):
147
+ """Covers consumer deletion.
148
+
149
+ A consumer is first created, and then the consumer is deleted and
150
+ verified to no longer exist.
151
+ """
152
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
153
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
154
+ test_model, self.container_ref)
155
+
156
+ self.assertEqual(resp.status_code, 200)
157
+ self.assertIsNotNone(consumer_data)
158
+
159
+ # Delete the consumer
160
+ resp, consumer_data = self.consumer_behaviors.delete_consumer(
161
+ test_model, self.container_ref
162
+ )
163
+ self.assertEqual(resp.status_code, 200)
164
+ self.assertIsNotNone(consumer_data)
165
+ self.assertNotIn(test_model.name, consumer_data)
166
+ self.assertNotIn(test_model.URL, consumer_data)
167
+
168
+ @testcase.attr('positive')
169
+ def test_recreate_consumer_defaults(self):
170
+ """Covers consumer recreation."""
171
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
172
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
173
+ test_model, self.container_ref)
174
+
175
+ self.assertEqual(resp.status_code, 200)
176
+ self.assertIsNotNone(consumer_data)
177
+
178
+ # Delete the consumer
179
+ resp, consumer_data = self.consumer_behaviors.delete_consumer(
180
+ test_model, self.container_ref
181
+ )
182
+ self.assertEqual(resp.status_code, 200)
183
+ self.assertIsNotNone(consumer_data)
184
+ self.assertNotIn(test_model.name, consumer_data)
185
+ self.assertNotIn(test_model.URL, consumer_data)
186
+
187
+ # Register the consumer again
188
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
189
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
190
+ test_model, self.container_ref)
191
+
192
+ self.assertEqual(resp.status_code, 200)
193
+ self.assertIsNotNone(consumer_data)
194
+
195
+ @testcase.attr('positive')
196
+ def test_create_consumer_defaults_is_idempotent(self):
197
+ """Covers checking that create consumer is idempotent."""
198
+ # Register the consumer once
199
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
200
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
201
+ test_model, self.container_ref)
202
+
203
+ self.assertEqual(resp.status_code, 200)
204
+ self.assertIsNotNone(consumer_data)
205
+
206
+ # Register the consumer again, without deleting it first
207
+ test_model = consumer_model.ConsumerModel(**self.consumer_data)
208
+ resp, consumer_data = self.consumer_behaviors.create_consumer(
209
+ test_model, self.container_ref)
210
+
211
+ count = consumer_data.count(self.consumer_data)
212
+
213
+ self.assertEqual(resp.status_code, 200)
214
+ self.assertIsNotNone(consumer_data)
215
+ self.assertIn(self.consumer_data, consumer_data)
216
+ self.assertEqual(1, count)
pool/shard000/Python/0007579_tasks.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mediacrush.config import _cfgi
2
+ from mediacrush.paths import file_storage
3
+ from mediacrush.objects import RedisObject, File, FailedFile, Album
4
+ from mediacrush.celery import app, get_task_logger, chord, signature
5
+ from mediacrush.processing import processor_table, detect
6
+ from mediacrush.fileutils import compression_rate, delete_file
7
+
8
+ import time
9
+ import os
10
+ import json
11
+
12
+ from subprocess import call
13
+
14
+ logger = get_task_logger(__name__)
15
+
16
+ @app.task
17
+ def zip_album(h):
18
+ a = Album.from_hash(h)
19
+ paths = map(lambda f: file_storage(f.original), a.items)
20
+ zip_path = file_storage(h + ".zip")
21
+
22
+ if os.path.exists(zip_path):
23
+ return
24
+
25
+ call(["zip", "-j", zip_path] + paths)
26
+
27
+ a.metadata = json.dumps({"has_zip": True})
28
+ a.save()
29
+
30
+ @app.task(bind=True, track_started=True)
31
+ def convert_file(self, h, path, p, metadata, processor_state, ignore_limit):
32
+ f = File.from_hash(h)
33
+
34
+ if p not in processor_table:
35
+ p = 'default'
36
+
37
+ processor = processor_table[p](path, f, processor_state, ignore_limit)
38
+
39
+ # Execute the synchronous step.
40
+ processor.sync()
41
+
42
+ # Save compression information
43
+ f = File.from_hash(h) # Reload file; user might have changed the config vector while processing
44
+ f.compression = compression_rate(path, f)
45
+ f.metadata = json.dumps(metadata)
46
+ f.save()
47
+
48
+ # Notify frontend: sync step is done.
49
+ self.update_state(state="READY")
50
+
51
+ # Execute the asynchronous step.
52
+ processor.important = False
53
+ processor.async()
54
+
55
+ @app.task
56
+ def cleanup(results, path, h):
57
+ f = File.from_hash(h)
58
+ os.unlink(path)
59
+
60
+ if f.status in ["internal_error", "error", "timeout", "unrecognised"]:
61
+ failed = FailedFile(hash=h, status=f.status) # Create a "failed file" record
62
+ failed.save()
63
+
64
+ delete_file(f)
65
+
66
+ @app.task
67
+ def process_file(path, h, ignore_limit):
68
+ t = time.time() + 2
69
+ while True:
70
+ f = File.from_hash(h)
71
+ if f or time.time() > t:
72
+ break
73
+ time.sleep(0.05) # Wait for Redis to catch up
74
+
75
+ try:
76
+ result = detect(path)
77
+ processor = result['type'] if result else 'default'
78
+ except:
79
+ processor = 'default'
80
+ finally:
81
+ if processor == 'default': # Unrecognised file type
82
+ failed = FailedFile(hash=h, status="unrecognised")
83
+ failed.save()
84
+
85
+ delete_file(f)
86
+ return
87
+
88
+ metadata = result['metadata'] if result else {}
89
+ processor_state = result['processor_state'] if result else {}
90
+
91
+ f.processor = processor
92
+ queue = "priority" if processor.startswith("image") else "celery"
93
+
94
+ setattr(f.flags, 'nsfw', False)
95
+ if result and result['flags']:
96
+ for flag, value in result['flags'].items():
97
+ setattr(f.flags, flag, value)
98
+
99
+ f.save()
100
+
101
+ args = [h, path, processor, metadata, processor_state, ignore_limit]
102
+ task = signature("mediacrush.tasks.convert_file", args=args, options={'queue': queue})
103
+ task_result = task.freeze() # This sets the taskid, so we can pass it to the UI
104
+
105
+ # This chord will execute `syncstep` and `asyncstep`, and `cleanup` after both of them have finished.
106
+ c = chord(task, cleanup.s(path, h))
107
+ c.apply_async()
108
+
109
+ f.taskid = task_result.id
110
+ f.save()
pool/shard000/Python/0007583_variable_replace_test.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Google Research Authors.
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
+ # python3
17
+ """Tests for task_set.variable_replace."""
18
+
19
+ import sonnet as snt
20
+
21
+ from task_set import variable_replace
22
+ import tensorflow.compat.v1 as tf
23
+
24
+
25
+ class VaraibleReplaceTest(tf.test.TestCase):
26
+
27
+ def test_variable_replace_getter(self):
28
+ with self.test_session() as sess:
29
+ context = variable_replace.VariableReplaceGetter()
30
+ mod = snt.Linear(1, custom_getter=context)
31
+
32
+ inp_data = tf.ones([10, 1])
33
+ with context.use_variables():
34
+ y1 = mod(inp_data)
35
+ sess.run(tf.initialize_all_variables())
36
+ np_y1 = sess.run(y1)
37
+
38
+ values = context.get_variable_dict()
39
+
40
+ new_values = {k: v + 1 for k, v in values.items()}
41
+
42
+ with context.use_value_dict(new_values):
43
+ np_y2 = mod(inp_data).eval()
44
+
45
+ self.assertNear((np_y2 - np_y1)[0], 2, 1e-8)
46
+
47
+ for v in values.values():
48
+ v.assign(v + 1).eval()
49
+
50
+ with context.use_variables():
51
+ np_y3 = mod(inp_data).eval()
52
+ self.assertNear((np_y3 - np_y2)[0], 0, 1e-8)
53
+
54
+
55
+ if __name__ == '__main__':
56
+ tf.test.main()
pool/shard000/Python/0007594_judge.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python
2
+ #-*- coding: utf8 -*-
3
+
4
+ from six import itervalues
5
+ from math import ceil
6
+ from settings import LANGUAGES, NODE
7
+ from sandbox import Sandbox
8
+ from result import Result
9
+ import threading
10
+ import logging
11
+
12
+
13
+ class Judge(threading.Thread):
14
+ """Compiles, executes and checks solutions for a specific task."""
15
+
16
+ def __init__(self, task, submission):
17
+ self.task = task
18
+ self.language = submission['language']
19
+ fileName = LANGUAGES[self.language].get('sourceFilename')
20
+ if callable(fileName):
21
+ fileName = fileName(submission['source'])
22
+ self.fileFullName = fileName
23
+ self.fileName, self.fileExtension = fileName.split('.')
24
+ self._results = []
25
+ self._compilation_log = None
26
+ self.source = submission['source']
27
+
28
+ # If the submission was sent in an active contest
29
+ # judge sample tests only
30
+ self.sampleTests = bool(int(submission['active']))
31
+ threading.Thread.__init__(self)
32
+
33
+ def run(self):
34
+ """Process the judge request - create the sandbox,
35
+ compile the source, execute and generate results."""
36
+
37
+ with Sandbox.new() as sandbox:
38
+ with sandbox.file(self.fileFullName) as sourceFile:
39
+ sourceFile.write(self.source)
40
+ self.compile(sandbox)
41
+ self.execute(sandbox)
42
+
43
+ def compare_files(self, out, ref=None):
44
+ """Basic comparation function.
45
+ Compares output file with reference file."""
46
+
47
+ out = out.rstrip()
48
+ ref = ref.rstrip()
49
+ out = out.split('\n')
50
+ ref = ref.split('\n')
51
+ if len(out) != len(ref):
52
+ return False
53
+ for outLine, refLine in zip(out, ref):
54
+ if outLine.rstrip() != refLine.rstrip():
55
+ return False
56
+ return True
57
+
58
+ def check_solution(self, out, ref=None, fun=compare_files):
59
+ """Compare solution with chosen function."""
60
+ return fun(self, out, ref)
61
+
62
+ def compile(self, sandbox):
63
+ """Compile source code and save compile logs"""
64
+ logging.info("Compiling the submission source.")
65
+ cmd = '{compiler} {compilerOptions} {fileName}.{fileExtension}'.format(
66
+ compiler=LANGUAGES[self.language].get('compiler'),
67
+ compilerOptions=LANGUAGES[self.language].get('compilerOptions'),
68
+ fileName=self.fileName,
69
+ fileExtension=self.fileExtension
70
+ )
71
+
72
+ ret = sandbox.execute(
73
+ cmd,
74
+ None,
75
+ timeLimit=NODE['SANDBOX']['COMPILER_TIMELIMIT']
76
+ )
77
+
78
+ self._compilation_log = u'{} {}'.format(*ret[0])
79
+ logging.info("Compilation finished.")
80
+
81
+ def execute(self, sandbox):
82
+ """Run program with all tests available for specific task
83
+ and compare using check_solution. Program is limited by execution time
84
+ and memory depending od information taken from the task."""
85
+ logging.info("Executing the submission.")
86
+ executionPath = LANGUAGES[self.language].get('runCommand').format(
87
+ fileName=self.fileName,
88
+ fileExtension=self.fileExtension,
89
+ sandboxHome=NODE['SANDBOX']['HOME_DIR'],
90
+ )
91
+
92
+ for test in itervalues(self.task.tests):
93
+ if not test.isSampleTest and self.sampleTests:
94
+ continue
95
+
96
+ (out, err), returncode, runTime = sandbox.execute(
97
+ executionPath,
98
+ test.input,
99
+ timeLimit=int(ceil(test.timeLimit)),
100
+ memoryLimit=test.memoryLimit
101
+ )
102
+
103
+ if not returncode == 0:
104
+ runTime = 0
105
+
106
+ if runTime > test.timeLimit:
107
+ returncode = 9
108
+
109
+ res = Result(
110
+ returncode,
111
+ int(self.check_solution(out, test.output) and returncode != 9),
112
+ runTime)
113
+ del out
114
+ self._results.append(res)
115
+ logging.info("Execution finished.")
116
+
117
+ if err:
118
+ logging.warning("There were errors during execution:\n{}".format(
119
+ err
120
+ ))
121
+
122
+ @property
123
+ def results(self):
124
+ """Return compiler logs and results"""
125
+ if len(self._results) == 0:
126
+ return None
127
+ return self._results
128
+
129
+ @property
130
+ def compilation_log(self):
131
+ if not self._compilation_log:
132
+ return None
133
+ return self._compilation_log
pool/shard000/Python/0007595_test_fact.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- encoding: utf-8 -*-
2
+ # vim: ts=4 sw=4 expandtab ai
3
+ """Test class for Fact CLI"""
4
+
5
+ from ddt import ddt
6
+ from fauxfactory import gen_string
7
+ from robottelo.cli.fact import Fact
8
+ from robottelo.common.decorators import data, run_only_on, stubbed
9
+ from robottelo.test import CLITestCase
10
+
11
+
12
+ @run_only_on('sat')
13
+ @ddt
14
+ class TestFact(CLITestCase):
15
+ """Fact related tests."""
16
+
17
+ @stubbed('Need to create facts before we can check them.')
18
+ @data(
19
+ 'uptime', 'uptime_days', 'uptime_seconds', 'memoryfree', 'ipaddress',
20
+ )
21
+ def test_list_success(self, fact):
22
+ """@Test: Test Fact List
23
+
24
+ @Feature: Fact - List Positive
25
+
26
+ @Assert: Fact List is displayed
27
+
28
+ """
29
+
30
+ args = {
31
+ 'search': "fact='%s'" % fact,
32
+ }
33
+
34
+ result = Fact().list(args)
35
+ stdout = result.stdout
36
+
37
+ self.assertEqual(stdout[0]['fact'], fact)
38
+
39
+ @data(
40
+ gen_string("alpha", 10),
41
+ gen_string("alpha", 10),
42
+ gen_string("alpha", 10),
43
+ gen_string("alpha", 10),
44
+ )
45
+ def test_list_fail(self, fact):
46
+ """@Test: Test Fact List failure
47
+
48
+ @Feature: Fact - List Negative
49
+
50
+ @Assert: Fact List is not displayed
51
+
52
+ """
53
+
54
+ args = {
55
+ 'search': "fact='%s'" % fact,
56
+ }
57
+ self.assertEqual(
58
+ Fact().list(args).stdout, [], "No records should be returned")
pool/shard000/Python/0007596_test_loadables.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2012 OpenStack Foundation # All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ # not use this file except in compliance with the License. You may obtain
5
+ # 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, WITHOUT
11
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ # License for the specific language governing permissions and limitations
13
+ # under the License.
14
+ """
15
+ Tests For Loadable class handling.
16
+ """
17
+
18
+ from zun.common import exception
19
+ from zun.tests import base
20
+ from zun.tests.unit.scheduler import fake_loadables
21
+
22
+
23
+ class LoadablesTestCase(base.TestCase):
24
+ def setUp(self):
25
+ super(LoadablesTestCase, self).setUp()
26
+ self.fake_loader = fake_loadables.FakeLoader()
27
+ # The name that we imported above for testing
28
+ self.test_package = 'zun.tests.unit.scheduler.fake_loadables'
29
+
30
+ def test_loader_init(self):
31
+ self.assertEqual(self.fake_loader.package, self.test_package)
32
+ # Test the path of the module
33
+ ending_path = '/' + self.test_package.replace('.', '/')
34
+ self.assertTrue(self.fake_loader.path.endswith(ending_path))
35
+ self.assertEqual(self.fake_loader.loadable_cls_type,
36
+ fake_loadables.FakeLoadable)
37
+
38
+ def _compare_classes(self, classes, expected):
39
+ class_names = [cls.__name__ for cls in classes]
40
+ self.assertEqual(set(class_names), set(expected))
41
+
42
+ def test_get_all_classes(self):
43
+ classes = self.fake_loader.get_all_classes()
44
+ expected_class_names = ['FakeLoadableSubClass1',
45
+ 'FakeLoadableSubClass2',
46
+ 'FakeLoadableSubClass5',
47
+ 'FakeLoadableSubClass6']
48
+ self._compare_classes(classes, expected_class_names)
49
+
50
+ def test_get_matching_classes(self):
51
+ prefix = self.test_package
52
+ test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1',
53
+ prefix + '.fake_loadable2.FakeLoadableSubClass5']
54
+ classes = self.fake_loader.get_matching_classes(test_classes)
55
+ expected_class_names = ['FakeLoadableSubClass1',
56
+ 'FakeLoadableSubClass5']
57
+ self._compare_classes(classes, expected_class_names)
58
+
59
+ def test_get_matching_classes_with_underscore(self):
60
+ prefix = self.test_package
61
+ test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1',
62
+ prefix + '.fake_loadable2._FakeLoadableSubClass7']
63
+ self.assertRaises(exception.ClassNotFound,
64
+ self.fake_loader.get_matching_classes,
65
+ test_classes)
66
+
67
+ def test_get_matching_classes_with_wrong_type1(self):
68
+ prefix = self.test_package
69
+ test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass4',
70
+ prefix + '.fake_loadable2.FakeLoadableSubClass5']
71
+ self.assertRaises(exception.ClassNotFound,
72
+ self.fake_loader.get_matching_classes,
73
+ test_classes)
74
+
75
+ def test_get_matching_classes_with_wrong_type2(self):
76
+ prefix = self.test_package
77
+ test_classes = [prefix + '.fake_loadable1.FakeLoadableSubClass1',
78
+ prefix + '.fake_loadable2.FakeLoadableSubClass8']
79
+ self.assertRaises(exception.ClassNotFound,
80
+ self.fake_loader.get_matching_classes,
81
+ test_classes)
82
+
83
+ def test_get_matching_classes_with_one_function(self):
84
+ prefix = self.test_package
85
+ test_classes = [prefix + '.fake_loadable1.return_valid_classes',
86
+ prefix + '.fake_loadable2.FakeLoadableSubClass5']
87
+ classes = self.fake_loader.get_matching_classes(test_classes)
88
+ expected_class_names = ['FakeLoadableSubClass1',
89
+ 'FakeLoadableSubClass2',
90
+ 'FakeLoadableSubClass5']
91
+ self._compare_classes(classes, expected_class_names)
92
+
93
+ def test_get_matching_classes_with_two_functions(self):
94
+ prefix = self.test_package
95
+ test_classes = [prefix + '.fake_loadable1.return_valid_classes',
96
+ prefix + '.fake_loadable2.return_valid_class']
97
+ classes = self.fake_loader.get_matching_classes(test_classes)
98
+ expected_class_names = ['FakeLoadableSubClass1',
99
+ 'FakeLoadableSubClass2',
100
+ 'FakeLoadableSubClass6']
101
+ self._compare_classes(classes, expected_class_names)
102
+
103
+ def test_get_matching_classes_with_function_including_invalids(self):
104
+ # When using a method, no checking is done on valid classes.
105
+ prefix = self.test_package
106
+ test_classes = [prefix + '.fake_loadable1.return_invalid_classes',
107
+ prefix + '.fake_loadable2.return_valid_class']
108
+ classes = self.fake_loader.get_matching_classes(test_classes)
109
+ expected_class_names = ['FakeLoadableSubClass1',
110
+ '_FakeLoadableSubClass3',
111
+ 'FakeLoadableSubClass4',
112
+ 'FakeLoadableSubClass6']
113
+ self._compare_classes(classes, expected_class_names)
pool/shard000/Python/0007601_setup.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Copyright (C) 2011 Cédric Krier
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
+ from setuptools import setup
19
+ import re
20
+ import os
21
+ import ConfigParser
22
+
23
+ def read(fname):
24
+ return open(os.path.join(os.path.dirname(__file__), fname)).read()
25
+
26
+ config = ConfigParser.ConfigParser()
27
+ config.readfp(open('tryton.cfg'))
28
+ info = dict(config.items('tryton'))
29
+
30
+ for key in ('depends', 'extras_depend', 'xml'):
31
+ if key in info:
32
+ info[key] = info[key].strip().splitlines()
33
+ major_version, minor_version = 3, 8
34
+
35
+ requires = []
36
+
37
+ for dep in info.get('depends', []):
38
+ if dep.startswith('health'):
39
+ requires.append('trytond_%s == %s' %
40
+ (dep, info.get('version')))
41
+ elif not re.match(r'(ir|res|webdav)(\W|$)', dep):
42
+ requires.append('trytond_%s >= %s.%s, < %s.%s' %
43
+ (dep, major_version, minor_version, major_version,
44
+ minor_version + 1))
45
+ requires.append('trytond >= %s.%s, < %s.%s' %
46
+ (major_version, minor_version, major_version, minor_version + 1))
47
+
48
+ setup(name='trytond_health_crypto',
49
+ version=info.get('version', '0.0.1'),
50
+ description=info.get('description', 'GNU Health Cryptography Module'),
51
+ author=info.get('author', 'GNU Solidario'),
52
+ author_email=info.get('email', 'health@gnusolidario.org'),
53
+ url=info.get('website', 'http://health.gnu.org/'),
54
+ download_url='http://ftp.gnu.org/gnu/health/',
55
+ package_dir={'trytond.modules.health_crypto': '.'},
56
+ packages=[
57
+ 'trytond.modules.health_crypto',
58
+ ],
59
+ package_data={
60
+ 'trytond.modules.health_crypto': info.get('xml', []) \
61
+ + info.get('translation', []) \
62
+ + ['tryton.cfg', 'view/*.xml', 'doc/*.rst', 'locale/*.po',
63
+ 'report/*.odt', 'icons/*.svg'],
64
+ },
65
+
66
+ classifiers=[
67
+ 'Development Status :: 5 - Production/Stable',
68
+ 'Environment :: Plugins',
69
+ 'Framework :: Tryton',
70
+ 'Intended Audience :: Developers',
71
+ 'Intended Audience :: Healthcare Industry',
72
+ 'License :: OSI Approved :: GNU General Public License (GPL)',
73
+ 'Natural Language :: English',
74
+ 'Natural Language :: Spanish',
75
+ 'Operating System :: OS Independent',
76
+ 'Programming Language :: Python :: 2.7',
77
+ 'Topic :: Scientific/Engineering :: Bio-Informatics',
78
+ 'Topic :: Scientific/Engineering :: Medical Science Apps.',
79
+ ],
80
+ license='GPL-3',
81
+ install_requires=requires,
82
+ zip_safe=False,
83
+ entry_points="""
84
+ [trytond.modules]
85
+ health_crypto = trytond.modules.health_crypto
86
+ """,
87
+ test_suite='tests',
88
+ test_loader='trytond.test_loader:Loader',
89
+ )
pool/shard000/Python/0007604_dummy.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2014 Sardar Yumatov
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+ import time
17
+ from struct import pack
18
+
19
+ try:
20
+ import threading as _threading
21
+ except ImportError:
22
+ import dummy_threading as _threading
23
+
24
+ from . import BaseBackend, BaseConnection
25
+ from ..certificate import BaseCertificate
26
+
27
+ # python 3 support
28
+ import six
29
+
30
+ # module level logger
31
+ LOG = logging.getLogger(__name__)
32
+
33
+
34
+ class Certificate(BaseCertificate):
35
+ """ Dummy certificate """
36
+
37
+ def load_context(self, cert_string=None, cert_file=None, key_string=None, key_file=None, passphrase=None):
38
+ """ Returns None as we don't handle any context. """
39
+ return None, None
40
+
41
+ def dump_certificate(self, raw_certificate):
42
+ """ Returns dummy contents. All dummy certificates are equal. """
43
+ return "CERTIFICATE"
44
+
45
+ def dump_digest(self, raw_certificate, digest):
46
+ """ Returns dummy digsst. All dummy certificates are equal. """
47
+ return self.dump_certificate(raw_certificate)
48
+
49
+
50
+ class Backend(BaseBackend):
51
+ """ Dummy backend designed for testing without performing real IO. Serves
52
+ as an exmple for your custom backends.
53
+ """
54
+ # simulate stdio behavior
55
+ can_detect_close = False
56
+
57
+ def __init__(self, push=None, feedback=None, **options):
58
+ """ Create new backend.
59
+
60
+ :Arguments:
61
+ - push (list): list of status codes to return while sending messages.
62
+ - feedback (int): number of tokens to generate in the feedback stream.
63
+ """
64
+ super(Backend, self).__init__(**options)
65
+ self.push_results = push
66
+ self.push_result_pos = -1
67
+ self.feedback_results = feedback
68
+ self.new_connections = 0
69
+ assert (push is not None) ^ (feedback is not None), "Push results or feedback stream must be provided"
70
+
71
+ def get_new_connection(self, address, certificate, timeout=None):
72
+ """ Open a new connection.
73
+
74
+ :Arguments:
75
+ - address (tuple): target (host, port).
76
+ - certificate (:class:`Certificate`): certificate instance.
77
+ - timeout (float): connection timeout in seconds
78
+ """
79
+ self.new_connections += 1
80
+ self.push_result_pos += 1
81
+ return Connection(self, address, certificate)
82
+
83
+ def get_certificate(self, cert_params):
84
+ """ Create/load certificate from parameters. """
85
+ return Certificate(**cert_params)
86
+
87
+ def create_lock(self):
88
+ """ Provides semaphore with ``threading.Lock`` interface. """
89
+ return _threading.Lock()
90
+
91
+
92
+ class Connection(BaseConnection):
93
+ """ Dummy connection. """
94
+
95
+ def __init__(self, pool, address, certificate):
96
+ """ Create new dummy connection.
97
+
98
+ :Arguments:
99
+ - pool (:class:`Backend`): dummy backend.
100
+ - address (tuple): target host and port.
101
+ - certificate (:class:`Certificate`): provider certificate.
102
+ """
103
+ super(Connection, self).__init__(address, certificate)
104
+ self.pool = pool
105
+ self._closed = False
106
+
107
+ def closed(self):
108
+ """ Returns True if :func:`close` has been explicitly called. """
109
+ return self._closed
110
+
111
+ def close(self):
112
+ """ Marks this connection as closed. """
113
+ self._closed = True
114
+
115
+ def reset(self):
116
+ """ Reset dummy connection to use next result record. """
117
+ pass
118
+
119
+ def write(self, data, timeout):
120
+ """ Does nothing, always succeeds. """
121
+ if self.closed():
122
+ raise IOError("Connection closed")
123
+
124
+ def peek(self, size):
125
+ """ Always returns None as we never fail prematurely. """
126
+ return None
127
+
128
+ def read(self, size, timeout):
129
+ """ Iterates over preconfigured send/feedback responses. """
130
+ if self.closed():
131
+ return None
132
+
133
+ if self.pool.push_results is not None:
134
+ # we are push connection
135
+ ret = self.pool.push_results[self.pool.push_result_pos % len(self.pool.push_results)]
136
+ if ret is not None:
137
+ ret = pack(">BBI", 8, ret, 0)
138
+
139
+ return ret
140
+ else: # feedback mode
141
+ ret = []
142
+ for x in range(0, self.pool.feedback_results):
143
+ token = six.b("test_{}".format(x))
144
+ ret.append(pack(">IH{}s".format(len(token)), int(time.time()), len(token), token))
145
+
146
+ self.close()
147
+ return six.binary_type().join(ret)
pool/shard000/Python/0007608_wrappers.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from bisect import bisect_left, bisect_right
2
+
3
+ from numpy import ndarray
4
+
5
+ from ..conf import settings
6
+ from ..exc import DateNotFound, OutOfBound, RightOutOfBound
7
+ from .section import asarray
8
+
9
+
10
+ class TimeSerieWrap:
11
+
12
+ def __init__(self, ts, **kwargs):
13
+ self.ts = ts
14
+ self.modified = False
15
+ self.names = ts.names()
16
+ self.wrap(**kwargs)
17
+
18
+ def wrap(self, **kwargs):
19
+ pass
20
+
21
+ def get(self, dt, default = None):
22
+ '''Equivalent to::
23
+
24
+ self[dt]
25
+
26
+ but catches exceptions and return *default*.'''
27
+ try:
28
+ return self[dt]
29
+ except DateNotFound:
30
+ return default
31
+
32
+ def getts(self):
33
+ return self.ts
34
+
35
+ @property
36
+ def shape(self):
37
+ return len(self), self.ts.count()
38
+
39
+
40
+ class asbtree(TimeSerieWrap):
41
+ '''Wrap a :class:`dynts.TimeSeries` and
42
+ expose binary-tree like functionalities. A :class:`dynts.TimeSeries` instance
43
+ has a shortcut method which construct a ``asbtree``. Here is an example::
44
+
45
+ >>> from dynts.utils.populate import randomts, date
46
+ >>> ts = randomts(cols = 2, start = date(2010, 1, 1), size = 50)
47
+ >>> dts = ts.asbtree()
48
+ >>> sts.find_ge(ts.start())
49
+ 1
50
+ >>> sts.find_ge(ts.end())
51
+ 49
52
+ '''
53
+ def wrap(self):
54
+ ts = self.ts
55
+ self.dates = asarray(ts.dates())
56
+ self.values = ts.values()
57
+
58
+ def __len__(self):
59
+ return len(self.dates)
60
+
61
+ def __getitem__(self, dt):
62
+ '''Get the value at *dt* otherwise it raises
63
+ an :class:`dynts.exceptions.DateNotFound`.'''
64
+ try:
65
+ index = self.find_ge(dt)
66
+ except OutOfBound:
67
+ raise DateNotFound
68
+ if self.dates[index] == dt:
69
+ return self.values[index]
70
+ else:
71
+ raise DateNotFound
72
+
73
+ def at(self, dt):
74
+ val = self[dt]
75
+ return dict(zip(self.names, val))
76
+
77
+ def find_ge(self, dt):
78
+ '''Building block of all searches. Find the index
79
+ corresponding to the leftmost value greater or equal to *dt*.
80
+ If *dt* is greater than the
81
+ :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.RightOutOfBound`
82
+ exception will raise.
83
+
84
+ *dt* must be a python datetime.date instance.'''
85
+ i = bisect_left(self.dates, dt)
86
+ if i != len(self.dates):
87
+ return i
88
+ raise RightOutOfBound
89
+
90
+ def find_le(self, dt):
91
+ '''Find the index corresponding to the rightmost
92
+ value less than or equal to *dt*.
93
+ If *dt* is less than :func:`dynts.TimeSeries.end`
94
+ a :class:`dynts.exceptions.LeftOutOfBound`
95
+ exception will raise.
96
+
97
+ *dt* must be a python datetime.date instance.'''
98
+ i = bisect_right(self.dates, dt)
99
+ if i:
100
+ return i-1
101
+ raise LeftOutOfBound
102
+
103
+ def __repr__(self):
104
+ return '%s(%s)' % (self.__class__.__name__, self.ts.__repr__())
105
+
106
+ def __str__(self):
107
+ return '%s(%s)' % (self.__class__.__name__, self.ts)
108
+
109
+
110
+ class ashash(TimeSerieWrap, dict):
111
+
112
+ def wrap(self):
113
+ ts = self.ts
114
+ hash = {}
115
+ self.hash = hash
116
+ dict.__init__(self, ts.items())
117
+
118
+ def __getitem__(self, dt):
119
+ '''Get the value at *dt* otherwise it raises
120
+ an :class:`dynts.exceptions.DateNotFound`.'''
121
+ try:
122
+ return dict.__getitem__(self, dt)
123
+ except KeyError:
124
+ raise DateNotFound
125
+
126
+ def __setitem__(self, dt, item):
127
+ # if the timeseries contains objects, the items must be a numpy array
128
+ # otherwise we put it into a 1 element array.
129
+ if self.ts.is_object and not isinstance(item, ndarray):
130
+ t, item = item, ndarray((1, ), dtype = self.ts.dtype)
131
+ item[0] = t
132
+ dict.__setitem__(self, dt, item)
133
+ self.modified = True
134
+
135
+ def __iter__(self):
136
+ dates = sorted(dict.__iter__(self))
137
+ if settings.desc:
138
+ dates = reversed(dates)
139
+ return iter(dates)
140
+
141
+ def items(self):
142
+ for dt in self:
143
+ yield dt, self[dt]
144
+
145
+ def getts(self):
146
+ if self.modified:
147
+ name = settings.splittingnames.join(self.names)
148
+ dates = list(self)
149
+ values = (self[dt] for dt in dates)
150
+ return self.ts.clone(name = name, date = dates, data = values)
151
+ else:
152
+ return self.ts
153
+
154
+
155
+ class pair(object):
156
+ __slots__ = ('time', 'value')
157
+
158
+ def __init__(self, time, value):
159
+ self.time, self.value = time, value
160
+
161
+ def __eq__(self, other):
162
+ return self.time == other.time
163
+
164
+ def __gt__(self, other):
165
+ return self.time > other.time
166
+
167
+ def __lt__(self, other):
168
+ return self.time < other.time
pool/shard000/Python/0007611_widgets.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from cms.forms.utils import get_site_choices, get_page_choices
3
+ from cms.models import Page, PageUser, Placeholder
4
+ from cms.plugin_pool import plugin_pool
5
+ from cms.utils import get_language_from_request
6
+ from django.conf import settings
7
+ from django.contrib.sites.models import Site
8
+ from django.forms.widgets import Select, MultiWidget, Widget
9
+ from django.template.context import RequestContext
10
+ from django.template.loader import render_to_string
11
+ from django.utils.encoding import force_unicode
12
+ from django.utils.safestring import mark_safe
13
+ from django.utils.translation import ugettext as _
14
+ from os.path import join
15
+ import copy
16
+
17
+ class PageSelectWidget(MultiWidget):
18
+ """A widget that allows selecting a page by first selecting a site and then
19
+ a page on that site in a two step process.
20
+ """
21
+ def __init__(self, site_choices=None, page_choices=None, attrs=None):
22
+ if attrs is not None:
23
+ self.attrs = attrs.copy()
24
+ else:
25
+ self.attrs = {}
26
+ if site_choices is None or page_choices is None:
27
+ site_choices, page_choices = get_site_choices(), get_page_choices()
28
+ self.site_choices = site_choices
29
+ self.choices = page_choices
30
+ widgets = (Select(choices=site_choices ),
31
+ Select(choices=[('', '----')]),
32
+ Select(choices=self.choices, attrs={'style': "display:none;"} ),
33
+ )
34
+ super(PageSelectWidget, self).__init__(widgets, attrs)
35
+
36
+ def decompress(self, value):
37
+ """
38
+ receives a page_id in value and returns the site_id and page_id
39
+ of that page or the current site_id and None if no page_id is given.
40
+ """
41
+ if value:
42
+ page = Page.objects.get(pk=value)
43
+ site = page.site
44
+ return [site.pk, page.pk, page.pk]
45
+ site = Site.objects.get_current()
46
+ return [site.pk,None,None]
47
+
48
+ def _has_changed(self, initial, data):
49
+ # THIS IS A COPY OF django.forms.widgets.Widget._has_changed()
50
+ # (except for the first if statement)
51
+
52
+ """
53
+ Return True if data differs from initial.
54
+ """
55
+ # For purposes of seeing whether something has changed, None is
56
+ # the same as an empty string, if the data or inital value we get
57
+ # is None, replace it w/ u''.
58
+ if data is None or (len(data)>=2 and data[1] in [None,'']):
59
+ data_value = u''
60
+ else:
61
+ data_value = data
62
+ if initial is None:
63
+ initial_value = u''
64
+ else:
65
+ initial_value = initial
66
+ if force_unicode(initial_value) != force_unicode(data_value):
67
+ return True
68
+ return False
69
+
70
+ def render(self, name, value, attrs=None):
71
+ # THIS IS A COPY OF django.forms.widgets.MultiWidget.render()
72
+ # (except for the last line)
73
+
74
+ # value is a list of values, each corresponding to a widget
75
+ # in self.widgets.
76
+ if not isinstance(value, list):
77
+ value = self.decompress(value)
78
+ output = []
79
+ final_attrs = self.build_attrs(attrs)
80
+ id_ = final_attrs.get('id', None)
81
+ for i, widget in enumerate(self.widgets):
82
+ try:
83
+ widget_value = value[i]
84
+ except IndexError:
85
+ widget_value = None
86
+ if id_:
87
+ final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
88
+ output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
89
+ output.append(r'''<script type="text/javascript">
90
+ (function($) {
91
+ var handleSiteChange = function(site_name, selected_id) {
92
+ $("#id_%(name)s_1 optgroup").remove();
93
+ var myOptions = $("#id_%(name)s_2 optgroup[label=" + site_name + "]").clone();
94
+ $("#id_%(name)s_1").append(myOptions);
95
+ $("#id_%(name)s_1").change();
96
+ };
97
+ var handlePageChange = function(page_id) {
98
+ if (page_id) {
99
+ $("#id_%(name)s_2 option").removeAttr('selected');
100
+ $("#id_%(name)s_2 option[value=" + page_id + "]").attr('selected','selected');
101
+ } else {
102
+ $("#id_%(name)s_2 option[value=]").attr('selected','selected');
103
+ };
104
+ };
105
+ $("#id_%(name)s_0").change(function(){
106
+ var site_label = $("#id_%(name)s_0").children(":selected").text();
107
+ handleSiteChange( site_label );
108
+ });
109
+ $("#id_%(name)s_1").change(function(){
110
+ var page_id = $(this).find('option:selected').val();
111
+ handlePageChange( page_id );
112
+ });
113
+ $(function(){
114
+ handleSiteChange( $("#id_%(name)s_0").children(":selected").text() );
115
+ $("#add_id_%(name)s").hide();
116
+ });
117
+ })(django.jQuery);
118
+ </script>''' % {'name': name})
119
+ return mark_safe(self.format_output(output))
120
+
121
+ def format_output(self, rendered_widgets):
122
+ return u' '.join(rendered_widgets)
123
+
124
+
125
+ class PluginEditor(Widget):
126
+ def __init__(self, attrs=None):
127
+ if attrs is not None:
128
+ self.attrs = attrs.copy()
129
+ else:
130
+ self.attrs = {}
131
+
132
+ class Media:
133
+ js = [join(settings.CMS_MEDIA_URL, path) for path in (
134
+ 'js/lib/jquery-ui.custom.min.js',
135
+ 'js/plugin_editor.js',
136
+ )]
137
+ css = {
138
+ 'all': [join(settings.CMS_MEDIA_URL, path) for path in (
139
+ 'css/plugin_editor.css',
140
+ )]
141
+ }
142
+
143
+ def render(self, name, value, attrs=None):
144
+
145
+ context = {
146
+ 'plugin_list': self.attrs['list'],
147
+ 'installed_plugins': self.attrs['installed'],
148
+ 'copy_languages': self.attrs['copy_languages'],
149
+ 'language': self.attrs['language'],
150
+ 'show_copy': self.attrs['show_copy'],
151
+ 'placeholder': self.attrs['placeholder'],
152
+ }
153
+ return mark_safe(render_to_string(
154
+ 'admin/cms/page/widgets/plugin_editor.html', context))
155
+
156
+
157
+ class UserSelectAdminWidget(Select):
158
+ """Special widget used in page permission inlines, because we have to render
159
+ an add user (plus) icon, but point it somewhere else - to special user creation
160
+ view, which is accessible only if user haves "add user" permissions.
161
+
162
+ Current user should be assigned to widget in form constructor as an user
163
+ attribute.
164
+ """
165
+ def render(self, name, value, attrs=None, choices=()):
166
+ output = [super(UserSelectAdminWidget, self).render(name, value, attrs, choices)]
167
+ if hasattr(self, 'user') and (self.user.is_superuser or \
168
+ self.user.has_perm(PageUser._meta.app_label + '.' + PageUser._meta.get_add_permission())):
169
+ # append + icon
170
+ add_url = '../../../cms/pageuser/add/'
171
+ output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
172
+ (add_url, name))
173
+ output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another')))
174
+ return mark_safe(u''.join(output))
175
+
176
+
177
+ class PlaceholderPluginEditorWidget(PluginEditor):
178
+ attrs = {}
179
+ def __init__(self, request, filter_func):
180
+ self.request = request
181
+ self.filter_func = filter_func
182
+
183
+ def __deepcopy__(self, memo):
184
+ obj = copy.copy(self)
185
+ obj.request = copy.copy(self.request)
186
+ obj.filter_func = self.filter_func
187
+ memo[id(self)] = obj
188
+ return obj
189
+
190
+ def render(self, name, value, attrs=None):
191
+ try:
192
+ ph = Placeholder.objects.get(pk=value)
193
+ except Placeholder.DoesNotExist:
194
+ ph = None
195
+ context = {'add':True}
196
+ if ph:
197
+ plugin_list = ph.cmsplugin_set.filter(parent=None).order_by('position')
198
+ plugin_list = self.filter_func(self.request, plugin_list)
199
+ language = get_language_from_request(self.request)
200
+ copy_languages = []
201
+ if ph.actions.can_copy:
202
+ copy_languages = ph.actions.get_copy_languages(
203
+ placeholder=ph,
204
+ model=ph._get_attached_model(),
205
+ fieldname=ph._get_attached_field_name()
206
+ )
207
+ context = {
208
+ 'plugin_list': plugin_list,
209
+ 'installed_plugins': plugin_pool.get_all_plugins(ph.slot),
210
+ 'copy_languages': copy_languages,
211
+ 'language': language,
212
+ 'show_copy': bool(copy_languages) and ph.actions.can_copy,
213
+ 'urloverride': True,
214
+ 'placeholder': ph,
215
+ }
216
+ #return mark_safe(render_to_string(
217
+ # 'admin/cms/page/widgets/plugin_editor.html', context))
218
+ return mark_safe(render_to_string(
219
+ 'admin/cms/page/widgets/placeholder_editor.html', context, RequestContext(self.request)))
pool/shard000/Python/0007612_protected_entities_radio_astronomy_sites.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from protected_entities import ProtectedEntities
2
+ from protected_entity_radio_astronomy_site import \
3
+ ProtectedEntityRadioAstronomySite
4
+ import os
5
+ import csv
6
+ import configuration
7
+
8
+
9
+ class ProtectedEntitiesRadioAstronomySites(ProtectedEntities):
10
+ """
11
+ Intermediate class
12
+ """
13
+
14
+
15
+ class ProtectedEntitiesRadioAstronomySitesUnitedStates(
16
+ ProtectedEntitiesRadioAstronomySites):
17
+ """
18
+ Radioastronomy sites for the United States. Defined in section 15.712(h)
19
+ of the FCC regulations.
20
+ """
21
+
22
+ def source_filename(self):
23
+ base_directory = configuration.paths['UnitedStates'][
24
+ 'protected_entities']
25
+ return os.path.join(base_directory,
26
+ "Radioastronomy sites (FCC regulations 2012) - "
27
+ "Sheet1.csv")
28
+
29
+ def source_name(self):
30
+ return "FCC 2012 regulations: section 15.712(h)"
31
+
32
+ def get_max_protected_radius_km(self):
33
+ """
34
+ See
35
+ :meth:`protected_entities.ProtectedEntities.get_max_protected_radius_km`
36
+ for more details.
37
+
38
+ :return: 10.0
39
+ :rtype: float
40
+ """
41
+ return 10.0
42
+
43
+ def _load_entities(self):
44
+ """Load the protected entities."""
45
+
46
+ self.log.debug("Loading radio astronomy sites from \"%s\" (%s)" % (
47
+ str(self.source_filename()), str(self.source_name())))
48
+
49
+ def str2bool(v):
50
+ return v.lower() in ("yes", "true", "t", "1")
51
+
52
+ ras_channel = 37
53
+
54
+ with open(self.source_filename(), 'r') as f:
55
+ ras_csv = csv.DictReader(f)
56
+ for ras_entry in ras_csv:
57
+ # print ras_entry
58
+
59
+ try:
60
+ lat_deg = float(ras_entry['Latitude (degree)'])
61
+ lat_min = float(ras_entry['Latitude (minute)'])
62
+ lat_sec = float(ras_entry['Latitude (second)'])
63
+ lat_dir = ras_entry['Latitude (direction)']
64
+ if lat_dir.lower() in ["n", "north"]:
65
+ lat_mult = 1.0
66
+ else:
67
+ lat_mult = -1.0
68
+ latitude = lat_mult * (
69
+ lat_deg + lat_min / 60 + lat_sec / 3600)
70
+
71
+ lon_deg = float(ras_entry['Longitude (degree)'])
72
+ lon_min = float(ras_entry['Longitude (minute)'])
73
+ lon_sec = float(ras_entry['Longitude (second)'])
74
+ lon_dir = ras_entry['Longitude (direction)']
75
+ if lon_dir.lower() in ["e", "east"]:
76
+ lon_mult = 1.0
77
+ else:
78
+ lon_mult = -1.0
79
+ longitude = lon_mult * (
80
+ lon_deg + lon_min / 60 + lon_sec / 3600)
81
+
82
+ name = ras_entry['Name']
83
+
84
+ is_point = str2bool(ras_entry['Is point'])
85
+
86
+ if is_point:
87
+ latitude_deviation = None
88
+ longitude_deviation = None
89
+ else:
90
+ latitude_deviation = float(
91
+ ras_entry['Latitude deviation (decimal degrees)'])
92
+ longitude_deviation = float(
93
+ ras_entry['Longitude deviation (decimal degrees)'])
94
+
95
+ new_ras_entry = ProtectedEntityRadioAstronomySite(
96
+ container=self, region=self.get_mutable_region(),
97
+ latitude=latitude, longitude=longitude,
98
+ channel=ras_channel, name=name, is_point=is_point,
99
+ latitude_deviation=latitude_deviation,
100
+ longitude_deviation=longitude_deviation)
101
+
102
+ self._add_entity(new_ras_entry)
103
+
104
+ except Exception as e:
105
+ self.log.error(
106
+ "Error reading in radio astronomy sites: " + str(
107
+ e) + " (last site read: " + str(name) + ")")
pool/shard000/Python/0007614_pyunit_expr_show.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.insert(1, "../../")
3
+ import h2o, tests
4
+
5
+
6
+ def expr_show():
7
+
8
+
9
+
10
+ iris = h2o.import_file(path=tests.locate("smalldata/iris/iris_wheader.csv"))
11
+ print "iris:"
12
+ iris.show()
13
+
14
+ ###################################################################
15
+
16
+ # expr[int], expr._data is pending
17
+ res = 2 - iris
18
+ res2 = res[0]
19
+ print "res2:"
20
+ res2.show()
21
+
22
+ # expr[int], expr._data is remote
23
+ res3 = res[0]
24
+ print "res3:"
25
+ res3.show()
26
+
27
+ if __name__ == "__main__":
28
+ tests.run_test(sys.argv, expr_show)
pool/shard000/Python/0007615_nss_http_server.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import json
4
+ from flask import Flask, request, abort, Response
5
+
6
+ app = Flask(__name__)
7
+
8
+
9
+ @app.route('/passwd')
10
+ def passwd():
11
+ data = [
12
+ {
13
+ "pw_name": "testuser1", "pw_passwd": "x", "pw_uid": 6000, "pw_gid": 6000,
14
+ "pw_gecos": "Testing", "pw_dir": "/home/testuser1", "pw_shell": "/bin/bash",
15
+ },
16
+ {
17
+ "pw_name": "testuser2", "pw_passwd": "x", "pw_uid": 6001, "pw_gid": 6000,
18
+ "pw_gecos": None, "pw_dir": "/home/testuser2", "pw_shell": "/bin/bash",
19
+ },
20
+ {
21
+ "pw_name": "testuser3", "pw_passwd": "x", "pw_uid": 6002, "pw_gid": 6001,
22
+ "pw_gecos": None, "pw_dir": "/home/testuser3", "pw_shell": "/bin/bash",
23
+ },
24
+ {
25
+ "pw_name": "testuser4", "pw_passwd": "x", "pw_uid": 6003, "pw_gid": 6001,
26
+ "pw_gecos": None, "pw_dir": "/home/testuser4", "pw_shell": "/bin/bash",
27
+ },
28
+ ]
29
+
30
+ name = request.args.get("name")
31
+ if name:
32
+ for struct in data:
33
+ if name == struct["pw_name"]:
34
+ return Response(json.dumps(struct), mimetype='application/json')
35
+ abort(404)
36
+
37
+ uid = request.args.get("uid")
38
+ if uid:
39
+ uid = int(uid)
40
+ for struct in data:
41
+ if uid == struct["pw_uid"]:
42
+ return Response(json.dumps(struct), mimetype='application/json')
43
+ abort(404)
44
+
45
+ return Response(json.dumps(data), mimetype='application/json')
46
+
47
+
48
+ @app.route('/group')
49
+ def group():
50
+ data = [
51
+ { "gr_name": "testgroup1", "gr_passwd": "x", "gr_gid": 6000, "gr_mem": ["testuser1", "testuser2"], },
52
+ { "gr_name": "testgroup2", "gr_passwd": "x", "gr_gid": 6001, "gr_mem": ["testuser3", "testuser4"], },
53
+ ]
54
+
55
+ name = request.args.get("name")
56
+ if name:
57
+ for struct in data:
58
+ if name == struct["gr_name"]:
59
+ return Response(json.dumps(struct), mimetype='application/json')
60
+ abort(404)
61
+
62
+ gid = request.args.get("gid")
63
+ if gid:
64
+ gid = int(gid)
65
+ for struct in data:
66
+ if gid == struct["gr_gid"]:
67
+ return Response(json.dumps(struct), mimetype='application/json')
68
+ abort(404)
69
+
70
+ return Response(json.dumps(data), mimetype='application/json')
71
+
72
+
73
+ @app.route('/shadow')
74
+ def shadow():
75
+ data = [
76
+ {
77
+ "sp_namp": "testuser1", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034,
78
+ "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None,
79
+ },
80
+ {
81
+ "sp_namp": "testuser2", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034,
82
+ "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None,
83
+ },
84
+ {
85
+ "sp_namp": "testuser3", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034,
86
+ "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": None, "sp_expire": None, "sp_flag": None,
87
+ },
88
+ {
89
+ "sp_namp": "testuser4", "sp_pwdp": "$1$BXZIu72k$S7oxt9hBiBl/O3Rm3H4Q30", "sp_lstchg": 16034,
90
+ "sp_min": 0, "sp_max": 99999, "sp_warn": 7, "sp_inact": 10, "sp_expire": 50, "sp_flag": None,
91
+ },
92
+ ]
93
+
94
+ name = request.args.get("name")
95
+ if name:
96
+ for struct in data:
97
+ if name == struct["sp_namp"]:
98
+ return Response(json.dumps(struct), mimetype='application/json')
99
+ abort(404)
100
+
101
+ return Response(json.dumps(data), mimetype='application/json')
102
+
103
+
104
+ if __name__ == "__main__":
105
+ app.debug = True
106
+ app.run(host="localhost", port=9669)
pool/shard000/Python/0007617_sms_settings.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
2
+ # License: GNU General Public License v3. See license.txt
3
+
4
+ from __future__ import unicode_literals
5
+ import frappe
6
+
7
+ from frappe import _, throw, msgprint
8
+ from frappe.utils import nowdate
9
+
10
+ from frappe.model.document import Document
11
+
12
+ class SMSSettings(Document):
13
+ pass
14
+
15
+ def validate_receiver_nos(receiver_list):
16
+ validated_receiver_list = []
17
+ for d in receiver_list:
18
+ # remove invalid character
19
+ for x in [' ', '+', '-', '(', ')']:
20
+ d = d.replace(x, '')
21
+
22
+ validated_receiver_list.append(d)
23
+
24
+ if not validated_receiver_list:
25
+ throw(_("Please enter valid mobile nos"))
26
+
27
+ return validated_receiver_list
28
+
29
+
30
+ def get_sender_name():
31
+ "returns name as SMS sender"
32
+ sender_name = frappe.db.get_single_value('SMS Settings', 'sms_sender_name') or \
33
+ 'ERPNXT'
34
+ if len(sender_name) > 6 and \
35
+ frappe.db.get_default("country") == "India":
36
+ throw("""As per TRAI rule, sender name must be exactly 6 characters.
37
+ Kindly change sender name in Setup --> Global Defaults.
38
+ Note: Hyphen, space, numeric digit, special characters are not allowed.""")
39
+ return sender_name
40
+
41
+ @frappe.whitelist()
42
+ def get_contact_number(contact_name, value, key):
43
+ "returns mobile number of the contact"
44
+ number = frappe.db.sql("""select mobile_no, phone from tabContact where name=%s and %s=%s""" %
45
+ ('%s', frappe.db.escape(key), '%s'), (contact_name, value))
46
+ return number and (number[0][0] or number[0][1]) or ''
47
+
48
+ @frappe.whitelist()
49
+ def send_sms(receiver_list, msg, sender_name = ''):
50
+
51
+ import json
52
+ if isinstance(receiver_list, basestring):
53
+ receiver_list = json.loads(receiver_list)
54
+ if not isinstance(receiver_list, list):
55
+ receiver_list = [receiver_list]
56
+
57
+ receiver_list = validate_receiver_nos(receiver_list)
58
+
59
+ arg = {
60
+ 'receiver_list' : receiver_list,
61
+ 'message' : msg,
62
+ 'sender_name' : sender_name or get_sender_name()
63
+ }
64
+
65
+ if frappe.db.get_value('SMS Settings', None, 'sms_gateway_url'):
66
+ send_via_gateway(arg)
67
+ else:
68
+ msgprint(_("Please Update SMS Settings"))
69
+
70
+ def send_via_gateway(arg):
71
+ ss = frappe.get_doc('SMS Settings', 'SMS Settings')
72
+ args = {ss.message_parameter: arg.get('message')}
73
+ for d in ss.get("parameters"):
74
+ args[d.parameter] = d.value
75
+
76
+ success_list = []
77
+ for d in arg.get('receiver_list'):
78
+ args[ss.receiver_parameter] = d
79
+ status = send_request(ss.sms_gateway_url, args)
80
+ if status >= 200 and status < 300:
81
+ success_list.append(d)
82
+
83
+ if len(success_list) > 0:
84
+ args.update(arg)
85
+ create_sms_log(args, success_list)
86
+ frappe.msgprint(_("SMS sent to following numbers: {0}").format("\n" + "\n".join(success_list)))
87
+
88
+
89
+ def send_request(gateway_url, params):
90
+ import requests
91
+ response = requests.get(gateway_url, params = params, headers={'Accept': "text/plain, text/html, */*"})
92
+ response.raise_for_status()
93
+ return response.status_code
94
+
95
+
96
+ # Create SMS Log
97
+ # =========================================================
98
+ def create_sms_log(args, sent_to):
99
+ sl = frappe.new_doc('SMS Log')
100
+ sl.sender_name = args['sender_name']
101
+ sl.sent_on = nowdate()
102
+ sl.message = args['message']
103
+ sl.no_of_requested_sms = len(args['receiver_list'])
104
+ sl.requested_numbers = "\n".join(args['receiver_list'])
105
+ sl.no_of_sent_sms = len(sent_to)
106
+ sl.sent_to = "\n".join(sent_to)
107
+ sl.flags.ignore_permissions = True
108
+ sl.save()
pool/shard000/Python/0007618_setup.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import platform
2
+ import sys
3
+ import os
4
+
5
+ from setuptools import find_packages, setup
6
+
7
+
8
+ def findRequirements():
9
+ """
10
+ Read the requirements.txt file and parse into requirements for setup's
11
+ install_requirements option.
12
+ """
13
+ return [
14
+ line.strip()
15
+ for line in open("requirements.txt").readlines()
16
+ if not line.startswith("#")
17
+ ]
18
+
19
+
20
+
21
+ depLinks = []
22
+
23
+
24
+
25
+ # If we wanted to use nupic
26
+ # if "linux" in sys.platform and platform.linux_distribution()[0] == "CentOS":
27
+ # depLinks = [ "https://pypi.numenta.com/pypi/nupic",
28
+ # "https://pypi.numenta.com/pypi/nupic.bindings" ]
29
+
30
+
31
+ def read(fname):
32
+ """
33
+ Utility function to read specified file.
34
+ """
35
+ path = os.path.join(os.path.dirname(__file__), fname)
36
+ return open(path).read()
37
+
38
+
39
+
40
+ setup(name="cloudbrain",
41
+ version="0.2.1",
42
+ description="Platform for wearable data analytics.",
43
+ author="Marion Le Borgne",
44
+ url="https://github.com/marionleborgne/cloudbrain",
45
+ packages=find_packages(),
46
+ install_requires=findRequirements(),
47
+ include_package_data=True,
48
+ dependency_links=depLinks,
49
+ long_description=read("README.md"),
50
+ license='GNU Affero General Public License v3',
51
+ classifiers=[
52
+ 'License :: OSI Approved :: GNU Affero General Public License v3'
53
+ ],
54
+ entry_points={
55
+ 'console_scripts': [
56
+ 'cloudbrain = cloudbrain.run:main'
57
+ ]
58
+ })
59
+
60
+
61
+ # import os
62
+ # from setuptools import setup, find_packages
63
+ # from pip.req import parse_requirements
64
+ #
65
+ #
66
+ #
67
+ # # parse_requirements() returns generator of pip.req.InstallRequirement objects
68
+ # install_reqs = parse_requirements("requirements.txt")
69
+ #
70
+ # # reqs is a list of requirement
71
+ # # e.g. ['django==1.5.1', 'mezzanine==1.4.6']
72
+ # reqs = [str(ir.req) for ir in install_reqs]
73
+ #
74
+ #
75
+ #
76
+ # def read(fname):
77
+ # """
78
+ # Utility function to read specified file.
79
+ # """
80
+ # path = os.path.join(os.path.dirname(__file__), fname)
81
+ # return open(path).read()
82
+ #
83
+ #
84
+ #
85
+ # setup(name="cloudbrain",
86
+ # version="0.2.1",
87
+ # description=("Platform for real-time sensor data analysis and
88
+ # visualization."),
89
+ # packages=find_packages(),
90
+ # install_requires=reqs,
91
+ # include_package_data=True,
92
+ # long_description=read("README.md"),
93
+ # license='GNU Affero General Public License v3',
94
+ # classifiers=[
95
+ # 'License :: OSI Approved :: GNU Affero General Public License v3'
96
+ # ],
97
+ # entry_points = {
98
+ # 'console_scripts': [
99
+ # 'cloudbrain = cloudbrain.run:main'
100
+ # ]
101
+ # })
pool/shard000/Python/0007619_test_events.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import, unicode_literals
2
+
3
+ import unittest
4
+
5
+ import mock
6
+
7
+ import pykka
8
+
9
+ from mopidy import core
10
+ from mopidy.internal import deprecation
11
+ from mopidy.models import Track
12
+
13
+ from tests import dummy_backend
14
+
15
+
16
+ @mock.patch.object(core.CoreListener, 'send')
17
+ class BackendEventsTest(unittest.TestCase):
18
+
19
+ def setUp(self): # noqa: N802
20
+ config = {
21
+ 'core': {
22
+ 'max_tracklist_length': 10000,
23
+ }
24
+ }
25
+
26
+ self.backend = dummy_backend.create_proxy()
27
+ self.backend.library.dummy_library = [
28
+ Track(uri='dummy:a'), Track(uri='dummy:b')]
29
+
30
+ with deprecation.ignore():
31
+ self.core = core.Core.start(
32
+ config, backends=[self.backend]).proxy()
33
+
34
+ def tearDown(self): # noqa: N802
35
+ pykka.ActorRegistry.stop_all()
36
+
37
+ def test_forwards_backend_playlists_loaded_event_to_frontends(self, send):
38
+ self.core.playlists_loaded().get()
39
+
40
+ self.assertEqual(send.call_args[0][0], 'playlists_loaded')
41
+
42
+ def test_forwards_mixer_volume_changed_event_to_frontends(self, send):
43
+ self.core.volume_changed(volume=60).get()
44
+
45
+ self.assertEqual(send.call_args[0][0], 'volume_changed')
46
+ self.assertEqual(send.call_args[1]['volume'], 60)
47
+
48
+ def test_forwards_mixer_mute_changed_event_to_frontends(self, send):
49
+ self.core.mute_changed(mute=True).get()
50
+
51
+ self.assertEqual(send.call_args[0][0], 'mute_changed')
52
+ self.assertEqual(send.call_args[1]['mute'], True)
53
+
54
+ def test_tracklist_add_sends_tracklist_changed_event(self, send):
55
+ self.core.tracklist.add(uris=['dummy:a']).get()
56
+
57
+ self.assertEqual(send.call_args[0][0], 'tracklist_changed')
58
+
59
+ def test_tracklist_clear_sends_tracklist_changed_event(self, send):
60
+ self.core.tracklist.add(uris=['dummy:a']).get()
61
+
62
+ self.core.tracklist.clear().get()
63
+
64
+ self.assertEqual(send.call_args[0][0], 'tracklist_changed')
65
+
66
+ def test_tracklist_move_sends_tracklist_changed_event(self, send):
67
+ self.core.tracklist.add(uris=['dummy:a', 'dummy:b']).get()
68
+
69
+ self.core.tracklist.move(0, 1, 1).get()
70
+
71
+ self.assertEqual(send.call_args[0][0], 'tracklist_changed')
72
+
73
+ def test_tracklist_remove_sends_tracklist_changed_event(self, send):
74
+ self.core.tracklist.add(uris=['dummy:a']).get()
75
+
76
+ self.core.tracklist.remove({'uri': ['dummy:a']}).get()
77
+
78
+ self.assertEqual(send.call_args[0][0], 'tracklist_changed')
79
+
80
+ def test_tracklist_shuffle_sends_tracklist_changed_event(self, send):
81
+ self.core.tracklist.add(uris=['dummy:a', 'dummy:b']).get()
82
+
83
+ self.core.tracklist.shuffle().get()
84
+
85
+ self.assertEqual(send.call_args[0][0], 'tracklist_changed')
86
+
87
+ def test_playlists_refresh_sends_playlists_loaded_event(self, send):
88
+ self.core.playlists.refresh().get()
89
+
90
+ self.assertEqual(send.call_args[0][0], 'playlists_loaded')
91
+
92
+ def test_playlists_refresh_uri_sends_playlists_loaded_event(self, send):
93
+ self.core.playlists.refresh(uri_scheme='dummy').get()
94
+
95
+ self.assertEqual(send.call_args[0][0], 'playlists_loaded')
96
+
97
+ def test_playlists_create_sends_playlist_changed_event(self, send):
98
+ self.core.playlists.create('foo').get()
99
+
100
+ self.assertEqual(send.call_args[0][0], 'playlist_changed')
101
+
102
+ @unittest.SkipTest
103
+ def test_playlists_delete_sends_playlist_deleted_event(self, send):
104
+ # TODO We should probably add a playlist_deleted event
105
+ pass
106
+
107
+ def test_playlists_save_sends_playlist_changed_event(self, send):
108
+ playlist = self.core.playlists.create('foo').get()
109
+ playlist = playlist.replace(name='bar')
110
+
111
+ self.core.playlists.save(playlist).get()
112
+
113
+ self.assertEqual(send.call_args[0][0], 'playlist_changed')
pool/shard000/Python/0007621_ScreenBlocksTest.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from yandextank.plugins.ConsoleScreen import Screen, CurrentHTTPBlock, CurrentNetBlock
2
+ from ConsoleOnlinePluginTest import FakeConsoleMarkup
3
+ from TankTests import TankTestCase
4
+
5
+ class BlocksTestCase(TankTestCase):
6
+ def test_HTTP(self):
7
+ screen = Screen(50, FakeConsoleMarkup())
8
+ block = CurrentHTTPBlock(screen)
9
+ block.render()
10
+ print block.lines
11
+ self.assertEquals('<w>HTTP for 0 RPS: <rst>', block.lines[0].strip())
12
+ self.assertEquals(1, len(block.lines))
13
+
14
+ data = self.get_aggregate_data('data/preproc_single.txt')
15
+ data.overall.planned_requests = 100
16
+ data.overall.http_codes = {'400': 10}
17
+ block.add_second(data)
18
+ block.render()
19
+ print block.lines
20
+ self.assertEquals(2, len(block.lines))
21
+
22
+ data.overall.http_codes = {'200': 4}
23
+ block.add_second(data)
24
+ block.render()
25
+ print block.lines
26
+ self.assertEquals(3, len(block.lines))
27
+
28
+ def test_Net(self):
29
+ screen = Screen(50, FakeConsoleMarkup())
30
+ block = CurrentNetBlock(screen)
31
+ block.render()
32
+ print block.lines
33
+ self.assertEquals('<w> NET for 0 RPS: <rst>', block.lines[0].strip())
34
+ self.assertEquals(1, len(block.lines))
35
+
36
+ data = self.get_aggregate_data('data/preproc_single.txt')
37
+ data.overall.planned_requests = 100
38
+ data.overall.net_codes = {'0': 10}
39
+ block.add_second(data)
40
+ block.render()
41
+ print block.lines
42
+ self.assertEquals(2, len(block.lines))
43
+
44
+ data.overall.net_codes = {'71': 4}
45
+ block.add_second(data)
46
+ block.render()
47
+ print block.lines
48
+ self.assertEquals(3, len(block.lines))
pool/shard000/Python/0007623_first.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+
3
+ balance = 0
4
+
5
+ def deposit(amount):
6
+ global balance
7
+ balance = balance + amount
8
+ return balance
9
+
10
+ def withdraw(amount):
11
+ global balance
12
+ balance = balance - amount
13
+ return balance
14
+
15
+ # Ranjith
16
+ print "my initial balance {}".format(balance)
17
+ print " i am depositing 1000 rs to Ranjith"
18
+ deposit(1000)
19
+ print "my balance after deposti{}".format(balance)
20
+ print " i am with drawing 500 rs of Ranjith"
21
+ withdraw(500)
22
+ print "my balance {} after withdraw".format(balance)
23
+
24
+ # Raj
25
+ print "my initial balance {}".format(balance)
pool/shard000/Python/0007624_get_redirected_url.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (c) 2016, Marcelo Leal
3
+ Description: Simple Azure Media Services Python library
4
+ License: MIT (see LICENSE.txt file for details)
5
+ """
6
+ import os
7
+ import json
8
+ import azurerm
9
+ import time
10
+ #import pytz
11
+ import logging
12
+ import datetime
13
+
14
+ ###########################################################################################
15
+ ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER #####
16
+ ###########################################################################################
17
+
18
+ # ALL CODE IN THIS DIRECTOY (INCLUDING THIS FILE) ARE EXAMPLE CODES THAT WILL ACT ON YOUR
19
+ # AMS ACCOUNT. IT ASSUMES THAT THE AMS ACCOUNT IS CLEAN (e.g.: BRAND NEW), WITH NO DATA OR
20
+ # PRODUCTION CODE ON IT. DO NOT, AGAIN: DO NOT RUN ANY EXAMPLE CODE AGAINST PRODUCTION AMS
21
+ # ACCOUNT! IF YOU RUN ANY EXAMPLE CODE AGAINST YOUR PRODUCTION AMS ACCOUNT, YOU CAN LOSE
22
+ # DATA, AND/OR PUT YOUR AMS SERVICES IN A DEGRADED OR UNAVAILABLE STATE. BE WARNED!
23
+
24
+ ###########################################################################################
25
+ ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER ##### ##### DISCLAIMER #####
26
+ ###########################################################################################
27
+
28
+ # Load Azure app defaults
29
+ try:
30
+ with open('config.json') as configFile:
31
+ configData = json.load(configFile)
32
+ except FileNotFoundError:
33
+ print("ERROR: Expecting config.json in current folder")
34
+ sys.exit()
35
+
36
+ account_name = configData['accountName']
37
+ account_key = configData['accountKey']
38
+
39
+ # Get the access token...
40
+ response = azurerm.get_ams_access_token(account_name, account_key)
41
+ resjson = response.json()
42
+ access_token = resjson["access_token"]
43
+
44
+ #Initialization...
45
+ print ("\n-----------------------= AMS Py =----------------------");
46
+ print ("Simple Python Library for Azure Media Services REST API");
47
+ print ("-------------------------------------------------------\n");
48
+
49
+ ### get ams redirected url
50
+ response = azurerm.get_url(access_token)
51
+ if (response.status_code == 200):
52
+ print("New Redirected URL: " + str(response.url))
53
+ else:
54
+ print("GET Status: " + str(response.status_code) + " - Getting Redirected URL ERROR." + str(response.content))
55
+
pool/shard000/Python/0007625_pyminer.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright (c) 2011 The Bitcoin developers
4
+ # Distributed under the MIT/X11 software license, see the accompanying
5
+ # file COPYING or http://www.opensource.org/licenses/mit-license.php.
6
+ #
7
+
8
+ import time
9
+ import json
10
+ import pprint
11
+ import hashlib
12
+ import struct
13
+ import re
14
+ import base64
15
+ import httplib
16
+ import sys
17
+ from multiprocessing import Process
18
+
19
+ ERR_SLEEP = 15
20
+ MAX_NONCE = 1000000L
21
+
22
+ settings = {}
23
+ pp = pprint.PrettyPrinter(indent=4)
24
+
25
+ class BitcoinRPC:
26
+ OBJID = 1
27
+
28
+ def __init__(self, host, port, username, password):
29
+ authpair = "%s:%s" % (username, password)
30
+ self.authhdr = "Basic %s" % (base64.b64encode(authpair))
31
+ self.conn = httplib.HTTPConnection(host, port, False, 30)
32
+ def rpc(self, method, params=None):
33
+ self.OBJID += 1
34
+ obj = { 'version' : '1.1',
35
+ 'method' : method,
36
+ 'id' : self.OBJID }
37
+ if params is None:
38
+ obj['params'] = []
39
+ else:
40
+ obj['params'] = params
41
+ self.conn.request('POST', '/', json.dumps(obj),
42
+ { 'Authorization' : self.authhdr,
43
+ 'Content-type' : 'application/json' })
44
+
45
+ resp = self.conn.getresponse()
46
+ if resp is None:
47
+ print "JSON-RPC: no response"
48
+ return None
49
+
50
+ body = resp.read()
51
+ resp_obj = json.loads(body)
52
+ if resp_obj is None:
53
+ print "JSON-RPC: cannot JSON-decode body"
54
+ return None
55
+ if 'error' in resp_obj and resp_obj['error'] != None:
56
+ return resp_obj['error']
57
+ if 'result' not in resp_obj:
58
+ print "JSON-RPC: no result in object"
59
+ return None
60
+
61
+ return resp_obj['result']
62
+ def getblockcount(self):
63
+ return self.rpc('getblockcount')
64
+ def getwork(self, data=None):
65
+ return self.rpc('getwork', data)
66
+
67
+ def uint32(x):
68
+ return x & 0xffffffffL
69
+
70
+ def bytereverse(x):
71
+ return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) |
72
+ (((x) >> 8) & 0x0000ff00) | ((x) >> 24) ))
73
+
74
+ def bufreverse(in_buf):
75
+ out_words = []
76
+ for i in range(0, len(in_buf), 4):
77
+ word = struct.unpack('@I', in_buf[i:i+4])[0]
78
+ out_words.append(struct.pack('@I', bytereverse(word)))
79
+ return ''.join(out_words)
80
+
81
+ def wordreverse(in_buf):
82
+ out_words = []
83
+ for i in range(0, len(in_buf), 4):
84
+ out_words.append(in_buf[i:i+4])
85
+ out_words.reverse()
86
+ return ''.join(out_words)
87
+
88
+ class Miner:
89
+ def __init__(self, id):
90
+ self.id = id
91
+ self.max_nonce = MAX_NONCE
92
+
93
+ def work(self, datastr, targetstr):
94
+ # decode work data hex string to binary
95
+ static_data = datastr.decode('hex')
96
+ static_data = bufreverse(static_data)
97
+
98
+ # the first 76b of 80b do not change
99
+ blk_hdr = static_data[:76]
100
+
101
+ # decode 256-bit target value
102
+ targetbin = targetstr.decode('hex')
103
+ targetbin = targetbin[::-1] # byte-swap and dword-swap
104
+ targetbin_str = targetbin.encode('hex')
105
+ target = long(targetbin_str, 16)
106
+
107
+ # pre-hash first 76b of block header
108
+ static_hash = hashlib.sha256()
109
+ static_hash.update(blk_hdr)
110
+
111
+ for nonce in xrange(self.max_nonce):
112
+
113
+ # encode 32-bit nonce value
114
+ nonce_bin = struct.pack("<I", nonce)
115
+
116
+ # hash final 4b, the nonce value
117
+ hash1_o = static_hash.copy()
118
+ hash1_o.update(nonce_bin)
119
+ hash1 = hash1_o.digest()
120
+
121
+ # sha256 hash of sha256 hash
122
+ hash_o = hashlib.sha256()
123
+ hash_o.update(hash1)
124
+ hash = hash_o.digest()
125
+
126
+ # quick test for winning solution: high 32 bits zero?
127
+ if hash[-4:] != '\0\0\0\0':
128
+ continue
129
+
130
+ # convert binary hash to 256-bit Python long
131
+ hash = bufreverse(hash)
132
+ hash = wordreverse(hash)
133
+
134
+ hash_str = hash.encode('hex')
135
+ l = long(hash_str, 16)
136
+
137
+ # proof-of-work test: hash < target
138
+ if l < target:
139
+ print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,)
140
+ return (nonce + 1, nonce_bin)
141
+ else:
142
+ print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,)
143
+ # return (nonce + 1, nonce_bin)
144
+
145
+ return (nonce + 1, None)
146
+
147
+ def submit_work(self, rpc, original_data, nonce_bin):
148
+ nonce_bin = bufreverse(nonce_bin)
149
+ nonce = nonce_bin.encode('hex')
150
+ solution = original_data[:152] + nonce + original_data[160:256]
151
+ param_arr = [ solution ]
152
+ result = rpc.getwork(param_arr)
153
+ print time.asctime(), "--> Upstream RPC result:", result
154
+
155
+ def iterate(self, rpc):
156
+ work = rpc.getwork()
157
+ if work is None:
158
+ time.sleep(ERR_SLEEP)
159
+ return
160
+ if 'data' not in work or 'target' not in work:
161
+ time.sleep(ERR_SLEEP)
162
+ return
163
+
164
+ time_start = time.time()
165
+
166
+ (hashes_done, nonce_bin) = self.work(work['data'],
167
+ work['target'])
168
+
169
+ time_end = time.time()
170
+ time_diff = time_end - time_start
171
+
172
+ self.max_nonce = long(
173
+ (hashes_done * settings['scantime']) / time_diff)
174
+ if self.max_nonce > 0xfffffffaL:
175
+ self.max_nonce = 0xfffffffaL
176
+
177
+ if settings['hashmeter']:
178
+ print "HashMeter(%d): %d hashes, %.2f Khash/sec" % (
179
+ self.id, hashes_done,
180
+ (hashes_done / 1000.0) / time_diff)
181
+
182
+ if nonce_bin is not None:
183
+ self.submit_work(rpc, work['data'], nonce_bin)
184
+
185
+ def loop(self):
186
+ rpc = BitcoinRPC(settings['host'], settings['port'],
187
+ settings['rpcuser'], settings['rpcpass'])
188
+ if rpc is None:
189
+ return
190
+
191
+ while True:
192
+ self.iterate(rpc)
193
+
194
+ def miner_thread(id):
195
+ miner = Miner(id)
196
+ miner.loop()
197
+
198
+ if __name__ == '__main__':
199
+ if len(sys.argv) != 2:
200
+ print "Usage: pyminer.py CONFIG-FILE"
201
+ sys.exit(1)
202
+
203
+ f = open(sys.argv[1])
204
+ for line in f:
205
+ # skip comment lines
206
+ m = re.search('^\s*#', line)
207
+ if m:
208
+ continue
209
+
210
+ # parse key=value lines
211
+ m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
212
+ if m is None:
213
+ continue
214
+ settings[m.group(1)] = m.group(2)
215
+ f.close()
216
+
217
+ if 'host' not in settings:
218
+ settings['host'] = '127.0.0.1'
219
+ if 'port' not in settings:
220
+ settings['port'] = 4869
221
+ if 'threads' not in settings:
222
+ settings['threads'] = 1
223
+ if 'hashmeter' not in settings:
224
+ settings['hashmeter'] = 0
225
+ if 'scantime' not in settings:
226
+ settings['scantime'] = 30L
227
+ if 'rpcuser' not in settings or 'rpcpass' not in settings:
228
+ print "Missing username and/or password in cfg file"
229
+ sys.exit(1)
230
+
231
+ settings['port'] = int(settings['port'])
232
+ settings['threads'] = int(settings['threads'])
233
+ settings['hashmeter'] = int(settings['hashmeter'])
234
+ settings['scantime'] = long(settings['scantime'])
235
+
236
+ thr_list = []
237
+ for thr_id in range(settings['threads']):
238
+ p = Process(target=miner_thread, args=(thr_id,))
239
+ p.start()
240
+ thr_list.append(p)
241
+ time.sleep(1) # stagger threads
242
+
243
+ print settings['threads'], "mining threads started"
244
+
245
+ print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port'])
246
+ try:
247
+ for thr_proc in thr_list:
248
+ thr_proc.join()
249
+ except KeyboardInterrupt:
250
+ pass
251
+ print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
252
+
pool/shard000/Python/0007628_config.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # vim: tabstop=4 shiftwidth=4 softtabstop=4
2
+ #
3
+ # Copyright 2012, Nachi Ueno, NTT MCL, Inc.
4
+ # All Rights Reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
7
+ # not use this file except in compliance with the License. You may obtain
8
+ # a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
+ # License for the specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ from oslo.config import cfg
19
+
20
+
21
+ meta_plugin_opts = [
22
+ cfg.StrOpt('plugin_list', default='',
23
+ help=_("List of plugins to load")),
24
+ cfg.StrOpt('l3_plugin_list', default='',
25
+ help=_("List of L3 plugins to load")),
26
+ cfg.StrOpt('default_flavor', default='',
27
+ help=_("Default flavor to use")),
28
+ cfg.StrOpt('default_l3_flavor', default='',
29
+ help=_("Default L3 flavor to use")),
30
+ cfg.StrOpt('supported_extension_aliases', default='',
31
+ help=_("Supported extension aliases")),
32
+ cfg.StrOpt('extension_map', default='',
33
+ help=_("A list of extensions, per plugin, to load.")),
34
+ cfg.StrOpt('rpc_flavor', default='',
35
+ help=_("Flavor of which plugin handles RPC")),
36
+ ]
37
+
38
+ proxy_plugin_opts = [
39
+ cfg.StrOpt('admin_user',
40
+ help=_("Admin user")),
41
+ cfg.StrOpt('admin_password',
42
+ help=_("Admin password"),
43
+ secret=True),
44
+ cfg.StrOpt('admin_tenant_name',
45
+ help=_("Admin tenant name")),
46
+ cfg.StrOpt('auth_url',
47
+ help=_("Authentication URL")),
48
+ cfg.StrOpt('auth_strategy', default='keystone',
49
+ help=_("The type of authentication to use")),
50
+ cfg.StrOpt('auth_region',
51
+ help=_("Authentication region")),
52
+ ]
53
+
54
+ cfg.CONF.register_opts(meta_plugin_opts, "META")
55
+ cfg.CONF.register_opts(proxy_plugin_opts, "PROXY")
pool/shard000/Python/0007631_bluedump.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ # file: inquiry.py
3
+ # auth: Albert Huang <albert@csail.mit.edu>
4
+ # desc: performs a simple device inquiry followed by a remote name request of
5
+ # each discovered device
6
+ # $Id: inquiry.py 401 2006-05-05 19:07:48Z albert $
7
+ #
8
+
9
+ import bluetooth
10
+ import sqlite3
11
+ import sys
12
+ from pprint import pprint,pformat
13
+
14
+ print "Setup database connection"
15
+ conn = sqlite3.connect('bluematter.db')
16
+ print "Opened database successfully";
17
+
18
+ print "Check if table 'people' exists."
19
+ cursor=conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='people';")
20
+ tableFound=False
21
+ for row in cursor:
22
+ if row[0] == 'people':
23
+ tableFound=True
24
+ print "Table 'people' already exists. Good."
25
+ break
26
+
27
+ #
28
+ if tableFound == False:
29
+ print "Table 'people' was not found. Exiting."
30
+ sys.exit(1)
31
+
32
+ cursor=conn.execute("select * from people ")
33
+ data=cursor.fetchall()
34
+ if len(data)==0:
35
+ print("There is no data in table 'people'.")
36
+ else:
37
+ pprint(data)
38
+
39
+ conn.close()
pool/shard000/Python/0007632_getpathart.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+
3
+ import os
4
+ import cgi
5
+ import json
6
+ import subprocess
7
+ import sqlite3 as lite
8
+
9
+ class GetPathArt():
10
+ def __init__(self):
11
+ db_loc = "/usr/share/ampyche/db/ampyche.db"
12
+ self.db_loc = db_loc
13
+ settings_db = "/usr/share/ampyche/db/settings.db"
14
+ self.settings_db = settings_db
15
+
16
+ def _get_webpath(self):
17
+ wlan0 = subprocess.getoutput('/sbin/ifconfig wlan0')
18
+ error = "wlan0: error fetching interface information: Device not found"
19
+ if wlan0 == error:
20
+ ipa = subprocess.getoutput('/sbin/ifconfig').split('\n')[1].split()[1][5:]
21
+ return ipa
22
+ else:
23
+ ipa = subprocess.getoutput('/sbin/ifconfig').split('\n')[17].split()[1][5:]
24
+ return ipa
25
+
26
+ def _create_path(self, fn):
27
+ con = lite.connect(self.settings_db)
28
+ cur = con.cursor()
29
+ cur.execute("SELECT catname, hostaddress FROM settings")
30
+ q = cur.fetchall()
31
+ con.close()
32
+ boo = "/usr/share/ampyche/music/" + q[0][0]
33
+ base = q[0][1] + "/music/" + q[0][0]
34
+ fn = fn[len(boo):]
35
+ fn = base + fn
36
+ fntmp = q[0][1] + "/music/tmp/" + fn[35:]
37
+ fsfntmp = "/usr/share/ampyche/music/tmp/" + fn[35:]
38
+ return fn, fntmp, fsfntmp
39
+
40
+ def _get_path_pic_for_song(self, sname, cpogg, cpmp3):
41
+ con = lite.connect(self.db_loc)
42
+ cur = con.cursor()
43
+ cur.execute("SELECT filename, album_art, fileid, song FROM ampyche WHERE song=?", [sname])
44
+ song = cur.fetchall()
45
+ gg = []
46
+ for s in song:
47
+ fn = s[0]
48
+ fnl = fn.lower()
49
+ ext = fnl[-3:]
50
+ y = {}
51
+ y['songname'] = s[3]
52
+ albumart = s[1]
53
+ albumart = albumart[10:]
54
+ z = self._get_webpath()
55
+ z = "http://" + z
56
+ albumart1 = z + albumart
57
+ y['albumart'] = albumart1
58
+ y['fileid'] = s[2]
59
+ if ext == "mp3":
60
+ #Browser supports mp3 playback so play the song
61
+ if cpmp3 == "true" and cpogg == 'true':
62
+ filename = self._create_path(fn)
63
+ y['filename'] = filename[0]
64
+ gg.append(y)
65
+ elif cpmp3 == "true" and cpogg == 'false':
66
+ filename = self._create_path(fn)
67
+ y['filename'] = filename[0]
68
+ gg.append(y)
69
+ elif cpmp3 == "false" and cpogg == 'true':
70
+ filename = self._create_path(fn)
71
+ filename1 = filename[1]
72
+ webpath = filename1[:-3] + "ogg"
73
+ convpath = filename[2][:-3] + "ogg"
74
+ dirmp3 = os.path.dirname(filename[2])
75
+ if not os.path.exists(dirmp3):
76
+ os.makedirs(dirmp3)
77
+ subprocess.call(['avconv', '-i', fn, '-ab', '128k', '-acodec', 'libvorbis', convpath])
78
+ y['filename'] = webpath
79
+ gg.append(y)
80
+ else:
81
+ pass
82
+ elif ext == "ogg":
83
+ if cpmp3 == 'true' and cpogg == "true":
84
+ filename = self._create_path(fn)
85
+ y['filename'] = filename[0]
86
+ gg.append(y)
87
+ elif cpmp3 == 'false' and cpogg == "true":
88
+ filename = self._create_path(fn)
89
+ y['filename'] = filename[0]
90
+ gg.append(y)
91
+ elif cpmp3 == 'true' and cpogg == "false":
92
+ filename = self._create_path(fn)
93
+ filename = filename[1]
94
+ filenamemp3 = filename[:-3] + "mp3"
95
+ dirogg = os.path.dirname(filename[2])
96
+ if not os.path.exists(dirogg):
97
+ os.makedirs(dirogg)
98
+ #subprocess.call(['avconv', '-i', fn, '-ab', '128k', filenamemp3])
99
+ y['filename'] = filenamemp3
100
+ gg.append(y)
101
+ else:
102
+ pass
103
+ else:
104
+ pass
105
+ print(json.dumps(gg, sort_keys=True, indent=4))
106
+
107
+
108
+ print("Content-Type: application/json\n\n")
109
+ s = cgi.FieldStorage()
110
+
111
+ #sn = "Brown Eyes"
112
+ #fsogg = "true"
113
+ #fsmp3 = "false"
114
+
115
+
116
+ sn = s.getvalue("songname")
117
+ fsogg = s.getvalue('canplayogg')
118
+ fsmp3 = s.getvalue('canplaymp3')
119
+ GPA = GetPathArt()
120
+ run = GPA._get_path_pic_for_song(sn, fsogg, fsmp3)
pool/shard000/Python/0007635_update_collection.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ #Last-modified: 14 Jan 2013 02:04:05 PM
3
+ import json
4
+ import os.path
5
+ import hashlib
6
+
7
+
8
+ HASH_PREFIX = "/mnt/us/documents/"
9
+ ALLOWED_EXTENSIONS = ["pdf", "mobi", "azw", "txt", "prc"]
10
+
11
+ class Collection(object):
12
+ def __init__(self, root="/media/Kindle/"):
13
+ """ Initialize the Collection class, load the existing class.
14
+ """
15
+ self.root = root
16
+ # load the current collections
17
+ self.load()
18
+
19
+ def load(self):
20
+ """ load existing collection json file.
21
+ """
22
+ fcln = os.path.join(self.root, "system", "collections.json")
23
+ f = file(fcln, "r")
24
+ # json file
25
+ self.cln = json.load(f)
26
+ # all the collection names
27
+ self.cnames = self.cln.keys()
28
+ f.close()
29
+
30
+ def update(self, c, new_hal, fname):
31
+ """ update collection and new_hal to the database.
32
+ """
33
+ _c = " ".join([c, "-@en-US"])
34
+ if _c in self.cnames :
35
+ if new_hal in self.cln[_c]["items"] or "*"+new_hal in self.cln[_c]["items"] :
36
+ pass
37
+ else :
38
+ print("file %s does not exist in %s..."%(fname, _c))
39
+ print("append file %s to %s..."%(fname, _c))
40
+ self.cln[_c]["items"].append("*%s" % new_hal)
41
+ else :
42
+ print("collection %s does not exist, create..."%_c)
43
+ print("append file %s to %s..."%(fname, _c))
44
+ new_collection = {"items":[]}
45
+ new_collection["items"].append("*%s" % new_hal)
46
+ self.cln[_c] = new_collection
47
+ self.cnames = self.cln.keys()
48
+
49
+ def forage(self, folder="Incoming"):
50
+ """ detect new files and merge them into data base.
51
+ """
52
+ if folder.startswith("/") :
53
+ raise RuntimeError("folder needs to be a dir relative to <documents>")
54
+ elif len(folder) == 0 :
55
+ isnode = True
56
+ path = os.path.join(self.root, "documents")
57
+ else :
58
+ isnode = False
59
+ path = os.path.join(self.root, "documents", folder)
60
+ if not os.path.isdir(path) :
61
+ print("folder %s does not exist, exit..." % folder)
62
+ else :
63
+ print("foraging directory : %s" % folder)
64
+ if isnode :
65
+ current_collection = None
66
+ print("at root node")
67
+ else :
68
+ current_collection = folder.replace("/", " - ")
69
+ print("Current collection name : %s" % current_collection)
70
+ # Go through all the files in this directory
71
+ for filename in os.listdir(path):
72
+ # Check if is a file
73
+ if os.path.isfile(os.path.join(path, filename)) and (not isnode):
74
+ # Get extension of that file
75
+ extension = filename.split(".")[-1]
76
+ # Check if file is the one we would want to add
77
+ if extension in ALLOWED_EXTENSIONS :
78
+ # Calculate SHA1 hash for the /mnt/us/<folder>/<filename>
79
+ old_hal = gethash(os.path.join(folder, filename))
80
+ self.update(current_collection, old_hal, filename)
81
+ # Check if is directory
82
+ elif os.path.isdir(os.path.join(path, filename)):
83
+ # Parse this sub-directory recursively
84
+ self.forage(folder=os.path.join(folder, filename))
85
+
86
+ def save(self, outdir=None) :
87
+ """ Convert collections to JSON
88
+ """
89
+ collections_json = json.dumps(self.cln)
90
+ # Write JSON to a collections.json
91
+ if outdir is None :
92
+ json_path = os.path.join(self.root, "system", "collections.json")
93
+ else :
94
+ json_path = outdir
95
+ print("Writing collections.json file to %s" % json_path)
96
+ f = open(json_path, "w")
97
+ f.write(collections_json)
98
+ f.close()
99
+
100
+ def default(self) :
101
+ self.cln = {}
102
+ self.cnames = []
103
+ self.forage(folder="")
104
+
105
+ def gethash(fname):
106
+ """ get hash string.
107
+ """
108
+ hin = os.path.join(HASH_PREFIX, fname)
109
+ hobj = hashlib.sha1(hin)
110
+ hval = hobj.hexdigest()
111
+ return(hval)
112
+
113
+ if __name__ == "__main__":
114
+ cln = Collection()
115
+ cln.forage(folder="Incoming/arxiv")
116
+ # cln.default()
117
+ cln.save()
pool/shard000/Python/0007640_get_completions_test.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2015 ycmd contributors
2
+ #
3
+ # This file is part of ycmd.
4
+ #
5
+ # ycmd 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
+ # ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ from __future__ import absolute_import
19
+ from __future__ import unicode_literals
20
+ from __future__ import print_function
21
+ from __future__ import division
22
+ from future import standard_library
23
+ standard_library.install_aliases()
24
+ from builtins import * # noqa
25
+
26
+ from hamcrest import assert_that, has_item
27
+ from .go_handlers_test import Go_Handlers_test
28
+ from ycmd.utils import ReadFile
29
+
30
+
31
+ class Go_GetCompletions_test( Go_Handlers_test ):
32
+
33
+ def Basic_test( self ):
34
+ filepath = self._PathToTestFile( 'test.go' )
35
+ completion_data = self._BuildRequest( filepath = filepath,
36
+ filetype = 'go',
37
+ contents = ReadFile( filepath ),
38
+ force_semantic = True,
39
+ line_num = 9,
40
+ column_num = 11 )
41
+
42
+ results = self._app.post_json( '/completions',
43
+ completion_data ).json[ 'completions' ]
44
+ assert_that( results,
45
+ has_item( self._CompletionEntryMatcher( u'Logger' ) ) )
pool/shard000/Python/0007644_test_model_serializer_deserialize_fk.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..serializers.model_serializer import ModelSerializer
2
+ from .dragon_test_case import DragonTestCase
3
+ from .models import TextModel, SDModel
4
+ from django.db import models
5
+
6
+
7
+ class Parent(SDModel):
8
+ name = models.CharField(max_length=20)
9
+
10
+
11
+ class Child(SDModel):
12
+ parent = models.ForeignKey(Parent)
13
+ number = models.IntegerField()
14
+
15
+
16
+ class ChildSerializer(ModelSerializer):
17
+ parent = 'ParentSerializer'
18
+
19
+ class Meta:
20
+ model = Child
21
+ update_fields = ('number', 'parent')
22
+
23
+
24
+ class ParentSerializer(ModelSerializer):
25
+ child_set = ChildSerializer
26
+
27
+ class Meta:
28
+ model = Parent
29
+ publish_fields = ('name')
30
+ update_fields = ('name', 'child_set')
31
+
32
+
33
+ class TestModelSerializer(DragonTestCase):
34
+ def test_deserialize_with_fk(self):
35
+ data = {
36
+ 'name': 'foo',
37
+ 'child_set': [
38
+ {'number': 5}
39
+ ]
40
+ }
41
+ serializer = ParentSerializer(data)
42
+ parent = serializer.save()
43
+ self.assertEqual(parent.name, data['name'])
44
+ self.assertEqual(parent.child_set.first().number, data['child_set'][0]['number'])
45
+
46
+ def test_deserialize_with_reverse_fk(self):
47
+ data = {
48
+ 'number': 123,
49
+ 'parent': {
50
+ 'name': 'foo'
51
+ }
52
+ }
53
+ serializer = ChildSerializer(data)
54
+ child = serializer.save()
55
+ self.assertEqual(child.number, data['number'])
56
+ self.assertEqual(child.parent.name, data['parent']['name'])
57
+
58
+ def test_get_object_map(self):
59
+ """
60
+ The object map should return information on how to map parents to children
61
+ and vice versa
62
+ """
63
+ object_map = ParentSerializer.get_object_map()
64
+ self.assertLessEqual(len(object_map), 2)
65
+ for om in object_map:
66
+ self.assertIn('via', om)
pool/shard000/Python/0007647_INIFILE.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding:utf-8 -*_
2
+ import ConfigParser, sys
3
+ class INIFILE:
4
+ """
5
+ a class which can process *.ini file
6
+ with read and write function.
7
+ """
8
+ def __init__(self, fileName):
9
+ self.fileName = fileName
10
+ # print self.fileName
11
+ self.initflag = False
12
+ self.cfg = None
13
+ self.readhandle = None
14
+ self.writehandle = None
15
+ self.is_read = False
16
+ self.is_write = False
17
+
18
+ #is_read :is read enable? is_write: is write enable?
19
+ #must write something if you set is_write to true. otherwise your file become empty.
20
+ def Init(self, is_read, is_write):
21
+ self.cfg = ConfigParser.ConfigParser()
22
+ try:
23
+ if is_read:
24
+ self.is_read = True
25
+ self.readhandle = open(self.fileName, 'r')
26
+ self.cfg.readfp(self.readhandle)
27
+
28
+ if is_write:
29
+ self.is_write = True
30
+ self.writehandle = open(self.fileName, 'w')
31
+
32
+ self.initflag = True
33
+ except Exception, e:
34
+ self.initflag = False
35
+ print e
36
+ return self.initflag
37
+
38
+ #close the file
39
+ def UnInit(self):
40
+ if self.initflag:
41
+ if self.is_read:
42
+ self.readhandle.close()
43
+ #print '================close the read handle================'
44
+ if self.is_write:
45
+ self.writehandle.close()
46
+ #print '================close the write handle================'
47
+
48
+ def GetValue(self, Section, Key, Default = '0'):
49
+ try:
50
+ value = self.cfg.get(Section, Key)
51
+ except Exception, e:
52
+ #print e
53
+ value = Default
54
+ return value
55
+
56
+ def SetValue(self, Section, Key, Value):
57
+ if not self.is_write:
58
+ print 'can not SetValue, switch the write function to true first.'
59
+ return
60
+ if not self.cfg.has_section(Section):
61
+ print 'Section [%s] does not exists. Going to add it first' %(Section)
62
+ self.cfg.add_section(Section)
63
+ self.cfg.set(Section, Key, Value)
64
+ self.cfg.write(self.writehandle)
65
+
66
+
67
+ # file = INIFILE('totalpage.ini')
68
+ # file.Init()
69
+ # num = file.GetValue('Main', 'totalpage', '')
70
+ # print num
71
+ #
72
+ # file.SetValue('Main', 'totalpage', '805')
73
+ # print file.GetValue('Main', 'TotalPage', '0')
74
+ #
75
+ # file.SetValue('DEMO', 'whoami', 'Admin')
76
+ # print file.GetValue('DEMO', 'whoami', 'Admin')
pool/shard000/Python/0007651_1138_01_01_SimpleGIS.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #SimpleGIS.py - A Simple GIS
2
+
3
+ import turtle as t
4
+
5
+ # DATA MODEL
6
+ # All layers will have a name, 1+ points, and population count
7
+ NAME = 0
8
+ POINTS = 1
9
+ POP = 2
10
+
11
+ # Create the state layer
12
+ state = ["COLORADO", [[-109, 37], [-109, 41], [-102, 41], [-102, 37]], 5187582]
13
+
14
+ # Cities layer list
15
+ # city = [name, [point], population]
16
+ cities = []
17
+
18
+ # Add Denver
19
+ cities.append(["DENVER",[-104.98, 39.74], 634265])
20
+ # Add Boulder
21
+ cities.append(["BOULDER",[-105.27, 40.02], 98889])
22
+ # Add Durango
23
+ cities.append(["DURANGO",[-107.88,37.28], 17069])
24
+
25
+ # MAP GRAPHICS RENDERING
26
+ map_width = 800
27
+ map_height = 500
28
+
29
+ # State Bounding Box
30
+ # Use Python min/max function to get bounding box
31
+ minx = 180
32
+ maxx = -180
33
+ miny = 90
34
+ maxy = -90
35
+ for x,y in state[POINTS]:
36
+ if x < minx: minx = x
37
+ elif x > maxx: maxx = x
38
+ if y < miny: miny = y
39
+ elif y > maxy: maxy = y
40
+ # Get earth distance on each axis
41
+ dist_x = maxx - minx
42
+ dist_y = maxy - miny
43
+
44
+ # Scaling ratio each axis
45
+ # to map points from world to screen
46
+ x_ratio = map_width / dist_x
47
+ y_ratio = map_height / dist_y
48
+
49
+ # Function to convert lat/lon to screen coordinates
50
+ def convert(point):
51
+ lon = point[0]
52
+ lat = point[1]
53
+ x = map_width - ((maxx - lon) * x_ratio)
54
+ y = map_height - ((maxy - lat) * y_ratio)
55
+ # Python turtle graphics start in the middle of the screen
56
+ # so we must offset the points so they are centered
57
+ x = x - (map_width/2)
58
+ y = y - (map_height/2)
59
+ return [x,y]
60
+
61
+ # Draw the state
62
+ t.up()
63
+ first_pixel = None
64
+ for point in state[POINTS]:
65
+ print(point)
66
+ pixel = convert(point)
67
+ print(pixel)
68
+ if not first_pixel:
69
+ first_pixel = pixel
70
+ t.goto(pixel)
71
+ t.down()
72
+ # Go back to the first point
73
+ t.goto(first_pixel)
74
+ # Label the state
75
+ t.up()
76
+ t.goto([0,0])
77
+ t.write(state[NAME], align="center", font=("Arial",16,"bold"))
78
+
79
+ # Draw the cities
80
+ for city in cities:
81
+ pixel = convert(city[POINTS])
82
+ t.up()
83
+ t.goto(pixel)
84
+ # Place a point for the city
85
+ t.dot(10)
86
+ # Label the city
87
+ t.write(city[NAME] + ", Pop.: " + str(city[POP]), align="left")
88
+ t.up()
89
+
90
+ # Perform an attribute query
91
+ # Question: Which city has the largest population?
92
+ # Write the result but make sure it's under the map
93
+ biggest_city = max(cities, key=lambda city:city[POP])
94
+ t.goto(0, -1*((map_height/2)+20))
95
+ t.write("The biggest city is: " + biggest_city[NAME])
96
+
97
+ # Perform a spatial query
98
+ # Question: Which is the western most city?
99
+ # Write the result but make sure it's under the other question
100
+ western_city = min(cities, key=lambda city:city[POINTS])
101
+ t.goto(0, -1*((map_height/2)+40))
102
+ t.write("The western-most city is: " + western_city[NAME])
103
+
104
+ # Hide our map pen
105
+ t.pen(shown=False)
106
+ t.done()
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
pool/shard000/Python/0007654_071_simplify_path.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Given an absolute path for a file (Unix-style), simplify it.
3
+
4
+ For example,
5
+ path = "/home/", => "/home"
6
+ path = "/a/./b/../../c/", => "/c"
7
+
8
+ Corner Cases:
9
+
10
+ Did you consider the case where path = "/../"?
11
+
12
+ In this case, you should return "/".
13
+
14
+ Another corner case is the path might contain multiple slashes '/' together,
15
+ such as "/home//foo/".
16
+
17
+ In this case, you should ignore redundant slashes and return "/home/foo".
18
+ """
19
+ class Solution(object):
20
+ def simplifyPath(self, path):
21
+ """
22
+ :type path: str
23
+ :rtype: str
24
+ """
25
+ soln = []
26
+ for folder in path.split('/'):
27
+ if folder == '.' or folder == '':
28
+ continue
29
+ elif folder == '..':
30
+ if len(soln) > 0:
31
+ soln.pop()
32
+ else:
33
+ soln.append(folder)
34
+ return '/' + '/'.join(soln)
35
+
36
+ a = Solution()
37
+ print(a.simplifyPath("/home/") == "/home")
38
+ print(a.simplifyPath("/a/./b/../../c/") == "/c")
39
+ print(a.simplifyPath("/../") == "/")
40
+ print(a.simplifyPath("/home//foo/") == "/home/foo")
pool/shard000/Python/0007657_cmakemakecp.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##
2
+ # Copyright 2009-2020 Ghent University
3
+ #
4
+ # This file is part of EasyBuild,
5
+ # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
6
+ # with support of Ghent University (http://ugent.be/hpc),
7
+ # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
8
+ # Flemish Research Foundation (FWO) (http://www.fwo.be/en)
9
+ # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
10
+ #
11
+ # https://github.com/easybuilders/easybuild
12
+ #
13
+ # EasyBuild is free software: you can redistribute it and/or modify
14
+ # it under the terms of the GNU General Public License as published by
15
+ # the Free Software Foundation v2.
16
+ #
17
+ # EasyBuild is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
+ # GNU General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU General Public License
23
+ # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
24
+ ##
25
+ """
26
+ EasyBuild support for software configured with CMake but without 'make install' step, implemented as an easyblock
27
+
28
+ @author: Samuel Moors, Vrije Universiteit Brussel (VUB)
29
+ """
30
+ from easybuild.easyblocks.generic.cmakemake import CMakeMake
31
+ from easybuild.easyblocks.generic.makecp import MakeCp
32
+ import os
33
+
34
+
35
+ class CMakeMakeCp(CMakeMake, MakeCp):
36
+ """Software configured with CMake but without 'make install' step
37
+
38
+ We use the default CMakeMake implementation, and use install_step from MakeCp.
39
+ """
40
+
41
+ @staticmethod
42
+ def extra_options(extra_vars=None):
43
+ extra_vars = MakeCp.extra_options(extra_vars)
44
+ return CMakeMake.extra_options(extra_vars=extra_vars)
45
+
46
+ def configure_step(self, srcdir=None, builddir=None):
47
+ """Configure build using CMake"""
48
+ return CMakeMake.configure_step(self, srcdir=srcdir, builddir=builddir)
49
+
50
+ def install_step(self):
51
+ """Install by copying specified files and directories."""
52
+ if self.cfg.get('separate_build_dir', False):
53
+ self.cfg['start_dir'] = os.path.join(self.builddir, 'easybuild_obj')
54
+ return MakeCp.install_step(self)
pool/shard000/Python/0007659_server.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+
3
+ import xmlrpclib
4
+ from SimpleXMLRPCServer import SimpleXMLRPCServer
5
+ import random, os, datetime, sys, traceback, math
6
+
7
+
8
+ start_time = datetime.datetime.now()
9
+ log_dir = "/home/dokstud/lew/logi/%s" % start_time.isoformat()
10
+
11
+ report_file = "report.csv"
12
+
13
+ params_sampler = {
14
+ "progressive_bias" : lambda: random.uniform (60.0, 120),
15
+ "progressive_bias_prior" : lambda: random.uniform (0, 40),
16
+ "proxy_1_bonus" : lambda: random.uniform (0, 30),
17
+ "proxy_2_bonus" : lambda: random.uniform (0, 20),
18
+ }
19
+
20
+ params_names = params_sampler.keys () #csv header
21
+
22
+ csv_header = ", ".join (params_names) + ", first_is_black, first_win, sgf_file"
23
+
24
+ params_of_series = []
25
+ games_per_series = 2
26
+
27
+ gnugo = \
28
+ "'/home/dokstud/lew/.bin/gnugo-3.8 --mode gtp --chinese-rules" \
29
+ " --capture-all-dead --positional-superko --level=0'"
30
+
31
+ libego = \
32
+ "'/home/dokstud/lew/libego/bin/engine" \
33
+ " \"LoadGammas /home/dokstud/lew/libego/bin/3x3.gamma\"" \
34
+ " %s gtp'"
35
+
36
+ gtp_set_command = "set"
37
+
38
+ # TODO seed, cputime
39
+ workers = {}
40
+ idle_workers = {}
41
+
42
+ def gen_params ():
43
+ return dict (((p, params_sampler [p] ()) for p in params_names))
44
+
45
+
46
+ def params_to_gtp (params):
47
+ gtp = ""
48
+ for param_name in params_names:
49
+ gtp += '"%s %s %f" ' % (gtp_set_command, param_name, params[param_name])
50
+ return gtp
51
+
52
+
53
+ def format_report_line (series_id, first_is_black, first_win, sgf):
54
+ params = params_of_series [series_id]
55
+ csv_line = ", ".join ((str(params [param_name]) for param_name in params_names))
56
+ # scv_line, oh yeah :)
57
+ return csv_line + (', %d, %d, "%s"' % (first_is_black, first_win, sgf))
58
+
59
+
60
+ def report_idling (worker_id):
61
+ idle_workers [worker_id] = datetime.datetime.now()
62
+ if (worker_id in workers):
63
+ print "Warning! Idling worker on worker list."
64
+ return 0
65
+
66
+
67
+ def get_game_setup (worker_id):
68
+ if (worker_id in workers):
69
+ print "Warning! Worker already on worker list."
70
+ if (worker_id in idle_workers):
71
+ idle_workers.pop (worker_id)
72
+ workers [worker_id] = datetime.datetime.now()
73
+
74
+ global series_id
75
+ params = gen_params ()
76
+ series_id = len (params_of_series)
77
+ params_of_series.append (params)
78
+ ret = (log_dir,
79
+ series_id,
80
+ games_per_series,
81
+ libego % params_to_gtp (params),
82
+ gnugo
83
+ )
84
+ return ret
85
+
86
+
87
+ def report_game_result (worker_id, clog_dir, series_id, result_list):
88
+ # error handling
89
+ if (not worker_id in workers):
90
+ print "Old report from ", worker_id
91
+ if (clog_dir == log_dir):
92
+ print "Warning! but the same experiment dir!"
93
+ return 0;
94
+ if clog_dir != log_dir:
95
+ print "Warning! in pool, but wrong dir!!"
96
+ return 0
97
+
98
+ worker_start = workers.pop (worker_id)
99
+ f = open (report_file, "a")
100
+ # TODO check for result length
101
+ for (first_is_black, first_win, sgf) in result_list:
102
+ print (first_is_black, first_win, sgf)
103
+ f.write ("%s\n" % format_report_line (series_id, first_is_black, first_win, sgf))
104
+ f.close ()
105
+ return 0
106
+
107
+
108
+ def list_workers ():
109
+ s = "ACTIVE:\n"
110
+ t_now = datetime.datetime.now()
111
+ for w in workers:
112
+ d = t_now - workers[w]
113
+ mark = " *" if d.seconds > 60 else ""
114
+ s += "%s %s %s\n" % (w, str(d), mark)
115
+ s += "IDLE:\n"
116
+ for w in idle_workers:
117
+ d = t_now - idle_workers[w]
118
+ mark = " *" if d.seconds > 60 else ""
119
+ s += "%s %s %s\n" % (w, str(d), mark)
120
+ return s
121
+
122
+ os.makedirs (log_dir)
123
+ os.chdir (log_dir)
124
+
125
+ address = "students.mimuw.edu.pl", 7553
126
+ server = SimpleXMLRPCServer (address)
127
+
128
+ server.register_function (get_game_setup, "get_game_setup")
129
+ server.register_function (report_game_result, "report_game_result")
130
+ server.register_function (list_workers, "list_workers")
131
+ server.register_function (report_idling, "report_idling")
132
+
133
+ print "Listening on port %d..." % address[1]
134
+
135
+ f = open (report_file, "a")
136
+ f.write ("%s\n" % csv_header)
137
+ f.close ()
138
+
139
+ server.serve_forever()
pool/shard000/Python/0007664_news.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date, datetime
2
+
3
+ from flask import Blueprint, abort, render_template, request, flash, \
4
+ redirect, url_for
5
+ from flask_babel import _ # gettext
6
+ from flask_login import current_user
7
+ from sqlalchemy import desc
8
+ from werkzeug.contrib.atom import AtomFeed
9
+
10
+ from app import db
11
+ from app.decorators import require_role
12
+ from app.forms import init_form
13
+ from app.forms.news import NewsForm
14
+ from app.models.news import News
15
+ from app.roles import Roles
16
+ from app.service import role_service
17
+
18
+ blueprint = Blueprint('news', __name__, url_prefix='/news')
19
+
20
+
21
+ @blueprint.route('/', methods=['GET'])
22
+ @blueprint.route('/<int:page_nr>/', methods=['GET'])
23
+ def list(page_nr=1):
24
+ items = News.query.filter(News.publish_date <= date.today(),
25
+ db.or_(News.archive_date >= date.today(),
26
+ News.archive_date == None), # noqa
27
+ db.or_(current_user.has_paid,
28
+ db.not_(News.needs_paid))) \
29
+ .order_by(desc(News.publish_date))
30
+
31
+ can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE)
32
+ return render_template('news/list.htm',
33
+ items=items.paginate(page_nr, 10, False),
34
+ archive=False, can_write=can_write)
35
+
36
+
37
+ @blueprint.route('/all/', methods=['GET'])
38
+ @blueprint.route('/all/<int:page_nr>/', methods=['GET'])
39
+ def all(page_nr=1):
40
+ return render_template('news/list.htm',
41
+ items=News.query.paginate(page_nr, 10, False),
42
+ archive=False)
43
+
44
+
45
+ @blueprint.route('/archive/', methods=['GET'])
46
+ @blueprint.route('/archive/<int:page_nr>/', methods=['GET'])
47
+ def archive(page_nr=1):
48
+ items = News.query.filter(db.and_(News.archive_date < date.today(),
49
+ News.archive_date != None)) # noqa
50
+
51
+ return render_template('news/list.htm',
52
+ items=items.paginate(page_nr, 10, False),
53
+ archive=True)
54
+
55
+
56
+ @blueprint.route('/create/', methods=['GET', 'POST'])
57
+ @blueprint.route('/edit/<int:news_id>/', methods=['GET', 'POST'])
58
+ @require_role(Roles.NEWS_WRITE)
59
+ def edit(news_id=None):
60
+ if news_id:
61
+ news_item = News.query.get_or_404(news_id)
62
+ else:
63
+ news_item = News()
64
+
65
+ form = init_form(NewsForm, obj=news_item)
66
+
67
+ if form.validate_on_submit():
68
+
69
+ # fill the news_item with the form entries.
70
+ form.populate_obj(news_item)
71
+
72
+ # Only set writer if post is brand new
73
+ if not news_item.id:
74
+ news_item.user_id = current_user.id
75
+
76
+ db.session.add(news_item)
77
+ db.session.commit()
78
+
79
+ news_id = news_item.id
80
+ flash(_('News item saved'), 'success')
81
+
82
+ return redirect(url_for('news.view', news_id=news_id))
83
+
84
+ return render_template('news/edit.htm', form=form, news_id=news_id)
85
+
86
+
87
+ @blueprint.route('/view/', methods=['GET'])
88
+ @blueprint.route('/view/<int:news_id>/', methods=['GET'])
89
+ def view(news_id=None):
90
+ if not news_id:
91
+ flash(_('This news item does not exist'), 'danger')
92
+ return redirect(url_for('news.list'))
93
+
94
+ news = News.query.get_or_404(news_id)
95
+ if not news.can_read():
96
+ return abort(403)
97
+
98
+ can_write = role_service.user_has_role(current_user, Roles.NEWS_WRITE)
99
+
100
+ return render_template('news/view_single.htm', news=news,
101
+ can_write=can_write)
102
+
103
+
104
+ @blueprint.route('/delete/', methods=['GET'])
105
+ @blueprint.route('/delete/<int:news_id>/', methods=['GET'])
106
+ @require_role(Roles.NEWS_WRITE)
107
+ def delete(news_id=None):
108
+ if not news_id:
109
+ flash(_('This news item does not exist'), 'danger')
110
+ return redirect(url_for('news.list'))
111
+
112
+ news = News.query.get_or_404(news_id)
113
+ db.session.delete(news)
114
+ db.session.commit()
115
+
116
+ flash(_('News item succesfully deleted'), 'success')
117
+
118
+ return redirect(url_for('news.list'))
119
+
120
+
121
+ @blueprint.route('/rss/', methods=['GET'])
122
+ @blueprint.route('/rss/<string:locale>/')
123
+ def rss(locale='en'):
124
+ name = 'via nieuws' if locale == 'nl' else 'via news'
125
+ feed = AtomFeed(name, feed_url=request.url, url=request.url_root)
126
+ items = News.query.filter(News.publish_date <= date.today(),
127
+ db.or_(News.archive_date >= date.today(),
128
+ News.archive_date == None), # noqa
129
+ db.or_(db.not_(News.needs_paid))) \
130
+ .order_by(News.publish_date.desc()).limit(20)
131
+
132
+ for item in items:
133
+ published = datetime.combine(item.publish_date, datetime.min.time())
134
+ title, content = item.get_localized_title_content(locale)
135
+ feed.add(title, content, id=item.id, content_type='markdown',
136
+ published=published, updated=published,
137
+ url=url_for('news.view', news_id=item.id),
138
+ author=item.user.name)
139
+
140
+ return feed.get_response()
pool/shard000/Python/0007667_rest_api_helper.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright 2021 Google LLC
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from functools import lru_cache
18
+ import logging
19
+ import requests
20
+ from requests import Response
21
+ from typing import Any, Dict, List, Union
22
+
23
+ from google.datacatalog_connectors.sisense.scrape import \
24
+ authenticator, constants
25
+
26
+
27
+ class RESTAPIHelper:
28
+
29
+ def __init__(self, server_address: str, api_version: str, username: str,
30
+ password: str):
31
+
32
+ self.__server_address = server_address
33
+ self.__api_version = api_version
34
+ self.__username = username
35
+ self.__password = password
36
+
37
+ self.__base_api_endpoint = f'{server_address}/api/{api_version}'
38
+ self.__common_headers = {
39
+ 'Content-Type': constants.JSON_CONTENT_TYPE,
40
+ 'Accept': constants.JSON_CONTENT_TYPE
41
+ }
42
+
43
+ self.__auth_credentials = None
44
+
45
+ def get_all_dashboards(self) -> List[Dict[str, Any]]:
46
+ """Get all Dashboards the user has access to on a given server.
47
+
48
+ Returns:
49
+ A ``list``.
50
+
51
+ Raises:
52
+ Exception: If the API returns any status code than ``200``.
53
+ """
54
+ self.__set_up_auth()
55
+
56
+ url = f'{self.__base_api_endpoint}/dashboards'
57
+ response = requests.get(url=url, headers=self.__common_headers)
58
+ # ``GET /dashboards`` currently does not support pagination.
59
+ all_dashboards = self.__get_response_body_or_raise(response)
60
+
61
+ # ``GET /dashboards`` returns an array containing a mix of summary
62
+ # objects for dashboards that are shared with the current user and full
63
+ # objects for dashboards that are owned by the user. Such summary
64
+ # objects contain only the ``oid`` and ``lastPublish`` fields.
65
+ #
66
+ # So, we check the presence of ``_id`` to determine whether an object
67
+ # refers to a shared dashboard or not. If ``_id`` is absent, we need to
68
+ # perform extra API calls to ``GET dashboards/{id}``, passing ``oid``
69
+ # as parameter, in order to get detailed metadata for each shared
70
+ # dashboard.
71
+ shared_dashboards = [
72
+ dashboard for dashboard in all_dashboards
73
+ if not dashboard.get('_id')
74
+ ]
75
+ for shared_dashboard in shared_dashboards:
76
+ all_dashboards.remove(shared_dashboard)
77
+ all_dashboards.extend([
78
+ self.get_dashboard(dashboard.get('oid'))
79
+ for dashboard in shared_dashboards
80
+ ])
81
+
82
+ return all_dashboards
83
+
84
+ def get_dashboard(self, dashboard_id: str) -> Dict[str, Any]:
85
+ """Get a specific Dashboard.
86
+
87
+ Returns:
88
+ A Dashboard object.
89
+
90
+ Raises:
91
+ Exception: If the API returns any status code than ``200``.
92
+ """
93
+ self.__set_up_auth()
94
+ url = f'{self.__base_api_endpoint}/dashboards/{dashboard_id}'
95
+ response = requests.get(url=url, headers=self.__common_headers)
96
+ return self.__get_response_body_or_raise(response)
97
+
98
+ def get_all_folders(self) -> List[Dict[str, Any]]:
99
+ """Get all Folders the user has access to on a given server.
100
+
101
+ Returns:
102
+ A ``list``.
103
+
104
+ Raises:
105
+ Exception: If the API returns any status code than ``200``.
106
+ """
107
+ self.__set_up_auth()
108
+
109
+ # Sisense can return the folders in flat (default) or tree structures.
110
+ # We decided for flat because it supports standard pagination handling
111
+ # (paginating a tree structure would require extra programming effort).
112
+ url = f'{self.__base_api_endpoint}/folders?structure=flat'
113
+ return self.__get_list_using_pagination(base_url=url,
114
+ results_per_page=50)
115
+
116
+ @lru_cache(maxsize=128)
117
+ def get_user(self, user_id: str) -> Dict[str, Any]:
118
+ """Get a specific User.
119
+
120
+ Returns:
121
+ A User object.
122
+
123
+ Raises:
124
+ Exception: If the API returns any status code than ``200``.
125
+ """
126
+ self.__set_up_auth()
127
+ url = f'{self.__base_api_endpoint}/users/{user_id}'
128
+ response = requests.get(url=url, headers=self.__common_headers)
129
+ return self.__get_response_body_or_raise(response)
130
+
131
+ def get_widgets(self, dashboard_id) -> List[Dict[str, Any]]:
132
+ """Get all Widgets belonging to a given Dashboard.
133
+
134
+ Returns:
135
+ A ``list``.
136
+
137
+ Raises:
138
+ Exception: If the API returns any status code than ``200``.
139
+ """
140
+ self.__set_up_auth()
141
+
142
+ url = f'{self.__base_api_endpoint}/dashboards/{dashboard_id}/widgets'
143
+ return self.__get_list_using_pagination(base_url=url,
144
+ results_per_page=50)
145
+
146
+ def __set_up_auth(self) -> None:
147
+ if self.__auth_credentials:
148
+ return
149
+
150
+ self.__auth_credentials = \
151
+ authenticator.Authenticator.authenticate(
152
+ self.__server_address,
153
+ self.__api_version,
154
+ self.__username,
155
+ self.__password)
156
+
157
+ self.__common_headers[constants.AUTHORIZATION_HEADER_NAME] = \
158
+ f'{constants.BEARER_TOKEN_PREFIX}' \
159
+ f' {self.__auth_credentials["access_token"]}'
160
+
161
+ def __get_list_using_pagination(self,
162
+ base_url: str,
163
+ results_per_page: int,
164
+ id_field='oid') -> List[Dict[str, Any]]:
165
+ """Get a ``List`` using pagination.
166
+
167
+ Args:
168
+ base_url: The url to which the ``skip`` and ``limit`` query
169
+ parameters will be appended to handle pagination accordingly.
170
+ results_per_page: The number of results per page. Must be greater
171
+ than 1.
172
+
173
+ Returns:
174
+ A ``list``.
175
+ """
176
+ if results_per_page <= 1:
177
+ raise ValueError('results_per_page must be greater than 1')
178
+
179
+ results = []
180
+ query_param_prefix = '?' if '?' not in base_url else '&'
181
+
182
+ page_count = 0
183
+ page_results = []
184
+ # Sisense APIs may add more results to some pages than specified by the
185
+ # ``results_per_page`` argument. It happens in the ``GET /folders``
186
+ # pages, for instance: all pages include the ``rootFolder``, resulting
187
+ # in ``results_per_page + 1`` folders in all pages but the last.
188
+ # Given this behavior, we need ``results_per_page`` to be greater than
189
+ # ``1`` and to use the ``>=`` operator to decide between executing the
190
+ # ``while`` loop or not, to avoid issues.
191
+ while page_count == 0 or len(page_results) >= results_per_page:
192
+ offset = page_count * results_per_page
193
+ url = f'{base_url}{query_param_prefix}skip={offset}' \
194
+ f'&limit={results_per_page}'
195
+ response = requests.get(url=url, headers=self.__common_headers)
196
+ page_results = self.__get_response_body_or_raise(response)
197
+ results.extend(page_results)
198
+ page_count += 1
199
+ logging.info(f'page {page_count}: {len(page_results)} results')
200
+
201
+ logging.info('')
202
+ logging.info('Removing potential duplicates...')
203
+ # Set comprehension is used to remove potential duplicates after
204
+ # merging the results, e.g.: the ``rootFolder`` that comes in all
205
+ # ``GET /folders`` pages.
206
+ unique_ids = {result.get(id_field) for result in results}
207
+
208
+ unique_results = []
209
+ for unique_id in unique_ids:
210
+ unique_results.append(
211
+ next(result for result in results
212
+ if result.get(id_field) == unique_id))
213
+
214
+ return unique_results
215
+
216
+ @classmethod
217
+ def __get_response_body_or_raise(
218
+ cls,
219
+ response: Response) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
220
+ """Get the response body on successful API call or raise an exception.
221
+
222
+ Returns:
223
+ A ``Dict`` or ``List``.
224
+
225
+ Raises:
226
+ Exception: If the API returns any status code than ``200``.
227
+ """
228
+
229
+ status_code = response.status_code
230
+
231
+ if status_code == 200:
232
+ return response.json()
233
+
234
+ # Raise exception for all status codes other than ``200`` to let the
235
+ # caller know what went wrong.
236
+ error = response.json().get('error') or {}
237
+ logging.warning('error on API call: %s', error)
238
+ raise Exception(error.get('message'))
pool/shard000/Python/0007668_grove_temp.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pyboard code for reading a grove temp sensor connected to X1
2
+
3
+ import pyb
4
+ import math
5
+
6
+ B = 4275
7
+
8
+ temp_adc = pyb.ADC('X1')
9
+
10
+ def read_temp():
11
+ temp_raw = temp_adc.read()
12
+ R = (4095 / temp_raw) - 1.0
13
+
14
+ temp = 1.0 / (math.log(R) / B + 1/298.15) - 273.15
15
+ return temp
16
+
17
+ while True:
18
+ t = read_temp()
19
+ print('temp =', t)
20
+ pyb.delay(1000)