本文将为您提供关于JS与trick的代码的详细介绍,我们还将为您解释js常用代码的相关知识,同时,我们还将为您提供关于bootstrap的datetimepicker.js的结束时间大于开始时间,当前
本文将为您提供关于JS与trick的代码的详细介绍,我们还将为您解释js常用代码的相关知识,同时,我们还将为您提供关于bootstrap的datetimepicker.js的结束时间大于开始时间,当前日期之前的代码、c# timerCallback的代码介绍、cocos quick的代码加密、com.codahale.metrics.Clock的实例源码的实用信息。
本文目录一览:- JS与trick的代码(js常用代码)
- bootstrap的datetimepicker.js的结束时间大于开始时间,当前日期之前的代码
- c# timerCallback的代码介绍
- cocos quick的代码加密
- com.codahale.metrics.Clock的实例源码
JS与trick的代码(js常用代码)
这次给大家带来JS与trick的代码,使用JS与trick的代码的注意事项有哪些,下面就是实战案例,一起来看一下。浮点数取整
const x = 123.4545; x >> 0; // 123 ~~x; // 123 x | 0; // 123 Math.floor(x); // 123
注意:前三种方法只适用于32个位整数,对于负数的处理上和 Math.floor是不同的。
Math.floor(-12.53); // -13 -12.53 | 0; // -12
生成6位数字验证码
// 方法一 ('000000' + Math.floor(Math.random() * 999999)).slice(-6); // 方法二 Math.random().toString().slice(-6); // 方法三 Math.random().toFixed(6).slice(-6); // 方法四 '' + Math.floor(Math.random() * 999999);
16进制颜色代码生成
(function() { return '#'+('00000'+ (Math.random()*0x1000000<<0).toString(16)).slice(-6); })();
驼峰命名转下划线
'componentMapModelRegistry'.match(/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g).join('_').toLowerCase(); // component_map_model_registry
url查询参数转json格式
// ES6 const query = (search = '') => ((querystring = '') => (q => (querystring.split('&').forEach(item => (kv => kv[0] && (q[kv[0]] = kv[1]))(item.split('='))), q))({}))(search.split('?')[1]); // 对应ES5实现 var query = function(search) { if (search === void 0) { search = ''; } return (function(querystring) { if (querystring === void 0) { querystring = ''; } return (function(q) { return (querystring.split('&').forEach(function(item) { return (function(kv) { return kv[0] && (q[kv[0]] = kv[1]); })(item.split('=')); }), q); })({}); })(search.split('?')[1]); }; query('?key1=value1&key2=value2'); // es6.html:14 {key1: value1, key2: value2}
获取URL参数
function getQueryString(key){ var reg = new RegExp((^|&)+ key +=([^&]*)(&|$)); var r = window.location.search.substr(1).match(reg); if(r!=null){ return unescape(r[2]); } return null; }
n维数组展开成一维数组
var foo = [1, [2, 3], ['4', 5, ['6',7,[8]]], [9], 10]; // 方法一 // 限制:数组项不能出现`,`,同时数组项全部变成了字符数字 foo.toString().split(','); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 方法二 // 转换后数组项全部变成数字了 eval('[' + foo + ']'); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 方法三,使用ES6展开操作符 // 写法太过麻烦,太过死板 [1, ...[2, 3], ...['4', 5, ...['6',7,...[8]]], ...[9], 10]; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 方法四 JSON.parse(`[${JSON.stringify(foo).replace(/\[|]/g, '')}]`); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 方法五 const flatten = (ary) => ary.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []); flatten(foo); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 方法六 function flatten(a) { return Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
注:更多方法请参考《How to flatten nested array in JavaScript?》
日期格式化
// 方法一 function format1(x, y) { var z = { y: x.getFullYear(), M: x.getMonth() + 1, d: x.getDate(), h: x.getHours(), m: x.getMinutes(), s: x.getSeconds() }; return y.replace(/(y+|M+|d+|h+|m+|s+)/g, function(v) { return ((v.length > 1 ? 0 : ) + eval('z.' + v.slice(-1))).slice(-(v.length > 2 ? v.length : 2)) }); } format1(new Date(), 'yy-M-d h:m:s'); // 17-10-14 22:14:41 // 方法二 Date.prototype.format = function (fmt) { var o = { M+: this.getMonth() + 1, //月份 d+: this.getDate(), //日 h+: this.getHours(), //小时 m+: this.getMinutes(), //分 s+: this.getSeconds(), //秒 q+: Math.floor((this.getMonth() + 3) / 3), //季度 S: this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)){ fmt = fmt.replace(RegExp.$1, (this.getFullYear() + ).substr(4 - RegExp.$1.length)); } for (var k in o){ if (new RegExp(( + k + )).test(fmt)){ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((00 + o[k]).substr(( + o[k]).length))); } } return fmt; } new Date().format('yy-M-d h:m:s'); // 17-10-14 22:18:17
特殊字符转义
function htmlspecialchars (str) { var str = str.toString().replace(/&/g, &).replace(/</g, <).replace(/>/g, >).replace(//g, ''); return str; } htmlspecialchars('&jfkds<>'); // &jfkds<>
动态插入js
function injectScript(src) { var s, t; s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src; t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s, t); }
格式化数量
// 方法一 function formatNum (num, n) { if (typeof num == number) { num = String(num.toFixed(n || 0)); var re = /(-?\d+)(\d{3})/; while (re.test(num)) num = num.replace(re, $1,$2); return num; } return num; } formatNum(2313123, 3); // 2,313,123.000 // 方法二 '2313123'.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 2,313,123 // 方法三 function formatNum(str) { return str.split('').reverse().reduce((prev, next, index) => { return ((index % 3) ? next : (next + ',')) + prev }); } formatNum('2313323'); // 2,313,323
身份证验证
function chechCHNCardId(sNo) { if (!this.regExpTest(sNo, /^[0-9]{17}[X0-9]$/)) { return false; } sNo = sNo.toString(); var a, b, c; a = parseInt(sNo.substr(0, 1)) * 7 + parseInt(sNo.substr(1, 1)) * 9 + parseInt(sNo.substr(2, 1)) * 10; a = a + parseInt(sNo.substr(3, 1)) * 5 + parseInt(sNo.substr(4, 1)) * 8 + parseInt(sNo.substr(5, 1)) * 4; a = a + parseInt(sNo.substr(6, 1)) * 2 + parseInt(sNo.substr(7, 1)) * 1 + parseInt(sNo.substr(8, 1)) * 6; a = a + parseInt(sNo.substr(9, 1)) * 3 + parseInt(sNo.substr(10, 1)) * 7 + parseInt(sNo.substr(11, 1)) * 9; a = a + parseInt(sNo.substr(12, 1)) * 10 + parseInt(sNo.substr(13, 1)) * 5 + parseInt(sNo.substr(14, 1)) * 8; a = a + parseInt(sNo.substr(15, 1)) * 4 + parseInt(sNo.substr(16, 1)) * 2; b = a % 11; if (b == 2) { c = sNo.substr(17, 1).toupperCase(); } else { c = parseInt(sNo.substr(17, 1)); } switch (b) { case 0: if (c != 1) { return false; } break; case 1: if (c != 0) { return false; } break; case 2: if (c != X) { return false; } break; case 3: if (c != 9) { return false; } break; case 4: if (c != 8) { return false; } break; case 5: if (c != 7) { return false; } break; case 6: if (c != 6) { return false; } break; case 7: if (c != 5) { return false; } break; case 8: if (c != 4) { return false; } break; case 9: if (c != 3) { return false; } break; case 10: if (c != 2) { return false; }; } return true; }
测试质数
function isPrime(n) { return !(/^.?$|^(..+?)\1+$/).test('1'.repeat(n)) }
统计字符串中相同字符出现的次数
var arr = 'abcdaabc'; var info = arr .split('') .reduce((p, k) => (p[k]++ || (p[k] = 1), p), {}); console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
使用 void0来解决 undefined被污染问题
undefined = 1; !!undefined; // true !!void(0); // false
单行写一个评级组件
★★★★★☆☆☆☆☆.slice(5 - rate, 10 - rate);
JavaScript 错误处理的方式的正确姿势
try { something } catch (e) { window.location.href = http://stackoverflow.com/search?q=[js]+ + e.message; }
匿名函数自执行写法
( function() {}() ); ( function() {} )(); [ function() {}() ]; ~ function() {}(); ! function() {}(); + function() {}(); - function() {}(); delete function() {}(); typeof function() {}(); void function() {}(); new function() {}(); new function() {}; var f = function() {}(); 1, function() {}(); 1 ^ function() {}(); 1 > function() {}();
两个整数交换数值
var a = 20, b = 30; a ^= b; b ^= a; a ^= b; a; // 30 b; // 20
数字字符转数字
var a = '1'; +a; // 1
最短的代码实现数组去重
[...new Set([1, 1, 2, 1, 1, 3])]; // [1, 1, 2, 3]
用最短的代码实现一个长度为m(6)且值都n(8)的数组
Array(6).fill(8); // [8, 8, 8, 8, 8, 8]
将argruments对象转换成数组
var argArray = Array.prototype.slice.call(arguments); // ES6: var argArray = Array.from(arguments) // or var argArray = [...arguments];
获取日期时间缀
// 获取指定时间的时间缀 new Date().getTime(); (new Date()).getTime(); (new Date).getTime(); // 获取当前的时间缀 Date.Now(); // 日期显示转换为数字 +new Date();
使用 ~x.indexOf('y')来简化 x.indexOf('y')>-1
var str = 'hello world'; if (str.indexOf('lo') > -1) { // ... } if (~str.indexOf('lo')) { // ... }
两者的差别之处在于解析和转换两者之间的理解。
解析允许字符串中含有非数字字符,解析按从左到右的顺序,如果遇到非数字字符就停止。而转换不允许出现非数字字符,否者会失败并返回NaN。
var a = '520'; var b = '520px'; Number(a); // 520 parseInt(a); // 520 Number(b); // NaN parseInt(b); // 520
parseInt方法第二个参数用于指定转换的基数,ES5默认为10进制。
parseInt('10', 2); // 2 parseInt('10', 8); // 8 parseInt('10', 10); // 10 parseInt('10', 16); // 16
对于网上 parseInt(0.0000008)的结果为什么为8,原因在于0.0000008转换成字符为8e-7,然后根据 parseInt的解析规则自然得到8这个结果。
+ 拼接操作,+x or String(x)?
+运算符可用于数字加法,同时也可以用于字符串拼接。如果+的其中一个操作符是字符串(或者通过 隐式强制转换可以得到字符串),则执行字符串拼接;否者执行数字加法。
需要注意的时对于数组而言,不能通过 valueOf()方法得到简单基本类型值,于是转而调用 toString()方法。
[1,2] + [3, 4]; // 1,23,4
对于对象同样会先调用 valueOf()方法,然后通过 toString()方法返回对象的字符串表示。
var a = {}; a + 123; // [object Object]123
对于 a+隐式转换和 String(a)显示转换有一个细微的差别: a+''会对a调用 valueOf()方法,而 String()直接调用 toString()方法。大多数情况下我们不会考虑这个问题,除非真遇到。
var a = { valueOf: function() { return 42; }, toString: function() { return 4; } } a + ''; // 42 String(a); // 4
判断对象的实例
// 方法一: ES3 function Person(name, age) { if (!(this instanceof Person)) { return new Person(name, age); } this.name = name; this.age = age; } // 方法二: ES5 function Person(name, age) { var self = this instanceof Person ? this : Object.create(Person.prototype); self.name = name; self.age = age; return self; } // 方法三:ES6 function Person(name, age) { if (!new.target) { throw 'Peron must called with new'; } this.name = name; this.age = age; }
数据安全类型检查
// 对象 function isObject(value) { return Object.prototype.toString.call(value).slice(8, -1) === 'Object''; } // 数组 function isArray(value) { return Object.prototype.toString.call(value).slice(8, -1) === 'Array'; } // 函数 function isFunction(value) { return Object.prototype.toString.call(value).slice(8, -1) === 'Function'; }
让数字的字面值看起来像对象
toString(); // Uncaught SyntaxError: Invalid or unexpected token ..toString(); // 第二个点号可以正常解析 .toString(); // 注意点号前面的空格 (2).toString(); // 2先被计算
对象可计算属性名(仅在ES6中)
var suffix = ' name'; var person = { ['first' + suffix]: 'Nicholas', ['last' + suffix]: 'Zakas' } person['first name']; // Nicholas person['last name']; // Zakas
数字四舍五入
// v: 值,p: 精度 function (v, p) { p = Math.pow(10, p >>> 31 ? 0 : p | 0) v *= p; return (v + 0.5 + (v >> 31) | 0) / p } round(123.45353, 2); // 123.45
在浏览器中根据url下载文件
function download(url) { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (isChrome || isSafari) { var link = document.createElement('a'); link.href = url; if (link.download !== undefined) { var fileName = url.substring(url.lastIndexOf('/') + 1, url.length); link.download = fileName; } if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } if (url.indexOf('?') === -1) { url += '?download'; } window.open(url, '_self'); return true; }
快速生成UUID
function uuid() { var d = new Date().getTime(); var uuid = 'xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; }; uuid(); // 33f7f26656cb-499b-b73e-89a921a59ba6
JavaScript浮点数精度问题
function isEqual(n1, n2, epsilon) { epsilon = epsilon == undefined ? 10 : epsilon; // 默认精度为10 return n1.toFixed(epsilon) === n2.toFixed(epsilon); } 0.1 + 0.2; // 0.30000000000000004 isEqual(0.1 + 0.2, 0.3); // true 0.7 + 0.1 + 99.1 + 0.1; // 99.99999999999999 isEqual(0.7 + 0.1 + 99.1 + 0.1, 100); // true
格式化表单数据
function formatParam(obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for(name in obj) { value = obj[name]; if(value instanceof Array) { for(i=0; i<value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += formatParam(innerObj) + '&'; } } else if(value instanceof Object) { for(subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += formatParam(innerObj) + '&'; } } else if(value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } return query.length ? query.substr(0, query.length - 1) : query; } var param = { name: 'jenemy', likes: [0, 1, 3], memberCard: [ { title: '1', id: 1 }, { title: '2', id: 2 } ] } formatParam(param); // name=12&likes%5B0%5D=0&likes%5B1%5D=1&likes%5B2%5D=3&memberCard%5B0%5D%5Btitle%5D=1&memberCard%5B0%5D%5Bid%5D=1&memberCard%5B1%5D%5Btitle%5D=2&memberCard%5B1%5D%5Bid%5D=2
创建指定长度非空数组
在JavaScript中可以通过new Array(3)的形式创建一个长度为3的空数组。在老的Chrome中其值为[undefined x 3],在最新的Chrome中为[empty x 3],即空单元数组。在老Chrome中,相当于显示使用[undefined, undefined, undefined]的方式创建长度为3的数组。
但是,两者在调用map()方法的结果是明显不同的
var a = new Array(3); var b = [undefined, undefined, undefined]; a.map((v, i) => i); // [empty × 3] b.map((v, i) => i); // [0, 1, 2]
多数情况我们期望创建的是包含undefined值的指定长度的空数组,可以通过下面这种方法来达到目的:
var a = Array.apply(null, { length: 3 }); a; // [undefined, undefined, undefined] a.map((v, i) => i); // [0, 1, 2]
总之,尽量不要创建和使用空单元数组。
相信看了本文案例你已经掌握了方法,更多精彩请关注小编网其它相关文章!
推荐阅读:
webpack如何动态引入文件
webpack打包指定JS文件需要怎么做
bootstrap的datetimepicker.js的结束时间大于开始时间,当前日期之前的代码
感觉不错的代码,贴出来,以后接着用
<link href="__ROOT__static/css/bootstrap-datetimepicker.min.css " rel="stylesheet">
<script type="text/javascript" src="__ROOT__static/js/bootstrap-datetimepicker.js" charset="UTF-8"></script>
<script type="text/javascript" src="__ROOT__static/js/locales/bootstrap-datetimepicker.fr.js" charset="UTF-8"></script>
<script type="text/javascript">
$("#stime").datetimepicker({
format: ''yyyy-mm-dd'',
language: ''zh-CN'',
weekStart: 1,
todayBtn: 1,//显示‘今日’按钮
autoclose: 1,
todayHighlight: 1,
startView: 2,
minView: 2, //Number, String. 默认值:0, ''hour'',日期时间选择器所能够提供的最精确的时间选择视图。
forceParse: 0,
endDate: new Date(),
}).on(''changeDate'',function(ev){
var starttime=$("#stime").val();
$("#etime").datetimepicker(''setStartDate'',starttime);
$("#stime").datetimepicker(''hide'');
});
$("#etime").datetimepicker({
format: ''yyyy-mm-dd'',
language: ''zh-CN'',
weekStart: 1,
todayBtn: 1,//显示‘今日’按钮
autoclose: 1,
todayHighlight: 1,
startView: 2,
minView: 2, //Number, String. 默认值:0, ''hour'',日期时间选择器所能够提供的最精确的时间选择视图。
forceParse: 0,
endDate: new Date(),
}).on(''changeDate'',function(ev){
var starttime=$("#stime").val();
var endtime=$("#etime").val();
$("#stime").datetimepicker(''setEndDate'',endtime);
$("#etime").datetimepicker(''hide'');
});
</script>
c# timerCallback的代码介绍
考虑这样的场景:需要定时去完成某个任务(例如,定时去远程server取数据,定时更新数据库的某个字段等),对于此类业务,C#也做了封装,可以帮助我们方便的去完成。
代码段:
代码说明:new了一个TimerCallBack类,同时传递给它一个委托,告诉他要定时完成什么任务。New 一个Timer同时传递四个参数:
l
l
l
l
New了之后,就开始执行了。
以上就是c# timercallback的代码介绍的内容,更多相关内容请关注php中文网(www.php.cn)!
cocos quick的代码加密
quick-cocos2d-x是用lua脚本来写的,而lua是明文形式,如果不对脚本进行处理,那么我们所写的代码将可能暴露给别人(apk和ipa都是简单的zip包装)。
quick-cocos2d-x框架为我们提供了一个可编译和加密代码的工具compile_scripts.sh(目前只提供了mac版),它位于quick-cocos2d-x/bin/compile_scripts.sh。下面将对其进行详细的介绍。
一、安装luajit
lua脚本的编译是通过luajit来执行的,如果你之前没有安装过luajit的话,运行compile_scripts.sh会出现下面的提示:
下面将介绍如何安装luajit。
1、运行<path>/quick-cocos2d-x/bin/install_luajit.sh,<path>为你具体的路径,请自行替换。这个时候会执行luajit的构建操作。
2、完成构建之后将进行安装,安装之前会叫你输入系统账户密码,如下图:
3、之后就是安装过程了,完成之后会出现下图这样的界面:
恭喜你完成了第一步。
二、示例
我们先来运行一个示例吧。这个将帮助你了解编译的过程。
我们做的很简单,就是把代码编译成一个zip包,并把它放置到res目录下(framework_precompiled.zip也在此目录)。
1、在bash下,设置当前工作目录到你游戏的目录下,如:
cd /Users/myname/mygames/game01
2、运行compile_scripts.sh。
/Users/myname/lua/tools/quick-cocos2d-x/bin/compile_scripts.sh -i scripts -o res/game.zip
生成会显示出具体的信息,如参数是什么、源代码文件夹地址、生成了什么文件,生成文件的位置等等,如下图:
之后就会看到game.zip在res目录下了,解压(不是必须操作,只是为了看看里面有什么)之后发现:
它生成了一个个的二进制文件,文件名已经包含了包名。
到这里你也一定会问,命令中-i,-o这些参数是什么意思啊?还有哪些其它的参数啊?下面我们将对其进行详解。
三、参数详解
compile_scripts.sh中带有不少的参数,详情如下:
1、-h帮助。显示参数的解释及使用,英文的。
2、-i 源码目录。
3、-o 输出文件或目录。
4、-p 包前缀。
5、-x 不包含在内的包。如果你有些源文件不想被编译进去的话,将会用到这个参数,只能设置包(对应文件夹),不能指定到文件,多个包的话用,(逗号)隔开。示例:-x app.test,server,指的是app/test/.*,server/.*这两个目录下的所有文件都不会被编译。
注:经测试,目前这个参数没有作用,已报告给作者,请等待修复。
6、-m 编译模式。有两个值:
-mzip默认,生成的是zip格式文件;
-mfiles生成的是一个个文件,不打包,这个时候-o参数指的就是输出的目录。
7、-e 加密模式。可以对编译后的文件再进行XXTEA加密,有两个值:
-e xxtea_zip对应-m zip,对打包后的zip格式文件进行加密,之后再打包成zip格式。
-exxtea_chunk对编译后的文件加密,最后打不打包取决于-m。
注:xxtea_zip一定要与-m zip编译模式对应,不然会提示出错。
8、-ek 加密密钥。对-e有效,且设置了-e之后一定要设置-ek。
9、-es 加密签名。对-e有效,默认值为"XXTEA",这个只是为了让引擎知道文件是否被加密过,意义不大,所以可不设置。
下面是一个编译及加密的例子:
compile_scripts.sh -i scripts -o res/game.zip -e xxtea_zip -ek aaa -es XT
10、-ex 编译后的文件的后缀名。对-m files有效,默认值为"lua"。
11、-c 从一个文件加载参数列表。
12、-q 生成过程不输出信息。
四、修改AppDelegate.cpp
我们编译了代码,并且把main.lua文件也包含进去了,我们要修改c++中的代码才能让程序正常运行。这个在AppDelegate.ccp文件中修改,把applicationDidFinishLaunching()方法改成如下:
bool AppDelegate::applicationDidFinishLaunching() { ... ccluaStack *pStack = pEngine->getLuaStack(); // 如果设置了 -e 和 -ek 要加上下面这句 // pStack->setXXTEAKeyAndSign("aaa",3); // 如果设置了 -e 和 -ek -es 则要加上下面这句 pStack->setXXTEAKeyAndSign("aaa",3,"XT",2); // load framework pStack->loadChunksFromZip("res/framework_precompiled.zip"); pStack->loadChunksFromZip("res/game.zip"); pStack->executeString("require 'main'"); return true; }
注意:一直有朋友不太注意,
pStack->setXXTEAKeyAndSign("aaa",2);
这一句的第二和第四个参数都是前一个参数的长度,并不是固定值,如可以这样
pStack->setXXTEAKeyAndSign("abcd",4,"SIGNCODE",8);
最后需要注意的是:编译发布程序的时候要记得把源代码文件夹从项目中移除(不是删除,只是不包含进项目里),不然一切都白费了。
到此整个过程结束,我们的代码已经被很好的保护起来了。
来源:https://my.oschina.net/lonewolf/blog/178515
com.codahale.metrics.Clock的实例源码
@VisibleForTesting DecayingEstimatedHistogramReservoir(boolean considerZeroes,int bucketCount,Clock clock) { if (bucketCount == DEFAULT_BUCKET_COUNT) { if (considerZeroes == true) { bucketoffsets = DEFAULT_WITH_ZERO_BUCKET_OFFSETS; } else { bucketoffsets = DEFAULT_WITHOUT_ZERO_BUCKET_OFFSETS; } } else { bucketoffsets = EstimatedHistogram.newOffsets(bucketCount,considerZeroes); } decayingBuckets = new AtomicLongArray(bucketoffsets.length + 1); buckets = new AtomicLongArray(bucketoffsets.length + 1); this.clock = clock; decayLandmark = clock.getTime(); }
public void onResponseReceived(HttpRequest request,HttpResponse response) { Long startTime = removeObjectProperty(request,START_TIME_PROPERTY_NAME); if (startTime == null) { return; } long t = Clock.defaultClock().getTick() - startTime; String method = request.getRequestLine().getmethod(); int statusCode = response.getStatusLine().getStatusCode(); String metricName = ROOT_NAME.withTags( "method",method,"status","" + statusCode).toString(); Timer timer = RegistryService.getMetricRegistry().timer(metricName); timer.update(t,TimeUnit.NANOSECONDS); }
public void onGetInputStream(HttpURLConnection urlConnection,int statusCode) { Long startTime = removeObjectProperty(urlConnection,START_TIME_PROPERTY_NAME); if (startTime == null) { return; } long t = Clock.defaultClock().getTick() - startTime; String method = urlConnection.getRequestMethod(); String status = "" + statusCode; Timer timer = timers.computeIfAbsent(status + method,s -> { TagEncodedMetricName metricName = ROOT_NAME.withTags( "method",status); return getTimer(metricName); }); timer.update(t,TimeUnit.NANOSECONDS); }
private ElasticsearchReporter(MetricRegistry registry,MetricFilter filter,TimeUnit rateUnit,TimeUnit durationUnit,String host,String port,String indexName,String timestampField) { super(registry,"elasticsearch-reporter",filter,rateUnit,durationUnit); this.clock = Clock.defaultClock(); this.connector = new ElasticsearchConnector(host,port,indexName); this.timestampField = timestampField; this.timestampformat = new SimpleDateFormat(timeStampString); this.localhost = Utils.localHostName(); jsonFactory = new JsonFactory(); indexInitialized = connector.addDefaultMappings(); if (!indexInitialized) { LOGGER.warn("Failed to initialize Elasticsearch index '" + indexName + "' on " + host + ":" + port); } }
HawkularReporter(MetricRegistry registry,HawkularHttpClient hawkularClient,Optional<String> prefix,MetricsDecomposer decomposer,MetricsTagger tagger,MetricFilter filter) { super(registry,"hawkular-reporter",durationUnit); this.prefix = prefix; this.clock = Clock.defaultClock(); this.hawkularClient = hawkularClient; this.decomposer = decomposer; this.tagger = tagger; }
HawkularReporter(MetricRegistry registry,durationUnit); this.prefix = prefix; this.clock = Clock.defaultClock(); this.hawkularClient = hawkularClient; this.decomposer = decomposer; this.tagger = tagger; }
@Test public void testBasic() throws Exception { FileUtil.removeIfExist("build/ServerLogMetricPlugin",false); YaraServiceImpl yaraService = new YaraServiceImpl() ; server.getServiceRegistry().register(YaraService.newReflectiveBlockingService(yaraService)); MetricRegistry server1 = createMetricRegistry("server1") ; MetricRegistry server2 = createMetricRegistry("server2") ; Random rand = new Random() ; for(int i = 0; i < 100000; i++) { long timestamp = Clock.defaultClock().getTick() ; server1.counter("counter").incr() ; server1.timer("timer").update(timestamp,rand.nextInt(1000)) ; server2.counter("counter").incr() ; server2.timer("timer").update(timestamp,rand.nextInt(1000)) ; } Thread.sleep(6000); new ClusterMetricPrinter().print(yaraService.getClusterMetricRegistry()); }
private StorageReporter(MetricRegistry registry,Locale locale,Clock clock,TimeZone timeZone,StorageAdapter storageAdapter) { super(registry,"storage-reporter",durationUnit); this.locale = locale; this.clock = clock; this.storageAdapter = storageAdapter; this.dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.MEDIUM,locale); dateFormat.setTimeZone(timeZone); }
public ReporterV08(MetricRegistry registry,Influxdb influxdb,String prefix,boolean skipIdleMetrics,scheduledexecutorservice executor) { super(registry,"influxdb-reporter",durationUnit,executor); this.skipIdleMetrics = skipIdleMetrics; this.prevIoUsValues = new TreeMap<String,Long>(); this.influxdb = influxdb; this.clock = clock; this.prefix = (prefix == null) ? "" : (prefix.trim() + "."); }
protected ElasticsearchReporter(MetricRegistry registry,String elasticsearchIndexPrefix,String timestampFieldName,String metricPrefix,durationUnit); this.clock = clock; this.metricPrefix = metricPrefix; this.timestampFieldName = timestampFieldName; if (elasticsearchIndexPrefix.endsWith("-")) { this.elasticsearchIndexPrefix = elasticsearchIndexPrefix; } else { this.elasticsearchIndexPrefix = elasticsearchIndexPrefix + "-"; } jsonFactory = new JsonFactory(); }
@Before public void setUp() throws Exception { httpClient = mock(HttpClient.class); Clock clock = mock(Clock.class); timestamp = System.currentTimeMillis(); when(clock.getTime()).thenReturn(timestamp); final CorePlugin corePlugin = mock(CorePlugin.class); when(corePlugin.getInfluxDbUrl()).thenReturn(new URL("http://localhost:8086")); when(corePlugin.getInfluxDbDb()).thenReturn("stm"); influxDbReporter = InfluxDbReporter.forRegistry(new Metric2Registry(),corePlugin) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(DURATION_UNIT) .globalTags(singletonMap("app","test")) .httpClient(httpClient) .clock(clock) .build(); }
public AsyncRequestLog(Clock clock,AppenderAttachableImpl<ILoggingEvent> appenders,final TimeZone timeZone,List<String> cookies) { this.clock = clock; this.cookies = cookies; this.queue = new LinkedBlockingQueue<String>(); this.dispatcher = new dispatcher(); this.dispatchThread = new Thread(dispatcher); dispatchThread.setName("async-request-log-dispatcher-" + THREAD_COUNTER.incrementAndGet()); dispatchThread.setDaemon(true); this.dateCache = new ThreadLocal<DateCache>() { @Override protected DateCache initialValue() { final DateCache cache = new DateCache("dd/MMM/yyyy:HH:mm:ss Z",Locale.US); cache.setTimeZoneID(timeZone.getID()); return cache; } }; this.appenders = appenders; }
private AbstractConnector configureExternalHttpsConnector() { logger.info("Creating https connector"); final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setCertAlias(getConfiguration().getSslConfiguration().getKeyStoreAlias()); sslContextFactory.setKeyStorePath(getConfiguration().getSslConfiguration().getKeyStorePath()); sslContextFactory.setKeyStorePassword(getConfiguration().getSslConfiguration().getKeyStorePassword()); final Integer port = getConfiguration().getSslConfiguration().getPort() != null ? getConfiguration().getSslConfiguration().getPort() : getConfiguration().getPort(); final InstrumentedSslSocketConnector connector = new InstrumentedSslSocketConnector( this.metricRegistry,sslContextFactory,Clock.defaultClock()); connector.setName(EXTERNAL_HTTPS_CONNECTOR_NAME); return connector; }
public void onTransactionExec(Transaction tx) { Long startTime = removeObjectProperty(tx,TRANSACTION_START_TIME_PROP_NAME); if (startTime == null) { return; } long t = Clock.defaultClock().getTick() - startTime; txExecTimer.update(t,TimeUnit.NANOSECONDS); }
public void onTransactiondiscard(Transaction tx) { Long startTime = removeObjectProperty(tx,TRANSACTION_START_TIME_PROP_NAME); if (startTime == null) { return; } long t = Clock.defaultClock().getTick() - startTime; txdiscardTimer.update(t,TimeUnit.NANOSECONDS); }
public void onPipelinesync(Pipeline pipeline) { Long startTime = removeObjectProperty(pipeline,TRANSACTION_START_TIME_PROP_NAME); if (startTime == null) { return; } long t = Clock.defaultClock().getTick() - startTime; pipelinesyncTimer.update(t,TimeUnit.NANOSECONDS); }
private Builder(MetricRegistry registry) { this.registry = registry; this.clock = Clock.defaultClock(); this.prefix = null; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; }
public ElasticsearchReporter(MetricRegistry registry,String[] hosts,int timeout,String index,String indexDateFormat,int bulkSize,MetricFilter percolationFilter,Notifier percolationNotifier,String timestampFieldname,Map<String,String> context) throws MalformedURLException { super(registry,durationUnit); this.hosts = hosts; this.index = index; this.bulkSize = bulkSize; this.clock = clock; this.prefix = prefix; this.timeout = timeout; if (indexDateFormat != null && indexDateFormat.length() > 0) { this.indexDateFormat = new SimpleDateFormat(indexDateFormat); } if (percolationNotifier != null && percolationFilter != null) { this.percolationFilter = percolationFilter; this.notifier = percolationNotifier; } if (timestampFieldname == null || timestampFieldname.trim().length() == 0) { LOGGER.error("Timestampfieldname {} is not valid,using default @timestamp",timestampFieldname); timestampFieldname = "@timestamp"; } objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); objectMapper.configure(SerializationFeature.CLOSE_CLOSEABLE,false); // auto closing means,that the objectmapper is closing after the first write call,which does not work for bulk requests objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT,false); objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,false); objectMapper.registerModule(new MetricsElasticsearchModule(rateUnit,timestampFieldname)); writer = objectMapper.writer(); checkForIndexTemplate(); }
private Builder(MetricRegistry registry) { this.registry = registry; this.locale = Locale.getDefault(); this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.clock = Clock.defaultClock(); this.filter = MetricFilter.ALL; }
/** */ private HumanReadableCsvReporter(MetricRegistry registry,File directory,"human-readable-csv-reporter",durationUnit); this.directory = directory; this.locale = locale; this.clock = clock; }
private void setupRatetest() throws InterruptedException { Clock clock = mock(Clock.class); meter = new DelegatingDerivingMeter(new Meter(clock)); when(clock.getTick()).thenReturn(0L); meter.mark(0); meter.mark(2000); // need to 'wait' more than 5 seconds for the Codahale metrics meter to 'tick'. when(clock.getTick()).thenReturn(TimeUnit.NANOSECONDS.convert(6,TimeUnit.SECONDS)); }
private Builder(final MetricRegistry metricRegistry,final AmazonCloudWatchAsync cloudWatchAsyncclient,final String namespace) { this.metricRegistry = metricRegistry; this.cloudWatchAsyncclient = cloudWatchAsyncclient; this.namespace = namespace; this.percentiles = new percentile[]{percentile.P75,percentile.P95,percentile.P999}; this.metricFilter = MetricFilter.ALL; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.globalDimensions = new LinkedHashSet<>(); this.cwRateUnit = toStandardUnit(rateUnit); this.cwDurationUnit = toStandardUnit(durationUnit); this.clock = Clock.defaultClock(); }
public CustomMeter(final Clock clock,final int periodSec) { final double ps = periodSec > 0 ? periodSec : 10; final int intervalSecs = 1; rateAvg = new EWMA(1 - exp(-intervalSecs / ps),intervalSecs,TimeUnit.SECONDS); this.clock = clock; startTime = clock.getTick(); lastTick.set(startTime); }
public CompositeForwardingTimer(Timer mainDelegate,MetricProvider<Timer> supplementaryMetricProvider) { Preconditions.checkNotNull(mainDelegate); Preconditions.checkNotNull(supplementaryMetricProvider); this.mainDelegate = mainDelegate; this.supplementaryMetricProvider = supplementaryMetricProvider; this.clock = Clock.defaultClock(); }
private CirconusReporter(MetricRegistry metricRegistry,Transport transport,EnumSet<Expansion> expansions,MetricNameFormatter metricNameFormatter,List<String> tags,DynamicTagsCallback tagsCallback,Boolean suppress) { super(metricRegistry,"circonus-reporter",durationUnit); if(!(metricRegistry instanceof CirconusMetricRegistryAlaCoda)) { LOG.warn("CirconusReporter started without a CirconusMetricRegistry(AlaCoda) so no real histograms."); } this.clock = clock; this.host = host; this.expansions = expansions; this.metricNameFormatter = metricNameFormatter; this.tags = (tags == null) ? new ArrayList<String>() : tags; this.transport = transport; this.prefix = prefix; this.tagsCallback = tagsCallback; this.suppress_bad_analytics = suppress; }
public Builder(MetricRegistry registry) { this.registry = registry; this.expansions = Expansion.ALL; this.clock = Clock.defaultClock(); this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; this.metricNameFormatter = new DefaultMetricNameFormatter(); this.tags = new ArrayList<String>(); this.suppress_bad_analytics = true; }
protected Builder(MetricRegistry registry) { this.registry = registry; this.output = System.out; this.locale = Locale.getDefault(); this.clock = Clock.defaultClock(); this.timeZone = TimeZone.getDefault(); this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; this.tags = new LinkedHashMap<String,String>(); }
public OperatingSystemGaugeSet( OperatingSystemMXBean osMxBean,int cacheTimeoutValue,TimeUnit cacheTimeoutUnit,Clock cacheTimeoutClock ) { this.osMxBean = osMxBean; this.cacheTimeoutValue = cacheTimeoutValue; this.cacheTimeoutUnit = cacheTimeoutUnit; this.cacheTimeoutClock = cacheTimeoutClock; }
public OperatingSystemInfo( OperatingSystemMXBean osMxBean,long timeout,TimeUnit timeoutUnit,Clock timeoutClock ) { super( Objects.requireNonNull( timeoutClock ),timeout,Objects.requireNonNull( timeoutUnit ) ); this.osMxBean = Objects.requireNonNull( osMxBean ); }
private Builder(MetricRegistry registry) { this.registry = registry; this.output = System.out; this.locale = Locale.getDefault(); this.clock = Clock.defaultClock(); this.timeZone = TimeZone.getDefault(); this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; }
private Builder(MetricRegistry registry) { this.registry = registry; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.clock = Clock.defaultClock(); this.filter = MetricFilter.ALL; }
private DasReporter(MetricRegistry registry,String source,String type,String receiverURL,String authURL,String username,String password,String dataAgentConfigPath,"das-reporter",durationUnit); this.source = source; this.clock = clock; if (source == null || source.trim().isEmpty()) { throw new IllegalArgumentException("Source cannot be null or empty"); } if (type == null || type.trim().isEmpty()) { throw new IllegalArgumentException("Type cannot be null or empty"); } if (receiverURL == null || receiverURL.trim().isEmpty()) { throw new IllegalArgumentException("Data Receiver URL cannot be null or empty"); } if (username == null || username.trim().isEmpty()) { throw new IllegalArgumentException("Username cannot be null or empty"); } if (password == null || password.trim().isEmpty()) { throw new IllegalArgumentException("Password cannot be null or empty"); } if (dataAgentConfigPath != null) { AgentHolder.setConfigPath(dataAgentConfigPath); } try { dataPublisher = new DataPublisher(type,receiverURL,authURL,username,password); } catch (DataEndpointAgentConfigurationException | DataEndpointException | DataEndpointConfigurationException | DataEndpointAuthenticationException | TransportException e) { throw new IllegalStateException("Error when initializing the Data Publisher",e); } }
private Builder(MetricRegistry registry) { this.registry = registry; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.clock = Clock.defaultClock(); this.filter = MetricFilter.ALL; this.timestampunit = TimeUnit.SECONDS; }
private JdbcReporter(MetricRegistry registry,DataSource dataSource,TimeUnit timestampunit,"jdbc-reporter",durationUnit); this.source = source; this.dataSource = dataSource; this.timestampunit = timestampunit; this.clock = clock; if (source == null || source.trim().isEmpty()) { throw new IllegalArgumentException("Source cannot be null or empty"); } if (dataSource == null) { throw new IllegalArgumentException("Data source cannot be null"); } }
/** * Build a new reservoir. * * @param clock Clock to use as a time source * @param size Number of buckets to maintain * @param step Step between each bucket * @param stepUnit Time unit used in 'step' * @param delegate Delegate reservoir that min/max is being corrected for. */ public MinMaxSlidingTimeReservoir( final Clock clock,final int size,final long step,final TimeUnit stepUnit,final Reservoir delegate ) { this.clock = clock; this.size = size; this.step = stepUnit.toNanos(step); this.delegate = delegate; }
private Builder(MetricRegistry registry) { this.registry = registry; this.clock = Clock.defaultClock(); this.filter = MetricFilter.ALL; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; }
public ExtendedMeter(Clock clock) { super(clock); this.clock = clock; this.lastTick = new AtomicLong(this.clock.getTick()); m30Rate = new EWMA(M30_ALPHA,INTERVAL,TimeUnit.SECONDS); h1Rate = new EWMA(H1_ALPHA,TimeUnit.SECONDS); h6Rate = new EWMA(H6_ALPHA,TimeUnit.SECONDS); h12Rate = new EWMA(H12_ALPHA,TimeUnit.SECONDS); h24Rate = new EWMA(H24_ALPHA,TimeUnit.SECONDS); }
private Builder(MetricRegistry registry) { this.registry = registry; this.clock = Clock.defaultClock(); this.prefix = null; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; }
关于JS与trick的代码和js常用代码的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于bootstrap的datetimepicker.js的结束时间大于开始时间,当前日期之前的代码、c# timerCallback的代码介绍、cocos quick的代码加密、com.codahale.metrics.Clock的实例源码等相关内容,可以在本站寻找。
本文标签: