前端技术
HTML
CSS
Javascript
前端框架和UI库
VUE
ReactJS
AngularJS
JQuery
NodeJS
JSON
Element-UI
Bootstrap
Material UI
服务端和客户端
Java
Python
PHP
Golang
Scala
Kotlin
Groovy
Ruby
Lua
.net
c#
c++
后端WEB和工程框架
SpringBoot
SpringCloud
Struts2
MyBatis
Hibernate
Tornado
Beego
Go-Spring
Go Gin
Go Iris
Dubbo
HessianRPC
Maven
Gradle
数据库
MySQL
Oracle
Mongo
中间件与web容器
Redis
MemCache
Etcd
Cassandra
Kafka
RabbitMQ
RocketMQ
ActiveMQ
Nacos
Consul
Tomcat
Nginx
Netty
大数据技术
Hive
Impala
ClickHouse
DorisDB
Greenplum
PostgreSQL
HBase
Kylin
Hadoop
Apache Pig
ZooKeeper
SeaTunnel
Sqoop
Datax
Flink
Spark
Mahout
数据搜索与日志
ElasticSearch
Apache Lucene
Apache Solr
Kibana
Logstash
数据可视化与OLAP
Apache Atlas
Superset
Saiku
Tesseract
系统与容器
Linux
Shell
Docker
Kubernetes
[TypeError esplit is ...]的搜索结果
这里是文章列表。热门标签的颜色随机变换,标签颜色没有特殊含义。
点击某个标签可搜索标签相关的文章。
点击某个标签可搜索标签相关的文章。
转载文章
...图片上传过程中出现的TypeError: e.split is not a function等错误,开发者不仅需要理解其背后的原因(即尝试将数组当作字符串处理),还应当关注不同平台API特性和兼容性问题。为了确保在各终端(如微信小程序、H5、App等)上都能稳定运行,建议开发者遵循官方文档指导,并结合社区讨论和实践案例不断优化代码逻辑。 此外,随着移动应用对数据安全及隐私保护要求的提高,uni-app在处理用户上传图片时也需注重合规性。比如,明确告知用户图片用途、存储期限,并在必要时对上传图片进行压缩或加密处理,降低因图片过大导致的性能瓶颈,同时也避免了潜在的数据泄露风险。 深入解读uni-app的图片上传机制,不难发现其与Web开发中的FormData、Blob对象以及移动端特有的临时文件路径管理有诸多相似之处。开发者可借鉴Web前端领域成熟的解决方案,结合uni-app生态内丰富的插件资源,实现更高效、安全且用户体验良好的图片上传功能。 综上所述,uni-app图片上传功能的完善既依赖于开发者对框架本身特性的掌握,也离不开对行业规范、技术趋势的敏锐洞察与灵活运用。通过持续学习与实践,开发者能够更好地应对各种场景下可能出现的问题,并打造出体验优良、适应多端环境的应用产品。
2023-03-05 15:38:13
59
转载
Javascript
...理解和解决这个常见的问题。 1. 错误概述 “Script did not run”的含义 首先,“Script did not run”是一个相对宽泛的错误提示,它可能指向多种情况,比如脚本文件加载失败、语法错误导致脚本无法执行、或者是由于某些特定条件未满足,使得脚本逻辑跳过或中断执行等。下面我们将逐一分析并给出实例说明。 示例1:脚本加载失败 javascript // 假设我们在HTML中引用了一个不存在的JS文件 在此例中,当浏览器尝试加载non_existent_script.js但找不到该文件时,就会出现“Script did not run”的错误提示。 2. 语法错误导致脚本无法执行 语法错误是初学者最常见的问题之一,也是引发“Script did not run”报错的原因。 javascript // 一个带有语法错误的示例 function test() { console.log("Hello, world!" } test(); // 缺少闭合括号,因此脚本无法执行 在上述例子中,由于函数体内的字符串没有正确闭合,JavaScript引擎在解析阶段就会抛出错误,从而导致整个脚本停止执行。 3. 脚本逻辑错误与异常处理不当 有时,即使脚本文件成功加载且语法无误,也可能因为内部逻辑错误或者异常未被捕获而触发“Script did not run”。 javascript // 逻辑错误示例,试图访问null对象的属性 let obj = null; console.log(obj.property); // 抛出TypeError异常,脚本在此处终止执行 // 异常处理改进方案: try { console.log(obj.property); } catch (error) { console.error('An error occurred:', error); } 在这个案例中,当尝试访问null对象的属性时,JavaScript会抛出TypeError异常。要是不处理这种异常情况,脚本就可能会被迫“撂挑子”,然后闹出个“脚本没运行起来”的状况。 4. 解决策略与思考过程 面对“Script did not run”的问题,我们的解决步骤可以归纳为以下几点: - 检查资源加载:确保所有引用的JavaScript文件都能正常加载,路径是否正确,文件是否存在。 - 审查语法:使用文本编辑器的语法高亮功能或IDE的错误提示,快速定位并修复语法错误。 - 调试逻辑:利用浏览器的开发者工具(如Chrome DevTools),通过断点、步进、查看变量值等方式,逐步排查程序逻辑中的问题。 - 善用异常处理:在可能出现错误的地方使用try...catch结构,对异常进行妥善处理,避免脚本因未捕获的异常而终止执行。 总的来说,“Script did not run”虽是一个看似简单的错误提示,但它背后隐藏的问题却需要我们根据具体情况进行细致入微的排查和解决。希望以上的代码实例和讨论能真正帮到你,让你对这个问题有个更接地气的理解,然后在实际操作时,能够迅速找到解题的“灵丹妙药”。在寻找答案、解决难题的过程中,咱们得拿出十足的耐心和细致劲儿,就像那侦探查案一样,得像剥洋葱那样一层层揭开谜团,最后,真相总会大白于天下。
2023-03-26 16:40:33
374
柳暗花明又一村
Javascript
...Script:面对“TypeError: null 或 undefined 不能作为对象使用” 在JavaScript的世界里,我们常常会遇到各种各样的错误提示,其中“TypeError: null 或 undefined 不能作为对象使用”可能是新手开发者最常遇到的一个挑战。嘿,兄弟!这篇文啊,就是想带你一起深挖问题的底细,给你支招解难题,顺便还用实际的编程代码例子,让你看得懂,学得会,以后再遇到这种情况,就能轻松绕过那些坑,玩转你的代码世界!咱们边聊边学,一起把这事儿搞定,怎么样? 1. 问题概述 当我们尝试使用null或undefined去调用一个方法或访问一个属性时,JavaScript引擎会抛出上述错误。哎呀,你知道吗?在JavaScript的世界里,null和undefined就像是一些空空如也的盒子。你不能指望从这些盒子里拿出什么东西来用,对吧?比如说,你打算用它们做点什么运算或者访问某个属性,但JavaScript可不知道该拿这些空盒子怎么办。所以,当它尝试去处理这些空空如也的东西时,就会出现错误或者奇怪的行为。这就是为什么我们说null和undefined表示“无值”的原因了。它们就像是编程中的空白页,需要我们用实际的数据来填充。 2. 理解null和undefined - null:通常用于表示变量已经被赋值为“空”或“没有值”。它是一个特殊的值,用于明确表示某个变量或引用的对象不存在。 - undefined:当一个变量未被初始化时,其默认值就是undefined。此外,函数的参数在调用函数之前也是undefined。 3. 代码示例 理解错误原因 假设我们有一个函数getInfo,用于获取用户信息: javascript function getInfo(userId) { return users[userId]; } const users = {}; console.log(getInfo(1)); // undefined, 因为users中没有id为1的用户 这里,由于users对象中不存在userId对应的键,因此getInfo返回的是undefined。如果我们在使用这个函数时直接使用getInfo()(即传入null或undefined),会发生什么呢? javascript console.log(getInfo(null)); // TypeError: Cannot read properties of null (reading 'userId') 4. 避免错误的策略 4.1 使用条件判断 在调用可能返回null或undefined的方法前,先检查是否为null或undefined: javascript function safeGetInfo(userId) { if (userId !== null && userId !== undefined) { return users[userId]; } else { console.log("User ID not found."); return null; // 或者抛出异常,取决于你的应用需求 } } console.log(safeGetInfo(1)); // 正常返回用户信息 console.log(safeGetInfo(null)); // 输出警告信息并返回null 4.2 使用默认值 在访问属性时,可以使用?.操作符(三元点)或.()(括号访问)来避免错误: javascript const user = users[1] ?? "User not found"; // 使用三元点操作符 // 或者 const user = users[1] || "User not found"; // 使用逻辑或运算符 // 或者使用括号访问 const user = users[(userId === null || userId === undefined) ? "User not found" : userId]; 4.3 使用try...catch块 对于更复杂的逻辑,可以使用try...catch结构来捕获并处理错误: javascript try { const user = users[userId]; } catch (error) { console.error("An error occurred:", error); } 5. 结语 面对“TypeError: null 或 undefined 不能作为对象使用”这样的错误,关键在于理解null和undefined的本质以及它们在JavaScript中的作用。嘿,兄弟!要想避免那些烦人的错误,咱们就得在代码上下点功夫了。比如说,咱们可以用条件判断来分清楚啥时候该做啥,啥时候不该动。再比如,设置个默认值,让程序知道如果啥都没给,就用这个值顶替,免得因为参数没填出问题。还有,咱们别忘了加个错误处理机制,万一程序遇到啥意外,咱就能及时捕捉到,不让它胡乱操作,把事儿搞砸了。这样,咱们的代码就更稳健,更不容易出岔子了!嘿,兄弟!每次你碰到点小错误,那可不就是一次大大的学习机会嘛!就像是在玩游戏时不小心踩了个坑,结果发现了一个新宝藏!你得动手实践,多想想为什么会这样,下次怎么避免。就像你做菜时,多试几次,找到那个完美的味道一样。这样一步步走来,你编程的路就会越走越稳,越来越自信!
2024-07-27 15:32:00
299
醉卧沙场
转载文章
....api.java.function.Function;import org.apache.spark.api.java.function.Function2;import org.apache.spark.api.java.function.PairFunction;import org.apache.spark.api.java.function.VoidFunction;import org.apache.spark.sql.DataFrame;import org.apache.spark.sql.Row;import org.apache.spark.sql.RowFactory;import org.apache.spark.sql.hive.HiveContext;import org.apache.spark.sql.types.DataTypes;import org.apache.spark.sql.types.StructType;import org.apache.spark.streaming.Durations;import org.apache.spark.streaming.api.java.JavaDStream;import org.apache.spark.streaming.api.java.JavaPairDStream;import org.apache.spark.streaming.api.java.JavaPairInputDStream;import org.apache.spark.streaming.api.java.JavaStreamingContext;import org.apache.spark.streaming.api.java.JavaStreamingContextFactory;import org.apache.spark.streaming.kafka.KafkaUtils;import com.google.common.base.Optional;import scala.Tuple2;/ 数据处理,Kafka消费者/public class AdClickedStreamingStats {/ @param args/public static void main(String[] args) {// TODO Auto-generated method stub//好处:1、checkpoint 2、工厂final SparkConf conf = new SparkConf().setAppName("SparkStreamingOnKafkaDirect").setMaster("hdfs://Master:7077/");final String checkpointDirectory = "hdfs://Master:9000/library/SparkStreaming/CheckPoint_Data";JavaStreamingContextFactory factory = new JavaStreamingContextFactory() {public JavaStreamingContext create() {// TODO Auto-generated method stubreturn createContext(checkpointDirectory, conf);} };/ 可以从失败中恢复Driver,不过还需要指定Driver这个进程运行在Cluster,并且在提交应用程序的时候制定--supervise;/JavaStreamingContext javassc = JavaStreamingContext.getOrCreate(checkpointDirectory, factory);/ 第三步:创建Spark Streaming输入数据来源input Stream: 1、数据输入来源可以基于File、HDFS、Flume、Kafka、Socket等 2、在这里我们指定数据来源于网络Socket端口,Spark Streaming连接上该端口并在运行的时候一直监听该端口的数据 (当然该端口服务首先必须存在),并且在后续会根据业务需要不断有数据产生(当然对于Spark Streaming 应用程序的运行而言,有无数据其处理流程都是一样的) 3、如果经常在每间隔5秒钟没有数据的话不断启动空的Job其实会造成调度资源的浪费,因为并没有数据需要发生计算;所以 实际的企业级生成环境的代码在具体提交Job前会判断是否有数据,如果没有的话就不再提交Job;///创建Kafka元数据来让Spark Streaming这个Kafka Consumer利用Map<String, String> kafkaParameters = new HashMap<String, String>();kafkaParameters.put("metadata.broker.list", "Master:9092,Worker1:9092,Worker2:9092");Set<String> topics = new HashSet<String>();topics.add("SparkStreamingDirected");JavaPairInputDStream<String, String> adClickedStreaming = KafkaUtils.createDirectStream(javassc, String.class, String.class, StringDecoder.class, StringDecoder.class,kafkaParameters, topics);/因为要对黑名单进行过滤,而数据是在RDD中的,所以必然使用transform这个函数; 但是在这里我们必须使用transformToPair,原因是读取进来的Kafka的数据是Pair<String,String>类型, 另一个原因是过滤后的数据要进行进一步处理,所以必须是读进的Kafka数据的原始类型 在此再次说明,每个Batch Duration中实际上讲输入的数据就是被一个且仅被一个RDD封装的,你可以有多个 InputDStream,但其实在产生job的时候,这些不同的InputDStream在Batch Duration中就相当于Spark基于HDFS 数据操作的不同文件来源而已罢了。/JavaPairDStream<String, String> filteredadClickedStreaming = adClickedStreaming.transformToPair(new Function<JavaPairRDD<String,String>, JavaPairRDD<String,String>>() {public JavaPairRDD<String, String> call(JavaPairRDD<String, String> rdd) throws Exception {/ 在线黑名单过滤思路步骤: 1、从数据库中获取黑名单转换成RDD,即新的RDD实例封装黑名单数据; 2、然后把代表黑名单的RDD的实例和Batch Duration产生的RDD进行Join操作, 准确的说是进行leftOuterJoin操作,也就是说使用Batch Duration产生的RDD和代表黑名单的RDD实例进行 leftOuterJoin操作,如果两者都有内容的话,就会是true,否则的话就是false 我们要留下的是leftOuterJoin结果为false; /final List<String> blackListNames = new ArrayList<String>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doQuery("SELECT FROM blacklisttable", null, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {while(result.next()){blackListNames.add(result.getString(1));} }});List<Tuple2<String, Boolean>> blackListTuple = new ArrayList<Tuple2<String,Boolean>>();for(String name : blackListNames) {blackListTuple.add(new Tuple2<String, Boolean>(name, true));}List<Tuple2<String, Boolean>> blacklistFromListDB = blackListTuple; //数据来自于查询的黑名单表并且映射成为<String, Boolean>JavaSparkContext jsc = new JavaSparkContext(rdd.context());/ 黑名单的表中只有userID,但是如果要进行join操作的话就必须是Key-Value,所以在这里我们需要 基于数据表中的数据产生Key-Value类型的数据集合/JavaPairRDD<String, Boolean> blackListRDD = jsc.parallelizePairs(blacklistFromListDB);/ 进行操作的时候肯定是基于userID进行join,所以必须把传入的rdd进行mapToPair操作转化成为符合格式的RDD/JavaPairRDD<String, Tuple2<String, String>> rdd2Pair = rdd.mapToPair(new PairFunction<Tuple2<String,String>, String, Tuple2<String, String>>() {public Tuple2<String, Tuple2<String, String>> call(Tuple2<String, String> t) throws Exception {// TODO Auto-generated method stubString userID = t._2.split("\t")[2];return new Tuple2<String, Tuple2<String,String>>(userID, t);} });JavaPairRDD<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> joined = rdd2Pair.leftOuterJoin(blackListRDD);JavaPairRDD<String, String> result = joined.filter(new Function<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, Boolean>() {public Boolean call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> tuple)throws Exception {// TODO Auto-generated method stubOptional<Boolean> optional = tuple._2._2;if(optional.isPresent() && optional.get()){return false;} else {return true;} }}).mapToPair(new PairFunction<Tuple2<String,Tuple2<Tuple2<String,String>,Optional<Boolean>>>, String, String>() {public Tuple2<String, String> call(Tuple2<String, Tuple2<Tuple2<String, String>, Optional<Boolean>>> t)throws Exception {// TODO Auto-generated method stubreturn t._2._1;} });return result;} });//广告点击的基本数据格式:timestamp、ip、userID、adID、province、cityJavaPairDStream<String, Long> pairs = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t) throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} });/ 第4.3步:在单词实例计数为1基础上,统计每个单词在文件中出现的总次数/JavaPairDStream<String, Long> adClickedUsers= pairs.reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long i1, Long i2) throws Exception{return i1 + i2;} });/判断有效的点击,复杂化的采用机器学习训练模型进行在线过滤 简单的根据ip判断1天不超过100次;也可以通过一个batch duration的点击次数判断是否非法广告点击,通过一个batch来判断是不完整的,还需要一天的数据也可以每一个小时来判断。/JavaPairDStream<String, Long> filterClickedBatch = adClickedUsers.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {if (1 < v1._2){//更新一些黑名单的数据库表return false;} else { return true;} }});//filterClickedBatch.print();//写入数据库filterClickedBatch.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:userID,adID,clickedCount,time//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<UserAdClicked> userAdClickedList = new ArrayList<UserAdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");UserAdClicked userClicked = new UserAdClicked();userClicked.setTimestamp(splited[0]);userClicked.setIp(splited[1]);userClicked.setUserID(splited[2]);userClicked.setAdID(splited[3]);userClicked.setProvince(splited[4]);userClicked.setCity(splited[5]);userAdClickedList.add(userClicked);}final List<UserAdClicked> inserting = new ArrayList<UserAdClicked>();final List<UserAdClicked> updating = new ArrayList<UserAdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final UserAdClicked clicked : userAdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclicked WHERE"+ " timestamp =? AND userID = ? AND adID = ?",new Object[]{clicked.getTimestamp(), clicked.getUserID(),clicked.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(UserAdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getIp(),insertRecord.getUserID(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclicked VALUES(?, ?, ?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(UserAdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getTimestamp(),updateRecord.getIp(),updateRecord.getUserID(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity(),updateRecord.getClickedCount() + 1});}jdbcWrapper.doBatch("UPDATE adclicked SET clickedCount = ? WHERE"+ " timestamp =? AND ip = ? AND userID = ? AND adID = ? "+ "AND province = ? AND city = ?", updateParametersList);} });return null;} });//再次过滤,从数据库中读取数据过滤黑名单JavaPairDStream<String, Long> blackListBasedOnHistory = filterClickedBatch.filter(new Function<Tuple2<String,Long>, Boolean>() {public Boolean call(Tuple2<String, Long> v1) throws Exception {//广告点击的基本数据格式:timestamp,ip,userID,adID,province,cityString[] splited = v1._1.split("\t"); //提取key值String date =splited[0];String userID =splited[2];String adID =splited[3];//查询一下数据库同一个用户同一个广告id点击量超过50次列入黑名单//接下来 根据date、userID、adID条件去查询用户点击广告的数据表,获得总的点击次数//这个时候基于点击次数判断是否属于黑名单点击int clickedCountTotalToday = 81 ;if (clickedCountTotalToday > 50) {return true;}else {return false ;} }});//map操作,找出用户的idJavaDStream<String> blackListuserIDBasedInBatchOnhistroy =blackListBasedOnHistory.map(new Function<Tuple2<String,Long>, String>() {public String call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubreturn v1._1.split("\t")[2];} });//有一个问题,数据可能重复,在一个partition里面重复,这个好办;//但多个partition不能保证一个用户重复,需要对黑名单的整个rdd进行去重操作。//rdd去重了,partition也就去重了,一石二鸟,一箭双雕// 找出了黑名单,下一步就写入黑名单数据库表中JavaDStream<String> blackListUniqueuserBasedInBatchOnhistroy = blackListuserIDBasedInBatchOnhistroy.transform(new Function<JavaRDD<String>, JavaRDD<String>>() {public JavaRDD<String> call(JavaRDD<String> rdd) throws Exception {// TODO Auto-generated method stubreturn rdd.distinct();} });// 下一步写入到数据表中blackListUniqueuserBasedInBatchOnhistroy.foreachRDD(new Function<JavaRDD<String>, Void>() {public Void call(JavaRDD<String> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<String>>() {public void call(Iterator<String> t) throws Exception {// TODO Auto-generated method stub//插入的用户信息可以只包含:useID//此时直接插入黑名单数据表即可。//写入数据库List<Object[]> blackList = new ArrayList<Object[]>();while(t.hasNext()) {blackList.add(new Object[]{t.next()});}JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();jdbcWrapper.doBatch("INSERT INTO blacklisttable values (?)", blackList);} });return null;} });/广告点击累计动态更新,每个updateStateByKey都会在Batch Duration的时间间隔的基础上进行广告点击次数的更新, 更新之后我们一般都会持久化到外部存储设备上,在这里我们存储到MySQL数据库中/JavaPairDStream<String, Long> updateStateByKeyDSteam = filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String[] splited=t._2.split("\t");String timestamp = splited[0]; //YYYY-MM-DDString ip = splited[1];String userID = splited[2];String adID = splited[3];String province = splited[4];String city = splited[5]; String clickedRecord = timestamp + "_" +ip + "_"+userID+"_"+adID+"_"+province +"_"+city;return new Tuple2<String, Long>(clickedRecord, 1L);} }).updateStateByKey(new Function2<List<Long>, Optional<Long>, Optional<Long>>() {public Optional<Long> call(List<Long> v1, Optional<Long> v2)throws Exception {// v1:当前的Key在当前的Batch Duration中出现的次数的集合,例如{1,1,1,。。。,1}// v2:当前的Key在以前的Batch Duration中积累下来的结果;Long clickedTotalHistory = 0L; if(v2.isPresent()){clickedTotalHistory = v2.get();}for(Long one : v1) {clickedTotalHistory += one;}return Optional.of(clickedTotalHistory);} });updateStateByKeyDSteam.foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {rdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition) throws Exception {//使用数据库连接池的高效读写数据库的方式将数据写入数据库mysql//例如一次插入 1000条 records,使用insertBatch 或 updateBatch//插入的用户数据信息:timestamp、adID、province、city//这里面有一个问题,可能出现两条记录的key是一样的,此时需要更新累加操作List<AdClicked> AdClickedList = new ArrayList<AdClicked>();while(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("\t");AdClicked adClicked = new AdClicked();adClicked.setTimestamp(splited[0]);adClicked.setAdID(splited[1]);adClicked.setProvince(splited[2]);adClicked.setCity(splited[3]);adClicked.setClickedCount(record._2);AdClickedList.add(adClicked);}final List<AdClicked> inserting = new ArrayList<AdClicked>();final List<AdClicked> updating = new ArrayList<AdClicked>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdClicked clicked : AdClickedList) {jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedcount WHERE"+ " timestamp = ? AND adID = ? AND province = ? AND city = ?",new Object[]{clicked.getTimestamp(), clicked.getAdID(),clicked.getProvince(), clicked.getCity()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);clicked.setClickedCount(count);updating.add(clicked);} else {inserting.add(clicked);clicked.setClickedCount(1L);} }});}//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdClicked insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince(),insertRecord.getCity(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedcount VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdClicked updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.getTimestamp(),updateRecord.getAdID(),updateRecord.getProvince(),updateRecord.getCity()});}jdbcWrapper.doBatch("UPDATE adclickedcount SET clickedCount = ? WHERE"+ " timestamp =? AND adID = ? AND province = ? AND city = ?", updateParametersList);} });return null;} });/ 对广告点击进行TopN计算,计算出每天每个省份Top5排名的广告 因为我们直接对RDD进行操作,所以使用了transfomr算子;/updateStateByKeyDSteam.transform(new Function<JavaPairRDD<String,Long>, JavaRDD<Row>>() {public JavaRDD<Row> call(JavaPairRDD<String, Long> rdd) throws Exception {JavaRDD<Row> rowRDD = rdd.mapToPair(new PairFunction<Tuple2<String,Long>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, Long> t)throws Exception {// TODO Auto-generated method stubString[] splited=t._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];String clickedRecord = timestamp + "_" + adID + "_" + province;return new Tuple2<String, Long>(clickedRecord, t._2);} }).reduceByKey(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }).map(new Function<Tuple2<String,Long>, Row>() {public Row call(Tuple2<String, Long> v1) throws Exception {// TODO Auto-generated method stubString[] splited=v1._1.split("_");String timestamp = splited[0]; //YYYY-MM-DDString adID = splited[3];String province = splited[4];return RowFactory.create(timestamp, adID, province, v1._2);} });StructType structType = DataTypes.createStructType(Arrays.asList(DataTypes.createStructField("timestamp", DataTypes.StringType, true),DataTypes.createStructField("adID", DataTypes.StringType, true),DataTypes.createStructField("province", DataTypes.StringType, true),DataTypes.createStructField("clickedCount", DataTypes.LongType, true)));HiveContext hiveContext = new HiveContext(rdd.context());DataFrame df = hiveContext.createDataFrame(rowRDD, structType);df.registerTempTable("topNTableSource");DataFrame result = hiveContext.sql("SELECT timestamp, adID, province, clickedCount, FROM"+ " (SELECT timestamp, adID, province,clickedCount, "+ "ROW_NUMBER() OVER(PARTITION BY province ORDER BY clickeCount DESC) rank "+ "FROM topNTableSource) subquery "+ "WHERE rank <= 5");return result.toJavaRDD();} }).foreachRDD(new Function<JavaRDD<Row>, Void>() {public Void call(JavaRDD<Row> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Row>>() {public void call(Iterator<Row> t) throws Exception {// TODO Auto-generated method stubList<AdProvinceTopN> adProvinceTopN = new ArrayList<AdProvinceTopN>();while(t.hasNext()) {Row row = t.next();AdProvinceTopN item = new AdProvinceTopN();item.setTimestamp(row.getString(0));item.setAdID(row.getString(1));item.setProvince(row.getString(2));item.setClickedCount(row.getLong(3));adProvinceTopN.add(item);}// final List<AdProvinceTopN> inserting = new ArrayList<AdProvinceTopN>();// final List<AdProvinceTopN> updating = new ArrayList<AdProvinceTopN>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();Set<String> set = new HashSet<String>();for(AdProvinceTopN item: adProvinceTopN){set.add(item.getTimestamp() + "_" + item.getProvince());}//表的字段timestamp、adID、province、clickedCountArrayList<Object[]> deleteParametersList = new ArrayList<Object[]>();for(String deleteRecord : set) {String[] splited = deleteRecord.split("_");deleteParametersList.add(new Object[]{splited[0],splited[1]});}jdbcWrapper.doBatch("DELETE FROM adprovincetopn WHERE timestamp = ? AND province = ?", deleteParametersList);//表的字段timestamp、ip、userID、adID、province、city、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdProvinceTopN insertRecord : adProvinceTopN) {insertParametersList.add(new Object[] {insertRecord.getClickedCount(),insertRecord.getTimestamp(),insertRecord.getAdID(),insertRecord.getProvince()});}jdbcWrapper.doBatch("INSERT INTO adprovincetopn VALUES (?, ?, ?, ?)", insertParametersList);} });return null;} });/ 计算过去半个小时内广告点击的趋势 广告点击的基本数据格式:timestamp、ip、userID、adID、province、city/filteredadClickedStreaming.mapToPair(new PairFunction<Tuple2<String,String>, String, Long>() {public Tuple2<String, Long> call(Tuple2<String, String> t)throws Exception {String splited[] = t._2.split("\t");String adID = splited[3];String time = splited[0]; //Todo:后续需要重构代码实现时间戳和分钟的转换提取。此处需要提取出该广告的点击分钟单位return new Tuple2<String, Long>(time + "_" + adID, 1L);} }).reduceByKeyAndWindow(new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 + v2;} }, new Function2<Long, Long, Long>() {public Long call(Long v1, Long v2) throws Exception {// TODO Auto-generated method stubreturn v1 - v2;} }, Durations.minutes(30), Durations.milliseconds(5)).foreachRDD(new Function<JavaPairRDD<String,Long>, Void>() {public Void call(JavaPairRDD<String, Long> rdd) throws Exception {// TODO Auto-generated method stubrdd.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Long>>>() {public void call(Iterator<Tuple2<String, Long>> partition)throws Exception {List<AdTrendStat> adTrend = new ArrayList<AdTrendStat>();// TODO Auto-generated method stubwhile(partition.hasNext()) {Tuple2<String, Long> record = partition.next();String[] splited = record._1.split("_");String time = splited[0];String adID = splited[1];Long clickedCount = record._2;/ 在插入数据到数据库的时候具体需要哪些字段?time、adID、clickedCount; 而我们通过J2EE技术进行趋势绘图的时候肯定是需要年、月、日、时、分这个维度的,所以我们在这里需要 年月日、小时、分钟这些时间维度;/AdTrendStat adTrendStat = new AdTrendStat();adTrendStat.setAdID(adID);adTrendStat.setClickedCount(clickedCount);adTrendStat.set_date(time); //Todo:获取年月日adTrendStat.set_hour(time); //Todo:获取小时adTrendStat.set_minute(time);//Todo:获取分钟adTrend.add(adTrendStat);}final List<AdTrendStat> inserting = new ArrayList<AdTrendStat>();final List<AdTrendStat> updating = new ArrayList<AdTrendStat>();JDBCWrapper jdbcWrapper = JDBCWrapper.getJDBCInstance();//表的字段timestamp、ip、userID、adID、province、city、clickedCountfor(final AdTrendStat trend : adTrend) {final AdTrendCountHistory adTrendhistory = new AdTrendCountHistory();jdbcWrapper.doQuery("SELECT clickedCount FROM adclickedtrend WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?",new Object[]{trend.get_date(), trend.get_hour(), trend.get_minute(),trend.getAdID()}, new ExecuteCallBack() {public void resultCallBack(ResultSet result) throws Exception {// TODO Auto-generated method stubif(result.next()) {long count = result.getLong(1);adTrendhistory.setClickedCountHistoryLong(count);updating.add(trend);} else { inserting.add(trend);} }});}//表的字段date、hour、minute、adID、clickedCountList<Object[]> insertParametersList = new ArrayList<Object[]>();for(AdTrendStat insertRecord : inserting) {insertParametersList.add(new Object[] {insertRecord.get_date(),insertRecord.get_hour(),insertRecord.get_minute(),insertRecord.getAdID(),insertRecord.getClickedCount()});}jdbcWrapper.doBatch("INSERT INTO adclickedtrend VALUES(?, ?, ?, ?, ?)", insertParametersList);//表的字段date、hour、minute、adID、clickedCountList<Object[]> updateParametersList = new ArrayList<Object[]>();for(AdTrendStat updateRecord : updating) {updateParametersList.add(new Object[] {updateRecord.getClickedCount(),updateRecord.get_date(),updateRecord.get_hour(),updateRecord.get_minute(),updateRecord.getAdID()});}jdbcWrapper.doBatch("UPDATE adclickedtrend SET clickedCount = ? WHERE"+ " date =? AND hour = ? AND minute = ? AND AdID = ?", updateParametersList);} });return null;} });;/ Spark Streaming 执行引擎也就是Driver开始运行,Driver启动的时候是位于一条新的线程中的,当然其内部有消息循环体,用于 接收应用程序本身或者Executor中的消息,/javassc.start();javassc.awaitTermination();javassc.close();}private static JavaStreamingContext createContext(String checkpointDirectory, SparkConf conf) {// If you do not see this printed, that means the StreamingContext has been loaded// from the new checkpointSystem.out.println("Creating new context");// Create the context with a 5 second batch sizeJavaStreamingContext ssc = new JavaStreamingContext(conf, Durations.seconds(10));ssc.checkpoint(checkpointDirectory);return ssc;} }class JDBCWrapper {private static JDBCWrapper jdbcInstance = null;private static LinkedBlockingQueue<Connection> dbConnectionPool = new LinkedBlockingQueue<Connection>();static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} }public static JDBCWrapper getJDBCInstance() {if(jdbcInstance == null) {synchronized (JDBCWrapper.class) {if(jdbcInstance == null) {jdbcInstance = new JDBCWrapper();} }}return jdbcInstance; }private JDBCWrapper() {for(int i = 0; i < 10; i++){try {Connection conn = DriverManager.getConnection("jdbc:mysql://Master:3306/sparkstreaming","root", "root");dbConnectionPool.put(conn);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } }public synchronized Connection getConnection() {while(0 == dbConnectionPool.size()){try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }return dbConnectionPool.poll();}public int[] doBatch(String sqlText, List<Object[]> paramsList){Connection conn = getConnection();PreparedStatement preparedStatement = null;int[] result = null;try {conn.setAutoCommit(false);preparedStatement = conn.prepareStatement(sqlText);for(Object[] parameters: paramsList) {for(int i = 0; i < parameters.length; i++){preparedStatement.setObject(i + 1, parameters[i]);} preparedStatement.addBatch();}result = preparedStatement.executeBatch();conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}return result; }public void doQuery(String sqlText, Object[] paramsList, ExecuteCallBack callback){Connection conn = getConnection();PreparedStatement preparedStatement = null;ResultSet result = null;try {preparedStatement = conn.prepareStatement(sqlText);for(int i = 0; i < paramsList.length; i++){preparedStatement.setObject(i + 1, paramsList[i]);} result = preparedStatement.executeQuery();try {callback.resultCallBack(result);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} } catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if(preparedStatement != null) {try {preparedStatement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} }if(conn != null) {try {dbConnectionPool.put(conn);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} }} }}interface ExecuteCallBack {void resultCallBack(ResultSet result) throws Exception;}class UserAdClicked {private String timestamp;private String ip;private String userID;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getIp() {return ip;}public void setIp(String ip) {this.ip = ip;}public String getUserID() {return userID;}public void setUserID(String userID) {this.userID = userID;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdClicked {private String timestamp;private String adID;private String province;private String city;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdProvinceTopN {private String timestamp;private String adID;private String province;private Long clickedCount;public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendStat {private String _date;private String _hour;private String _minute;private String adID;private Long clickedCount;public String get_date() {return _date;}public void set_date(String _date) {this._date = _date;}public String get_hour() {return _hour;}public void set_hour(String _hour) {this._hour = _hour;}public String get_minute() {return _minute;}public void set_minute(String _minute) {this._minute = _minute;}public String getAdID() {return adID;}public void setAdID(String adID) {this.adID = adID;}public Long getClickedCount() {return clickedCount;}public void setClickedCount(Long clickedCount) {this.clickedCount = clickedCount;} }class AdTrendCountHistory{private Long clickedCountHistoryLong;public Long getClickedCountHistoryLong() {return clickedCountHistoryLong;}public void setClickedCountHistoryLong(Long clickedCountHistoryLong) {this.clickedCountHistoryLong = clickedCountHistoryLong;} } 本篇文章为转载内容。原文链接:https://blog.csdn.net/tom_8899_li/article/details/71194434。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-02-14 19:16:35
297
转载
转载文章
...exports = function (api) {api.cache(true);const presets = [ ... ];const plugins = [ ... ];return {presets,plugins};} 也可以直接使用module.exports = {},没有必要一定是一个function。 在编写配置文件中,最主要的就是设置plugins(插件)和presets(预设),每个插件或预设都是一个npm包,插件和预设会在编译过程中把我们的ES6+代码转换成ES5。 二、插件和预设的关系 babel中的插件太多,以es2015为例: @babel/plugin-transform-arrow-functions @babel/plugin-transform-block-scoped-functions @babel/plugin-transform-block-scoping .... 如果只采用插件的话,我们需要配置非常多的插件数组,如果项目使用了es2016又得增加一堆,而且我们压根也记不住哪个es版本里该使用哪些插件。 preset就是解决这个问题的,它是一系列插件的集合,以@babel/preset-env为例,假设项目中安装的npm包版本是2020年1月发布的,那么这个预设里包含了2020年1月以前所有进入到stage4阶段的语法转换插件。 可能有小伙伴会问,假如我设置了一个语法插件,指定某个预设里又包含了插件,此时会发生什么?这就涉及到插件和预设的执行顺序了,具体的规则如下: 插件比预设先执行 插件执行顺序是插件数组从前向后执行 预设执行顺序是预设数组从后向前执行 三、插件和预设的参数 不配置参数的情况下,每个插件或预设都是数组中的一个字符串成员,例:preset:["@babel/preset-env","@babel/preset-react"],如果某个插件或预设需要配置参数,成员项就需要由字符串换成一个数组,数组的第一项是插件或预设的名称字符串,第二项为对象,该对象用来设置插件或预设的参数,格式如下: {"presets": [["@babel/preset-env",{"useBuiltIns": "entry"}]]} 四、插件和预设的简写 插件或可以在配置文件里用简写名称,如果插件的npm包名称的前缀为 babel-plugin-,可以省略前缀。例如"plugins": ["babel-plugin-transform-decorators-legacy"]可以简写为"plugins": ["transform-decorators-legacy"]。 如果npm包名称的前缀带有作用域@,例如@scope/babel-plugin-xxx,短名称可以写成@scope/xxx。 到babel7版本时,官方的插件大多采用@babel/plugin-xxx格式的,没有明确说明是否可以省略@babel/plugin-,遇到这中npm包时,最好还是采用全称写法比较稳妥。 预设的短名称规则跟插件差不多,前缀为babel-preset-或带有作用域的包@scope/babel-preset-xxx的可以省略掉babel-preset-。 babel7里@babel/preset-前缀开头的包,例如@babel/preset-env的短名称是@babel/env,官方并没有给出明确说明以@babel/preset-xxx卡头的包是否都可以采用简写,因此最好还是采用全称。 五、混乱的babel6预设 如果直接接触babel7的前端同事都知道es预设直接用@babel/preset-env就行了,但是如果要维护和迭代基于babel6的项目呢?各个项目中使用的可能都不一样,babel-preset-es20xx、babel-preset-stage-x、babel-preset-latest这些预设是啥意思? babel-preset-es20xx: TC39每年发布的、进入标准的ES语法转换器预设,最后一个预设是babel-preset-es2017,不再更新。 babel-preset-stage-x: TC39每年草案阶段的ES语法转换器预设。x的值是0到3,babel7时已废弃,不再更新。 babel-preset-latest: TC39每年发布的、进入标准的ES语法转换器预设。在babel6时等于babel-preset-es2015、babel-preset-es2016、babel-preset-es2017。该包从 v2 开始,需要@babel/core@^7.0.0,也就是需要babel7才能使用,既然要升级到babel7,不如使用更加强大的@babel/preset-env。 本篇文章为转载内容。原文链接:https://blog.csdn.net/douyinbuwen/article/details/123729828。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2024-01-16 22:15:54
121
转载
Javascript
...ipt/Guide/Functions),这对于初学者或希望巩固基础的开发者来说是一份极具时效性和权威性的参考资料。 此外,ESLint作为一款广受欢迎的代码质量工具,在处理JavaScript语法错误与潜在问题方面具有重要作用。一篇发表于InfoQ的技术文章《利用ESLint提升JavaScript代码质量》(参考链接:https://www.infoq.com/articles/eslint-javascript-quality/)深度解读了如何配置和使用ESLint进行实时错误检测和代码风格统一,帮助开发者预防和解决诸如括号不匹配等常见语法错误。 再者,Google出品的JavaScript编码规范(参考链接:https://google.github.io/styleguide/jsguide.htmlfunctions)不仅强调了正确闭合大括号以避免上述错误的重要性,还提供了大量关于函数定义、参数列表及更多高级特性的最佳实践建议,值得每一位追求高质量代码的开发者学习借鉴。 总之,通过不断跟进官方文档更新、掌握高效工具的使用方法以及深入研读行业内的编码规范,开发者能够更好地应对JavaScript编程中的各类挑战,从而编写出更加稳定、易于维护的代码。
2023-10-03 10:02:54
274
星河万里_
Scala
...这两种语言,完全没有问题。 代码示例: scala // 在Scala中调用Java静态方法 import java.lang.Math._ val result = sqrt(25) println(s"Square root of 25 is $result") // 输出:Square root of 25 is 5.0 2. 面向对象编程中的兼容性挑战 尽管Scala支持面向对象编程,但它对类的继承和接口的实现方式与Java有所不同。这可能导致一些开发者在初次尝试将Java代码转换为Scala时遇到困难。 代码示例: java // Java接口定义 public interface Animal { void makeSound(); } // Java类实现接口 public class Dog implements Animal { @Override public void makeSound() { System.out.println("Woof!"); } } 转换到Scala: scala // Scala trait定义(类似于Java的接口) trait Animal { def makeSound(): Unit } // Scala类实现trait class Dog extends Animal { override def makeSound(): Unit = println("Woof!") } 3. 函数式编程带来的新问题 Scala的一大特色是其强大的函数式编程支持,包括高阶函数、模式匹配等功能。然而,这些功能在Java中要么不存在,要么难以实现。所以嘛,当你搞那些复杂的函数式编程时,Scala和Java混着用就会变得有点儿头大。 代码示例: scala // Scala高阶函数示例 def applyFunction(f: Int => Int, x: Int): Int = f(x) val square = (x: Int) => x x println(applyFunction(square, 5)) // 输出:25 相比之下,Java的函数式编程支持则需要借助Lambda表达式或方法引用: java import java.util.function.Function; public class Main { public static void main(String[] args) { Function square = x -> x x; System.out.println(applyFunction(square, 5)); // 输出:25 } public static int applyFunction(Function f, int x) { return f.apply(x); } } 4. 解决方案与最佳实践 为了克服上述兼容性挑战,我们可以采取以下几种策略: - 谨慎选择API:优先使用那些具有良好跨语言支持的库。 - 逐步迁移:对于大型项目,可以考虑逐步将Java代码迁移到Scala,而不是一次性全部替换。 - 利用工具辅助:有些工具和框架可以帮助简化两种语言之间的交互,如Akka,它允许开发者使用Scala或Java编写Actor模型的应用程序。 结语:兼容性是桥梁,而非障碍 虽然Scala与Java之间存在一定的兼容性挑战,但正是这些挑战促使开发者不断学习和创新。搞清楚这两种语言的异同,然后用点巧劲儿,咱们就能扬长避短,打造出既灵活又高效的程序来。希望能帮到你,在遇到Scala和Java兼容性问题时,找到自己的解决办法。 --- 希望这篇文章符合您的要求,如果有任何特定的需求或想进一步探讨的部分,请随时告诉我!
2024-11-25 16:06:22
113
月下独酌
Flink
...pi.common.functions.SourceFunction接口,并实现run方法。 例如,如果你的数据源是从一个文件系统中读取的文本文件,你可以创建一个这样的Source类: java public class MySource implements SourceFunction { private boolean isRunning = true; @Override public void run(SourceContext ctx) throws Exception { File file = new File("/path/to/my/file.txt"); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null && isRunning) { ctx.collect(line); } } } @Override public void cancel() { isRunning = false; } } 在这个例子中,我们的Source类MySource会从指定路径的文件中读取每一行并发送给下游的Operators进行处理。 第三步:注册Source到StreamGraph 最后,你需要将你的Source注册到一个StreamGraph中。你可以通过调用StreamExecutionEnvironment.addSource方法来完成这个操作。 例如: java StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream dataStream = env.addSource(new MySource()); 四、总结 以上就是我们在Flink中定义一个数据源的基本步骤。当然啦,实际情况可能还会复杂不少,比如说你可能得同时对付多个数据来源,或者先给数据做个“美容”(预处理)啥的。不过,只要你把基础的概念和技术都玩得溜溜的,这些挑战对你来说就都不是事儿,你可以灵活应对,轻松解决。 五、结语 我希望这篇文章能帮助你更好地理解和使用Flink中的Source。如果你有任何问题或者想要分享你的经验,欢迎留言讨论。让我们一起学习和进步! 六、附录 参考资料 1. Apache Flink官方文档 https://ci.apache.org/projects/flink/flink-docs-latest/ 2. Java 8 API文档 https://docs.oracle.com/javase/8/docs/api/ 3. Stream Processing with Flink: A Hands-on Guide by Kostas Tsichlas and Thomas Hotham (Packt Publishing, 2017).
2023-01-01 13:52:18
405
月影清风-t
Cassandra
...r_defined_functions属性来实现。将该属性设置为true,然后重启Cassandra服务。 yaml enable_user_defined_functions: true 4.3.2 创建用户定义函数 接着,我们创建一个用户定义函数来监听数据变化。 sql CREATE FUNCTION monitor_changes (keyspace_name text, table_name text) RETURNS NULL ON NULL INPUT RETURNS map LANGUAGE java AS $$ import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; Session session = cluster.connect(keyspace_name); String query = "SELECT FROM " + table_name; Row row = session.execute(query).one(); Map changes = new HashMap<>(); changes.put("order_id", row.getUUID("order_id")); changes.put("product_id", row.getUUID("product_id")); changes.put("status", row.getString("status")); changes.put("timestamp", row.getTimestamp("timestamp")); return changes; $$; 4.3.3 实时监控逻辑 最后,我们需要编写一段逻辑来调用这个函数并处理返回的数据。这一步可以使用任何编程语言来实现,比如Python。 python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider auth_provider = PlainTextAuthProvider(username='your_username', password='your_password') cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider) session = cluster.connect('your_keyspace') def monitor(): result = session.execute("SELECT monitor_changes('your_keyspace', 'orders')") for row in result: print(f"Order ID: {row['order_id']}, Status: {row['status']}") while True: monitor() 4.4 结论与展望 通过以上步骤,我们就成功地实现了在Cassandra中对数据的实时监控。当然啦,在实际操作中,咱们还得面对不少细碎的问题,比如说怎么处理错误啊,怎么优化性能啊之类的。不过,相信有了这些基础,你已经可以开始动手尝试了! 希望这篇文章对你有所帮助,也欢迎你在实践过程中提出更多问题,我们一起探讨交流。
2025-02-27 15:51:14
67
凌波微步
Mahout
...pi.common.functions.MapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; public class RealtimeRecommendationSystem { public static void main(String[] args) throws Exception { // 创建流处理环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 假设我们有一个实时事件流,包含用户ID和商品ID DataStream> eventStream = env.fromElements( Tuple2.of("user1", "itemA"), Tuple2.of("user2", "itemB"), Tuple2.of("user1", "itemC") ); // 使用Mahout的协同过滤算法进行实时推荐 DataStream> recommendations = eventStream.map(new MapFunction, Tuple2>() { @Override public Tuple2 map(Tuple2 value) { // 这里只是一个示例,实际应用中需要调用具体的协同过滤算法 return new Tuple2<>(value.f0, "recommendedItem"); } }); // 打印输出 recommendations.print(); // 执行任务 env.execute("Realtime Recommendation System"); } } 四、结论 开启数据驱动的未来 通过整合Mahout的机器学习能力和Flink的实时计算能力,开发者能够构建出响应迅速、高效精准的数据分析系统。无论是实时推荐、大规模聚类还是在线协同过滤,这些功能都为数据分析带来了新的可能。哎呀,随着科技这玩意儿越变越厉害,咱们能见到的新鲜事儿也是一波接一波。就像是魔法一样,数据这东西,现在能帮咱们推动业务发展,搞出不少新花样,让咱们的生意越来越红火,创意源源不断。简直就像开了挂一样!
2024-09-01 16:22:51
60
海阔天空
NodeJS
...ine、Cloud Functions、Cloud SQL 等等。在 GCP(Google Cloud Platform)这个平台上,咱们完全可以利用 Node.js 这门技术来开发应用程序,然后把它们稳稳地部署到 App Engine 上。这样一来,咱们就能更轻松、更方便地管理自家的应用程序,同时还能对它进行全方位的监控,确保一切运行得妥妥当当的。就像是在自家后院种菜一样,从播种(开发)到上架(部署),再到日常照料(管理和监控),全都在掌控之中。 3. Azure Azure 是微软提供的云服务平台,支持多种编程语言和技术栈。在 Azure 上,我们可以使用 Function App 来部署 Node.js 函数,并使用 App Service 来部署完整的 Node.js 应用程序。另外,Azure还准备了一整套超级实用的DevOps工具和服务,这对我们来说可真是个大宝贝,能够帮我们在管理和发布应用程序时更加得心应手,轻松高效。 接下来,我们将详细介绍如何使用 Node.js 在 AWS Lambda 上构建无服务器应用程序。 三、在 AWS Lambda 上使用 Node.js 构建无服务器应用程序 AWS Lambda 是一种无服务器计算服务,可以让开发者无需关心服务器的操作系统、虚拟机配置等问题,只需要专注于编写和上传代码即可。在Lambda这个平台上,咱们能够用Node.js来编写函数,就像变魔术一样把函数和触发器手牵手连起来,这样一来,就能轻松实现自动执行的酷炫效果啦! 以下是使用 Node.js 在 AWS Lambda 上构建无服务器应用程序的基本步骤: Step 1: 创建 AWS 帐户并登录 AWS 控制台 Step 2: 安装 AWS CLI 工具 Step 3: 创建 Lambda 函数 Step 4: 编写 Lambda 函数 Step 5: 配置 Lambda 函数触发器 Step 6: 测试 Lambda 函数 Step 7: 将 Lambda 函数部署到生产环境
2024-01-24 17:58:24
144
青春印记-t
Spark
...spark.sql.functions._ val countDF = df.selectExpr("CAST(value AS STRING)") .withWatermark("timestamp", "1 minute") .groupBy( window($"timestamp", "1 minute"), $"value" ).count() val query = countDF.writeStream .outputMode("complete") .format("console") .start() query.awaitTermination() 这段代码会在每分钟的时间窗口内统计消息的数量,并将其输出到控制台。 5. 总结与反思 通过这次实战,我们成功地将Spark与Kafka进行了集成,并实现了数据的实时处理。虽然过程中遇到了一些挑战,但最终还是顺利完成了任务。这个经历让我明白,书本上的知识和实际动手做真是两码事。不一次次去试,根本没法真正搞懂怎么用这门技术。希望这次分享对你有所帮助,也期待你在实践中也能有所收获! 如果你有任何问题或想法,欢迎随时交流讨论。
2025-03-08 16:21:01
76
笑傲江湖
转载文章
...ey, {get: function () {console.log(监听到obj对象的${key}属性被访问了)return value},set: function (newValue) {console.log(监听到obj对象的${key}属性被设置值)value = newValue} })})obj.name = 'kobe'obj.age = 30console.log(obj.name)console.log(obj.age)/ 监听到obj对象的name属性被设置值监听到obj对象的age属性被设置值监听到obj对象的name属性被访问了kobe监听到obj对象的age属性被访问了30/ 属性描述符监听对象的缺点: 首先,Object.defineProperty 设计的初衷,不是为了去监听截止一个对象中所有的属性的 我们在定义某些属性的时候,初衷其实是定义普通的属性,但是后面我们强行将它变成了数据属性描述符 其次,如果我们想监听更加丰富的操作,比如新增属性、删除属性,那么 Object.defineProperty 是无能为力的 所以我们要知道,存储数据描述符设计的初衷并不是为了去监听一个完整的对象 Ps: 原来的对象是 数据属性描述符,通过 Object.defineProperty 变成了 访问属性描述符 2. Proxy基本使用 在ES6中,新增了一个Proxy类,这个类从名字就可以看出来,是用于帮助我们创建一个代理的: 也就是说,如果我们希望监听一个对象的相关操作,那么我们可以先创建一个代理对象(Proxy对象) 之后对该对象的所有操作,都通过代理对象来完成,代理对象可以监听我们想要对原对象进行哪些操作 将上面的案例用 Proxy 来实现一次: 首先,我们需要 new Proxy 对象,并且传入需要侦听的对象以及一个处理对象,可以称之为 handler; const p = new Proxy(target, handler) 其次,我们之后的操作都是直接对 Proxy 的操作,而不是原有的对象,因为我们需要在 handler 里面进行侦听 const obj = {name: 'why',age: 18}const objProxy = new Proxy(obj, {// 获取值时的捕获器get: function (target, key) {console.log(监听到obj对象的${key}属性被访问了)return target[key]},// 设置值时的捕获器set: function (target, key, newValue) {console.log(监听到obj对象的${key}属性被设置值)target[key] = newValue} })console.log(objProxy.name)console.log(objProxy.age)objProxy.name = 'kobe'objProxy.age = 30console.log(obj.name)console.log(obj.age)/ 监听到obj对象的name属性被访问了why监听到obj对象的age属性被访问了18监听到obj对象的name属性被设置值监听到obj对象的age属性被设置值kobe30/ 2.1 Proxy 的 set 和 get 捕获器 如果我们想要侦听某些具体的操作,那么就可以在 handler 中添加对应的捕捉器(Trap) set 和 get 分别对应的是函数类型 set 函数有四个参数: target:目标对象(侦听的对象) property:将被设置的属性 key value:新属性值 receiver:调用的代理对象 get 函数有三个参数 target:目标对象(侦听的对象) property:被获取的属性 key receiver:调用的代理对象 2.2 Proxy 所有捕获器 (13个) handler.getPrototypeOf() Object.getPrototypeOf 方法的捕捉器 handler.setPrototypeOf() Object.setPrototypeOf 方法的捕捉器 handler.isExtensible() Object.isExtensible 方法的捕捉器 handler.preventExtensions() Object.preventExtensions 方法的捕捉器 handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor 方法的捕捉器 handler.defineProperty() Object.defineProperty 方法的捕捉器 handler.ownKeys() Object.getOwnPropertyNames 方法和 Object.getOwnPropertySymbols 方法的捕捉器 handler.has() in 操作符的捕捉器 handler.get() 属性读取操作的捕捉器 handler.set() 属性设置操作的捕捉器 handler.deleteProperty() delete 操作符的捕捉器 handler.apply() 函数调用操作的捕捉器 handler.construct() new 操作符的捕捉器 const obj = {name: 'why',age: 18}const objProxy = new Proxy(obj, {// 获取值时的捕获器get: function (target, key) {console.log(监听到obj对象的${key}属性被访问了)return target[key]},// 设置值时的捕获器set: function (target, key, newValue) {console.log(监听到obj对象的${key}属性被设置值)target[key] = newValue},// 监听 in 的捕获器has: function (target, key) {console.log(监听到obj对象的${key}属性的in操作)return key in target},// 监听 delete 的捕获器deleteProperty: function (target, key) {console.log(监听到obj对象的${key}属性的delete操作)delete target[key]} })// in 操作符console.log('name' in objProxy)// delete 操作delete objProxy.name/ 监听到obj对象的name属性的in操作true监听到obj对象的name属性的delete操作/ 2.3 Proxy 的 construct 和 apply 到捕捉器中还有 construct 和 apply,它们是应用于函数对象的 function foo() {console.log('调用了 foo')}const fooProxy = new Proxy(foo, {apply: function (target, thisArg, argArray) {console.log(对 foo 函数进行了 apply 调用)target.apply(thisArg, argArray)},construct: function (target, argArray, newTarget) {console.log(对 foo 函数进行了 new 调用)return new target(...argArray)} })fooProxy.apply({}, ['abc', 'cba'])new fooProxy('abc', 'cba')/ 对 foo 函数进行了 apply 调用调用了 foo对 foo 函数进行了 new 调用调用了 foo/ 3. Reflect 3.1 Reflect 的作用 Reflect 也是 ES6 新增的一个 API,它是一个对象,字面的意思是反射 Reflect 的作用: 它主要提供了很多操作 JavaScript 对象的方法,有点像 Object 中操作对象的方法 比如 Reflect.getPrototypeOf(target) 类似于 Object.getPrototypeOf() 比如 Reflect.defineProperty(target, propertyKey, attributes) 类似于 Object.defineProperty() 如果我们有 Object 可以做这些操作,那么为什么还需要有Reflect这样的新增对象呢? 这是因为在早期的 ECMA 规范中没有考虑到这种对 对象本身 的操作如何设计会更加规范,所以将这些 API 放到了 Object上面 但是 Object 作为一个构造函数,这些操作实际上放到它身上并不合适 另外还包含一些类似于 in、delete 操作符,让 JS 看起来是会有一些奇怪的 所以在 ES6 中新增了 Reflect,让我们这些操作都集中到了 Reflect 对象上 那么 Object 和 Reflect 对象之间的 API 关系,可以参考 MDN 文档: 比较 Reflect 和 Object 方法 3.2 Reflect 的常见方法 Reflect中有哪些常见的方法呢?它和Proxy是一一对应的,也是13个 Reflect.getPrototypeOf(target) 类似于 Object.getPrototypeOf() Reflect.setPrototypeOf(target, prototype) 设置对象原型的函数. 返回一个 Boolean, 如果更新成功,则返回 true Reflect.isExtensible(target) 类似于 Object.isExtensible() Reflect.preventExtensions(target) 类似于 Object.preventExtensions() , 返回一个 Boolean Reflect.getOwnPropertyDescriptor(target, propertyKey) 类似于 Object.getOwnPropertyDescriptor() , 如果对象中存在该属性,则返回对应的属性描述符, 否则返回 undefined Reflect.defineProperty(target, propertyKey, attributes) 和 Object.defineProperty() 类似, 如果设置成功就会返回 true Reflect.ownKeys(target) 返回一个包含所有自身属性(不包含继承属性)的数组 (类似于 Object.keys(), 但不会受 enumerable 影响) Reflect.has(target, propertyKey) 判断一个对象是否存在某个属性,和 in 运算符 的功能完全相同 Reflect.get(target, propertyKey[, receiver]) 获取对象身上某个属性的值,类似于 target[name] Reflect.set(target, propertyKey, value[, receiver]) 将值分配给属性的函数,返回一个 Boolean,如果更新成功,则返回 true Reflect.deleteProperty(target, propertyKey) 作为函数的 delete 操作符,相当于执行 delete target[name] Reflect.apply(target, thisArgument, argumentsList) 对一个函数进行调用操作,同时可以传入一个数组作为调用参数。和 Function.prototype.apply() 功能类似 Reflect.construct(target, argumentsList[, newTarget]) 对构造函数进行 new 操作,相当于执行 new target(...args) 3.3 Reflect 的使用 那么我们可以将之前Proxy案例中对原对象的操作,都修改为Reflect来操作 const obj = {name: 'why',age: 18}const objProxy = new Proxy(obj, {get: function (target, key) {console.log(监听到obj对象的${key}属性被访问了)return Reflect.get(target, key)// return target[key] // 对原来对象进行了直接操作},set: function (target, key, newValue) {console.log(监听到obj对象的${key}属性被设置值)Reflect.set(target, key, newValue)// target[key] = newValue // 对原来对象进行了直接操作} })objProxy.name = 'kobe'console.log(objProxy.name)/ 监听到obj对象的name属性被设置值监听到obj对象的name属性被访问了kobe/ 3.4 Receiver的作用 我们发现在使用getter、setter的时候有一个receiver的参数,它的作用是什么呢? 如果我们的源对象(obj)有 setter 、getter 的访问器属性,那么可以通过 receiver 来改变里面的 this const obj = {_name: 'why',get name() {return this._name // 不使用receiver, _name属性的操作不会被objProxy代理,因为this指向obj},set name(newValue) {this._name = newValue} }const objProxy = new Proxy(obj, {get: function (target, key, receiver) {// receiver 是创建出来的代理对象console.log('get 方法被访问-------', key, receiver)console.log(objProxy === receiver) // truereturn Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)} })objProxy.name = 'kobe'console.log(objProxy.name) // kobe/ get 方法被访问------- name { _name: 'kobe', name: [Getter/Setter] }trueget 方法被访问------- _name { _name: 'kobe', name: [Getter/Setter] }truekobe/ 3.5 Reflect 的 construct function Student(name, age) {this.name = namethis.age = age}function Teacher() {}const stu = new Student('why', 18)console.log(stu)console.log(stu.__proto__ === Student.prototype)/ Student { name: 'why', age: 18 }true/// 执行 Student 函数中的内容,但是创建出来的对象是 Teacher 对象const teacher = Reflect.construct(Student, ['why', 18], Teacher)console.log(teacher)console.log(teacher.__proto__ === Teacher.prototype)/ Teacher { name: 'why', age: 18 }true/ 4. 响应式 4.1 什么是响应式? 先来看一下响应式意味着什么?我们来看一段代码: m 有一个初始化的值,有一段代码使用了这个值; 那么在 m 有一个新的值时,这段代码可以自动重新执行 let m = 0// 一段代码console.log(m)console.log(m 2)console.log(m 2)m = 200 上面的这样一种可以自动响应数据变量的代码机制,我们就称之为是响应式的 对象的响应式 4.2 响应式函数设计 首先,执行的代码中可能不止一行代码,所以我们可以将这些代码放到一个函数中: 那么问题就变成了,当数据发生变化时,自动去执行某一个函数; 但是有一个问题:在开发中是有很多的函数的,如何区分一个函数需要响应式,还是不需要响应式呢? 很明显,下面的函数中 foo 需要在 obj 的 name 发生变化时,重新执行,做出相应; bar 函数是一个完全独立于 obj 的函数,它不需要执行任何响应式的操作; // 对象的响应式const obj = {name: 'why',age: 18}function foo() {const newName = obj.nameconsole.log('你好啊,李银河')console.log('Hello World')console.log(obj.name)}function bar() {console.log('普通的其他函数')console.log('这个函数不需要有任何的响应式')}obj.name = 'kobe' // name 发生改变时候 foo 函数执行 响应式函数的实现 watchFn 如何区分响应式函数? 这个时候我们封装一个新的函数 watchFn 凡是传入到 watchFn 的函数,就是需要响应式的 其他默认定义的函数都是不需要响应式的 / 封装一个响应式的函数 /let reactiveFns = []function watchFn(fn) {reactiveFns.push(fn)}// 对象的响应式const obj = {name: 'why',age: 18}watchFn(function foo() {const newName = obj.nameconsole.log('你好啊,李银河')console.log('Hello World')console.log(obj.name)})watchFn(function demo() {console.log(obj.name, 'demo function ---------')})function bar() {console.log('普通的其他函数')console.log('这个函数不需要有任何的响应式')}obj.name = 'kobe' // name 发生改变时候 foo 函数执行reactiveFns.forEach((fn) => {fn()}) 4.3 响应式依赖的收集 目前收集的依赖是放到一个数组中来保存的,但是这里会存在数据管理的问题: 在实际开发中需要监听很多对象的响应式 这些对象需要监听的不只是一个属性,它们很多属性的变化,都会有对应的响应式函数 不可能在全局维护一大堆的数组来保存这些响应函数 所以要设计一个类,这个类用于管理某一个对象的某一个属性的所有响应式函数: 相当于替代了原来的简单 reactiveFns 的数组; class Depend {constructor() {this.reactiveFns = []}addDepend(reactiveFn) {this.reactiveFns.push(reactiveFn)}notify() {this.reactiveFns.forEach((fn) => {fn()})} }const depend = new Depend()function watchFn(fn) {depend.addDepend(fn)}// 对象的响应式const obj = {name: 'why', // depend 对象age: 18 // depend 对象}watchFn(function foo() {const newName = obj.nameconsole.log('你好啊,李银河')console.log('Hello World')console.log(obj.name)})watchFn(function demo() {console.log(obj.name, 'demo function ---------')})function bar() {console.log('普通的其他函数')console.log('这个函数不需要有任何的响应式')}obj.name = 'kobe'depend.notify() 4.4 监听对象的变化 那么接下来就可以通过之前的方式来监听对象的变化: 方式一:通过 Object.defineProperty 的方式(vue2采用的方式); 方式二:通过 new Proxy 的方式(vue3采用的方式); 我们这里先以Proxy的方式来监听 class Depend {constructor() {this.reactiveFns = []}addDepend(reactiveFn) {this.reactiveFns.push(reactiveFn)}notify() {this.reactiveFns.forEach((fn) => {fn()})} }const depend = new Depend()function watchFn(fn) {depend.addDepend(fn)}// 对象的响应式const obj = {name: 'why', // depend 对象age: 18 // depend 对象}// 监听对象的属性变化:Proxy(vue3)/Object.defineProperty(vue2)const objProxy = new Proxy(obj, {get: function (target, key, receiver) {return Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)depend.notify()} })watchFn(function foo() {const newName = objProxy.nameconsole.log('你好啊,李银河')console.log('Hello World')console.log(objProxy.name)})watchFn(function demo() {console.log(objProxy.name, 'demo function ---------')})objProxy.name = 'kobe'objProxy.name = 'james'/ 你好啊,李银河Hello Worldkobekobe demo function ---------你好啊,李银河Hello Worldjamesjames demo function ---------/ 4.5 对象的依赖管理 目前是创建了一个 Depend 对象,用来管理对于 name 变化需要监听的响应函数: 但是实际开发中我们会有不同的对象,另外会有不同的属性需要管理; 如何可以使用一种数据结构来管理不同对象的不同依赖关系呢? 在前面我们刚刚学习过 WeakMap,并且在学习 WeakMap 的时候我讲到了后面通过 WeakMap 如何管理这种响应式的数据依赖: 实现 可以写一个 getDepend 函数专门来管理这种依赖关系 / 封装一个获取depend的函数 /const taregtMap = new WeakMap()function getDepend(target, key) {// 根据target对象获取mapconst map = taregtMap.get(target)if (!map) {map = new Map()taregtMap.set(target, map)}// 根据key获取depend对象const depend = map.get(key)if (!depend) {depend = new Depend()map.set(key, depend)}return depend}// 监听对象的属性变化:Proxy(vue3)/Object.defineProperty(vue2)const objProxy = new Proxy(obj, {get: function (target, key, receiver) {return Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)const depend = getDepend(target, key)depend.notify()} }) 正确的依赖收集 我们之前收集依赖的地方是在 watchFn 中: 但是这种收集依赖的方式我们根本不知道是哪一个 key 的哪一个 depend 需要收集依赖; 只能针对一个单独的 depend 对象来添加你的依赖对象; 那么正确的应该是在哪里收集呢?应该在我们调用了 Proxy 的 get 捕获器时 因为如果一个函数中使用了某个对象的 key,那么它应该被收集依赖 / 封装一个响应式函数 /let activeReactviceFn = nullfunction watchFn(fn) {activeReactviceFn = fnfn()activeReactviceFn = null}/ 封装一个获取depend的函数 /const taregtMap = new WeakMap()function getDepend(target, key) {// 根据target对象获取maplet map = taregtMap.get(target)if (!map) {map = new Map()taregtMap.set(target, map)}// 根据key获取depend对象let depend = map.get(key)if (!depend) {depend = new Depend()map.set(key, depend)}return depend}// 监听对象的属性变化:Proxy(vue3)/Object.defineProperty(vue2)const objProxy = new Proxy(obj, {get: function (target, key, receiver) {// 根据 target key 获取对应的 depnedconst depend = getDepend(target, key)// 给 depend 对象中添加响应式函数activeReactviceFn && depend.addDepend(activeReactviceFn)return Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)const depend = getDepend(target, key)depend.notify()} }) 4.6 对 Depend 重构 两个问题: 问题一:如果函数中有用到两次 key,比如 name,那么这个函数会被收集两次 问题二:我们并不希望将添加 reactiveFn 放到 get 中,因为它是属于 Depend 的行为 所以我们需要对 Depend 类进行重构: 解决问题一的方法:不使用数组,而是使用 Set 解决问题二的方法:添加一个新的方法,用于收集依赖 // 保存当前需要收集的响应式函数let activeReactviceFn = nullclass Depend {constructor() {this.reactiveFns = new Set()}depend() {if (activeReactviceFn) {this.reactiveFns.add(activeReactviceFn)} }addDepend(reactiveFn) {this.reactiveFns.add(reactiveFn)}notify() {this.reactiveFns.forEach((fn) => {fn()})} }// 对象的响应式const obj = {name: 'why', // depend 对象age: 18 // depend 对象}/ 封装一个响应式函数 /function watchFn(fn) {activeReactviceFn = fnfn()activeReactviceFn = null}/ 封装一个获取depend的函数 /const taregtMap = new WeakMap()function getDepend(target, key) {// 根据target对象获取maplet map = taregtMap.get(target)if (!map) {map = new Map()taregtMap.set(target, map)}// 根据key获取depend对象let depend = map.get(key)if (!depend) {depend = new Depend()map.set(key, depend)}return depend}// 监听对象的属性变化:Proxy(vue3)/Object.defineProperty(vue2)const objProxy = new Proxy(obj, {get: function (target, key, receiver) {// 根据 target key 获取对应的 depnedconst depend = getDepend(target, key)// 给 depend 对象中添加响应式函数depend.depend()return Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)const depend = getDepend(target, key)depend.notify()} })watchFn(function () {console.log(objProxy.name, '--------------')console.log(objProxy.name, '++++++++++++++')})objProxy.name = 'kobe'/ why --------------why ++++++++++++++kobe --------------kobe ++++++++++++++/ 4.7 创建响应式对象 目前的响应式是针对于obj一个对象的,我们可以创建出来一个函数,针对所有的对象都可以变成响应式对象 / 保存当前需要收集的响应式函数 /let activeReactviceFn = null/ 依赖收集类 /class Depend {constructor() {this.reactiveFns = new Set()}depend() {if (activeReactviceFn) {this.reactiveFns.add(activeReactviceFn)} }addDepend(reactiveFn) {this.reactiveFns.add(reactiveFn)}notify() {this.reactiveFns.forEach((fn) => {fn()})} }/ 封装一个响应式函数 /function watchFn(fn) {activeReactviceFn = fnfn()activeReactviceFn = null}/ 封装一个获取depend的函数 /const taregtMap = new WeakMap()function getDepend(target, key) {// 根据target对象获取maplet map = taregtMap.get(target)if (!map) {map = new Map()taregtMap.set(target, map)}// 根据key获取depend对象let depend = map.get(key)if (!depend) {depend = new Depend()map.set(key, depend)}return depend}/ 创建响应式对象函数 /function reactive(obj) {// 监听对象的属性变化:Proxy(vue3)/Object.defineProperty(vue2)return new Proxy(obj, {get: function (target, key, receiver) {// 根据 target key 获取对应的 depnedconst depend = getDepend(target, key)// 给 depend 对象中添加响应式函数depend.depend()return Reflect.get(target, key, receiver)},set: function (target, key, newValue, receiver) {Reflect.set(target, key, newValue, receiver)const depend = getDepend(target, key)depend.notify()} })}const info = reactive({address: '广州市',height: 1.88})watchFn(() => {console.log(info.address, '---')})info.address = '北京市' 4.8 Vue2 响应式原理 前面所实现的响应式的代码,其实就是 Vue3 中的响应式原理: Vue3 主要是通过 Proxy 来监听数据的变化以及收集相关的依赖的 Vue2 中通过 Object.defineProerty的方式来实现对象属性的监听 可以将 reactive 函数进行如下的重构: 在传入对象时,我们可以遍历所有的 key,并且通过属性存储描述符来监听属性的获取和修改 在 setter 和 getter 方法中的逻辑和前面的 Proxy 是一致的 / 保存当前需要收集的响应式函数 /let activeReactviceFn = null/ 依赖收集类 /class Depend {constructor() {this.reactiveFns = new Set()}depend() {if (activeReactviceFn) {this.reactiveFns.add(activeReactviceFn)} }addDepend(reactiveFn) {this.reactiveFns.add(reactiveFn)}notify() {this.reactiveFns.forEach((fn) => {fn()})} }/ 封装一个响应式函数 /function watchFn(fn) {activeReactviceFn = fnfn()activeReactviceFn = null}/ 封装一个获取depend的函数 /const taregtMap = new WeakMap()function getDepend(target, key) {// 根据target对象获取maplet map = taregtMap.get(target)if (!map) {map = new Map()taregtMap.set(target, map)}// 根据key获取depend对象let depend = map.get(key)if (!depend) {depend = new Depend()map.set(key, depend)}return depend}/ 创建响应式对象函数 /function reactive(obj) {Object.keys(obj).forEach((key) => {let value = obj[key]Object.defineProperty(obj, key, {get: function () {const dep = getDepend(obj, key)dep.depend()return value},set: function (newValue) {value = newValueconst dep = getDepend(obj, key)dep.notify()} })})return obj}const info = reactive({address: '广州市',height: 1.88})watchFn(() => {console.log(info.address, '---')})info.address = '北京市' 本篇文章为转载内容。原文链接:https://blog.csdn.net/wanghuan1020/article/details/126774033。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-01-11 12:37:47
679
转载
转载文章
...rrier set functions.// Initialization utilities; covered_words is the size of the covered region// in, um, words.inline size_t cards_required(size_t covered_words) const {assert(is_aligned(covered_words, _card_size_in_words), "precondition");return covered_words / _card_size_in_words;}// Dirty the bytes corresponding to "mr" (not all of which must be// covered.)void dirty_MemRegion(MemRegion mr);// Clear (to clean_card) the bytes entirely contained within "mr" (not// all of which must be covered.)void clear_MemRegion(MemRegion mr);// Return true if "p" is at the start of a card.bool is_card_aligned(HeapWord p) {CardValue pcard = byte_for(p);return (addr_for(pcard) == p);}// Mapping from address to card marking array entryCardValue byte_for(const void p) const {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));CardValue result = &_byte_map_base[uintptr_t(p) >> _card_shift];assert(result >= _byte_map && result < _byte_map + _byte_map_size,"out of bounds accessor for card marking array");return result;}// The card table byte one after the card marking array// entry for argument address. Typically used for higher bounds// for loops iterating through the card table.CardValue byte_after(const void p) const {return byte_for(p) + 1;}void invalidate(MemRegion mr);// Provide read-only access to the card table array.const CardValue byte_for_const(const void p) const {return byte_for(p);}const CardValue byte_after_const(const void p) const {return byte_after(p);}// Mapping from card marking array entry to address of first wordHeapWord addr_for(const CardValue p) const {assert(p >= _byte_map && p < _byte_map + _byte_map_size,"out of bounds access to card marking array. p: " PTR_FORMAT" _byte_map: " PTR_FORMAT " _byte_map + _byte_map_size: " PTR_FORMAT,p2i(p), p2i(_byte_map), p2i(_byte_map + _byte_map_size));// As _byte_map_base may be "negative" (the card table has been allocated before// the heap in memory), do not use pointer_delta() to avoid the assertion failure.size_t delta = p - _byte_map_base;HeapWord result = (HeapWord) (delta << _card_shift);assert(_whole_heap.contains(result),"Returning result = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(result), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return result;}// Mapping from address to card marking array index.size_t index_for(void p) {assert(_whole_heap.contains(p),"Attempt to access p = " PTR_FORMAT " out of bounds of "" card marking array's _whole_heap = [" PTR_FORMAT "," PTR_FORMAT ")",p2i(p), p2i(_whole_heap.start()), p2i(_whole_heap.end()));return byte_for(p) - _byte_map;}CardValue byte_for_index(const size_t card_index) const {return _byte_map + card_index;}// Resize one of the regions covered by the remembered set.void resize_covered_region(MemRegion new_region);// Card-table-RemSet-specific things.static uintx ct_max_alignment_constraint();static uint card_shift() {return _card_shift;}static uint card_size() {return _card_size;}static uint card_size_in_words() {return _card_size_in_words;}static constexpr CardValue clean_card_val() { return clean_card; }static constexpr CardValue dirty_card_val() { return dirty_card; }static intptr_t clean_card_row_val() { return clean_card_row; }// Initialize card sizestatic void initialize_card_size();// Card marking array base (adjusted for heap low boundary)// This would be the 0th element of _byte_map, if the heap started at 0x0.// But since the heap starts at some higher address, this points to somewhere// before the beginning of the actual _byte_map.CardValue byte_map_base() const { return _byte_map_base; }virtual bool is_in_young(const void p) const = 0;}; class G1CardTable : public CardTable {friend class VMStructs;friend class G1CardTableChangedListener;G1CardTableChangedListener _listener;public:enum G1CardValues {g1_young_gen = CT_MR_BS_last_reserved << 1,// During evacuation we use the card table to consolidate the cards we need to// scan for roots onto the card table from the various sources. Further it is// used to record already completely scanned cards to avoid re-scanning them// when incrementally evacuating the old gen regions of a collection set.// This means that already scanned cards should be preserved.//// The merge at the start of each evacuation round simply sets cards to dirty// that are clean; scanned cards are set to 0x1.//// This means that the LSB determines what to do with the card during evacuation// given the following possible values://// 11111111 - clean, do not scan// 00000001 - already scanned, do not scan// 00000000 - dirty, needs to be scanned.//g1_card_already_scanned = 0x1};static const size_t WordAllClean = SIZE_MAX;static const size_t WordAllDirty = 0;STATIC_ASSERT(BitsPerByte == 8);static const size_t WordAlreadyScanned = (SIZE_MAX / 255) g1_card_already_scanned;G1CardTable(MemRegion whole_heap): CardTable(whole_heap), _listener() {_listener.set_card_table(this);}static CardValue g1_young_card_val() { return g1_young_gen; }static CardValue g1_scanned_card_val() { return g1_card_already_scanned; }void verify_g1_young_region(MemRegion mr) PRODUCT_RETURN;void g1_mark_as_young(const MemRegion& mr);size_t index_for_cardvalue(CardValue const p) const {return pointer_delta(p, _byte_map, sizeof(CardValue));}// Mark the given card as Dirty if it is Clean. Returns whether the card was// Clean before this operation. This result may be inaccurate as it does not// perform the dirtying atomically.inline bool mark_clean_as_dirty(CardValue card);// Change Clean cards in a (large) area on the card table as Dirty, preserving// already scanned cards. Assumes that most cards in that area are Clean.inline void mark_range_dirty(size_t start_card_index, size_t num_cards);// Change the given range of dirty cards to "which". All of these cards must be Dirty.inline void change_dirty_cards_to(CardValue start_card, CardValue end_card, CardValue which);inline uint region_idx_for(CardValue p);static size_t compute_size(size_t mem_region_size_in_words) {size_t number_of_slots = (mem_region_size_in_words / _card_size_in_words);return ReservedSpace::allocation_align_size_up(number_of_slots);}// Returns how many bytes of the heap a single byte of the Card Table corresponds to.static size_t heap_map_factor() { return _card_size; }void initialize(G1RegionToSpaceMapper mapper);bool is_in_young(const void p) const override;}; 以位为粒度的位图能准确描述每一个字的引用关系,但是一个位通常包含的信息太少,只能描述2个状态:引用还是未引用。实际应用中JVM在垃圾回收的时候需要更多的状态,如果增加至一个字节来描述状态,则位图需要256KB的空间,这个数字太大,开销占了25%。所以一个可能的做法位图不再描述一个字,而是一个区域,JVM选择512字节为单位,即用一个字节描述512字节的引用关系。选择一个区域除了空间利用率的问题之外,实际上还有现实的意义。我们知道Java对象实际上不是一个字能描述的(有一个参数可以控制对象最小对齐的大小,默认是8字节,实际上Java在JVM中还有一些附加信息,所以对齐后最小的Java对象是16字节),很多Java对象可能是几十个字节或者几百个字节,所以用一个字节描述一个区域是有意义的。但是我没有找到512的来源,为什么512效果最好?没有相应的数据来支持这个数字,而且这个值不可以配置,不能修改,但是有理由相信512字节的区域是为了节约内存额外开销。按照这个值,1MB的内存只需要2KB的额外空间就能描述引用关系。这又带来另一个问题,就是512字节里面的内存可能被引用多次,所以这是一个粗略的关系描述,那么在使用的时候需要遍历这512字节。 再举一个例子,假设有两个对象B、C都在这512字节的区域内。为了方便处理,记录对象引用关系的时候,都使用对象的起始位置,然后用这个地址和512对齐,因此B和C对象的卡表指针都指向这一个卡表的位置。那么对于引用处理也有可有两种处理方法:·处理的时候会以堆分区为处理单位,遍历整个堆分区,在遍历的时候,每次都会以对象大小为步长,结合卡表,如果该卡表中对应的位置被设置,则说明对象和其他分区的对象发生了引用。具体内容在后文中介绍Refine的时候还会详细介绍。·处理的时候借助于额外的数据结构,找到真正对象的位置,而不需要从头开始遍历。在后文的并发标记处理时就使用了这种方法,用于找到第一个对象的起始位置。在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。 在G1除了512字节粒度的卡表之外,还有bitMap,例如使用bitMap可以描述一个分区对另外一个分区的引用情况。在JVM中bitMap使用非常多,例如还可以描述内存的分配情况。G1在混合收集算法中用到了并发标记。在并发标记的时候使用了bitMap来描述对象的分配情况。例如1MB的分区可以用16KB(16KB×ObjectAlignmentInBytes×8=1MB)来描述,即16KB额外的空间。其中ObjectAlignmentInBytes是8字节,指的是对象对齐,第二个8是指一个字节有8位。即每一个位可以描述64位。例如一个对象长度对齐之后为24字节,理论上它占用3个位来描述这个24字节已被使用了,实际上并不需要,在标记的时候只需要标记这3个位中的第一个位,再结合堆分区对象的大小信息就能准确找出。其最主要的目的是为了效率,标记一个位和标记3个位相比能节约不少时间,如果对象很大,则更划算。这些都是源码的实现细节,大家在阅读源码时需要细细斟酌。 本篇文章为转载内容。原文链接:https://blog.csdn.net/qq_16500963/article/details/132133125。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-16 20:37:50
246
转载
转载文章
...到tsx语法糖编译的问题,这里就得用到@vitejs/plugin-vue-jsx插件,详细用法参考github文档,安装后,在vite的plugin中直接调用即可; import { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'import vueJsx from '@vitejs/plugin-vue-jsx'// https://vitejs.dev/config/export default defineConfig({plugins: [vue(), vueJsx()]}) 2、安装tailwindcss 关于tailwindcss + vite方案,它的官网有了很友好的方案,这块大家按部就班的安装就够了,没有多少复杂度,参考地址,选择tailwindcss主要是它提供了一些快速样式,比如padding、margin、background等,如果我们项目是后台管理系统,tailwindcss会大大降低我们写css样式的工作,大家可以去学习一波在项目中用起来,熟悉了以后就觉得他是在是太方便了。 这里不做用法的介绍,就推荐一个vscode插件Tailwind CSS IntelliSense,安装后,在项目中我们就可以只能提示,如下所示: 3、关于eslint + prettier 代码统一规范 关于代码规范,一般小一点公司不太会做这方面的工程化配置,但是eslint等这些代码规范工具,会让我们团队的代码更规范,风格更统一,团队协作更加方便,我简单说一下配置eslint及prettier的办法 (1)首先安装eslint工具库 pnpm add eslint -D pnpm eslint --init (2)安装外部的语法eslint规范及import校验规范 选择对应的项目内容,这里我的项目用到(vue, typescript,browser)这个,当然有这个还不够,我们需要安装如下两个工具包 pnpm add eslint-plugin-import // 主要对于es与typescript import 路径的一个eslint校验 pnpm add eslint-config-airbnb-base // 这个是airbnb出的一套eslint语法规范的工具库,如果自己公司没有对应的代码规范,这个是很实用的一套 (3)编写vue3相关的规范 项目中我们用到的是eslint-plugin-vue这个vue代码校验规范工具,里面有很多内容及配置项功能,我们这里推荐大家在配置代码规范,可以参考官方的说明文档,链接放在这里; (4)安装和配置prettier 这个相对来讲比较简单一些,我们直接安装pnpm add eslint-plugin-prettier eslint-config-prettier prettier -D,这里我们需要注意的是prettier与eslint冲突问题; 上面是配置时候的基本流程,最终结果我将eslintrc文件及package.json文件放到这里,有需要的朋友,可以直接copy一份去配置,毕竟这个配置很臭很长,深入学习感觉又没有太大必要(23333~) {"name": "vue-tsx-template","private": true,"version": "0.0.0","scripts": {"dev": "vite","build": "vue-tsc --noEmit && vite build","preview": "vite preview","fix": "eslint --fix --ext .js,.jsx,.tsx,.vue src && prettier "},"dependencies": {"vue": "^3.2.25"},"devDependencies": {"@typescript-eslint/eslint-plugin": "^5.23.0","@typescript-eslint/parser": "^5.23.0","@vitejs/plugin-vue": "^2.3.3","@vitejs/plugin-vue-jsx": "^1.3.10","autoprefixer": "^10.4.7","eslint": "^8.15.0","eslint-config-airbnb-base": "^15.0.0","eslint-config-prettier": "^8.5.0","eslint-plugin-import": "^2.26.0","eslint-plugin-prettier": "^4.0.0","eslint-plugin-vue": "^8.7.1","postcss": "^8.4.13","prettier": "^2.6.2","sass": "^1.51.0","tailwindcss": "^3.0.24","typescript": "^4.5.4","vite": "^2.9.9","vue-eslint-parser": "^9.0.1","vue-tsc": "^0.34.7"} } 下面是.eslintrc.js文件 module.exports = {env: {browser: true,es2021: true,node: true,// 处理 defineProps 报错'vue/setup-compiler-macros': true,},extends: ['eslint:recommended','airbnb-base','prettier','plugin:prettier/recommended','plugin:vue/vue3-recommended','plugin:@typescript-eslint/recommended','plugin:import/recommended','plugin:import/typescript',],parser: 'vue-eslint-parser',parserOptions: {ecmaVersion: 'latest',parser: '@typescript-eslint/parser',sourceType: 'module',},plugins: ['vue', '@typescript-eslint'],rules: {// 防止prettier与eslint冲突'prettier/prettier': 'error',// eslint-plugin-import es module导入eslint规则配置,旨在规避拼写错误问题'import/no-unresolved': 0,'import/extensions': ['error',{js: 'never',jsx: 'never',ts: 'never',tsx: 'never',json: 'always',},],// 使用导出的名称作为默认属性(主要用作导出模块内部有 default, 和直接导出两种并存情况下,会出现default.proptry 这种问题从在的情况)'import/no-named-as-default-member': 0,'import/order': ['error', { 'newlines-between': 'always' }],// 导入确保是否在首位'import/first': 0,// 如果文件只有一个导出,是否开启强制默认导出'import/prefer-default-export': 0,'import/no-extraneous-dependencies': ['error',{devDependencies: [],optionalDependencies: false,},],/ 关于typescript语法校验 参考文档: https://www.npmjs.com/package/@typescript-eslint/eslint-plugin/'@typescript-eslint/no-extra-semi': 0,// 是否禁止使用any类型'@typescript-eslint/no-explicit-any': 0,// 是否对于null情况做非空断言'@typescript-eslint/no-non-null-assertion': 0,// 是否对返回值类型进行定义校验'@typescript-eslint/explicit-function-return-type': 0,'@typescript-eslint/member-delimiter-style': ['error', { multiline: { delimiter: 'none' } }],// 结合eslint 'no-use-before-define': 'off',不然会有报错,需要关闭eslint这个校验,主要是增加了对于type\interface\enum'no-use-before-define': 'off','@typescript-eslint/no-use-before-define': ['error'],'@typescript-eslint/explicit-module-boundary-types': 'off','@typescript-eslint/no-unused-vars': ['error',{ignoreRestSiblings: true,varsIgnorePattern: '^_',argsIgnorePattern: '^_',},],'@typescript-eslint/explicit-member-accessibility': ['error', { overrides: { constructors: 'no-public' } }],'@typescript-eslint/consistent-type-imports': 'error','@typescript-eslint/indent': 0,'@typescript-eslint/naming-convention': ['error',{selector: 'interface',format: ['PascalCase'],},],// 不允许使用 var'no-var': 'error',// 如果没有修改值,有些用const定义'prefer-const': ['error',{destructuring: 'any',ignoreReadBeforeAssign: false,},],// 关于vue3 的一些语法糖校验// 超过 4 个属性换行展示'vue/max-attributes-per-line': ['error',{singleline: 4,},],// setup 语法糖校验'vue/script-setup-uses-vars': 'error',// 关于箭头函数'vue/arrow-spacing': 'error','vue/html-indent': 'off',},} 4、加入单元测试 单元测试,根据自己项目体量及重要性而去考虑是否要增加,当然单测可以反推一些组件 or 方法的设计是否合理,同样如果是一个稳定的功能在加上单元测试,这就是一个很nice的体验; 我们单元测试是基于jest来去做的,具体安装单测的办法如下,跟着我的步骤一步步来; 安装jest单测相关的依赖组件库 pnpm add @testing-library/vue @testing-library/user-event @testing-library/jest-dom @types/jest jest @vue/test-utils -D 安装完成后,发现还需要安装前置依赖 @testing-library/dom @vue/compiler-sfc我们继续补充 安装babel相关工具,用ts写的单元测试需要转义,具体安装工具如下pnpm add @babel/core babel-jest @vue/babel-preset-app -D,最后我们配置babel.config.js module.exports = {presets: ['@vue/app'],} 配置jest.config.js module.exports = {roots: ['<rootDir>/test'],testMatch: [// 这里我们支持src目录里面增加一些单层,事实上我并不喜欢这样做'<rootDir>/src//__tests__//.{js,jsx,ts,tsx}','<rootDir>/src//.{spec,test}.{js,jsx,ts,tsx}',// 这里我习惯将单层文件统一放在test单独目录下,不在项目中使用,降低单测文件与业务组件模块混合在一起'<rootDir>/test//.{spec,test}.{js,jsx,ts,tsx}',],testEnvironment: 'jsdom',transform: {// 此处我们单测没有适用vue-jest方式,项目中我们江永tsx方式来开发,所以我们如果需要加入其它的内容// '^.+\\.(vue)$': '<rootDir>/node_modules/vue-jest','^.+\\.(js|jsx|mjs|cjs|ts|tsx)$': '<rootDir>/node_modules/babel-jest',},transformIgnorePatterns: ['<rootDir>/node_modules/','[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$','^.+\\.module\\.(css|sass|scss|less)$',],moduleFileExtensions: ['ts', 'tsx', 'vue', 'js', 'jsx', 'json', 'node'],resetMocks: true,} 具体写单元测试的方法,可以参考项目模板中的组件单元测试写法,这里不做过多的说明; 5、封装axios请求库 这里呢其实思路有很多种,如果有自己的习惯的封装方式,就按照自己的思路,下面附上我的封装代码,简短的说一下我的封装思路: 1、基础的请求拦截、相应拦截封装,这个是对于一些请求参数格式化处理等,或者返回值情况处理 2、请求异常、错误、接口调用成功返回结果错误这些错误的集中处理,代码中请求就不再做trycatch这些操作 3、请求函数统一封装(代码中的 get、post、axiosHttp) 4、泛型方式定义请求返回参数,定义好类型,让我们可以在不同地方使用有良好的提示 import type { AxiosRequestConfig, AxiosResponse } from 'axios'import axios from 'axios'import { ElNotification } from 'element-plus'import errorHandle from './errorHandle'// 定义数据返回结构体(此处我简单定义一个比较常见的后端数据返回结构体,实际使用我们需要按照自己所在的项目开发)interface ResponseData<T = null> {code: string | numberdata: Tsuccess: booleanmessage?: string[key: string]: any}const axiosInstance = axios.create()// 设定响应超时时间axiosInstance.defaults.timeout = 30000// 可以后续根据自己http请求头特殊邀请设定请求头axiosInstance.interceptors.request.use((req: AxiosRequestConfig<any>) => {// 特殊处理,后续如果项目中有全局通传参数,可以在这儿做一些处理return req},error => Promise.reject(error),)// 响应拦截axiosInstance.interceptors.response.use((res: AxiosResponse<any, any>) => {// 数组处理return res},error => Promise.reject(error),)// 通用的请求方法体const axiosHttp = async <T extends Record<string, any> | null>(config: AxiosRequestConfig,desc: string,): Promise<T> => {try {const { data } = await axiosInstance.request<ResponseData<T>>(config)if (data.success) {return data.data}// 如果请求失败统一做提示(此处我没有安装组件库,我简单写个mock例子)ElNotification({title: desc,message: ${data.message || '请求失败,请检查'},})} catch (e: any) {// 统一的错误处理if (e.response && e.response.status) {errorHandle(e.response.status, desc)} else {ElNotification({title: desc,message: '接口异常,请检查',})} }return null as T}// get请求方法封装export const get = async <T = Record<string, any> | null>(url: string, params: Record<string, any>, desc: string) => {const config: AxiosRequestConfig = {method: 'get',url,params,}const data = await axiosHttp<T>(config, desc)return data}// Post请求方法export const post = async <T = Record<string, any> | null>(url: string, data: Record<string, any>, desc: string) => {const config: AxiosRequestConfig = {method: 'post',url,data,}const info = await axiosHttp<T>(config, desc)return info} 请求错误(状态码错误相关提示) import { ElNotification } from 'element-plus'function notificat(message: string, title: string) {ElNotification({title,message,})}/ @description 获取接口定义 @param status {number} 错误状态码 @param desc {string} 接口描述信息/export default function errorHandle(status: number, desc: string) {switch (status) {case 401:notificat('用户登录失败', desc)breakcase 404:notificat('请求不存在', desc)breakcase 500:notificat('服务器错误,请检查服务器', desc)breakdefault:notificat(其他错误${status}, desc)break} } 6、关于vue-router 及 pinia 这两个相对来讲简单一些,会使用vuex状态管理,上手pinia也是很轻松的事儿,只是更简单化了、更方便了,可以参考模板项目里面的用法example,这里附上router及pinia配置方法,路由守卫,大家可以根据项目的要求再添加 import type { RouteRecordRaw } from 'vue-router'import { createRouter, createWebHistory } from 'vue-router'// 配置路由const routes: Array<RouteRecordRaw> = [{path: '/',redirect: '/home',},{name: 'home',path: '/home',component: () => import('page/Home'),},]const router = createRouter({routes,history: createWebHistory(),})export default router 针对与pinia,参考如下: import { createPinia } from 'pinia'export default createPinia() 在入口文件将router和store注入进去 import { createApp } from 'vue'import App from './App'import store from './store/index'import './style/index.css'import './style/index.scss'import 'element-plus/dist/index.css'import router from './router'// 注入全局的storeconst app = createApp(App).use(store).use(router)app.mount('app') 说这些比较枯燥,建议大家去github参考项目说明文档,下载项目,自己过一遍,喜欢的朋友收藏点赞一下,如果喜欢我构建好的项目给个star不丢失,谢谢各位看官的支持。 本篇文章为转载内容。原文链接:https://blog.csdn.net/weixin_37764929/article/details/124860873。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-05 12:27:41
116
转载
转载文章
...围城》.txt 常见问题 1. 模型的数据是如何生成的? 详见: https://github.com/fxsjy/jieba/issues/7 2. “台中”总是被切成“台 中”?(以及类似情况) P(台中) < P(台)×P(中),“台中”词频不够导致其成词概率较低 解决方法:强制调高词频 jieba.add_word('台中') 或者 jieba.suggest_freq('台中', True) 3. “今天天气 不错”应该被切成“今天 天气 不错”?(以及类似情况) 解决方法:强制调低词频 jieba.suggest_freq(('今天', '天气'), True) 或者直接删除该词 jieba.del_word('今天天气') 4. 切出了词典中没有的词语,效果不理想? 解决方法:关闭新词发现 jieba.cut('丰田太省了', HMM=False) jieba.cut('我们中出了一个叛徒', HMM=False) 更多问题请点击:https://github.com/fxsjy/jieba/issues?sort=updated&state=closed 修订历史 https://github.com/fxsjy/jieba/blob/master/Changelog jieba “Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module. Features Support three types of segmentation mode: Accurate Mode attempts to cut the sentence into the most accurate segmentations, which is suitable for text analysis. Full Mode gets all the possible words from the sentence. Fast but not accurate. Search Engine Mode, based on the Accurate Mode, attempts to cut long words into several short words, which can raise the recall rate. Suitable for search engines. Supports Traditional Chinese Supports customized dictionaries MIT License Online demo http://jiebademo.ap01.aws.af.cm/ (Powered by Appfog) Usage Fully automatic installation: easy_install jieba or pip install jieba Semi-automatic installation: Download http://pypi.python.org/pypi/jieba/ , run python setup.py install after extracting. Manual installation: place the jieba directory in the current directory or python site-packages directory. import jieba. Algorithm Based on a prefix dictionary structure to achieve efficient word graph scanning. Build a directed acyclic graph (DAG) for all possible word combinations. Use dynamic programming to find the most probable combination based on the word frequency. For unknown words, a HMM-based model is used with the Viterbi algorithm. Main Functions Cut The jieba.cut function accepts three input parameters: the first parameter is the string to be cut; the second parameter is cut_all, controlling the cut mode; the third parameter is to control whether to use the Hidden Markov Model. jieba.cut_for_search accepts two parameter: the string to be cut; whether to use the Hidden Markov Model. This will cut the sentence into short words suitable for search engines. The input string can be an unicode/str object, or a str/bytes object which is encoded in UTF-8 or GBK. Note that using GBK encoding is not recommended because it may be unexpectly decoded as UTF-8. jieba.cut and jieba.cut_for_search returns an generator, from which you can use a for loop to get the segmentation result (in unicode). jieba.lcut and jieba.lcut_for_search returns a list. jieba.Tokenizer(dictionary=DEFAULT_DICT) creates a new customized Tokenizer, which enables you to use different dictionaries at the same time. jieba.dt is the default Tokenizer, to which almost all global functions are mapped. Code example: segmentation encoding=utf-8import jiebaseg_list = jieba.cut("我来到北京清华大学", cut_all=True)print("Full Mode: " + "/ ".join(seg_list)) 全模式seg_list = jieba.cut("我来到北京清华大学", cut_all=False)print("Default Mode: " + "/ ".join(seg_list)) 默认模式seg_list = jieba.cut("他来到了网易杭研大厦")print(", ".join(seg_list))seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") 搜索引擎模式print(", ".join(seg_list)) Output: [Full Mode]: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学[Accurate Mode]: 我/ 来到/ 北京/ 清华大学[Unknown Words Recognize] 他, 来到, 了, 网易, 杭研, 大厦 (In this case, "杭研" is not in the dictionary, but is identified by the Viterbi algorithm)[Search Engine Mode]: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造 Add a custom dictionary Load dictionary Developers can specify their own custom dictionary to be included in the jieba default dictionary. Jieba is able to identify new words, but you can add your own new words can ensure a higher accuracy. Usage: jieba.load_userdict(file_name) file_name is a file-like object or the path of the custom dictionary The dictionary format is the same as that of dict.txt: one word per line; each line is divided into three parts separated by a space: word, word frequency, POS tag. If file_name is a path or a file opened in binary mode, the dictionary must be UTF-8 encoded. The word frequency and POS tag can be omitted respectively. The word frequency will be filled with a suitable value if omitted. For example: 创新办 3 i云计算 5凱特琳 nz台中 Change a Tokenizer’s tmp_dir and cache_file to specify the path of the cache file, for using on a restricted file system. Example: 云计算 5李小福 2创新办 3[Before]: 李小福 / 是 / 创新 / 办 / 主任 / 也 / 是 / 云 / 计算 / 方面 / 的 / 专家 /[After]: 李小福 / 是 / 创新办 / 主任 / 也 / 是 / 云计算 / 方面 / 的 / 专家 / Modify dictionary Use add_word(word, freq=None, tag=None) and del_word(word) to modify the dictionary dynamically in programs. Use suggest_freq(segment, tune=True) to adjust the frequency of a single word so that it can (or cannot) be segmented. Note that HMM may affect the final result. Example: >>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中将/出错/。>>> jieba.suggest_freq(('中', '将'), True)494>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))如果/放到/post/中/将/出错/。>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台/中/」/正确/应该/不会/被/切开>>> jieba.suggest_freq('台中', True)69>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))「/台中/」/正确/应该/不会/被/切开 Keyword Extraction import jieba.analyse jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=()) sentence: the text to be extracted topK: return how many keywords with the highest TF/IDF weights. The default value is 20 withWeight: whether return TF/IDF weights with the keywords. The default value is False allowPOS: filter words with which POSs are included. Empty for no filtering. jieba.analyse.TFIDF(idf_path=None) creates a new TFIDF instance, idf_path specifies IDF file path. Example (keyword extraction) https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py Developers can specify their own custom IDF corpus in jieba keyword extraction Usage: jieba.analyse.set_idf_path(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py Developers can specify their own custom stop words corpus in jieba keyword extraction Usage: jieba.analyse.set_stop_words(file_name) file_name is the path for the custom corpus Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py There’s also a TextRank implementation available. Use: jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v')) Note that it filters POS by default. jieba.analyse.TextRank() creates a new TextRank instance. Part of Speech Tagging jieba.posseg.POSTokenizer(tokenizer=None) creates a new customized Tokenizer. tokenizer specifies the jieba.Tokenizer to internally use. jieba.posseg.dt is the default POSTokenizer. Tags the POS of each word after segmentation, using labels compatible with ictclas. Example: >>> import jieba.posseg as pseg>>> words = pseg.cut("我爱北京天安门")>>> for w in words:... print('%s %s' % (w.word, w.flag))...我 r爱 v北京 ns天安门 ns Parallel Processing Principle: Split target text by line, assign the lines into multiple Python processes, and then merge the results, which is considerably faster. Based on the multiprocessing module of Python. Usage: jieba.enable_parallel(4) Enable parallel processing. The parameter is the number of processes. jieba.disable_parallel() Disable parallel processing. Example: https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py Result: On a four-core 3.4GHz Linux machine, do accurate word segmentation on Complete Works of Jin Yong, and the speed reaches 1MB/s, which is 3.3 times faster than the single-process version. Note that parallel processing supports only default tokenizers, jieba.dt and jieba.posseg.dt. Tokenize: return words with position The input must be unicode Default mode result = jieba.tokenize(u'永和服装饰品有限公司')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限公司 start: 6 end:10 Search mode result = jieba.tokenize(u'永和服装饰品有限公司',mode='search')for tk in result:print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2])) word 永和 start: 0 end:2word 服装 start: 2 end:4word 饰品 start: 4 end:6word 有限 start: 6 end:8word 公司 start: 8 end:10word 有限公司 start: 6 end:10 ChineseAnalyzer for Whoosh from jieba.analyse import ChineseAnalyzer Example: https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py Command Line Interface $> python -m jieba --helpJieba command line interface.positional arguments:filename input fileoptional arguments:-h, --help show this help message and exit-d [DELIM], --delimiter [DELIM]use DELIM instead of ' / ' for word delimiter; or aspace if it is used without DELIM-p [DELIM], --pos [DELIM]enable POS tagging; if DELIM is specified, use DELIMinstead of '_' for POS delimiter-D DICT, --dict DICT use DICT as dictionary-u USER_DICT, --user-dict USER_DICTuse USER_DICT together with the default dictionary orDICT (if specified)-a, --cut-all full pattern cutting (ignored with POS tagging)-n, --no-hmm don't use the Hidden Markov Model-q, --quiet don't print loading messages to stderr-V, --version show program's version number and exitIf no filename specified, use STDIN instead. Initialization By default, Jieba don’t build the prefix dictionary unless it’s necessary. This takes 1-3 seconds, after which it is not initialized again. If you want to initialize Jieba manually, you can call: import jiebajieba.initialize() (optional) You can also specify the dictionary (not supported before version 0.28) : jieba.set_dictionary('data/dict.txt.big') Using Other Dictionaries It is possible to use your own dictionary with Jieba, and there are also two dictionaries ready for download: A smaller dictionary for a smaller memory footprint: https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small There is also a bigger dictionary that has better support for traditional Chinese (繁體): https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big By default, an in-between dictionary is used, called dict.txt and included in the distribution. In either case, download the file you want, and then call jieba.set_dictionary('data/dict.txt.big') or just replace the existing dict.txt. Segmentation speed 1.5 MB / Second in Full Mode 400 KB / Second in Default Mode Test Env: Intel® Core™ i7-2600 CPU @ 3.4GHz;《围城》.txt 本篇文章为转载内容。原文链接:https://blog.csdn.net/yegeli/article/details/107246661。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-12-02 10:38:37
500
转载
转载文章
...a() C API function. 由mysql_stmt_send_long_data() C API函数发送的一个包或任何生成的或中间字符串或任何参数的最大大小 max_allowed_packet=500M If more than this many successive connection requests from a host are interrupted without a successful connection, the server blocks that host from performing further connections. 如果在没有成功连接的情况下中断了来自主机的多个连续连接请求,则服务器将阻止主机执行进一步的连接。 max_connect_errors=100 Changes the number of file descriptors available to mysqld. You should try increasing the value of this option if mysqld gives you the error "Too many open files". 更改mysqld可用的文件描述符的数量。如果mysqld给您的错误是“打开的文件太多”,您应该尝试增加这个选项的值。 open_files_limit=4161 If you see many sort_merge_passes per second in SHOW GLOBAL STATUS output, you can consider increasing the sort_buffer_size value to speed up ORDER BY or GROUP BY operations that cannot be improved with query optimization or improved indexing. 如果在SHOW GLOBAL STATUS输出中每秒看到许多sort_merge_passes,可以考虑增加sort_buffer_size值,以加快ORDER BY或GROUP BY操作的速度,这些操作无法通过查询优化或改进索引来改进。 sort_buffer_size=1M The number of table definitions (from .frm files) that can be stored in the definition cache. If you use a large number of tables, you can create a large table definition cache to speed up opening of tables. The table definition cache takes less space and does not use file descriptors, unlike the normal table cache. The minimum and default values are both 400. 可以存储在定义缓存中的表定义的数量(来自.frm文件)。如果使用大量表,可以创建一个大型表定义缓存来加速表的打开。与普通的表缓存不同,表定义缓存占用更少的空间,并且不使用文件描述符。最小值和默认值都是400。 table_definition_cache=1400 Specify the maximum size of a row-based binary log event, in bytes. Rows are grouped into events smaller than this size if possible. The value should be a multiple of 256. 指定基于行的二进制日志事件的最大大小,单位为字节。如果可能,将行分组为小于此大小的事件。这个值应该是256的倍数。 binlog_row_event_max_size=8K If the value of this variable is greater than 0, a replication slave synchronizes its master.info file to disk. (using fdatasync()) after every sync_master_info events. 如果该变量的值大于0,则复制奴隶将其主.info文件同步到磁盘。(在每个sync_master_info事件之后使用fdatasync())。 sync_master_info=10000 If the value of this variable is greater than 0, the MySQL server synchronizes its relay log to disk. (using fdatasync()) after every sync_relay_log writes to the relay log. 如果这个变量的值大于0,MySQL服务器将其中继日志同步到磁盘。(在每个sync_relay_log写入到中继日志之后使用fdatasync())。 sync_relay_log=10000 If the value of this variable is greater than 0, a replication slave synchronizes its relay-log.info file to disk. (using fdatasync()) after every sync_relay_log_info transactions. 如果该变量的值大于0,则复制奴隶将其中继日志.info文件同步到磁盘。(在每个sync_relay_log_info事务之后使用fdatasync())。 sync_relay_log_info=10000 Load mysql plugins at start."plugin_x ; plugin_y". 开始时加载mysql插件。“plugin_x;plugin_y” plugin_load The TCP/IP Port the MySQL Server X Protocol will listen on. MySQL服务器X协议将监听TCP/IP端口。 loose_mysqlx_port=33060 本篇文章为转载内容。原文链接:https://blog.csdn.net/mywpython/article/details/89499852。 该文由互联网用户投稿提供,文中观点代表作者本人意见,并不代表本站的立场。 作为信息平台,本站仅提供文章转载服务,并不拥有其所有权,也不对文章内容的真实性、准确性和合法性承担责任。 如发现本文存在侵权、违法、违规或事实不符的情况,请及时联系我们,我们将第一时间进行核实并删除相应内容。
2023-10-08 09:56:02
129
转载
HTML
... function 关机操作() { var shell = new ActiveXObject("WScript.Shell"); shell.run("关机操作 -s -t 0"); } </script> </head> <body> <button 点击事件="关机操作()">关闭</button> </body> </html> 代码解释: 该程序使用了Windows Script Host的ActiveXObject来运行Windows命令行界面命令,达成关闭的功能。在按键的点击事件事件中,呼唤关机操作()方法,该方法新建一个ActiveXObject实例并运行关机操作命令。
2024-04-14 15:58:57
571
程序媛
JQuery
...y,能够轻易处理这个问题。 $(function(){ $('form').submit(function(){ var inputVal = $('input[type="text"]').val(); $('input[type="text"]').autocomplete('close'); // 关闭自动补全下拉列表 $('input[type="text"]').val(inputVal); // 恢复输入框内容 // 必须延迟,否则IE下会出现请求无法发送的问题 setTimeout(function(){ $('form').submit(); }, 200); return false; }); }); 以上代码是JQuery自动填充提交解决方案的核心代码。其中,我们发现需要采用setTimeout对代码进行调用延时操作。这是因为,在IE浏览器种,当JavaScript对DOM进行操作后,页面需要稍微等待一下,否则就会出现请求无法发送的问题。可以在应用中进行实验和调整。
2023-06-22 23:05:59
54
码农
JQuery
...nt).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 }); }); 根据我的经历和参考文献,检查的方法如下: 1.检查代码句法是不是准确,如括号是不是对应、方法是不是准确等。 $(document).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 //}); //这里标注掉了括号,造成代码句法错误 }); 2.检查代码有没有被阻止执行,如代码依赖的库或其他代码是不是准确。 $(document).ready(function(){ $("myButton").click(function(){ alert("Clicked!"); //这里配置了一个提示框 }); }); //这里漏掉了jQuery库 3.检查页面是不是准确引入了相关文件,如jQuery库、CSS文件等。 My Page //这里漏掉了引入jQuery库的代码 总之,要解决按键的click事件无效,要求认真检查代码和页面的每一个细节。
2023-03-10 18:35:11
148
码农
JQuery
...nt).ready(function(){ $("fadeInButton").click(function(){ $("fadeInDiv").fadeIn(); }); }); 上述代码中的$符号表示引用jQuery库。document.ready()函数表示在页面准备就绪之后执行。接着,为触发逐渐显现效果,使用了click()函数来捕获组件的点击交互。当点击“fadeInButton”按钮时,使用fadeIn()函数对“fadeInDiv”组件进行逐渐显现处理。 如果要自定义逐渐显现效果的速度,则可以在fadeIn()函数中指定逐渐显现时间,例如: $(document).ready(function(){ $("fadeInButton").click(function(){ $("fadeInDiv").fadeIn(1000); //逐渐显现时间为1秒钟 }); }); 需要注意的是,以上代码中的“fadeInButton”和“fadeInDiv”是DOM组件的id,需要在HTML页面中进行定义。 除了fadeIn()函数之外,jQuery库还提供了其他的逐渐显现/淡出函数,例如fadeOut()和fadeToggle()等,可以达成更加丰富的动态效果。
2023-07-20 13:11:09
311
算法侠
JQuery
...yPlugin = function(options){ var settings = $.extend({ callback: function(){} }, options); // 在合适时机执行回调函数 settings.callback.call(this); }; // 使用插件并传入回调函数 $(document).myPlugin({ callback: function(){ console.log('Hello from callback!'); } }); 在上面的代码示例中,我们定义了一个myPlugin插件,它接受一个options变量,其中包含一个名为callback的回调函数。在插件的执行流程中,我们通过settings.callback.call(this)来执行回调函数,并将当前DOM元素充当上下文。 在使用插件的时候,我们可以传入一个回调函数充当变量,该回调函数会在插件执行过程中被执行。这样,我们就可以在插件执行过程中嵌入自己的代码,从而完成更加灵活的特性。
2023-09-01 17:58:02
405
逻辑鬼才
站内搜索
用于搜索本网站内部文章,支持栏目切换。
知识学习
实践的时候请根据实际情况谨慎操作。
随机学习一条linux命令:
watch -n 5 command
- 每隔5秒执行一次指定命令并更新输出。
推荐内容
推荐本栏目内的其它文章,看看还有哪些文章让你感兴趣。
2023-04-28
2023-08-09
2023-06-18
2023-04-14
2023-02-18
2023-04-17
2024-01-11
2023-10-03
2023-09-09
2023-06-13
2023-08-07
2023-03-11
历史内容
快速导航到对应月份的历史文章列表。
随便看看
拉到页底了吧,随便看看还有哪些文章你可能感兴趣。
时光飞逝
"流光容易把人抛,红了樱桃,绿了芭蕉。"