Python中声音信号导入后显示出问题(函数fromstring和frombuffer的使用区别)
  1. 关于Python中声音信号的导入及显示;
  2. 相关代码:
import wave     # 导入音频处理包
import matplotlib.pyplot as plt
import numpy as np


f = wave.open(r'D:\1.wav', 'rb')
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
# nchannels:声道数;sampwidth:量化位数(byte);framerate:采样频率;nframes:采样点数
print('channel:', nchannels, 'sampwidth:', sampwidth, 'framerate:', framerate, 'numframes:', nframes)

strData = f.readframes(nframes)  # 读取音频,字符串格式
f.close()

# waveData = np.frombuffer(strData, dtype='S1', offset=0)  
waveData = np.fromstring(strData, dtype=np.short)  # 将字符串转化为int

waveData.shape = -1,2   # 将waveData数组改为2列,行数自动匹配。
waveData = waveData.T
time = np.arange(0, nframes) * (1.0 / framerate)

plt.figure(1)
plt.subplot(2,1,1)
plt.plot(time, waveData[0])
plt.subplot(2,1,2)
plt.plot(time, waveData[1], c='r')
plt.xlabel("Time(s)")
plt.show()

  1. 报错信息:
    DeprecationWarning: The binary mode of fromstring is deprecated, as it behaves surprisingly on unicode inputs. Use frombuffer instead
    waveData = np.fromstring(strData, dtype=np.short) # 将字符串转化为int

  2. 系统建议改用frombuffer,因为fromstring提示将会被弃用,但是使用frombuffer后得出的数组经过转换后不能和time的维度相匹配,而fromstring后的数据是左右声道的数据。想要知道如何使用frombuffer来代替fromstring!

  3. 图像可以正常显示,不会报错但是会报警告,多谢大神的帮忙

  4. 声音信号 1.wav

  5. 图片说明

jiachengbest
jiachengbest 遇到相同的问题,请问这个问题最终如何解决?
大约一个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
导入模块错误:(无法从“string”导入名称“atof”)【python】

代码: import os,sys sys.path.append('/nfs3group/chlgrp/datasets/Animals_with_Attributes/code/') from numpy import * from platt import * import pickle, bz2 def nameonly(x): return x.split('\t')[1] def loadstr(openname,converter=str): return [converter(c.strip()) for c in open(openname).readlines()] def bzUnpickle(openname): return pickle.load(bz2.BZ2File(openname)) feature_pattern = '/D:/shuxingfenlei/AwA-features/Animals_with_Attributes/Features/hist/%s-%s.txt' labels_pattern = '/D:/shuxingfenlei/AwA2-features/Animals_with_Attributes2/Features/ResNet101/%s-AwA2-labels.txt' all_features = ['cq','lss','phog','sift','surf','rgsift'] attribute_matrix = 2*loadstr('/shuxingfenlei/AwA2-data/Animals_with_Attributes2/predicate-matrix-binary.txt',dtype=float)-1 classnames = loadstr('/shuxingfenlei/AwA2-data/Animals_with_Attributes2/classes.txt',nameonly) attributenames = loadstr('/shuxingfenlei/AwA2-data/Animals_with_Attributes2/predicates.txt',nameonly) def create_data(all_classes,attribute_id): featurehist={} for feature in all_features: featurehist[feature]=[] labels=[] for classname in all_classes: class_id = classnames.index(classname) class_size = 0 for feature in all_features: featurefilename = feature_pattern % (classname,feature) print ('# ',featurefilename) histopen = bzUnpickle(featurefilename) featurehist[feature].extend( histopen ) labelfilename = labels_pattern % classname print ('# ',labelfilename) print ('#') labels.extend( bzUnpickle(labelfilename)[:,attribute_id] ) for feature in all_features: featurehist[feature]=array(featurehist[feature]).T # shogun likes its data matrices shaped FEATURES x SAMPLES labels = array(labels) return featurehist,labels def train_attribute(attribute_id, C, split=0): from shogun import Classifier,Features,Kernel,Distance attribute_id = int(attribute_id) print ("# attribute ",attributenames[attribute_id]) C = float(C) print ("# C ", C) if split == 0: train_classes=loadstr('/nfs3group/chlgrp/datasets/Animals_with_Attributes/trainclasses.txt') test_classes=loadstr('/nfs3group/chlgrp/datasets/Animals_with_Attributes/testclasses.txt') else: classnames = loadstr('/nfs3group/chlgrp/datasets/Animals_with_Attributes/classnames.txt') startid= (split-1)*10 stopid = split*10 test_classes = classnames[startid:stopid] train_classes = classnames[0:startid]+classnames[stopid:] Xtrn,Ltrn = create_data(train_classes,attribute_id) Xtst,Ltst = create_data(test_classes,attribute_id) if min(Ltrn) == max(Ltrn): # only 1 class Lprior = mean(Ltrn) prediction = sign(Lprior)*ones(len(Ltst)) probabilities = 0.1+0.8*0.5*(Lprior+1.)*ones(len(Ltst)) # fallback return prediction,probabilities,Ltst #sg('loglevel', 'WARN') widths={} for feature in all_features: traindata = array(Xtrn[feature][:,::50],float) # used to be 5*offset sg('set_distance', 'CHISQUARE', 'REAL') sg('clean_features', 'TRAIN') sg('set_features', 'TRAIN', traindata) sg('init_distance', 'TRAIN') DM=sg('get_distance_matrix') widths[feature] = median(DM.flatten()) del DM s = Classifier.LibSVM() #sg('new_svm', 'LIBSVM') Lplatt_trn = concatenate([Ltrn[i::10] for i in range(9)]) # 90% for training Lplatt_val = Ltrn[9::10] # remaining 10% for platt scaling feats_trn = Features.CombinedFeatures() feats_val = Features.CombinedFeatures() for feature in all_features: Xplatt_trn = concatenate([Xtrn[feature][:,i::10] for i in range(9)], axis=1) feats_trn.append_feature_obj( Features.RealFeatures(ascontiguousarray(Xplatt_trn)) ) #sg('add_features', 'TRAIN', Xplatt_trn) Xplatt_val = Xtrn[feature][:,9::10] feats_val.append_feature_obj( Features.RealFeatures(ascontiguousarray(Xplatt_val)) ) #sg('add_features', 'TEST', Xplatt_val) del Xplatt_trn,Xplatt_val,Xtrn[feature] labels_trn = Features.Labels(Lplatt_trn) #sg('set_labels', 'TRAIN', Lplatt_trn) kernel = Kernel.CombinedKernel() #sg('set_kernel', 'COMBINED', 5000) for featureset in all_features: kernel.append_kernel( Kernel.Chi2Kernel( 5000, widths[featureset]/5. ) ) #sg('add_kernel', 1., 'CHI2', 'REAL', 10, widths[featureset]/5. ) kernel.init(feats_trn,feats_trn) K=kernel.get_kernel_matrix() K.tofile('/scratch/chl/cvfold%d_C%g_%02d-trn.kernel' % (split, C, attribute_id)) del K s.set_max_train_time(600*60.) #sg('svm_max_train_time', 600*60.) # one hour should be plenty s.set_C(C,C) #sg('c', C) s.set_kernel(kernel) s.set_labels(labels_trn) #sg('init_kernel', 'TRAIN') try: s.train() #sg('train_classifier') except (RuntimeWarning,RuntimeError): # can't train, e.g. all samples have the same labels Lprior = mean(Ltrn) prediction = sign(Lprior) * ones(len(Ltst)) probabilities = 0.1+0.8*0.5*(Lprior+1.) * ones(len(Ltst)) savetxt('./DAP/cvfold%d_C%g_%02d.txt' % (split, C, attribute_id), prediction) savetxt('./DAP/cvfold%d_C%g_%02d.prob' % (split, C, attribute_id), probabilities) savetxt('./DAP/cvfold%d_C%g_%02d.labels' % (split, C, attribute_id), Ltst) return prediction,probabilities,Ltst bias = s.get_bias() alphas = s.get_alphas() #[bias, alphas]=sg('get_svm') #print bias,alphas kernel.init(feats_trn,feats_val) K=kernel.get_kernel_matrix() K.tofile('/scratch/chl/cvfold%d_C%g_%02d-val.kernel' % (split, C, attribute_id)) del K #sg('init_kernel', 'TEST') try: prediction=s.classify().get_labels() #prediction=sg('classify') platt_params = SigmoidTrain(prediction, Lplatt_val) probabilities = SigmoidPredict(prediction, platt_params) savetxt('./DAP/cvfold%d_C%g_%02d-val.txt' % (split, C, attribute_id), prediction) savetxt('./DAP/cvfold%d_C%g_%02d-val.prob' % (split, C, attribute_id), probabilities) savetxt('./DAP/cvfold%d_C%g_%02d-val.labels' % (split, C, attribute_id), Lplatt_val) savetxt('./DAP/cvfold%d_C%g_%02d-val.platt' % (split, C, attribute_id), platt_params) #print '#train-perf ',attribute_id,C,mean((prediction*Lplatt_val)>0),mean(Lplatt_val>0) #print '#platt-perf ',attribute_id,C,mean((sign(probabilities-0.5)*Lplatt_val)>0),mean(Lplatt_val>0) except RuntimeError: Lprior = mean(Ltrn) prediction = sign(Lprior)*ones(len(Ltst)) probabilities = 0.1+0.8*0.5*(Lprior+1.)*ones(len(Ltst)) print (sys.stderr, "#Error during testing. Using constant platt scaling") platt_params=[1.,0.] # ----------------------------- now apply to test classes ------------------ feats_tst = Features.CombinedFeatures() #sg('clean_features', 'TEST') for feature in all_features: feats_tst.append_feature_obj( Features.RealFeatures(ascontiguousarray(Xtst[feature])) ) del Xtst[feature] kernel.init(feats_trn,feats_tst) K=kernel.get_kernel_matrix() K.tofile('/scratch/chl/cvfold%d_C%g_%02d-tst.kernel' % (split, C, attribute_id)) del K #sg('init_kernel', 'TEST') prediction=s.classify().get_labels() #prediction=sg('classify') probabilities = SigmoidPredict(prediction, platt_params) savetxt('./DAP/cvfold%d_C%g_%02d.txt' % (split, C, attribute_id), prediction) savetxt('./DAP/cvfold%d_C%g_%02d.prob' % (split, C, attribute_id), probabilities) savetxt('./DAP/cvfold%d_C%g_%02d.labels' % (split, C, attribute_id), Ltst) return prediction,probabilities,Ltst if __name__ == '__main__': import sys try: attribute_id = int(sys.argv[1]) except IndexError: print ("Must specify attribute ID!") raise SystemExit try: split = int(sys.argv[2]) except IndexError: split = 0 try: C = float(sys.argv[3]) except IndexError: C = 10. pred,prob,Ltst = train_attribute(attribute_id,C,split) print ("Done.", attribute_id, C, split)

python import 和from import 区别

上网查了一下,貌似是一个简单问题,网上都是这么说的,我之前也是这么理解的: 假设有一个包名字叫 numpy, 里面有一个函数 zeros 1、 from numpy import zeros 那么你可以直接调用 zeros()函数 2、import numpy.zeros 那么你只能使用全名 numpy.zeros 但今天遇到了问题了。 ``` from sklearn import datasets a=datasets.load_digits() print(a) ``` 这个代码没问题 但是下面这个代码居然提示错误 ``` import sklearn a=sklearn.datasets.load_digits() print(a) ``` 提示错误是:AttributeError: module 'sklearn' has no attribute 'datasets' 什么鬼,看不懂,不是说import sklearn 后应该可以通过点.来访问sklearn里的所有内容吗,就像numpy中那样。初学者,不懂,求大神解释下,不胜感激!! 这样也报错 ``` import sklearn.datasets a=datasets.load_digits() print(a) ``` NameError: name 'datasets' is not defined

Linux环境下,在Qt中调用Python,导入第三方库时出错?

有关python的文件列表如下: ![图片说明](https://img-ask.csdn.net/upload/202003/10/1583811655_177622.png) 在Terminal中用python解释器运行时完全正常: ![图片说明](https://img-ask.csdn.net/upload/202003/10/1583811736_800874.png) 在把该py文件加入Qt项目后,运行时出错。 ![图片说明](https://img-ask.csdn.net/upload/202003/10/1583811777_994860.png) 以下是python的调用代码: ``` //【1】初始化 Py_Initialize(); if (!Py_IsInitialized()) { qDebug() << "init python failed"; return; } //【2】添加python模块路径 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('/root/IOLTest/')"); //【3】导入python模块 PyObject* pModule = PyImport_ImportModule("bandpass"); if (!pModule) { qDebug() << "import module bandpass failed"; return; } //【4】获取python函数 PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); if(!pFunhello) { qDebug() << "call hello failed"; return; } //【5】调用python函数 PyObject_CallObject(pFunhello,NULL); //【6】释放python组件 Py_Finalize(); ``` 程序运行到第三步导入python模块时出错,try-except打印的信息是: ``` IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy c-extensions failed. - Try uninstalling and reinstalling numpy. - If you have already done that, then: 1. Check that you expected to use Python3.6 from "/usr/bin/python3", and that you have no directories in your PATH or PYTHONPATH that can interfere with the Python and numpy version "1.18.1" you're trying to use. 2. If (1) looks fine, you can open a new issue at https://github.com/numpy/numpy/issues. Please include details on: - how you installed Python - how you installed numpy - your operating system - whether or not you have multiple versions of Python installed - if you built from source, your compiler versions and ideally a build log - If you're working with a numpy git repository, try `git clean -xdf` (removes all files not under version control) and rebuild numpy. Note: this error has many possible causes, so please don't comment on an existing issue about this - open a new one instead. Original error was: /usr/local/lib/python3.6/dist-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PyExc_ImportError ``` 问题出在导入第三方库上,即 import scipy.signal as signal 这行代码,若是去掉,则可以正常运行。 貌似是Qt里的环境跟Terminal不一样,所以有没有知道原因和解决方案的大牛,还望指点一二。

python的tkinter中的variable封装成类后调用无效?

学校要求开发一个小程序,目前我做了个查询天气的,当查询天气单独使用时,调用正常,可是import查询天气后,就出了bug 主程序代码: ``` from tkinter import * import WEATHER class main_menu: def __init__(self, master): master.title('主菜单') master.geometry('250x100') master.resizable(width=False, height=False) F1 = Frame(master) F2 = Frame(master) F1.pack(side=TOP) F2.pack(side=BOTTOM) weather_buttom = Button(F1, text='天气查询', command=self.init_weather) express_buttom = Button(F1, text='快递查询') plane_buttom = Button(F2, text='机票查询') train_buttom = Button(F2, text='车票查询') weather_buttom.pack(side=LEFT, pady=10, padx=10) express_buttom.pack(side=RIGHT, pady=10, padx=10) plane_buttom.pack(side=LEFT, pady=10, padx=10) train_buttom.pack(side=RIGHT, pady=10, padx=10) def init_weather(self): weather_window = Tk() weather = WEATHER.Weather(weather_window) weather_window.mainloop() if __name__ == '__main__': tk = Tk() main = main_menu(tk) tk.mainloop() ``` 天气查询实现的代码: ``` import time from selenium import webdriver #导入Selenium的webdriver from selenium.webdriver.common.keys import Keys #导入Keys from tkinter import * class Weather: def __init__(self, master): master.title('天气查询') master.resizable(width=False, height=False) F1 = Frame(master) F2 = Frame(master) F1.pack(side=TOP) F2.pack(side=BOTTOM) self.var = StringVar() self.var.set('aaaaa') self.e = Entry(F1) self.e.pack(side=LEFT, padx=5, pady=5) b = Button(F1, text='确认', command=self.__search) b.pack(side=RIGHT, padx=5, pady=5) L = Label(F2, textvariable=self.var, height=3) L.pack(side=BOTTOM) def __search(self): city = self.e.get() print('查询需要一定时间,请稍候...') driver = webdriver.PhantomJS() #指定使用的浏览器,初始化webdriver driver.get("http://www.tianqi.com/") #请求网页地址 assert "天气" in driver.title #看看 关键字 是否在网页title中,如果在则继续,如果不在,程序跳出。 search = driver.find_element_by_xpath('//*[@id="index_serch"]/input') #找到xpath元素,这里是个搜索框 search.clear() #清空搜索框中的内容 search.send_keys(city) #在搜索框中输入city search.send_keys(Keys.RETURN) #相当于回车键,提交 temperature_text = driver.find_element_by_xpath('/html/body/div[5]/div/div[1]/dl/dd[3]/p/b').text temperature_now = '%s当前温度:%s ℃'%(city, temperature_text) weather_text = driver.find_element_by_xpath('/html/body/div[5]/div/div[1]/dl/dd[3]/span/b').text weather_now = '%s当前天气:%s'%(city, weather_text) text = '查询城市:%s\n' \ '%s\n' \ '%s'%(city, weather_now, temperature_now) self.var.set(text) print(text) driver.close() #关闭webdriver if __name__ == '__main__': root = Tk() weather = Weather(root) root.mainloop() ``` 查询天气中的self.var在把查询天气单独使用时,可以正常赋值,而当在menu中调用查询天气,self.var就无效了

python递归式不能正常工作

我写了个个python方法想要归类wikipedia,然后在做递归式的时候想要把导入的parameter更换,可是却改变不了 import csv from bs4 import BeautifulSoup import urllib.request string_set=[] url_link=[] def get_first_category(url): k=urllib.request.urlopen(url) soup=BeautifulSoup(k) s=soup.find_all('a') for i in s: string_set.append(i.string) for i in range(-len(string_set), 0): if string_set[i] == ("Categories"): return (string_set[i + 1]) def join_with(k): return k.replace(" ","_") def get_category_page(k): p=["https://en.wikipedia.org/wiki/Category:",k] return "".join(p) def return_link(url): return (get_category_page(join_with(get_first_category(url)))) file=open("Categories.csv") categories=csv.reader(file) categories=zip(*categories) def find_category(url): k=get_first_category(url) for i in categories: if k in i: return [True,i[0]] return [False,k] category_url='' def main(url): j=find_category(url) if j[0]: return j[1] else: url=return_link(url) print(url) return main(url) #print(return_link('https://en.wikipedia.org/wiki/Category:Mathematics_of_infinitesimals')) print (main('https://en.wikipedia.org/wiki/Category:Charitable_organizations')) 这是我的code,然后 https://www.dropbox.com/s/647hpufvzq0fksk/Categories.csv?dl=0 这是csv的地址,按理说应该会一个个找下去可是parameter被改变一次就不再被改变,已经试了很多方法了可是还是没有办法

python结合grads绘图的问题

``` import grads #导入库 ga=grads.GrADS() #使用GrADS客户端程序,要求GrADS版本大于2.0.0 fh = ga.open("http://monsoondata.org:9090/dods/model") #读取文件 ga("display ps") #显示图形 ga("printim D:/x.png white") #保存图形,将背景设为白色 ``` 在canopy下面运行这个例子,提示下面的错误信息,怎么回事: %run "E:\software\pythonGrads\pygrads-1.1.9\test1.py" 'grads' ²»ÊÇÄÚ²¿»òÍⲿÃüÁҲ²»ÊÇ¿ÉÔËÐеijÌÐò »òÅú´¦ÀíÎļþ¡£ --------------------------------------------------------------------------- GrADSError Traceback (most recent call last) E:\software\pythonGrads\pygrads-1.1.9\test1.py in <module>() 1 # -*- coding: utf-8 -*- 2 from grads.gacore import GaCore ----> 3 ga = GaCore(Bin='grads') # 如果GrADS的版本小于2.0,可以使用ga = GaCore(Bin='gradsnc') 4 fh = ga.open("http://monsoondata.org:9090/dods/model") 5 ga("display ps") E:\software\pythonGrads\pygrads-1.1.9\grads\gacore.pyc in __init__(self, Bin, Echo, Opts, Port, Strict, Verb, Window) 174 # Parse out inital splash screen 175 # ------------------------------- --> 176 rc = self._parseReader() 177 178 # Record GrADS version E:\software\pythonGrads\pygrads-1.1.9\grads\gacore.pyc in _parseReader(self, Quiet) 1037 got = self.Reader.readline() 1038 if got == '': -> 1039 raise GrADSError, "GrADS terminated while waiting for response" 1040 tokens = split(got) 1041 GrADSError: 'GrADS terminated while waiting for response'

MongoDB中string类型日期怎么改为MongoDB的ISODate类型 ?

我是在做csv文件里的数据导入到mongodb数据库中,程序要求是数据库中datetime列的类型为ISODate类型。 我要怎么在插入数据库前或者插入后将格式改为ISODate类型??? 或者可以用python的pandas模块怎么指定列的类型??? 又或者MongoDB 怎么把已经插入的String类型的日期(例:"2017-02-06 21:00:10.500"),改为MongoDB的ISODate类型(例:ISODate("2017-02-06T21:00:10Z"))???跪求解决方法

保存keras模型时出现的问题

求助各路大神,小弟最近用keras跑神经网络模型,在训练和测试时都很好没问题,但是在保存时出现问题 小弟保存模型用的语句: json_string = model.to_json() open('my_model_architecture.json', 'w').write(json_string) #保存网络结构 model.save_weights('my_model_weights.h5',overwrite='true') #保存权重 但是运行后会显示Process finished with exit code -1073741819 (0xC0000005) 然后保存权重的.h5文件没有内容 求助各位大神是怎么回事啊

把中文词限定在一个特定的形状中(中文词云)

用给出的Textboard编写,Textboard可以将一个中文词显示在Frame上,并且可改变其坐标、大小、字体、颜色。 要求利用已经分好的词以及其频率(这个请自行假设)限定这些词在一个特定形状中如:圆、矩形、调用的图片形状。 并且重点必须突出(对比最好鲜明) Textboard以及其测试代码TestTextboard如下 import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Font; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.util.ArrayList; class Scribbling { String what; int xpos; int ypos; double angle; Font font; Color col; } class WritePanel extends JPanel { private Graphics2D g; private ArrayList<Scribbling> text = new ArrayList<Scribbling>(); private void doWriting(Graphics g) { Graphics2D g2d = (Graphics2D) g; Font font = getFont(); Color col = g.getColor(); double angle = 0; AffineTransform orig = g2d.getTransform(); for (Scribbling s: text) { if (s.angle != angle) { g2d.setTransform(orig); g2d.rotate(s.angle * Math.PI / 180.0); angle = s.angle; } if (s.font != null && !s.font.equals(font)) { g2d.setFont(s.font); font = g2d.getFont(); } if (!s.col.equals(col)) { col = new Color(s.col.getRGB()); g2d.setColor(col); } g2d.drawString(s.what, s.xpos, s.ypos); } } public void addText(String what, int xpos, int ypos, double angle, Font font, Color col) { Scribbling s = new Scribbling(); s.what = what; s.xpos = xpos; s.ypos = ypos; s.angle = angle; s.font = font; s.col = col; text.add(s); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doWriting(g); } } /** * Textboard is in fact a full graphical application that displays * text in a graphical Window */ public class TextBoard extends JFrame { private WritePanel board; private double currentAngle; private Color currentColor; private Font currentFont; /** * Only constructor. * * @param width Width of the window in pixels * @param height Height of the window in pixels * @param col Background color */ public TextBoard(int width, int height, Color col) { board = new WritePanel(); // Put the WritePanel into the main window add(board); // Set its background color board.setOpaque(true); board.setBackground(col); // Initial settings currentAngle = 0; currentColor = Color.BLACK; currentFont = getFont(); // Geometry of the main window setSize(width, height); setLocationRelativeTo(null); // When users close the window, we quit the application setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(false); } // Overloaded methods to write text /** * Write text to the screen * <p> * The text can be written at any position, it can be * rotated, the font and color can be changed. Every piece * of text is added to a list, and only written when the * window is drawn. * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top * @param angle Rotation angle in degrees * @param font Font to use to write the text * @param col Text color */ public void write(String what, int xpos, int ypos, double angle, Font font, Color col) { if (currentAngle != angle) { currentAngle = angle; } if (currentFont != null && !currentFont.equals(font)) { currentFont = font; } if (!currentColor.equals(col)) { currentColor = new Color(col.getRGB()); } board.addText(what, xpos, ypos, angle, font, col); } /** * Write text to the screen * <p> * Use the last set angle (0 by default), font and color * (black by default). * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top */ public void write(String what, int xpos, int ypos) { write(what, xpos, ypos, currentAngle, currentFont, currentColor); } /** * Write text to the screen * <p> * Use the last set font and color (black by default), set the angle. * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top * @param angle Rotation angle in degrees */ public void write(String what, int xpos, int ypos, double angle) { write(what, xpos, ypos, angle, currentFont, currentColor); } /** * Write text to the screen * <p> * Use the last set font, set angle and color. * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top * @param angle Rotation angle in degrees * @param col Text color */ public void write(String what, int xpos, int ypos, double angle, Color col) { write(what, xpos, ypos, angle, currentFont, col); } /** * Write text to the screen * <p> * Use the last set angle(0 by default) and font, set the color. * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top * @param col Text color */ public void write(String what, int xpos, int ypos, Color col) { write(what, xpos, ypos, currentAngle, currentFont, col); } /** * Write text to the screen * <p> * Use the last set angle (0 by default), set font and color. * * @param what The text to write * @param xpos Horizontal position in pixels, from the left hand side * @param ypos Vertical position in pixels, from the top * @param font Font to use to write the text * @param col Text color */ public void write(String what, int xpos, int ypos, Font font, Color col) { write(what, xpos, ypos, currentAngle, font, col); } /** * Show the window */ public void display() { this.setVisible(true); } } package com.kennycason.CourseProject; import java.awt.Font; import java.awt.Color; public class TestTextBoard { public static void main(String[] args) { Font font; TextBoard tb = new TextBoard(1000, 700, Color.WHITE); System.out.println("-- Initialized"); font = new Font("SansSerif", Font.BOLD, 60); tb.write("Hello", 160, 500, font, Color.YELLOW); font = new Font("SansSerif", Font.BOLD, 150); tb.write("chinese", 150, 300, 10, font, new Color(250, 230, 241)); tb.write("Tally ho", 500, 500); font = new Font("SansSerif", Font.BOLD, 80); tb.write("Awesome!", 60, 200,90, font, Color.BLACK); System.out.println("-- Written"); tb.display(); System.out.println("-- Displayed (be patient, it's coming ...)"); } }

想要在一个.py里调用另一个.py但是有错?

主程序如下,num想给图片编号,但是调用有问题 ``` # -*- coding: UTF-8 -*- #!/usr/bin/env python #前进1m,画边长( 0.6 )m的五边形 import rospy from geometry_msgs.msg import Twist from math import radians import trying class ROUTE(): count = 0 num = 0 def __init__(self): # 初始化节点 rospy.init_node('route', anonymous=True) # ctrl + c退出 rospy.on_shutdown(self.shutdown) self.cmd_vel = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10) # 5 HZ更新频率 r = rospy.Rate(5); # 两个不同的Twist,转,直走 # 0.5 m/s 前进 move_cmd = Twist() move_cmd.linear.x = 0.2 #旋转18 deg/s turn_cmd = Twist() turn_cmd.linear.x = 0 turn_cmd.angular.z = radians(18); # 前进1M rospy.loginfo("我在找位置ing") for x in range(0,25): self.cmd_vel.publish(move_cmd) r.sleep() while not rospy.is_shutdown(): #来拍照啊 rospy.loginfo("123,茄子!") for x in range(0,15): trying.TakePhoto( num ) num = num + 1 r.sleep() #转54度 rospy.loginfo("好丑~我换个角度哈~") for x in range(0,15): self.cmd_vel.publish(turn_cmd) r.sleep() # 前进0.5M rospy.loginfo("我在找下一个位置ing") for x in range(0,15): self.cmd_vel.publish(move_cmd) r.sleep() # 转234度 rospy.loginfo("就在这里拍啦!") for x in range(0,65): self.cmd_vel.publish(turn_cmd) r.sleep() count = count + 1 if(count == 5): count = 0 if(count == 0): rospy.loginfo("是不是该结束了?好累哦~~") if( num > 7): rospy.loginfo("都要没电啦……停下来吧……机器人也很累呀!") def shutdown(self): # 停啦 rospy.loginfo("停啦,么么哒,记得充电~~") self.cmd_vel.publish(Twist()) rospy.sleep(1) if __name__ == '__main__': try: ROUTE() except: rospy.loginfo("Bye~~") rospy.sleep(1) ``` 调用的trying.py如下: ``` # -*- coding: UTF-8 -*- #!/usr/bin/env python from __future__ import print_function import sys import rospy import cv2 from std_msgs.msg import String from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class TakePhoto ( num ): def __init__(self): self.bridge = CvBridge() self.image_received = False # Connect image topic img_topic = "/camera/rgb/image_raw" self.image_sub = rospy.Subscriber(img_topic, Image, self.callback) # Allow up to one second to connection rospy.sleep(1) def callback(self, data): # Convert image to OpenCV format try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) self.image_received = True self.image = cv_image def take_picture(self, img_title): if self.image_received: # Save an image cv2.imwrite(img_title, self.image) return True else: return False # Initialize rospy.init_node('take_photo', anonymous=False) camera = TakePhoto() # Take a photo # Use '_image_title' parameter from command line # Default value is 'photo.jpg' img_title = rospy.get_param('~image_title', num+'.jpg') if camera.take_picture(img_title): rospy.loginfo("保存啦 " + img_title) else: rospy.loginfo("没有吧……") # Sleep to give the last log messages time to be sent rospy.sleep(1) ``` 报错: Traceback (most recent call last): File "route.py", line 10, in <module> import trying File "/home/hazel/helloworld/turtlebot/trying.py", line 13, in <module> class TakePhoto ( num ): NameError: name 'num' is not defined 自己感觉没有错……前两次都是缩进的问题,现在专门全部改成了Tab键,就算吧num全部删掉,它也不调用直接退出了,我觉得是函数调用的问题

smtplib断开连接:连接意外关闭?

Python—爬虫之实操项目:将爬取的数据定时发送邮件‘ import requests #导入requests库 import smtplib #发送邮件使用 import schedule #定时发送 import time #时间模块 from bs4 import BeautifulSoup #导入BeautifulSoup from email.mime.text import MIMEText #构建邮件内容 from email.header import Header #构建邮件头 #输入隐私信息 mailbox = input('请输入你的邮箱:') password = input('请输入你的密码:') receiver = input('请输入收件人的邮箱') #爬取数据 def foods(): url = 'http://www.xiachufang.com/explore/' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'} res = requests.get(url,headers = headers) soup = BeautifulSoup(res.text,'html.parser') list_foods = soup.find_all('div',class_ = 'info pure-u') list_all = [] for food in list_foods: title = food.find('a').text.strip() herf = 'http://www.xiachufang.com' + food.find('a')['href'] pei_l = food.find('p',class_ = 'ing ellipsis').text.strip() list_all.append([title,herf,pei_l]) return list_all #发送邮件 def send_email(list_all): global mailbox,password,receiver #设置为全局变量 mailhost = 'smtp.qq.com' qqmail = smtplib.SMTP() qqmail.connect(mailhost,46) qqmail.login(mailbox,password) content = list_all massage = MIMEText(content,'plain','utf-8') subject = '本周最受欢迎菜谱' message['subject'] = Header(subject,'utf-8') try: qqmail.sendmail(mailbox,receiver,message.as_string()) print('邮件发送成功') except: print('邮件发送失败') qqmail.quit() #定时执行任务 def job(): print('开始执行') list_all = foods() #调取爬取数据的函数并将结果赋值给新变量 send_email(list_all) #调取发送邮件的函数,并传入邮件内容 print('任务完成') schedule.every().day.at("10:30").do(job) #设定每天10:30执行任务 while True: #当符合条件的情况下就执行任务 schedule.run_pending() time.sleep(2) Traceback (most recent call last): File "D:\hello-world.py\youjian4.py", line 10, in <module> qqmail.connect(mailhost,465) File "D:\py\lib\smtplib.py", line 338, in connect (code, msg) = self.getreply() File "D:\py\lib\smtplib.py", line 394, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed 总是出现这个问题,请问该怎么解决

Python关于AES加密程序的运行出现error,有大神相助吗?

代码如下:(AES CBC模式加密) ``` # 导入图像处理标准库 from PIL import Image # 导入Cryptodome库,引用aes加密模块 from Cryptodome import AES import random import string # 随机生成16个由小写字母组成的字符串 def key_generator(size = 16, chars = string.ascii_lowercase): return ''.join(random.choice(chars) for _ in range(size)) #filename = "d:/blackhat.bmp" #filename_encrypted_cbc = "blackhat_encrypted_cbc" #formatt = "BMP" # 利用函数随机生成一个由小写字母组成的字符串 #key = key_generator(16) #print("key:"+key) # AES加密的明文空间为16的整数倍,不能整除,则需要进行填充 # 在对应的ascii中,"\x00"表示为0x00,具体的值为NULL,b表示以字节表示 def pad(data): return data + b"\x00" * (16 - len(data) % 16) # 将图像的数据映射为RGB def trans_format_rbg(data): # tuple:不可变,保证数据不丢失 red, green, blue = tuple(map(lambda e: [data[i] for i in range(0, len(data)) if i % 3 == e], [0, 1, 2])) pixels = tuple(zip(red, green, blue)) return pixels # CBC加密 def aes_cbc_encrypt(key1, data, mode=AES.MODE_CBC): # iv为随机值 iv = key_generator(16) aes = AES.new(key1, mode, iv) new_data = aes.encrypt(data) return new_data def encrypt_image_cbc(filename1): # 打开bmp图片,然后将之转换为RGB图像 im = Image.open(filename1) value_vector = im.convert("RGB").tobytes() # 将图像数据转换为像素值字节 imlength = len(value_vector) # 将填充、加密后的数据进行像素值映射 value_encrypt = trans_format_rbg(aes_cbc_encrypt(key, pad(value_vector))[:imlength]) # 创建一个新对象,存储相对应的值 im2 = Image.new(im.mode, im.size) im2.putdata(value_encrypt) # 将对象保存为对应格式的图像 im2.save(filename_encrypted_cbc + "." + formatt, format) # im2.save(filename_encrypted_cbc+".bmp") key = key_generator(16) filename = "d:/blackhat.bmp" filename_encrypted_cbc = "blackhat_encrypted_cbc" formatt = "BMP" encrypt_image_cbc(filename) im = Image.open(filename) im.show() ``` 运行后出现如下错误: Traceback (most recent call last): File "C:/Users/GYW/PycharmProjects/untitled/CBC encrypt", line 74, in <module> encrypt_image_cbc(filename) File "C:/Users/GYW/PycharmProjects/untitled/CBC encrypt", line 59, in encrypt_image_cbc value_encrypt = trans_format_rbg(aes_cbc_encrypt(key, pad(value_vector))[:imlength]) File "C:/Users/GYW/PycharmProjects/untitled/CBC encrypt", line 45, in aes_cbc_encrypt aes = AES.new(key1, mode, iv) File "C:\Users\GYW\PycharmProjects\untitled\venv\lib\site-packages\Cryptodome\AES.py", line 232, in new return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs) File "C:\Users\GYW\PycharmProjects\untitled\venv\lib\site-packages\Cryptodome\Cipher\__init__.py", line 79, in _create_cipher return modes[mode](factory, **kwargs) File "C:\Users\GYW\PycharmProjects\untitled\venv\lib\site-packages\Cryptodome\Cipher\_mode_cbc.py", line 274, in _create_cbc_cipher cipher_state = factory._create_base_cipher(kwargs) File "C:\Users\GYW\PycharmProjects\untitled\venv\lib\site-packages\Cryptodome\AES.py", line 103, in _create_base_cipher result = start_operation(c_uint8_ptr(key), File "C:\Users\GYW\PycharmProjects\untitled\venv\lib\site-packages\Cryptodome\Util\_raw_api.py", line 238, in c_uint8_ptr raise TypeError("Object type %s cannot be passed to C code" % type(data)) TypeError: Object type <class 'str'> cannot be passed to C code Process finished with exit code 1 刚接触python 求大神拉一把~

vue 修改的时候报undefind错误

<template> <el-container v-loading="loadingData" style="height: 100%" class="app-container calendar-list-container"> <el-header height="62px" class="filter-container"> <el-row> <el-col :span="21"> <el-form :inline="true" :model="formSearch" class="demo-form-inline"> <el-form-item> <el-input v-model="formSearch.value" placeholder="请输入水道名称" clearable></el-input> </el-form-item> <el-form-item> <el-select v-model="formSearch.type" filterable clearable placeholder="请选择水道类型"> <el-option v-for="item in dataType" :key="item.value" :label="item.text" :value="item.value"> </el-option> </el-select> </el-form-item> <el-form-item> <el-select v-model="formSearch.official" placeholder="请选择水道性质" filterable clearable> <el-option key="true" label="正式水道" value="true"></el-option> <el-option key="false" label="测试水道" value="false"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="loadMain" size="small" icon="el-icon-search" round>搜索</el-button> </el-form-item> </el-form> </el-col> <el-col :span="3" style="text-align: right"> <el-button @click="handleAdd" v-show="visibleBtnAdd" type="success" size="small" icon="el-icon-plus" round>新增水道</el-button> </el-col> </el-row> </el-header> <el-main ref="layoutMain" class="table-container"> <el-table :data="dataMain" :height="heightMain" stripe highlight-current-row class="el-table-border"> <el-table-column prop="name" label="水道名称"></el-table-column> <el-table-column prop="swzName" label="水位站"></el-table-column> <el-table-column prop="typeName" label="水道类型" width="100"></el-table-column> <el-table-column prop="isOfficial" label="水道性质" align="center" width="100" :formatter="formatOfficial"></el-table-column> <el-table-column prop="startName" label="水道起点" width="100"></el-table-column> <el-table-column prop="endName" label="水道讫点" width="100"></el-table-column> <el-table-column label="里程" width="100"> <template slot-scope="scope">{{ Math.abs(scope.row.endMileage - scope.row.startMileage) + '公里' }}</template> </el-table-column> <el-table-column prop="remark" label="水道概况" width="200"></el-table-column> <el-table-column label="操作" align="center" fixed="right" width="150"> <template slot-scope="scope"> <el-button @click="handleEdit(scope.row)" v-show="visibleBtnEdit" type="primary" size="mini" round plain>编辑</el-button> <el-button @click="handleDelete(scope.row)" v-show="visibleBtnDelete" type="danger" size="mini" round plain>删除</el-button> </template> </el-table-column> </el-table> </el-main> <el-footer> <el-pagination @size-change="handlePageSizeChange" @current-change="handlePageCurrentChange" :current-page="dataPage" :page-sizes="[10, 20, 50, 100]" :page-size="dataSize" :total="dataTotal" layout="total, sizes, prev, pager, next, jumper"> </el-pagination> </el-footer> <el-dialog :title="dataRecordTitle[actionDialogRecord]" :visible.sync="visibleDialogRecord" :close-on-click-modal="false" :before-close="handleClose" > <el-form class="large-space" ref="formRecord" :model="formRecord" :rules="ruleRecord" label-position="left" label-width="90px"> <el-row :gutter="24"> <el-col :span="4"><strong>图片信息</strong></el-col> <el-col :span="20"> <el-upload :action="imageUpload" :headers="headers" :with-credentials="true" list-type="picture-card" :file-list="formRecord.waterInfomationPicDTO" :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview" :before-upload="beforeAvatarUpload" :on-remove="handleRemove" style="float: left; margin-bottom: 10px"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible" size="tiny"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </el-col> </el-row> <el-form-item label="水道名称" prop="name"> <el-input v-model="formRecord.name"></el-input> </el-form-item> <el-row :gutter="20"> <el-col :span="12"><el-form-item label="水道类型" prop="type"> <el-select v-model="formRecord.type" filterable placeholder="请选择水道类型" style="width: 100%"> <el-option v-for="item in dataType" :key="item.value" :label="item.text" :value="item.value"> </el-option> </el-select> </el-form-item></el-col> <el-col :span="12"><el-form-item label="水道性质" prop="official"> <el-switch v-model="formRecord.official" :disabled.sync="disabledSelOfficial" active-text="正式水道" inactive-text="测试水道" ></el-switch> </el-form-item></el-col> </el-row> <!-- <el-form-item label="位置" prop="waterway"> <map-box v-loading="loadingWaterway" @mapReady="handleMapReady" class="map-box"></map-box> </el-form-item> --> <el-row :gutter="20"> <el-col :span="12"><el-form-item label="水道起点" prop="start"> <el-select ref="selStart" v-model="formRecord.start" filterable placeholder="请选择水道起点" style="width: 100%"> <el-option v-for="item in dataNode" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select> </el-form-item></el-col> <el-col :span="12"><el-form-item label="水道讫点" prop="end"> <el-select ref="selEnd" v-model="formRecord.end" filterable placeholder="请选择水道讫点" style="width: 100%"> <el-option v-for="item in dataNode" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select> </el-form-item></el-col> </el-row> <el-row :gutter="20"> <el-col :span="12"><el-form-item label="水位站" prop="swzId"> <el-select ref="selStation" v-model="formRecord.swzId" filterable placeholder="请选择关联水位站" style="width: 100%"> <el-option v-for="item in dataWaterStation" :key="item[0]" :label="item[1]" :value="item[0]"> </el-option> </el-select> </el-form-item></el-col> </el-row> <el-form-item label="水道概况" prop="remark"> <el-input type="textarea" v-model="formRecord.remark"></el-input> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="handleCancel">取消</el-button> <el-button @click="handleSave" type="primary">保存</el-button> </div> </el-dialog> </el-container> </template> <style rel="stylesheet/scss" lang="scss" scoped> .map-box { height: 200px; overflow: auto; border: 1px solid #ebeef5; } </style> <script> import $ from 'jquery' import waves from '@/directive/waves/index.js' import MapBox from '@/components/mapBox.vue' import { addGraphicsLayer, RAddListGraphic, RegClick } from '@/filters/RMapUitl.js' import { queryWaterwayList, queryWaterwayPointList, waterInfomationList } from '@/api/base/waterway' import { debounce, getTableHeight } from '@/utils' import { queryNodeList } from '@/api/base/node' import { queryChannelTypeList, queryChannelFullList, queryChannelAdd, queryChannelEdit, queryChannelDelete } from '@/api/base/channel' import { fetchSelectData, getCoordinate, addWaterStation, getWaterStation, updateWaterStation, getUpload, deletePicByid, fetchCjjmDetail } from '@/api/water/waterStation.js' import {getToken} from '@/utils/auth' // 验权 export default { name: 'channel_page', directives: { waves }, components: { MapBox }, data() { return { visibleBtnAdd: true, visibleBtnEdit: true, visibleBtnDelete: true, formSearch: { type: undefined, value: '', official: undefined }, formRecord: { id: null, name: '', type: null, official: false, waterway: null, startId: null, endId: null, start: null, end: null, swzId: null, remark: '', waterInfomationPicDTO: [] }, imageUpload: getUpload(), headers: {'X-Token': getToken()}, heightMain: getTableHeight(10), dataWaterway: [], dataWaterStation: [], dataType: [], dataNode: [], dataMain: [], dataTotal: 0, dataPage: 1, dataSize: 10, loadingData: false, loadingWaterway: false, visibleDialogRecord: false, disabledSelOfficial: false, actionDialogRecord: '', fullscreenLoading: false, dialogVisible: false, dialogImageUrl: '' } }, computed: { ruleRecord: () => { return { name: [ { required: true, message: '请输入水道名称', trigger: 'blur' }, { max: 30, message: '长度不得超过30个字符', trigger: 'blur' } ], type: [ { required: true, message: '请选择水道类型', trigger: 'blur' } ], waterway: [ { required: true, message: '请选择水道位置', trigger: 'blur' } ], start: [ { required: true, message: '请选择水道起点', trigger: 'blur' } ], end: [ { required: true, message: '请选择水道讫点', trigger: 'blur' } ], swzId: [ { required: true, message: '请选择水位站', trigger: 'blur' } ], remark: [ { max: 100, message: '长度不得超过100个字符', trigger: 'blur' } ] } }, dataRecordTitle: () => { return { add: '新增水道', edit: '编辑水道' } } }, beforeDestroy() { window.removeEventListener('resize', this.__resizeHanlder) }, mounted() { this.__resizeHanlder = debounce(() => { this.heightMain = getTableHeight(10) }, 100) window.addEventListener('resize', this.__resizeHanlder) this.loadMain() queryChannelTypeList(null, result => { this.dataType = result }) this.dataWaterway = [] queryWaterwayList(null, result => { if (result) { for (const i in result) { const record = result[i] queryWaterwayPointList({ 'waterway': record.id }, ((me, polyline) => { return result => { if (result) { for (const i in result) { const record = result[i] if (polyline.geometry.length > 0) { polyline.geometry += '#' } polyline.geometry += record.long + ',' + record.lat } } me.dataWaterway.push(polyline) } })(this, { 'id': record.id, 'xtype': 'polyline', 'style': { 'stype': 'lineSymbol' }, 'geometry': '' })) } } }), // 新建水道->水位站选项数据获取 waterInfomationList(null, result => { if (result) { this.dataWaterStation = result } }) }, methods: { // 上传照片之前判断是否符合格式要求 beforeAvatarUpload(file) { // 照片格式 const picArr = ['image/jpeg', 'image/JPEG', 'image/png', 'image/PNG'] // 照片大小 const isLt2M = file.size / 1024 / 1024 < 2 // 一次上传照片数量 const maxLength = this.formRecord.waterInfomationPicDTO.length < 5 if (picArr.indexOf(file.type) < 0) { this.$message.error('上传图片只能是 JPG 或者 PNG 格式!') return false } if (!maxLength) { this.$message.error('图片最多只能上传五张!') return false } if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!') return false } this.imgLoading = true }, // 上传照片成功 handleAvatarSuccess(res) { if (res.status) { const urlObj = {} urlObj.url = res.imageUrl this.formRecord.waterInfomationPicDTO.push(urlObj) this.imgLoading = false } }, // 删除照片 handleRemove(file, fileList) { deletePicByid(file.id).then(() => { }) this.formRecord.waterInfomationPicDTO = fileList }, // 放大图片 handlePictureCardPreview(file) { this.dialogImageUrl = file.url this.dialogVisible = true }, beforeClose() { this.$refs.formRecord.resetFields() this.actionDialogRecord = '' this.disabledSelOfficial = false this.formRecord.id = null this.formRecord.name = '' this.formRecord.type = null this.formRecord.official = false this.formRecord.waterway = null this.formRecord.startId = null this.formRecord.endId = null this.formRecord.swzId = null this.formRecord.remark = '' }, resetSearch() { this.formSearch.type = undefined this.formSearch.value = '' this.formSearch.official = undefined this.dataPage = 1 }, loadNode() { debugger const param = {} if (this.formRecord.waterway !== null) { param.waterway = this.formRecord.waterway } queryNodeList(param, result => { this.dataNode = result }, null, () => { if (this.formRecord.start) { this.formRecord.startId = this.formRecord.start } if (this.formRecord.end) { this.formRecord.endId = this.formRecord.end } this.formRecord.start = null this.formRecord.end = null for (const i in this.dataNode) { const node = this.dataNode[i] if (this.formRecord.startId && node.id === this.formRecord.startId) { this.formRecord.start = node.id } if (this.formRecord.endId && node.id === this.formRecord.endId) { this.formRecord.end = node.id } } }) }, loadMain() { this.loadingData = true const param = {} if (this.formSearch.type) { param.type = this.formSearch.type } if (this.formSearch.value) { param.value = this.formSearch.value } if (this.formSearch.official) { param.isOfficial = this.formSearch.official } queryChannelFullList(param, this.dataPage, this.dataSize, (data, total) => { if (data) { this.dataMain = data } else { this.dataMain = [] } if (total) { this.dataTotal = total } else { this.dataTotal = this.dataMain.length } }, null, () => { this.loadingData = false }) }, formatOfficial(row, column) { const value = row[column.property] if (value === undefined || value === null) { return '' } else { if (value === true || value === 'true' || value === '1') { return '正式水道' } else { return '测试水道' } } }, handleMapReady() { this.loadingWaterway = true addGraphicsLayer({ 'type': 'GraphicsLayer', 'layerid': 'WaterwayLayer' }, (me => { return layer => { RAddListGraphic(layer, me.dataWaterway) RegClick(layer, me.handleMapLineClick) } })(this)) this.loadingWaterway = false }, handleMapLineClick(evt) { this.formRecord.waterway = evt.graphic.attributes.id this.loadNode() }, handleAdd() { this.loadNode() this.actionDialogRecord = 'add' this.visibleDialogRecord = true }, handleEdit(r) { this.disabledSelOfficial = true this.formRecord.id = r.id this.formRecord.name = r.name this.formRecord.type = r.typeId this.formRecord.official = r.isOfficial //this.formRecord.waterway = r.waterwayId this.formRecord.startId = r.startId this.formRecord.endId = r.endId this.formRecord.remark = r.remark this.loadNode() this.actionDialogRecord = 'edit' this.visibleDialogRecord = true }, handleDelete(r) { this.$confirm('确认删除?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { this.fullscreenLoading = true queryChannelDelete({ 'id': r.id }, () => { this.resetSearch() this.loadMain() this.$notify({ type: 'success', title: '成功', message: '操作成功!' }) }, null, () => { this.fullscreenLoading = false }) }) }, handlePageSizeChange(v) { this.dataSize = v this.loadMain() }, handlePageCurrentChange(v) { this.dataPage = v this.loadMain() }, handleSave() { this.$refs.formRecord.validate((valid) => { if (valid) { const param = { 'name': this.formRecord.name, 'type': this.formRecord.type, 'waterway': this.formRecord.waterway, 'start': this.formRecord.start, 'end': this.formRecord.end, 'swzId': this.formRecord.swzId, 'sdzp': this.formRecord.waterInfomationPicDTO } if (this.formRecord.remark) { param['remark'] = this.formRecord.remark } const done = () => { this.handleCancel() this.resetSearch() this.loadMain() this.$notify({ type: 'success', title: '成功', message: '操作成功!' }) } const always = () => { this.fullscreenLoading = false } this.fullscreenLoading = true switch (this.actionDialogRecord) { case 'add': param['isOfficial'] = this.formRecord.official queryChannelAdd(param, done, null, always) break case 'edit': param['id'] = this.formRecord.id param['waterway'] = 0 queryChannelEdit(param, done, null, always) break default: always() } } else { return false } }) }, handleCancel() { this.beforeClose() this.visibleDialogRecord = false }, handleClose(done) { this.beforeClose() done() } } } </script>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

C 语言编程 — 堆栈与内存管理

目录 文章目录目录前文列表堆、栈内存管理动态分配内存重新调整内存的大小和释放内存 前文列表 《程序编译流程与 GCC 编译器》 《C 语言编程 — 基本语法》 《C 语言编程 — 基本数据类型》 《C 语言编程 — 变量与常量》 《C 语言编程 — 运算符》 《C 语言编程 — 逻辑控制语句》 《C 语言编程 — 函数》 《C 语言编程 — 高级数据类型 — 指针》 《C 语言编程 — 高级数据类...

实时更新:计算机编程语言排行榜—TIOBE世界编程语言排行榜(2020年6月份最新版)

内容导航: 1、TIOBE排行榜 2、总榜(2020年6月份) 3、本月前三名 3.1、C 3.2、Java 3.3、Python 4、学习路线图 5、参考地址 1、TIOBE排行榜 TIOBE排行榜是根据全世界互联网上有经验的程序员、课程和第三方厂商的数量,并使用搜索引擎(如Google、Bing、Yahoo!)以及Wikipedia、Amazon、YouTube统计出排名数据。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

立即提问
相关内容推荐