留数计算反常积分

移步https://blog.csdn.net/weixin_42578412/article/details/110149981
这个hexo不支持latex公式。引html又有很多的加载项影响速度。

这是一道用分部积分法无法解出的题目,故写博客以记之。

题目

$$
\int_{0}^{+\infty}\frac{ln x}{a^2+x^2}dx
$$
其中a为常数。

方法一:朴素换元法

这是一道反常积分的题目,理论上应该分为两段计算,分别是一个第一类反常积分和一个第二类反常积分。不过如果求出原函数并且两边极限都存在的话就免去了分段这一步。

$$
\int_{0}^{+\infty}\frac{ln x}{a^2+x^2}dx
$$
首先进行换元,令x = atan(u)
$$
\overset{令x = a
tan(u)}{=}\int_{0}^{\pi/2}\frac{lna+ln(tan(u))}{\frac{a^2}{cos^2u}}d(a*tanu)
$$
$$
=\frac{1}{a}\int_{0}^{\pi/2}lna + ln(cosu)-ln(sinu)du
$$

又因为
$$
\int_{0}^{\pi/2}ln(cosu)du=\int_{0}^{\pi/2}ln(sinu)du
$$

所以原式可以化为
$$
\frac{1}{a}\int_{0}^{+\infty}lna,du=\frac{lna·\pi}{2a}
$$

方法二:留数

设$z_0$为$f(z)$的孤立奇点,$f(z)$在$H:0<|z-z_0|<R$内解析,C为H内包含$z_0$的简单正向闭曲线,则称一下为$f(z)$在$z_0$处的留数。

$$
Res[f(z_),z_0] = \frac{1}{2\pi i}\oint_{c}^{}f(z)dz
$$

留数和定理,设函数$f(z)$在扩充复平面内只有有限个孤立奇点,则$f(z)$在所有奇点(包括无穷)的留数总和为零。

观察原积分,将其扩展为

$$
\frac{1}{2}\int_{-\infty}^{+\infty}\frac{ln |x|}{a^2+x^2}dx
$$
然后取整个虚平面的上半平面的一个顺时针大半圆为积分路径则在上半圆内部只有两个奇点,一个是原点另一个是$ai$

$$
\int_{-\infty}^{+\infty}\frac{ln |x|}{a^2+x^2}dx =\int_{-\infty}^{+\infty}\frac{ln |x|}{(x+ai)(x-ai)}dx
$$
由于原点处的极点乘以$(x-0)$为0,所以该处的留数为0.
$$
\int_{-\infty}^{+\infty}\frac{ln |x|}{(x+ai)(x-ai)}dx = 2\pi i , Res[\frac{ln |x|}{(x+ai)(x-ai)},ai]
$$

然后计算即可

$$=2\pi i , \frac{ln,a}{2ai}=\frac{lna·\pi}{a}
$$

所以原式为该积分的一半

$$
\int_{0}^{+\infty}\frac{ln x}{a^2+x^2}dx =\frac{1}{2}\int_{-\infty}^{+\infty}\frac{ln |x|}{a^2+x^2}dx =\frac{lna·\pi}{2a}
$$

与方法一结果一致。

kmeans聚类手动实现-python版

聚类算法

是在没有给定划分类别的情况下,根据数据的相似度进行分组的一种方法,分组的原则是组内距离最小化而组间距离最大化。

K-means算法是典型的基于距离的非层次聚类算法,在最小化误差函数的基础上将数据划分为预定的K类别,采用距离作为相似性的评级指标,即认为两个对象的距离越近,其相似度越大。

kmeans流程

算法过程:

  1. 从N个样本数据中随机选取K个对象作为初始的聚类质心。
  2. 分别计算每个样本到各个聚类中心的距离,将对象分配到距离最近的聚类中。
  3. 所有对象分配完成之后,重新计算K个聚类的质心。
  4. 与前一次的K个聚类中心比较,如果发生变化,重复过程2,否则转过程5.
  5. 当质心不再发生变化时,停止聚类过程,并输出聚类结果。

数据集介绍

使用sklearn自带的鸢尾花数据集

from sklearn.datasets import load_iris
data = load_iris()

即可导入数据。

数据集中的特征包括:

print("鸢尾花数据集的返回值:\n", iris)
# 返回值是一个继承自字典的Bench
print("鸢尾花的特征值:\n", iris["data"])
print("鸢尾花的目标值:\n", iris.target)
print("鸢尾花特征的名字:\n", iris.feature_names)
print("鸢尾花目标值的名字:\n", iris.target_names)
print("鸢尾花的描述:\n", iris.DESCR)

我们这里只使用目标是和特征值,这个特征值经过print是一个四维向量。
鸢尾花的target只包括三种花,所以k=3时候理论上最佳。编写代码的时候将target一并写入数组进行组合,这样在聚类完成后进行验证分类的错误率来衡量算法好坏。

代码简介

代码除了调用数据集和划分数据集使用到了sklearn的库函数之外,其余全部使用python自带的list结构或set结构和numpy相关函数实现。

主函数

第一次随机选取核心,就取数据集的前k个分别作为中心

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

def main(x,y,k,max_iter,interrupte_distance = 0):
#x是数据集,y是标签,k是聚类数目,终止距离和最大迭代数目.
#第一步初始化ak
a=[]
a_check = []#用于之后检查准确率
for i in range(k):
a.append([x.pop(0)])
a_check.append([y.pop(0)])
#初始化完了,来一遍第一次
for i in range(len(x)):
dist = []
for num in range(k):
dist.append(calc_distance(a[num][0],x[i]))
min_index = indexofMin(dist)
a[min_index].append(x[i])
a_check[min_index].append(y[i])
check_print(a,a_check)
#c初始化完成,a是一个k*特征数,的矩阵,a_check是检查矩阵。
for i in range(max_iter):
print('\n------------')
print('第'+str(i+1)+'次循环')
main_loop(a,a_check,interrupte_distance)

主循环

先检查终止条件是否满足。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

def main_loop(a,a_check,interrupte_distance=0):
#a的一重下表是k,a_check跟着最后算准确率.第二下标是数据集。
k = len(a)
ll = len(a[0][0])#特征的数量

## a的第一个是上次的质心
#计算质心
a_array = np.array(a)
heart_calc = []
flag_interrupt = 0
for i in range(k):
heart_calc.append([])

#print(len())
#print(a[2])
#exit(0)
for i in range(k):
#对a[i]求均值了
for j in range(ll):
#print(a[i][:][j][1])
#print(i,j)
#heart_calc[i].append(np.mean(a[i][:][j]))
heart_calc[i].append(middle_mean(a,i,j))
if calc_distance(heart_calc[i],a[i][0])>interrupte_distance:
flag_interrupt = 1
if flag_interrupt == 0:
#满足距离要求
return 0

#聚类中心算完,并且不满足距离要求,开始迭代

for i in range(k):
for j in range(len(a[i])):
tmp = a[i].pop(0)
tmp_lab = a_check[i].pop(0)
tmp_index = find_heart_index(heart_calc,tmp)
a[tmp_index].append(tmp)
a_check[tmp_index].append(tmp_lab)
print('中心点坐标:')
print(heart_calc)
check_print(a,a_check)
return a,a_check

实验结果

当k=3时候,输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

初始化错误率:0.35
初始化方差:0.2637878757089331


------------
第1次循环
中心点坐标:
[[5.173076923076924, 3.661538461538462, 1.4653846153846157, 0.27692307692307694], [6.528333333333333, 2.986666666666667, 5.255000000000001, 1.8366666666666667], [5.161764705882353, 2.8058823529411767, 2.85, 0.776470588235294]]
错误率:0.20833333333333334
方差:0.12704004558840606


------------
第2次循环
中心点坐标:
[[4.9975000000000005, 3.47, 1.4625, 0.2475], [6.495238095238095, 2.9777777777777783, 5.204761904761905, 1.8126984126984127], [5.447058823529411, 2.5529411764705885, 3.7588235294117647, 1.1588235294117646]]
错误率:0.15
方差:0.126100321239607


------------
第3次循环
中心点坐标:
[[4.9975000000000005, 3.47, 1.4625, 0.2475], [6.583928571428572, 3.001785714285714, 5.310714285714285, 1.8678571428571427], [5.545833333333333, 2.620833333333333, 3.9333333333333336, 1.2208333333333334]]
错误率:0.125
方差:0.12874688121486713


------------
第4次循环
中心点坐标:
[[4.9975000000000005, 3.47, 1.4625, 0.2475], [6.609433962264151, 3.020754716981132, 5.350943396226417, 1.8962264150943395], [5.61111111111111, 2.625925925925926, 4.007407407407407, 1.237037037037037]]
错误率:0.10833333333333334
方差:0.13044657523262912


------------
第5次循环
中心点坐标:
[[4.9975000000000005, 3.47, 1.4625, 0.2475], [6.631372549019607, 3.0156862745098034, 5.3803921568627455, 1.911764705882353], [5.641379310344826, 2.662068965517242, 4.048275862068966, 1.2551724137931033]]
错误率:0.10833333333333334
方差:0.13267293238109287

实验结论

整体来看,由于kmeans主要使用的是距离来分类,导致算法迅速收敛,一般两三个循环就可以收敛到最终结果了,即使一开始的中心点是随机选取的。

从实验结果可以看出,k=3和k=4时候差距不大,如果在增加k,效果就会变得不佳。由于k=4比三多一类,所以每一类内部的样本个数会变少,所以方差会略低与k=3。

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np

def indexofMin(arr):
minindex = 0
currentindex = 1
while currentindex < len(arr):
if arr[currentindex] < arr[minindex]:
minindex = currentindex
currentindex += 1
return minindex
def get_var(a):
#狗屁需求还要弄什么密度,用方差来反映离散程度吧
l = len(a)
ans = []
for i in range(l):
ans.append(np.array(a[i]).var(axis=0))
return ans
def calc_distance(list_a,list_b):
l = len(list_a)
#约束是最小均方误差MSE
ans = 0
for i in range(l):
ans += pow(list_a[i] - list_b[i],2)
return np.sqrt(ans)

def main(x,y,k,max_iter,interrupte_distance = 0):
#x是数据集,y是标签,k是聚类数目,终止距离和最大迭代数目.
#第一步初始化ak
a=[]
a_check = []#用于之后检查准确率
for i in range(k):
a.append([x.pop(0)])
a_check.append([y.pop(0)])
#初始化完了,来一遍第一次
for i in range(len(x)):
dist = []
for num in range(k):
dist.append(calc_distance(a[num][0],x[i]))
min_index = indexofMin(dist)
a[min_index].append(x[i])
a_check[min_index].append(y[i])
check_print(a,a_check)
#c初始化完成,a是一个k*特征数,的矩阵,a_check是检查矩阵。
for i in range(max_iter):
print('\n------------')
print('第'+str(i+1)+'次循环')
main_loop(a,a_check,interrupte_distance)

def middle_mean(l,i,j):
#妈的heart_calc[i].append(np.mean(a[i][:][j]))用不了,why doesnt np work?
tmp =[]
for ii in range(len(l[i])):
tmp.append(l[i][ii][j])
return np.mean(tmp)

def main_loop(a,a_check,interrupte_distance=0):
#a的一重下表是k,a_check跟着最后算准确率.第二下标是数据集。
k = len(a)
ll = len(a[0][0])#特征的数量

## a的第一个是上次的质心
#计算质心
a_array = np.array(a)
heart_calc = []
flag_interrupt = 0
for i in range(k):
heart_calc.append([])

#print(len())
#print(a[2])
#exit(0)
for i in range(k):
#对a[i]求均值了
for j in range(ll):
#print(a[i][:][j][1])
#print(i,j)
#heart_calc[i].append(np.mean(a[i][:][j]))
heart_calc[i].append(middle_mean(a,i,j))
if calc_distance(heart_calc[i],a[i][0])>interrupte_distance:
flag_interrupt = 1
if flag_interrupt == 0:
#满足距离要求
return 0

#聚类中心算完,并且不满足距离要求,开始迭代

for i in range(k):
for j in range(len(a[i])):
tmp = a[i].pop(0)
tmp_lab = a_check[i].pop(0)
tmp_index = find_heart_index(heart_calc,tmp)
a[tmp_index].append(tmp)
a_check[tmp_index].append(tmp_lab)
print('中心点坐标:')
print(heart_calc)
check_print(a,a_check)
return a,a_check
def check_print(a,a_check):
sum_num = 0
wrong_num = 0
for i in range(len(a_check)):
tmp = max(a_check[i],key = a_check.count)
for j in a_check[i]:
sum_num+=1
if j != tmp:
wrong_num += 1
#print(a_check)
print("错误率:"+str(wrong_num/sum_num))
print("方差:"+str(np.mean(get_var(a))))
print()
def find_heart_index(heart,undef):
#heart是各个中心节点,undef是待确定的特征
k = len(heart)
#print(heart)
min_index = 0
min_dis = 100000
for i in range(k):
tmp_dis = calc_distance(undef,heart[i])
#print(tmp_dis)
if(tmp_dis<min_dis):
min_index = i
min_dis = tmp_dis
#print('min')
#print(min_index)
return min_index


if __name__ == '__main__':
data = load_iris()

#print(data.keys())
x_train, x_test, y_train, y_test = train_test_split(data.data, data.target,test_size=0.2, random_state=222)


#print("测试集的目标值:\n", y_train)
main(x_train.tolist(),y_train.tolist(),4,5)

实轴上开环零极点之间的分离会和点问题

问题

判断题:

若实轴上某开环极点与开环零点之间具有根轨迹,那么他们之间肯定没有分离汇合点。

答案:错,可以有分离汇合点,反例如下。

例子

sys =
 
     s + 1
  -----------
  s^3 + 9 s^2

或者

sys =
 
     s + 2
  ------------
  s^3 + 20 s^2

图书馆预约脚本新版个人版_requests

script_for_PG

由于之前图书馆敏感的原因下线了GitHub的仓库,也被图书馆管理员叫去谈话,只能在博客里面做一下记录吧,这个是午休期间可以维持座位的脚本,测试可用仅限于四楼东侧座位,其余座位需要轻微修改,早上的预约脚本中mylist可以根据个人需求修改座位号。

日后希望能做出一个完整版个人预约服务脚本,然后放在校内师兄服务器上运行,个人电脑的运行环境不稳定,可能因为宿舍网络原因导致预约失败。

午休脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env python3
# @Author : Guoguo
# @Blog :https://gwyxjtu.github.io
import os
import time
import json
import base64
import requests
from Crypto.Cipher import AES
import re
from lxml import etree
from threading import Thread
import datetime

class XJTUUser(object):

def __init__(self, config_file_path='./config.json'):
with open(config_file_path) as config_file:
config = json.loads(config_file.read())
self.config = config
self.is_login = False
self.session = requests.Session()
self.session.headers.update(config['headers'])
self.session.cookies.update(config['cookies'])


def login(self):
#--------------------------------------
self.weizhi = ''
def vxpush(self,msg):
url = 'http://wxpusher.zjiecode.com/api/send/message'
uid = ''
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
'Content-Type':'application/json;charset=UTF-8'
}
data = {
'appToken':'',
'content': msg,
'contentType':1,
'uids':[uid]
}
print(requests.post(url,headers=headers,json=data).text)

def check_my_seat(self):#返回你的座位字符穿
r = self.session.get('http://rg.lib.xjtu.edu.cn:8010/my/')
dom = etree.HTML(r.text)
a_text = dom.xpath('/html/body/div[2]/center/div[1]/div/div/div/div/div/div[1]/h3/text()[2]')
ans = re.findall('\d+', a_text[0])[0]
#print()
self.weizhi = a_text[0].split('\xa0')[-1].split('\n')[0]
jjj = dom.xpath('/html/body/div[2]/center/div[1]/div/div/div/div/div/div[2]/center/h3[1]')
if(len(jjj)<1):
return 0;
if jjj[0].text == '已取消' or jjj[0].text == '已离馆' or jjj[0].text == '超时未入馆':
vxpush(self,self.config['username']+'没弄上,出现错误')
print(self.config['username']+'没弄上,出现错误')
return 0
else:
vxpush(self,self.config['username']+'弄好了,当前位置'+ans)
print(self.config['username']+'弄好了'+ans)
return 1


def cancel(self):
try:
r = self.session.get("http://rg.lib.xjtu.edu.cn:8010/my/")
pattern = re.compile("cancelconfirm\('(.*?)'\);", re.S)
yu_id = re.findall(pattern, r.text)[0]
print(yu_id)
self.session.get("http://rg.lib.xjtu.edu.cn:8010/my/?cancel=1&ri=" + yu_id)
#微信通知
vxpush(self,'取消成功')
print("取消成功")
return 1
except Exception as e:
print("取消失败\n" + str(e))
return 0
#预约座位
def reserve(self,kid,sp):
r = self.session.get('http://rg.lib.xjtu.edu.cn:8010/ruguan')#入关
#print('--------------------------')
nn = r.text.find('<input id="csrf_token" name="csrf_token" type="hidden" value=')
tok = r.text[nn+1+len('<input id="csrf_token" name="csrf_token" type="hidden" value='):nn+56+len('<input id="csrf_token" name="csrf_token" type="hidden" value=')]
#print(r.text[nn+1+len('<input id="csrf_token" name="csrf_token" type="hidden" value='):nn+56+len('<input id="csrf_token" name="csrf_token" type="hidden" value=')])
data={
'csrf_token':tok,
'csrf_token':tok,
'service':'seat',
'submit':'%E6%8F%90%E4%BA%A4',
'rplace':'east'
}#入关post,比较麻烦
r = self.session.post('http://rg.lib.xjtu.edu.cn:8010/ruguan',data = data)#提交

r = self.session.get('http://rg.lib.xjtu.edu.cn:8010/seat/?kid='+kid+'&sp='+sp)
#print(r.text)
#------------------------------新版判断
#兴庆区的,别的区得自行修改了
if check_my_seat(self) == 1:
#vxpush(self,'预约成功'+str(check_my_seat(self)))
#print('预约成功状态'+str(check_my_seat(self)))
return 1
else:
vxpush(self,'预约失败')
print('预约失败')
return 0
# if(sp == 'west3B'):
# r_w3=self.session.get('http://rg.lib.xjtu.edu.cn:8010/qseat?sp=west3B')
# s2 = json.loads(r_w3.text)['seat']
# if(s2[kid] == 1):
# return 200
# else:
# print('预约了但是没有成功,肯定是你已经预约过了')
# exit(0)
# return 0
# if(sp == 'east3A'):
# r_w3=self.session.get('http://rg.lib.xjtu.edu.cn:8010/qseat?sp=east3A')
# s2 = json.loads(r_w3.text)['seat']
# if(s2[kid] == 1):
# return 200
# else:
# print('预约了但是没有成功,肯定是你已经预约过了')
# exit(0)
# return 0
return r.status_code
def encrypt_pwd(raw_pwd, publicKey='0725@pwdorgopenp'):
''' AES-ECB encrypt '''
publicKey = publicKey.encode('utf-8')
# pkcs7 padding
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
pwd = pad(raw_pwd)
# zero padding
'''
pwd = raw_pwd
while len(raw_pwd.encode('utf-8')) % 16 != 0:
pwd += '\0'
'''
cipher = AES.new(publicKey, AES.MODE_ECB)
pwd = cipher.encrypt(pwd.encode('utf-8'))
return str(base64.b64encode(pwd), encoding='utf-8')

_headers = self.config['headers']
_headers['Content-Type'] = 'application/x-www-form-urlencoded'

# start with 302 redirection from ehall
_r = self.session.get('http://rg.lib.xjtu.edu.cn:8010/auth/login/?next=%2Fseat%2F')

# get cookie route
self.session.get('https://org.xjtu.edu.cn/openplatform/login.html')

# get JcaptchaCode and cookie JSESSIONID & sid_code
r_JcaptchaCode = self.session.post('https://org.xjtu.edu.cn/openplatform/g/admin/getJcaptchaCode',
headers=_headers)

# is_JcaptchaCode_show
url = 'https://org.xjtu.edu.cn/openplatform/g/admin/getIsShowJcaptchaCode'
params = {
'userName': self.config['username'],
'_': str(int(time.time() * 1000))
}
r = self.session.get(url, params=params, headers=_headers)
print(r.text)
# login
url = 'https://org.xjtu.edu.cn/openplatform/g/admin/login'
cookie = {
'cur_appId_':'JL4oKidbLpQ='
}
data = {
"loginType": 1,
"username": self.config['username'],
"pwd": encrypt_pwd(self.config['password']),
"jcaptchaCode": ""
}
_headers['Content-Type'] = 'application/json;charset=UTF-8'
r = self.session.post(url, data=json.dumps(data), headers=_headers,cookies=cookie)
print(r.text)
token = json.loads(r.text)['data']['tokenKey']

cookie = {
'cur_appId_':'JL4oKidbLpQ=',
'open_Platform_User' : token
}
r=self.session.get('http://org.xjtu.edu.cn/openplatform/oauth/auth/getRedirectUrl?userType=1&personNo='+self.config['person_id']+'&_=1590998261976',cookies = cookie)
print(r.text)
r=self.session.get(json.loads(r.text)['data'])
r=self.session.get('http://rg.lib.xjtu.edu.cn:8080/bxusr/link.jsp?uid='+self.config['username']+'&cn=%E9%83%AD%E7%8E%8B%E6%87%BF&employeeNumber='+self.config['person_id']+'&depId=%E7%94%B5%E5%AD%90%E4%B8%8E%E4%BF%A1%E6%81%AF%E5%AD%A6%E9%83%A8&mobile')#&email=867718012@qq.com去掉了
#print(r.text)
#---------------------登陆成功------------------------
check_my_seat(self)
re_time = datetime.datetime.now()
while(1):
#ii+=1
r=self.session.get('http://rg.lib.xjtu.edu.cn:8086/qseat?sp=north4east')#兴庆区的,别的区得自行修改了
s = json.loads(r.text)['seat']
#print(s1,s2,s_new)
print('循环次数:')
#vxpush(self,'test')
#print(ii)
#reserve(self,'029','south3middle')
print("位置状态" + str(s[self.weizhi]))
if s[self.weizhi] == 0:
while(1):
if reserve(self,self.weizhi,'north4east') == 1:
print('座位号是'+self.weizhi)
time.sleep(60*25)
while(cancel(self) == 0):
time.sleep(5)

# return(0)
time.sleep(2)
# if((datetime.datetime.now()-re_time).seconds>=300):
# exit(0)

if __name__ == '__main__':
#time.sleep(60*1)#预计一分钟离馆加延迟
dt = '2020-08-19 11:00:02'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
t = int(time.time())
cha = ts - t
while cha >0:
t = int(time.time())
cha = ts - t
time.sleep(1)
if(cha%100 == 0):
print(cha)
print("开始")
guoguo = XJTUUser('./config.json')
guoguo.login()
exit(0)

凌晨预约脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
# @Author : Guoguo
# @Blog :https://gwyxjtu.github.io
import os
import time
import json
import base64
import requests
from Crypto.Cipher import AES
import re
from lxml import etree
from threading import Thread

our_seat = []

class XJTUUser(object):

def __init__(self, config_file_path='./config.json'):
with open(config_file_path) as config_file:
config = json.loads(config_file.read())
self.config = config
self.is_login = False
self.session = requests.Session()
self.session.headers.update(config['headers'])
self.session.cookies.update(config['cookies'])


def login(self):

#--------------------------------------
def check_my_seat(self):#返回你的座位字符穿
r = self.session.get('http://rg.lib.xjtu.edu.cn:8086/my/')
dom = etree.HTML(r.text)
a_text = dom.xpath('/html/body/div[2]/center/div[1]/div/div/div/div/div/div[1]/h3/text()[2]')
jjj = dom.xpath('/html/body/div[2]/center/div[1]/div/div/div/div/div/div[2]/center/h3[1]')
if(len(jjj)<1):
print('没弄上1,出现错误')
return 0;
if jjj[0].text == '已取消' or jjj[0].text == '已离馆' or jjj[0].text == '超时未入馆':
print('没弄上,出现错误')
return 0
else:
print('弄好了'+str(a_text))
our_seat.append(str(a_text))
return 1



def reserve(self,kid,sp):
r = self.session.get('http://rg.lib.xjtu.edu.cn:8086/ruguan')#入关
#print('--------------------------')
nn = r.text.find('<input id="csrf_token" name="csrf_token" type="hidden" value=')
tok = r.text[nn+1+len('<input id="csrf_token" name="csrf_token" type="hidden" value='):nn+56+len('<input id="csrf_token" name="csrf_token" type="hidden" value=')]
#print(r.text[nn+1+len('<input id="csrf_token" name="csrf_token" type="hidden" value='):nn+56+len('<input id="csrf_token" name="csrf_token" type="hidden" value=')])
data={
'csrf_token':tok,
'csrf_token':tok,
'service':'seat',
'submit':'%E6%8F%90%E4%BA%A4',
'rplace':'east'
}#入关post,比较麻烦
r = self.session.post('http://rg.lib.xjtu.edu.cn:8086/ruguan',data = data)#提交

r = self.session.get('http://rg.lib.xjtu.edu.cn:8086/seat/?kid='+kid+'&sp='+sp)
#print(r.text)
#------------------------------新版判断
#兴庆区的,别的区得自行修改了
if check_my_seat(self) == 1:
print('预约成功'+str(check_my_seat(self)))
return 1
else:
print('预约失败')
return 0

return r.status_code
def encrypt_pwd(raw_pwd, publicKey='0725@pwdorgopenp'):
''' AES-ECB encrypt '''
publicKey = publicKey.encode('utf-8')
# pkcs7 padding
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
pwd = pad(raw_pwd)
# zero padding
'''
pwd = raw_pwd
while len(raw_pwd.encode('utf-8')) % 16 != 0:
pwd += '\0'
'''
cipher = AES.new(publicKey, AES.MODE_ECB)
pwd = cipher.encrypt(pwd.encode('utf-8'))
return str(base64.b64encode(pwd), encoding='utf-8')

_headers = self.config['headers']
_headers['Content-Type'] = 'application/x-www-form-urlencoded'

# start with 302 redirection from ehall
_r = self.session.get('http://rg.lib.xjtu.edu.cn:8086/auth/login/?next=%2Fseat%2F')

# get cookie route
self.session.get('https://org.xjtu.edu.cn/openplatform/login.html')

# get JcaptchaCode and cookie JSESSIONID & sid_code
r_JcaptchaCode = self.session.post('https://org.xjtu.edu.cn/openplatform/g/admin/getJcaptchaCode',
headers=_headers)

# is_JcaptchaCode_show
url = 'https://org.xjtu.edu.cn/openplatform/g/admin/getIsShowJcaptchaCode'
params = {
'userName': self.config['username'],
'_': str(int(time.time() * 1000))
}
r = self.session.get(url, params=params, headers=_headers)
print(r.text)
# login
url = 'https://org.xjtu.edu.cn/openplatform/g/admin/login'
cookie = {
'cur_appId_':'JL4oKidbLpQ='
}
data = {
"loginType": 1,
"username": self.config['username'],
"pwd": encrypt_pwd(self.config['password']),
"jcaptchaCode": ""
}
_headers['Content-Type'] = 'application/json;charset=UTF-8'
r = self.session.post(url, data=json.dumps(data), headers=_headers,cookies=cookie)
print(r.text)
token = json.loads(r.text)['data']['tokenKey']

cookie = {
'cur_appId_':'JL4oKidbLpQ=',
'open_Platform_User' : token
}
r=self.session.get('http://org.xjtu.edu.cn/openplatform/oauth/auth/getRedirectUrl?userType=1&personNo='+self.config['person_id']+'&_=1590998261976',cookies = cookie)
print(r.text)
r=self.session.get(json.loads(r.text)['data'])
r=self.session.get('http://rg.lib.xjtu.edu.cn:8080/bxusr/link.jsp?uid='+self.config['username']+'&cn=%E9%83%AD%E7%8E%8B%E6%87%BF&employeeNumber='+self.config['person_id']+'&depId=%E7%94%B5%E5%AD%90%E4%B8%8E%E4%BF%A1%E6%81%AF%E5%AD%A6%E9%83%A8&mobile')#&email=867718012@qq.com去掉了
#print(r.text)
#---------------------登陆成功------------------------

#print(r_w3.text)
#print('各层座位数量',end = '')
#print(json.loads(r_e3.text)['scount'])
#s.update(json.loads(r_w3.text)['seat'])/seat/?kid=015&sp=north4southwest
#print(s1,s2)


#check_my_seat(self)
my_list = ['G029','G054','G066']
ii=0
while(1):
ii+=1
r=self.session.get('http://rg.lib.xjtu.edu.cn:8086/qseat?sp=north4east')#兴庆区的,别的区得自行修改了

#print('各层座位数量',end = '')
s = json.loads(r.text)['seat']
print('循环次数:')
print(ii)
for i in my_list:
if s[i] == 0:
print(i)
if reserve(self,i,'north4east') == 1:
return(0)
for i in s:
if s[i] == 0:
print(i)
if reserve(self,i,'north4east') == 1:
return(0)
time.sleep(2)

if __name__ == '__main__':

guoguo = XJTUUser('./config.json')
zxz = XJTUUser('./config_zxz.json')
dt = '2020-08-20 06:00:02'
ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
t = int(time.time())
cha = ts - t
while cha >0:
t = int(time.time())
cha = ts - t
time.sleep(1)
if(cha%100 == 0):
print(cha)
print("开始")

#guoguo.login()
#别的人就分别建立新的结构体就行
#ruo = XJTUUser('./config_1.json')
guoguo.login()
zxz.login()
exit(0)

config文件

{
    "username": "netid",
    "password": "",
    "person_id":"217611****",
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
    },
    "cookies": {}
}

考研加油!

  • Copyrights © 2015-2023 galaxy
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信