Dorothydu commited on
Commit
bf8177d
·
verified ·
1 Parent(s): 8040cc1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 2020-7-7-git-master/venv/Scripts/easy_install-script.py +12 -0
  2. 2020-7-7-git-master/venv/Scripts/pip-script.py +12 -0
  3. 2020-7-7-git-master/venv/Scripts/pip.exe +0 -0
  4. 2020-7-7-git-master/venv/Scripts/pip3-script.py +12 -0
  5. 2020-7-7-git-master/venv/Scripts/pip3.7.exe +0 -0
  6. 2020-7-7-git-master/venv/Scripts/python3.dll +0 -0
  7. 2020-7-7-git-master/venv/Scripts/pythonw.exe +0 -0
  8. 2020-7-7-git-master/venv/Scripts/select.pyd +0 -0
  9. 2020-7-7-git-master/venv/Scripts/vcruntime140.dll +0 -0
  10. 2020-7-7-git-master/venv/Scripts/winsound.pyd +0 -0
  11. 2020-zju-summer-intern-master/libsvm-3.24/python/svm.py +441 -0
  12. 2020-zju-summer-intern-master/libsvm-3.24/python/svmutil.py +259 -0
  13. 2020-zju-summer-intern-master/libsvm-3.24/tools/README +210 -0
  14. 2020-zju-summer-intern-master/libsvm-3.24/windows/libsvmwrite.mexw64 +0 -0
  15. 2020-zju-summer-intern-master/libsvm-3.24/windows/svmpredict.mexw64 +0 -0
  16. 2020-zju-summer-intern-master/libsvm-3.24/windows/svmtrain.mexw64 +0 -0
  17. 2021sp-final-project-mdhor-master/docs/Makefile +20 -0
  18. 2021sp-final-project-mdhor-master/docs/conclusion.rst +45 -0
  19. 2021sp-final-project-mdhor-master/docs/conf.py +80 -0
  20. 2021sp-final-project-mdhor-master/docs/django.rst +39 -0
  21. 2021sp-final-project-mdhor-master/docs/final_project.cli.rst +7 -0
  22. 2021sp-final-project-mdhor-master/docs/final_project.django_target.rst +7 -0
  23. 2021sp-final-project-mdhor-master/docs/final_project.rst +20 -0
  24. 2021sp-final-project-mdhor-master/docs/final_project.tasks.rst +7 -0
  25. 2021sp-final-project-mdhor-master/docs/index.rst +54 -0
  26. 2021sp-final-project-mdhor-master/docs/intro.rst +75 -0
  27. 2021sp-final-project-mdhor-master/docs/luigi_cli.rst +9 -0
  28. 2021sp-final-project-mdhor-master/docs/luigi_django_target.rst +21 -0
  29. 2021sp-final-project-mdhor-master/docs/luigi_intro.rst +39 -0
  30. 2021sp-final-project-mdhor-master/docs/luigi_tasks.rst +7 -0
  31. 2021sp-final-project-mdhor-master/docs/luigi_workflow.rst +10 -0
  32. 2021sp-final-project-mdhor-master/docs/make.bat +35 -0
  33. 2021sp-final-project-mdhor-master/docs/modules.rst +8 -0
  34. 2021sp-final-project-mdhor-master/docs/pj_scraper.rst +25 -0
  35. 2021sp-final-project-mdhor-master/docs/prisjakt.admin.rst +7 -0
  36. 2021sp-final-project-mdhor-master/docs/prisjakt.apps.rst +7 -0
  37. 2021sp-final-project-mdhor-master/docs/prisjakt.models.rst +7 -0
  38. 2021sp-final-project-mdhor-master/docs/prisjakt.rst +22 -0
  39. 2021sp-final-project-mdhor-master/docs/prisjakt.urls.rst +7 -0
  40. 2021sp-final-project-mdhor-master/docs/prisjakt.views.rst +7 -0
  41. 2021sp-final-project-mdhor-master/docs/requirements.txt +123 -0
  42. 2021sp-final-project-mdhor-master/final_project/__init__.py +7 -0
  43. 2021sp-final-project-mdhor-master/final_project/__main__.py +4 -0
  44. 2021sp-final-project-mdhor-master/final_project/cli.py +55 -0
  45. 2021sp-final-project-mdhor-master/final_project/conftest.py +14 -0
  46. 2021sp-final-project-mdhor-master/final_project/django_target.py +39 -0
  47. 2021sp-final-project-mdhor-master/final_project/tasks.py +133 -0
  48. 2021sp-final-project-mdhor-master/final_project/templates/account/email_confirm.html +31 -0
  49. 2021sp-final-project-mdhor-master/final_project/templates/account/login.html +47 -0
  50. 2021sp-final-project-mdhor-master/final_project/templates/account/logout.html +19 -0
2020-7-7-git-master/venv/Scripts/easy_install-script.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!D:\softwaredate\workspace\venv\Scripts\python.exe
2
+ # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install'
3
+ __requires__ = 'setuptools==39.1.0'
4
+ import re
5
+ import sys
6
+ from pkg_resources import load_entry_point
7
+
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(
11
+ load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install')()
12
+ )
2020-7-7-git-master/venv/Scripts/pip-script.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!D:\softwaredate\workspace\venv\Scripts\python.exe
2
+ # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
3
+ __requires__ = 'pip==10.0.1'
4
+ import re
5
+ import sys
6
+ from pkg_resources import load_entry_point
7
+
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(
11
+ load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
12
+ )
2020-7-7-git-master/venv/Scripts/pip.exe ADDED
Binary file (74.8 kB). View file
 
2020-7-7-git-master/venv/Scripts/pip3-script.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!D:\softwaredate\workspace\venv\Scripts\python.exe
2
+ # EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3'
3
+ __requires__ = 'pip==10.0.1'
4
+ import re
5
+ import sys
6
+ from pkg_resources import load_entry_point
7
+
8
+ if __name__ == '__main__':
9
+ sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
10
+ sys.exit(
11
+ load_entry_point('pip==10.0.1', 'console_scripts', 'pip3')()
12
+ )
2020-7-7-git-master/venv/Scripts/pip3.7.exe ADDED
Binary file (74.8 kB). View file
 
2020-7-7-git-master/venv/Scripts/python3.dll ADDED
Binary file (59 kB). View file
 
2020-7-7-git-master/venv/Scripts/pythonw.exe ADDED
Binary file (98.5 kB). View file
 
2020-7-7-git-master/venv/Scripts/select.pyd ADDED
Binary file (26.8 kB). View file
 
2020-7-7-git-master/venv/Scripts/vcruntime140.dll ADDED
Binary file (89.8 kB). View file
 
2020-7-7-git-master/venv/Scripts/winsound.pyd ADDED
Binary file (28.8 kB). View file
 
2020-zju-summer-intern-master/libsvm-3.24/python/svm.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ from ctypes import *
4
+ from ctypes.util import find_library
5
+ from os import path
6
+ import sys
7
+
8
+ try:
9
+ import scipy
10
+ from scipy import sparse
11
+ except:
12
+ scipy = None
13
+ sparse = None
14
+
15
+ if sys.version_info[0] < 3:
16
+ range = xrange
17
+ from itertools import izip as zip
18
+
19
+ __all__ = ['libsvm', 'svm_problem', 'svm_parameter',
20
+ 'toPyModel', 'gen_svm_nodearray', 'print_null', 'svm_node', 'C_SVC',
21
+ 'EPSILON_SVR', 'LINEAR', 'NU_SVC', 'NU_SVR', 'ONE_CLASS',
22
+ 'POLY', 'PRECOMPUTED', 'PRINT_STRING_FUN', 'RBF',
23
+ 'SIGMOID', 'c_double', 'svm_model']
24
+
25
+ try:
26
+ dirname = path.dirname(path.abspath(__file__))
27
+ if sys.platform == 'win32':
28
+ libsvm = CDLL(path.join(dirname, r'..\windows\libsvm.dll'))
29
+ else:
30
+ libsvm = CDLL(path.join(dirname, '../libsvm.so.2'))
31
+ except:
32
+ # For unix the prefix 'lib' is not considered.
33
+ if find_library('svm'):
34
+ libsvm = CDLL(find_library('svm'))
35
+ elif find_library('libsvm'):
36
+ libsvm = CDLL(find_library('libsvm'))
37
+ else:
38
+ raise Exception('LIBSVM library not found.')
39
+
40
+ C_SVC = 0
41
+ NU_SVC = 1
42
+ ONE_CLASS = 2
43
+ EPSILON_SVR = 3
44
+ NU_SVR = 4
45
+
46
+ LINEAR = 0
47
+ POLY = 1
48
+ RBF = 2
49
+ SIGMOID = 3
50
+ PRECOMPUTED = 4
51
+
52
+ PRINT_STRING_FUN = CFUNCTYPE(None, c_char_p)
53
+ def print_null(s):
54
+ return
55
+
56
+ def genFields(names, types):
57
+ return list(zip(names, types))
58
+
59
+ def fillprototype(f, restype, argtypes):
60
+ f.restype = restype
61
+ f.argtypes = argtypes
62
+
63
+ class svm_node(Structure):
64
+ _names = ["index", "value"]
65
+ _types = [c_int, c_double]
66
+ _fields_ = genFields(_names, _types)
67
+
68
+ def __init__(self, index=-1, value=0):
69
+ self.index, self.value = index, value
70
+
71
+ def __str__(self):
72
+ return '%d:%g' % (self.index, self.value)
73
+
74
+ def gen_svm_nodearray(xi, feature_max=None, isKernel=False):
75
+ if feature_max:
76
+ assert(isinstance(feature_max, int))
77
+
78
+ xi_shift = 0 # ensure correct indices of xi
79
+ if scipy and isinstance(xi, tuple) and len(xi) == 2\
80
+ and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
81
+ if not isKernel:
82
+ index_range = xi[0] + 1 # index starts from 1
83
+ else:
84
+ index_range = xi[0] # index starts from 0 for precomputed kernel
85
+ if feature_max:
86
+ index_range = index_range[scipy.where(index_range <= feature_max)]
87
+ elif scipy and isinstance(xi, scipy.ndarray):
88
+ if not isKernel:
89
+ xi_shift = 1
90
+ index_range = xi.nonzero()[0] + 1 # index starts from 1
91
+ else:
92
+ index_range = scipy.arange(0, len(xi)) # index starts from 0 for precomputed kernel
93
+ if feature_max:
94
+ index_range = index_range[scipy.where(index_range <= feature_max)]
95
+ elif isinstance(xi, (dict, list, tuple)):
96
+ if isinstance(xi, dict):
97
+ index_range = xi.keys()
98
+ elif isinstance(xi, (list, tuple)):
99
+ if not isKernel:
100
+ xi_shift = 1
101
+ index_range = range(1, len(xi) + 1) # index starts from 1
102
+ else:
103
+ index_range = range(0, len(xi)) # index starts from 0 for precomputed kernel
104
+
105
+ if feature_max:
106
+ index_range = filter(lambda j: j <= feature_max, index_range)
107
+ if not isKernel:
108
+ index_range = filter(lambda j:xi[j-xi_shift] != 0, index_range)
109
+
110
+ index_range = sorted(index_range)
111
+ else:
112
+ raise TypeError('xi should be a dictionary, list, tuple, 1-d numpy array, or tuple of (index, data)')
113
+
114
+ ret = (svm_node*(len(index_range)+1))()
115
+ ret[-1].index = -1
116
+
117
+ if scipy and isinstance(xi, tuple) and len(xi) == 2\
118
+ and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
119
+ for idx, j in enumerate(index_range):
120
+ ret[idx].index = j
121
+ ret[idx].value = (xi[1])[idx]
122
+ else:
123
+ for idx, j in enumerate(index_range):
124
+ ret[idx].index = j
125
+ ret[idx].value = xi[j - xi_shift]
126
+
127
+ max_idx = 0
128
+ if len(index_range) > 0:
129
+ max_idx = index_range[-1]
130
+ return ret, max_idx
131
+
132
+ try:
133
+ from numba import jit
134
+ jit_enabled = True
135
+ except:
136
+ jit = lambda x: x
137
+ jit_enabled = False
138
+
139
+ @jit
140
+ def csr_to_problem_jit(l, x_val, x_ind, x_rowptr, prob_val, prob_ind, prob_rowptr, indx_start):
141
+ for i in range(l):
142
+ b1,e1 = x_rowptr[i], x_rowptr[i+1]
143
+ b2,e2 = prob_rowptr[i], prob_rowptr[i+1]-1
144
+ for j in range(b1,e1):
145
+ prob_ind[j-b1+b2] = x_ind[j]+indx_start
146
+ prob_val[j-b1+b2] = x_val[j]
147
+ def csr_to_problem_nojit(l, x_val, x_ind, x_rowptr, prob_val, prob_ind, prob_rowptr, indx_start):
148
+ for i in range(l):
149
+ x_slice = slice(x_rowptr[i], x_rowptr[i+1])
150
+ prob_slice = slice(prob_rowptr[i], prob_rowptr[i+1]-1)
151
+ prob_ind[prob_slice] = x_ind[x_slice]+indx_start
152
+ prob_val[prob_slice] = x_val[x_slice]
153
+
154
+ def csr_to_problem(x, prob, isKernel):
155
+ if not x.has_sorted_indices:
156
+ x.sort_indices()
157
+
158
+ # Extra space for termination node and (possibly) bias term
159
+ x_space = prob.x_space = scipy.empty((x.nnz+x.shape[0]), dtype=svm_node)
160
+ prob.rowptr = x.indptr.copy()
161
+ prob.rowptr[1:] += scipy.arange(1,x.shape[0]+1)
162
+ prob_ind = x_space["index"]
163
+ prob_val = x_space["value"]
164
+ prob_ind[:] = -1
165
+ if not isKernel:
166
+ indx_start = 1 # index starts from 1
167
+ else:
168
+ indx_start = 0 # index starts from 0 for precomputed kernel
169
+ if jit_enabled:
170
+ csr_to_problem_jit(x.shape[0], x.data, x.indices, x.indptr, prob_val, prob_ind, prob.rowptr, indx_start)
171
+ else:
172
+ csr_to_problem_nojit(x.shape[0], x.data, x.indices, x.indptr, prob_val, prob_ind, prob.rowptr, indx_start)
173
+
174
+ class svm_problem(Structure):
175
+ _names = ["l", "y", "x"]
176
+ _types = [c_int, POINTER(c_double), POINTER(POINTER(svm_node))]
177
+ _fields_ = genFields(_names, _types)
178
+
179
+ def __init__(self, y, x, isKernel=False):
180
+ if (not isinstance(y, (list, tuple))) and (not (scipy and isinstance(y, scipy.ndarray))):
181
+ raise TypeError("type of y: {0} is not supported!".format(type(y)))
182
+
183
+ if isinstance(x, (list, tuple)):
184
+ if len(y) != len(x):
185
+ raise ValueError("len(y) != len(x)")
186
+ elif scipy != None and isinstance(x, (scipy.ndarray, sparse.spmatrix)):
187
+ if len(y) != x.shape[0]:
188
+ raise ValueError("len(y) != len(x)")
189
+ if isinstance(x, scipy.ndarray):
190
+ x = scipy.ascontiguousarray(x) # enforce row-major
191
+ if isinstance(x, sparse.spmatrix):
192
+ x = x.tocsr()
193
+ pass
194
+ else:
195
+ raise TypeError("type of x: {0} is not supported!".format(type(x)))
196
+ self.l = l = len(y)
197
+
198
+ max_idx = 0
199
+ x_space = self.x_space = []
200
+ if scipy != None and isinstance(x, sparse.csr_matrix):
201
+ csr_to_problem(x, self, isKernel)
202
+ max_idx = x.shape[1]
203
+ else:
204
+ for i, xi in enumerate(x):
205
+ tmp_xi, tmp_idx = gen_svm_nodearray(xi,isKernel=isKernel)
206
+ x_space += [tmp_xi]
207
+ max_idx = max(max_idx, tmp_idx)
208
+ self.n = max_idx
209
+
210
+ self.y = (c_double * l)()
211
+ if scipy != None and isinstance(y, scipy.ndarray):
212
+ scipy.ctypeslib.as_array(self.y, (self.l,))[:] = y
213
+ else:
214
+ for i, yi in enumerate(y): self.y[i] = yi
215
+
216
+ self.x = (POINTER(svm_node) * l)()
217
+ if scipy != None and isinstance(x, sparse.csr_matrix):
218
+ base = addressof(self.x_space.ctypes.data_as(POINTER(svm_node))[0])
219
+ x_ptr = cast(self.x, POINTER(c_uint64))
220
+ x_ptr = scipy.ctypeslib.as_array(x_ptr,(self.l,))
221
+ x_ptr[:] = self.rowptr[:-1]*sizeof(svm_node)+base
222
+ else:
223
+ for i, xi in enumerate(self.x_space): self.x[i] = xi
224
+
225
+ class svm_parameter(Structure):
226
+ _names = ["svm_type", "kernel_type", "degree", "gamma", "coef0",
227
+ "cache_size", "eps", "C", "nr_weight", "weight_label", "weight",
228
+ "nu", "p", "shrinking", "probability"]
229
+ _types = [c_int, c_int, c_int, c_double, c_double,
230
+ c_double, c_double, c_double, c_int, POINTER(c_int), POINTER(c_double),
231
+ c_double, c_double, c_int, c_int]
232
+ _fields_ = genFields(_names, _types)
233
+
234
+ def __init__(self, options = None):
235
+ if options == None:
236
+ options = ''
237
+ self.parse_options(options)
238
+
239
+ def __str__(self):
240
+ s = ''
241
+ attrs = svm_parameter._names + list(self.__dict__.keys())
242
+ values = map(lambda attr: getattr(self, attr), attrs)
243
+ for attr, val in zip(attrs, values):
244
+ s += (' %s: %s\n' % (attr, val))
245
+ s = s.strip()
246
+
247
+ return s
248
+
249
+ def set_to_default_values(self):
250
+ self.svm_type = C_SVC;
251
+ self.kernel_type = RBF
252
+ self.degree = 3
253
+ self.gamma = 0
254
+ self.coef0 = 0
255
+ self.nu = 0.5
256
+ self.cache_size = 100
257
+ self.C = 1
258
+ self.eps = 0.001
259
+ self.p = 0.1
260
+ self.shrinking = 1
261
+ self.probability = 0
262
+ self.nr_weight = 0
263
+ self.weight_label = None
264
+ self.weight = None
265
+ self.cross_validation = False
266
+ self.nr_fold = 0
267
+ self.print_func = cast(None, PRINT_STRING_FUN)
268
+
269
+ def parse_options(self, options):
270
+ if isinstance(options, list):
271
+ argv = options
272
+ elif isinstance(options, str):
273
+ argv = options.split()
274
+ else:
275
+ raise TypeError("arg 1 should be a list or a str.")
276
+ self.set_to_default_values()
277
+ self.print_func = cast(None, PRINT_STRING_FUN)
278
+ weight_label = []
279
+ weight = []
280
+
281
+ i = 0
282
+ while i < len(argv):
283
+ if argv[i] == "-s":
284
+ i = i + 1
285
+ self.svm_type = int(argv[i])
286
+ elif argv[i] == "-t":
287
+ i = i + 1
288
+ self.kernel_type = int(argv[i])
289
+ elif argv[i] == "-d":
290
+ i = i + 1
291
+ self.degree = int(argv[i])
292
+ elif argv[i] == "-g":
293
+ i = i + 1
294
+ self.gamma = float(argv[i])
295
+ elif argv[i] == "-r":
296
+ i = i + 1
297
+ self.coef0 = float(argv[i])
298
+ elif argv[i] == "-n":
299
+ i = i + 1
300
+ self.nu = float(argv[i])
301
+ elif argv[i] == "-m":
302
+ i = i + 1
303
+ self.cache_size = float(argv[i])
304
+ elif argv[i] == "-c":
305
+ i = i + 1
306
+ self.C = float(argv[i])
307
+ elif argv[i] == "-e":
308
+ i = i + 1
309
+ self.eps = float(argv[i])
310
+ elif argv[i] == "-p":
311
+ i = i + 1
312
+ self.p = float(argv[i])
313
+ elif argv[i] == "-h":
314
+ i = i + 1
315
+ self.shrinking = int(argv[i])
316
+ elif argv[i] == "-b":
317
+ i = i + 1
318
+ self.probability = int(argv[i])
319
+ elif argv[i] == "-q":
320
+ self.print_func = PRINT_STRING_FUN(print_null)
321
+ elif argv[i] == "-v":
322
+ i = i + 1
323
+ self.cross_validation = 1
324
+ self.nr_fold = int(argv[i])
325
+ if self.nr_fold < 2:
326
+ raise ValueError("n-fold cross validation: n must >= 2")
327
+ elif argv[i].startswith("-w"):
328
+ i = i + 1
329
+ self.nr_weight += 1
330
+ weight_label += [int(argv[i-1][2:])]
331
+ weight += [float(argv[i])]
332
+ else:
333
+ raise ValueError("Wrong options")
334
+ i += 1
335
+
336
+ libsvm.svm_set_print_string_function(self.print_func)
337
+ self.weight_label = (c_int*self.nr_weight)()
338
+ self.weight = (c_double*self.nr_weight)()
339
+ for i in range(self.nr_weight):
340
+ self.weight[i] = weight[i]
341
+ self.weight_label[i] = weight_label[i]
342
+
343
+ class svm_model(Structure):
344
+ _names = ['param', 'nr_class', 'l', 'SV', 'sv_coef', 'rho',
345
+ 'probA', 'probB', 'sv_indices', 'label', 'nSV', 'free_sv']
346
+ _types = [svm_parameter, c_int, c_int, POINTER(POINTER(svm_node)),
347
+ POINTER(POINTER(c_double)), POINTER(c_double),
348
+ POINTER(c_double), POINTER(c_double), POINTER(c_int),
349
+ POINTER(c_int), POINTER(c_int), c_int]
350
+ _fields_ = genFields(_names, _types)
351
+
352
+ def __init__(self):
353
+ self.__createfrom__ = 'python'
354
+
355
+ def __del__(self):
356
+ # free memory created by C to avoid memory leak
357
+ if hasattr(self, '__createfrom__') and self.__createfrom__ == 'C':
358
+ libsvm.svm_free_and_destroy_model(pointer(pointer(self)))
359
+
360
+ def get_svm_type(self):
361
+ return libsvm.svm_get_svm_type(self)
362
+
363
+ def get_nr_class(self):
364
+ return libsvm.svm_get_nr_class(self)
365
+
366
+ def get_svr_probability(self):
367
+ return libsvm.svm_get_svr_probability(self)
368
+
369
+ def get_labels(self):
370
+ nr_class = self.get_nr_class()
371
+ labels = (c_int * nr_class)()
372
+ libsvm.svm_get_labels(self, labels)
373
+ return labels[:nr_class]
374
+
375
+ def get_sv_indices(self):
376
+ total_sv = self.get_nr_sv()
377
+ sv_indices = (c_int * total_sv)()
378
+ libsvm.svm_get_sv_indices(self, sv_indices)
379
+ return sv_indices[:total_sv]
380
+
381
+ def get_nr_sv(self):
382
+ return libsvm.svm_get_nr_sv(self)
383
+
384
+ def is_probability_model(self):
385
+ return (libsvm.svm_check_probability_model(self) == 1)
386
+
387
+ def get_sv_coef(self):
388
+ return [tuple(self.sv_coef[j][i] for j in range(self.nr_class - 1))
389
+ for i in range(self.l)]
390
+
391
+ def get_SV(self):
392
+ result = []
393
+ for sparse_sv in self.SV[:self.l]:
394
+ row = dict()
395
+
396
+ i = 0
397
+ while True:
398
+ if sparse_sv[i].index == -1:
399
+ break
400
+ row[sparse_sv[i].index] = sparse_sv[i].value
401
+ i += 1
402
+
403
+ result.append(row)
404
+ return result
405
+
406
+ def toPyModel(model_ptr):
407
+ """
408
+ toPyModel(model_ptr) -> svm_model
409
+
410
+ Convert a ctypes POINTER(svm_model) to a Python svm_model
411
+ """
412
+ if bool(model_ptr) == False:
413
+ raise ValueError("Null pointer")
414
+ m = model_ptr.contents
415
+ m.__createfrom__ = 'C'
416
+ return m
417
+
418
+ fillprototype(libsvm.svm_train, POINTER(svm_model), [POINTER(svm_problem), POINTER(svm_parameter)])
419
+ fillprototype(libsvm.svm_cross_validation, None, [POINTER(svm_problem), POINTER(svm_parameter), c_int, POINTER(c_double)])
420
+
421
+ fillprototype(libsvm.svm_save_model, c_int, [c_char_p, POINTER(svm_model)])
422
+ fillprototype(libsvm.svm_load_model, POINTER(svm_model), [c_char_p])
423
+
424
+ fillprototype(libsvm.svm_get_svm_type, c_int, [POINTER(svm_model)])
425
+ fillprototype(libsvm.svm_get_nr_class, c_int, [POINTER(svm_model)])
426
+ fillprototype(libsvm.svm_get_labels, None, [POINTER(svm_model), POINTER(c_int)])
427
+ fillprototype(libsvm.svm_get_sv_indices, None, [POINTER(svm_model), POINTER(c_int)])
428
+ fillprototype(libsvm.svm_get_nr_sv, c_int, [POINTER(svm_model)])
429
+ fillprototype(libsvm.svm_get_svr_probability, c_double, [POINTER(svm_model)])
430
+
431
+ fillprototype(libsvm.svm_predict_values, c_double, [POINTER(svm_model), POINTER(svm_node), POINTER(c_double)])
432
+ fillprototype(libsvm.svm_predict, c_double, [POINTER(svm_model), POINTER(svm_node)])
433
+ fillprototype(libsvm.svm_predict_probability, c_double, [POINTER(svm_model), POINTER(svm_node), POINTER(c_double)])
434
+
435
+ fillprototype(libsvm.svm_free_model_content, None, [POINTER(svm_model)])
436
+ fillprototype(libsvm.svm_free_and_destroy_model, None, [POINTER(POINTER(svm_model))])
437
+ fillprototype(libsvm.svm_destroy_param, None, [POINTER(svm_parameter)])
438
+
439
+ fillprototype(libsvm.svm_check_parameter, c_char_p, [POINTER(svm_problem), POINTER(svm_parameter)])
440
+ fillprototype(libsvm.svm_check_probability_model, c_int, [POINTER(svm_model)])
441
+ fillprototype(libsvm.svm_set_print_string_function, None, [PRINT_STRING_FUN])
2020-zju-summer-intern-master/libsvm-3.24/python/svmutil.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os, sys
4
+ sys.path = [os.path.dirname(os.path.abspath(__file__))] + sys.path
5
+ from svm import *
6
+ from svm import __all__ as svm_all
7
+ from svm import scipy, sparse
8
+ from commonutil import *
9
+ from commonutil import __all__ as common_all
10
+
11
+ if sys.version_info[0] < 3:
12
+ range = xrange
13
+ from itertools import izip as zip
14
+ _cstr = lambda s: s.encode("utf-8") if isinstance(s,unicode) else str(s)
15
+ else:
16
+ _cstr = lambda s: bytes(s, "utf-8")
17
+
18
+ __all__ = ['svm_load_model', 'svm_predict', 'svm_save_model', 'svm_train'] + svm_all + common_all
19
+
20
+
21
+ def svm_load_model(model_file_name):
22
+ """
23
+ svm_load_model(model_file_name) -> model
24
+
25
+ Load a LIBSVM model from model_file_name and return.
26
+ """
27
+ model = libsvm.svm_load_model(_cstr(model_file_name))
28
+ if not model:
29
+ print("can't open model file %s" % model_file_name)
30
+ return None
31
+ model = toPyModel(model)
32
+ return model
33
+
34
+ def svm_save_model(model_file_name, model):
35
+ """
36
+ svm_save_model(model_file_name, model) -> None
37
+
38
+ Save a LIBSVM model to the file model_file_name.
39
+ """
40
+ libsvm.svm_save_model(_cstr(model_file_name), model)
41
+
42
+ def svm_train(arg1, arg2=None, arg3=None):
43
+ """
44
+ svm_train(y, x [, options]) -> model | ACC | MSE
45
+
46
+ y: a list/tuple/ndarray of l true labels (type must be int/double).
47
+
48
+ x: 1. a list/tuple of l training instances. Feature vector of
49
+ each training instance is a list/tuple or dictionary.
50
+
51
+ 2. an l * n numpy ndarray or scipy spmatrix (n: number of features).
52
+
53
+ svm_train(prob [, options]) -> model | ACC | MSE
54
+ svm_train(prob, param) -> model | ACC| MSE
55
+
56
+ Train an SVM model from data (y, x) or an svm_problem prob using
57
+ 'options' or an svm_parameter param.
58
+ If '-v' is specified in 'options' (i.e., cross validation)
59
+ either accuracy (ACC) or mean-squared error (MSE) is returned.
60
+ options:
61
+ -s svm_type : set type of SVM (default 0)
62
+ 0 -- C-SVC (multi-class classification)
63
+ 1 -- nu-SVC (multi-class classification)
64
+ 2 -- one-class SVM
65
+ 3 -- epsilon-SVR (regression)
66
+ 4 -- nu-SVR (regression)
67
+ -t kernel_type : set type of kernel function (default 2)
68
+ 0 -- linear: u'*v
69
+ 1 -- polynomial: (gamma*u'*v + coef0)^degree
70
+ 2 -- radial basis function: exp(-gamma*|u-v|^2)
71
+ 3 -- sigmoid: tanh(gamma*u'*v + coef0)
72
+ 4 -- precomputed kernel (kernel values in training_set_file)
73
+ -d degree : set degree in kernel function (default 3)
74
+ -g gamma : set gamma in kernel function (default 1/num_features)
75
+ -r coef0 : set coef0 in kernel function (default 0)
76
+ -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
77
+ -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
78
+ -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
79
+ -m cachesize : set cache memory size in MB (default 100)
80
+ -e epsilon : set tolerance of termination criterion (default 0.001)
81
+ -h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)
82
+ -b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
83
+ -wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)
84
+ -v n: n-fold cross validation mode
85
+ -q : quiet mode (no outputs)
86
+ """
87
+ prob, param = None, None
88
+ if isinstance(arg1, (list, tuple)) or (scipy and isinstance(arg1, scipy.ndarray)):
89
+ assert isinstance(arg2, (list, tuple)) or (scipy and isinstance(arg2, (scipy.ndarray, sparse.spmatrix)))
90
+ y, x, options = arg1, arg2, arg3
91
+ param = svm_parameter(options)
92
+ prob = svm_problem(y, x, isKernel=(param.kernel_type == PRECOMPUTED))
93
+ elif isinstance(arg1, svm_problem):
94
+ prob = arg1
95
+ if isinstance(arg2, svm_parameter):
96
+ param = arg2
97
+ else:
98
+ param = svm_parameter(arg2)
99
+ if prob == None or param == None:
100
+ raise TypeError("Wrong types for the arguments")
101
+
102
+ if param.kernel_type == PRECOMPUTED:
103
+ for i in range(prob.l):
104
+ xi = prob.x[i]
105
+ idx, val = xi[0].index, xi[0].value
106
+ if idx != 0:
107
+ raise ValueError('Wrong input format: first column must be 0:sample_serial_number')
108
+ if val <= 0 or val > prob.n:
109
+ raise ValueError('Wrong input format: sample_serial_number out of range')
110
+
111
+ if param.gamma == 0 and prob.n > 0:
112
+ param.gamma = 1.0 / prob.n
113
+ libsvm.svm_set_print_string_function(param.print_func)
114
+ err_msg = libsvm.svm_check_parameter(prob, param)
115
+ if err_msg:
116
+ raise ValueError('Error: %s' % err_msg)
117
+
118
+ if param.cross_validation:
119
+ l, nr_fold = prob.l, param.nr_fold
120
+ target = (c_double * l)()
121
+ libsvm.svm_cross_validation(prob, param, nr_fold, target)
122
+ ACC, MSE, SCC = evaluations(prob.y[:l], target[:l])
123
+ if param.svm_type in [EPSILON_SVR, NU_SVR]:
124
+ print("Cross Validation Mean squared error = %g" % MSE)
125
+ print("Cross Validation Squared correlation coefficient = %g" % SCC)
126
+ return MSE
127
+ else:
128
+ print("Cross Validation Accuracy = %g%%" % ACC)
129
+ return ACC
130
+ else:
131
+ m = libsvm.svm_train(prob, param)
132
+ m = toPyModel(m)
133
+
134
+ # If prob is destroyed, data including SVs pointed by m can remain.
135
+ m.x_space = prob.x_space
136
+ return m
137
+
138
+ def svm_predict(y, x, m, options=""):
139
+ """
140
+ svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
141
+
142
+ y: a list/tuple/ndarray of l true labels (type must be int/double).
143
+ It is used for calculating the accuracy. Use [] if true labels are
144
+ unavailable.
145
+
146
+ x: 1. a list/tuple of l training instances. Feature vector of
147
+ each training instance is a list/tuple or dictionary.
148
+
149
+ 2. an l * n numpy ndarray or scipy spmatrix (n: number of features).
150
+
151
+ Predict data (y, x) with the SVM model m.
152
+ options:
153
+ -b probability_estimates: whether to predict probability estimates,
154
+ 0 or 1 (default 0); for one-class SVM only 0 is supported.
155
+ -q : quiet mode (no outputs).
156
+
157
+ The return tuple contains
158
+ p_labels: a list of predicted labels
159
+ p_acc: a tuple including accuracy (for classification), mean-squared
160
+ error, and squared correlation coefficient (for regression).
161
+ p_vals: a list of decision values or probability estimates (if '-b 1'
162
+ is specified). If k is the number of classes, for decision values,
163
+ each element includes results of predicting k(k-1)/2 binary-class
164
+ SVMs. For probabilities, each element contains k values indicating
165
+ the probability that the testing instance is in each class.
166
+ Note that the order of classes here is the same as 'model.label'
167
+ field in the model structure.
168
+ """
169
+
170
+ def info(s):
171
+ print(s)
172
+
173
+ if scipy and isinstance(x, scipy.ndarray):
174
+ x = scipy.ascontiguousarray(x) # enforce row-major
175
+ elif sparse and isinstance(x, sparse.spmatrix):
176
+ x = x.tocsr()
177
+ elif not isinstance(x, (list, tuple)):
178
+ raise TypeError("type of x: {0} is not supported!".format(type(x)))
179
+
180
+ if (not isinstance(y, (list, tuple))) and (not (scipy and isinstance(y, scipy.ndarray))):
181
+ raise TypeError("type of y: {0} is not supported!".format(type(y)))
182
+
183
+ predict_probability = 0
184
+ argv = options.split()
185
+ i = 0
186
+ while i < len(argv):
187
+ if argv[i] == '-b':
188
+ i += 1
189
+ predict_probability = int(argv[i])
190
+ elif argv[i] == '-q':
191
+ info = print_null
192
+ else:
193
+ raise ValueError("Wrong options")
194
+ i+=1
195
+
196
+ svm_type = m.get_svm_type()
197
+ is_prob_model = m.is_probability_model()
198
+ nr_class = m.get_nr_class()
199
+ pred_labels = []
200
+ pred_values = []
201
+
202
+ if scipy and isinstance(x, sparse.spmatrix):
203
+ nr_instance = x.shape[0]
204
+ else:
205
+ nr_instance = len(x)
206
+
207
+ if predict_probability:
208
+ if not is_prob_model:
209
+ raise ValueError("Model does not support probabiliy estimates")
210
+
211
+ if svm_type in [NU_SVR, EPSILON_SVR]:
212
+ info("Prob. model for test data: target value = predicted value + z,\n"
213
+ "z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g" % m.get_svr_probability());
214
+ nr_class = 0
215
+
216
+ prob_estimates = (c_double * nr_class)()
217
+ for i in range(nr_instance):
218
+ if scipy and isinstance(x, sparse.spmatrix):
219
+ indslice = slice(x.indptr[i], x.indptr[i+1])
220
+ xi, idx = gen_svm_nodearray((x.indices[indslice], x.data[indslice]), isKernel=(m.param.kernel_type == PRECOMPUTED))
221
+ else:
222
+ xi, idx = gen_svm_nodearray(x[i], isKernel=(m.param.kernel_type == PRECOMPUTED))
223
+ label = libsvm.svm_predict_probability(m, xi, prob_estimates)
224
+ values = prob_estimates[:nr_class]
225
+ pred_labels += [label]
226
+ pred_values += [values]
227
+ else:
228
+ if is_prob_model:
229
+ info("Model supports probability estimates, but disabled in predicton.")
230
+ if svm_type in (ONE_CLASS, EPSILON_SVR, NU_SVC):
231
+ nr_classifier = 1
232
+ else:
233
+ nr_classifier = nr_class*(nr_class-1)//2
234
+ dec_values = (c_double * nr_classifier)()
235
+ for i in range(nr_instance):
236
+ if scipy and isinstance(x, sparse.spmatrix):
237
+ indslice = slice(x.indptr[i], x.indptr[i+1])
238
+ xi, idx = gen_svm_nodearray((x.indices[indslice], x.data[indslice]), isKernel=(m.param.kernel_type == PRECOMPUTED))
239
+ else:
240
+ xi, idx = gen_svm_nodearray(x[i], isKernel=(m.param.kernel_type == PRECOMPUTED))
241
+ label = libsvm.svm_predict_values(m, xi, dec_values)
242
+ if(nr_class == 1):
243
+ values = [1]
244
+ else:
245
+ values = dec_values[:nr_classifier]
246
+ pred_labels += [label]
247
+ pred_values += [values]
248
+
249
+ if len(y) == 0:
250
+ y = [0] * nr_instance
251
+ ACC, MSE, SCC = evaluations(y, pred_labels)
252
+
253
+ if svm_type in [EPSILON_SVR, NU_SVR]:
254
+ info("Mean squared error = %g (regression)" % MSE)
255
+ info("Squared correlation coefficient = %g (regression)" % SCC)
256
+ else:
257
+ info("Accuracy = %g%% (%d/%d) (classification)" % (ACC, int(round(nr_instance*ACC/100)), nr_instance))
258
+
259
+ return pred_labels, (ACC, MSE, SCC), pred_values
2020-zju-summer-intern-master/libsvm-3.24/tools/README ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This directory includes some useful codes:
2
+
3
+ 1. subset selection tools.
4
+ 2. parameter selection tools.
5
+ 3. LIBSVM format checking tools
6
+
7
+ Part I: Subset selection tools
8
+
9
+ Introduction
10
+ ============
11
+
12
+ Training large data is time consuming. Sometimes one should work on a
13
+ smaller subset first. The python script subset.py randomly selects a
14
+ specified number of samples. For classification data, we provide a
15
+ stratified selection to ensure the same class distribution in the
16
+ subset.
17
+
18
+ Usage: subset.py [options] dataset number [output1] [output2]
19
+
20
+ This script selects a subset of the given data set.
21
+
22
+ options:
23
+ -s method : method of selection (default 0)
24
+ 0 -- stratified selection (classification only)
25
+ 1 -- random selection
26
+
27
+ output1 : the subset (optional)
28
+ output2 : the rest of data (optional)
29
+
30
+ If output1 is omitted, the subset will be printed on the screen.
31
+
32
+ Example
33
+ =======
34
+
35
+ > python subset.py heart_scale 100 file1 file2
36
+
37
+ From heart_scale 100 samples are randomly selected and stored in
38
+ file1. All remaining instances are stored in file2.
39
+
40
+
41
+ Part II: Parameter Selection Tools
42
+
43
+ Introduction
44
+ ============
45
+
46
+ grid.py is a parameter selection tool for C-SVM classification using
47
+ the RBF (radial basis function) kernel. It uses cross validation (CV)
48
+ technique to estimate the accuracy of each parameter combination in
49
+ the specified range and helps you to decide the best parameters for
50
+ your problem.
51
+
52
+ grid.py directly executes libsvm binaries (so no python binding is needed)
53
+ for cross validation and then draw contour of CV accuracy using gnuplot.
54
+ You must have libsvm and gnuplot installed before using it. The package
55
+ gnuplot is available at http://www.gnuplot.info/
56
+
57
+ On Mac OSX, the precompiled gnuplot file needs the library Aquarterm,
58
+ which thus must be installed as well. In addition, this version of
59
+ gnuplot does not support png, so you need to change "set term png
60
+ transparent small" and use other image formats. For example, you may
61
+ have "set term pbm small color".
62
+
63
+ Usage: grid.py [grid_options] [svm_options] dataset
64
+
65
+ grid_options :
66
+ -log2c {begin,end,step | "null"} : set the range of c (default -5,15,2)
67
+ begin,end,step -- c_range = 2^{begin,...,begin+k*step,...,end}
68
+ "null" -- do not grid with c
69
+ -log2g {begin,end,step | "null"} : set the range of g (default 3,-15,-2)
70
+ begin,end,step -- g_range = 2^{begin,...,begin+k*step,...,end}
71
+ "null" -- do not grid with g
72
+ -v n : n-fold cross validation (default 5)
73
+ -svmtrain pathname : set svm executable path and name
74
+ -gnuplot {pathname | "null"} :
75
+ pathname -- set gnuplot executable path and name
76
+ "null" -- do not plot
77
+ -out {pathname | "null"} : (default dataset.out)
78
+ pathname -- set output file path and name
79
+ "null" -- do not output file
80
+ -png pathname : set graphic output file path and name (default dataset.png)
81
+ -resume [pathname] : resume the grid task using an existing output file (default pathname is dataset.out)
82
+ Use this option only if some parameters have been checked for the SAME data.
83
+
84
+ svm_options : additional options for svm-train
85
+
86
+ The program conducts v-fold cross validation using parameter C (and gamma)
87
+ = 2^begin, 2^(begin+step), ..., 2^end.
88
+
89
+ You can specify where the libsvm executable and gnuplot are using the
90
+ -svmtrain and -gnuplot parameters.
91
+
92
+ For windows users, please use pgnuplot.exe. If you are using gnuplot
93
+ 3.7.1, please upgrade to version 3.7.3 or higher. The version 3.7.1
94
+ has a bug. If you use cygwin on windows, please use gunplot-x11.
95
+
96
+ If the task is terminated accidentally or you would like to change the
97
+ range of parameters, you can apply '-resume' to save time by re-using
98
+ previous results. You may specify the output file of a previous run
99
+ or use the default (i.e., dataset.out) without giving a name. Please
100
+ note that the same condition must be used in two runs. For example,
101
+ you cannot use '-v 10' earlier and resume the task with '-v 5'.
102
+
103
+ The value of some options can be "null." For example, `-log2c -1,0,1
104
+ -log2 "null"' means that C=2^-1,2^0,2^1 and g=LIBSVM's default gamma
105
+ value. That is, you do not conduct parameter selection on gamma.
106
+
107
+ Example
108
+ =======
109
+
110
+ > python grid.py -log2c -5,5,1 -log2g -4,0,1 -v 5 -m 300 heart_scale
111
+
112
+ Users (in particular MS Windows users) may need to specify the path of
113
+ executable files. You can either change paths in the beginning of
114
+ grid.py or specify them in the command line. For example,
115
+
116
+ > grid.py -log2c -5,5,1 -svmtrain "c:\Program Files\libsvm\windows\svm-train.exe" -gnuplot c:\tmp\gnuplot\binary\pgnuplot.exe -v 10 heart_scale
117
+
118
+ Output: two files
119
+ dataset.png: the CV accuracy contour plot generated by gnuplot
120
+ dataset.out: the CV accuracy at each (log2(C),log2(gamma))
121
+
122
+ The following example saves running time by loading the output file of a previous run.
123
+
124
+ > python grid.py -log2c -7,7,1 -log2g -5,2,1 -v 5 -resume heart_scale.out heart_scale
125
+
126
+ Parallel grid search
127
+ ====================
128
+
129
+ You can conduct a parallel grid search by dispatching jobs to a
130
+ cluster of computers which share the same file system. First, you add
131
+ machine names in grid.py:
132
+
133
+ ssh_workers = ["linux1", "linux5", "linux5"]
134
+
135
+ and then setup your ssh so that the authentication works without
136
+ asking a password.
137
+
138
+ The same machine (e.g., linux5 here) can be listed more than once if
139
+ it has multiple CPUs or has more RAM. If the local machine is the
140
+ best, you can also enlarge the nr_local_worker. For example:
141
+
142
+ nr_local_worker = 2
143
+
144
+ Example:
145
+
146
+ > python grid.py heart_scale
147
+ [local] -1 -1 78.8889 (best c=0.5, g=0.5, rate=78.8889)
148
+ [linux5] -1 -7 83.3333 (best c=0.5, g=0.0078125, rate=83.3333)
149
+ [linux5] 5 -1 77.037 (best c=0.5, g=0.0078125, rate=83.3333)
150
+ [linux1] 5 -7 83.3333 (best c=0.5, g=0.0078125, rate=83.3333)
151
+ .
152
+ .
153
+ .
154
+
155
+ If -log2c, -log2g, or -v is not specified, default values are used.
156
+
157
+ If your system uses telnet instead of ssh, you list the computer names
158
+ in telnet_workers.
159
+
160
+ Calling grid in Python
161
+ ======================
162
+
163
+ In addition to using grid.py as a command-line tool, you can use it as a
164
+ Python module.
165
+
166
+ >>> rate, param = find_parameters(dataset, options)
167
+
168
+ You need to specify `dataset' and `options' (default ''). See the following example.
169
+
170
+ > python
171
+
172
+ >>> from grid import *
173
+ >>> rate, param = find_parameters('../heart_scale', '-log2c -1,1,1 -log2g -1,1,1')
174
+ [local] 0.0 0.0 rate=74.8148 (best c=1.0, g=1.0, rate=74.8148)
175
+ [local] 0.0 -1.0 rate=77.037 (best c=1.0, g=0.5, rate=77.037)
176
+ .
177
+ .
178
+ [local] -1.0 -1.0 rate=78.8889 (best c=0.5, g=0.5, rate=78.8889)
179
+ .
180
+ .
181
+ >>> rate
182
+ 78.8889
183
+ >>> param
184
+ {'c': 0.5, 'g': 0.5}
185
+
186
+
187
+ Part III: LIBSVM format checking tools
188
+
189
+ Introduction
190
+ ============
191
+
192
+ `svm-train' conducts only a simple check of the input data. To do a
193
+ detailed check, we provide a python script `checkdata.py.'
194
+
195
+ Usage: checkdata.py dataset
196
+
197
+ Exit status (returned value): 1 if there are errors, 0 otherwise.
198
+
199
+ This tool is written by Rong-En Fan at National Taiwan University.
200
+
201
+ Example
202
+ =======
203
+
204
+ > cat bad_data
205
+ 1 3:1 2:4
206
+ > python checkdata.py bad_data
207
+ line 1: feature indices must be in an ascending order, previous/current features 3:1 2:4
208
+ Found 1 lines with error.
209
+
210
+
2020-zju-summer-intern-master/libsvm-3.24/windows/libsvmwrite.mexw64 ADDED
Binary file (12.3 kB). View file
 
2020-zju-summer-intern-master/libsvm-3.24/windows/svmpredict.mexw64 ADDED
Binary file (27.1 kB). View file
 
2020-zju-summer-intern-master/libsvm-3.24/windows/svmtrain.mexw64 ADDED
Binary file (69.1 kB). View file
 
2021sp-final-project-mdhor-master/docs/Makefile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line, and also
5
+ # from the environment for the first two.
6
+ SPHINXOPTS ?=
7
+ SPHINXBUILD ?= sphinx-build
8
+ SOURCEDIR = .
9
+ BUILDDIR = _build
10
+
11
+ # Put it first so that "make" without argument is like "make help".
12
+ help:
13
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14
+
15
+ .PHONY: help Makefile
16
+
17
+ # Catch-all target: route all unknown targets to Sphinx using the new
18
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19
+ %: Makefile
20
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
2021sp-final-project-mdhor-master/docs/conclusion.rst ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Conclusion and Main Learnings
3
+ ==============================
4
+
5
+ #. Developing pj-scraper
6
+
7
+ * The libraries requests and BeautifulSoup4 has been used to mine unstructured data from prisjakt.no
8
+
9
+ * Two main functions have been developed: Getting all products from a category and getting all retailers and prices for a product or list of products
10
+
11
+ * The tools sdist and Twine has been used to publish pj-scraper to PyPi for easy installation
12
+
13
+ #. Organizing the workflow into Luigi Tasks
14
+
15
+ * Four main tasks has been developed that encapsulates the full data science pipeline
16
+
17
+ * The first two tasks handles the scraping of products, retailers and prices, utilizing the pj-scraper library
18
+
19
+ * The last two tasks handles appending the scraped data to the Django database, using Django commands
20
+
21
+ #. Creating a Django database
22
+
23
+ * A Django database has been developed which contains two tables: Products and Prices
24
+ * The Prices table is a fact table containing prices for each product and retailer for a given timestamp
25
+ * The Products table is a dim-table containing information about products, like product name and category
26
+
27
+ #. Developing a simple Django web app
28
+
29
+ * A simple web app has been developed, to showcase how the system could be used in practice
30
+
31
+ * To avoid unneseccary boilerplate and simplify visuals creation, mpld3 has been used
32
+
33
+ * Two simple visuals has been made, that shows two interesting analyses
34
+
35
+
36
+
37
+
38
+ Future Work
39
+ -------------------------------------
40
+
41
+ Before this project would have real value, two main things are missing:
42
+
43
+ #. Move the system to the cloud and schedule Luigi to run with certain intervals
44
+
45
+ #. Create insightful analyses based on inputs from potential users of the system
2021sp-final-project-mdhor-master/docs/conf.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # This file only contains a selection of the most common options. For a full
4
+ # list see the documentation:
5
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
6
+
7
+ # -- Path setup --------------------------------------------------------------
8
+
9
+ # If extensions (or modules to document with autodoc) are in another directory,
10
+ # add these directories to sys.path here. If the directory is relative to the
11
+ # documentation root, use os.path.abspath to make it absolute, like shown here.
12
+ #
13
+ import os
14
+ import sys
15
+
16
+ import django
17
+ from sphinx.ext.apidoc import main
18
+
19
+ sys.path.insert(0, os.path.abspath(".."))
20
+
21
+ # -- Django setup ------------------------------------------------------------
22
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
23
+ django.setup()
24
+
25
+
26
+ # -- Project information -----------------------------------------------------
27
+
28
+ project = "Final Project, Mattias Hornum, CSCI E-29"
29
+ copyright = "2021, Mattias Hornum"
30
+ author = "Mattias Hornum"
31
+
32
+
33
+ # -- General configuration ---------------------------------------------------
34
+
35
+ # Add any Sphinx extension module names here, as strings. They can be
36
+ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
37
+ # ones.
38
+ extensions = ["sphinx.ext.napoleon"]
39
+
40
+ # Add any paths that contain templates here, relative to this directory.
41
+ templates_path = ["_templates"]
42
+
43
+ # List of patterns, relative to source directory, that match files and
44
+ # directories to ignore when looking for source files.
45
+ # This pattern also affects html_static_path and html_extra_path.
46
+ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
47
+
48
+
49
+ # -- Options for HTML output -------------------------------------------------
50
+
51
+ # The theme to use for HTML and HTML Help pages. See the documentation for
52
+ # a list of builtin themes.
53
+ #
54
+ html_theme = "sphinx_rtd_theme"
55
+
56
+ # Add any paths that contain custom static files (such as style sheets) here,
57
+ # relative to this directory. They are copied after the builtin static files,
58
+ # so a file named "default.css" will overwrite the builtin "default.css".
59
+ html_static_path = ["_static"]
60
+
61
+
62
+ main(
63
+ [
64
+ "-e",
65
+ "-f",
66
+ "-o",
67
+ ".",
68
+ "..",
69
+ "../final_project/contrib*",
70
+ "../final_project/conftest*",
71
+ "../final_project/users*",
72
+ "../final_project/tests*",
73
+ "../final_project/utils*",
74
+ "../prisjakt/migrations*",
75
+ "../conftest*",
76
+ "../manage*",
77
+ "../config*",
78
+ "../modules*",
79
+ ]
80
+ )
2021sp-final-project-mdhor-master/docs/django.rst ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Introduction
3
+ ==================
4
+
5
+
6
+
7
+
8
+ Django Database
9
+ -----------------
10
+
11
+ The database is structured as a star schema. The fact table contains prices per retailer per timestamp per product.
12
+ The unique identifier for this table is the combination of timestamp, retailer and product. In future, this schema is
13
+ easily expandable with new dim-tables containing information on e.g. the retailers. Here is the schema:
14
+
15
+ .. image:: ./images/database.png
16
+ :width: 800
17
+
18
+
19
+
20
+
21
+
22
+ Django Web-App
23
+ ------------------
24
+
25
+ The web app for now only contains two simple visuals:
26
+
27
+ #. A line chart showing the historical prices of an iPhone 12, for the 10 retailers with lowest price today
28
+
29
+ #. A scatter plot showing retailer rating on the x-axis and price in the y-axis
30
+
31
+ The visuals have been created using the following procedure:
32
+
33
+ #. Query the DB to get only the needed data for the visual
34
+
35
+ #. Load data into a pandas dataframe
36
+
37
+ #. Use matplotlib to create the graph
38
+
39
+ #. Use mpld3 to convert the graph into html
2021sp-final-project-mdhor-master/docs/final_project.cli.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ final\_project.cli module
2
+ =========================
3
+
4
+ .. automodule:: final_project.cli
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/final_project.django_target.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ final\_project.django\_target module
2
+ ====================================
3
+
4
+ .. automodule:: final_project.django_target
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/final_project.rst ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ final\_project package
2
+ ======================
3
+
4
+ Submodules
5
+ ----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ final_project.cli
11
+ final_project.django_target
12
+ final_project.tasks
13
+
14
+ Module contents
15
+ ---------------
16
+
17
+ .. automodule:: final_project
18
+ :members:
19
+ :undoc-members:
20
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/final_project.tasks.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ final\_project.tasks module
2
+ ===========================
3
+
4
+ .. automodule:: final_project.tasks
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/index.rst ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. Final Project, CSCI E-29 documentation master file, created by
2
+ sphinx-quickstart on Wed Apr 28 18:13:52 2021.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+
7
+
8
+
9
+
10
+
11
+ Welcome to my Final Project
12
+ ====================================================================
13
+
14
+ .. start-badges
15
+
16
+ .. list-table::
17
+ :stub-columns: 1
18
+ :widths: 10 40
19
+
20
+ * - Build
21
+ - | |travis| |codeclimate| |codeclimate2|
22
+ * - Docs
23
+ - | |readthedocs|
24
+
25
+ .. |travis| image:: https://travis-ci.com/mdhor/2021sp-final-project-mdhor.svg?branch=master
26
+ :alt: Travis-CI Build Status
27
+ :target: https://travis-ci.com/github/mdhor/2021sp-final-project-mdhor
28
+
29
+ .. |codeclimate| image:: https://api.codeclimate.com/v1/badges/7469f8aaac5c1798b9e4/maintainability
30
+ :target: https://codeclimate.com/github/csci-e-29/2021sp-final-project-mdhor
31
+ :alt: CodeClimate Quality Status
32
+
33
+ .. |codeclimate2| image:: https://api.codeclimate.com/v1/badges/7469f8aaac5c1798b9e4/test_coverage
34
+ :target: https://codeclimate.com/github/csci-e-29/2021sp-final-project-mdhor
35
+ :alt: CodeClimate Coverage Status
36
+
37
+ .. |readthedocs| image:: https://readthedocs.org/projects/2021sp-final-project-mdhor/badge/?version=latest
38
+ :target: https://2021sp-final-project-mdhor.readthedocs.io/en/latest/?badge=latest
39
+ :alt: Documentation Status
40
+
41
+ .. end-badges
42
+
43
+
44
+
45
+ .. toctree::
46
+ :maxdepth: 4
47
+ :caption: Contents:
48
+
49
+ intro
50
+ pj_scraper
51
+ luigi_workflow
52
+ django_main
53
+ conclusion
54
+ #modules
2021sp-final-project-mdhor-master/docs/intro.rst ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Introduction
3
+ ============
4
+
5
+ Pricing and assortment data is highly valuable but can be difficult and expensive to obtain, especially for smaller retailers.
6
+
7
+ Because of digitalization, the importance of pricing and assortment data has increased. An insight into a companys online presence is crucial for success.
8
+ This is especially true after COVID-19, where smaller retailers are forced to differentiate themselves online.
9
+ Without large IT-budgets, gaining good data surrounding ones own as well as competitors pricing and assortment can be difficult.
10
+
11
+ Data on pricing and assortment can be used for several insightful analyses. One example is pricing analysis to answer questions like "Where do our prices differ from competitors?".
12
+ Another example is assortment analysis; "How does our assortment compare to competitors?".
13
+
14
+ prisjakt.no is a leading actor within price comparison in Norway. It acts as an "all-inclusive" shopping mall, so the consumer does not have to browse many different website, by comparing pricing
15
+ from many different retailers. The products range widely from electronics, to clothing, to vehicles.
16
+
17
+
18
+
19
+ Quick-Start
20
+ -------------------------------------
21
+
22
+ If you want to test the project quickly, first clone the repo and create an environment using the Pipfile.
23
+ Then execute the following commands:
24
+
25
+ .. code-block:: bash
26
+
27
+ pipenv run python manage.py migrate
28
+ pipenv run python -m final_project
29
+ pipenv run python manage.py runserver
30
+
31
+ Now you can open the server and check out a visual.
32
+
33
+
34
+
35
+
36
+
37
+ Aim of Project
38
+ -------------------------------------
39
+
40
+ The project aims to create a full stack data science pipeline, from mining prisjakt.no data all the way to showing results in a web application.
41
+ The project can be split into four main workflows:
42
+
43
+ #. Developing pj-scraper, a library that will act as a simplified interface for scraping of prisjakt.no
44
+
45
+ #. Organizing the pipeline into Luigi Tasks, all the way from handling scraping to appending data in a Django database
46
+
47
+ #. Creating a Django database that will contain the data that has been scraped from prisjakt.no
48
+
49
+ #. Developing a simple Django web app to show a simple example of how the data can be used for analysis
50
+
51
+
52
+
53
+ High-Level Workflow
54
+ ----------------------------------
55
+
56
+
57
+ .. image:: ./images/workflow.png
58
+ :width: 800
59
+
60
+
61
+
62
+
63
+
64
+ Autogeneration of the Documentation
65
+ -------------------------------------
66
+
67
+ To autogenerate the documentation i did the following three things:
68
+
69
+ #. Link ReadTheDocs with the Github repo, so a new RTD build will be executed on every new commit
70
+
71
+ #. Add a requirements.txt to the docs/ directory, to enable RTD to create the documentation within the right environment
72
+
73
+ #. Run sphinx-apidoc from within docs/conf.py, so that apidoc will run before the html output is created (although this is a cool feature, I decided not to use it in the end, but I've left it in for others to learn)
74
+
75
+ It should be noted that some of the autogenerated docs are blank because csci_utils can't be installed, because it is a private repo.
2021sp-final-project-mdhor-master/docs/luigi_cli.rst ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Autodocs: CLI
2
+ ================
3
+
4
+
5
+
6
+ .. automodule:: final_project.cli
7
+ :members:
8
+ :undoc-members:
9
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/luigi_django_target.rst ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Django Target
2
+ =================
3
+
4
+
5
+ I created a new target class, called DjangoModelTarget. The purpose of the class, is to tell Luigi whether the target
6
+ keys in a database table already exist or not. I've included the source code here:
7
+
8
+
9
+ .. literalinclude:: ../final_project/django_target.py
10
+ :language: python
11
+ :linenos:
12
+
13
+
14
+
15
+ Autodocs
16
+ -------------------
17
+
18
+ .. automodule:: final_project.django_target
19
+ :members:
20
+ :undoc-members:
21
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/luigi_intro.rst ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ Introduction
4
+ =================
5
+
6
+ The workflow consists of four main tasks:
7
+
8
+ #. Scrape products from a list of categories
9
+
10
+ #. Scrape retailers and prices for all products
11
+
12
+ #. Append any new products to database
13
+
14
+ #. Append all prices to the database with a new timestamp
15
+
16
+ The two tasks handling scraping both write to a parquet target which is salted. The salt is a function of the parameters,
17
+ as well the current day of the year, to avoid scraping prices more than once a day. This could in future be changed to be once per hour or even per minute.
18
+
19
+ Below are descriptions of each tasks, with pseudo code.
20
+
21
+ **Scrape product IDs**
22
+
23
+ .. image:: ./images/product_ids.png
24
+ :width: 800
25
+
26
+ **Scrape retailers and prices**
27
+
28
+ .. image:: ./images/scrape_prices.png
29
+ :width: 800
30
+
31
+ **Load product IDs to DB**
32
+
33
+ .. image:: ./images/task_load_prods.png
34
+ :width: 800
35
+
36
+ **Load retailers and prices to DB**
37
+
38
+ .. image:: ./images/task_load_prices.png
39
+ :width: 800
2021sp-final-project-mdhor-master/docs/luigi_tasks.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Autodocs: Luigi Tasks
2
+ ===============
3
+
4
+ .. automodule:: final_project.tasks
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/luigi_workflow.rst ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Luigi Workflow
2
+ ======================
3
+
4
+ .. toctree::
5
+ :maxdepth: 4
6
+
7
+ luigi_intro
8
+ luigi_tasks
9
+ luigi_django_target
10
+ luigi_cli
2021sp-final-project-mdhor-master/docs/make.bat ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @ECHO OFF
2
+
3
+ pushd %~dp0
4
+
5
+ REM Command file for Sphinx documentation
6
+
7
+ if "%SPHINXBUILD%" == "" (
8
+ set SPHINXBUILD=sphinx-build
9
+ )
10
+ set SOURCEDIR=.
11
+ set BUILDDIR=_build
12
+
13
+ if "%1" == "" goto help
14
+
15
+ %SPHINXBUILD% >NUL 2>NUL
16
+ if errorlevel 9009 (
17
+ echo.
18
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
19
+ echo.installed, then set the SPHINXBUILD environment variable to point
20
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
21
+ echo.may add the Sphinx directory to PATH.
22
+ echo.
23
+ echo.If you don't have Sphinx installed, grab it from
24
+ echo.http://sphinx-doc.org/
25
+ exit /b 1
26
+ )
27
+
28
+ %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29
+ goto end
30
+
31
+ :help
32
+ %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33
+
34
+ :end
35
+ popd
2021sp-final-project-mdhor-master/docs/modules.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ 2021sp-final-project-mdhor
2
+ ==========================
3
+
4
+ .. toctree::
5
+ :maxdepth: 4
6
+
7
+ final_project
8
+ prisjakt
2021sp-final-project-mdhor-master/docs/pj_scraper.rst ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ pj-scraper
4
+ ==========
5
+
6
+ The pj-scraper library is centered around the use of a single class, with methods that handle to main tasks:
7
+
8
+ #. Getting all products from a category, e.g. all from the category "smartphones"
9
+
10
+ #. Getting all retailers and prices for a product, e.g. all from the product "iPhone 12"
11
+
12
+ See repo on Github here: https://github.com/mdhor/pj-scraper#overview
13
+
14
+
15
+
16
+
17
+
18
+
19
+ pj_scraper package
20
+ ---------------------
21
+
22
+ .. autoclass:: pj_scraper.scraper.Scraper
23
+ :members:
24
+ :undoc-members:
25
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.admin.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ prisjakt.admin module
2
+ =====================
3
+
4
+ .. automodule:: prisjakt.admin
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.apps.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ prisjakt.apps module
2
+ ====================
3
+
4
+ .. automodule:: prisjakt.apps
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.models.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ prisjakt.models module
2
+ ======================
3
+
4
+ .. automodule:: prisjakt.models
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.rst ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ prisjakt package
2
+ ================
3
+
4
+ Submodules
5
+ ----------
6
+
7
+ .. toctree::
8
+ :maxdepth: 4
9
+
10
+ prisjakt.admin
11
+ prisjakt.apps
12
+ prisjakt.models
13
+ prisjakt.urls
14
+ prisjakt.views
15
+
16
+ Module contents
17
+ ---------------
18
+
19
+ .. automodule:: prisjakt
20
+ :members:
21
+ :undoc-members:
22
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.urls.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ prisjakt.urls module
2
+ ====================
3
+
4
+ .. automodule:: prisjakt.urls
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/prisjakt.views.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ prisjakt.views module
2
+ =====================
3
+
4
+ .. automodule:: prisjakt.views
5
+ :members:
6
+ :undoc-members:
7
+ :show-inheritance:
2021sp-final-project-mdhor-master/docs/requirements.txt ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # These requirements were autogenerated by pipenv
3
+ # To regenerate from the project's Pipfile, run:
4
+ #
5
+ # pipenv lock --requirements --dev
6
+ #
7
+
8
+ # Note: in pipenv 2020.x, "--dev" changed to emit both default and development
9
+ # requirements. To emit only development requirements, pass "--dev-only".
10
+
11
+ -i https://pypi.org/simple
12
+ aiobotocore==1.3.0; python_version >= '3.6'
13
+ aiohttp==3.7.4.post0; python_version >= '3.6'
14
+ aioitertools==0.7.1; python_version >= '3.6'
15
+ alabaster==0.7.12
16
+ appdirs==1.4.4
17
+ asgiref==3.3.4; python_version >= '3.6'
18
+ async-timeout==3.0.1; python_full_version >= '3.5.3'
19
+ atomicwrites==1.4.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
20
+ attrs==21.2.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
21
+ babel==2.9.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
22
+ beautifulsoup4==4.9.3
23
+ botocore==1.20.49; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
24
+ canvasapi==2.2.0
25
+ certifi==2020.12.5
26
+ cffi==1.14.5
27
+ cfgv==3.2.0; python_full_version >= '3.6.1'
28
+ chardet==4.0.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
29
+ cloudpickle==1.6.0; python_version >= '3.5'
30
+ coverage==5.5; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'
31
+ cramjam==2.3.0
32
+ cryptography==3.4.7
33
+ cycler==0.10.0
34
+ dask[dataframe]==2021.4.1; python_version >= '3.7'
35
+ defusedxml==0.7.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
36
+ distlib==0.3.1
37
+ django-allauth==0.44.0
38
+ django-crispy-forms==1.11.2
39
+ django-debug-toolbar==3.2.1
40
+ django-environ==0.4.5
41
+ django-extensions==3.1.3
42
+ django-model-utils==4.1.1
43
+ django==3.2.2
44
+ docutils==0.17.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
45
+ environs==9.3.2; python_version >= '3.6'
46
+ et-xmlfile==1.1.0; python_version >= '3.6'
47
+ factory-boy==3.2.0
48
+ faker==8.1.2; python_version >= '3.6'
49
+ fastparquet==0.6.0.post1
50
+ filelock==3.0.12
51
+ fsspec==2021.4.0; python_version >= '3.6'
52
+ gitdb==4.0.7; python_version >= '3.4'
53
+ gitpython==3.1.14; python_version >= '3.4'
54
+ identify==2.2.4; python_full_version >= '3.6.1'
55
+ idna==2.10; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
56
+ imagesize==1.2.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
57
+ iniconfig==1.1.1
58
+ jinja2==2.11.3; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
59
+ jmespath==0.10.0; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
60
+ kiwisolver==1.3.1; python_version >= '3.6'
61
+ llvmlite==0.36.0; python_version < '3.10' and python_version >= '3.6'
62
+ locket==0.2.1
63
+ lockfile==0.12.2
64
+ luigi==3.0.3
65
+ markupsafe==1.1.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
66
+ marshmallow==3.11.1; python_version >= '3.5'
67
+ matplotlib==3.4.2; python_version >= '3.7'
68
+ mpld3==0.5.2
69
+ multidict==5.1.0; python_version >= '3.6'
70
+ nodeenv==1.6.0
71
+ numba==0.53.1; python_version < '3.10' and python_version >= '3.6'
72
+ numpy==1.20.2
73
+ oauthlib==3.1.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
74
+ openpyxl==3.0.7; python_version >= '3.6'
75
+ packaging==20.9; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
76
+ pandas==1.2.4
77
+ partd==1.2.0; python_version >= '3.5'
78
+ pillow==8.2.0; python_version >= '3.6'
79
+ pj-scraper==0.0.4
80
+ pluggy==0.13.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
81
+ pre-commit==2.12.1
82
+ py==1.10.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
83
+ pycparser==2.20; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
84
+ pygments==2.9.0; python_version >= '3.5'
85
+ pyjwt[crypto]==2.1.0; python_version >= '3.6'
86
+ pyparsing==2.4.7; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
87
+ pytest-cov==2.11.1
88
+ pytest-django==4.2.0
89
+ pytest==6.2.4
90
+ python-daemon==2.3.0
91
+ python-dateutil==2.8.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
92
+ python-dotenv==0.17.1
93
+ python3-openid==3.2.0
94
+ pytz==2021.1
95
+ pyyaml==5.4.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'
96
+ requests-oauthlib==1.3.0
97
+ requests==2.25.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'
98
+ s3fs==2021.4.0; python_version >= '3.6'
99
+ scipy==1.6.3; python_version < '3.10' and python_version >= '3.7'
100
+ seaborn==0.11.1
101
+ six==1.16.0; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
102
+ smmap==4.0.0; python_version >= '3.5'
103
+ snowballstemmer==2.1.0
104
+ soupsieve==2.2.1; python_version >= '3.0'
105
+ sphinx==4.0.0
106
+ sphinxcontrib-applehelp==1.0.2; python_version >= '3.5'
107
+ sphinxcontrib-devhelp==1.0.2; python_version >= '3.5'
108
+ sphinxcontrib-htmlhelp==1.0.3; python_version >= '3.5'
109
+ sphinxcontrib-jsmath==1.0.1; python_version >= '3.5'
110
+ sphinxcontrib-qthelp==1.0.3; python_version >= '3.5'
111
+ sphinxcontrib-serializinghtml==1.1.4; python_version >= '3.5'
112
+ sqlparse==0.4.1; python_version >= '3.5'
113
+ tenacity==6.3.1
114
+ text-unidecode==1.3
115
+ thrift==0.13.0
116
+ toml==0.10.2; python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2, 3.3'
117
+ toolz==0.11.1; python_version >= '3.5'
118
+ tornado==6.1; python_version >= '3.5'
119
+ typing-extensions==3.10.0.0
120
+ urllib3==1.26.4; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'
121
+ virtualenv==20.4.6; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'
122
+ wrapt==1.12.1
123
+ yarl==1.6.3; python_version >= '3.6'
2021sp-final-project-mdhor-master/final_project/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __version__ = "0.1.0"
2
+ __version_info__ = tuple(
3
+ [
4
+ int(num) if num.isdigit() else num
5
+ for num in __version__.replace("-", ".", 1).split(".")
6
+ ]
7
+ )
2021sp-final-project-mdhor-master/final_project/__main__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
2021sp-final-project-mdhor-master/final_project/cli.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from unittest.mock import MagicMock
3
+
4
+ import django
5
+ from csci_utils.canvas.canvas import SubmissionHelper
6
+ from environs import Env
7
+ from luigi import WrapperTask, build
8
+ from luigi.util import requires
9
+
10
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
11
+ django.setup()
12
+
13
+
14
+ from .tasks import LoadPricesToDatabase, LoadProductsToDatabase
15
+
16
+
17
+ @requires(LoadProductsToDatabase, LoadPricesToDatabase)
18
+ class FinalProjectWrapper(WrapperTask):
19
+ pass
20
+
21
+
22
+ def main():
23
+ """ Main for running project and submitting """
24
+ # Fix for removing unwanted logging by requests/bs4 in Travis
25
+ import os
26
+ import sys
27
+
28
+ f = open(os.devnull, "w")
29
+ sys.stdout = f
30
+
31
+ build(
32
+ [
33
+ FinalProjectWrapper(
34
+ categories=["mobiltelefoner", "smartklokker", "hodetelefoner"]
35
+ )
36
+ ],
37
+ local_scheduler=True,
38
+ log_level="INFO",
39
+ )
40
+
41
+ env = Env()
42
+ env.read_env()
43
+
44
+ submission = SubmissionHelper.quick_start(
45
+ env.str("CANVAS_URL"),
46
+ env.str("CANVAS_TOKEN"),
47
+ "CSCI E-29",
48
+ "Final Project",
49
+ )
50
+
51
+ quiz_submission = MagicMock()
52
+ quiz_submission.id = ""
53
+ quiz_submission.attempt = ""
54
+
55
+ submission.submit_assignment(quiz_submission, submit=True)
2021sp-final-project-mdhor-master/final_project/conftest.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from final_project.users.models import User
4
+ from final_project.users.tests.factories import UserFactory
5
+
6
+
7
+ @pytest.fixture(autouse=True)
8
+ def media_storage(settings, tmpdir):
9
+ settings.MEDIA_ROOT = tmpdir.strpath
10
+
11
+
12
+ @pytest.fixture
13
+ def user() -> User:
14
+ return UserFactory()
2021sp-final-project-mdhor-master/final_project/django_target.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from luigi import Target
2
+
3
+
4
+ class DjangoModelTarget(Target):
5
+ """ Luigi target for Django models """
6
+
7
+ def __init__(self, model, **unique):
8
+ """Input args for Django target
9
+
10
+ Args:
11
+ model: A Django model
12
+ unique: The keys to target (should only be one field)
13
+
14
+ Example:
15
+ target = DjangoModelTarget(Model, unique_key=[1,2,3])
16
+ This will target the values "1, 2, and 3" in field "unique_key" in model "Model"
17
+ """
18
+ self.model = model
19
+ if len(unique) == 1:
20
+ self.unique = unique
21
+ else:
22
+ raise RuntimeError("More than one unique key")
23
+
24
+ def get(self):
25
+ """ Get the objects matching the keys """
26
+ return self.model.objects.filter(
27
+ **{f"{key}__in": value for key, value in self.unique.items()}
28
+ )
29
+
30
+ def exists(self):
31
+ try:
32
+ m = self.get()
33
+ return (
34
+ True
35
+ if len(m) == len([val for val in self.unique.values()][0])
36
+ else False
37
+ )
38
+ except:
39
+ return False
2021sp-final-project-mdhor-master/final_project/tasks.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from contextlib import contextmanager
3
+ from datetime import datetime, timedelta
4
+
5
+ import pandas as pd
6
+ from csci_utils.luigi.target import SuffixPreservingLocalTarget
7
+ from csci_utils.luigi.task import Requirement, Requires, TargetOutput
8
+ from luigi import IntParameter, ListParameter, Task
9
+ from luigi.contrib.external_program import ExternalProgramTask
10
+ from luigi.util import inherits
11
+ from pj_scraper.scraper import Scraper
12
+
13
+ from final_project.django_target import DjangoModelTarget
14
+ from prisjakt.models import Prices, Products
15
+
16
+
17
+ class ScrapeProducts(Task):
18
+
19
+ categories = ListParameter(default=["mobiltelefoner", "smartklokker"])
20
+ no_pages = IntParameter(default=1)
21
+
22
+ now = datetime.now() + timedelta(days=1)
23
+ output = TargetOutput(
24
+ "./data/",
25
+ file_pattern="day"
26
+ + str(now.timetuple().tm_yday)
27
+ + "-{task.__class__.__name__}-{salt}{self.ext}",
28
+ target_class=SuffixPreservingLocalTarget,
29
+ salted=True,
30
+ ext=".parquet",
31
+ )
32
+
33
+ def run(self):
34
+ s = Scraper()
35
+ all_products = pd.DataFrame()
36
+
37
+ for category in self.categories:
38
+ temp_df = s.get_all_products_from_category(category, no_pages=self.no_pages)
39
+ all_products = all_products.append(temp_df)
40
+
41
+ with self.output().temporary_path() as fp:
42
+ all_products.to_parquet(fp, compression="gzip")
43
+
44
+
45
+ @inherits(ScrapeProducts)
46
+ class ScrapePrices(Task):
47
+
48
+ products = Requirement(ScrapeProducts)
49
+ requires = Requires()
50
+
51
+ now = datetime.now() + timedelta(days=1)
52
+ output = TargetOutput(
53
+ "./data/",
54
+ file_pattern="day"
55
+ + str(now.timetuple().tm_yday)
56
+ + "-{task.__class__.__name__}-{salt}{self.ext}",
57
+ target_class=SuffixPreservingLocalTarget,
58
+ salted=True,
59
+ ext=".parquet",
60
+ )
61
+
62
+ def run(self):
63
+ s = Scraper()
64
+ products = pd.read_parquet(
65
+ self.products.output().path, columns=["product_number"]
66
+ )
67
+ products = products.astype(str)
68
+ prices_and_retailers = s.get_sellers_and_prices_of_product_list(
69
+ products.product_number
70
+ )
71
+ prices_and_retailers["timestamp"] = self.now
72
+ with self.output().temporary_path() as fp:
73
+ prices_and_retailers.to_parquet(fp, compression="gzip")
74
+
75
+
76
+ @inherits(ScrapePrices)
77
+ class LoadPricesToDatabase(ExternalProgramTask):
78
+
79
+ prices = Requirement(ScrapePrices)
80
+ requires = Requires()
81
+
82
+ def program_args(self):
83
+ return f"python manage.py load_prices --input_path {self.prices.output().path}".split(
84
+ " "
85
+ )
86
+
87
+ def run(self):
88
+ super().run()
89
+
90
+ def output(self):
91
+ ids = pd.read_parquet(
92
+ self.prices.output().path,
93
+ columns=["product_number", "seller_id", "timestamp"],
94
+ )
95
+ ids = [
96
+ str(entry.product_number)
97
+ + str(entry.seller_id)
98
+ + str(entry.timestamp.timetuple().tm_yday)
99
+ for entry in ids.itertuples()
100
+ ]
101
+ return DjangoModelTarget(Prices, unique_identifier=list(set(ids)))
102
+
103
+
104
+ @inherits(ScrapeProducts)
105
+ class LoadProductsToDatabase(ExternalProgramTask):
106
+
107
+ products = Requirement(ScrapeProducts)
108
+ requires = Requires()
109
+
110
+ def program_args(self):
111
+ return f"python manage.py load_products --input_path {self.products.output().path}".split(
112
+ " "
113
+ )
114
+
115
+ def run(self):
116
+ super().run()
117
+
118
+ def output(self):
119
+ ids = pd.read_parquet(self.products.output().path, columns=["product_number"])
120
+ ids = ids.product_number.values
121
+ return DjangoModelTarget(Products, product_number=list(set(ids)))
122
+
123
+
124
+ @contextmanager
125
+ def change_dir(relative_dir):
126
+ """ Context manager for temporarily entering another dir """
127
+ cwd = os.getcwd()
128
+ try:
129
+ os.chdir("./" + relative_dir)
130
+ yield
131
+ finally:
132
+ if os.getcwd() is not cwd:
133
+ os.chdir(cwd)
2021sp-final-project-mdhor-master/final_project/templates/account/email_confirm.html ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "account/base.html" %}
2
+
3
+ {% load i18n %}
4
+ {% load account %}
5
+
6
+ {% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %}
7
+
8
+
9
+ {% block inner %}
10
+ <h1>{% trans "Confirm E-mail Address" %}</h1>
11
+
12
+ {% if confirmation %}
13
+
14
+ {% user_display confirmation.email_address.user as user_display %}
15
+
16
+ <p>{% blocktrans with confirmation.email_address.email as email %}Please confirm that <a href="mailto:{{ email }}">{{ email }}</a> is an e-mail address for user {{ user_display }}.{% endblocktrans %}</p>
17
+
18
+ <form method="post" action="{% url 'account_confirm_email' confirmation.key %}">
19
+ {% csrf_token %}
20
+ <button class="btn btn-primary" type="submit">{% trans 'Confirm' %}</button>
21
+ </form>
22
+
23
+ {% else %}
24
+
25
+ {% url 'account_email' as email_url %}
26
+
27
+ <p>{% blocktrans %}This e-mail confirmation link expired or is invalid. Please <a href="{{ email_url }}">issue a new e-mail confirmation request</a>.{% endblocktrans %}</p>
28
+
29
+ {% endif %}
30
+
31
+ {% endblock %}
2021sp-final-project-mdhor-master/final_project/templates/account/login.html ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "account/base.html" %}
2
+
3
+ {% load i18n %}
4
+ {% load account socialaccount %}
5
+ {% load crispy_forms_tags %}
6
+
7
+ {% block head_title %}{% trans "Sign In" %}{% endblock %}
8
+
9
+ {% block inner %}
10
+
11
+ <h1>{% trans "Sign In" %}</h1>
12
+
13
+ {% get_providers as socialaccount_providers %}
14
+
15
+ {% if socialaccount_providers %}
16
+ <p>{% blocktrans with site.name as site_name %}Please sign in with one
17
+ of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a>
18
+ for a {{ site_name }} account and sign in below:{% endblocktrans %}</p>
19
+
20
+ <div class="socialaccount_ballot">
21
+
22
+ <ul class="socialaccount_providers">
23
+ {% include "socialaccount/snippets/provider_list.html" with process="login" %}
24
+ </ul>
25
+
26
+ <div class="login-or">{% trans 'or' %}</div>
27
+
28
+ </div>
29
+
30
+ {% include "socialaccount/snippets/login_extra.html" %}
31
+
32
+ {% else %}
33
+ <p>{% blocktrans %}If you have not created an account yet, then please
34
+ <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p>
35
+ {% endif %}
36
+
37
+ <form class="login" method="POST" action="{% url 'account_login' %}">
38
+ {% csrf_token %}
39
+ {{ form|crispy }}
40
+ {% if redirect_field_value %}
41
+ <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
42
+ {% endif %}
43
+ <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a>
44
+ <button class="primaryAction btn btn-primary" type="submit">{% trans "Sign In" %}</button>
45
+ </form>
46
+
47
+ {% endblock %}
2021sp-final-project-mdhor-master/final_project/templates/account/logout.html ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "account/base.html" %}
2
+
3
+ {% load i18n %}
4
+
5
+ {% block head_title %}{% trans "Sign Out" %}{% endblock %}
6
+
7
+ {% block inner %}
8
+ <h1>{% trans "Sign Out" %}</h1>
9
+
10
+ <p>{% trans 'Are you sure you want to sign out?' %}</p>
11
+
12
+ <form method="post" action="{% url 'account_logout' %}">
13
+ {% csrf_token %}
14
+ {% if redirect_field_value %}
15
+ <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}"/>
16
+ {% endif %}
17
+ <button class="btn btn-danger" type="submit">{% trans 'Sign Out' %}</button>
18
+ </form>
19
+ {% endblock %}