Dorothydu commited on
Commit
c6f6cfd
·
verified ·
1 Parent(s): e345cd9

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. -Api_avec_python-master/.pipreqs/requirements_pipreqs.txt +1 -0
  2. -Api_avec_python-master/Api.py +35 -0
  3. -Api_avec_python-master/README.md +2 -0
  4. -QuQ--master/.gitignore +101 -0
  5. -QuQ--master/.pipreqs/requirements_pipreqs.txt +4 -0
  6. -QuQ--master/baseClass/ControlFlow.py +72 -0
  7. -QuQ--master/baseClass/Qubit.py +374 -0
  8. -QuQ--master/config/errorRate.cfg +2 -0
  9. -QuQ--master/doc/UserManual/userManual.pdf +1 -0
  10. -QuQ--master/main/main.py +72 -0
  11. -QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/QASM.txt +5 -0
  12. -QuQ--master/results/EXP2018-03-14-15.23.40/Physical-Level/QASM.txt +13 -0
  13. -QuQ--master/results/EXP2018-03-14-15.23.40/originalData.csv +2 -0
  14. -QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/QASM.txt +19 -0
  15. -QuQ--master/results/EXP2018-03-14-15.23.45/originalData.csv +2 -0
  16. -QuQ--master/tools/export.py +1 -0
  17. -QuQ--master/userCode/Grover.py +93 -0
  18. -QuQ--master/userCode/GroverN=8theory/originalData.csv +9 -0
  19. -QuQ--master/userCode/UserSWAP.py +15 -0
  20. 0617-audio_stream-master/README.md +1 -0
  21. 0617-audio_stream-master/hyper.py +29 -0
  22. 0617-audio_stream-master/mean_std.py +11 -0
  23. 0617-audio_stream-master/model/ResNe3D.py +270 -0
  24. 0617-audio_stream-master/model/ResNet.py +142 -0
  25. 0617-audio_stream-master/model/ResNet_18.py +79 -0
  26. 0617-audio_stream-master/model/v_a_con.py +43 -0
  27. 0621_test-master/.gitignore +229 -0
  28. 0621_test-master/.pipreqs/requirements_pipreqs.txt +1 -0
  29. 0621_test-master/django_app/config/urls.py +22 -0
  30. 0621_test-master/django_app/manage.py +22 -0
  31. 0621_test-master/django_app/post/urls.py +10 -0
  32. 0621_test-master/django_app/post/views.py +36 -0
  33. 10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.py +16 -0
  34. 10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree.go +24 -0
  35. 10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.py +26 -0
  36. 10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.py +22 -0
  37. 10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits_test.go +22 -0
  38. 10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.py +13 -0
  39. 10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.go +18 -0
  40. 10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.py +28 -0
  41. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.go +34 -0
  42. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.py +19 -0
  43. 10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.go +15 -0
  44. 10-week-algorithm-excercise-master/OneQuestionPerDay/README.md +79 -0
  45. 10-week-algorithm-excercise-master/Week_01/1/two_sum.go +44 -0
  46. 10-week-algorithm-excercise-master/Week_01/1/two_sum_2.go +13 -0
  47. 10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.py +29 -0
  48. 10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.go +16 -0
  49. 10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii_test.go +24 -0
  50. 10-week-algorithm-excercise-master/Week_01/15/3sum.py +43 -0
-Api_avec_python-master/.pipreqs/requirements_pipreqs.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Requests==2.32.3
-Api_avec_python-master/Api.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###########
2
+ # IMPORTS #
3
+ ###########
4
+
5
+ import requests
6
+
7
+ # url va me servir de changer de page dans la boucle while
8
+ url = "https://swapi.co/api/people/"
9
+
10
+ # Quand il n'y a plus de "page suivante", la page "next" sera egale a None
11
+ # Donc, je boucle sur url tant qu'elle n'est egale a None :)
12
+ while url is not None:
13
+ print("")
14
+
15
+ ############################
16
+ # RÉCUPÉRATION DES DONNÉES #
17
+ ############################
18
+
19
+ # Je fais la requête sur la page en cours, et je recupere la data
20
+ r = requests.get(url)
21
+ data = r.json()
22
+
23
+ # C'est ici que je change l'url pour avoir la page d'apres :)
24
+ url = data["next"]
25
+ # Ce tableau est la liste de tous les personnages
26
+ persosTab = data["results"]
27
+
28
+ ###########################
29
+ # UTILISATION DES DONNÉES #
30
+ ###########################
31
+
32
+ # Je fais ensuite une boucle qui parcourt tous les personnages
33
+ # et qui affiche leur nom !
34
+ for perso in persosTab:
35
+ print(perso["name"])
-Api_avec_python-master/README.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # -Api_avec_python
2
+ Différente Api avec python
-QuQ--master/.gitignore ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ env/
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ .hypothesis/
48
+
49
+ # Translations
50
+ *.mo
51
+ *.pot
52
+
53
+ # Django stuff:
54
+ *.log
55
+ local_settings.py
56
+
57
+ # Flask stuff:
58
+ instance/
59
+ .webassets-cache
60
+
61
+ # Scrapy stuff:
62
+ .scrapy
63
+
64
+ # Sphinx documentation
65
+ docs/_build/
66
+
67
+ # PyBuilder
68
+ target/
69
+
70
+ # Jupyter Notebook
71
+ .ipynb_checkpoints
72
+
73
+ # pyenv
74
+ .python-version
75
+
76
+ # celery beat schedule file
77
+ celerybeat-schedule
78
+
79
+ # SageMath parsed files
80
+ *.sage.py
81
+
82
+ # dotenv
83
+ .env
84
+
85
+ # virtualenv
86
+ .venv
87
+ venv/
88
+ ENV/
89
+
90
+ # Spyder project settings
91
+ .spyderproject
92
+ .spyproject
93
+
94
+ # Rope project settings
95
+ .ropeproject
96
+
97
+ # mkdocs documentation
98
+ /site
99
+
100
+ # mypy
101
+ .mypy_cache/
-QuQ--master/.pipreqs/requirements_pipreqs.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ IBMQuantumExperience==2.0.4
2
+ matplotlib==3.10.1
3
+ numpy==2.2.4
4
+ psutil==7.0.0
-QuQ--master/baseClass/ControlFlow.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from baseCF import *
2
+ from Gate import *
3
+ from Circuit import *
4
+ from DMO import DMO,MO,QWMO
5
+
6
+ #a single qubit can be used as the guard;
7
+ #if there is more the one qubit in the guard, you should pass these qubits as a list
8
+ #if the values list has only one element, the value of all the qubits should be same with the value of the element;
9
+ #otherwise the length of the values list should be same with the length of the qubits list
10
+ # class Qif(ControlFlow):
11
+ # def __init__(self,q,v):
12
+ # ControlFlow.__init__(self,q,v)
13
+ # #this function is quantum teleportation quantum if
14
+ # def __enter__(self):
15
+ # resList = []
16
+ # for q in self.ql:
17
+ # q1 = Qubit(True)
18
+ # q2 = Qubit(True)
19
+ # H(q1,False)
20
+ # CNOT(q1,q2,False)
21
+ # CNOT(q,q1,False)
22
+ # H(q,False)
23
+ # CNOT(q1,q2,False)
24
+ # H(q2,False)
25
+ # CNOT(q,q2,False)
26
+ # H(q2,False)
27
+ # # #restore the state of the Qubit "q"
28
+ # # H(q,False)
29
+ # #destory the auxiliary qubits "q1" and "q2"
30
+ # q2 = M(q2,False)
31
+ # q1 = M(q1,False)
32
+ # resList.append(q2.value)
33
+ # if len(self.vl) == 1:
34
+ # for r in resList:
35
+ # if r != self.vl[0]:
36
+ # return False
37
+ # else:
38
+ # for i in range(0,len(resList)):
39
+ # if resList[i] != self.vl[i]:
40
+ # return False
41
+ # return True
42
+
43
+ #in the following two methods, the qubit used as the guard can't be appeared in the executive body.
44
+ class DMif(ControlFlow):
45
+ def __init__(self,q,v):
46
+ ControlFlow.__init__(self,q,v)
47
+
48
+ #this function is delay measure-based quantum if
49
+ def __enter__(self):
50
+ dmo = DMO(self.ql,self.vl)
51
+ return dmo
52
+ def __exit__(self,a,b,c):
53
+ return True
54
+
55
+ class Mif(ControlFlow):
56
+ def __init__(self,q,v):
57
+ ControlFlow.__init__(self,q,v)
58
+ #this function is measure-based quantum if
59
+ def __enter__(self):
60
+ mo = MO(self.ql,self.vl)
61
+ #mo.bool stands for the control guard
62
+ return mo
63
+
64
+
65
+ class Qwhile(ControlFlow):
66
+ def __init__(self,q,v,angle):
67
+ ControlFlow.__init__(self,q,v)
68
+ self.angle = angle
69
+ #this function is delay measure-based quantum while
70
+ def __enter__(self):
71
+ qw = QWMO(self.ql,self.vl,self.angle)
72
+ return qw
-QuQ--master/baseClass/Qubit.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ from baseQubit import BaseQubit
3
+ import sys
4
+ sys.path.append('../tools/')
5
+ import interactCfg
6
+ import math
7
+ #from Circuit import Circuit
8
+ from Error import *
9
+ from Bit import Bit
10
+ import random
11
+ import copy
12
+
13
+ #get the info about the function name and the line number
14
+ def get_curl_info():
15
+ try:
16
+ raise Exception
17
+ except:
18
+ f = sys.exc_info()[2].tb_frame.f_back
19
+ return [f.f_code.co_name, f.f_lineno]
20
+
21
+ #the init state of the qubit must be |0>
22
+ class Qubit(BaseQubit):
23
+ #mode is an argument of the class, so that all the qubit can have the same execution mode
24
+ mode = interactCfg.readCfgEM()
25
+ #use the list to store the ids, so that ID won't repeat
26
+ idList = []
27
+ #figure out the number of the Qubit in <QuQ>, and the value of the parameter can only increase
28
+ totalNum = 0
29
+ #the physical process of "preparation" is described as this function
30
+ #mode='theory' or 'simulator', the user manual introduce details of the arguments
31
+
32
+ #if the parameter "tag" is set to True, it means that the qubit is an auxiliary qubit
33
+
34
+ def __init__(self,tag = False,ids=None):
35
+ #BaseQubit.__init__(self)
36
+ self.matrix = [[],[]]
37
+ self.amplitude = [0,0]
38
+ self.assignmentError = 0.0
39
+ self.singleGateError = 0.0
40
+ #show whether the qubit was in entanglement
41
+ self.entanglement = None
42
+ if ids == None:
43
+ ids = Qubit.totalNum + 1
44
+ #the index of the current qubit, the range is from 0 to n
45
+ if ids in Qubit.idList:
46
+ try:
47
+ raise IDRepeatError()
48
+ except IDRepeatError as ir:
49
+ info = get_curl_info()
50
+ funName = info[0]
51
+ line = info[1]
52
+ interactCfg.writeErrorMsg(ir,funName,line)
53
+ self.ids = ids
54
+ Qubit.totalNum += 1
55
+ Qubit.idList.append(ids)
56
+ #set the initial value of the qubit according to the mode
57
+ if self.mode == 'simulator':
58
+ #has assignment error and gate error
59
+ error = interactCfg.readCfgER(ids)
60
+ #according to the error to product the amplitude
61
+ self.matrix[1].append(math.sqrt(error))
62
+ self.matrix[0].append(math.sqrt(1-error))
63
+ elif self.mode == 'theory':
64
+ #no assignment error or gate error
65
+ self.matrix[0].append(1)
66
+ self.matrix[1].append(0)
67
+ else:
68
+ try:
69
+ raise ExecuteModeError()
70
+ except ExecuteModeError as em:
71
+ info = get_curl_info()
72
+ funName = info[0]
73
+ line = info[1]
74
+ interactCfg.writeErrorMsg(em,funName,line)
75
+ self.setAmp()
76
+ #set the type of the qubit
77
+ if tag:
78
+ #it means that the qubit is an auxiliary Qubit
79
+ self.tag = "AX"
80
+ else:
81
+ #the qubit is an actual qubit
82
+ self.tag = "AC"
83
+ self.recordQubit()
84
+
85
+ #overwrite the function
86
+ def getAmp(self):
87
+ if self.entanglement == None:
88
+ return self.amplitude
89
+ else:
90
+ prob = self.decideProb([self])[0]
91
+ amp = []
92
+ for p in prob:
93
+ amp.append(math.sqrt(p))
94
+ return amp
95
+ def getMatrix(self):
96
+ if self.entanglement == None:
97
+ return self.matrix
98
+ else:
99
+ prob = self.decideProb([self])[0]
100
+ matrix = []
101
+ for p in prob:
102
+ matrix.append([math.sqrt(p)])
103
+ return matrix
104
+
105
+ #store the current qubit in the circuit instance
106
+ def recordQubit(self):
107
+ circuitInstance = checkEnvironment()
108
+ if circuitInstance == None:
109
+ #there is zero or more than one circuit instance
110
+ try:
111
+ raise EnvironmentError()
112
+ except EnvironmentError as ee:
113
+ info = get_curl_info()
114
+ funName = info[0]
115
+ line = info[1]
116
+ interactCfg.writeErrorMsg(ee,funName,line)
117
+
118
+ if circuitInstance.withOD:
119
+ if self in circuitInstance.qubitExecuteList:
120
+ del circuitInstance.qubitExecuteListOD[self]
121
+ circuitInstance.qubitNumOD -= 1
122
+ circuitInstance.qubitExecuteListOD[self] = []
123
+ circuitInstance.qubitNumOD += 1
124
+
125
+ if self.tag == "AC":
126
+ if self in circuitInstance.qubitExecuteList:
127
+ del circuitInstance.qubitExecuteList[self]
128
+ circuitInstance.qubitNum -= 1
129
+ circuitInstance.qubitExecuteList[self] = []
130
+ circuitInstance.qubitNum += 1
131
+
132
+ def decideProb(self, qubitList:list = None):
133
+ #the first dimen is probability, the second dimen is state
134
+ result = [[],[]]
135
+ qs = self.entanglement
136
+ #once the qubit is in entanglement, the amplitude maybe different
137
+ if qs == None:
138
+ #print(self.getAmp())
139
+ self.normalize()
140
+ #print(self.getAmp())
141
+ amplitude = self.getAmp()
142
+ result[0].append((amplitude[0] * amplitude[0].conjugate()).real)
143
+ result[0].append((amplitude[1] * amplitude[1].conjugate()).real)
144
+ result[1].append("0")
145
+ result[1].append("1")
146
+ else:
147
+ if qubitList == None or len(qubitList) == 0:
148
+ try:
149
+ raise ValueError()
150
+ except ValueError:
151
+ info = get_curl_info()
152
+ funName = info[0]
153
+ line = info[1]
154
+ interactCfg.writeErrorMsg("ValueError: The argument qubitList has no element, it must has at least one element",funName,line)
155
+ #print(qs.getAmp())
156
+ qs.normalize()
157
+ amplitude = qs.getAmp()
158
+ totalQubit = len(qs.qubitList)
159
+ iTH = []
160
+ #get the index of the argument qubitList
161
+ for qubit in qubitList:
162
+ index = qs.getIndex(qubit)
163
+ if index == -1:
164
+ try:
165
+ raise ValueError("Q" + str(qubit.ids) + " is not belong to the qubits")
166
+ except ValueError as ve:
167
+ info = get_curl_info()
168
+ funName = info[0]
169
+ line = info[1]
170
+ interactCfg.writeErrorMsg(ve,funName,line)
171
+ iTH.append(index)
172
+ length = len(iTH)
173
+ caseNum = 2 ** length
174
+ iTH.sort()
175
+ #get the corresponding state
176
+ stateList = []
177
+ probList = []
178
+ for i in range(0,caseNum):
179
+ state = bin(i).split('b')[1]
180
+ #add zero to beginning of the binary
181
+ for m in range(len(state) , len(iTH)):
182
+ state = '0' + state
183
+ stateList.append(state)
184
+ for state in stateList:
185
+ #len(state) = length
186
+ indexList = []
187
+
188
+ for j in range(0,length):
189
+ indexList.append(2 ** (totalQubit - iTH[j] - 1))
190
+ prob = 0
191
+ for k in range(0,2**totalQubit):
192
+ target = True
193
+ for index in range(0,len(indexList)):
194
+ if k & indexList[index] == int(state[index]) * indexList[index]:
195
+ continue
196
+ target = False
197
+ if target:
198
+ prob += (amplitude[k] * amplitude[k].conjugate()).real
199
+ probList.append(prob)
200
+ # print(stateList)
201
+ # print(amplitudeList)
202
+ result[0] = probList
203
+ result[1] = stateList
204
+ return result
205
+
206
+ def degenerate(self):
207
+ self.normalize()
208
+ ampList = self.getAmp()
209
+ probList = [(i*i.conjugate()).real for i in ampList]
210
+ if len(probList) != 2:
211
+ try:
212
+ raise ValueError
213
+ except ValueError:
214
+ info = get_curl_info()
215
+ funName = info[0]
216
+ line = info[1]
217
+ interactCfg.writeErrorMsg("ValueError: the sum of the probabilities of |0> and |1> is not 1!",funName,line)
218
+ randomNumber = random.uniform(0,1)
219
+ #the order of the state of the qubit must be 0 and 1
220
+ if randomNumber - probList[0] > 0:
221
+ value = 1
222
+ else:
223
+ value = 0
224
+ bit = Bit(value,self.ids)
225
+ qs = self.entanglement
226
+ if qs != None:
227
+ qs.deleteItem([self])
228
+ return bit
229
+
230
+ #delete the qubit
231
+ def delete(self):
232
+ self.entanglement = None
233
+ if self.ids in Qubit.idList:
234
+ Qubit.idList.remove(self.ids)
235
+
236
+ # def __del__(self):
237
+ # try:
238
+ # Qubit.idList.remove(self.ids)
239
+ # #the qubit is degenerated to Bit
240
+ # except KeyError as ke:
241
+ # interactCfg.writeErrorMsg("KeyError: " + str(ve) + " is not in Qubit instance!")
242
+
243
+ class Qubits(BaseQubit):
244
+ #the init has two qubits as input, compute the tensor product of the two elements
245
+ #########################################################################################################
246
+ #if there are some other ways to preparation entanglement, we can write another init with different input
247
+ #########################################################################################################
248
+ def __init__(self,q1:Qubit,q2:Qubit):
249
+ #the two qubits must be not in the entanglement
250
+ if q1.entanglement != None or q2.entanglement != None:
251
+ try:
252
+ raise ValueError("The qubits must not be in the entanglement!")
253
+ except ValueError as ve:
254
+ info = get_curl_info()
255
+ funName = info[0]
256
+ line = info[1]
257
+ interactCfg.writeErrorMsg(ve,funName,line)
258
+ #store the number of entanglement qubits
259
+ self.number = 2
260
+ self.matrix = []
261
+ self.setMatrix(q1 * q2)
262
+ self.amplitude = [0] * (len(q1.getAmp())*len(q2.getAmp()))
263
+ self.qubitList = [q1,q2]
264
+ #change the variable "entanglement" of qubit to this instance
265
+ q1.entanglement = self
266
+ q2.entanglement = self
267
+
268
+ #qs[index]
269
+ def __getitem__(self,index):
270
+ item = None
271
+ try:
272
+ item = self.qubitList[index]
273
+ except IndexError as ie:
274
+ info = get_curl_info()
275
+ funName = info[0]
276
+ line = info[1]
277
+ interactCfg.writeErrorMsg(ie,funName,line)
278
+ return item
279
+
280
+ #input two matrix, then compute the tensor product of the two matrix and return the new matrix
281
+ def mulMatrix(self,matrix,newMatrix):
282
+ result = []
283
+ for i in range(0,len(matrix)):
284
+ for j in range(0,len(newMatrix)):
285
+ item = []
286
+ item.append(matrix[i][0] * newMatrix[j][0])
287
+ result.append(item)
288
+ return result
289
+
290
+ #return the index of the qubitList, if not in, return -1
291
+ def getIndex(self,qubit:Qubit):
292
+ for i in range(0,len(self.qubitList)):
293
+ if qubit == self.qubitList[i]:
294
+ return i
295
+ return -1
296
+
297
+ #data can be Qubit or Qubits
298
+ def addNewItem(self,data):
299
+ if len(self.qubitList) == 0:
300
+ try:
301
+ raise ValueError()
302
+ except ValueError:
303
+ info = get_curl_info()
304
+ funName = info[0]
305
+ line = info[1]
306
+ interactCfg.writeErrorMsg("ValueError: There is no element in this Qubits!",funName,line)
307
+ types = type(data)
308
+ if types != Qubit and types != Qubits:
309
+ try:
310
+ raise TypeError()
311
+ except TypeError:
312
+ info = get_curl_info()
313
+ funName = info[0]
314
+ line = info[1]
315
+ interactCfg.writeErrorMsg("TypeError: the type should be Qubit or Qubits",funName,line)
316
+ #compute the matrix of the new qubits
317
+ newMatrix = self.mulMatrix(self.getMatrix(),data.getMatrix())
318
+ if types == Qubit:
319
+ self.qubitList.append(data)
320
+ self.number += 1
321
+ data.entanglement = self
322
+ else:
323
+ #the types of data is qubits
324
+ for item in data.qubitList:
325
+ self.qubitList.append(item)
326
+ self.number += 1
327
+ item.entanglement = self
328
+ self.setMatrix(newMatrix)
329
+ return 0
330
+
331
+ #delete the list of qubit from current instance
332
+ def deleteItem(self,ql:list):
333
+ for q in ql:
334
+ if self.getIndex(q) == -1:
335
+ #the qubit isn't in this instance
336
+ try:
337
+ raise ValueError()
338
+ except ValueError:
339
+ info = get_curl_info()
340
+ funName = info[0]
341
+ line = info[1]
342
+ interactCfg.writeErrorMsg("ValueError: qubit(q" + str(q.ids) + ") is not in this Qubits!",funName,line)
343
+ #qlIn store the qubit which are in this Qubits and haven't been measured
344
+ qlIn = []
345
+ for qubit in self.qubitList:
346
+ if qubit not in ql:
347
+ qlIn.append(qubit)
348
+ #change the state of the current Qubits
349
+ newMatrix = []
350
+ if len(qlIn) == 0:
351
+ pass
352
+ else:
353
+ result = q.decideProb(qlIn)
354
+ state = result[1]
355
+ prob = result[0]
356
+ newMatrix = []
357
+ for i in range(0,2**(len(qlIn))):
358
+ newMatrix.append([0])
359
+ for s in range(0,len(state)):
360
+ l = len(state[s])
361
+ sums = 0
362
+ for index in range(0,l):
363
+ number = int(state[s][index]) * (2**(l-index-1))
364
+ sums += number
365
+ newMatrix[sums][0] = math.sqrt(prob[s])
366
+ #delete the measured qubit from qubits and convert the measured qubit to bit class
367
+ for q in ql:
368
+ q.delete()
369
+ for i in range(0,len(ql)):
370
+ self.number -= 1
371
+ self.qubitList.remove(ql[i])
372
+ self.setMatrix(newMatrix)
373
+
374
+
-QuQ--master/config/errorRate.cfg ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"single":{"0":"0.00179","1":"0.00347","2":"0.00323","3":"0.00214","4":"0.00231","5":"0.00183","6":"0.00219","7":"0.00246","8":"0.00094","9":"0.00127","10":"0.00186","11":"0.00175","12":"0.00163","13":"0.00225","14":"0.00213","15":"0.0037"}}
2
+ {"multi":"0.03945"}
-QuQ--master/doc/UserManual/userManual.pdf ADDED
@@ -0,0 +1 @@
 
 
1
+
-QuQ--master/main/main.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append('../userCode/')
3
+ sys.path.append('../tools/')
4
+ from interactCfg import readCfgEA
5
+ import warnings
6
+ #from Grover import grover
7
+
8
+ if __name__ == "__main__":
9
+ #ignore the warning message
10
+ warnings.filterwarnings("ignore")
11
+ print('-' * 80)
12
+ print('')
13
+ print(' '*30 + "Welcome to QuanSim!" + " "*20)
14
+ print('')
15
+ print('-' * 80)
16
+ # import_string = "from Grover import grover"
17
+ # exec(import_string)
18
+ # grover()
19
+ funName = ""
20
+ funFile = ""
21
+ functionList = readCfgEA()
22
+ way = -1
23
+ #there are two ways to execute the code
24
+ #1.give the function name as a parameter, the format of the parameter is xx()
25
+ #2.input the number of the function you want to run
26
+ if len(sys.argv) == 2:
27
+ way = 1
28
+ #the first way
29
+ funName = sys.argv[1]
30
+ for function in functionList:
31
+ if funName == function[1]:
32
+ funFile = function[0]
33
+ if funFile == "":
34
+ print("Invalid parameter! The format of the function name must be xx()!")
35
+ way = 2
36
+ elif len(sys.argv) == 1:
37
+ #the second way
38
+ way = 2
39
+ else:
40
+ print("Invalid parameter! There can only be one parameter, and the format of it is 'xx()'!")
41
+ way = 2
42
+ if way == 2:
43
+ #the second way
44
+ print(' '*26 + 'The following code is vaild:' + ' '*20)
45
+
46
+ for i in range(1,len(functionList)+1):
47
+ print(str(i) + ':' + functionList[i-1][1])
48
+ ids = input("Please enter the number of the code you want to execute:")
49
+ try:
50
+ funName = functionList[int(ids)-1][1]
51
+ funFile = functionList[int(ids)-1][0]
52
+ except ValueError:
53
+ print("ValueError: The input is not a number!")
54
+ sys.exit(0)
55
+ except KeyError:
56
+ print("KeyError: The input number is invalid! ")
57
+ sys.exit(0)
58
+ except IndexError:
59
+ print("IndexError: The input number is out of range!")
60
+ sys.exit(0)
61
+ print("The code you want to execute is :" + funFile + "." + funName)
62
+ import_string = "from " + funFile + " import " + funName.split("(")[0]
63
+ try:
64
+ exec(import_string)
65
+ exec(funName)
66
+ except ImportError as ie:
67
+ print("ImportError: " + str(ie))
68
+ sys.exit(0)
69
+
70
+
71
+
72
+
-QuQ--master/results/EXP2018-03-14-15.23.40/Logical-Level/QASM.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Rx(0.25*pi) q[4];
2
+ Rx(0.25*pi) q[4];
3
+ Rx(0.25*pi) q[4];
4
+ Rx(0.25*pi) q[4];
5
+ M q[4] -> c[4];
-QuQ--master/results/EXP2018-03-14-15.23.40/Physical-Level/QASM.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Rz(0.5*pi) q[4];
2
+ Ry(-0.25*pi) q[4];
3
+ Rz(-0.5*pi) q[4];
4
+ Rz(0.5*pi) q[4];
5
+ Ry(-0.25*pi) q[4];
6
+ Rz(-0.5*pi) q[4];
7
+ Rz(0.5*pi) q[4];
8
+ Ry(-0.25*pi) q[4];
9
+ Rz(-0.5*pi) q[4];
10
+ Rz(0.5*pi) q[4];
11
+ Ry(-0.25*pi) q[4];
12
+ Rz(-0.5*pi) q[4];
13
+ M q[4] -> c[4];
-QuQ--master/results/EXP2018-03-14-15.23.40/originalData.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ state,times
2
+ |1>,1024
-QuQ--master/results/EXP2018-03-14-15.23.45/Logical-Level/QASM.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ H q[1];
2
+ H q[2];
3
+ X q[3];
4
+ H q[3];
5
+ Toffoli q[1],q[2],q[3];
6
+ H q[1];
7
+ H q[2];
8
+ H q[3];
9
+ X q[1];
10
+ X q[2];
11
+ H q[2];
12
+ CNOT q[1],q[2];
13
+ X q[1];
14
+ H q[2];
15
+ H q[1];
16
+ X q[2];
17
+ M q[1] -> c[1];
18
+ H q[2];
19
+ M q[2] -> c[2];
-QuQ--master/results/EXP2018-03-14-15.23.45/originalData.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ state,times
2
+ |11>,1024
-QuQ--master/tools/export.py ADDED
@@ -0,0 +1 @@
 
 
1
+
-QuQ--master/userCode/Grover.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ def grover():
4
+ totalElement = 4
5
+ #the number of the qubits in theory
6
+ n = 0
7
+ amount = 2 ** n
8
+ while amount < totalElement:
9
+ amount *= 2
10
+ n += 1
11
+ #the number of qubits actually used
12
+ N = 2*n - 1
13
+ #the target element
14
+ targetE = "11"
15
+ #check the length of the target element and the totalElement
16
+ if checkE(totalElement,targetE):
17
+ c = Circuit()
18
+ qList = []
19
+ for i in range(0,N):
20
+ q = Qubit()
21
+ qList.append(q)
22
+
23
+ X(qList[N-1])
24
+ for i in range(0,N):
25
+ H(qList[i])
26
+
27
+ #act the G operator for "times" times
28
+ times = executeTimes(totalElement)
29
+ for i in range(0,times):
30
+ G(qList,targetE)
31
+
32
+ #measure the qubits
33
+ for i in range(0,N-1):
34
+ qList[i] = M(qList[i])
35
+
36
+ #execute the circuit for 1024 times
37
+ c.execute(1024)
38
+ else:
39
+ writeErrorMsg("The length of the target element isn't correspond with the number of the total elements!")
40
+
41
+ #the parameter is the size of the database.
42
+ #and the target is supposed to one element
43
+ def executeTimes(n):
44
+ theta = math.asin(math.sqrt(1 / n)) / math.pi * 180
45
+ times = (90 - theta) / (2 * theta)
46
+ if times > int(times) + 0.5:
47
+ return int(times) + 1
48
+ else:
49
+ return int(times)
50
+
51
+ def checkE(toE:int,taE:str):
52
+ if toE <= (2 ** len(taE)):
53
+ return True
54
+ else:
55
+ return False
56
+
57
+ def G(qList:list,taE:str):
58
+ qn = len(qList)
59
+ #there are four phase in this G operator
60
+ #PH1: apply the oracle operator
61
+ vl = []
62
+ for k in range(0,len(taE)):
63
+ vl.append(int(taE[k]))
64
+ tmp1 = []
65
+ for j in range(0,qn-1):
66
+ tmp1.append(qList[j])
67
+ with DMif(tmp1,vl) as dmo1:
68
+ dmo1.X(qList[qn-1])
69
+
70
+ #PH2: act H gates on the qubits except the last element
71
+ for i in range(0,qn-1):
72
+ H(qList[i])
73
+
74
+ #PH3: act the phase operator on the qubits except the last element
75
+ for i in range(0,qn-1):
76
+ X(qList[i])
77
+ H(qList[qn-2])
78
+
79
+ tmp2 = []
80
+ for j in range(0,qn-2):
81
+ tmp2.append(qList[j])
82
+ with DMif(tmp2,1) as dmo2:
83
+ dmo2.X(qList[qn-2])
84
+
85
+ H(qList[qn-2])
86
+ for i in range(0,qn-1):
87
+ X(qList[i])
88
+
89
+ #PH4: act the H gates on all the qubits
90
+ for i in range(0,qn):
91
+ H(qList[i])
92
+
93
+
-QuQ--master/userCode/GroverN=8theory/originalData.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ state,times
2
+ |000>,126
3
+ |001>,63
4
+ |100>,129
5
+ |101>,68
6
+ |010>,131
7
+ |011>,63
8
+ |110>,123
9
+ |111>,321
-QuQ--master/userCode/UserSWAP.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from header import *
2
+
3
+ def SWAP():
4
+ c = Circuit(True)
5
+ q1 = Qubit()
6
+ q2 = Qubit()
7
+ X(q2)
8
+ ########SWAP gate########
9
+ CNOT(q1,q2)
10
+ CNOT(q2,q1)
11
+ CNOT(q1,q2)
12
+ #########################
13
+ M(q1)
14
+ M(q2)
15
+ c.execute(1024)
0617-audio_stream-master/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # 0617-audio_stream
0617-audio_stream-master/hyper.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from torch import nn
3
+ from mean_std import *
4
+ now = str(datetime.now())
5
+
6
+ epochs = 25
7
+ batch_size = 20
8
+ lr = 1e-3
9
+ decay = 5
10
+ save_hop = 2
11
+ obj_func = nn.BCEWithLogitsLoss()
12
+ fixed = 0
13
+ f_num = 7
14
+ specs_stack = 7
15
+ '''
16
+ MEAN = [ 110.63666788 / 255.0, 103.16065604 / 255.0, 96.29023126 / 255.0 ]
17
+ STD = [ 38.7568578 / 255.0, 37.88248729 / 255.0, 40.02898126 / 255.0 ]
18
+ '''
19
+ MEAN = train_specs_mean
20
+ STD = train_specs_std
21
+
22
+ train_data_path = './Data/OP_Train_DATA/frames/'
23
+ test_data_path = './Data/OP_Test_DATA/specs/'
24
+ test_data_path1 = './Data/DAVSOD_Test_DATA/frames_and_GT_part/easy/'
25
+ # checkpoint_load = './pre-trained/model.pth.tar'
26
+ checkpoint_load = './pre-trained/model_cpd_400615_Adam_0.0001_20_BCEWithLogitsLoss_8.pth'
27
+ # checkpoint_load = './pre-trained/model_cpd_500608_Adam_1.0000000000000002e-07_20_BCEWithLogitsLoss_40.pth'
28
+ checkpoint_name = 'cpd_' + str(epochs) + now[5:7] + now[8:10]
29
+ checkpoint_save = './checkpoint/'
0617-audio_stream-master/mean_std.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ train_frames_mean = [0.133460, 0.121699, 0.104900]
2
+ train_frames_std = [0.198126, 0.179522, 0.164552]
3
+
4
+ train_specs_mean = [0.252584, 0.710676, 0.641858]
5
+ train_specs_std = [0.260608, 0.099738, 0.244512]
6
+
7
+ test_frames_mean = [0.201312, 0.201226, 0.195387]
8
+ test_frames_std = [0.222184, 0.227670, 0.225742]
9
+
10
+ test_specs_mean = [0.279390, 0.712614, 0.621488]
11
+ test_specs_std = [0.278205, 0.101402, 0.256067]
0617-audio_stream-master/model/ResNe3D.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torch.autograd import Variable
6
+ import math
7
+ from functools import partial
8
+
9
+ __all__ = [
10
+ 'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
11
+ 'resnet152', 'resnet200'
12
+ ]
13
+
14
+
15
+ def conv3x3x3(in_planes, out_planes, stride=1):
16
+ # 3x3x3 convolution with padding
17
+ return nn.Conv3d(
18
+ in_planes,
19
+ out_planes,
20
+ kernel_size=3,
21
+ stride=stride,
22
+ padding=1,
23
+ bias=False)
24
+
25
+
26
+ def downsample_basic_block(x, planes, stride):
27
+ out = F.avg_pool3d(x, kernel_size=1, stride=stride)
28
+ zero_pads = torch.Tensor(
29
+ out.size(0), planes - out.size(1), out.size(2), out.size(3),
30
+ out.size(4)).zero_()
31
+ if isinstance(out.data, torch.cuda.FloatTensor):
32
+ zero_pads = zero_pads.cuda()
33
+
34
+ out = Variable(torch.cat([out.data, zero_pads], dim=1))
35
+
36
+ return out
37
+
38
+
39
+ class BasicBlock(nn.Module):
40
+ expansion = 1
41
+
42
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
43
+ super(BasicBlock, self).__init__()
44
+ self.conv1 = conv3x3x3(inplanes, planes, stride)
45
+ self.bn1 = nn.BatchNorm3d(planes)
46
+ self.relu = nn.ReLU(inplace=True)
47
+ self.conv2 = conv3x3x3(planes, planes)
48
+ self.bn2 = nn.BatchNorm3d(planes)
49
+ self.downsample = downsample
50
+ self.stride = stride
51
+
52
+ def forward(self, x):
53
+ residual = x
54
+
55
+ out = self.conv1(x)
56
+ out = self.bn1(out)
57
+ out = self.relu(out)
58
+
59
+ out = self.conv2(out)
60
+ out = self.bn2(out)
61
+
62
+ if self.downsample is not None:
63
+ residual = self.downsample(x)
64
+
65
+ out += residual
66
+ out = self.relu(out)
67
+
68
+ return out
69
+
70
+
71
+ class Bottleneck(nn.Module):
72
+ expansion = 4
73
+
74
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
75
+ super(Bottleneck, self).__init__()
76
+ self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
77
+ self.bn1 = nn.BatchNorm3d(planes)
78
+ self.conv2 = nn.Conv3d(
79
+ planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
80
+ self.bn2 = nn.BatchNorm3d(planes)
81
+ self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=False)
82
+ self.bn3 = nn.BatchNorm3d(planes * 4)
83
+ self.relu = nn.ReLU(inplace=True)
84
+ self.downsample = downsample
85
+ self.stride = stride
86
+
87
+ def forward(self, x):
88
+ residual = x
89
+
90
+ out = self.conv1(x)
91
+ out = self.bn1(out)
92
+ out = self.relu(out)
93
+
94
+ out = self.conv2(out)
95
+ out = self.bn2(out)
96
+ out = self.relu(out)
97
+
98
+ out = self.conv3(out)
99
+ out = self.bn3(out)
100
+
101
+ if self.downsample is not None:
102
+ residual = self.downsample(x)
103
+
104
+ out += residual
105
+ out = self.relu(out)
106
+
107
+ return out
108
+
109
+
110
+ class ResNet(nn.Module):
111
+
112
+ def __init__(self,
113
+ block,
114
+ layers,
115
+ sample_size,
116
+ sample_duration,
117
+ shortcut_type='B',
118
+ num_classes=400,
119
+ last_fc = True,
120
+ last_pool = True):
121
+ self.inplanes = 64
122
+ super(ResNet, self).__init__()
123
+ self.conv1 = nn.Conv3d(
124
+ 3,
125
+ 64,
126
+ kernel_size=7,
127
+ stride=(1, 2, 2),
128
+ padding=(3, 3, 3),
129
+ bias=False)
130
+ self.bn1 = nn.BatchNorm3d(64)
131
+ self.relu = nn.ReLU(inplace=True)
132
+ self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1)
133
+ self.layer1 = self._make_layer(
134
+ block, 64, layers[0], shortcut_type)
135
+ self.layer2 = self._make_layer(
136
+ block, 128, layers[1], shortcut_type, stride=2)
137
+ self.layer3 = self._make_layer(
138
+ block, 256, layers[2], shortcut_type, stride=2)
139
+ self.layer4 = self._make_layer(
140
+ block, 512, layers[3], shortcut_type, stride=2)
141
+ last_duration = int(math.ceil(sample_duration / 16))
142
+ last_size = int(math.ceil(sample_size / 32))
143
+ self.avgpool = nn.AvgPool3d(
144
+ (last_duration, last_size, last_size), stride=1)
145
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
146
+
147
+ for m in self.modules():
148
+ if isinstance(m, nn.Conv3d):
149
+ m.weight = nn.init.kaiming_normal(m.weight, mode='fan_out')
150
+ elif isinstance(m, nn.BatchNorm3d):
151
+ m.weight.data.fill_(1)
152
+ m.bias.data.zero_()
153
+
154
+ def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
155
+ downsample = None
156
+ if stride != 1 or self.inplanes != planes * block.expansion:
157
+ if shortcut_type == 'A':
158
+ downsample = partial(
159
+ downsample_basic_block,
160
+ planes=planes * block.expansion,
161
+ stride=stride)
162
+ else:
163
+ downsample = nn.Sequential(
164
+ nn.Conv3d(
165
+ self.inplanes,
166
+ planes * block.expansion,
167
+ kernel_size=1,
168
+ stride=stride,
169
+ bias=False), nn.BatchNorm3d(planes * block.expansion))
170
+
171
+ layers = []
172
+ layers.append(block(self.inplanes, planes, stride, downsample))
173
+ self.inplanes = planes * block.expansion
174
+ for i in range(1, blocks):
175
+ layers.append(block(self.inplanes, planes))
176
+
177
+ return nn.Sequential(*layers)
178
+
179
+ def forward(self, x):
180
+ x = self.conv1(x)
181
+ x = self.bn1(x)
182
+ x = self.relu(x)
183
+ x = self.maxpool(x)
184
+
185
+ x = self.layer1(x)
186
+
187
+ x = self.layer2(x)
188
+ x1 = x
189
+ x1 = x1.reshape(x1.size(0), x1.size(1)*x1.size(2), x1.size(3), x1.size(4))
190
+
191
+ x = self.layer3(x)
192
+ x2 = x
193
+ x2 = x2.reshape(x2.size(0), x2.size(1) * x2.size(2), x2.size(3), x2.size(4))
194
+
195
+ x = self.layer4(x)
196
+ x3 = x
197
+ x3 = x3.reshape(x3.size(0), x3.size(1) * x3.size(2), x3.size(3), x3.size(4))
198
+ # print(x.shape, x3.shape)
199
+
200
+ return x1, x2, x3
201
+
202
+
203
+ def get_fine_tuning_parameters(model, ft_begin_index):
204
+ if ft_begin_index == 0:
205
+ return model.parameters()
206
+
207
+ ft_module_names = []
208
+ for i in range(ft_begin_index, 5):
209
+ ft_module_names.append('layer{}'.format(i))
210
+ ft_module_names.append('fc')
211
+
212
+ parameters = []
213
+ for k, v in model.named_parameters():
214
+ for ft_module in ft_module_names:
215
+ if ft_module in k:
216
+ parameters.append({'params': v})
217
+ break
218
+ else:
219
+ parameters.append({'params': v, 'lr': 0.0})
220
+
221
+ return parameters
222
+
223
+
224
+ def resnet10(**kwargs):
225
+ """Constructs a ResNet-18 model.
226
+ """
227
+ model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)
228
+ return model
229
+
230
+
231
+ def resnet18(**kwargs):
232
+ """Constructs a ResNet-18 model.
233
+ """
234
+ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
235
+ return model
236
+
237
+
238
+ def resnet34(**kwargs):
239
+ """Constructs a ResNet-34 model.
240
+ """
241
+ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
242
+ return model
243
+
244
+
245
+ def resnet50(**kwargs):
246
+ """Constructs a ResNet-50 model.
247
+ """
248
+ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
249
+ return model
250
+
251
+
252
+ def resnet101(**kwargs):
253
+ """Constructs a ResNet-101 model.
254
+ """
255
+ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
256
+ return model
257
+
258
+
259
+ def resnet152(**kwargs):
260
+ """Constructs a ResNet-101 model.
261
+ """
262
+ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
263
+ return model
264
+
265
+
266
+ def resnet200(**kwargs):
267
+ """Constructs a ResNet-101 model.
268
+ """
269
+ model = ResNet(Bottleneck, [3, 24, 36, 3], **kwargs)
270
+ return model
0617-audio_stream-master/model/ResNet.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import math
3
+
4
+
5
+ def conv3x3(in_planes, out_planes, stride=1):
6
+ """3x3 convolution with padding"""
7
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
8
+ padding=1, bias=False)
9
+
10
+
11
+ class BasicBlock(nn.Module):
12
+ expansion = 1
13
+
14
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
15
+ super(BasicBlock, self).__init__()
16
+ self.conv1 = conv3x3(inplanes, planes, stride)
17
+ self.bn1 = nn.BatchNorm2d(planes)
18
+ self.relu = nn.ReLU(inplace=True)
19
+ self.conv2 = conv3x3(planes, planes)
20
+ self.bn2 = nn.BatchNorm2d(planes)
21
+ self.downsample = downsample
22
+ self.stride = stride
23
+
24
+ def forward(self, x):
25
+ residual = x
26
+
27
+ out = self.conv1(x)
28
+ out = self.bn1(out)
29
+ out = self.relu(out)
30
+
31
+ out = self.conv2(out)
32
+ out = self.bn2(out)
33
+
34
+ if self.downsample is not None:
35
+ residual = self.downsample(x)
36
+
37
+ out += residual
38
+ out = self.relu(out)
39
+
40
+ return out
41
+
42
+
43
+ class Bottleneck(nn.Module):
44
+ expansion = 4
45
+
46
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
47
+ super(Bottleneck, self).__init__()
48
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
49
+ self.bn1 = nn.BatchNorm2d(planes)
50
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
51
+ padding=1, bias=False)
52
+ self.bn2 = nn.BatchNorm2d(planes)
53
+ self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
54
+ self.bn3 = nn.BatchNorm2d(planes * 4)
55
+ self.relu = nn.ReLU(inplace=True)
56
+ self.downsample = downsample
57
+ self.stride = stride
58
+
59
+ def forward(self, x):
60
+ residual = x
61
+
62
+ out = self.conv1(x)
63
+ out = self.bn1(out)
64
+ out = self.relu(out)
65
+
66
+ out = self.conv2(out)
67
+ out = self.bn2(out)
68
+ out = self.relu(out)
69
+
70
+ out = self.conv3(out)
71
+ out = self.bn3(out)
72
+
73
+ if self.downsample is not None:
74
+ residual = self.downsample(x)
75
+
76
+ out += residual
77
+ out = self.relu(out)
78
+
79
+ return out
80
+
81
+
82
+ class B2_ResNet(nn.Module):
83
+ # ResNet50 with two branches
84
+ def __init__(self):
85
+ # self.inplanes = 128
86
+ self.inplanes = 64
87
+ super(B2_ResNet, self).__init__()
88
+
89
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
90
+ bias=False)
91
+ self.bn1 = nn.BatchNorm2d(64)
92
+ self.relu = nn.ReLU(inplace=True)
93
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
94
+ self.layer1 = self._make_layer(Bottleneck, 64, 3)
95
+ self.layer2 = self._make_layer(Bottleneck, 128, 4, stride=2)
96
+ self.layer3_1 = self._make_layer(Bottleneck, 256, 6, stride=2)
97
+ self.layer4_1 = self._make_layer(Bottleneck, 512, 3, stride=2)
98
+
99
+ self.inplanes = 512
100
+ self.layer3_2 = self._make_layer(Bottleneck, 256, 6, stride=2)
101
+ self.layer4_2 = self._make_layer(Bottleneck, 512, 3, stride=2)
102
+
103
+ for m in self.modules():
104
+ if isinstance(m, nn.Conv2d):
105
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
106
+ m.weight.data.normal_(0, math.sqrt(2. / n))
107
+ elif isinstance(m, nn.BatchNorm2d):
108
+ m.weight.data.fill_(1)
109
+ m.bias.data.zero_()
110
+
111
+ def _make_layer(self, block, planes, blocks, stride=1):
112
+ downsample = None
113
+ if stride != 1 or self.inplanes != planes * block.expansion:
114
+ downsample = nn.Sequential(
115
+ nn.Conv2d(self.inplanes, planes * block.expansion,
116
+ kernel_size=1, stride=stride, bias=False),
117
+ nn.BatchNorm2d(planes * block.expansion),
118
+ )
119
+
120
+ layers = []
121
+ layers.append(block(self.inplanes, planes, stride, downsample))
122
+ self.inplanes = planes * block.expansion
123
+ for i in range(1, blocks):
124
+ layers.append(block(self.inplanes, planes))
125
+
126
+ return nn.Sequential(*layers)
127
+
128
+ def forward(self, x):
129
+ x = self.conv1(x)
130
+ x = self.bn1(x)
131
+ x = self.relu(x)
132
+ x = self.maxpool(x)
133
+
134
+ x = self.layer1(x)
135
+ x = self.layer2(x)
136
+ x1 = self.layer3_1(x)
137
+ x1 = self.layer4_1(x1)
138
+
139
+ x2 = self.layer3_2(x)
140
+ x2 = self.layer4_2(x2)
141
+
142
+ return x1, x2
0617-audio_stream-master/model/ResNet_18.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class ResidualBlock(nn.Module):
7
+ def __init__(self, inchannel, outchannel, stride=1):
8
+ super(ResidualBlock, self).__init__()
9
+ self.left = nn.Sequential(
10
+ nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
11
+ nn.BatchNorm2d(outchannel),
12
+ nn.ReLU(inplace=True),
13
+ nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
14
+ nn.BatchNorm2d(outchannel)
15
+ )
16
+ self.shortcut = nn.Sequential()
17
+ if stride != 1 or inchannel != outchannel:
18
+ self.shortcut = nn.Sequential(
19
+ nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
20
+ nn.BatchNorm2d(outchannel)
21
+ )
22
+
23
+ def forward(self, x):
24
+ out = self.left(x)
25
+ out += self.shortcut(x)
26
+ out = F.relu(out)
27
+ return out
28
+
29
+
30
+ class ResNet(nn.Module):
31
+ def __init__(self, ResidualBlock, num_classes=10):
32
+ super(ResNet, self).__init__()
33
+ self.inchannel = 64
34
+ self.conv1 = nn.Sequential(
35
+ nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
36
+ nn.BatchNorm2d(64),
37
+ nn.ReLU(),
38
+ )
39
+ self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=1)
40
+ self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
41
+ self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
42
+ self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
43
+ self.fc = nn.Linear(512, num_classes)
44
+
45
+ def make_layer(self, block, channels, num_blocks, stride):
46
+ strides = [stride] + [1] * (num_blocks - 1) #strides=[1,1]
47
+ layers = []
48
+ for stride in strides:
49
+ layers.append(block(self.inchannel, channels, stride))
50
+ self.inchannel = channels
51
+ return nn.Sequential(*layers)
52
+
53
+ def forward(self, x):
54
+ # torch.Size([bs, 3, 256, 320])
55
+
56
+ # torch.Size([8, 64, 256, 320])
57
+ out = self.conv1(x)
58
+
59
+ # torch.Size([8, 64, 256, 320])
60
+ out = self.layer1(out)
61
+
62
+ # torch.Size([8, 128, 128, 160])
63
+ out = self.layer2(out)
64
+
65
+ # torch.Size([8, 256, 64, 80])
66
+ out = self.layer3(out)
67
+
68
+ # torch.Size([8, 512, 32, 40])
69
+ out = self.layer4(out)
70
+
71
+ # out = F.avg_pool2d(out, 4)
72
+ # out = out.view(out.size(0), -1)
73
+ # out = self.fc(out)
74
+
75
+ return out
76
+
77
+
78
+ def ResNet2_18():
79
+ return ResNet(ResidualBlock)
0617-audio_stream-master/model/v_a_con.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class Video_Audio_Con(nn.Module):
6
+ def __init__(self):
7
+ super(Video_Audio_Con, self).__init__()
8
+
9
+ # f_num = 10 384
10
+ self.conv_3 = nn.Conv2d(128, 256, 1, padding=0)
11
+ self.conv_4 = nn.Conv2d(256, 512, 1, padding=0)
12
+ self.conv_5 = nn.Conv2d(512, 512, 1, padding=0)
13
+
14
+ def forward(self, x, y):
15
+ mix = torch.cat((x, y), 1)
16
+
17
+ return mix
18
+
19
+
20
+ class Video_Audio_Con_10(nn.Module):
21
+ def __init__(self):
22
+ super(Video_Audio_Con_10, self).__init__()
23
+
24
+ self.upsample_a1 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=False)
25
+ self.conv_last = nn.Conv2d(512, 1, 1, padding=0)
26
+
27
+ def forward(self, x, y):
28
+ mix = torch.cat((x, y), 1)
29
+
30
+ return mix
31
+
32
+
33
+ class Video_Audio_Con_audio(nn.Module):
34
+ def __init__(self):
35
+ super(Video_Audio_Con_audio, self).__init__()
36
+
37
+ self.upsample_a1 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=False)
38
+ self.conv_last = nn.Conv2d(512, 1, 1, padding=0)
39
+
40
+ def forward(self, x, y):
41
+ mix = torch.cat((x, y), 1)
42
+
43
+ return mix
0621_test-master/.gitignore ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ustom
2
+ .idea/
3
+
4
+ # Created by https://www.gitignore.io/api/vim,macos,linux,django,python,pycharm
5
+
6
+ ### Django ###
7
+ *.log
8
+ *.pot
9
+ *.pyc
10
+ __pycache__/
11
+ local_settings.py
12
+ db.sqlite3
13
+ media
14
+
15
+ ### Linux ###
16
+ *~
17
+
18
+ # temporary files which can be created if a process still has a handle open of a deleted file
19
+ .fuse_hidden*
20
+
21
+ # KDE directory preferences
22
+ .directory
23
+
24
+ # Linux trash folder which might appear on any partition or disk
25
+ .Trash-*
26
+
27
+ # .nfs files are created when an open file is removed but is still being accessed
28
+ .nfs*
29
+
30
+ ### macOS ###
31
+ *.DS_Store
32
+ .AppleDouble
33
+ .LSOverride
34
+
35
+ # Icon must end with two \r
36
+ Icon
37
+
38
+ # Thumbnails
39
+ ._*
40
+
41
+ # Files that might appear in the root of a volume
42
+ .DocumentRevisions-V100
43
+ .fseventsd
44
+ .Spotlight-V100
45
+ .TemporaryItems
46
+ .Trashes
47
+ .VolumeIcon.icns
48
+ .com.apple.timemachine.donotpresent
49
+
50
+ # Directories potentially created on remote AFP share
51
+ .AppleDB
52
+ .AppleDesktop
53
+ Network Trash Folder
54
+ Temporary Items
55
+ .apdisk
56
+
57
+ ### PyCharm ###
58
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
59
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
60
+
61
+ # User-specific stuff:
62
+ .idea/**/workspace.xml
63
+ .idea/**/tasks.xml
64
+ .idea/dictionaries
65
+
66
+ # Sensitive or high-churn files:
67
+ .idea/**/dataSources/
68
+ .idea/**/dataSources.ids
69
+ .idea/**/dataSources.xml
70
+ .idea/**/dataSources.local.xml
71
+ .idea/**/sqlDataSources.xml
72
+ .idea/**/dynamic.xml
73
+ .idea/**/uiDesigner.xml
74
+
75
+ # Gradle:
76
+ .idea/**/gradle.xml
77
+ .idea/**/libraries
78
+
79
+ # CMake
80
+ cmake-build-debug/
81
+
82
+ # Mongo Explorer plugin:
83
+ .idea/**/mongoSettings.xml
84
+
85
+ ## File-based project format:
86
+ *.iws
87
+
88
+ ## Plugin-specific files:
89
+
90
+ # IntelliJ
91
+ /out/
92
+
93
+ # mpeltonen/sbt-idea plugin
94
+ .idea_modules/
95
+
96
+ # JIRA plugin
97
+ atlassian-ide-plugin.xml
98
+
99
+ # Cursive Clojure plugin
100
+ .idea/replstate.xml
101
+
102
+ # Crashlytics plugin (for Android Studio and IntelliJ)
103
+ com_crashlytics_export_strings.xml
104
+ crashlytics.properties
105
+ crashlytics-build.properties
106
+ fabric.properties
107
+
108
+ ### PyCharm Patch ###
109
+ # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
110
+
111
+ # *.iml
112
+ # modules.xml
113
+ # .idea/misc.xml
114
+ # *.ipr
115
+
116
+ # Sonarlint plugin
117
+ .idea/sonarlint
118
+
119
+ ### Python ###
120
+ # Byte-compiled / optimized / DLL files
121
+ *.py[cod]
122
+ *$py.class
123
+
124
+ # C extensions
125
+ *.so
126
+
127
+ # Distribution / packaging
128
+ .Python
129
+ env/
130
+ build/
131
+ develop-eggs/
132
+ dist/
133
+ downloads/
134
+ eggs/
135
+ .eggs/
136
+ lib/
137
+ lib64/
138
+ parts/
139
+ sdist/
140
+ var/
141
+ wheels/
142
+ *.egg-info/
143
+ .installed.cfg
144
+ *.egg
145
+
146
+ # PyInstaller
147
+ # Usually these files are written by a python script from a template
148
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
149
+ *.manifest
150
+ *.spec
151
+
152
+ # Installer logs
153
+ pip-log.txt
154
+ pip-delete-this-directory.txt
155
+
156
+ # Unit test / coverage reports
157
+ htmlcov/
158
+ .tox/
159
+ .coverage
160
+ .coverage.*
161
+ .cache
162
+ nosetests.xml
163
+ coverage.xml
164
+ *,cover
165
+ .hypothesis/
166
+
167
+ # Translations
168
+ *.mo
169
+
170
+ # Django stuff:
171
+
172
+ # Flask stuff:
173
+ instance/
174
+ .webassets-cache
175
+
176
+ # Scrapy stuff:
177
+ .scrapy
178
+
179
+ # Sphinx documentation
180
+ docs/_build/
181
+
182
+ # PyBuilder
183
+ target/
184
+
185
+ # Jupyter Notebook
186
+ .ipynb_checkpoints
187
+
188
+ # pyenv
189
+ .python-version
190
+
191
+ # celery beat schedule file
192
+ celerybeat-schedule
193
+
194
+ # SageMath parsed files
195
+ *.sage.py
196
+
197
+ # dotenv
198
+ .env
199
+
200
+ # virtualenv
201
+ .venv
202
+ venv/
203
+ ENV/
204
+
205
+ # Spyder project settings
206
+ .spyderproject
207
+ .spyproject
208
+
209
+ # Rope project settings
210
+ .ropeproject
211
+
212
+ # mkdocs documentation
213
+ /site
214
+
215
+ ### Vim ###
216
+ # swap
217
+ [._]*.s[a-v][a-z]
218
+ [._]*.sw[a-p]
219
+ [._]s[a-v][a-z]
220
+ [._]sw[a-p]
221
+ # session
222
+ Session.vim
223
+ # temporary
224
+ .netrwhist
225
+ # auto-generated tag files
226
+ tags
227
+
228
+ # End of https://www.gitignore.io/api/vim,macos,linux,django,python,pycharm
229
+
0621_test-master/.pipreqs/requirements_pipreqs.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Django==5.1.7
0621_test-master/django_app/config/urls.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """test_project URL Configuration
2
+
3
+ The `urlpatterns` list routes URLs to views. For more information please see:
4
+ https://docs.djangoproject.com/en/1.11/topics/http/urls/
5
+ Examples:
6
+ Function views
7
+ 1. Add an import: from my_app import views
8
+ 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9
+ Class-based views
10
+ 1. Add an import: from other_app.views import Home
11
+ 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12
+ Including another URLconf
13
+ 1. Import the include() function: from django.conf.urls import url, include
14
+ 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
15
+ """
16
+ from django.conf.urls import url, include
17
+ from django.contrib import admin
18
+
19
+ urlpatterns = [
20
+ url(r'^admin/', admin.site.urls),
21
+ url(r'^post/', include('post.urls'))
22
+ ]
0621_test-master/django_app/manage.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import os
3
+ import sys
4
+
5
+ if __name__ == "__main__":
6
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
7
+ try:
8
+ from django.core.management import execute_from_command_line
9
+ except ImportError:
10
+ # The above import may fail for some other reason. Ensure that the
11
+ # issue is really that Django is missing to avoid masking other
12
+ # exceptions on Python 2.
13
+ try:
14
+ import django
15
+ except ImportError:
16
+ raise ImportError(
17
+ "Couldn't import Django. Are you sure it's installed and "
18
+ "available on your PYTHONPATH environment variable? Did you "
19
+ "forget to activate a virtual environment?"
20
+ )
21
+ raise
22
+ execute_from_command_line(sys.argv)
0621_test-master/django_app/post/urls.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.conf.urls import url
2
+
3
+ from . import views
4
+
5
+ app_name = 'post'
6
+ urlpatterns = [
7
+ url(r'^$', views.post_list, name='post_list'),
8
+ url(r'^(?P<post_pk>\d+)/delete$', views.post_delete, name='post_delete'),
9
+ url(r'^(?P<post_pk>\d+)/modify$', views.post_modify, name='post_modify')
10
+ ]
0621_test-master/django_app/post/views.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from django.http import HttpResponseRedirect
2
+ from django.shortcuts import render, redirect
3
+
4
+ from .forms import CommentForm
5
+ from .models import Post
6
+
7
+
8
+ def post_list(request):
9
+ posts = Post.objects.all()
10
+ context = {
11
+ 'posts': posts
12
+ }
13
+ return render(request, 'post/post_list.html', context)
14
+
15
+
16
+ def post_delete(request, post_pk):
17
+ if request.method == 'POST':
18
+ post = Post.objects.get(pk=post_pk)
19
+ post.delete()
20
+ return redirect('post:post_list')
21
+
22
+
23
+ def post_modify(request, post_pk):
24
+ if request.method == 'POST':
25
+ post = Post.objects.get(pk=post_pk)
26
+ form = CommentForm(data=request.POST)
27
+ if form.is_valid():
28
+ comment = form.cleaned_data['comment']
29
+ post.comment = comment
30
+ post.save()
31
+ return redirect('post:post_list')
32
+ else:
33
+ context = {
34
+ 'form': CommentForm()
35
+ }
36
+ return render(request, 'post/post_modify.html', context)
10-week-algorithm-excercise-master/OneQuestionPerDay/1021/remove_outermost_parentheses.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def removeOuterParentheses(self, S: str) -> str:
3
+ counter = 0
4
+ start = 0
5
+
6
+ strs = []
7
+ for i, c in enumerate(S):
8
+ if c == "(":
9
+ counter += 1
10
+ else:
11
+ counter -= 1
12
+
13
+ if counter == 0:
14
+ strs.append(S[start + 1:i])
15
+ start = i + 1
16
+ return "".join(strs)
10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ type TreeNode struct {
4
+ Val int
5
+ Left *TreeNode
6
+ Right *TreeNode
7
+ }
8
+
9
+ func maxDepth(root *TreeNode) int {
10
+ n := -1
11
+ var dfs func(node *TreeNode, level int)
12
+ dfs = func(node *TreeNode, level int) {
13
+ if node == nil {
14
+ if level >= n {
15
+ n = level + 1
16
+ }
17
+ return
18
+ }
19
+ dfs(node.Left, level+1)
20
+ dfs(node.Right, level+1)
21
+ }
22
+ dfs(root, n)
23
+ return n
24
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/104/maximum_depth_of_binary_tree3.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class TreeNode:
2
+ def __init__(self, x):
3
+ self.val = x
4
+ self.left = None
5
+ self.right = None
6
+
7
+
8
+ class Solution:
9
+ def maxDepth(self, root: TreeNode) -> int:
10
+ if root is None:
11
+ return 0
12
+ level = 0
13
+ queue = [root]
14
+
15
+ while queue:
16
+ n = len(queue)
17
+ level += 1
18
+
19
+ for i in range(n):
20
+ if queue[i].left is not None:
21
+ queue.append(queue[i].left)
22
+ if queue[i].right is not None:
23
+ queue.append(queue[i].right)
24
+
25
+ queue = queue[n:]
26
+ return level
10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits2.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Solution:
2
+ def addDigits(self, num: int) -> int:
3
+ if num == 0:
4
+ return 0
5
+ return (num - 1) % 9 + 1
6
+
7
+ def test(self):
8
+ for num, target in [
9
+ (0, 0),
10
+ (1, 1),
11
+ (9, 9),
12
+ (10, 1),
13
+ (11, 2),
14
+ (19, 1),
15
+ ]:
16
+ ans = self.addDigits(num)
17
+ assert ans == target, f"target: {target}, ans: {ans}"
18
+ print("well done")
19
+
20
+
21
+ if __name__ == "__main__":
22
+ Solution().test()
10-week-algorithm-excercise-master/OneQuestionPerDay/258/add_digits_test.go ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ tests := []struct {
7
+ num int
8
+ target int
9
+ }{
10
+ {3, 3},
11
+ {38, 2},
12
+ {19, 1},
13
+ {138, 3},
14
+ {888, 6},
15
+ }
16
+
17
+ for _, tt := range tests {
18
+ if ans := addDigits(tt.num); ans != tt.target {
19
+ t.Fatalf("ans: %d, target: %d\n", tt.num, tt.target)
20
+ }
21
+ }
22
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/300/longest_increasing_subsequence.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def lengthOfLIS(self, nums: List[int]) -> int:
6
+ if len(nums) == 0:
7
+ return 0
8
+ dp = [1] * len(nums)
9
+ for i, n in enumerate(nums):
10
+ for j in range(0, i):
11
+ if nums[j] < nums[i]:
12
+ dp[i] = max(dp[i], dp[j] + 1)
13
+ return max(dp)
10-week-algorithm-excercise-master/OneQuestionPerDay/66/plus_one.go ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func plusOne(digits []int) []int {
4
+ carry := true
5
+ for i := len(digits) - 1; i >= 0; i-- {
6
+ if digits[i] == 9 {
7
+ digits[i] = 0
8
+ } else {
9
+ digits[i]++
10
+ carry = false
11
+ break
12
+ }
13
+ }
14
+ if carry {
15
+ digits = append([]int{1}, digits...)
16
+ }
17
+ return digits
18
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/718/maximum_length_of_repeated_subarray.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def findLength(self, A: List[int], B: List[int]) -> int:
6
+ m, n = len(A), len(B)
7
+ if m == 0 or n == 0:
8
+ return 0
9
+
10
+ dp = [[0] * (n + 1) for _ in range(m + 1)]
11
+ res = 0
12
+ for i in range(m):
13
+ for j in range(n):
14
+ if A[i] == B[j]:
15
+ dp[i + 1][j + 1] = dp[i][j] + 1
16
+ else:
17
+ dp[i + 1][j + 1] = 0
18
+ return res
19
+
20
+ def test(self):
21
+ a = [1, 2, 3, 2, 1]
22
+ b = [3, 2, 1, 4, 7]
23
+ ans = self.findLength(a, b)
24
+ print(ans)
25
+
26
+
27
+ if __name__ == "__main__":
28
+ Solution().test()
10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number.go ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func getKthMagicNumber(k int) int {
4
+ dp := make([]int, k)
5
+ dp[0] = 1
6
+ three := 0
7
+ five := 0
8
+ seven := 0
9
+
10
+ for i := 1; i < k; i++ {
11
+ dp[i] = min3(3*dp[three], 5*dp[five], 7*dp[seven])
12
+ if 3*dp[three] == dp[i] {
13
+ three++
14
+ }
15
+ if 5*dp[five] == dp[i] {
16
+ five++
17
+ }
18
+ if 7*dp[seven] == dp[i] {
19
+ seven++
20
+ }
21
+ }
22
+ return dp[k-1]
23
+ }
24
+
25
+ func min3(x, y, z int) int {
26
+ return min(x, min(y, z))
27
+ }
28
+
29
+ func min(x, y int) int {
30
+ if x < y {
31
+ return x
32
+ }
33
+ return y
34
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/LCCI17/get_kth_magic_number2.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import heapq
2
+
3
+
4
+ class Solution:
5
+ def getKthMagicNumber(self, k: int) -> int:
6
+ h = [1]
7
+ heapq.heapify(h)
8
+ visited = {1: True}
9
+ i = 0
10
+ n = 1
11
+ while i < k:
12
+ i += 1
13
+ n = heapq.heappop(h)
14
+ for f in [3, 5, 7]:
15
+ m = f * n
16
+ if m not in visited:
17
+ heapq.heappush(h, m)
18
+ visited[m] = True
19
+ return n
10-week-algorithm-excercise-master/OneQuestionPerDay/LCOF5/replace_space.go ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "strings"
4
+
5
+ func replaceSpace(s string) string {
6
+ var sb strings.Builder
7
+ for i := 0;i< len(s);i++ {
8
+ if s[i] == ' ' {
9
+ sb.WriteString("%20")
10
+ } else {
11
+ sb.WriteByte(s[i])
12
+ }
13
+ }
14
+ return sb.String()
15
+ }
10-week-algorithm-excercise-master/OneQuestionPerDay/README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 每日一题
2
+
3
+
4
+ |Day|Number|Title|Solutions|
5
+ |---|---|---|------|
6
+ |1|70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 递推([Go](../Week_01/70/climbing_stairs.go),[Py](../Week_01/70/climbing_stairs.py))|
7
+ |2|66|[plus-one](https://leetcode-cn.com/problems/plus-one) | O(n)遍历([Go](66/plus_one.go),[Py](66/plus_one.py))|
8
+ |3|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 先排序后双指针夹逼([Go](../Week_01/1/two_sum.go)), 字典缓存差值的索引([Go](../Week_01/1/two_sum_2.go),[Py](../Week_01/1/two_sum.py))|
9
+ |4|24|[swap-nodes-in-pairs](https://leetcode-cn.com/problems/swap-nodes-in-pairs)| 迭代([Go](../Week_01/24/swap_nodes_in_pairs2.go),[Py](../Week_01/24/swap_nodes_in_pairs2.py)), 递归([Go](../Week_01/24/swap_nodes_in_pairs.go),[Py](../Week_01/24/swap_nodes_in_pairs.py))|
10
+ |5|21|[merge-two-sorted-lists](https://leetcode-cn.com/problems/merge-two-sorted-lists) | 迭代([Go](../Week_01/21/merge_two_sorted_lists.go), [Py](../Week_01/21/merge_two_sorted_lists.py)), 递归([Go](../Week_01/21/merge_two_sorted_lists2.go),[Py](../Week_01/21/merge_two_sorted_lists2.py))|
11
+ |6|299|[bulls-and-cows](https://leetcode-cn.com/problems/bulls-and-cows) | 数组记录可能的cows([Go](299/bulls_and_cows.go), [Py](299/bulls_and_cows.go))|
12
+ |7|641|[design-circular-deque](https://leetcode-cn.com/problems/design-circular-deque) | 双指针([Go](../Week_01/641/design_circular_deque.go)),双指针优化([Go](../Week_01/641/design_circular_deque2.go),[Py](../Week_01/641/design_circular_deque2.py))|
13
+ |8|350|[intersection-of-two-arrays-ii](https://leetcode-cn.com/problems/intersection-of-two-arrays-ii) | 哈希表计数([Go](350/intersection_of_two_arrays_ii.go),[Py](350/intersection_of_two_arrays_ii.py)))|
14
+ |9|LCOF59|[mac-sliding-window](https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/) | 单调递减队列([Go](LCOF59/max_sliding_window.go),[Py](LCOF59/max_sliding_window.go)))|
15
+ |10|1021|[remove-outermost-parentheses](https://leetcode-cn.com/problems/remove-outermost-parentheses) | 双指针记录有效括号的起止([Go](1021/remove_outermost_parentheses.go),[Py](1021/remove_outermost_parentheses.py)))|
16
+ |11|412|[fizz-buzz](https://leetcode-cn.com/problems/fizz-buzz) | 遍历([Go](412/fizz_buzz.go),[Py](412/fizz_buzz.py)))|
17
+ |12|258|[add-digits](https://leetcode-cn.com/problems/add-digits) | 迭代([Go](258/add_digits.go),[Py](258/add_digits.py))), 取余([Go](258/add_digits2.go),[Py](258/add_digits2.py)))|
18
+ |13|104|[maximum-depth-of-binary-tree](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree) | 递归([Go](104/maximum_depth_of_binary_tree2.go),[Py](104/maximum_depth_of_binary_tree2.py))), 队列([Go](104/maximum_depth_of_binary_tree3.go),[Py](104/maximum_depth_of_binary_tree3.go)))|
19
+ |14|283|[move-zeroes](https://leetcode-cn.com/problems/move-zeroes) | 统计0的个数([Go](../Week_01/283/move_zeros.go),[Py](../Week_01/283/move_zeros.py)), 快慢指针([Go](../Week_01/283/move_zeros.go))|
20
+ |15|94|[binary-tree-inorder-traversal](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) | 递归([Go](../Week_02/94/binary_tree_inorder_traversal.go),[Py](../Week_02/94/binary_tree_inorder_traversal.py)),栈([Go](../Week_02/94/binary_tree_inorder_traversal2.go),[Py](../Week_02/94/binary_tree_inorder_traversal2.py)), Morris遍历([Go](../Week_02/94/binary_tree_inorder_traversal3.go),[Py](../Week_02/94/binary_tree_inorder_traversal3.py))|
21
+ |16|LCOF5|[replace-space](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) | 新建一个buff([Go](LCOF5/replace_space.go),[Py](LCOF5/replace_space.go))|
22
+ |17|LCOF6|[reverse-print](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) | 遍历([Go](LCOF6/reverse_link_node.go),[Py](LCOF6/reverse_link_node.py))|
23
+ |18|236|[lowest-common-ancestor-of-a-binary-tree](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) | 递归([Go](../Week_03/236/lowest_common_ancestor_of_a-binary_tree.go),[Py](LCOF6/reverse_link_node.py))|
24
+ |19|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 字典存num-index键值对([Go](1/two_sum.go),[Py](1/two_sum.py))|
25
+ |20|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))|
26
+ |21|LCCI17|[get-kth-magic-number-lcci](https://leetcode-cn.com/problems/get-kth-magic-number-lcci) | 三指针([Go](LCCI17/get_kth_magic_number.go),[Py](LCCI17/get_kth_magic_number.py)), 小顶堆([Go](LCCI17/get_kth_magic_number2.go),[Py](LCCI17/get_kth_magic_number2.py))|
27
+ |22|46|[permutations](https://leetcode-cn.com/problems/permutations) | 递归+回溯([Go](../Week_03/46/permutations.go),[Py](../Week_03/46/permutations.py))|
28
+ |23|70|[climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) | 递推([Go](../Week_01/70/climbing_stairs.go),[Py](../Week_01/70/climbing_stairs.py))|
29
+ |24|122|[best-time-to-buy-and-sell-stock-ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) | 贪心([Go](../Week_04/122/best_time_to_buy_and_sell_stock_ii.go),[Py](../Week_04/122/best_time_to_buy_and_sell_stock_ii.py))|
30
+ |25|860|[lemonade-change](https://leetcode-cn.com/problems/lemonade-change) | 贪心([Go](../Week_04/860/lemonade_change.go),[Py](../Week_04/860/lemonade_change.py))|
31
+ |26|200|[numbers-of-islands](https://leetcode-cn.com/problems/numbers-of-islands) | 深度优先([Go](../Week_04/200/number_of_islands.go),[Py](../Week_04/200/number_of_islands.py))|
32
+ |27|367|[valid-perfect-square](https://leetcode-cn.com/problems/valid-perfect-square) | 二分查找([Go](../Week_04/367/valid_perfect_square.go),[Py](../Week_04/367/valid_perfect_square.go))|
33
+ |28|169|[majority-element](https://leetcode-cn.com/problems/majority-element) | 哈希表([Go](../Week_03/169/majority_element.go),[Py](../Week_03/169/majority_element.py)),计数投票([Go](../Week_03/169/majority_element2.go),[Py](../Week_03/169/majority_element2.py))|
34
+ |29|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))|
35
+ |30|1|[two-sum](https://leetcode-cn.com/problems/two-sum) | 先排序后双指针夹逼([Go](../Week_01/1/two_sum.go)), 字典缓存差值的索引([Go](../Week_01/1/two_sum_2.go),[Py](../Week_01/1/two_sum.py))|
36
+ |31|874|[walking-robot-simulation](https://leetcode-cn.com/problems/walking-robot-simulation) | 迭代([Go](../Week_04/874/walking_robot_simulation.go),[Py](../Week_04/874/walking_robot_simulation.py))|
37
+ |32|53|[maximum-subarray](https://leetcode-cn.com/problems/maximum-subarray) | 迭代([Go](53/maximum_subarray.go),[Py](53/maximum_subarray.py)),分治([Go](53/maximum_subarray2.go),[Py](53/maximum_subarray2.py))|
38
+ |33|1143|[longest-common-subsequence](https://leetcode-cn.com/problems/longest-common-subsequence) | 递归([Go](../Week_06/1143/longest_common_subsequence.go),[Py](../Week_06/1143/longest_common_subsequence.py)),动态规划([Go](../Week_06/1143/longest_common_subsequence2.go),[Py](../Week_06/1143/longest_common_subsequence2.py)),动态规划2([Go](../Week_06/1143/longest_common_subsequence3.go),[Py](../Week_06/1143/longest_common_subsequence3.py))|
39
+ |34|74|[search-a-2d-matrix](https://leetcode-cn.com/problems/search-a-2d-matrix) | 二分查找([Go](../Week_04/74/search_a_2d_matrix.go),[Py](../Week_04/74/search_a_2d_matrix.py))|
40
+ |35|LCOF5|[replace-space](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) | 新建一个buff([Go](LCOF5/replace_space.go),[Py](LCOF5/replace_space.go))|
41
+ |36|64|[minimum-path-sum](https://leetcode-cn.com/problems/minimum-path-sum) | 动态规划([Go](../Week_09/64/minimum_path_sum.go),[Py](../Week_09/64/minimum_path_sum.py))|
42
+ |37|322|[coin-change](https://leetcode-cn.com/problems/coin-change) | 递推([Go](../Week_04/322/coin_change.go),[Py](../Week_04/322/coin_change.py)),递归([Go](../Week_04/322/coin_change2.go),[Py](../Week_04/322/coin_change2.py))|
43
+ |38|213|[house-robber-ii](https://leetcode-cn.com/problems/house-robber-ii) | 动态规划([Go](../Week_06/213/house_robber_ii.go),[Py](../Week_06/213/house_robber_ii.go))|
44
+ |39|589|[n-ary-tree-preorder-traversal](https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal) | 递归([Go](../Week_02/589/n_ary_tree_preorder_traversal.go),[Py](../Week_02/589/n_ary_tree_preorder_traversal.go)),栈([Go](../Week_02/589/n_ary_tree_preorder_traversal2.go),[Py](../Week_02/589/n_ary_tree_preorder_traversal2.go))|
45
+ |40|363|[max-sum-of-rectangle-no-larger-than-k](https://leetcode-cn.com/problems/max-sum-of-rectangle-no-larger-than-k) | TODO|
46
+ |41|33|[search-in-rotated-sorted-array](https://leetcode-cn.com/problems/search-in-rotated-sorted-array) | 二分查找([Go](../Week_04/33/search_in_rotated_sorted_array.go),[Py](../Week_04/33/search_in_rotated_sorted_array.py))|
47
+ |42|212|[word-search-ii](https://leetcode-cn.com/problems/word-search-ii) | 前缀树+回溯([Go](../Week_07/212/word_search_ii.go),[Py](../Week_07/212/word_search_ii.py))|
48
+ |43|74|[search-a-2d-matrix](https://leetcode-cn.com/problems/search-a-2d-matrix) | 二分查找([Go](../Week_04/74/search_a_2d_matrix.go),[Py](../Week_04/74/search_a_2d_matrix.py))|
49
+ |44|208|[implement-trie-prefix-tree](https://leetcode-cn.com/problems/implement-trie-prefix-tree) | 前缀树([Go](../Week_07/208/implement_trie_prefix_tree.go),[Py](../Week_07/208/implement_trie_prefix_tree.py))|
50
+ |45|200|[numbers-of-islands](https://leetcode-cn.com/problems/numbers-of-islands) | 深度优先([Go](../Week_04/200/number_of_islands.go),[Py](../Week_04/200/number_of_islands.py))|
51
+ |46|53|[maximum-subarray](https://leetcode-cn.com/problems/maximum-subarray) | 迭代([Go](../Week_06/53/maximum_subarray.go),[Py](../Week_06/53/maximum_subarray.py)),分治([Go](../Week_06/53/maximum_subarray2.go),[Py](../Week_06/53/maximum_subarray2.py))|
52
+ |47|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))|
53
+ |48|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))|
54
+ |49|91|[decode-ways](https://leetcode-cn.com/problems/decode-ways) | 动态规划([Go](../Week_06/91/decode_ways.go),[Py](../Week_06/91/decode_ways.py))|
55
+ |50|547|[friend-circles](https://leetcode-cn.com/problems/friend-circles) | 深度优先([Go](../Week_07/547/friend_circles.go),[Py](../Week_07/547/friend_circles.py)),并查集([Go](../Week_07/547/friend_circles2.go),[Py](../Week_07/547/friend_circles2.py))|
56
+ |51|367|[valid-perfect-square](https://leetcode-cn.com/problems/valid-perfect-square) | 二分查找([Go](../Week_04/367/valid_perfect_square.go),[Py](../Week_04/367/valid_perfect_square.go))|
57
+ |52|198|[house-robber](https://leetcode-cn.com/problems/house-robber) | 动态规划([Go](../Week_06/198/house_robber.go),[Py](../Week_06/198/house_robber.py))|
58
+ |53|190|[reverse_bits](https://leetcode-cn.com/problems/reverse_bits) | 迭代([Go](../Week_08/190/reverse_bits.go),[Py](../Week_08/190/reverse_bits.py)),分治位运算([Go](../Week_08/190/reverse_bits2.go),[Py](../Week_08/190/reverse_bits2.py))|
59
+ |54|24|[swap-nodes-in-pairs](https://leetcode-cn.com/problems/swap-nodes-in-pairs)| 迭代([Go](../Week_01/24/swap_nodes_in_pairs2.go),[Py](../Week_01/24/swap_nodes_in_pairs2.py)), 递归([Go](../Week_01/24/swap_nodes_in_pairs.go),[Py](../Week_01/24/swap_nodes_in_pairs.py))|
60
+ |55|1122|[relative-sort-array](https://leetcode-cn.com/problems/relative-sort-array)| 计数排序([Go](../Week_08/1122/relative_sort_array.go),[Py](../Week_08/1122/relative_sort_array.py))|
61
+ |56|718|[maximum-length-of-repeated-subarray](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray)| 动态规划([Go](718/maximum_length_of_repeated_subarray.go),[Py](718/maximum_length_of_repeated_subarray.py)),滑动窗口([Go](718/maximum_length_of_repeated_subarray2.go),[Py](718/maximum_length_of_repeated_subarray2.py))|
62
+ |57|387|[first-unique-character-in-a-string](https://leetcode-cn.com/problems/first-unique-character-in-a-string)| 迭代([Go](387/first_unique_character_in_a_string.go),[Py](387/first_unique_character_in_a_string.py))|
63
+ |58|62|[unique-paths](https://leetcode-cn.com/problems/unique-paths) | 动态规划([Go](../Week_06/62/unique_paths.go),[Py](../Week_06/62/unique_paths.py))|
64
+ |59|541|[reverse-string-ii](https://leetcode-cn.com/problems/reverse-string-ii) | 迭代([Go](../Week_09/541/reverse_string_ii.go),[Py](../Week_09/541/reverse_string_ii.py))|
65
+ |60|300|[longest-increasing-subsequence](https://leetcode-cn.com/problems/longest-increasing-subsequence) | 动态规划([Go](300/longest_increasing_subsequence.go),[Py](300/longest_increasing_subsequence.py)),贪心+二分搜索([Go](300/longest_increasing_subsequence2.go),[Py](300/longest_increasing_subsequence2.py))|
66
+ |61|15|[3sum](https://leetcode-cn.com/problems/3sum) | 双指针夹逼([Go](15/3sum.go),[Py](15/3sum.py))|
67
+ |62|680|[valid-palindrome-ii](https://leetcode-cn.com/problems/valid-palindrome-ii) | 双指针夹逼([Go](../Week_09/680/valid_palindrome_ii.go),[Py](../Week_09/680/valid_palindrome_ii.py))|
68
+ |63|32|[longest-valid-parentheses](https://leetcode-cn.com/problems/longest-valid-parentheses) | 动态规划([Go](../Week_09/32/longest_valid_parentheses.go),[Py](../Week_09/32/longest_valid_parentheses.py)),栈([Go](../Week_09/32/longest_valid_parentheses2.go),[Py](../Week_09/32/longest_valid_parentheses2.py)),贪心([Go](../Week_09/32/longest_valid_parentheses3.go),[Py](../Week_09/32/longest_valid_parentheses3.py))|
69
+ |64|83|[remove-duplicates-from-sorted-list](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list) | 迭代([Go](83/remove_duplicates_from_sorted_list.go),[Py](83/remove_duplicates_from_sorted_list.py))|
70
+ |65|120|[triangle](https://leetcode-cn.com/problems/triangle) | 动态规划([Go](../Week_06/120/triangle.go),[Py](../Week_06/120/triangle.py))|
71
+ |66|127|[word-ladder](https://leetcode-cn.com/problems/word-ladder) | 广度优先([Go](../Week_04/127/word_ladder.go)),双向广度优先([Go](../Week_04/127/word_ladder2.go),[Py](../Week_04/127/word_ladder2.py))|
72
+ |67|46|[permutations](https://leetcode-cn.com/problems/permutations) | 递归([Go](../Week_03/46/permutations.go),[Py](../Week_03/46/permutations.py))|
73
+ |68|122|[best-time-to-buy-and-sell-stock-ii](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii) | 贪心([Go](../Week_04/122/best_time_to_buy_and_sell_stock_ii.go),[Py](../Week_04/122/best_time_to_buy_and_sell_stock_ii.py))|
74
+ |69|238|[product-of-array-except-self](https://leetcode-cn.com/problems/product-of-array-except-self) | 迭代([Go](238/product_of_array_except_self.go),[Py](238/product_of_array_except_self.py))|
75
+ |70|239|[sliding-window-maximum](https://leetcode-cn.com/problems/sliding-window-maximum) | 单调递减队列([Go](../Week_01/239/sliding_window_maximum.go), [Py](../Week_01/239/sliding_window_maximum.py))|
76
+
77
+ ## 题解
78
+
79
+ ###
10-week-algorithm-excercise-master/Week_01/1/two_sum.go ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "sort"
5
+ )
6
+
7
+ type NumIndex [][2]int
8
+
9
+ func (n NumIndex) Len() int {
10
+ return len(n)
11
+ }
12
+
13
+ func (n NumIndex) Less(i, j int) bool {
14
+ if n[i][0] <= n[j][0] {
15
+ return true
16
+ }
17
+ return false
18
+ }
19
+
20
+ func (n NumIndex) Swap(i, j int) {
21
+ n[i], n[j] = n[j], n[i]
22
+ }
23
+
24
+ func twoSum(nums []int, target int) []int {
25
+ var numIndex NumIndex
26
+ for i, n := range nums {
27
+ numIndex = append(numIndex, [2]int{n, i})
28
+ }
29
+ sort.Sort(numIndex)
30
+ //fmt.Println(numIndex)
31
+ i, j := 0, len(numIndex)-1
32
+ for i < j {
33
+ s := numIndex[i][0] + numIndex[j][0]
34
+ //fmt.Println(i, j, s)
35
+ if s == target {
36
+ return []int{numIndex[i][1], numIndex[j][1]}
37
+ } else if s < target {
38
+ i++
39
+ } else {
40
+ j--
41
+ }
42
+ }
43
+ return nil
44
+ }
10-week-algorithm-excercise-master/Week_01/1/two_sum_2.go ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func twoSum2(nums []int, target int) []int {
4
+ cache := map[int]int{}
5
+ for i, n := range nums {
6
+ m := target - n
7
+ if j, ok := cache[m]; ok {
8
+ return []int{j, i}
9
+ }
10
+ cache[n] = i
11
+ }
12
+ return nil
13
+ }
10-week-algorithm-excercise-master/Week_01/11/container_with_most_water.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def maxArea(self, height: List[int]) -> int:
6
+ i, j, res = 0, len(height) - 1, 0
7
+ while i < j:
8
+ if height[i] <= height[j]:
9
+ v = height[i] * (j - i)
10
+ i += 1
11
+ else:
12
+ v = height[j] * (j - i)
13
+ j -= 1
14
+ res = max(res, v)
15
+ return res
16
+
17
+ def test(self):
18
+ for height, target in [
19
+ ([1, 1], 1),
20
+ ([1, 1, 2, 3], 3),
21
+ ([1, 8, 6, 2, 5, 4, 8, 3, 7], 49),
22
+
23
+ ]:
24
+ ans = self.maxArea(height)
25
+ assert ans == target, f"target {target}, ans {ans}"
26
+
27
+
28
+ if __name__ == "__main__":
29
+ Solution().test()
10-week-algorithm-excercise-master/Week_01/141/linked_list_cycle2.go ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ func hasCycle(head *ListNode) bool {
4
+ if head == nil || head.Next == nil {
5
+ return false
6
+ }
7
+ fast, slow := head.Next, head
8
+ for fast != nil && fast.Next != nil {
9
+ if fast == slow {
10
+ return true
11
+ }
12
+ fast = fast.Next.Next
13
+ slow = slow.Next
14
+ }
15
+ return false
16
+ }
10-week-algorithm-excercise-master/Week_01/142/linked_list_cycle_ii_test.go ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import "testing"
4
+
5
+ func Test(t *testing.T) {
6
+ n1 := &ListNode{1, nil}
7
+ n2 := &ListNode{2, n1}
8
+ n3 := &ListNode{3, n2}
9
+ n4 := &ListNode{4, n3}
10
+ n5 := &ListNode{5, n4}
11
+ n6 := &ListNode{6, n5}
12
+
13
+ if detectCycle(n1) != nil {
14
+ t.Fatalf("failed")
15
+ }
16
+
17
+ if detectCycle(n6) != nil {
18
+ t.Fatalf("failed")
19
+ }
20
+ n1.Next = n4
21
+ if detectCycle(n5) != n4 {
22
+ t.Fatalf("failed")
23
+ }
24
+ }
10-week-algorithm-excercise-master/Week_01/15/3sum.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+
3
+
4
+ class Solution:
5
+ def threeSum(self, nums: List[int]) -> List[List[int]]:
6
+ nums.sort()
7
+ res = []
8
+ for i, a in enumerate(nums[:-2]):
9
+ if a > 0:
10
+ break
11
+ if i > 0 and nums[i - 1] == a:
12
+ continue
13
+ l, r = i + 1, len(nums) - 1
14
+ while l < r:
15
+ s = nums[i] + nums[l] + nums[r]
16
+ if s == 0:
17
+ res.append([nums[i], nums[l], nums[r]])
18
+ l += 1
19
+ r -= 1
20
+ while l < r and nums[l] == nums[l - 1]:
21
+ l += 1
22
+ while l < r and nums[r] == nums[r + 1]:
23
+ r -= 1
24
+ elif s < 0:
25
+ l += 1
26
+ while l < r and nums[l] == nums[l - 1]:
27
+ l += 1
28
+ else:
29
+ r -= 1
30
+ while l < r and nums[r] == nums[r + 1]:
31
+ r -= 1
32
+ return res
33
+
34
+ def test(self):
35
+ for nums, target in [
36
+ ([1, 0, -1, -1], [[-1, 0, 1]]),
37
+ ]:
38
+ ans = self.threeSum(nums)
39
+ assert ans == target, f"target: {target}, ans: {ans}"
40
+
41
+
42
+ if __name__ == "__main__":
43
+ Solution().test()