text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
dir = File.dirname(__FILE__)
$LOAD_PATH.unshift dir unless $LOAD_PATH.include?(dir)
unless defined?(Sass)
require 'sass'
end
module Gsass
if defined?(Rails) && defined?(Rails::Engine)
class Engine < ::Rails::Engine
require 'gsass/engine'
end
else
Sass.load_paths << File.expand_path("../../app/assets/stylesheets", __FILE__)
end
end
| {'content_hash': 'c6f839cbd10de7d20e50448644293908', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 81, 'avg_line_length': 22.5625, 'alnum_prop': 0.6592797783933518, 'repo_name': 'gorillasoftware/gsass', 'id': '91e400274b021754610d729a357718cb18bd802d', 'size': '392', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/gsass.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '83'}, {'name': 'Ruby', 'bytes': '1257'}]} |
"""
rMake, build utility for conary
"""
def initializePlugins(pluginDirs, disabledPlugins=None):
global pluginManager
from rmake import plugins
pluginManager = plugins.PluginManager(pluginDirs=pluginDirs,
disabledPlugins=disabledPlugins)
pluginManager.loadPlugins()
pluginManager.callLibraryHook('library_preInit')
| {'content_hash': '7b33642c7430b66b1f27412e598b2333', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 74, 'avg_line_length': 37.7, 'alnum_prop': 0.7029177718832891, 'repo_name': 'fedora-conary/rmake-2', 'id': 'f60500cf6ee4c11ae12539c9a1c954f85569b396', 'size': '964', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'rmake/__init__.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '35796'}, {'name': 'C++', 'bytes': '3953'}, {'name': 'Python', 'bytes': '1682020'}, {'name': 'Shell', 'bytes': '12415'}]} |
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega/3.0.2/vega.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-lite/2.0.0-beta.21/vega-lite.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.0.0-beta.19/vega-embed.js"></script>
<script src="scripts/page_interactions.js" defer="defer"></script>
<style>
body {
font-family: sans-serif;
}
.vega-actions a {
padding: 5px;
}
</style>
<title>Visualization of IMDB and Bechdel test data</title>
</head>
<body>
<h1>Visualization of IMDB and Bechdel test data</h1>
<button id="avgRatingPerYear">Average Bechdel Rating per YEAR</button>
<button id="avgRatingPerCountry">Average Bechdel Rating per COUNTRY</button>
<button id="bechdelRatingPerYearStackedBar">Stacked Barchart Bechdel Rating per YEAR</button>
<button id="selectionFilter">Selection filter</button>
<button id="imdbBechdelYear">Bechdel rating per year 1990-2016</button>
<div id="vis"></div>
</body>
| {'content_hash': '67244a61af2435f9bfc154bafd286f81', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 103, 'avg_line_length': 32.27272727272727, 'alnum_prop': 0.7070422535211267, 'repo_name': 'OlaKarlsson/TNM101_Advanced_Visualization', 'id': '151be6ef24c7117539a5c015631a167193c8994f', 'size': '1065', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'project2/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '3823'}, {'name': 'JavaScript', 'bytes': '2067'}]} |
goog.provide('lf.cache.DefaultCache');
goog.require('goog.asserts');
goog.require('lf.cache.Cache');
goog.require('lf.structs.map');
goog.require('lf.structs.set');
goog.forwardDeclare('lf.schema.Database');
/**
* In-memory row cache.
* @param {!lf.schema.Database} dbSchema
* @implements {lf.cache.Cache}
* @constructor @struct
*/
lf.cache.DefaultCache = function(dbSchema) {
/** @private {!lf.structs.Map<number, lf.Row>} */
this.map_ = lf.structs.map.create();
/** @private {!lf.structs.Map<string, !lf.structs.Set<number>>} */
this.tableRows_ = lf.structs.map.create();
// Create set for tableRows
dbSchema.tables().forEach(function(table) {
this.tableRows_.set(table.getName(), lf.structs.set.create());
}, this);
};
/** @override */
lf.cache.DefaultCache.prototype.set = function(tableName, row) {
this.map_.set(row.id(), row);
this.tableRows_.get(tableName).add(row.id());
};
/** @override */
lf.cache.DefaultCache.prototype.setMany = function(tableName, rows) {
var tableSet = this.tableRows_.get(tableName);
rows.forEach(function(row) {
this.map_.set(row.id(), row);
tableSet.add(row.id());
}, this);
};
/** @override */
lf.cache.DefaultCache.prototype.get = function(id) {
return this.map_.get(id) || null;
};
/** @override */
lf.cache.DefaultCache.prototype.getMany = function(ids) {
return ids.map(function(id) {
return this.get(id);
}, this);
};
/** @override */
lf.cache.DefaultCache.prototype.getRange = function(tableName, fromId, toId) {
var data = [];
var min = Math.min(fromId, toId);
var max = Math.max(fromId, toId);
var tableSet = this.tableRows_.get(tableName);
// Ensure the least number of keys are iterated.
if (tableSet.size < max - min) {
tableSet.forEach(
/** @this {lf.cache.DefaultCache} */
function(key) {
if (key >= min && key <= max) {
var value = this.map_.get(key);
goog.asserts.assert(
goog.isDefAndNotNull(value), 'Inconsistent cache');
data.push(value);
}
}, this);
} else {
for (var i = min; i <= max; ++i) {
if (!tableSet.has(i)) {
continue;
}
var value = this.map_.get(i);
goog.asserts.assert(goog.isDefAndNotNull(value), 'Inconsistent cache');
data.push(value);
}
}
return data;
};
/** @override */
lf.cache.DefaultCache.prototype.remove = function(tableName, id) {
this.map_.delete(id);
this.tableRows_.get(tableName).delete(id);
};
/** @override */
lf.cache.DefaultCache.prototype.removeMany = function(tableName, ids) {
var tableSet = this.tableRows_.get(tableName);
ids.forEach(function(id) {
this.map_.delete(id);
tableSet.delete(id);
}, this);
};
/** @override */
lf.cache.DefaultCache.prototype.getCount = function(opt_tableName) {
return goog.isDefAndNotNull(opt_tableName) ?
this.tableRows_.get(opt_tableName).size :
this.map_.size;
};
/** @override */
lf.cache.DefaultCache.prototype.clear = function() {
this.map_.clear();
this.tableRows_.clear();
};
| {'content_hash': '21e9e9df8de650d058ea4037cecc9442', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 78, 'avg_line_length': 24.656, 'alnum_prop': 0.6327060350421804, 'repo_name': 'ralic/lovefield', 'id': '31653dc2d73e0d8c27bad2b8d72f69a6f13b7200', 'size': '3729', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/cache/default_cache.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1909'}, {'name': 'HTML', 'bytes': '39922'}, {'name': 'JavaScript', 'bytes': '2453576'}, {'name': 'TypeScript', 'bytes': '2162'}]} |
Startup-ready web skeleton
# How to build
Run the following command:
```
mvn clean install
| {'content_hash': '3f21f4704acc969dc7a17f06ce484b6c', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 26, 'avg_line_length': 13.285714285714286, 'alnum_prop': 0.7526881720430108, 'repo_name': 'Nebulashines/devopsbuddy', 'id': '34e5bb145999e8e1982f8139cc59d5e2aefeb6ae', 'size': '107', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '5006'}, {'name': 'HTML', 'bytes': '158'}, {'name': 'Java', 'bytes': '984'}, {'name': 'Shell', 'bytes': '7058'}]} |
import React from 'react'
import '../utils/prism'
export default React.createClass({
render () {
const { language, children } = this.props
return (
<pre>
<code className={'language-' + (language || 'jsx')}>
{children()}
</code>
</pre>
)
},
componentDidMount () {
window.Prism.highlightAll()
},
componentDidUpdate () {
window.Prism.highlightAll()
}
})
| {'content_hash': 'ecb29e7150c4f1812648147de5e72c2d', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 60, 'avg_line_length': 20.095238095238095, 'alnum_prop': 0.5639810426540285, 'repo_name': 'zsherman/react-limitless', 'id': '7a3bfdd8e6b59502ef7ff4e97b1f087621e97d10', 'size': '422', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'stories/components/codeHighlight.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3592'}, {'name': 'JavaScript', 'bytes': '9696'}]} |
@charset "utf-8";
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {margin: 0; padding: 0; border: 0; font-size: inherit; font-weight:inherit; color:inherit; vertical-align: inherit; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; -webkit-tap-highlight-color:rgba(102, 102, 102, 0.3);}
html, body{width:100%; height:100%; word-break:break-all;}
body{line-height:1.1; font-size:14px; font-family:'Nanum Gothic'; color:#333; overflow-y:scroll; background:#fff;}
ol, ul{list-style: none;}
table{border-collapse: collapse;border-spacing: 0;}
table caption{display:none;}
table th, table td{vertical-align:middle;}
a, a:hover, a:link, a:focus{text-decoration: none; color:inherit;}
i{font-style:normal;}
/*FORM RESET*/
input{border:0; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; vertical-align:middle;}
input[type=email], input[type=text], input[type=password], input[type=tel], input[type=file], input[type=number], select, textarea {margin:0; padding:0; border: 1px solid #ddd; font-family:'Nanum Gothic'; font-size:inherit; resize:none; vertical-align:middle; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; height:26px; padding:0 4px; line-height:24px;}
select{height:26px; line-height:24px; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box;}
input, img{vertical-align:middle;}
input[type=file]{border:0; padding:0;}
input[type=button], input[type=submit], button{padding:0; color:inherit; font-family:'Nanum Gothic'; border:0; background:none; vertical-align:middle; cursor:pointer; font-weight:inherit; font-size:inherit; line-height:1.1;}
input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {-webkit-appearance: none; margin: 0;}
label{font-family:'Nanum Gothic';}
textarea{width:100%; height:100px; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; padding:4px; line-height:1.3;}
.hidden, .hide{display:none;}
.w10p{width:10%;}
.w20p{width:20%;}
.w30p{width:30%;}
.w40p{width:40%;}
.w50p{width:50%;}
.w60p{width:60%;}
.w70p{width:70%;}
.w80p{width:80%;}
.w90p{width:90%;}
.w100p{width:100%;}
.w5p{width:5%;}
.w15p{width:15%;}
.w25p{width:25%;}
.w35p{width:35%;}
.w45p{width:45%;}
.w55p{width:55%;}
.w65p{width:65%;}
.w75p{width:75%;}
.w85p{width:85%;}
.w95p{width:95%;}
.left{text-align:left !important;}
.right{text-align:right !important;}
.center{text-align:center !important;}
input + span.guide{margin-left:5px;}
.dateInput{position:relative; display:inline-block;}
.dateInput input.date,.dateInput input.mdate{position:relative; z-index:2; background:none; text-align:left; margin:0; padding:0 4px; font-size:12px; font-family:'굴림체'; color:#333; width:85px; font-weight:700; vertical-align:middle;}
.dateInput .before{position:absolute; top:50%; left:0; z-index:1; width:100%; height:100%; padding:0 4px; margin-top:-11px; line-height:22px; border:1px solid transparent; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; font-size:12px; color:#ddd; font-family:'굴림체'; font-weight:700;}
.dateInput .before span{color:#fff; opacity:0;}
.loading_layer{position:fixed; top:0; left:0; z-index:5000; width:100%; height:100%; background:rgba(0,0,0,0.0); color:rgba(255, 255, 255, 0.0); font-size:14px; text-align:center;}
.loading_layer p{position:absolute; top:45%; left:0; width:100%; margin-top:55px; font-family:'Verdana'; font-weight:700;}
label.checkbox{position:relative; display:inline-block; line-height:16px; vertical-align:middle;}
label.checkbox input{position:absolute; top:0; left:0; opacity:0; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0, 0, 0, 0);}
label.checkbox input ~ span{position:relative; display:block; width:100%; height:100%; padding-left:21px;}
label.checkbox input ~ span:before{content:' '; position:absolute; top:50%; left:0; display:block; width:14px; height:14px; border:1px solid #aaa; background:#fff; color:#c00; text-align:center; line-height:14px; font-size:14px; -moz-transform:translate(0, -50%); -webkit-transform:translate(0, -50%); -ms-transform:translate(0, -50%); -o-transform:translate(0, -50%); transform:translate(0, -50%);}
label.checkbox input:checked ~ span:before{content:'\2714'; font-weight:400;}
label.radio{position:relative; display:inline-block; line-height:16px; vertical-align:middle;}
label.radio input{position:absolute; top:0; left:0; opacity:0; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0, 0, 0, 0);}
label.radio input ~ span{position:relative; display:block; width:100%; height:100%; padding-left:21px;}
label.radio input ~ span:before{content:' '; position:absolute; top:50%; left:0; display:block; width:14px; height:14px; border:1px solid #aaa; background:#fff; color:#c00; text-align:center; line-height:14px; font-size:14px; border-radius:100%; -webkit-border-radius:100%; -moz-border-radius:100%; -moz-transform:translate(0, -50%); -webkit-transform:translate(0, -50%); -ms-transform:translate(0, -50%); -o-transform:translate(0, -50%); transform:translate(0, -50%);}
label.radio input:checked ~ span:after{content:' '; position:absolute; top:50%; left:3px; display:block; width:10px; height:10px; background:#666; border-radius:100%; -webkit-border-radius:100%; -moz-border-radius:100%; -moz-transform:translate(0, -50%); -webkit-transform:translate(0, -50%); -ms-transform:translate(0, -50%); -o-transform:translate(0, -50%); transform:translate(0, -50%);}
.selectBox{display:inline-block; position:relative; border:1px solid #d6d6d6; background:#fff; cursor:pointer; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; font-size:12px; overflow:hidden; vertical-align:middle;}
.selectBox:before,.selectBox:after{content:''; position:absolute; top:0; right:0; width:30px; height:100%; background:#f8f8f8; text-align:center;}
.selectBox:after{content:'\2039'; top:50%; height:auto; line-height:20px; margin-top:-10px; background:none; color:#999; font-size:13px; -moz-transform:rotate(-90deg) scale(0.5,1); -webkit-transform:rotate(-90deg) scale(0.5,1); -ms-transform:rotate(-90deg) scale(0.5,1); -o-transform:rotate(-90deg) scale(0.5,1); transform:rotate(-90deg) scale(0.5,1); font-weight:800;}
.selectBox span.selected{position:absolute; top:0; left:0; display:block; height:100%; width:100%; padding:0 35px 0 10px; font-weight:300; color:#222; white-space:nowrap; overflow:hidden; -ms-text-overflow:ellipsis; text-overflow:ellipsis; font-size:inherit;}
.selectBox span.selected:before{content:' '; display:inline-block; width:0; height:100%; vertical-align:middle;}
.selectBox select{position:relative; z-index:2; opacity:0; -ms-filter:alpha(opacity=0); margin:0; padding:0 35px 0 10px; border:0; color:#333; font-size:inherit;}
.MessageModal{position:fixed; top:0; left:0; z-index:6000; width:100%; height:100%; min-width:320px; background:rgba(0,0,0,0.5); font-size:13px; color:#333;}
.MessageModal .MessageModalWrap{position:absolute; top:50%; left:50%; min-width:250px; max-width:500px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0, 0, 0, 0.3); -moz-box-shadow:2px 2px 3px rgba(0, 0, 0, 0.3); box-shadow:2px 2px 3px rgba(0, 0, 0, 0.3); border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; overflow:hidden; -moz-transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); -ms-transform:translate(-50%, -50%); -o-transform:translate(-50%, -50%); transform:translate(-50%, -50%);}
.MessageModal .MessageModalWrap > header{padding:7px; font-weight:700; background:#999; color:#fff;}
.MessageModal .MessageModalWrap > div.text{padding:10px; min-height:70px;}
.MessageModal .MessageModalWrap > footer{padding:7px 15px; text-align:right; background:#f6f6f6;}
.MessageModal .MessageModalWrap > footer a{display:inline-block; margin-left:4px; font-weight:700; padding:2px 5px;}
.MessageModal .MessageModalWrap > footer a:focus{background:#ddd;}
span.uploadedFile{display:inline-block; padding:3px 5px; border:1px solid #ccc; background:#eee; border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px;}
.fileUploadArea{padding:10px 0;}
.fileUploadArea + .fileUploadArea{padding-top:0;}
.fileUploadImage{display:inline-block; vertical-align:middle;}
.fileUploadImage img{display:block; max-width:100px; max-height:100px;}
.fileUploadImage i{display:block; width:100px; height:100px; background:no-repeat center center; -webkit-background-size:contain; background-size:contain;}
.fileUploadArea2{padding:10px 0;}
.fileUploadArea2 + .fileUploadArea2{padding-top:0;}
.fileUploadArea2 p{display:inline-block;}
.jqFileUploadArea .progress{display: inline-block; height: 20px; width: 100px; overflow: hidden; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; background:#eee;vertical-align: middle;}
.jqFileUploadArea .progress .bar{width: 0%; height: 100%;}
.cross{position:relative; display:inline-block; font-size:12px; width:1em; height:1em; vertical-align:middle; overflow:hidden;}
.cross:before{content:''; position:absolute; top:0.5em; left:0.5em; display:block; width:1px; height:1.4142em; -moz-transform:translate(-50%, -50%) rotate(45deg); -webkit-transform:translate(-50%, -50%) rotate(45deg); -ms-transform:translate(-50%, -50%) rotate(45deg); -o-transform:translate(-50%, -50%) rotate(45deg); transform:translate(-50%, -50%) rotate(45deg); background:#000;}
.cross:after{content:''; position:absolute; top:0.5em; left:0.5em; display:block; width:1px; height:1.4142em; -moz-transform:translate(-50%, -50%) rotate(-45deg); -webkit-transform:translate(-50%, -50%) rotate(-45deg); -ms-transform:translate(-50%, -50%) rotate(-45deg); -o-transform:translate(-50%, -50%) rotate(-45deg); transform:translate(-50%, -50%) rotate(-45deg); background:#000;}
#checkActionModal .modal_wrap{width:400px; height:auto !important;}
#checkActionModal .modal_contents{padding:10px;}
#checkActionModal .selected{padding:5px; border:1px solid #666;}
#checkActionModal .selected b{font-weight:700;}
#checkActionModal div.group{padding:10px; margin-top:10px; height:250px; border:1px solid #ccc; overflow-y:scroll;}
#checkActionModal button.boardActionGroupBtn{position:relative; margin-bottom:5px; height:24px; width:100%; padding:0 10px; background:#999; color:#fff; text-align:left;}
#checkActionModal ul{display:none;}
#checkActionModal li{border-bottom:1px solid #ddd;}
#checkActionModal li button{display:block; width:100%; text-align:left; padding:5px;}
#checkActionModal li button:hover{background:#eee;}
#checkActionModal li.active button{background:#555; color:#fff; font-weight:700;}
#checkActionModal .bottomBtn{margin-top:0; padding:10px 0;}
#checkActionModal .selectedCategory select{margin-top:5px; width:100%;}
.youtubeFrameWrap{position:relative; width:100%; height:0; padding-bottom:56.25%;}
.youtubeFrameWrap iframe{position:absolute; top:0; left:0; width:100%; height:100%;}
.se2_addi_btns{padding:2px 5px; border:1px solid #ddd; border-bottom:0; background:#f4f4f4; font-size:12px; font-weight:700; color:#666; text-align:right;}
.se2_addi_btns > div{display:inline-block;}
.se2_addi_btns > div + div{margin-left:5px;}
.se2_addi_btns button{height:18px; padding:0 5px; border:1px solid #aaa; background:-webkit-linear-gradient(#fff, #fff, #fff, #eee); background:-moz-linear-gradient(#fff, #fff, #fff, #eee); background:-o-linear-gradient(#fff, #fff, #fff, #eee); background:linear-gradient(#fff, #fff, #fff, #eee); border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px;}
.se2_addi_btns .se2_add_img button i{position:relative; display:inline-block; width:12px; height:12px; border:1px solid #b18d82; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px; background:#fff; margin-right:5px; overflow:hidden;}
.se2_addi_btns .se2_add_img button i:after{content:''; position:absolute; top:100%; left:50%; width:30px; height:30px; margin:-4px 0 0 -15px; border-radius:50%; -webkit-border-radius:50%; -moz-border-radius:50%; background:#0db01c;}
.se2_addi_btns .se2_add_img button i:before{content:''; position:absolute; top:10%; right:10%; width:4px; height:4px; display:block; border-radius:50%; -webkit-border-radius:50%; -moz-border-radius:50%; background:#ff8d46;}
.se2_addi_btns .se2_add_youtube button i{position:relative; display:inline-block; width:12px; height:8px; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px; background:#c11; margin-right:5px; overflow:hidden;}
.se2_addi_btns .se2_add_youtube button i:before{content:''; display:block; width:1px; height:150%;}
.se2_addi_btns .se2_add_youtube button i:after{content:''; position:absolute; top:50%; left:50%; display:block; border-top:2px solid transparent; border-left:4px solid #fff; border-bottom:2px solid transparent; margin:-2px 0 0 -2px;}
.se2_addi_btns .se2_add_link button i{position:relative; display:inline-block; width:14px; height:14px; margin-right:5px; overflow:hidden;}
.se2_addi_btns .se2_add_link button i:before{content:''; display:block; width:4px; height:2px; border:2px solid #666; border-radius:4px; -webkit-border-radius:4px; -moz-border-radius:4px; -moz-transform:translate(0, 5px) rotate(-45deg); -webkit-transform:translate(0, 5px) rotate(-45deg); -ms-transform:translate(0, 5px) rotate(-45deg); -o-transform:translate(0, 5px) rotate(-45deg); transform:translate(0, 5px) rotate(-45deg);}
.se2_addi_btns .se2_add_link button i:after{content:''; position:absolute; top:0; left:0; display:block; width:4px; height:2px; border:2px solid #888; border-radius:4px; -webkit-border-radius:4px; -moz-border-radius:4px; -moz-transform:translate(5px, 3px) rotate(-45deg); -webkit-transform:translate(5px, 3px) rotate(-45deg); -ms-transform:translate(5px, 3px) rotate(-45deg); -o-transform:translate(5px, 3px) rotate(-45deg); transform:translate(5px, 3px) rotate(-45deg);}
#youtubeLinkModal .modal_wrap{width:500px; height:350px;}
#youtubeLinkModal .modal_contents{padding:20px;}
#youtubeLinkModal textarea{height:150px; border:1px solid #ccc;}
#youtubeLinkModal input[type=text]{width:60px; margin-right:5px; border:1px solid #ccc; height:24px;}
#youtubeLinkModal textarea{height:150px; border:1px solid #ccc;}
#youtubeLinkModal dl{display:table; width:100%; table-layout:fixed;}
#youtubeLinkModal dt{display:table-cell; width:80px; padding:2px;}
#youtubeLinkModal dd{display:table-cell; padding:2px;}
#youtubeLinkModal footer{margin-top:10px; text-align:center;}
#urlLinkModal .modal_wrap{width:500px; height:170px;}
#urlLinkModal .modal_contents{padding:20px;}
#urlLinkModal textarea{height:150px; border:1px solid #ccc;}
#urlLinkModal input[type=text]{border:1px solid #ccc; height:24px;}
#urlLinkModal textarea{height:150px; border:1px solid #ccc;}
#urlLinkModal dl{display:table; width:100%; table-layout:fixed;}
#urlLinkModal dt{display:table-cell; width:80px; padding:2px;}
#urlLinkModal dd{display:table-cell; padding:2px;}
#urlLinkModal footer{margin-top:10px; text-align:center;}
html{font-size:31.25vw;}
@media (min-width:1000px){
html{font-size:312.5px;}
}
@media (max-width:320px){
html{font-size:100px;}
}
/* ---------------------------------------------------------------------
*Common
* --------------------------------------------------------------------- */
.colorTest{color:#e6ecf2; color:#b8c2cc; color:#828b99; color:#3c4155; color:#713f73; color:#341133; color:#3de7a5; color:#585f7c;}
body{font-size:13px; background:#e6ecf2; color:#222;}
a.sBtn, button.sBtn{display:inline-block; padding:3px 10px; background:#929599; color:#fff; vertical-align:middle; font-size:12px; line-height:16px;}
a.mBtn, button.mBtn{display:inline-block; min-width:100px; height:30px; padding:0 10px; text-align:center; background:#929599; color:#fff; vertical-align:middle; font-size:14px; line-height:18px;}
a.bBtn, button.bBtn{display:inline-block; min-width:200px; height:40px; text-align:center; padding:0 20px; background:#929599; color:#fff; vertical-align:middle; font-size:16px; line-height:24px;}
a.sBtn:before, a.mBtn:before, a.bBtn:before{content:''; display:inline-block; width:0; height:100%; vertical-align:middle;}
a.btn1, button.btn1{background:#fff; color:#333; border:1px solid #ccc;}
a.btn2, button.btn2{background:#3c4155; color:#fff;}
a.btn3, button.btn3{background:#c10; color:#fff;}
.left{text-align:left !important;}
.right{text-align:right !important;}
.center{text-align:center !important;}
input[type=email], input[type=text], input[type=password], input[type=tel], input[type=file], select, textarea {border-radius:0; -webkit-border-radius:0; -moz-border-radius:0; height:30px; line-height:28px;}
select{height:30px; line-height:28px;}
.articleAction{padding-top:50px; text-align:center;}
.articleAction ul{display:inline-block;}
.articleAction ul:after{content:' '; display:block; clear:both}
.articleAction li{float:left;}
.articleAction a{display:inline-block; height:22px; width:70px; margin:0 5px; color:#fff; font-size:12px; background:#713f73;}
.articleAction a:before{content:''; display:inline-block; width:0; height:100%; vertical-align:middle;}
.articleAction a span.num{font-weight:700;}
.articleAction a.already{background:#341133;}
.leftBoardSearch, .left_btn{float:left; margin-top:20px; padding-bottom:20px;}
.rightBoardSearch, .right_btn{float:right; margin-top:20px; padding-bottom:20px;}
.boardSearch{padding-bottom:20px; margin-top:20px;}
.bottomBtn{padding:30px 0; text-align:center;}
.bottomBtn a + button, .bottomBtn button + a, .bottomBtn button + button, .bottomBtn a + a{margin-left:5px;}
.moreViewBtn{margin-top:20px; text-align:center;}
.moreViewBtn a{display:inline-block; width:300px; border:1px solid #ccc; line-height:30px; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; background:#f8f8f8;}
.left_btn + .table, .right_btn + table{clear:both;}
.right_btn + .paging, .left_btn + .paging{padding-top:0;}
p.alert{padding-bottom:20px; color:#c10;}
.modalConfirm{position:fixed; top:0; left:0; z-index:100; width:100%; height:100%; background:#999; background:rgba(0,0,0,0.1);}
.modalConfirm form{position:absolute; top:50%; left:50%; width:300px; padding:20px; margin:-80px 0 0 -150px; border:2px solid #333; background:#fff; text-align:center;}
.modalConfirm p{font-weight:700; padding-bottom:15px;}
.modalConfirm .sPopBtns{padding-top:10px;}
.modalConfirm .sPopBtns button + *{margin-left:5px;}
.modalConfirm .sPopBtns a + *{margin-left:5px;}
.nothing{text-align:center; color:#888; padding:20px 0;}
span.secretDoc{position:relative; display:inline-block; width:16px; height:16px; overflow:hidden; vertical-align:middle;}
span.secretDoc:before{content:''; display:block; width:10px; height:8px; margin:6px auto 5px; background:#828b99; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px;}
span.secretDoc:after{content:''; position:absolute; top:1px; left:50%; display:block; width:5px; height:10px; border:1px solid #828b99; border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px; -moz-transform:translate(-50%, 0); -webkit-transform:translate(-50%, 0); -ms-transform:translate(-50%, 0); -o-transform:translate(-50%, 0); transform:translate(-50%, 0);}
span.newDoc{position:relative; display:inline-block; width:12px; height:14px; margin-left:3px; overflow:hidden; vertical-align:middle; border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px; background:#ff963f; color:#fff;}
span.newDoc:before{content:'N'; display:block; height:100%; margin-bottom:5px; font-weight:800; font-size:10px; text-align:center; line-height:14px;}
span.answerDoc{position:relative; display:inline-block; width:14px; height:14px; margin-right:3px; overflow:hidden; vertical-align:middle;}
span.answerDoc:before{content:''; display:block; width:50%; height:50%; margin-bottom:100%; border:1px solid #828b99; border-width:0 0 4px 1px; border-radius:50% 0 0 50%; -webkit-border-radius:50% 0 0 50%; -moz-border-radius:50% 0 0 50%;}
span.answerDoc:after{content:''; position:absolute; top:50%; right:0; display:block; border-left:8px solid #828b99; border-top:5px solid transparent; border-bottom:5px solid transparent; -moz-transform:translate(0, -50%); -webkit-transform:translate(0, -50%); -ms-transform:translate(0, -50%); -o-transform:translate(0, -50%); transform:translate(0, -50%); margin-top:2px;}
/* ---------------------------------------------------------------------
*Contents
* --------------------------------------------------------------------- */
#wrap{width:100%; height:100%; min-width:1220px;}
#header{position:relative; z-index:2; background:#fff; -webkit-box-shadow:0 2px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow:0 2px 2px rgba(0, 0, 0, 0.05); box-shadow:0 2px 2px rgba(0, 0, 0, 0.05);}
#header #header_wrap{position:relative; width:1200px; z-index:2; height:60px; padding-left:200px; margin:0 auto;}
#header h1{position:absolute; top:0; left:0; height:100%; z-index:2; font-weight:800; font-size:18px; line-height:60px; color:#555; background:#fff; text-align:center; width:200px;}
#header h1 i{margin-right:10px;}
#header h1 i img{width:45px;}
#header #gnb{height:24px;}
#header #gnb:after{content:' '; display:block; clear:both}
#header #gnb ul{float:right; height:100%; padding:1px 0; text-align:right; font-size:12px;}
#header #gnb ul:after{content:' '; display:block; clear:both}
#header #gnb li{float:left; height:100%; display:inline-block; color:#fff; background:#828b99; font-weight:700;}
#header #gnb li.admin{background:#c10; color:#fff;}
#header #gnb li a{display:block; height:100%; padding:0 10px;}
#header #gnb li a:after{content:''; display:inline-block; width:0; height:100%; vertical-align:middle;}
#header #gnb li + li{margin-left:1px;}
#header #gnb li:hover{color:#fff; background:#b8c2cc;}
#header #gnb li.admin:hover{background:#f33; color:#fff; font-weight:700;}
#header #tnb{width:100%; height:36px; padding:3px 0; font-weight:700; font-size:15px;}
#header #tnb ul{height:100%;}
#header #tnb ul:after{content:' '; display:block; clear:both}
#header #tnb ul > li{position:relative; float:left; height:100%; width:20%;}
#header #tnb ul > li > a{display:block; height:100%; color:#333; text-align:center;}
#header #tnb ul > li > a:after{content:''; display:inline-block; width:0; height:100%; vertical-align:middle;}
#header #tnb ul > li:hover > a{background:#e6ecf2; color:#333;}
#header #tnb ul > li.active > a{background:#828b99; color:#fff;}
#header #tnb ul ol{position:absolute; left:0; top:100%; display:none; width:100%; line-height:1.2em; background:#fff; border:1px solid #fff; -webkit-box-shadow:2px 2px 2px rgba(0,0,0,0.05); -moz-box-shadow:2px 2px 2px rgba(0,0,0,0.05); box-shadow:2px 2px 2px rgba(0,0,0,0.05);}
#header #tnb ul ol li{position:relative; font-size:11px; font-weight:700; color:#666; overflow:hidden;}
#header #tnb ul ol li + li{margin-top:1px;}
#header #tnb ul ol li a{display:block; height:100%; padding:5px 10px;}
#header #tnb ul ol li:hover{background:#e6ecf2; color:#333;}
#header #tnb ul ol li.active{color:#fff; background:#828b99;}
#header #tnb ul ol li:first-child:before{content:none;}
#header #tnb ul > li:hover ol{display:block;}
#container{padding:60px 0 130px; min-height:100%; width:1200px; margin:-60px auto 0;}
#container_wrap{position:relative; padding:0;}
#container_wrap:after{content:' '; display:block; clear:both;}
#footer{margin-top:-130px; height:130px; background:#fff;}
#footer #footer_wrap{position:relative; width:1200px; margin:0 auto;}
#footer #fnb{height:26px; background:#828b99; color:#fff; font-size:13px;}
#footer #fnb ul{width:1200px; margin:0 auto; text-align:center;}
#footer #fnb li{position:relative; display:inline-block; line-height:26px; padding:0 10px;}
#footer #fnb li:before{content:''; position:absolute; left:0; top:50%; height:10px; width:1px; margin-top:-5px; background:#ddd;}
#footer #fnb li:first-child:before{content:none;}
#footer #footerInfo{position:relative; height:104px; width:1200px; margin:0 auto; padding:10px 0 0 240px; font-size:13px; color:#888; line-height:1.3;}
#footer #footerInfo h1{position:absolute; top:10px; left:0; width:200px; font-size:30px; font-weight:800; color:#333;}
#footer #footerInfo h1 img{max-width:100%;}
#footer #footerInfo dl{float:left;}
#footer #footerInfo dl + dl{margin-left:15px;}
#footer #footerInfo dt{display:inline-block;}
#footer #footerInfo dd{display:inline-block; font-weight:700;}
#footer #footerInfo dd:before{content:' : '; font-weight:400;}
#footer #footerInfo dl.address,#footer #footerInfo dl.bNum{clear:left; margin-left:0;}
#footer .copyright{clear:both; padding-top:10px; font-size:13px; color:#666;}
#footer .copyright b{font-weight:700; color:#333;}
#contents h2{padding:7px 10px; font-size:16px; font-weight:700; background:#e6ecf2; color:#3c4155;}
.BH_Popup{position:absolute; top:0; left:0; z-index:10; border:1px solid #888;}
.BH_PopupContent{overflow-y:auto; overflow-x:hidden;}
.BH_PopupContent img{max-width:100%; width:auto; height:auto;}
.BH_PopupBtns{line-height:21px; background:#333; color:white; font-size:12px;}
.BH_PopupBtns a{cursor:pointer;}
.BH_PopupBtns:after{content:' '; display:block; clear:both;}
.BH_PopupTodayClose{float:left; display:block; padding:5px 10px;}
.BH_PopupClose{float:right; display:block; padding:5px 10px;}
.guide{color:#999; font-size:11px;}
ul.guide, p.guide{padding-top:5px;}
i.requiredBullet{font-weight:700; color:#c10; float:left; margin-right:5px; -moz-transform:translate(0, -5px); -webkit-transform:translate(0, -5px); -ms-transform:translate(0, -5px); -o-transform:translate(0, -5px); transform:translate(0, -5px);}
table.write{width:100%; table-layout:fixed; font-size:12px;}
table.write th{width:150px; padding:5px 10px; border:1px solid #b8c2cc; border-width:1px 0; text-align:left; background:#e6ecf2; color:#585f7c; height:40px; font-weight:700;}
table.write td{padding:5px 10px; border:1px solid #e6ecf2; border-width:1px 0; text-align:left;}
table.write label + label{margin-left:10px;}
table.write select + select{margin-left:10px;}
table.write p + p{margin-top:5px;}
table.write textarea{height:250px;}
table.list{width:100%; table-layout:fixed; font-size:0.9em;}
table.list th{width:100px; padding:5px 10px; border:1px solid #D3D6DF; border-width:1px 0; text-align:center; background:#F2F3F5;}
table.list td{padding:10px; border:1px solid #D3D6DF; border-width:1px 0; text-align:center;}
table.list a{text-decoration:underline;}
table.list img{max-width:200px; max-height:100px;}
table.view{width:100%; table-layout:fixed;}
table.view th{width:150px; padding:10px; border:1px solid #D3D6DF; border-width:1px 0; text-align:left; background:#F2F3F5;}
table.view td{padding:10px; border:1px solid #D3D6DF; border-width:1px 0; text-align:left;}
h2 + .boardList,
h2 + table.list{margin-top:20px;}
.paging{clear:both; padding:20px; text-align:center;}
.paging span,.paging a,.paging strong{display:inline-block; padding:0 10px; border:1px solid #D3D6DF; color:#D3D6DF; line-height:30px; height:30px; overflow:hidden; font-size:13px;}
.paging a{color:inherit;}
.paging strong{background:#6EA9AF; color:white; border:0; font-size:16px;}
.paging .first,.paging .prev,.paging .prevp,.paging .nextp,.paging .next,.paging .last{width:30px;}
.paging .first:before{content:'\f048'; display:block; height:100%; font-family:'FontAwesome';}
.paging .prev:before{content:'\f100'; display:block; height:100%; font-family:'FontAwesome';}
.paging .prevp:before{content:'\f104'; display:block; height:100%; font-family:'FontAwesome';}
.paging .nextp:before{content:'\f105'; display:block; height:100%; font-family:'FontAwesome';}
.paging .next:before{content:'\f101'; display:block; height:100%; font-family:'FontAwesome';}
.paging .last:before{content:'\f051'; display:block; height:100%; font-family:'FontAwesome';}
#contents.board{padding:20px; width:970px; margin:20px auto; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.board:after{content:' '; display:block; clear:both}
#contents.board .categoryTab{margin-top:20px; padding-bottom:10px;}
#contents.board .categoryTab ul:after{content:' '; display:block; clear:both;}
#contents.board .categoryTab li{float:left;}
#contents.board .categoryTab li a{display:block; padding:0 10px; font-size:13px; color:#333;}
#contents.board .categoryTab li.active a{font-weight:700; color:#c10;}
#contents.board .categoryTab li + li{border-left:1px solid #ccc;}
#contents.board .categoryTab li.parent a{color:#999;}
#contents.board h2 + section.boardList{margin-top:20px;}
#contents.board h2 + #BoardWriteForm{margin-top:20px;}
.BoardView header{border-bottom:1px solid #e6ecf2;}
.BoardView header div{padding:40px 10px 10px; border-bottom:1px solid #e6ecf2; font-weight:700; font-size:17px;}
.BoardView header ul{padding:10px; font-size:0.87em; color:#828b99;}
.BoardView header ul:after{content:' '; display:block; clear:both;}
.BoardView header li{float:right; margin-left:15px;}
.BoardView header li.mname{float:left; margin-left:0;}
.BoardView .contents{padding:20px 10px; min-height:300px;}
.BoardView .contents img{max-width:100% !important;}
.BoardView .links{display:table; width:100%; table-layout:fixed; border-bottom:1px solid #e6ecf2;}
.BoardView .links dt{display:table-cell; width:50px; color:#b8c2cc; font-weight:700; font-size:11px; vertical-align:middle; padding:5px 10px;}
.BoardView .links dd{display:table-cell; vertical-align:middle; padding:5px 10px;}
.BoardView .links a{font-weight:700; font-size:12px; text-decoration:underline;}
.BoardView div.image{padding-bottom:10px;}
.youtube{margin-bottom:10px;}
#boardSelectModal .modal_wrap{height:auto;}
ul.boardSelectForW{padding:20px;}
ul.boardSelectForW li{padding:2px; text-align:center; font-weight:700; color:#3c4155;}
ul.boardSelectForW li a{display:block; padding:20px; border:2px solid #e6ecf2;}
ul.boardSelectForW li a:hover{background:#3c4155; border-color:#828b99; color:#fff;}
.fileUploadArea2 span.fileName{display:inline-block; padding-left:5px; font-size:11px; font-weight:700; color:#828b99;}
.fileUploadArea2 .fileUploadBtn{background:#828b99;}
#Reply{padding-top:50px;}
#Reply h3{font-weight:700; padding-bottom:5px;}
#Reply h3 span{font-weight:400; color:#888; font-size:12px;}
.replyWrite{margin-bottom:20px; padding-bottom:5px;}
.replyWrite fieldset{padding:5px 0;border-top:1px solid #b8c2cc;}
.replyWrite fieldset.user{display:table; width:100%; table-layout:fixed; background:#e6ecf2;}
.replyWrite fieldset.user dl{display:table-cell;}
.replyWrite fieldset.user dt{display:inline-block; width:100px; text-align:center; font-size:12px; font-weight:700; color:#828b99;}
.replyWrite fieldset.user dd{display:inline-block;}
.replyWrite fieldset.text{position:relative; padding-right:150px;}
.replyWrite fieldset.text textarea{height:100px; margin:0;}
.replyWrite fieldset.text .btn{position:absolute; top:5px; right:0; width:140px; height:100px;}
.replyWrite fieldset.text .btn button{width:100%; height:100%; background:#828b99; font-size:1.8em; color:#fff; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; text-align:center;}
.replyWrite div.option{padding:0;}
.replyWrite div.option:after{content:' '; display:block; clear:both}
.replyWrite div.option > span{float:left; width:80px;}
.replyWrite div.option .fileUploadArea2{padding:0; float:left;}
.replyAnswer fieldset.text{padding-right:0;}
.modifyForm fieldset.text{padding-right:0;}
.modifyForm form:after{content:' '; display:block; clear:both;}
.modifyForm .pwdinp{float:left; width:70%; padding:0; border:0;}
.modifyForm .pwdinp p{display:inline-block; font-size:11px; margin-right:5px; color:#828b99;}
.replyDelete{position:absolute; top:50%; left:50%; padding:10px 20px; margin-bottom:0; border:1px solid #e6ecf2; background:rgba(255, 255, 255, 0.8); -moz-transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); -ms-transform:translate(-50%, -50%); -o-transform:translate(-50%, -50%); transform:translate(-50%, -50%); text-align:center;}
.replyDelete fieldset{border:0;}
.replyDelete fieldset.pwd p{font-size:11px; margin-right:5px; color:#828b99; line-height:15px; vertical-align:middle; font-weight:700;}
.replyDelete fieldset.pwd span.pwdinp{display:block; padding-top:10px; vertical-align:middle;}
.replyDelete .btn{padding-top:10px;}
#replyListContents{font-size:0.90em;}
#replyListContents article{position:relative; border-bottom:1px solid #b8c2cc;}
#replyListContents article:first-child{border-top:1px solid #b8c2cc;}
#replyListContents header{padding:7px; background:#e6ecf2;}
#replyListContents header:after{content:' '; display:block; clear:both}
#replyListContents header b{display:inline-block; font-weight:700; margin-right:5px;}
#replyListContents .btns{float:right;}
#replyListContents .btns a{float:left; display:block; padding:2px 5px; background:#3c4155; color:#fff; font-size:0.9em; border-radius:2px; -webkit-border-radius:2px; -moz-border-radius:2px;}
#replyListContents .btns a + a{margin-left:5px;}
#replyListContents .btns a.replyActionBtn{font-weight:400; border:1px solid #3c4155; line-height:11px; background:#828b99; color:#fff;}
#replyListContents .btns a.replyActionBtn.already{font-weight:700; background:#3c4155;}
#replyListContents .btns a.replyReportActionBtn{background:#713f73; border-color:#341133; color:#fff;}
#replyListContents .btns a.replyReportActionBtn.already{background:#341133;}
#replyListContents form .btn{text-align:right;}
#replyListContents form .btn button + button{margin-left:5px;}
#replyListContents .comment{padding:10px; line-height:1.5em;}
#replyListContents .comment b{color:#999; margin-right:10px;}
#replyListContents a.pwdView{color:#713f73; display:inline-block; margin-left:5px; font-weight:700;}
.repLayer{position:fixed; top:0; left:0; z-index:100; width:100%; height:100%; background:#999; background:rgba(0,0,0,0.1);}
.repLayer form{position:absolute; top:50%; left:50%; width:400px; padding:20px; margin:-80px 0 0 -150px; border:2px solid #333; background:#fff; text-align:center;}
.repLayer div.btn{padding-top:10px;}
.repLayer div.btn button + button{margin-left:5px;}
.repLayer .targetContent{text-align:left; font-size:0.9em;}
.repLayer textarea{height:80px;}
.repLayer fieldset.user{text-align:left;}
.repLayer fieldset.user dl,.repLayer .repLayer fieldset.user dt,.repLayer .repLayer fieldset.user dd{display:inline-block;}
.repLayer fieldset.user dd input{width:100px;}
.repLayer fieldset.pwd{text-align:center;}
.repLayer fieldset.pwd p{font-weight:700; padding:15px 0 5px;}
#contents.login2{padding:100px 0;}
#contents.login2 #login_wrap2{width:400px; padding:20px; margin:0 auto; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.login2 #login_wrap2 fieldset{padding-top:20px;}
#contents.login2 #login_wrap2 fieldset:after{content:' '; display:block; clear:both;}
#contents.login2 #login_wrap2 fieldset label{display:block; padding-left:10px; line-height:30px; font-weight:700;}
#contents.login2 #login_wrap2 fieldset label:after{content:' '; display:block; clear:both}
#contents.login2 #login_wrap2 fieldset label span.tt{float:left; display:block; width:33%; line-height:30px;}
#contents.login2 #login_wrap2 fieldset input{float:left; width:67%;}
#contents.login2 #login_wrap2 fieldset label + label{margin-top:10px;}
#contents.login2 #login_wrap2 #LoginRemember{padding:20px 10px 0;}
#contents.login2 #login_wrap2 #LoginConfirm{margin-top:30px; padding-top:20px; border-top:1px solid #b8c2cc;}
#contents.login2 #login_wrap2 #LoginConfirm button{width:100%; margin:0; font-weight:700;}
#contents.login2 #login_wrap2 #link a{width:100%; margin-top:5px; font-weight:700;}
#contents.register{width:800px; padding:20px; margin:50px auto; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.register h3{padding:5px; font-weight:700; font-size:12px; color:#fff; background:#828b99;}
#contents.register form{padding-top:20px;}
#contents.register fieldset > .txt{height:200px; padding:10px; border:1px solid #b8c2cc; overflow-y:scroll;}
#contents.register fieldset > p.chk{padding:5px; text-align:right; font-size:12px; color:#666; font-weight:700;}
#contents.register fieldset + fieldset{margin-top:20px;}
#contents.register form > p{padding:10px 0; margin-top:20px; border:1px solid #b8c2cc; border-width:1px 0; text-align:center; font-weight:700; font-size:13px;}
#contents.registerForm{width:600px; margin:50px auto; padding:20px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.registerForm p.alert{margin-top:20px;}
#contents.registerForm table.write{margin-top:20px;}
#contents.registerForm p.alert + table.write{margin-top:0;}
#contents.registerForm input[type=text],#contents.registerForm input[type=password],#contents.registerForm input[type=tel],#contents.registerForm input[type=email],#contents.registerForm input[type=number]{width:60%;}
#contents.registerForm input + button{margin-left:5px;}
#contents.findIDPW{padding:50px 0; width:1000px; margin:0 auto;}
#contents.findIDPW .findWrap{float:left; width:48%; padding:20px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.findIDPW .findWrap~ .findWrap{margin-left:4%;}
#contents.findIDPW .findWrap > p{padding:30px 0; text-align:center; color:#999; font-size:13px;}
#contents.findIDPW .findWrap form fieldset{height:130px;}
#contents.findIDPW .findWrap form dl{display:table; width:100%; table-layout:fixed;}
#contents.findIDPW .findWrap form dl + dl{margin-top:10px;}
#contents.findIDPW .findWrap form dt{display:table-cell; width:150px; font-size:12px; font-weight:700;}
#contents.findIDPW .findWrap form dd{display:table-cell;}
#contents.findIDPW .findWrap form input[type=text],#contents.findIDPW .findWrap form input[type=password],#contents.findIDPW .findWrap form input[type=tel],#contents.findIDPW .findWrap form input[type=email],#contents.findIDPW .findWrap form input[type=number]{width:100%;}
#lnb{float:left; width:200px; padding:10px; margin-top:20px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#lnb h2{height:120px; padding-top:48px; font-size:20px; background:#3c4155; text-align:center; color:#fff;}
#lnb nav li a{display:block; padding:15px 10px; font-size:13px; color:#585f7c;}
#lnb nav li.active,#lnb nav li:hover{background:#e6ecf2;}
#lnb nav li + li{border-top:1px solid #b8c2cc;}
#lnb + #contents{float:right; width:980px; padding:20px; margin-top:20px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
div.MyPageMain{font-size:14px;}
div.MyPageMain h3{margin-top:20px; padding:5px; font-weight:700; font-size:14px; color:#828b99;}
#PasswordForm{padding:100px 0; text-align:center;}
#PasswordForm form{width:400px; padding:3px 0; margin:0 auto;}
#PasswordForm p{margin-bottom:30px; color:#888; font-weight:700;}
#WithdrawForm{padding:20px 0;}
#WithdrawForm p{padding:20px; background:#eee;}
#WithdrawForm ul{padding:30px;}
#WithdrawForm li{padding:5px 0;}
#WithdrawForm .reason_etc{display:table; width:100%;}
#WithdrawForm .reason_etc label{display:table-cell; width:10%; margin:0;}
#WithdrawForm .reason_etc span{display:table-cell; width:90%;}
#WithdrawForm .reason_etc span textarea{margin:0; height:100px;}
section.boardList{font-size:13px;}
section.boardList ul{display:table; width:100%; table-layout:fixed;}
section.boardList li{display:table-cell; text-align:center; padding:10px 5px;}
section.boardList li.check{width:40px;}
section.boardList li.num{width:60px;}
section.boardList li.category{width:140px;}
section.boardList li.name{width:120px;}
section.boardList li.date{width:140px; font-size:12px;}
section.boardList > header{background:#828b99; color:#fff;}
section.boardList > header li{padding:5px;}
section.boardList .articles li{border-bottom:1px solid #e6ecf2;}
section.boardList .articles li.subject{text-align:left;}
section.galleryBoardList{font-size:13px;}
section.galleryBoardList > header{padding:5px 10px; text-align:right;}
section.galleryBoardList .noticeArticles{margin-top:10px;}
section.galleryBoardList .noticeArticles > header{background:#828b99; color:#fff;}
section.galleryBoardList .noticeArticles > header li{padding:5px;}
section.galleryBoardList .noticeArticles ul{display:table; width:100%; table-layout:fixed;}
section.galleryBoardList .noticeArticles li{display:table-cell; text-align:center; padding:10px 5px; border-bottom:1px solid #ccc;}
section.galleryBoardList .noticeArticles li.check{width:40px;}
section.galleryBoardList .noticeArticles li.subject{text-align:left; font-weight:700;}
section.galleryBoardList .noticeArticles li.num{width:60px;}
section.galleryBoardList .noticeArticles li.name{width:120px;}
section.galleryBoardList .noticeArticles li.date{width:140px;}
section.galleryBoardList .articles{padding-top:20px;}
section.galleryBoardList .articles:after{content:' '; display:block; clear:both}
section.galleryBoardList .articles article{float:left; width:24.4%; margin-left:0.8%; border:1px solid #ccc; padding:5px;}
section.galleryBoardList .articles article:nth-child(4n+1){clear:left; margin-left:0;}
section.galleryBoardList .articles article:nth-child(n+5){margin-top:10px;}
section.galleryBoardList .articles ul{position:relative;}
section.galleryBoardList .articles ul:after{content:' '; display:block; clear:both}
section.galleryBoardList .articles li.check{position:absolute; top:0; left:0;}
section.galleryBoardList .articles li.thumb img{width:100%;}
section.galleryBoardList .articles li.thumb i{display:block; height:0; padding-bottom:75%; background:no-repeat center center; -webkit-background-size:cover; background-size:cover;}
section.galleryBoardList .articles li.subject{text-align:left; font-weight:700; margin-top:5px; line-height:16px; max-height:32px; overflow:hidden;}
section.galleryBoardList .articles li.name{padding-top:5px;}
section.galleryBoardList .articles li.hit{padding-top:5px; font-size:12px;}
section.galleryBoardList .articles li.hit:before{content:'조회수 : ';}
section.galleryBoardList .articles li.recommend{float:left; width:50%; padding-top:5px; font-size:12px; font-weight:700;}
section.galleryBoardList .articles li.recommend:before{content:'추천 : ';}
section.galleryBoardList .articles li.date{float:left; width:50%; padding-top:5px; font-size:11px; color:#888; text-align:right;}
.leftSysBtn{padding-top:10px;}
.leftSysBtn:after{content:' '; display:block; clear:both}
.leftSysBtn > *{margin:0 2px;}
/* 모달창 */
.modal_layer{position:fixed; top:0; left:0; z-index:5000; display:none; width:100%; height:100%; background:rgba(0,0,0,0.3);}
.modal_layer .modal_wrap{position:fixed; top:50%; left:50%; z-index:2; width:400px; height:300px; padding-top:50px; max-width:90%; max-height:90%; background:#F7F7F7; -moz-transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%); -ms-transform:translate(-50%, -50%); -o-transform:translate(-50%, -50%); transform:translate(-50%, -50%);}
.modal_layer .modal_header{position:absolute; top:0; left:0; width:100%; height:50px; background:#2C3E50;}
.modal_layer .modal_header h1{padding:0 80px 0 20px; height:100%; font-size:16px; color:white; overflow:hidden; line-height:50px;}
.modal_layer .modal_header .close{position:absolute; top:16px; left:100%; margin-left:-38px; line-height:16px; font-size:18px; color:white; cursor:pointer; text-align:center;}
.modal_layer .modal_header .close{margin-left:-35px; font-size:24px;}
.modal_layer .modal_header .close i{font-size:16px;}
.modal_layer .modal_header .close i:before,.modal_layer .modal_header .close i:after{background:#fff;}
.modal_layer .submit_btn button{height:40px; font-size:14px; width:100px;}
.modal_layer .modal_contents{height:100%; overflow-y:auto;}
.modal_layer .modal_contents .modal_inner{padding:20px;}
#contents.main{width:970px; margin:0 auto; padding:20px 0;}
#contents.main section > header{position:relative; padding:7px 10px; background:#e6ecf2; line-height:20px;}
#contents.main section > header a.more{position:absolute; top:7px; right:10px; font-size:12px; font-weight:700; color:#828b99; text-decoration:underline;}
#contents.main section > header a.more i{display:inline-block; width:6px; height:6px; margin-left:3px; border:1px solid #828b99; border-width:1px 1px 0 0; vertical-align:middle; -moz-transform:rotate(45deg) translate(0, -1px); -webkit-transform:rotate(45deg) translate(0, -1px); -ms-transform:rotate(45deg) translate(0, -1px); -o-transform:rotate(45deg) translate(0, -1px); transform:rotate(45deg) translate(0, -1px);}
#contents.main section > header h2{padding:0; background:none;}
#contents.main .boardArticles{padding:10px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2); color:#585f7c;}
#contents.main .boardArticles .articles li{border-bottom:1px solid #e6ecf2;}
#contents.main .boardArticles .articles a{display:table; width:100%; table-layout:fixed; vertical-align:middle;}
#contents.main .boardArticles .articles a > * > b{display:inline-block; line-height:20px; height:20px; overflow:hidden; white-space:nowrap; -ms-text-overflow:ellipsis; text-overflow:ellipsis;}
#contents.main .boardArticles .articles div.title{display:table-cell; padding:7px 10px; font-weight:700;}
#contents.main .boardArticles .articles div.title > b{max-width:85%;}
#contents.main .boardArticles .articles div.name{display:table-cell; width:100px; padding:7px 5px; text-align:center;}
#contents.main .boardArticles .articles div.date{display:table-cell; width:90px; padding:7px 10px; text-align:right; font-size:11px; color:#828b99;}
#contents.main .galleryArticles{padding:10px 10px 20px; background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2);}
#contents.main .galleryArticles .articles{margin-top:10px;}
#contents.main .galleryArticles .articles:after{content:' '; display:block; clear:both;}
#contents.main .galleryArticles .articles li{position:relative; float:left; width:24.4%; margin-left:0.8%; border:1px solid #ccc; padding:5px;}
#contents.main .galleryArticles .articles li:nth-child(4n+1){clear:left; margin-left:0;}
#contents.main .galleryArticles .articles .thumb img{width:100%;}
#contents.main .galleryArticles .articles .thumb i{display:block; height:0; padding-bottom:75%; background:no-repeat center center; -webkit-background-size:cover; background-size:cover;}
#contents.main .galleryArticles .articles .info{position:absolute; top:0; left:0; z-index:1; display:none; width:100%; height:100%; padding:20px; background:rgba(0,0,0,0.5); color:#fff; line-height:16px;}
#contents.main .galleryArticles .articles div.title{font-weight:700; min-height:48px;}
#contents.main .galleryArticles .articles div.date{font-size:11px; color:#ccc;}
#contents.main .galleryArticles .articles li:hover .info{display:block;}
#contents.main #mainNotice{float:left; width:49%; margin-bottom:20px; height:250px;}
#contents.main #mainFreeBoard{float:right; width:49%; margin-bottom:20px; height:250px;}
#contents.main #mainGalleryBoard{clear:both;}
#MemberWriteForm{margin-top:20px;}
#contents.terms{background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2); width:970px; padding:20px; margin:20px auto;}
#contents.terms > div.text{margin-top:10px; padding:10px; min-height:300px; border:1px solid #b8c2cc;}
#contents.introduce{background:#fff; -webkit-box-shadow:2px 2px 3px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 3px rgba(0,0,0,0.2); box-shadow:2px 2px 3px rgba(0,0,0,0.2); width:970px; padding:20px; margin:20px auto;}
/* ---------------------------------------------------------------
*메세지
--------------------------------------------------------------- */
.read{color:#6086b1;}
.notRead{color:#c33;}
#messageModal .modal_contents{position:relative; padding-bottom:84px;}
#messageModal .modal_wrap{height:450px;}
#messageChatWrap{position:relative; height:100%;}
#messageChatWrap > div{position:absolute; bottom:0; left:0; width:100%; max-height:100%; padding:20px 20px 0; overflow-y:auto;}
#messageChatWrap > div:after{content:''; display:block; height:20px; clear:both;}
#messageChatWrap button.beforeReadBtn{background:rgba(255,255,255,0.6); color:#000; width:100%; height:28px; text-align:center; font-size:12px;}
#messageChatWrap article{position:relative; clear:both; float:left; padding-top:10px; max-width:90%;}
#messageChatWrap article.myMsg{float:right; text-align:right;}
#messageChatWrap article div.msg{padding:10px 15px; background:#f2be1f; border-radius:10px; -webkit-border-radius:10px; -moz-border-radius:10px; font-weight:700; text-align:left;}
#messageChatWrap article div.notRead{margin-top:5px; font-size:11px; font-weight:700; color:#666;}
#messageChatWrap article div.date{padding:5px 5px 0; font-size:11px; text-align:right; color:rgba(0,0,0,0.5);}
#messageChatWrap article div.img{margin-bottom:5px; border-radius:5px; -webkit-border-radius:5px; -moz-border-radius:5px; overflow:hidden;}
#messageChatWrap article div.img img{max-width:200px; max-height:200px;}
#messageChatWrap article div.file{display:inline-block; margin-bottom:5px; padding:4px 10px; background:#ddd; border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px; text-decoration:underline; font-weight:700; font-size:12px;}
#messageWriteWrap{position:absolute; bottom:0; left:0; width:100%; height:83px; padding-top:24px; background:#fff;}
#messageWriteWrap form{height:100%;}
#messageWriteWrap textarea{float:left; width:80%; height:100%; border:0;}
#messageWriteWrap button[type=submit]{float:right; width:50px; height:50px; margin:5px 5px 0 0; background:#333; color:#fff;}
#messageWriteWrap .fileUploadArea2{position:absolute; top:0; left:0; width:100%; clear:both; padding:0; border:1px solid #ccc; border-width:1px 0; background:#fff;}
#messageWriteWrap .fileUploadArea2 .fileName{line-height:22px;}
#messageWriteWrap .fileUploadArea2 button{height:22px; background:#666;}
.messageView{padding:20px 20px 0;}
.messageView > header{line-height:22px; font-size:14px; border:2px solid #828b99; background:#fff;}
.messageView > header > div{display:table; width:100%; table-layout:fixed; padding:5px 0;}
.messageView > header > div + div{border-top:1px solid #b8c2cc;}
.messageView > header dl{display:table-cell; vertical-align:middle;}
.messageView > header dt{display:inline-block; padding:0 15px; font-weight:700; color:#999;}
.messageView > header dd{position:relative; display:inline-block; padding:0 15px; font-weight:700;}
.messageView > header dd:before{content:''; position:absolute; top:50%; left:0; width:1px; height:10px; margin-top:-5px; background:rgba(0,0,0,0.2);}
.messageView > header dl.readDate{display:block;}
.messageView .cont{margin-top:10px; height:280px; border:2px solid #828b99; overflow-y:auto; background:#fff;}
.messageView .cont .img{text-align:center;}
.messageView .cont img{max-width:100%; max-height:200px;}
.messageView .cont > table{width:100%; table-layout:fixed;}
.messageView .cont > table > tr > td,.messageView .cont > table > tbody > tr > td{padding:5px 10px; line-height:30px;}
.messageWrite{padding:20px;}
.messageWrite table.write{background:#fff;}
.messageWrite table.write th{width:20%; text-align:center;}
#userMenuPopup{-webkit-box-shadow:2px 2px 2px rgba(0,0,0,0.2); -moz-box-shadow:2px 2px 2px rgba(0,0,0,0.2); box-shadow:2px 2px 2px rgba(0,0,0,0.2);}
#userMenuPopup li{padding:2px;}
#userMenuPopup li + li{border-top:1px solid #ddd;}
#userMenuPopup button{height:22px; width:80px; font-size:12px;}
#userMenuPopup button:hover{background:#999; color:#fff;}
@media(max-width:999px) and (min-width:800px){
}
@media(max-width:799px) and (min-width:600px){
}
@media(max-width:599px) and (min-width:400px){
}
@media(max-width:399px){
}
| {'content_hash': '05a1b92cdee1e7a6f4d056c5330eaf24', 'timestamp': '', 'source': 'github', 'line_count': 665, 'max_line_length': 535, 'avg_line_length': 79.403007518797, 'alnum_prop': 0.7467189364240668, 'repo_name': 'huny0522/bh-board', 'id': 'a1bb0322f44f95f899239b65799293e8fcb2f053', 'size': '52837', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Skin/css/style.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '123'}, {'name': 'CSS', 'bytes': '106713'}, {'name': 'HTML', 'bytes': '207708'}, {'name': 'Hack', 'bytes': '8'}, {'name': 'JavaScript', 'bytes': '265809'}, {'name': 'PHP', 'bytes': '699887'}]} |
var entity = require('basis.entity');
var DatasetWrapper = require('basis.data').DatasetWrapper;
var Filter = require('basis.data.dataset').Filter;
var MapFilter = require('basis.data.dataset').MapFilter;
var Split = require('basis.data.dataset').Split;
var type = require('basis.type');
var File = require('./file');
var utils = require('app.utils');
var ModuleLoader = require('./module-loader');
var options = require('app.options');
var Module = entity.createType('Module', {
id: entity.StringId,
type: type.enum(['normal', 'multi', 'context', 'delegated', 'external', 'unknown']).default('unknown'),
name: String,
index: Number,
size: Number,
formattedSize: entity.calc('size', utils.formatSize),
rawRequest: String,
userRequest: String,
context: String,
resource: File,
isEntry: Boolean,
dependencies: entity.createSetType('Module'),
retained: entity.createSetType('Module'),
exclusive: entity.createSetType('Module'),
reasons: entity.createSetType('Module'),
loaders: entity.createSetType(ModuleLoader)
});
var moduleTypeSplit = new Split({
rule: 'data.type'
});
Module.byType = function(type, ifExists) {
ifExists = ifExists === undefined ? false : ifExists;
if (type) {
return moduleTypeSplit.getSubset(type, !ifExists);
}
};
Module.entryPoints = new Filter({
source: Module.all,
rule: 'data.isEntry'
});
Module.projectModules = new Filter({
source: Module.all,
rule: function(module) {
if (module.data.resource) {
return module.data.resource.data.name.indexOf('/node_modules/') == -1;
}
return true;
}
});
Module.allWrapper = new DatasetWrapper({
dataset: options.hide3rdPartyModules.as(function(hide) {
return hide ? Module.projectModules : Module.all;
})
});
moduleTypeSplit.setSource(Module.allWrapper);
Module.files = new MapFilter({
source: Module.byType('normal'),
map: function(module) {
return module.data.resource;
}
});
Module.allFiles = new MapFilter({
source: new Filter({
source: Module.all,
rule: function(module) {
return module.data.type == 'normal';
}
}),
map: function(module) {
return module.data.resource;
}
});
module.exports = Module;
| {'content_hash': '17e7f6e20af5e37b7d35eb51a72c78ba', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 107, 'avg_line_length': 26.96511627906977, 'alnum_prop': 0.6524363949978439, 'repo_name': 'smelukov/webpack-runtime-analyzer', 'id': 'c5b698fa79877fbdd550a6feb5ec42b08a35b5fd', 'size': '2319', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ui/src/type/module.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12981'}, {'name': 'HTML', 'bytes': '790'}, {'name': 'JavaScript', 'bytes': '123173'}]} |
if AkDebugLoad then print("[#Start] Loading ak.io.AkWebServerIo ...") end
local AkCommandExecutor = require("ak.io.AkCommandExecutor")
local os = require("os")
local AkWebServerIo = {}
AkWebServerIo.debug = AkStartWithDebug or false
--- Prüfe ob das Verzeichnis existiert und Dateien geschrieben werden können.
-- Call this function via pcall to catch any exceptions
local function dirExists(dir)
local file = io.open(dir .. "/" .. "ak-eep-version.txt", "w")
file:write(string.format("%.1f", EEPVer))
file:flush()
file:close()
return true
end
--- Finde ein schreibbares Verzeichnis.
local function existingDirOf(...)
for _, dir in pairs(...) do if pcall(dirExists, dir) then return dir end end
return nil
end
--- Prüfe ob Datei existiert.
local function fileExists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
--- Schreibe Datei.
local function writeFile(fileName, inhalt)
local file = io.open(fileName, "w")
assert(file, fileName)
file:write(inhalt)
file:flush()
file:close()
end
local ioDirectoryName
local outFileNameLog
local outFileNameJson
local watchFileNameServer
local watchFileNameLua
local inFileCommands
--- Bestimme Dateipfade.
function AkWebServerIo.setOutputDirectory(dirName)
assert(dirName, "Verzeichnis angeben!")
ioDirectoryName = dirName
-- EEP appends the log to this file
outFileNameLog = ioDirectoryName .. "/ak-eep-out.log"
-- EEP writes it's status to this file regularly
-- but only if the Web Server is listening and has finished reading the previous version of the file
outFileNameJson = ioDirectoryName .. "/ak-eep-out.json"
-- EEP writes it's status to this file regularly
-- but only if the Web Server is listening and has finished reading the previous version of the file
AkWebServerIo.inFileNameEventCounter = ioDirectoryName .. "/ak-eep-web-server-state.counter"
-- The Web Server creates this file at start and deletes it on exit
-- Conclusion: The server is listening while this file exists
watchFileNameServer = ioDirectoryName .. "/ak-server.iswatching"
-- EEP creates this empty file after updating the json file to indicate that the Web Server
-- can now read the json file
-- The Web Server should delete this file after reading the json file
-- Conclusion: The server is busy while this file exists
watchFileNameLua = ioDirectoryName .. "/ak-eep-out-json.isfinished"
-- Delete the file during initialization to trigger the creation of the json file once
-- assert(os.remove(watchFileNameLua))
-- However, this is not possible because within EEP, the library os contains only the following functions:
-- setlocale date time difftime clock getenv tmpname
-- EEP reads commands from this file
local inFileNameCommands = ioDirectoryName .. "/ak-eep-in.commands"
-- clear content of commands file
writeFile(inFileNameCommands, "")
inFileCommands = io.open(inFileNameCommands, "r")
end
--- Bestimme Default-Dateipfade.
AkWebServerIo.setOutputDirectory(existingDirOf({
-- default value
"../LUA/ak/io/exchange", "./LUA/ak/io/exchange"
}) or ".")
local _assert = assert
local _error = error
local _print = print
local _warn = warn
local function printToFile(...)
if ... then
-- We open the file for every write, so EEP will not keep this file open all the time
local file = _assert(io.open(outFileNameLog, "a"))
local time = ""
if os.date then time = os.date("%X ") end
local text = "" .. time
local args = {...}
for _, arg in ipairs(args) do text = text .. tostring(arg):gsub("\n", "\n . ") end
file:write(text .. "\n")
file:close()
end
end
--- Schreibe log zusätzlich in Datei.
function print(...)
printToFile(...) -- print the output to the log file
_print(...) -- call the original print function
end
--- Schreibe Fehler zusätzlich in Datei.
error = function(message, level)
printToFile(message) -- print the output to the file
_error(message, level) -- call the original error function
end
--- Schreibe Fehler zusätzlich in Datei.
warn = function(message, ...)
printToFile(message, ...) -- print the output to the file
_warn(message, ...) -- call the original warn function
end
-- add traceback to assert message by default
assert = function(v, message)
local status, retval = pcall(_assert, v, message)
if not status then error(debug.traceback(message and message or "Assertion failed.", 2), 0) end
return retval
end
local _clearlog = clearlog
--- Lösche Inhalt der log-Datei.
function clearlog()
-- call the original clearlog function
local file = io.open(outFileNameLog, "w+")
file:close()
file = _assert(io.open(outFileNameLog, "a"))
file:write("")
file:close()
_clearlog()
end
-- These two functions must be registered AFTER print and clearlog are overwritten
AkCommandExecutor.addAcceptedRemoteFunction("clearlog", clearlog)
AkCommandExecutor.addAcceptedRemoteFunction("print", print)
local serverWasReadyLastTime = true
local serverWasListeningLastTime = true
--- Prüfe Status des Web Servers.
function AkWebServerIo.checkWebServer()
if fileExists(watchFileNameServer) then -- file: ak-server.iswatching
if fileExists(watchFileNameLua) then -- file: ak-eep-out-json.isfinished
if AkWebServerIo.debug and serverWasReadyLastTime then
print("[#WebServerIo] SERVER IS NOT READY")
end
serverWasReadyLastTime = false
return false
else
if AkWebServerIo.debug and (not serverWasReadyLastTime or not serverWasListeningLastTime) then
print("SERVER IS READY AND LISTENING")
end
serverWasReadyLastTime = true
serverWasListeningLastTime = true
return true
end
else
if AkWebServerIo.debug and serverWasListeningLastTime then
print("[#WebServerIo] SERVER IS NOT LISTENING")
end
serverWasListeningLastTime = false
return false
end
end
local writing = false
--- Schreibe Datei.
---@param jsonData string Dateiinhalt als JSON-formatierter String
function AkWebServerIo.updateJsonFile(jsonData)
if not writing then
writing = true
if not pcall(writeFile, outFileNameJson, jsonData .. "\n") then -- file: ak-eep-out.json
print("[#WebServerIo] CANNOT WRITE TO " .. outFileNameJson)
end
writing = false
end
if fileExists(watchFileNameServer) then -- file: ak-server.iswatching
writeFile(watchFileNameLua, "") -- file: ak-eep-out-json.isfinished
end
end
--- Lese Kommandos aus Datei und führe sie aus.
function AkWebServerIo.processNewCommands()
local commands = inFileCommands:read("*all") -- file: ak-eep-in.commands
if commands and commands ~= "" then AkCommandExecutor.execute(commands) end
end
return AkWebServerIo
| {'content_hash': 'd22ac4ed395af7110e2762d6b20b4534', 'timestamp': '', 'source': 'github', 'line_count': 205, 'max_line_length': 110, 'avg_line_length': 34.51219512195122, 'alnum_prop': 0.6932862190812721, 'repo_name': 'Andreas-Kreuz/ak-lua-skripte-fuer-eep', 'id': '4a6b893d5b0f2e9f158d92e1e6dc3c2df956efd4', 'size': '7075', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lua/LUA/ak/io/AkWebServerIo.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13442'}, {'name': 'HTML', 'bytes': '28937'}, {'name': 'Lua', 'bytes': '155167'}, {'name': 'Ruby', 'bytes': '73'}]} |
package com.bbva.kltt.apirest.core.parsed_info;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.bbva.kltt.apirest.core.parsed_info.common.Item;
import com.bbva.kltt.apirest.core.parsed_info.parameters.Parameter;
import com.bbva.kltt.apirest.core.parsed_info.parameters.ParameterBody;
import com.bbva.kltt.apirest.core.parsed_info.responses.Response;
/**
* ------------------------------------------------
* @author Francisco Manuel Benitez Chico
* ------------------------------------------------
*/
public class ParsedInfoHandler
{
/** Attribute - Parsed information */
private final ParsedInfo parsedInfo ;
/**
* Public constructor
* @param parsedInfo with the parsed information
*/
public ParsedInfoHandler(final ParsedInfo parsedInfo)
{
this.parsedInfo = parsedInfo ;
}
/**
* @return the information values
*/
public InfoValues getInfoValues()
{
return this.parsedInfo.getInfoValues() ;
}
/**
* @return true if there is info to generate
*/
public boolean hasInfoToGenerate()
{
return this.parsedInfo.getPaths() != null && !this.parsedInfo.getPaths().getPathsMap().isEmpty() ;
}
/**
* @return the host
*/
public String getHost()
{
return this.parsedInfo.getRootValues().getHost() ;
}
/**
* @return the business unit
*/
public String getBUnit()
{
return this.parsedInfo.getGeneratorParams().getBUnit() ;
}
/**
* @return the base path
*/
public String getBasePath()
{
return this.parsedInfo.getRootValues().getBasePath() ;
}
/**
* @return the path values
*/
public Set<String> getPathValues()
{
Set<String> outcome = null ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().getPathsMap().keySet() ;
}
return outcome ;
}
/**
* @return a new map with the full definitions (complex and references)
*/
public Map<String, Item> generateDefinitionsMap()
{
Map<String, Item> outcome = new HashMap<String, Item>() ;
if (this.parsedInfo.getDefinitions() != null)
{
outcome = this.parsedInfo.getDefinitions().generateDefinitionsMap() ;
}
return outcome ;
}
/**
* @return the definitions names (complex and references)
*/
public Set<String> getDefinitionsListNames()
{
final Set<String> outcome = new HashSet<String>() ;
for (final Item complexDefinition : this.generateDefinitionsMap().values())
{
outcome.add(complexDefinition.getName()) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return the schemes
*/
public Set<Scheme> getSchemes(final String pathValue, final String pathOperation)
{
Set<Scheme> outcome = this.parsedInfo.getRootValues().getSchemes() ;
if (this.hasAnyScheme(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().getSchemes(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any scheme in the operation
*/
private boolean hasAnyScheme(String pathValue, String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyScheme(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new body parameter
*/
public Parameter getParameterBody(final String pathValue, final String pathOperation)
{
ParameterBody outcome = null ;
if (this.hasAnyParameterBody(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().generateParameterBody(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any body parameter in the operation
*/
private boolean hasAnyParameterBody(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyParameterBody(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return an entry with the parameter and its description
*/
public Entry<String, String> getParametersDescriptionBody(final String pathValue, final String pathOperation)
{
Entry<String, String> entry = null ;
final Parameter parameter = this.getParameterBody(pathValue, pathOperation) ;
if (parameter != null)
{
entry = this.generateNewParamDescriptionEntry(parameter) ;
}
return entry ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any formData parameter in the operation
*/
private boolean hasAnyParameterFormData(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyParameterFormData(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new map with the form data parameters
*/
public Map<String, Parameter> getParametersFormDataMap(final String pathValue, final String pathOperation)
{
Map<String, Parameter> outcome = null ;
if (this.hasAnyParameterFormData(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().generateParametersFormDataMap(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new list with the entries (parameter and its description)
*/
public List<Entry<String, String>> getParametersDescriptionFormData(final String pathValue, final String pathOperation)
{
List<Entry<String, String>> entriesList = null ;
final Map<String, Parameter> parameterMap = this.getParametersFormDataMap(pathValue, pathOperation) ;
if (parameterMap != null && !parameterMap.isEmpty())
{
entriesList = this.generateNewParamDescriptionListEntry(parameterMap) ;
}
return entriesList ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any header parameter in the operation
*/
private boolean hasAnyParameterHeader(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyParameterHeader(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new map with the header parameters
*/
public Map<String, Parameter> getParametersHeaderMap(final String pathValue, final String pathOperation)
{
Map<String, Parameter> outcome = null ;
if (this.hasAnyParameterHeader(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().generateParametersHeaderMap(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new list with the entries (parameter and its description)
*/
public List<Entry<String, String>> getParametersDescriptionHeader(final String pathValue, final String pathOperation)
{
List<Entry<String, String>> entriesList = null ;
final Map<String, Parameter> parameterMap = this.getParametersHeaderMap(pathValue, pathOperation) ;
if (parameterMap != null && !parameterMap.isEmpty())
{
entriesList = this.generateNewParamDescriptionListEntry(parameterMap) ;
}
return entriesList ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any path parameter in the operation
*/
private boolean hasAnyParameterPath(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyParameterPath(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new map with the path parameters
*/
public Map<String, Parameter> getParametersPathMap(final String pathValue, final String pathOperation)
{
Map<String, Parameter> outcome = null ;
if (this.hasAnyParameterPath(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().generateParametersPathMap(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new list with the entries (parameter and its description)
*/
public List<Entry<String, String>> getParametersDescriptionPath(final String pathValue, final String pathOperation)
{
List<Entry<String, String>> entriesList = null ;
final Map<String, Parameter> parameterMap = this.getParametersPathMap(pathValue, pathOperation) ;
if (parameterMap != null && !parameterMap.isEmpty())
{
entriesList = this.generateNewParamDescriptionListEntry(parameterMap) ;
}
return entriesList ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is any query parameter in the operation
*/
private boolean hasAnyParameterQuery(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyParameterQuery(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new map with the query parameters
*/
public Map<String, Parameter> getParametersQueryMap(final String pathValue, final String pathOperation)
{
Map<String, Parameter> outcome = null ;
if (this.hasAnyParameterQuery(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().generateParametersQueryMap(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new list with the entries (parameter and its description)
*/
public List<Entry<String, String>> getParametersDescriptionQuery(final String pathValue, final String pathOperation)
{
List<Entry<String, String>> entriesList = null ;
final Map<String, Parameter> parameterMap = this.getParametersQueryMap(pathValue, pathOperation) ;
if (parameterMap != null && !parameterMap.isEmpty())
{
entriesList = this.generateNewParamDescriptionListEntry(parameterMap) ;
}
return entriesList ;
}
/**
* @param parameterMap with the parameters map
* @return a new list with the entries (parameter and its description)
*/
private List<Entry<String, String>> generateNewParamDescriptionListEntry(final Map<String, Parameter> parameterMap)
{
final List<Entry<String, String>> entriesList = new ArrayList<Entry<String, String>>() ;
for (final Parameter parameter : parameterMap.values())
{
entriesList.add(this.generateNewParamDescriptionEntry(parameter)) ;
}
return entriesList ;
}
/**
* @param parameter with the parameter
* @return a new entry with the parameter and its description
*/
private Entry<String, String> generateNewParamDescriptionEntry(final Parameter parameter)
{
return new AbstractMap.SimpleEntry<String, String>(parameter.getName(), parameter.getDescription()) ;
}
/**
* @return true if there is operation identifier for whatever path
*/
public boolean hasAnyOperationId()
{
return this.hasInfoToGenerate() ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if there is operation identifier for this path operation
*/
public boolean hasAnyOperationId(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyOperationId(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return the operation identifier
*/
public String getOperationId(final String pathValue, final String pathOperation)
{
String outcome = null ;
if (this.hasAnyOperationId(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().getOperationId(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @return all the operation identifiers
*/
public List<String> getAllOperationIds()
{
List<String> outcome = null ;
if (this.hasAnyOperationId())
{
outcome = this.parsedInfo.getPaths().getAllOperationIds() ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return the return item type
*/
public Item getOutboundServerItemType(final String pathValue, final String pathOperation)
{
Item outcome = null ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().getOutboundServerItemType(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @return a new map with all the response exceptions
*/
public Map<String, List<Response>> getOutboundServerExceptionsMap()
{
final Map<String, List<Response>> outcome = new HashMap<String, List<Response>>() ;
if (this.hasInfoToGenerate())
{
this.parsedInfo.getPaths().getOutboundServerExceptionsMap(outcome) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a list with all the custom response exceptions for the path and operation
*/
public List<Response> getOutboundServerExceptionsList(final String pathValue, final String pathOperation)
{
List<Response> customExceptionsList = new ArrayList<Response>() ;
if (this.hasInfoToGenerate())
{
customExceptionsList = this.parsedInfo.getPaths().getOutboundServerExceptionsList(pathValue, pathOperation) ;
}
return customExceptionsList ;
}
/**
* Global consumes
* @return a new String with the global consumes
*/
public Set<String> getConsumes()
{
return this.parsedInfo.getRootValues().getConsumes() ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new set with the consumes for the pathValue-pathOperation
*/
public Set<String> getConsumes(final String pathValue, final String pathOperation)
{
Set<String> outcome = null ;
if (this.hasAnyOperationConsumes(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().getConsumes(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if exists any consumes for the pathValue-pathOperation
*/
private boolean hasAnyOperationConsumes(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyOperationConsumes(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* Global produces
* @return a new String with the global produces
*/
public Set<String> getProduces()
{
return this.parsedInfo.getRootValues().getProduces() ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return a new set with the produces for the pathValue-pathOperation
*/
public Set<String> getProduces(final String pathValue, final String pathOperation)
{
Set<String> outcome = null ;
if (this.hasAnyOperationProduces(pathValue, pathOperation))
{
outcome = this.parsedInfo.getPaths().getProduces(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @param pathValue with the path value
* @param pathOperation with the path operation
* @return true if exists any produces for the pathValue-pathOperation
*/
private boolean hasAnyOperationProduces(final String pathValue, final String pathOperation)
{
boolean outcome = false ;
if (this.hasInfoToGenerate())
{
outcome = this.parsedInfo.getPaths().hasAnyOperationProduces(pathValue, pathOperation) ;
}
return outcome ;
}
/**
* @return the Architecture type
*/
public String getOsgiArchitectureType()
{
return this.parsedInfo.getGeneratorParams().getOsgiParams().getArchitectureType() ;
}
/**
* @return the CXF Address
*/
public String getOsgiCxfAddress()
{
return this.parsedInfo.getGeneratorParams().getOsgiParams().getCxfAddress() ;
}
/**
* @return the CXF Context
*/
public String getOsgiCxfContext()
{
return this.parsedInfo.getGeneratorParams().getOsgiParams().getCxfContext() ;
}
@Override
public String toString()
{
return this.parsedInfo.toString() ;
}
}
| {'content_hash': '5d54dda15c66ac703be5511324dd4109', 'timestamp': '', 'source': 'github', 'line_count': 663, 'max_line_length': 120, 'avg_line_length': 27.238310708898943, 'alnum_prop': 0.6899053103715599, 'repo_name': 'BBVA-CIB/APIRestGenerator', 'id': '804d8c2fe0b6a32134e058fd8e8b39e300636560', 'size': '18883', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/bbva/kltt/apirest/core/parsed_info/ParsedInfoHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '229'}, {'name': 'CSS', 'bytes': '504463'}, {'name': 'HTML', 'bytes': '9688'}, {'name': 'Java', 'bytes': '1098093'}, {'name': 'JavaScript', 'bytes': '136674'}, {'name': 'Shell', 'bytes': '253'}]} |
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Iterator,
Optional,
Sequence,
Tuple,
)
from google.cloud.compute_v1.types import compute
class AggregatedListPager:
"""A pager for iterating through ``aggregated_list`` requests.
This class thinly wraps an initial
:class:`google.cloud.compute_v1.types.AddressAggregatedList` object, and
provides an ``__iter__`` method to iterate through its
``items`` field.
If there are more pages, the ``__iter__`` method will make additional
``AggregatedList`` requests and continue to iterate
through the ``items`` field on the
corresponding responses.
All the usual :class:`google.cloud.compute_v1.types.AddressAggregatedList`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., compute.AddressAggregatedList],
request: compute.AggregatedListAddressesRequest,
response: compute.AddressAggregatedList,
*,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.compute_v1.types.AggregatedListAddressesRequest):
The initial request object.
response (google.cloud.compute_v1.types.AddressAggregatedList):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = compute.AggregatedListAddressesRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[compute.AddressAggregatedList]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[Tuple[str, compute.AddressesScopedList]]:
for page in self.pages:
yield from page.items.items()
def get(self, key: str) -> Optional[compute.AddressesScopedList]:
return self._response.items.get(key)
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
class ListPager:
"""A pager for iterating through ``list`` requests.
This class thinly wraps an initial
:class:`google.cloud.compute_v1.types.AddressList` object, and
provides an ``__iter__`` method to iterate through its
``items`` field.
If there are more pages, the ``__iter__`` method will make additional
``List`` requests and continue to iterate
through the ``items`` field on the
corresponding responses.
All the usual :class:`google.cloud.compute_v1.types.AddressList`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
method: Callable[..., compute.AddressList],
request: compute.ListAddressesRequest,
response: compute.AddressList,
*,
metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.compute_v1.types.ListAddressesRequest):
The initial request object.
response (google.cloud.compute_v1.types.AddressList):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = compute.ListAddressesRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterator[compute.AddressList]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterator[compute.Address]:
for page in self.pages:
yield from page.items
def __repr__(self) -> str:
return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
| {'content_hash': '7619467d721cbea14471a058c8639fc3', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 83, 'avg_line_length': 35.97841726618705, 'alnum_prop': 0.6354729054189162, 'repo_name': 'googleapis/python-compute', 'id': 'f5d081230324f82968e93ec7f6d2bd095d0bd80f', 'size': '5601', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'google/cloud/compute_v1/services/addresses/pagers.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2050'}, {'name': 'Python', 'bytes': '32681847'}, {'name': 'Shell', 'bytes': '30663'}]} |
<template name="Explorer_Interests_Page">
{{#Explorer_Layout addedList = addedInterests nonAddedList = nonAddedInterests careerList = addedCareerInterests type = 'interests'}}
{{> Explorer_Interests_Widget name=interest.name slug=(slugName interest.slugID) descriptionPairs=(descriptionPairs interest) socialPairs=(socialPairs interest) id=interest._id updateID=updateID item=interest}}
{{> Back_To_Top_Button}}
{{/Explorer_Layout}}
</template>
| {'content_hash': '2c70e0be4370669bd1d072f8424cd190', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 214, 'avg_line_length': 76.16666666666667, 'alnum_prop': 0.774617067833698, 'repo_name': 'radgrad/radgrad', 'id': 'ffb8bcab4068dfd0701168bcdf23e3edde2bdb88', 'size': '457', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/imports/ui/pages/shared/explorer-interests-page.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7218'}, {'name': 'HTML', 'bytes': '518789'}, {'name': 'JavaScript', 'bytes': '1643515'}, {'name': 'Shell', 'bytes': '9949'}]} |
package com.addy.learn.maxaliveyear;
/**
* Problem Description
* You have a list of people with their birth and death years.
* Find the year with maximum population.
*
* Input as a list of people with
* People may not be alive at the same time
*/
public class MaxAliveApp {
public static void main(String[] args) {
}
}
| {'content_hash': 'e2122c653aad35786e4611b2863ccda2', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 62, 'avg_line_length': 21.0625, 'alnum_prop': 0.7002967359050445, 'repo_name': 'adityaka/misc_scripts', 'id': '3353bf76f4edc44f4f2308b9fd94f35c24f81f0d', 'size': '337', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'prep_and_learning/javads/addy-learn-javads/src/main/java/com/addy/learn/maxaliveyear/MaxAliveApp.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '18717'}, {'name': 'C++', 'bytes': '1251'}, {'name': 'CSS', 'bytes': '233'}, {'name': 'Dockerfile', 'bytes': '158'}, {'name': 'HTML', 'bytes': '1403'}, {'name': 'Java', 'bytes': '11584'}, {'name': 'JavaScript', 'bytes': '2659'}, {'name': 'Jupyter Notebook', 'bytes': '30667423'}, {'name': 'Makefile', 'bytes': '1585'}, {'name': 'PowerShell', 'bytes': '2333'}, {'name': 'Python', 'bytes': '24980'}, {'name': 'Ruby', 'bytes': '1352'}, {'name': 'Rust', 'bytes': '2168'}, {'name': 'TSQL', 'bytes': '422'}]} |
import { helper } from '@ember/component/helper';
import { htmlSafe } from '@ember/template';
export function progressStyleHelper([percent, id, colors] /*, hash*/) {
let color = colors[id % colors.length];
return new htmlSafe(`width: ${percent}%; background-color: ${color};`);
}
export default helper(progressStyleHelper);
| {'content_hash': '1d4ed950756aff9acb691d31e8070270', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 73, 'avg_line_length': 36.666666666666664, 'alnum_prop': 0.7090909090909091, 'repo_name': 'machty/ember-concurrency', 'id': 'd8827481bd6b910e3000bf8f4e91d5b7d2f70067', 'size': '330', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/dummy/app/helpers/progress-style.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2029'}, {'name': 'Handlebars', 'bytes': '89577'}, {'name': 'JavaScript', 'bytes': '281649'}, {'name': 'SCSS', 'bytes': '3466'}, {'name': 'Shell', 'bytes': '32'}, {'name': 'TypeScript', 'bytes': '94614'}]} |
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {'content_hash': 'a37b1cb95078c265359d6f2992daddb1', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 281, 'avg_line_length': 53.48571428571429, 'alnum_prop': 0.7863247863247863, 'repo_name': 'ka010/KAVROneSDK', 'id': '749a305703141bf4524d35f31e0e95cd144926de', 'size': '2035', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Demo/KAVROneSDKDemo/KAVROneSDKDemo/AppDelegate.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '14102'}]} |
/**************************************************************************
* snort_pop.c
*
* Author: Bhagyashree Bantwal <[email protected]>
*
* Description:
*
* This file handles POP protocol checking and normalization.
*
* Entry point functions:
*
* SnortPOP()
* POP_Init()
* POP_Free()
*
**************************************************************************/
/* Includes ***************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <pcre.h>
#include "sf_types.h"
#include "snort_pop.h"
#include "pop_config.h"
#include "pop_util.h"
#include "pop_log.h"
#include "sf_snort_packet.h"
#include "stream_api.h"
#include "snort_debug.h"
#include "profiler.h"
#include "snort_bounds.h"
#include "sf_dynamic_preprocessor.h"
#include "ssl.h"
#include "sfPolicy.h"
#include "sfPolicyUserData.h"
#include "file_api.h"
#ifdef DEBUG_MSGS
#include "sf_types.h"
#endif
/**************************************************************************/
/* Externs ****************************************************************/
#ifdef PERF_PROFILING
extern PreprocStats popDetectPerfStats;
extern int popDetectCalled;
#endif
extern tSfPolicyUserContextId pop_config;
extern POPConfig *pop_eval_config;
extern MemPool *pop_mime_mempool;
extern MemPool *pop_mempool;
#ifdef DEBUG_MSGS
extern char pop_print_buffer[];
#endif
/**************************************************************************/
/* Globals ****************************************************************/
const POPToken pop_known_cmds[] =
{
{"APOP", 4, CMD_APOP},
{"AUTH", 4, CMD_AUTH},
{"CAPA", 4, CMD_CAPA},
{"DELE", 4, CMD_DELE},
{"LIST", 4, CMD_LIST},
{"NOOP", 4, CMD_NOOP},
{"PASS", 4, CMD_PASS},
{"QUIT", 4, CMD_QUIT},
{"RETR", 4, CMD_RETR},
{"RSET", 4, CMD_RSET},
{"STAT", 4, CMD_STAT},
{"STLS", 4, CMD_STLS},
{"TOP", 3, CMD_TOP},
{"UIDL", 4, CMD_UIDL},
{"USER", 4, CMD_USER},
{NULL, 0, 0}
};
const POPToken pop_resps[] =
{
{"+OK", 3, RESP_OK}, /* SUCCESS */
{"-ERR", 4, RESP_ERR}, /* FAILURE */
{NULL, 0, 0}
};
const POPToken pop_hdrs[] =
{
{"Content-type:", 13, HDR_CONTENT_TYPE},
{"Content-Transfer-Encoding:", 26, HDR_CONT_TRANS_ENC},
{"Content-Disposition:", 20, HDR_CONT_DISP},
{NULL, 0, 0}
};
const POPToken pop_data_end[] =
{
{"\r\n.\r\n", 5, DATA_END_1},
{"\n.\r\n", 4, DATA_END_2},
{"\r\n.\n", 4, DATA_END_3},
{"\n.\n", 3, DATA_END_4},
{NULL, 0, 0}
};
POP *pop_ssn = NULL;
POP pop_no_session;
POPPcre mime_boundary_pcre;
char pop_normalizing;
POPSearchInfo pop_search_info;
#ifdef DEBUG_MSGS
uint64_t pop_session_counter = 0;
#endif
#ifdef TARGET_BASED
int16_t pop_proto_id;
#endif
void *pop_resp_search_mpse = NULL;
POPSearch pop_resp_search[RESP_LAST];
void *pop_hdr_search_mpse = NULL;
POPSearch pop_hdr_search[HDR_LAST];
void *pop_data_search_mpse = NULL;
POPSearch pop_data_end_search[DATA_END_LAST];
POPSearch *pop_current_search = NULL;
/**************************************************************************/
/* Private functions ******************************************************/
static int POP_Setup(SFSnortPacket *p, POP *ssn);
static void POP_ResetState(void);
static void POP_SessionFree(void *);
static void POP_NoSessionFree(void);
static int POP_GetPacketDirection(SFSnortPacket *, int);
static void POP_ProcessClientPacket(SFSnortPacket *);
static void POP_ProcessServerPacket(SFSnortPacket *);
static void POP_DisableDetect(SFSnortPacket *);
static const uint8_t * POP_HandleCommand(SFSnortPacket *, const uint8_t *, const uint8_t *);
static const uint8_t * POP_HandleData(SFSnortPacket *, const uint8_t *, const uint8_t *);
static const uint8_t * POP_HandleHeader(SFSnortPacket *, const uint8_t *, const uint8_t *);
static const uint8_t * POP_HandleDataBody(SFSnortPacket *, const uint8_t *, const uint8_t *);
static int POP_SearchStrFound(void *, void *, int, void *, void *);
static int POP_BoundaryStrFound(void *, void *, int , void *, void *);
static int POP_GetBoundary(const char *, int);
static int POP_Inspect(SFSnortPacket *);
/**************************************************************************/
static void SetPopBuffers(POP *ssn)
{
if ((ssn != NULL) && (ssn->decode_state == NULL))
{
MemBucket *bkt = mempool_alloc(pop_mime_mempool);
if (bkt != NULL)
{
ssn->decode_state = (Email_DecodeState *)calloc(1, sizeof(Email_DecodeState));
if( ssn->decode_state != NULL )
{
ssn->decode_bkt = bkt;
SetEmailDecodeState(ssn->decode_state, bkt->data, pop_eval_config->max_depth,
pop_eval_config->b64_depth, pop_eval_config->qp_depth,
pop_eval_config->uu_depth, pop_eval_config->bitenc_depth,
pop_eval_config->file_depth);
}
else
{
/*free mempool if calloc fails*/
mempool_free(pop_mime_mempool, bkt);
}
}
else
{
POP_GenerateAlert(POP_MEMCAP_EXCEEDED, "%s", POP_MEMCAP_EXCEEDED_STR);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "No memory available for decoding. Memcap exceeded \n"););
}
}
}
void POP_InitCmds(POPConfig *config)
{
const POPToken *tmp;
if (config == NULL)
return;
/* add one to CMD_LAST for NULL entry */
config->cmds = (POPToken *)calloc(CMD_LAST + 1, sizeof(POPToken));
if (config->cmds == NULL)
{
DynamicPreprocessorFatalMessage("%s(%d) => failed to allocate memory for pop "
"command structure\n",
*(_dpd.config_file), *(_dpd.config_line));
}
for (tmp = &pop_known_cmds[0]; tmp->name != NULL; tmp++)
{
config->cmds[tmp->search_id].name_len = tmp->name_len;
config->cmds[tmp->search_id].search_id = tmp->search_id;
config->cmds[tmp->search_id].name = strdup(tmp->name);
if (config->cmds[tmp->search_id].name == NULL)
{
DynamicPreprocessorFatalMessage("%s(%d) => failed to allocate memory for pop "
"command structure\n",
*(_dpd.config_file), *(_dpd.config_line));
}
}
/* initialize memory for command searches */
config->cmd_search = (POPSearch *)calloc(CMD_LAST, sizeof(POPSearch));
if (config->cmd_search == NULL)
{
DynamicPreprocessorFatalMessage("%s(%d) => failed to allocate memory for pop "
"command structure\n",
*(_dpd.config_file), *(_dpd.config_line));
}
config->num_cmds = CMD_LAST;
}
/*
* Initialize POP searches
*
* @param none
*
* @return none
*/
void POP_SearchInit(void)
{
const char *error;
int erroffset;
const POPToken *tmp;
/* Response search */
pop_resp_search_mpse = _dpd.searchAPI->search_instance_new();
if (pop_resp_search_mpse == NULL)
{
DynamicPreprocessorFatalMessage("Could not allocate POP "
"response search.\n");
}
for (tmp = &pop_resps[0]; tmp->name != NULL; tmp++)
{
pop_resp_search[tmp->search_id].name = tmp->name;
pop_resp_search[tmp->search_id].name_len = tmp->name_len;
_dpd.searchAPI->search_instance_add(pop_resp_search_mpse, tmp->name,
tmp->name_len, tmp->search_id);
}
_dpd.searchAPI->search_instance_prep(pop_resp_search_mpse);
/* Header search */
pop_hdr_search_mpse = _dpd.searchAPI->search_instance_new();
if (pop_hdr_search_mpse == NULL)
{
DynamicPreprocessorFatalMessage("Could not allocate POP "
"header search.\n");
}
for (tmp = &pop_hdrs[0]; tmp->name != NULL; tmp++)
{
pop_hdr_search[tmp->search_id].name = tmp->name;
pop_hdr_search[tmp->search_id].name_len = tmp->name_len;
_dpd.searchAPI->search_instance_add(pop_hdr_search_mpse, tmp->name,
tmp->name_len, tmp->search_id);
}
_dpd.searchAPI->search_instance_prep(pop_hdr_search_mpse);
/* Data end search */
pop_data_search_mpse = _dpd.searchAPI->search_instance_new();
if (pop_data_search_mpse == NULL)
{
DynamicPreprocessorFatalMessage("Could not allocate POP "
"data search.\n");
}
for (tmp = &pop_data_end[0]; tmp->name != NULL; tmp++)
{
pop_data_end_search[tmp->search_id].name = tmp->name;
pop_data_end_search[tmp->search_id].name_len = tmp->name_len;
_dpd.searchAPI->search_instance_add(pop_data_search_mpse, tmp->name,
tmp->name_len, tmp->search_id);
}
_dpd.searchAPI->search_instance_prep(pop_data_search_mpse);
/* create regex for finding boundary string - since it can be cut across multiple
* lines, a straight search won't do. Shouldn't be too slow since it will most
* likely only be acting on a small portion of data */
//"^content-type:\\s*multipart.*boundary\\s*=\\s*\"?([^\\s]+)\"?"
//"^\\s*multipart.*boundary\\s*=\\s*\"?([^\\s]+)\"?"
//mime_boundary_pcre.re = pcre_compile("^.*boundary\\s*=\\s*\"?([^\\s\"]+)\"?",
//mime_boundary_pcre.re = pcre_compile("boundary(?:\n|\r\n)?=(?:\n|\r\n)?\"?([^\\s\"]+)\"?",
mime_boundary_pcre.re = pcre_compile("boundary\\s*=\\s*\"?([^\\s\"]+)\"?",
PCRE_CASELESS | PCRE_DOTALL,
&error, &erroffset, NULL);
if (mime_boundary_pcre.re == NULL)
{
DynamicPreprocessorFatalMessage("Failed to compile pcre regex for getting boundary "
"in a multipart POP message: %s\n", error);
}
mime_boundary_pcre.pe = pcre_study(mime_boundary_pcre.re, 0, &error);
if (error != NULL)
{
DynamicPreprocessorFatalMessage("Failed to study pcre regex for getting boundary "
"in a multipart POP message: %s\n", error);
}
}
/*
* Initialize run-time boundary search
*/
static int POP_BoundarySearchInit(void)
{
if (pop_ssn->mime_boundary.boundary_search != NULL)
_dpd.searchAPI->search_instance_free(pop_ssn->mime_boundary.boundary_search);
pop_ssn->mime_boundary.boundary_search = _dpd.searchAPI->search_instance_new();
if (pop_ssn->mime_boundary.boundary_search == NULL)
return -1;
_dpd.searchAPI->search_instance_add(pop_ssn->mime_boundary.boundary_search,
pop_ssn->mime_boundary.boundary,
pop_ssn->mime_boundary.boundary_len, BOUNDARY);
_dpd.searchAPI->search_instance_prep(pop_ssn->mime_boundary.boundary_search);
return 0;
}
/*
* Reset POP session state
*
* @param none
*
* @return none
*/
static void POP_ResetState(void)
{
if (pop_ssn->mime_boundary.boundary_search != NULL)
{
_dpd.searchAPI->search_instance_free(pop_ssn->mime_boundary.boundary_search);
pop_ssn->mime_boundary.boundary_search = NULL;
}
pop_ssn->state = STATE_UNKNOWN;
pop_ssn->data_state = STATE_DATA_INIT;
pop_ssn->prev_response = 0;
pop_ssn->state_flags = 0;
ClearEmailDecodeState(pop_ssn->decode_state);
memset(&pop_ssn->mime_boundary, 0, sizeof(POPMimeBoundary));
}
/*
* Given a server configuration and a port number, we decide if the port is
* in the POP server port list.
*
* @param port the port number to compare with the configuration
*
* @return integer
* @retval 0 means that the port is not a server port
* @retval !0 means that the port is a server port
*/
int POP_IsServer(uint16_t port)
{
if (pop_eval_config->ports[port / 8] & (1 << (port % 8)))
return 1;
return 0;
}
static POP * POP_GetNewSession(SFSnortPacket *p, tSfPolicyId policy_id)
{
POP *ssn;
POPConfig *pPolicyConfig = NULL;
pPolicyConfig = (POPConfig *)sfPolicyUserDataGetCurrent(pop_config);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Creating new session data structure\n"););
ssn = (POP *)calloc(1, sizeof(POP));
if (ssn == NULL)
{
DynamicPreprocessorFatalMessage("Failed to allocate POP session data\n");
}
pop_ssn = ssn;
ssn->prev_response = 0;
if (_dpd.fileAPI->set_log_buffers(&(pop_ssn->log_state), &(pPolicyConfig->log_config), pop_mempool) < 0)
{
free(ssn);
return NULL;
}
_dpd.streamAPI->set_application_data(p->stream_session_ptr, PP_POP,
ssn, &POP_SessionFree);
if (p->flags & SSNFLAG_MIDSTREAM)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Got midstream packet - "
"setting state to unknown\n"););
ssn->state = STATE_UNKNOWN;
}
#ifdef DEBUG_MSGS
pop_session_counter++;
ssn->session_number = pop_session_counter;
#endif
if (p->stream_session_ptr != NULL)
{
/* check to see if we're doing client reassembly in stream */
if (_dpd.streamAPI->get_reassembly_direction(p->stream_session_ptr) & SSN_DIR_FROM_CLIENT)
ssn->reassembling = 1;
if(!ssn->reassembling)
{
_dpd.streamAPI->set_reassembly(p->stream_session_ptr,
STREAM_FLPOLICY_FOOTPRINT, SSN_DIR_FROM_CLIENT, STREAM_FLPOLICY_SET_ABSOLUTE);
ssn->reassembling = 1;
}
}
ssn->policy_id = policy_id;
ssn->config = pop_config;
pPolicyConfig->ref_count++;
return ssn;
}
/*
* Do first-packet setup
*
* @param p standard Packet structure
*
* @return none
*/
static int POP_Setup(SFSnortPacket *p, POP *ssn)
{
int flags = 0;
int pkt_dir;
if (p->stream_session_ptr != NULL)
{
/* set flags to session flags */
flags = _dpd.streamAPI->get_session_flags(p->stream_session_ptr);
}
/* Figure out direction of packet */
pkt_dir = POP_GetPacketDirection(p, flags);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Session number: "STDu64"\n", ssn->session_number););
/* Check to see if there is a reassembly gap. If so, we won't know
* what state we're in when we get the _next_ reassembled packet */
if ((pkt_dir != POP_PKT_FROM_SERVER) &&
(p->flags & FLAG_REBUILT_STREAM))
{
int missing_in_rebuilt =
_dpd.streamAPI->missing_in_reassembled(p->stream_session_ptr, SSN_DIR_FROM_CLIENT);
if (ssn->session_flags & POP_FLAG_NEXT_STATE_UNKNOWN)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Found gap in previous reassembly buffer - "
"set state to unknown\n"););
ssn->state = STATE_UNKNOWN;
ssn->session_flags &= ~POP_FLAG_NEXT_STATE_UNKNOWN;
}
if (missing_in_rebuilt == SSN_MISSING_BEFORE)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Found missing packets before "
"in reassembly buffer - set state to unknown\n"););
ssn->state = STATE_UNKNOWN;
}
}
return pkt_dir;
}
/*
* Determine packet direction
*
* @param p standard Packet structure
*
* @return none
*/
static int POP_GetPacketDirection(SFSnortPacket *p, int flags)
{
int pkt_direction = POP_PKT_FROM_UNKNOWN;
if (flags & SSNFLAG_MIDSTREAM)
{
if (POP_IsServer(p->src_port) &&
!POP_IsServer(p->dst_port))
{
pkt_direction = POP_PKT_FROM_SERVER;
}
else if (!POP_IsServer(p->src_port) &&
POP_IsServer(p->dst_port))
{
pkt_direction = POP_PKT_FROM_CLIENT;
}
}
else
{
if (p->flags & FLAG_FROM_SERVER)
{
pkt_direction = POP_PKT_FROM_SERVER;
}
else if (p->flags & FLAG_FROM_CLIENT)
{
pkt_direction = POP_PKT_FROM_CLIENT;
}
/* if direction is still unknown ... */
if (pkt_direction == POP_PKT_FROM_UNKNOWN)
{
if (POP_IsServer(p->src_port) &&
!POP_IsServer(p->dst_port))
{
pkt_direction = POP_PKT_FROM_SERVER;
}
else if (!POP_IsServer(p->src_port) &&
POP_IsServer(p->dst_port))
{
pkt_direction = POP_PKT_FROM_CLIENT;
}
}
}
return pkt_direction;
}
/*
* Free POP-specific related to this session
*
* @param v pointer to POP session structure
*
*
* @return none
*/
static void POP_SessionFree(void *session_data)
{
POP *pop = (POP *)session_data;
#ifdef SNORT_RELOAD
POPConfig *pPolicyConfig = NULL;
#endif
if (pop == NULL)
return;
#ifdef SNORT_RELOAD
pPolicyConfig = (POPConfig *)sfPolicyUserDataGet(pop->config, pop->policy_id);
if (pPolicyConfig != NULL)
{
pPolicyConfig->ref_count--;
if ((pPolicyConfig->ref_count == 0) &&
(pop->config != pop_config))
{
sfPolicyUserDataClear (pop->config, pop->policy_id);
POP_FreeConfig(pPolicyConfig);
/* No more outstanding policies for this config */
if (sfPolicyUserPolicyGetActive(pop->config) == 0)
POP_FreeConfigs(pop->config);
}
}
#endif
if (pop->mime_boundary.boundary_search != NULL)
{
_dpd.searchAPI->search_instance_free(pop->mime_boundary.boundary_search);
pop->mime_boundary.boundary_search = NULL;
}
if(pop->decode_state != NULL)
{
mempool_free(pop_mime_mempool, pop->decode_bkt);
free(pop->decode_state);
}
if(pop->log_state != NULL)
{
mempool_free(pop_mempool, pop->log_state->log_hdrs_bkt);
free(pop->log_state);
}
free(pop);
}
static void POP_NoSessionFree(void)
{
if (pop_no_session.mime_boundary.boundary_search != NULL)
{
_dpd.searchAPI->search_instance_free(pop_no_session.mime_boundary.boundary_search);
pop_no_session.mime_boundary.boundary_search = NULL;
}
}
static int POP_FreeConfigsPolicy(
tSfPolicyUserContextId config,
tSfPolicyId policyId,
void* pData
)
{
POPConfig *pPolicyConfig = (POPConfig *)pData;
//do any housekeeping before freeing POPConfig
sfPolicyUserDataClear (config, policyId);
POP_FreeConfig(pPolicyConfig);
return 0;
}
void POP_FreeConfigs(tSfPolicyUserContextId config)
{
if (config == NULL)
return;
sfPolicyUserDataFreeIterate (config, POP_FreeConfigsPolicy);
sfPolicyConfigDelete(config);
}
void POP_FreeConfig(POPConfig *config)
{
if (config == NULL)
return;
if (config->cmds != NULL)
{
POPToken *tmp = config->cmds;
for (; tmp->name != NULL; tmp++)
free(tmp->name);
free(config->cmds);
}
if (config->cmd_search_mpse != NULL)
_dpd.searchAPI->search_instance_free(config->cmd_search_mpse);
if (config->cmd_search != NULL)
free(config->cmd_search);
free(config);
}
/*
* Free anything that needs it before shutting down preprocessor
*
* @param none
*
* @return none
*/
void POP_Free(void)
{
POP_NoSessionFree();
POP_FreeConfigs(pop_config);
pop_config = NULL;
if (pop_resp_search_mpse != NULL)
_dpd.searchAPI->search_instance_free(pop_resp_search_mpse);
if (pop_hdr_search_mpse != NULL)
_dpd.searchAPI->search_instance_free(pop_hdr_search_mpse);
if (pop_data_search_mpse != NULL)
_dpd.searchAPI->search_instance_free(pop_data_search_mpse);
if (mime_boundary_pcre.re )
pcre_free(mime_boundary_pcre.re);
if (mime_boundary_pcre.pe )
pcre_free(mime_boundary_pcre.pe);
}
/*
* Callback function for string search
*
* @param id id in array of search strings from pop_config.cmds
* @param index index in array of search strings from pop_config.cmds
* @param data buffer passed in to search function
*
* @return response
* @retval 1 commands caller to stop searching
*/
static int POP_SearchStrFound(void *id, void *unused, int index, void *data, void *unused2)
{
int search_id = (int)(uintptr_t)id;
pop_search_info.id = search_id;
pop_search_info.index = index;
pop_search_info.length = pop_current_search[search_id].name_len;
/* Returning non-zero stops search, which is okay since we only look for one at a time */
return 1;
}
/*
* Callback function for boundary search
*
* @param id id in array of search strings
* @param index index in array of search strings
* @param data buffer passed in to search function
*
* @return response
* @retval 1 commands caller to stop searching
*/
static int POP_BoundaryStrFound(void *id, void *unused, int index, void *data, void *unused2)
{
int boundary_id = (int)(uintptr_t)id;
pop_search_info.id = boundary_id;
pop_search_info.index = index;
pop_search_info.length = pop_ssn->mime_boundary.boundary_len;
return 1;
}
static int POP_GetBoundary(const char *data, int data_len)
{
int result;
int ovector[9];
int ovecsize = 9;
const char *boundary;
int boundary_len;
int ret;
char *mime_boundary;
int *mime_boundary_len;
int *mime_boundary_state;
mime_boundary = &pop_ssn->mime_boundary.boundary[0];
mime_boundary_len = &pop_ssn->mime_boundary.boundary_len;
mime_boundary_state = &pop_ssn->mime_boundary.state;
/* result will be the number of matches (including submatches) */
result = pcre_exec(mime_boundary_pcre.re, mime_boundary_pcre.pe,
data, data_len, 0, 0, ovector, ovecsize);
if (result < 0)
return -1;
result = pcre_get_substring(data, ovector, result, 1, &boundary);
if (result < 0)
return -1;
boundary_len = strlen(boundary);
if (boundary_len > MAX_BOUNDARY_LEN)
{
/* XXX should we alert? breaking the law of RFC */
boundary_len = MAX_BOUNDARY_LEN;
}
mime_boundary[0] = '-';
mime_boundary[1] = '-';
ret = SafeMemcpy(mime_boundary + 2, boundary, boundary_len,
mime_boundary + 2, mime_boundary + 2 + MAX_BOUNDARY_LEN);
pcre_free_substring(boundary);
if (ret != SAFEMEM_SUCCESS)
{
return -1;
}
*mime_boundary_len = 2 + boundary_len;
*mime_boundary_state = 0;
mime_boundary[*mime_boundary_len] = '\0';
return 0;
}
/*
* Handle COMMAND state
*
* @param p standard Packet structure
* @param ptr pointer into p->payload buffer to start looking at data
* @param end points to end of p->payload buffer
*
* @return pointer into p->payload where we stopped looking at data
* will be end of line or end of packet
*/
static const uint8_t * POP_HandleCommand(SFSnortPacket *p, const uint8_t *ptr, const uint8_t *end)
{
const uint8_t *eol; /* end of line */
const uint8_t *eolm; /* end of line marker */
int cmd_found;
/* get end of line and end of line marker */
POP_GetEOL(ptr, end, &eol, &eolm);
/* TODO If the end of line marker coincides with the end of payload we can't be
* sure that we got a command and not a substring which we could tell through
* inspection of the next packet. Maybe a command pending state where the first
* char in the next packet is checked for a space and end of line marker */
/* do not confine since there could be space chars before command */
pop_current_search = &pop_eval_config->cmd_search[0];
cmd_found = _dpd.searchAPI->search_instance_find
(pop_eval_config->cmd_search_mpse, (const char *)ptr,
eolm - ptr, 0, POP_SearchStrFound);
/* see if we actually found a command and not a substring */
if (cmd_found > 0)
{
const uint8_t *tmp = ptr;
const uint8_t *cmd_start = ptr + pop_search_info.index;
const uint8_t *cmd_end = cmd_start + pop_search_info.length;
/* move past spaces up until start of command */
while ((tmp < cmd_start) && isspace((int)*tmp))
tmp++;
/* if not all spaces before command, we found a
* substring */
if (tmp != cmd_start)
cmd_found = 0;
/* if we're before the end of line marker and the next
* character is not whitespace, we found a substring */
if ((cmd_end < eolm) && !isspace((int)*cmd_end))
cmd_found = 0;
/* there is a chance that end of command coincides with the end of payload
* in which case, it could be a substring, but for now, we will treat it as found */
}
/* if command not found, alert and move on */
if (!cmd_found)
{
POP_GenerateAlert(POP_UNKNOWN_CMD, "%s", POP_UNKNOWN_CMD_STR);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "No known command found\n"););
return eol;
}
/* At this point we have definitely found a legitimate command */
DEBUG_WRAP(DebugMessage(DEBUG_POP, "%s\n", pop_eval_config->cmds[pop_search_info.id].name););
/* switch (pop_search_info.id)
{
case CMD_USER:
case CMD_PASS:
case CMD_RSET:
case CMD_QUIT:
case CMD_RETR:
break;
default:
break;
}*/
return eol;
}
static const uint8_t * POP_HandleData(SFSnortPacket *p, const uint8_t *ptr, const uint8_t *end)
{
const uint8_t *data_end_marker = NULL;
const uint8_t *data_end = NULL;
int data_end_found;
FilePosition position = SNORT_FILE_START;
/* if we've just entered the data state, check for a dot + end of line
* if found, no data */
if ((pop_ssn->data_state == STATE_DATA_INIT) ||
(pop_ssn->data_state == STATE_DATA_UNKNOWN))
{
if ((ptr < end) && (*ptr == '.'))
{
const uint8_t *eol = NULL;
const uint8_t *eolm = NULL;
POP_GetEOL(ptr, end, &eol, &eolm);
/* this means we got a real end of line and not just end of payload
* and that the dot is only char on line */
if ((eolm != end) && (eolm == (ptr + 1)))
{
/* if we're normalizing and not ignoring data copy data end marker
* and dot to alt buffer */
POP_ResetState();
return eol;
}
}
if (pop_ssn->data_state == STATE_DATA_INIT)
pop_ssn->data_state = STATE_DATA_HEADER;
/* XXX A line starting with a '.' that isn't followed by a '.' is
* deleted (RFC 821 - 4.5.2. TRANSPARENCY). If data starts with
* '. text', i.e a dot followed by white space then text, some
* servers consider it data header and some data body.
* Postfix and Qmail will consider the start of data:
* . text\r\n
* . text\r\n
* to be part of the header and the effect will be that of a
* folded line with the '.' deleted. Exchange will put the same
* in the body which seems more reasonable. */
}
/* get end of data body
* TODO check last bytes of previous packet to see if we had a partial
* end of data */
pop_current_search = &pop_data_end_search[0];
data_end_found = _dpd.searchAPI->search_instance_find
(pop_data_search_mpse, (const char *)ptr, end - ptr,
0, POP_SearchStrFound);
if (data_end_found > 0)
{
data_end_marker = ptr + pop_search_info.index;
data_end = data_end_marker + pop_search_info.length;
}
else
{
data_end_marker = data_end = end;
}
_dpd.setFileDataPtr((uint8_t*)ptr, (uint16_t)(data_end - ptr));
if ((pop_ssn->data_state == STATE_DATA_HEADER) ||
(pop_ssn->data_state == STATE_DATA_UNKNOWN))
{
#ifdef DEBUG_MSGS
if (pop_ssn->data_state == STATE_DATA_HEADER)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "DATA HEADER STATE ~~~~~~~~~~~~~~~~~~~~~~\n"););
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "DATA UNKNOWN STATE ~~~~~~~~~~~~~~~~~~~~~\n"););
}
#endif
ptr = POP_HandleHeader(p, ptr, data_end_marker);
if (ptr == NULL)
return NULL;
}
/* now we shouldn't have to worry about copying any data to the alt buffer
* only mime headers if we find them and only if we're ignoring data */
initFilePosition(&position, _dpd.fileAPI->get_file_processed_size(p->stream_session_ptr));
while ((ptr != NULL) && (ptr < data_end_marker))
{
/* multiple MIME attachments in one single packet.
* Pipeline the MIME decoded data.*/
if ( pop_ssn->state_flags & POP_FLAG_MULTIPLE_EMAIL_ATTACH)
{
int detection_size = getDetectionSize(pop_eval_config->b64_depth, pop_eval_config->qp_depth,
pop_eval_config->uu_depth, pop_eval_config->bitenc_depth,pop_ssn->decode_state );
_dpd.setFileDataPtr(pop_ssn->decode_state->decodePtr, (uint16_t)detection_size);
/*Download*/
if (_dpd.fileAPI->file_process(p,(uint8_t *)pop_ssn->decode_state->decodePtr,
(uint16_t)pop_ssn->decode_state->decoded_bytes, position, false, false)
&& (isFileStart(position)) && pop_ssn->log_state)
{
_dpd.fileAPI->set_file_name_from_log(&(pop_ssn->log_state->file_log), p->stream_session_ptr);
}
updateFilePosition(&position, _dpd.fileAPI->get_file_processed_size(p->stream_session_ptr));
_dpd.detect(p);
pop_ssn->state_flags &= ~POP_FLAG_MULTIPLE_EMAIL_ATTACH;
ResetEmailDecodeState(pop_ssn->decode_state);
p->flags |=FLAG_ALLOW_MULTIPLE_DETECT;
/* Reset the log count when a packet goes through detection multiple times */
_dpd.DetectReset((uint8_t *)p->payload, p->payload_size);
}
switch (pop_ssn->data_state)
{
case STATE_MIME_HEADER:
DEBUG_WRAP(DebugMessage(DEBUG_POP, "MIME HEADER STATE ~~~~~~~~~~~~~~~~~~~~~~\n"););
ptr = POP_HandleHeader(p, ptr, data_end_marker);
_dpd.fileAPI->finalize_mime_position(p->stream_session_ptr,
pop_ssn->decode_state, &position);
break;
case STATE_DATA_BODY:
DEBUG_WRAP(DebugMessage(DEBUG_POP, "DATA BODY STATE ~~~~~~~~~~~~~~~~~~~~~~~~\n"););
ptr = POP_HandleDataBody(p, ptr, data_end_marker);
_dpd.fileAPI->update_file_name(pop_ssn->log_state);
break;
}
}
/* We have either reached the end of MIME header or end of MIME encoded data*/
if(pop_ssn->decode_state != NULL)
{
int detection_size = getDetectionSize(pop_eval_config->b64_depth, pop_eval_config->qp_depth,
pop_eval_config->uu_depth, pop_eval_config->bitenc_depth,pop_ssn->decode_state );
_dpd.setFileDataPtr(pop_ssn->decode_state->decodePtr, (uint16_t)detection_size);
if ((data_end_marker != end) || (pop_ssn->state_flags & POP_FLAG_MIME_END))
{
finalFilePosition(&position);
}
/*Download*/
if (_dpd.fileAPI->file_process(p,(uint8_t *)pop_ssn->decode_state->decodePtr,
(uint16_t)pop_ssn->decode_state->decoded_bytes, position, false, false)
&& (isFileStart(position)) && pop_ssn->log_state)
{
_dpd.fileAPI->set_file_name_from_log(&(pop_ssn->log_state->file_log), p->stream_session_ptr);
}
ResetDecodedBytes(pop_ssn->decode_state);
}
/* if we got the data end reset state, otherwise we're probably still in the data
* to expect more data in next packet */
if (data_end_marker != end)
{
POP_ResetState();
}
return data_end;
}
/*
* Handle Headers - Data or Mime
*
* @param packet standard Packet structure
*
* @param i index into p->payload buffer to start looking at data
*
* @return i index into p->payload where we stopped looking at data
*/
static const uint8_t * POP_HandleHeader(SFSnortPacket *p, const uint8_t *ptr,
const uint8_t *data_end_marker)
{
const uint8_t *eol;
const uint8_t *eolm;
const uint8_t *colon;
const uint8_t *content_type_ptr = NULL;
const uint8_t *cont_trans_enc = NULL;
const uint8_t *cont_disp = NULL;
int header_found;
int ret;
const uint8_t *start_hdr;
start_hdr = ptr;
/* if we got a content-type in a previous packet and are
* folding, the boundary still needs to be checked for */
if (pop_ssn->state_flags & POP_FLAG_IN_CONTENT_TYPE)
content_type_ptr = ptr;
if (pop_ssn->state_flags & POP_FLAG_IN_CONT_TRANS_ENC)
cont_trans_enc = ptr;
if (pop_ssn->state_flags & POP_FLAG_IN_CONT_DISP)
cont_disp = ptr;
while (ptr < data_end_marker)
{
POP_GetEOL(ptr, data_end_marker, &eol, &eolm);
/* got a line with only end of line marker should signify end of header */
if (eolm == ptr)
{
/* reset global header state values */
pop_ssn->state_flags &=
~(POP_FLAG_FOLDING | POP_FLAG_IN_CONTENT_TYPE | POP_FLAG_DATA_HEADER_CONT
| POP_FLAG_IN_CONT_TRANS_ENC );
pop_ssn->data_state = STATE_DATA_BODY;
/* if no headers, treat as data */
if (ptr == start_hdr)
return eolm;
else
return eol;
}
/* if we're not folding, see if we should interpret line as a data line
* instead of a header line */
if (!(pop_ssn->state_flags & (POP_FLAG_FOLDING | POP_FLAG_DATA_HEADER_CONT)))
{
char got_non_printable_in_header_name = 0;
/* if we're not folding and the first char is a space or
* colon, it's not a header */
if (isspace((int)*ptr) || *ptr == ':')
{
pop_ssn->data_state = STATE_DATA_BODY;
return ptr;
}
/* look for header field colon - if we're not folding then we need
* to find a header which will be all printables (except colon)
* followed by a colon */
colon = ptr;
while ((colon < eolm) && (*colon != ':'))
{
if (((int)*colon < 33) || ((int)*colon > 126))
got_non_printable_in_header_name = 1;
colon++;
}
/* If the end on line marker and end of line are the same, assume
* header was truncated, so stay in data header state */
if ((eolm != eol) &&
((colon == eolm) || got_non_printable_in_header_name))
{
/* no colon or got spaces in header name (won't be interpreted as a header)
* assume we're in the body */
pop_ssn->state_flags &=
~(POP_FLAG_FOLDING | POP_FLAG_IN_CONTENT_TYPE | POP_FLAG_DATA_HEADER_CONT
|POP_FLAG_IN_CONT_TRANS_ENC);
pop_ssn->data_state = STATE_DATA_BODY;
return ptr;
}
if(tolower((int)*ptr) == 'c')
{
pop_current_search = &pop_hdr_search[0];
header_found = _dpd.searchAPI->search_instance_find
(pop_hdr_search_mpse, (const char *)ptr,
eolm - ptr, 1, POP_SearchStrFound);
/* Headers must start at beginning of line */
if ((header_found > 0) && (pop_search_info.index == 0))
{
switch (pop_search_info.id)
{
case HDR_CONTENT_TYPE:
content_type_ptr = ptr + pop_search_info.length;
pop_ssn->state_flags |= POP_FLAG_IN_CONTENT_TYPE;
break;
case HDR_CONT_TRANS_ENC:
cont_trans_enc = ptr + pop_search_info.length;
pop_ssn->state_flags |= POP_FLAG_IN_CONT_TRANS_ENC;
break;
case HDR_CONT_DISP:
cont_disp = ptr + pop_search_info.length;
pop_ssn->state_flags |= POP_FLAG_IN_CONT_DISP;
break;
default:
break;
}
}
}
else if(tolower((int)*ptr) == 'e')
{
if((eolm - ptr) >= 9)
{
if(strncasecmp((const char *)ptr, "Encoding:", 9) == 0)
{
cont_trans_enc = ptr + 9;
pop_ssn->state_flags |= POP_FLAG_IN_CONT_TRANS_ENC;
}
}
}
}
else
{
pop_ssn->state_flags &= ~POP_FLAG_DATA_HEADER_CONT;
}
/* check for folding
* if char on next line is a space and not \n or \r\n, we are folding */
if ((eol < data_end_marker) && isspace((int)eol[0]) && (eol[0] != '\n'))
{
if ((eol < (data_end_marker - 1)) && (eol[0] != '\r') && (eol[1] != '\n'))
{
pop_ssn->state_flags |= POP_FLAG_FOLDING;
}
else
{
pop_ssn->state_flags &= ~POP_FLAG_FOLDING;
}
}
else if (eol != eolm)
{
pop_ssn->state_flags &= ~POP_FLAG_FOLDING;
}
/* check if we're in a content-type header and not folding. if so we have the whole
* header line/lines for content-type - see if we got a multipart with boundary
* we don't check each folded line, but wait until we have the complete header
* because boundary=BOUNDARY can be split across mulitple folded lines before
* or after the '=' */
if ((pop_ssn->state_flags &
(POP_FLAG_IN_CONTENT_TYPE | POP_FLAG_FOLDING)) == POP_FLAG_IN_CONTENT_TYPE)
{
if (pop_ssn->data_state != STATE_MIME_HEADER)
{
/* we got the full content-type header - look for boundary string */
ret = POP_GetBoundary((const char *)content_type_ptr, eolm - content_type_ptr);
if (ret != -1)
{
ret = POP_BoundarySearchInit();
if (ret != -1)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Got mime boundary: %s\n",
pop_ssn->mime_boundary.boundary););
pop_ssn->state_flags |= POP_FLAG_GOT_BOUNDARY;
}
}
}
else if (!(pop_ssn->state_flags & POP_FLAG_EMAIL_ATTACH))
{
if( !POP_IsDecodingEnabled(pop_eval_config))
{
SetPopBuffers(pop_ssn);
if(pop_ssn->decode_state != NULL)
{
ResetBytesRead(pop_ssn->decode_state);
POP_DecodeType((const char *)content_type_ptr, (eolm - content_type_ptr), false );
pop_ssn->state_flags |= POP_FLAG_EMAIL_ATTACH;
/* check to see if there are other attachments in this packet */
if( pop_ssn->decode_state->decoded_bytes )
pop_ssn->state_flags |= POP_FLAG_MULTIPLE_EMAIL_ATTACH;
}
}
}
pop_ssn->state_flags &= ~POP_FLAG_IN_CONTENT_TYPE;
content_type_ptr = NULL;
}
else if ((pop_ssn->state_flags &
(POP_FLAG_IN_CONT_TRANS_ENC | POP_FLAG_FOLDING)) == POP_FLAG_IN_CONT_TRANS_ENC)
{
/* Check for Content-Transfer-Encoding : */
if( !POP_IsDecodingEnabled(pop_eval_config))
{
SetPopBuffers(pop_ssn);
if(pop_ssn->decode_state != NULL)
{
ResetBytesRead(pop_ssn->decode_state);
POP_DecodeType((const char *)cont_trans_enc, (eolm - cont_trans_enc), true );
pop_ssn->state_flags |= POP_FLAG_EMAIL_ATTACH;
/* check to see if there are other attachments in this packet */
if( pop_ssn->decode_state->decoded_bytes )
pop_ssn->state_flags |= POP_FLAG_MULTIPLE_EMAIL_ATTACH;
}
}
pop_ssn->state_flags &= ~POP_FLAG_IN_CONT_TRANS_ENC;
cont_trans_enc = NULL;
}
else if (((pop_ssn->state_flags &
(POP_FLAG_IN_CONT_DISP | POP_FLAG_FOLDING)) == POP_FLAG_IN_CONT_DISP) && cont_disp)
{
bool disp_cont = (pop_ssn->state_flags & POP_FLAG_IN_CONT_DISP_CONT)? true: false;
if( pop_eval_config->log_config.log_filename && pop_ssn->log_state)
{
if(! _dpd.fileAPI->log_file_name(cont_disp, eolm - cont_disp,
&(pop_ssn->log_state->file_log), &disp_cont) )
pop_ssn->log_flags |= POP_FLAG_FILENAME_PRESENT;
}
if (disp_cont)
{
pop_ssn->state_flags |= POP_FLAG_IN_CONT_DISP_CONT;
}
else
{
pop_ssn->state_flags &= ~POP_FLAG_IN_CONT_DISP;
pop_ssn->state_flags &= ~POP_FLAG_IN_CONT_DISP_CONT;
}
cont_disp = NULL;
}
/* if state was unknown, at this point assume we know */
if (pop_ssn->data_state == STATE_DATA_UNKNOWN)
pop_ssn->data_state = STATE_DATA_HEADER;
ptr = eol;
if (ptr == data_end_marker)
pop_ssn->state_flags |= POP_FLAG_DATA_HEADER_CONT;
}
return ptr;
}
/*
* Handle DATA_BODY statepop_ssn->log_state
*
* @param packet standard Packet structure
*
* @param i index into p->payload buffer to start looking at data
*
* @return i index into p->payload where we stopped looking at data
*/
static const uint8_t * POP_HandleDataBody(SFSnortPacket *p, const uint8_t *ptr,
const uint8_t *data_end_marker)
{
int boundary_found = 0;
const uint8_t *boundary_ptr = NULL;
const uint8_t *attach_start = NULL;
const uint8_t *attach_end = NULL;
if ( pop_ssn->state_flags & POP_FLAG_EMAIL_ATTACH )
attach_start = ptr;
/* look for boundary */
if (pop_ssn->state_flags & POP_FLAG_GOT_BOUNDARY)
{
boundary_found = _dpd.searchAPI->stateful_search_instance_find
(pop_ssn->mime_boundary.boundary_search, (const char *)ptr,
data_end_marker - ptr, 0, POP_BoundaryStrFound, &(pop_ssn->mime_boundary.state));
if (boundary_found > 0)
{
pop_ssn->mime_boundary.state = 0;
boundary_ptr = ptr + pop_search_info.index;
/* should start at beginning of line */
if ((boundary_ptr == ptr) || (*(boundary_ptr - 1) == '\n'))
{
const uint8_t *eol;
const uint8_t *eolm;
const uint8_t *tmp;
if (pop_ssn->state_flags & POP_FLAG_EMAIL_ATTACH )
{
attach_end = boundary_ptr-1;
pop_ssn->state_flags &= ~POP_FLAG_EMAIL_ATTACH;
if(attach_start < attach_end)
{
if (*(attach_end - 1) == '\r')
attach_end--;
if(EmailDecode( attach_start, attach_end, pop_ssn->decode_state) < DECODE_SUCCESS )
{
POP_DecodeAlert();
}
}
}
if(boundary_ptr > ptr)
tmp = boundary_ptr + pop_search_info.length;
else
{
tmp = (const uint8_t *)_dpd.searchAPI->search_instance_find_end((char *)boundary_ptr,
(data_end_marker - boundary_ptr), pop_ssn->mime_boundary.boundary, pop_search_info.length);
}
/* Check for end boundary */
if (((tmp + 1) < data_end_marker) && (tmp[0] == '-') && (tmp[1] == '-'))
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Mime boundary end found: %s--\n",
(char *)pop_ssn->mime_boundary.boundary););
/* no more MIME */
pop_ssn->state_flags &= ~POP_FLAG_GOT_BOUNDARY;
pop_ssn->state_flags |= POP_FLAG_MIME_END;
/* free boundary search */
_dpd.searchAPI->search_instance_free(pop_ssn->mime_boundary.boundary_search);
pop_ssn->mime_boundary.boundary_search = NULL;
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Mime boundary found: %s\n",
(char *)pop_ssn->mime_boundary.boundary););
pop_ssn->data_state = STATE_MIME_HEADER;
}
/* get end of line - there could be spaces after boundary before eol */
POP_GetEOL(boundary_ptr + pop_search_info.length, data_end_marker, &eol, &eolm);
return eol;
}
}
}
if ( pop_ssn->state_flags & POP_FLAG_EMAIL_ATTACH )
{
attach_end = data_end_marker;
if(attach_start < attach_end)
{
if(EmailDecode( attach_start, attach_end, pop_ssn->decode_state) < DECODE_SUCCESS )
{
POP_DecodeAlert();
}
}
}
return data_end_marker;
}
/*
* Process client packet
*
* @param packet standard Packet structure
*
* @return none
*/
static void POP_ProcessClientPacket(SFSnortPacket *p)
{
const uint8_t *ptr = p->payload;
const uint8_t *end = p->payload + p->payload_size;
ptr = POP_HandleCommand(p, ptr, end);
}
/*
* Process server packet
*
* @param packet standard Packet structure
*
*/
static void POP_ProcessServerPacket(SFSnortPacket *p)
{
int resp_found;
const uint8_t *ptr;
const uint8_t *end;
const uint8_t *eolm;
const uint8_t *eol;
int resp_line_len;
const char *tmp = NULL;
ptr = p->payload;
end = p->payload + p->payload_size;
while (ptr < end)
{
if(pop_ssn->state == STATE_DATA)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "DATA STATE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"););
ptr = POP_HandleData(p, ptr, end);
continue;
}
POP_GetEOL(ptr, end, &eol, &eolm);
resp_line_len = eol - ptr;
/* Check for response code */
pop_current_search = &pop_resp_search[0];
resp_found = _dpd.searchAPI->search_instance_find
(pop_resp_search_mpse, (const char *)ptr,
resp_line_len, 1, POP_SearchStrFound);
if (resp_found > 0)
{
const uint8_t *cmd_start = ptr + pop_search_info.index;
switch (pop_search_info.id)
{
case RESP_OK:
tmp = _dpd.SnortStrcasestr((const char *)cmd_start, (eol - cmd_start), "octets");
if(tmp != NULL)
pop_ssn->state = STATE_DATA;
else
{
pop_ssn->prev_response = RESP_OK;
pop_ssn->state = STATE_UNKNOWN;
}
break;
default:
break;
}
}
else
{
if(pop_ssn->prev_response == RESP_OK)
{
{
pop_ssn->state = STATE_DATA;
pop_ssn->prev_response = 0;
continue;
}
}
else if(*ptr == '+')
{
POP_GenerateAlert(POP_UNKNOWN_RESP, "%s", POP_UNKNOWN_RESP_STR);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Server response not found\n"););
}
}
ptr = eol;
}
return;
}
/* For Target based
* If a protocol for the session is already identified and not one POP is
* interested in, POP should leave it alone and return without processing.
* If a protocol for the session is already identified and is one that POP is
* interested in, decode it.
* If the protocol for the session is not already identified and the preprocessor
* is configured to detect on one of the packet ports, detect.
* Returns 0 if we should not inspect
* 1 if we should continue to inspect
*/
static int POP_Inspect(SFSnortPacket *p)
{
#ifdef TARGET_BASED
/* POP could be configured to be stateless. If stream isn't configured, assume app id
* will never be set and just base inspection on configuration */
if (p->stream_session_ptr == NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: No stream session.\n"););
if ((POP_IsServer(p->src_port) && (p->flags & FLAG_FROM_SERVER)) ||
(POP_IsServer(p->dst_port) && (p->flags & FLAG_FROM_CLIENT)))
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: Configured for this "
"traffic, so let's inspect.\n"););
return 1;
}
}
else
{
int16_t app_id = _dpd.streamAPI->get_application_protocol_id(p->stream_session_ptr);
if (app_id != 0)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: App id: %u.\n", app_id););
if (app_id == pop_proto_id)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: App id is "
"set to \"%s\".\n", POP_PROTO_REF_STR););
return 1;
}
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: Unknown protocol for "
"this session. See if we're configured.\n"););
if ((POP_IsServer(p->src_port) && (p->flags & FLAG_FROM_SERVER)) ||
(POP_IsServer(p->dst_port) && (p->flags & FLAG_FROM_CLIENT)))
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP: Target-based: POP port is configured."););
return 1;
}
}
}
DEBUG_WRAP(DebugMessage(DEBUG_POP,"POP: Target-based: Not inspecting ...\n"););
#else
/* Make sure it's traffic we're interested in */
if ((POP_IsServer(p->src_port) && (p->flags & FLAG_FROM_SERVER)) ||
(POP_IsServer(p->dst_port) && (p->flags & FLAG_FROM_CLIENT)))
return 1;
#endif /* TARGET_BASED */
return 0;
}
/*
* Entry point to snort preprocessor for each packet
*
* @param packet standard Packet structure
*
* @return none
*/
void SnortPOP(SFSnortPacket *p)
{
int detected = 0;
int pkt_dir;
tSfPolicyId policy_id = _dpd.getRuntimePolicy();
PROFILE_VARS;
pop_ssn = (POP *)_dpd.streamAPI->get_application_data(p->stream_session_ptr, PP_POP);
if (pop_ssn != NULL)
pop_eval_config = (POPConfig *)sfPolicyUserDataGet(pop_ssn->config, pop_ssn->policy_id);
else
pop_eval_config = (POPConfig *)sfPolicyUserDataGetCurrent(pop_config);
if (pop_eval_config == NULL)
return;
if (pop_ssn == NULL)
{
if (!POP_Inspect(p))
return;
pop_ssn = POP_GetNewSession(p, policy_id);
if (pop_ssn == NULL)
return;
}
pkt_dir = POP_Setup(p, pop_ssn);
if (pkt_dir == POP_PKT_FROM_CLIENT)
{
POP_ProcessClientPacket(p);
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP client packet\n"););
}
else
{
#ifdef DEBUG_MSGS
if (pkt_dir == POP_PKT_FROM_SERVER)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP server packet\n"););
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP packet NOT from client or server! "
"Processing as a server packet\n"););
}
#endif
if (!_dpd.readyForProcess(p))
{
/* Packet will be rebuilt, so wait for it */
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Client packet will be reassembled\n"));
return;
}
else if (pop_ssn->reassembling && !(p->flags & FLAG_REBUILT_STREAM))
{
/* If this isn't a reassembled packet and didn't get
* inserted into reassembly buffer, there could be a
* problem. If we miss syn or syn-ack that had window
* scaling this packet might not have gotten inserted
* into reassembly buffer because it fell outside of
* window, because we aren't scaling it */
pop_ssn->session_flags |= POP_FLAG_GOT_NON_REBUILT;
pop_ssn->state = STATE_UNKNOWN;
}
else if (pop_ssn->reassembling && (pop_ssn->session_flags & POP_FLAG_GOT_NON_REBUILT))
{
/* This is a rebuilt packet. If we got previous packets
* that were not rebuilt, state is going to be messed up
* so set state to unknown. It's likely this was the
* beginning of the conversation so reset state */
DEBUG_WRAP(DebugMessage(DEBUG_POP, "Got non-rebuilt packets before "
"this rebuilt packet\n"););
pop_ssn->state = STATE_UNKNOWN;
pop_ssn->session_flags &= ~POP_FLAG_GOT_NON_REBUILT;
}
/* Process as a server packet */
POP_ProcessServerPacket(p);
}
PREPROC_PROFILE_START(popDetectPerfStats);
detected = _dpd.detect(p);
#ifdef PERF_PROFILING
popDetectCalled = 1;
#endif
PREPROC_PROFILE_END(popDetectPerfStats);
/* Turn off detection since we've already done it. */
POP_DisableDetect(p);
if (detected)
{
DEBUG_WRAP(DebugMessage(DEBUG_POP, "POP vulnerability detected\n"););
}
}
static void POP_DisableDetect(SFSnortPacket *p)
{
_dpd.disableAllDetect(p);
_dpd.setPreprocBit(p, PP_SFPORTSCAN);
_dpd.setPreprocBit(p, PP_PERFMONITOR);
_dpd.setPreprocBit(p, PP_STREAM5);
_dpd.setPreprocBit(p, PP_SDF);
}
static inline POP *POP_GetSession(void *data)
{
if(data)
return (POP *)_dpd.streamAPI->get_application_data(data, PP_POP);
return NULL;
}
/* Callback to return the MIME attachment filenames accumulated */
int POP_GetFilename(void *data, uint8_t **buf, uint32_t *len, uint32_t *type)
{
POP *ssn = POP_GetSession(data);
if(ssn == NULL)
return 0;
*buf = ssn->log_state->file_log.filenames;
*len = ssn->log_state->file_log.file_logged;
return 1;
}
| {'content_hash': '6b7114cae496a543e024b96f9bf5c649', 'timestamp': '', 'source': 'github', 'line_count': 1751, 'max_line_length': 119, 'avg_line_length': 31.880639634494575, 'alnum_prop': 0.5401537000877774, 'repo_name': 'liuchuang/snort', 'id': '41e6aee76a39145bea3d7769b37f35905bee2fdd', 'size': '56875', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'snort-2.9.6.0/src/dynamic-preprocessors/pop/snort_pop.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '13492693'}, {'name': 'C++', 'bytes': '194474'}, {'name': 'Objective-C', 'bytes': '22299'}, {'name': 'Perl', 'bytes': '4230'}, {'name': 'Python', 'bytes': '115154'}, {'name': 'Shell', 'bytes': '1083939'}, {'name': 'TeX', 'bytes': '656483'}]} |
\startreport{Gambling on Decision Trees}
\reportauthor{Ramesh Subramonian}
\newcommand{\extra}{0}
\section{Introduction}
Decision trees are a well understood statistical technique \cite{Hastie2009}.
This paper makes the following contributions:
\be
\item Well known metrics used to determine the best decision to be made
at a given node are (i) gini impurity (ii) information gain and (iii)
variance reduction. In contrast, we propose a metric that is inspired by looking
at the decision making as a gambling problem, the aim being to maximize the
expected gain at each step.
\item
Well known metrics used to measure the quality of the decision tree
induced by the splitting metric chosen above are
precision, recall, accuracy, f1-score, \ldots
In contrast, continuing the gambling metaphor, we propose a ``payout'' metric which
measures the quality of the decision tree.
\item Lastly, we show that the quality of the decision tree is affected by the
choice of splitting metric. What this means is that one should choose the
splitting metric {\bf after} one has decided which quality metric is most
appropriate for the problem at hand.
\ee
We believe that the proposed changes to the way decision trees are created and
evaluated is particularly relevant to the case where relative
confidences are involved. This is often the case when multiple candidates are
competing for a limited resource, like user attention.
For example, supposed we have 2 decision trees, \(C_A, C_B\), one for product A and one for
product B. We need \(C_A, C_B\) to return \(p_A, p_B\), where \(p_A\) is
\(C_A\)'s estimate of how likely the user is to select product A. In order to
make the best business decision, we would like \(p_A, p_B\) to be as asccurate
as possible.
Random forests are a common way is which an ensemble of decision tres can be
used to produce better results than any single tree. This paper specifically
does not address how random forests are created. For example, different decision
trees can be created by withholding some of the features, or some of the
instances. What we focus on is creating the ``best'' possible decision tree
given the inputs.
%% \subsection{Conventions}
%% Throughout the paper, we use the data sets listed in Table~\ref{tbl_data_sets}
%% for our experiments.
%% \begin{table}
%% \centering
%% \begin{tabular}{|l|l|l|l|} \hline \hline
%% {\bf Data Set Name } & {\bf Rows} & {\bf Columns} & {\bf Location} \\ \hline
%% Breast Cancer & X & X & \\ \hline
%% Titanic & X & X & \\ \hline
%% \ldots & X & X & \\ \hline
%% \end{tabular}
%% \label{tbl_data_sets}
%% \caption{Data Sets used for experimentation}
%% \end{table}
%%
\subsection{A brief introduction to \cal{Q}}
\cal{Q} is a column oriented database that is used to implement the decision
tree algorithm. In this section, we present the essential aspects of \cal{Q}.
\cal{Q} allows efficient manipulation of vectors. All elements of vectors are
the same type. The 2 types we use in this paper are F4 and I4, representing
single precision floating point and 4-byte signed integers. A vector has a fixed
length \(n\) and can be thought of as a map from \(i\) to \(f(i)\),
where \(i \in [0, n-1]\).
\subsection{Notations}
\bi
\item Let \(T = \{t_i\}\) be a table of vectors of type F4, representing the features.
\item Let \(g\) be a vector of type I4, representing the {\bf goal} or
outcome which we wish to
predict. We assume the goal can be either Heads, represented by the integer value 1 or Tails, represented as 0.
\item boolean features are
modeled as having type F4 and the comparison is always \(\leq 0\), so that the
left branch has instances where the feature value is false and the
right branch has instances where the feature value is true.
\ei
A decision tree is a Lua table where each element identifies
\be
\item a feature e.g., age
\item the comparison to be made e.g., age \(\leq 40\). Currently, the comparison
is {\bf always} \(\leq\)
\item a left decision tree, which may be null
\item a right decision tree, which may be null
\ee
\begin{figure}
\centering
\fbox{
\begin{minipage}{35cm}
\begin{tabbing} \hspace*{0.25in} \= \hspace*{0.25in} \=
\hspace*{0.25in} \= \hspace*{0.25in} \= \kill
Let \(\alpha\) be minimum benefit required to continue branching \\
Let \(n_G = 2\) be the number of values of the goal attribute \\
Let \(n_T =\) number of instances classified as tails \\
Let \(n_H =\) number of instances classified as heads \\
Let \(T\) be table of vectors, each vector being an attribute \\
Initialize, decision tree \(D = \{\}\) \\
\(F, g\) as described above \\
{\bf function } MakeDecisionTree(D, T, g) \+ \ \\
\(C = Q.\mathrm{numby}(g, n_G);~n_T = C[0];~n_H = C[1]\) \\
{\bf forall} \(f \in T:~ b(f), s(f) = \mathrm{Benefit}(f, g, n_T, n_H)\) \\
Let \(f'\) be feature with maximum benefit. \\
{\bf if} \(b(f') < \alpha\) {\bf then } \+ \\
{\bf return} \- \\
{\bf endif} \\
\(x = \mathrm{Q.vsgt}(f', s(f'))\) \\
\(T_L = T_R = \{\}\) \\
{\bf forall} \(f \in F\) {\bf do} \+ \\
\(f_L = Q.\mathrm{where}(f, x)\) \\
\(f_R = Q.\mathrm{where}(f, \mathrm{Q.not}(x))\) \\
{\bf if } \(Q.max(f_L) > Q.min(f_L)\) {\bf then} \+ \\
\(T_L = T_L \cup f_L \) \- \\
{\bf endif} \\
{\bf if } \(Q.max(f_R) > Q.min(f_R)\) {\bf then} \+ \\
\(T_R = T_R \cup f_R \) \- \\
{\bf endif} \- \\
{\bf endfor} \\
D.feature = \(f'\) \\
D.threshold = \(b(f')\) \\
D.left = \(\{\}\) \\
D.right = \(\{\}\) \\
\(DT(D.left, g_L, T_L)\) \\
\(DT(D.right, F_R, g_R, T_R)\) \- \\
{\bf end}
\end{tabbing}
\end{minipage}
}
\label{dt_pseudo_code}
\caption{Decision Tree algorithm}
\end{figure}
\begin{figure}
\centering
\fbox{
\begin{minipage}{15cm}
\begin{tabbing} \hspace*{0.25in} \= \hspace*{0.25in} \=
\hspace*{0.25in} \= \hspace*{0.25in} \= \kill
{\bf function } \(\mathrm{Benefit}(f, g, n_T, n_H)\) \+ \\
\(f', h^0, h^1 = CountIntervals(f, g)\) \\
\(b = \mathrm{Q.wtbnft}(h^0, h^1, n_T, n_H)\) (Table~\ref{algo_weighted_benefit}) \\
\(b', \_, i = \mathrm{Q.max}(b)\) \\
{\bf return} \(b', f'[i]\) \- \\
{\bf end}
\end{tabbing}
\end{minipage}
}
\label{compute_benefit_numeric}
\caption{Benefit Computation (numeric attributes)}
\end{figure}
%%-------------------------------------------
\begin{table}
\centering
\begin{tabular}{|l|l|l|} \hline \hline
{\bf Variable} & {\bf Formula} & {\bf Explanation} \\ \hline \hline
\(n_T^L\) & & number of tails on left \\ \hline
\(n_H^L\) & & number of heads on left \\ \hline
\(n_T^R\) & & number of tails on right \\ \hline
\(n_H^R\) & & number of heads on right \\ \hline
\(n_L\) & \(n_T^L + n_H^L \) & number on left \\ \hline
\(n_R\) & \(n_T^R + n_H^R \) & number on right \\ \hline
\(n\) & \(n_T + n_H \) & total number \\ \hline
\(w_L \) & \( n^L/n\) & weight on left \\ \hline
\(w_R \) & \( n^R/n\) & weight on left \\ \hline
\hline
\(o_H \) & \( n_T/n_H\) & odds for heads \\ \hline
\(o_T \) & \( n_H/n_T\) & odds for tails \\ \hline
\hline
\(p_H^L \) & \( n_H^L/n_L\) & probability of heads on left \\ \hline
\(p_H^R \) & \( n_H^R/n_R\) & probability of heads on right \\ \hline
\(p_T^L \) & \( n_T^L/n_L\) & probability of tails on left \\ \hline
\(p_T^R \) & \( n_T^R/n_R\) & probability of tails on right \\ \hline
\hline
\(b_H^L\) & \(o_H^L \times p_H^L + (-1) \times p_T^L\) &
benefit of betting heads on left \\ \hline
\(b_T^L\) & \(o_T^L \times p_T^L + (-1) \times p^H_L \) &
benefit of betting tails on left \\ \hline
\(b_H^R\) & \(o_H^R \times p_H^R + (-1) \times p_T^R \) &
benefit of betting heads on right \\ \hline
\(b_T^R\) & \(o_T^R \times p_T^R + (-1) \times p_H^R \) &
benefit of betting tails on right \\ \hline
\hline
\(b_L\) & \( \mathrm{max}(b_H^L, b_T^L)\) & benefit on left \\ \hline
\(b_R\) & \( \mathrm{max}(b_H^R, b_T^R)\) & benefit on right \\ \hline
\hline
\(b\) & \(b_L \times w_L + b_R \times w_R\) & weighted benefit \\ \hline
\end{tabular}
\label{algo_weighted_benefit}
\caption{Weighted Benefit Computation}
\end{table}
%%-------------------------------------------
\begin{figure}
\centering
\fbox{
\begin{minipage}{15cm}
\begin{tabbing} \hspace*{0.25in} \= \hspace*{0.25in} \= \kill
{\bf function } \(\mathrm{CountIntervals}(f, g)\) \+ \\
{\bf Inputs} \+ \\
Vector \(f\) of length \(n\) type F4 \\
Vector \(g\) of length \(n\) type I4 with values 0, 1 \- \\
{\bf Outputs} \+ \\
Vector \(f'\) of length \(n'\) type F4 \\
Vector \(h^0\) of length \(n'\) type I4 \\
Vector \(h^1\) of length \(n'\) type I4 \- \\
\(f'\) is the unique values of \(f\), sorted ascending \\
Let \(\delta(x)\) = 1 if \(x\) is true and 0 otherwise \\
For \(k = 0, 1\), compute \(h^k_j = \sum_{i=1}^{i=n} \delta(g_i = k \wedge f_i \leq f_j)\) \- \\
{\bf end}
\end{tabbing}
\end{minipage}
}
\label{count_intervals}
\caption{Count Intervals}
\end{figure}
%%-------------------------------------------
\section{Algorithm}
Since decision trees have been well documented, we focus our attention on the
salient characteristics of our approach which are
\be
\item how does one decide on the comparison to be performed at a node?
\item how does one decide when to not split a node further, assuming that asplit
is possible at all.
\ee
Given the simple recursive nature of decision trees, we focus our
decision on what is done at a single node. Without loss of generality,
let this be the root node. At this point, we know the number of elements
classified as Heads and Tails, \(n_H, n_T\) respectively. This allows us to set
the odds of betting on heads or tails. At each node, we are asked to a single
question.
\bi
\item For a numeric attribute, it is of the form \(x \leq y\)
\item For a boolean attribute, it is of the form \(x == y\), where
\(y\) can be true or false
%% TODO LATER
%% \item For an unordered categorical attribute that can take on values in \(X\),
%% it is of the form \(x \in y \subset X\)
\ei
We iterate over all possible values of \(y\) for each attribute and find the
attribute and decision that produces the maximum benefit. If this benefit
exceeds a pre-defined threshold, we split the data into two, a left branch and a
right branch and proceed recursively. Else, the expansion of the decision tree
stops at this point.
Figure~\ref{dt_pseudo_code} describes the algorithm at this level. For clarity of
exposition, we only describe the treatment of numeric attributes.
\subsection{Q Operators Used}
The Q operators used in Table~\ref{tbl_q_op}.
\begin{table}
\centering
\begin{tabular}{|l|l|l|l|} \hline \hline
{\bf Operator} & {\bf Input} & {\bf Output} & {\bf Explanation} \\ \hline \hline
y = not(x) & x B1 Vector & y B1 Vector & \(y_i = ~x_i\) \\ \hline
y = vsgt(x, s) & x Vector, s Scalar & \(y\) B1 Vector &
\(x_i \geq s \Rightarrow y_i = \) true; else, \(y_i = \) false \\ \hline
y = sum(x) & x Vector & y Scalar & \(y = \sum_i x_i\) \\ \hline
numby(x, n) & x Vector, n number,
% \(x_i \in [0, n-1]\)
&
y Vector & \(y_i = \) number of elements of \(x\) that have value \(i\) \\ \hline
% . Note that \(y:\mathrm{length} == n\)
\hline
\end{tabular}
\caption{Q Operators Used}
\label{tbl_q_op}
\end{table}
\subsection{Benefit Computation}
It is useful to model this problem as a gambling problem where we are
sampling with replacement.
\bi
\item Let there be 100 balls, with 60 being marked Heads and 40
being marked Tails.
\item Assume that we have to gamble on whether a ball picked at random is Heads
ot Tails. If the ``house'' sets odds to ensure a fair game, then it would offer
a payout of 4/6 if you bet heads and 6/4 if you bet tails.
\item If you bet heads, then the expected benefit is
\(\frac{60}{100} \times \frac{4}{6} +
\frac{40}{100} \times (-1) = 0\)
\item If you bet tails, then the expected benefit is
\(\frac{60}{100} \times (-1) +
\frac{40}{100} \times \frac{6}{4} = 0\)
\ei
Now, assume that before we place out bet, we are allowed to ask one question
which has an answer of left or right. If left, we are told that the ball was
selected from a population of 40 heads and 15 tails. If right, we are told that
the ball was selected from a population of 20 heads and 25 tails. Clearly, we
would bet heads if the answer is left and tails if the answer is right. The
question is: What is the expected benefit for 100 trials?
The answer is \(29 \frac{1}{6}\) and not 0 as before, calculated as follows.
\(100 ( \times ( \frac{40+15}{100} \times (
\frac{40}{40+15} \times \frac{4}{6} +
\frac{15}{40+15} \times -1 ) ) +
( \frac{20+25}{100} \times (
\frac{20}{20+25} \times -1 +
\frac{25}{20+25} \times \frac{6}{4} ) ) )
\)
which is \(
= (40 \times \frac{4}{6}) -15 - 20 + (25 \times \frac{6}{4} )
= 29 \frac{1}{6}\)
\ifthenelse{\equal{extra}{1}}{
\subsubsection{Categorical Attributes}
We deal with categorical attributes as follows. Let \(X\) be a categorical
attribute that takes on values \(\{x_1, x_2, \ldots x_M\}\), where \(M\) is
typically small. We can assume less than 100 values.
Let \(Y = \{(x_i, g_i)\}\) be the data set, where \(i = 1, \ldots N\).
By this we ean
that the \(i^{th}\) point has value \(x_i \in X\) and its goal attribute has
value \(g_i \in \{0, 1\}\).
\(Y\) may have other features but for now we are concentrating on \(X\).
Create a table, \(Z\), of vectors \(N, P, \rho\) of length \(M\) as follows.
\begin{enumerate}
\item
\(n_j = \sum_{i=1}^{i=N} z(i, j)\) where
\(z_j = 1 \) if \(x_i = x_j \) and \(g_i = 0\)
\item
\(p_j = \sum_{i=1}^{i=N} z(i, j)\) where
\(z_j = 1 \) if \(x_i = x_j \) and \(g_i = 1\)
\item
\(rho_j = \frac{p_j}{p_j+n_j}\)
\end{enumerate}
Sort \(Z\) on \(rho\). Create vectors, \(N', P'\) of length \(M\) as follows
\be
\item
\ee
}{}
\newpage
\section{Evaluating a decision tree}
\label{payout}
In addition to the standard metrics, such as classification accuracy, we
evaluate decision trees using the ``payout'' metric.
Table~\ref{dt_eval_code} describes what happens at a particular leaf of the decision tree. Let's explain the intuition with an example. Consider a leaf which had
\bi
\item 20 Heads and 30 Tails in the training set and
\item 10 Heads and 40 Tails in the testing set
\ei
When a head is presented to this leaf, the prediction is Tails. We award the
algorithm a credit of 2/5 and a debit of 3/5.
Similarly, when a tail is presented to this leaf, the prediction is Tails. We award the
algorithm a credit of 3/5 and a debit of 2/5. We average the payout for every
testing instance and that is construed to be the ``benefit'' of this decision tree.
Let \(b_x, w_x\) be the values for leaf \(x\). Then, the total payout of the tree is \(\frac{\sum_x b_x}{\sum_x w_x}\)
\begin{table}[hbtp]
\centering
\begin{tabular}{|l|l|l|} \hline \hline
\(n^H_1\) & number of heads in test data & \\ \hline
\(n^T_1\) & number of tails in test data & \\ \hline
\(n^H_0\) & number of heads in train data& \\ \hline
\(n^T_0\) & number of tails in train data& \\ \hline
%%
\(p^H\) & probability of heads at leaf & \(n^H_0 / (n^H_0 + n^T_0)\) \\ \hline
\(p^T\) & probability of tails at leaf & \(n^T_0 / (n^H_0 + n^T_0)\) \\ \hline
%%
\(b^H\) & payout for heads in test data & \(n^H_1 \times ( p^H - p^T )\) \\ \hline
\(b^T\) & payout for tails in test data & \(n^T_1 \times ( p^T - p^H )\) \\ \hline
%%
\(b\) & payout for test data & \(b_H + b_T\) \\ \hline
\(w\) & number of test instances & \(n^H_1 + n^T_1\) \\ \hline
\(\bar{b}\) & payout per instance & \(b/w\) \\ \hline
\hline
\end{tabular}
\label{dt_eval_code}
\caption{How a Leaf of a Decision Tree is evaluated}
\end{table}
\section{When to stop splitting?}
In Figure~\ref{dt_pseudo_code}, we stated that we stop splitting when the weighted benefit
is less than a threshold of \(\alpha\). We are now in a position to describe how
\(\alpha\) is determined. We search the space of possible values of \(\alpha =
(0, 1)\), evaluating the ``payout'' (Section~\ref{payout}) for each \(\alpha\).
We pick the \(\alpha\) which produces the maximum payout.
%% A sample on the breast cancer data set (reference TODO) is in
%% Figure~\ref{fig_breast_cancer_cost_versus_alpha}.
%
\section{Evalaution}
For evaluation, we chose the following data sets
\be
\item 2 publicly available data sets, the breast cancer data set and the
Titanic data set from the UCI ML Repository.
\item 3 proprietary data sets --- ds1, ds2, ds3
\item 2 synthetic data sets generated as follows
\be
\item \TBC
\item \TBC
\ee
\ee
We compare Q against sklearn.
In case of Q, the hyper-parameter to be optimized is \(\alpha\).
In case of sklearn, we use grid search to optimize for the hyper-parameters.We
pick the model that optimizes f1 score.
See \verb+../python/grid*txt+ \TBC
\begin{table}
\centering
\begin{tabular}{|l||l|l|l|l|l|l|l|} \hline \hline
{\bf Data Set} & {\bf Algorithm} & {\bf accuracy} & {\bf precision} & {\bf recall} & {\bf f1 score} & {\bf payout} \\ \hline \hline
cancer & Q & 92.0962 & 0.9385 & 0.9333 & 0.9359 & \textcolor{red}{0.8385} \\ \hline
cancer & sklearn & 94.1581 & 0.9605 & 0.9444 & 0.9524 & 0.8196 \\ \hline
\hline
titanic & Q & 78.7946 & 0.7453 & 0.6897 & 0.7164 & \textcolor{red}{0.5609} \\ \hline
titanic & sklearn & 81.0268 & 0.7871 & 0.7011 & 0.7416 & 0.4937 \\ \hline
\hline
ds1 & Q & 76.7681 &0.2441 &0.1511 & 0.1866 & \textcolor{red}{0.4723} \\ \hline
ds1 & sklearn & 75.6626 & 0.2659 & 0.2155 & 0.238 & 0.4687 \\ \hline
\hline
ds2 & Q & 62.0271 & 0.5597 & 0.7833 & 0.6529 & \textcolor{red}{0.1505} \\ \hline
ds2 & sklearn & 60.8696 & 0.5424 & 0.9077 & 0.679 & 0.1102 \\ \hline
\hline
ds3 & Q & 60.1256 & 0.5714 & 0.6323 & 0.6003 & \textcolor{red}{0.1722} \\ \hline
ds3 & sklearn & 59.056 & 0.5386 & 0.944 & 0.6859 & 0.0787 \\ \hline
\hline
\end{tabular}
\label{tbl_results}
\caption{Results comparing Q versus sklearn}
\end{table}
\subsection{Discussion}
The key takeaway from the results is that you get what you look for. In case of
Q, we are building the decision tree with optimizing payout in mind. In the case
of sk-learn, we are building the decision tree with optimizing f1 score in mind.
It should not come as a surprise that Q out performs sklearn when payout is the
quality metric and that sklearn out performs Q when f1 score is the quality
metric.
This leads us to the conclusion that the choice of splitting decision
should not be made independent of the metric that will be used to judge the
resultant decision tree. Of course, the quality metric should be chosen
base on how well it models the business problem at hand.
\subsection{Grid Search specifications for sklearn}
See \verb+f1_score_sklearn.txt+ \TBC
\bibliographystyle{alpha}
\bibliography{../../../DOC/Q_PAPER/ref.bib}
| {'content_hash': '6e7b1a7e29733beca28684b2a0459668', 'timestamp': '', 'source': 'github', 'line_count': 468, 'max_line_length': 162, 'avg_line_length': 40.51709401709402, 'alnum_prop': 0.6394367682733889, 'repo_name': 'NerdWalletOSS/Q', 'id': 'a48e693983b402be504eb059fc43bb4fdc25174a', 'size': '18962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ML/DT/doc/dt.tex', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1528854'}, {'name': 'C++', 'bytes': '11900'}, {'name': 'CMake', 'bytes': '414'}, {'name': 'CSS', 'bytes': '651'}, {'name': 'Cuda', 'bytes': '4192'}, {'name': 'HTML', 'bytes': '184009'}, {'name': 'JavaScript', 'bytes': '12282'}, {'name': 'Jupyter Notebook', 'bytes': '60539'}, {'name': 'Lex', 'bytes': '5777'}, {'name': 'Logos', 'bytes': '18046'}, {'name': 'Lua', 'bytes': '2273456'}, {'name': 'Makefile', 'bytes': '72536'}, {'name': 'Perl', 'bytes': '3421'}, {'name': 'Python', 'bytes': '121910'}, {'name': 'R', 'bytes': '1071'}, {'name': 'RPC', 'bytes': '5973'}, {'name': 'Shell', 'bytes': '128156'}, {'name': 'TeX', 'bytes': '819194'}, {'name': 'Terra', 'bytes': '3360'}, {'name': 'Vim script', 'bytes': '5911'}, {'name': 'Yacc', 'bytes': '52645'}]} |
<?php
use DTS\eBaySDK\Trading\Types\SummaryEventScheduleType;
class SummaryEventScheduleTypeTest extends \PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new SummaryEventScheduleType();
}
public function testCanBeCreated()
{
$this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\SummaryEventScheduleType', $this->obj);
}
public function testExtendsBaseType()
{
$this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
}
}
| {'content_hash': '97771a95f3c3171f51cbbeac2c0b8a19', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 99, 'avg_line_length': 23.347826086956523, 'alnum_prop': 0.6852886405959032, 'repo_name': 'spoilie/ebay-sdk-trading', 'id': '3625d00993ed6f783260ab299dc7cb6f38880347', 'size': '537', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/DTS/eBaySDK/Trading/Types/SummaryEventScheduleTypeTest.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Makefile', 'bytes': '1963'}, {'name': 'PHP', 'bytes': '3778863'}]} |
<?php
/**
* View: Events Bar Search Button Icon
*
* Override this template in your own theme by creating a file at:
* [your-theme]/tribe/events/v2/components/events-bar/search-button/icon.php
*
* See more documentation about our views templating system.
*
* @link {INSERT_ARTCILE_LINK_HERE}
*
* @version 4.9.10
*
*/
?>
<span class="tribe-events-c-events-bar__search-button-icon tribe-common-svgicon"></span>
| {'content_hash': 'bb8b0a2090f9f9e365b2da2600f6a89f', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 88, 'avg_line_length': 26.25, 'alnum_prop': 0.7047619047619048, 'repo_name': 'attacbe/ab2', 'id': 'a57b33488f674e2c0763d1bd00fc67c86e4e4800', 'size': '420', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'tribe-events/components/events-bar/search-button/icon.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '178374'}, {'name': 'Hack', 'bytes': '1845'}, {'name': 'JavaScript', 'bytes': '7855'}, {'name': 'PHP', 'bytes': '189324'}, {'name': 'SCSS', 'bytes': '13479'}]} |
<html>
<head>
<!-- script src="http://localhost:9091"> </script -->
<link href="../build-output/css/sdk.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript" src="../build-output/_single-bundle/readium-shared-js_all.js"> </script>
<script type="text/javascript" src="./index.js"> </script>
<script type="text/javascript" src="../readium-cfi-js/dev/index.js"> </script>
</head>
<body>
<div id="viewport"> </div>
</body>
</html>
| {'content_hash': '9ddd6b9940d9f66e61a61c5db8ae75b3', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 103, 'avg_line_length': 26.529411764705884, 'alnum_prop': 0.6541019955654102, 'repo_name': 'dariocravero/readium-shared-js', 'id': '3fe99d97ec1a3b24ed698eb7fdc63d2b612959da', 'size': '451', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'dev/index_RequireJS_single-bundle.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '3873'}, {'name': 'CoffeeScript', 'bytes': '8503'}, {'name': 'HTML', 'bytes': '3042'}, {'name': 'JavaScript', 'bytes': '3431189'}]} |
import '../amp-accordion';
import {ActionTrust} from '../../../../src/action-constants';
import {Keys} from '../../../../src/utils/key-codes';
import {computedStyle} from '../../../../src/style';
import {poll} from '../../../../testing/iframe';
import {toggleExperiment} from '../../../../src/experiments';
import {tryFocus} from '../../../../src/dom';
describes.realWin(
'amp-accordion',
{
amp: {
extensions: ['amp-accordion'],
},
},
(env) => {
let win, doc;
let counter = 0;
beforeEach(() => {
win = env.win;
doc = win.document;
counter += 1;
});
function getAmpAccordionWithContents(contents, opt_shouldSetId) {
win.sessionStorage.clear();
const ampAccordion = doc.createElement('amp-accordion');
if (opt_shouldSetId) {
ampAccordion.setAttribute('id', `acc${counter}`);
}
for (let i = 0; i < contents.length; i++) {
const section = doc.createElement('section');
if (opt_shouldSetId) {
section.setAttribute('id', `acc${counter}sec${i}`);
}
section.innerHTML = contents[i];
ampAccordion.appendChild(section);
if (i == 1) {
section.setAttribute('expanded', '');
}
}
doc.body.appendChild(ampAccordion);
return ampAccordion
.build()
.then(() => {
ampAccordion.implementation_.mutateElement = (fn) =>
new Promise(() => {
fn();
});
return ampAccordion.layoutCallback();
})
.then(() => ampAccordion);
}
function getAmpAccordion(opt_shouldSetId) {
const contents = [0, 1, 2].map((i) => {
return (
'<h2 tabindex="0">' +
`Section ${i}<span>nested stuff<span>` +
`</h2><div id='test${i}'>Lorem ipsum</div>`
);
});
return getAmpAccordionWithContents(contents, opt_shouldSetId);
}
/** Helper for invoking expand/collapse actions on amp-accordion. */
function execute(impl, method, trust = ActionTrust.HIGH, opt_sectionId) {
const invocation = {
method,
trust,
satisfiesTrust: (min) => trust >= min,
};
if (opt_sectionId) {
invocation.args = {section: opt_sectionId};
}
impl.executeAction(invocation);
}
it('should expand when high trust toggle action is triggered on a collapsed section', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
impl.toggle_(headerElements[0].parentNode, ActionTrust.HIGH);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
});
});
it('multiple accordions should not have the same IDs on content', () => {
return getAmpAccordion().then(() => {
return getAmpAccordion().then(() => {
const contentElements = doc.getElementsByClassName(
'i-amphtml-accordion-content'
);
for (let i = 0; i < contentElements.length; i++) {
expect(contentElements[i].id.startsWith('_AMP_content_')).to.be
.false;
}
});
});
});
it('should collapse when high trust toggle action is triggered on a expanded section', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
impl.toggle_(headerElements[1].parentNode, ActionTrust.HIGH);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
});
});
it('should expand when expand action is triggered on a collapsed section', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
impl.toggle_(headerElements[0].parentNode, ActionTrust.HIGH, true);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
});
});
it(
'should collapse other sections when expand action is triggered on a ' +
'collapsed section if expand-single-section attribute is set',
() => {
return getAmpAccordion().then((ampAccordion) => {
ampAccordion.setAttribute('expand-single-section', '');
expect(ampAccordion.hasAttribute('expand-single-section')).to.be.true;
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll(
'section > *:first-child'
);
// second section is expanded by default
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
// expand the first section
impl.toggle_(headerElements[0].parentNode, ActionTrust.HIGH, true);
// we expect the first section to be expanded
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
// we expect the second section to be collapsed
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
});
}
);
it('should expand when low trust toggle action is triggered on a collapsed section', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
impl.toggle_(headerElements[0].parentNode, ActionTrust.LOW);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
});
});
it('should collapse when low trust toggle action is triggered on an expanded section', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
impl.toggle_(headerElements[1].parentNode, ActionTrust.LOW);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
});
});
it('should expand when rendersubtreeactivation event is triggered on a collapsed section', () => {
toggleExperiment(win, 'amp-accordion-display-locking', true);
return getAmpAccordion().then(() => {
const section = doc.querySelector('section:not([expanded])');
const header = section.firstElementChild;
const content = section.children[1];
expect(section.hasAttribute('expanded')).to.be.false;
expect(header.getAttribute('aria-expanded')).to.equal('false');
content.dispatchEvent(new Event('rendersubtreeactivation'));
expect(section.hasAttribute('expanded')).to.be.true;
expect(header.getAttribute('aria-expanded')).to.equal('true');
toggleExperiment(win, 'amp-accordion-display-locking', false);
});
});
it(
"should trigger a section's expand event the section is expanded " +
'without animation',
() => {
let impl;
return getAmpAccordion(true)
.then((ampAccordion) => {
impl = ampAccordion.implementation_;
impl.sections_[0].setAttribute(
'on',
`expand:acc${counter}.expand(section='acc${counter}sec${2}')`
);
expect(impl.sections_[2].hasAttribute('expanded')).to.be.false;
impl.toggle_(impl.sections_[0], ActionTrust.HIGH, true);
return poll('wait for first section to expand', () =>
impl.sections_[0].hasAttribute('expanded')
);
})
.then(() => {
expect(impl.sections_[2].hasAttribute('expanded')).to.be.true;
});
}
);
it(
"should trigger a section's collapse event the section is expanded " +
'without animation',
() => {
let impl;
return getAmpAccordion(true)
.then((ampAccordion) => {
impl = ampAccordion.implementation_;
impl.sections_[1].setAttribute(
'on',
`collapse:acc${counter}.expand(section='acc${counter}sec${2}')`
);
expect(impl.sections_[2].hasAttribute('expanded')).to.be.false;
impl.toggle_(impl.sections_[1], ActionTrust.HIGH, false);
return poll(
'wait for first section to expand',
() => !impl.sections_[1].hasAttribute('expanded')
);
})
.then(() => {
expect(impl.sections_[2].hasAttribute('expanded')).to.be.true;
});
}
);
it(
"should trigger a section's expand event the section is expanded " +
'with animation',
() => {
let impl;
return getAmpAccordion(true)
.then((ampAccordion) => {
ampAccordion.setAttribute('animate', '');
impl = ampAccordion.implementation_;
impl.sections_[0].setAttribute(
'on',
`expand:acc${counter}.expand(section='acc${counter}sec${2}')`
);
expect(impl.sections_[2].hasAttribute('expanded')).to.be.false;
impl.toggle_(impl.sections_[0], ActionTrust.HIGH, true);
return poll('wait for first section to expand', () =>
impl.sections_[0].hasAttribute('expanded')
);
})
.then(() => {
return poll('wait for second section to expand', () =>
impl.sections_[2].hasAttribute('expanded')
);
});
}
);
it(
"should trigger a section's collapse event the section is expanded " +
'with animation',
() => {
let impl;
return getAmpAccordion(true)
.then((ampAccordion) => {
ampAccordion.setAttribute('animate', '');
impl = ampAccordion.implementation_;
impl.sections_[1].setAttribute(
'on',
`collapse:acc${counter}.expand(section='acc${counter}sec${2}')`
);
expect(impl.sections_[2].hasAttribute('expanded')).to.be.false;
impl.toggle_(impl.sections_[1], ActionTrust.HIGH, false);
return poll(
'wait for first section to expand',
() => !impl.sections_[1].hasAttribute('expanded')
);
})
.then(() => {
return poll('wait for second section to expand', () =>
impl.sections_[2].hasAttribute('expanded')
);
});
}
);
it('should size responsive children correctly when animating', async () => {
const contents = [
`
<h2>Section header</h2>
<amp-layout layout="responsive" width="3" height="2"></amp-layout>
`,
];
const ampAccordion = await getAmpAccordionWithContents(contents, true);
const impl = ampAccordion.implementation_;
const firstSection = impl.sections_[0];
const content = firstSection.querySelector('amp-layout');
ampAccordion.setAttribute('animate', '');
ampAccordion.style.width = '300px';
impl.toggle_(firstSection, ActionTrust.HIGH, true);
await poll('wait for first section to finish animating', () => {
return (
firstSection.hasAttribute('expanded') &&
computedStyle(win, content).opacity == '1'
);
});
expect(content.getBoundingClientRect()).to.include({
width: 300,
height: 200,
});
});
it('should size fixed size children correctly when animating', async () => {
const contents = [
`
<h2>Section header</h2>
<amp-layout layout="fixed" width="300" height="200"></amp-layout>
`,
];
const ampAccordion = await getAmpAccordionWithContents(contents, true);
const impl = ampAccordion.implementation_;
const firstSection = impl.sections_[0];
const content = firstSection.querySelector('amp-layout');
ampAccordion.setAttribute('animate', '');
ampAccordion.style.width = '400px';
impl.toggle_(firstSection, ActionTrust.HIGH, true);
await poll('wait for first section to finish animating', () => {
return (
firstSection.hasAttribute('expanded') &&
computedStyle(win, content).opacity == '1'
);
});
expect(content.getBoundingClientRect()).to.include({
width: 300,
height: 200,
});
});
it('should stay expanded on the expand action when expanded', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
impl.toggle_(headerElements[1].parentNode, ActionTrust.HIGH, true);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
});
});
it('should collapse on the collapse action when expanded', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
impl.toggle_(headerElements[1].parentNode, ActionTrust.HIGH, false);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
});
});
it('should stay collapsed on the collapse action when collapsed', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
impl.toggle_(headerElements[0].parentNode, ActionTrust.HIGH, false);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
});
});
it('should expand when header of a collapsed section is clicked', () => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll('section > *:first-child');
const clickEvent = {
target: headerElements[0],
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
ampAccordion.implementation_.onHeaderPicked_(clickEvent);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
expect(clickEvent.preventDefault.called).to.be.true;
});
});
it("should expand section when header's child is clicked", () => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll('section > *:first-child');
const header = headerElements[0];
const child = doc.createElement('div');
header.appendChild(child);
const clickEvent = {
target: child,
currentTarget: header,
preventDefault: env.sandbox.spy(),
};
expect(header.parentNode.hasAttribute('expanded')).to.be.false;
expect(header.getAttribute('aria-expanded')).to.equal('false');
ampAccordion.implementation_.onHeaderPicked_(clickEvent);
expect(header.parentNode.hasAttribute('expanded')).to.be.true;
expect(header.getAttribute('aria-expanded')).to.equal('true');
expect(clickEvent.preventDefault).to.have.been.called;
});
});
it('should collapse when header of an expanded section is clicked', () => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll('section > *:first-child');
const clickEvent = {
target: headerElements[1],
currentTarget: headerElements[1],
preventDefault: env.sandbox.spy(),
};
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
ampAccordion.implementation_.onHeaderPicked_(clickEvent);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
expect(clickEvent.preventDefault).to.have.been.called;
});
});
it('should allow for clickable links in header', () => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll('section > *:first-child');
const a = doc.createElement('a');
headerElements[0].appendChild(a);
const aClickEvent = {
target: a,
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
ampAccordion.implementation_.clickHandler_(aClickEvent);
expect(aClickEvent.preventDefault).to.not.have.been.called;
});
});
it(
'should expand when header of a collapsed section is ' +
'activated via keyboard',
() => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll(
'section > *:first-child'
);
const keyDownEvent = {
key: Keys.SPACE,
target: headerElements[0],
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
ampAccordion.implementation_.keyDownHandler_(keyDownEvent);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
expect(keyDownEvent.preventDefault.called).to.be.true;
});
}
);
it(
"should NOT expand section when header's child is " +
'activated via keyboard',
() => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll(
'section > *:first-child'
);
const child = doc.createElement('div');
headerElements[0].appendChild(child);
const keyDownEvent = {
key: Keys.ENTER,
target: child,
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
ampAccordion.implementation_.keyDownHandler_(keyDownEvent);
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
expect(keyDownEvent.preventDefault.called).to.be.false;
});
}
);
it(
'should collapse when header of an expanded section is ' +
'activated via keyboard',
() => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll(
'section > *:first-child'
);
const keyDownEvent = {
key: Keys.ENTER,
target: headerElements[1],
currentTarget: headerElements[1],
preventDefault: env.sandbox.spy(),
};
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'true'
);
ampAccordion.implementation_.keyDownHandler_(keyDownEvent);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[1].getAttribute('aria-expanded')).to.equal(
'false'
);
expect(keyDownEvent.preventDefault.called).to.be.true;
});
}
);
it(
'should be navigable by up and down arrow keys when ' +
'any header has focus',
() => {
return getAmpAccordion().then((ampAccordion) => {
const headerElements = doc.querySelectorAll(
'section > *:first-child'
);
// Focus the first header,
tryFocus(headerElements[0]);
expect(doc.activeElement).to.equal(headerElements[0]);
const upArrowEvent = {
key: Keys.UP_ARROW,
target: headerElements[0],
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
ampAccordion.implementation_.keyDownHandler_(upArrowEvent);
expect(doc.activeElement).to.equal(
headerElements[headerElements.length - 1]
);
const downArrowEvent = {
key: Keys.DOWN_ARROW,
target: headerElements[headerElements.length - 1],
currentTarget: headerElements[headerElements.length - 1],
preventDefault: env.sandbox.spy(),
};
ampAccordion.implementation_.keyDownHandler_(downArrowEvent);
expect(doc.activeElement).to.equal(headerElements[0]);
});
}
);
it('should return correct sessionStorageKey', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const url = win.location.href;
impl.element.id = '321';
const id = impl.getSessionStorageKey_();
const correctId = 'amp-321-' + url;
expect(id).to.be.equal(correctId);
});
});
it('should set sessionStorage on change in expansion', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const headerElements = doc.querySelectorAll('section > *:first-child');
const clickEventExpandElement = {
target: headerElements[0],
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
const clickEventCollapseElement = {
target: headerElements[1],
currentTarget: headerElements[1],
preventDefault: env.sandbox.spy(),
};
expect(Object.keys(impl.currentState_)).to.have.length(0);
impl.onHeaderPicked_(clickEventExpandElement);
expect(Object.keys(impl.currentState_)).to.have.length(1);
expect(impl.currentState_['test0']).to.be.true;
impl.onHeaderPicked_(clickEventCollapseElement);
expect(Object.keys(impl.currentState_)).to.have.length(2);
expect(impl.currentState_['test0']).to.be.true;
expect(impl.currentState_['test1']).to.be.false;
});
});
it('should respect session states and expand/collapse', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
let headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'false'
);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[2].parentNode.hasAttribute('expanded')).to.be
.false;
impl.getSessionState_ = function () {
return {
'test0': true,
};
};
impl.buildCallback();
headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[2].parentNode.hasAttribute('expanded')).to.be
.false;
impl.getSessionState_ = function () {
return {
'test0': true,
'test1': false,
};
};
impl.buildCallback();
headerElements = doc.querySelectorAll('section > *:first-child');
expect(headerElements[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements[0].getAttribute('aria-expanded')).to.equal(
'true'
);
expect(headerElements[1].parentNode.hasAttribute('expanded')).to.be
.false;
expect(headerElements[2].parentNode.hasAttribute('expanded')).to.be
.false;
});
});
it('should disable sessionStorage when opt-out', () => {
return getAmpAccordion().then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const setSessionStateSpy = env.sandbox.spy();
const getSessionStateSpy = env.sandbox.spy();
impl.win.sessionStorage.setItem = function () {
setSessionStateSpy();
};
impl.win.sessionStorage.getItem = function () {
getSessionStateSpy();
};
ampAccordion.setAttribute('disable-session-states', null);
impl.buildCallback();
expect(Object.keys(impl.currentState_)).to.have.length(0);
const headerElements = doc.querySelectorAll('section > *:first-child');
const clickEventExpandElement = {
target: headerElements[0],
currentTarget: headerElements[0],
preventDefault: env.sandbox.spy(),
};
impl.onHeaderPicked_(clickEventExpandElement);
expect(getSessionStateSpy).to.not.have.been.called;
expect(setSessionStateSpy).to.not.have.been.called;
expect(Object.keys(impl.currentState_)).to.have.length(1);
});
});
it('two accordions should not affect each other', () => {
return getAmpAccordion().then((ampAccordion) => {
const ampAccordion1 = ampAccordion;
const ampAccordion2 = doc.createElement('amp-accordion');
for (let i = 0; i < 3; i++) {
const section = doc.createElement('section');
section.innerHTML =
'<h2>Section ' +
i +
"<span>nested stuff<span></h2><div id='test" +
i +
"'>Loreum ipsum</div>";
ampAccordion2.appendChild(section);
}
doc.body.appendChild(ampAccordion2);
return ampAccordion2
.build()
.then(() => {
ampAccordion.implementation_.mutateElement = (fn) => fn();
return ampAccordion.layoutCallback();
})
.then(() => {
const headerElements1 = ampAccordion1.querySelectorAll(
'section > *:first-child'
);
const clickEventElement = {
target: headerElements1[0],
currentTarget: headerElements1[0],
preventDefault: env.sandbox.spy(),
};
ampAccordion1.implementation_.onHeaderPicked_(clickEventElement);
const headerElements2 = ampAccordion2.querySelectorAll(
'section > *:first-child'
);
expect(headerElements1[0].parentNode.hasAttribute('expanded')).to.be
.true;
expect(headerElements2[0].parentNode.hasAttribute('expanded')).to.be
.false;
});
});
});
it('should trigger expand/collapse events', () => {
return getAmpAccordion(true).then((ampAccordion) => {
const impl = ampAccordion.implementation_;
const actions = impl.getActionServiceForTesting();
env.sandbox.stub(actions, 'trigger');
execute(impl, 'collapse', 123, `acc${counter}sec1`);
expect(actions.trigger).to.be.calledOnce;
expect(actions.trigger.getCall(0)).to.be.calledWith(
/* element */ env.sandbox.match.has('tagName'),
'collapse',
/* event */ env.sandbox.match.has('detail'),
/* trust */ 123
);
execute(impl, 'expand', 456, `acc${counter}sec1`);
expect(actions.trigger).to.be.calledTwice;
expect(actions.trigger.getCall(1)).to.be.calledWith(
/* element */ env.sandbox.match.has('tagName'),
'expand',
/* event */ env.sandbox.match.has('detail'),
/* trust */ 456
);
});
});
}
);
| {'content_hash': '9f77f6db0c07c2fb0c02fad6867186e1', 'timestamp': '', 'source': 'github', 'line_count': 844, 'max_line_length': 102, 'avg_line_length': 37.58175355450237, 'alnum_prop': 0.5821747217755919, 'repo_name': 'yandex-pcode/amphtml', 'id': 'd691c05ca10950d3495d5e78e65ad7822bdb6470', 'size': '32346', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'extensions/amp-accordion/0.1/test/test-amp-accordion.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '105490'}, {'name': 'Go', 'bytes': '7459'}, {'name': 'HTML', 'bytes': '956707'}, {'name': 'Java', 'bytes': '36670'}, {'name': 'JavaScript', 'bytes': '8646504'}, {'name': 'Python', 'bytes': '75512'}, {'name': 'Ruby', 'bytes': '12941'}, {'name': 'Shell', 'bytes': '6942'}, {'name': 'Yacc', 'bytes': '22026'}]} |
namespace {
#if !BUILDFLAG(IS_ANDROID)
cart_db::ChromeCartContentProto BuildProto(const char* domain,
const char* cart_url) {
cart_db::ChromeCartContentProto proto;
proto.set_key(domain);
proto.set_merchant(domain);
proto.set_merchant_cart_url(cart_url);
proto.set_timestamp(base::Time::Now().ToDoubleT());
return proto;
}
cart_db::ChromeCartProductProto BuildProductInfoProto(const char* product_id) {
cart_db::ChromeCartProductProto proto;
proto.set_product_id(product_id);
return proto;
}
cart_db::ChromeCartContentProto BuildProtoWithProducts(
const char* domain,
const char* cart_url,
const std::vector<const char*>& product_urls) {
cart_db::ChromeCartContentProto proto;
proto.set_key(domain);
proto.set_merchant_cart_url(cart_url);
for (const auto* const v : product_urls) {
proto.add_product_image_urls(v);
}
return proto;
}
cart_db::ChromeCartContentProto BuildProtoWithProducts(
const char* domain,
const char* cart_url,
const std::vector<const char*>& product_urls,
const std::vector<const char*>& product_ids) {
cart_db::ChromeCartContentProto proto;
proto.set_key(domain);
proto.set_merchant_cart_url(cart_url);
for (const auto* const url : product_urls) {
proto.add_product_image_urls(url);
}
for (const auto* const id : product_ids) {
auto* added_product = proto.add_product_infos();
*added_product = BuildProductInfoProto(id);
}
return proto;
}
const char kMockExample[] = "guitarcenter.com";
const char kMockExampleFallbackURL[] = "https://www.guitarcenter.com/cart";
const char kMockExampleLinkURL[] =
"https://www.guitarcenter.com/shopping-cart/";
const char kMockExampleURL[] = "https://www.guitarcenter.com/cart.html";
const cart_db::ChromeCartContentProto kMockExampleProtoFallbackCart =
BuildProto(kMockExample, kMockExampleFallbackURL);
const cart_db::ChromeCartContentProto kMockExampleProtoLinkCart =
BuildProto(kMockExample, kMockExampleLinkURL);
const cart_db::ChromeCartContentProto kMockExampleProto =
BuildProto(kMockExample, kMockExampleURL);
const cart_db::ChromeCartContentProto kMockExampleProtoWithProducts =
BuildProtoWithProducts(
kMockExample,
kMockExampleURL,
{"https://static.guitarcenter.com/product-image/foo_123",
"https://images.cymax.com/Images/3/bar_456-baz_789",
"https://static.guitarcenter.com/product-image/qux_357"});
const cart_db::ChromeCartContentProto
kMockExampleProtoWithProductsWithoutSaved = BuildProtoWithProducts(
kMockExample,
kMockExampleURL,
{"https://static.guitarcenter.com/product-image/foo_123",
"https://images.cymax.com/Images/3/bar_456-baz_789"});
const char kMockAmazon[] = "amazon.com";
const char kMockAmazonURL[] = "https://www.amazon.com/gp/cart/view.html";
const cart_db::ChromeCartContentProto kMockAmazonProto =
BuildProto(kMockAmazon, kMockAmazonURL);
const char kMockWalmart[] = "walmart.com";
const char kMockWalmartURL[] = "https://www.walmart.com/cart";
const cart_db::ChromeCartContentProto kMockWalmartProto =
BuildProto(kMockWalmart, kMockWalmartURL);
using ShoppingCarts =
std::vector<SessionProtoDB<cart_db::ChromeCartContentProto>::KeyAndValue>;
const ShoppingCarts kExpectedExampleFallbackCart = {
{kMockExample, kMockExampleProtoFallbackCart}};
const ShoppingCarts kExpectedExampleLinkCart = {
{kMockExample, kMockExampleProtoLinkCart}};
const ShoppingCarts kExpectedExample = {{kMockExample, kMockExampleProto}};
const ShoppingCarts kExpectedExampleWithProducts = {
{kMockExample, kMockExampleProtoWithProducts}};
const ShoppingCarts kExpectedExampleWithProductsWithoutSaved = {
{kMockExample, kMockExampleProtoWithProductsWithoutSaved}};
const ShoppingCarts kExpectedAmazon = {{kMockAmazon, kMockAmazonProto}};
const ShoppingCarts kExpectedWalmart = {{kMockWalmart, kMockWalmartProto}};
const ShoppingCarts kEmptyExpected = {};
#endif
std::unique_ptr<net::test_server::HttpResponse> BasicResponse(
const net::test_server::HttpRequest& request) {
// This should be served from test data.
if (request.relative_url == "/purchase.html")
return nullptr;
if (request.relative_url == "/product.html")
return nullptr;
if (request.relative_url == "/cart.html")
return nullptr;
if (request.relative_url == "/shopping-cart.html")
return nullptr;
if (request.relative_url == "/cart-in-portal.html")
return nullptr;
if (request.relative_url == "/product-page.html")
return nullptr;
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_content("dummy");
response->set_content_type("text/html");
return response;
}
// Tests CommerceHintAgent.
class CommerceHintAgentTest : public PlatformBrowserTest {
public:
using FormSubmittedEntry = ukm::builders::Shopping_FormSubmitted;
using XHREntry = ukm::builders::Shopping_WillSendRequest;
using ExtractionEntry = ukm::builders::Shopping_CartExtraction;
CommerceHintAgentTest() = default;
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"},
// Extend timeout to avoid flakiness.
{"cart-extraction-timeout", "1m"}}}},
{optimization_guide::features::kOptimizationHints});
}
void SetUpCommandLine(base::CommandLine* command_line) override {
// HTTPS server only serves a valid cert for localhost, so this is needed
// to load pages from other hosts without an error.
command_line->AppendSwitch(switches::kIgnoreCertificateErrors);
}
void SetUpOnMainThread() override {
PlatformBrowserTest::SetUpOnMainThread();
commerce_hint_service_ =
cart::CommerceHintService::FromWebContents(web_contents());
#if !BUILDFLAG(IS_ANDROID)
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
service_ = CartServiceFactory::GetForProfile(profile);
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
ASSERT_TRUE(identity_manager);
signin::SetPrimaryAccount(identity_manager, "[email protected]",
signin::ConsentLevel::kSync);
#endif
// This is necessary to test non-localhost domains. See |NavigateToURL|.
host_resolver()->AddRule("*", "127.0.0.1");
https_server_.ServeFilesFromSourceDirectory("chrome/test/data/cart/");
https_server_.RegisterRequestHandler(base::BindRepeating(&BasicResponse));
ASSERT_TRUE(https_server_.InitializeAndListen());
https_server_.StartAcceptingConnections();
ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
}
protected:
content::WebContents* web_contents() {
return chrome_test_utils::GetActiveWebContents(this);
}
void NavigateToURL(const std::string& url) {
// All domains resolve to 127.0.0.1 in this test.
GURL gurl(url);
ASSERT_TRUE(content::NavigateToURL(
web_contents(), https_server_.GetURL(gurl.host(), gurl.path())));
base::RunLoop().RunUntilIdle();
}
void SendXHR(const std::string& relative_path, const char post_data[]) {
const char script_template[] = R"(
new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open('POST', $1, true);
xhr.onload = () => {
resolve(true);
};
xhr.send($2);
});
)";
std::string script =
content::JsReplace(script_template, relative_path, post_data);
ASSERT_EQ(true, EvalJs(web_contents(), script)) << script;
}
#if !BUILDFLAG(IS_ANDROID)
void WaitForCartCount(const ShoppingCarts& expected) {
satisfied_ = false;
while (true) {
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
service_->LoadAllActiveCarts(base::BindOnce(
&CommerceHintAgentTest::CheckCartCount, base::Unretained(this),
run_loop.QuitClosure(), expected));
run_loop.Run();
if (satisfied_)
break;
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
}
}
void CheckCartCount(base::OnceClosure closure,
ShoppingCarts expected,
bool result,
ShoppingCarts found) {
bool same_size = found.size() == expected.size();
satisfied_ = same_size;
if (same_size) {
for (size_t i = 0; i < expected.size(); i++) {
EXPECT_EQ(found[i].first, expected[i].first);
GURL::Replacements remove_port;
remove_port.ClearPort();
EXPECT_EQ(GURL(found[i].second.merchant_cart_url())
.ReplaceComponents(remove_port)
.spec(),
expected[i].second.merchant_cart_url());
}
} else {
VLOG(3) << "Found " << found.size() << " but expecting "
<< expected.size();
}
std::move(closure).Run();
}
void WaitForCarts(const ShoppingCarts& expected) {
satisfied_ = false;
while (true) {
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
service_->LoadAllActiveCarts(base::BindOnce(
&CommerceHintAgentTest::CheckCarts, base::Unretained(this),
run_loop.QuitClosure(), expected));
run_loop.Run();
if (satisfied_)
break;
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
}
}
void CheckCarts(base::OnceClosure closure,
ShoppingCarts expected,
bool result,
ShoppingCarts found) {
bool same_size = found.size() == expected.size();
satisfied_ = same_size;
if (same_size) {
for (size_t i = 0; i < expected.size(); i++) {
satisfied_ &= found[i].first == expected[i].first;
GURL::Replacements remove_port;
remove_port.ClearPort();
satisfied_ &= GURL(found[i].second.merchant_cart_url())
.ReplaceComponents(remove_port)
.spec() == expected[i].second.merchant_cart_url();
satisfied_ &=
found[i].second.merchant() == expected[i].second.merchant();
}
}
std::move(closure).Run();
}
void WaitForProductCount(const ShoppingCarts& expected) {
satisfied_ = false;
while (true) {
base::RunLoop().RunUntilIdle();
base::RunLoop run_loop;
service_->LoadAllActiveCarts(base::BindOnce(
&CommerceHintAgentTest::CheckCartWithProducts, base::Unretained(this),
run_loop.QuitClosure(), expected));
run_loop.Run();
if (satisfied_)
break;
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout());
}
}
void CheckCartWithProducts(base::OnceClosure closure,
ShoppingCarts expected,
bool result,
ShoppingCarts found) {
bool fail = false;
bool same_size = found.size() == expected.size();
if (!same_size)
fail = true;
for (size_t i = 0; i < std::min(found.size(), expected.size()); i++) {
EXPECT_EQ(found[i].first, expected[i].first);
GURL::Replacements remove_port;
remove_port.ClearPort();
EXPECT_EQ(GURL(found[i].second.merchant_cart_url())
.ReplaceComponents(remove_port)
.spec(),
expected[i].second.merchant_cart_url());
same_size = found[i].second.product_image_urls_size() ==
expected[i].second.product_image_urls_size();
if (!same_size) {
fail = true;
} else {
for (int j = 0; j < found[i].second.product_image_urls_size(); j++) {
EXPECT_EQ(found[i].second.product_image_urls(j),
expected[i].second.product_image_urls(j));
}
}
same_size = found[i].second.product_infos_size() ==
expected[i].second.product_infos_size();
if (!same_size) {
fail = true;
} else {
for (int j = 0; j < found[i].second.product_infos_size(); j++) {
EXPECT_EQ(found[i].second.product_infos(j).product_id(),
expected[i].second.product_infos(j).product_id());
}
}
}
satisfied_ = !fail;
std::move(closure).Run();
}
#endif
void ExpectUKMCount(base::StringPiece entry_name,
const std::string& metric_name,
int expected_count) {
auto entries = ukm_recorder()->GetEntriesByName(entry_name);
int count = 0;
for (const auto* const entry : entries) {
if (ukm_recorder()->GetEntryMetric(entry, metric_name)) {
count += 1;
}
}
EXPECT_EQ(count, expected_count);
}
ukm::TestAutoSetUkmRecorder* ukm_recorder() { return ukm_recorder_.get(); }
void WaitForUmaCount(base::StringPiece name,
base::HistogramBase::Count expected_count) {
while (true) {
base::RunLoop().RunUntilIdle();
metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
base::HistogramBase::Count count = 0;
for (const auto& bucket : histogram_tester_.GetAllSamples(name))
count += bucket.count;
ASSERT_LE(count, expected_count) << "WaitForUmaCount(" << name
<< ") has more counts than expectation.";
if (count == expected_count)
break;
LOG(INFO) << "WaitForUmaCount() is expecting " << expected_count
<< " but found " << count;
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout() * 10);
}
}
void WaitForUmaBucketCount(base::StringPiece name,
base::HistogramBase::Sample sample,
base::HistogramBase::Count expected_count) {
while (true) {
base::RunLoop().RunUntilIdle();
metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting();
auto count = histogram_tester_.GetBucketCount(name, sample);
if (count == expected_count)
break;
LOG(INFO) << "WaitForUmaBucketCount() is expecting " << expected_count
<< " but found " << count;
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout() * 10);
}
}
base::test::ScopedFeatureList scoped_feature_list_;
#if !BUILDFLAG(IS_ANDROID)
CartService* service_;
#endif
cart::CommerceHintService* commerce_hint_service_;
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
bool satisfied_;
base::HistogramTester histogram_tester_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByURL) {
// For add-to-cart by URL, normally a URL in that domain has already been
// committed.
NavigateToURL("https://www.guitarcenter.com/");
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByForm) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByForm_WithLink) {
NavigateToURL("https://www.guitarcenter.com/product.html");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleLinkCart);
#endif
ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1);
}
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByForm_WithWrongLink) {
// Mismatching eTLD+1 domain uses cart URL in the look-up table.
NavigateToURL("https://walmart.com/product.html");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
WaitForCartCount(kExpectedWalmart);
ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1);
}
#endif
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddToCartByURL_XHR) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
ExpectUKMCount(XHREntry::kEntryName, "IsAddToCart", 1);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, SkipAddToCart_FromComponent) {
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), R"###(
{
"guitarcenter.com": {
"skip_add_to_cart_regex": "dummy-request"
}
}
)###",
"{}", "", "");
DCHECK(is_populated);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
SendXHR("/add-to-cart/dummy-request-url", "product: 123");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
}
// TODO(https://crbug/1310497, https://crbug.com/1362442): This test is flaky
// on ChromeOS and Linux Asan.
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_VisitCart DISABLED_VisitCart
#elif BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER)
#define MAYBE_VisitCart DISABLED_VisitCart
#else
#define MAYBE_VisitCart VisitCart
#endif
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, MAYBE_VisitCart) {
// Cannot use dummy page with zero products, or the cart would be deleted.
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExample);
#endif
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest,
VisitCart_GeneralPattern_FromComponent) {
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), "{}", R"###(
{
"cart_page_url_regex": "(special|lol)"
}
)###",
"", "");
DCHECK(is_populated);
NavigateToURL("https://www.guitarcenter.com/special.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/lol.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 2);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest,
VisitCart_PerDomain_FromComponent) {
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), R"###(
{
"guitarcenter.com": {
"cart_url_regex" : "unique|laugh"
}
}
)###",
R"###(
{
"cart_page_url_regex": "(special|lol)"
}
)###",
"", "");
DCHECK(is_populated);
NavigateToURL("https://www.guitarcenter.com/unique.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/special.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/laugh.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 2);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, ExtractCart_ScriptFromResource) {
// This page has three products.
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForProductCount(kExpectedExampleWithProductsWithoutSaved);
#endif
WaitForUmaCount("Commerce.Carts.ExtractionExecutionTime", 1);
WaitForUmaCount("Commerce.Carts.ExtractionLongestTaskTime", 1);
WaitForUmaCount("Commerce.Carts.ExtractionTotalTasksTime", 1);
WaitForUmaCount("Commerce.Carts.ExtractionElapsedTime", 1);
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 1);
WaitForUmaBucketCount(
"Commerce.Heuristics.CartExtractionScriptSource",
int(CommerceHeuristicsDataMetricsHelper::HeuristicsSource::FROM_RESOURCE),
1);
WaitForUmaBucketCount("Commerce.Heuristics.ProductIDExtractionPatternSource",
int(CommerceHeuristicsDataMetricsHelper::
HeuristicsSource::FROM_FEATURE_PARAMETER),
1);
ExpectUKMCount(ExtractionEntry::kEntryName, "ExtractionExecutionTime", 1);
ExpectUKMCount(ExtractionEntry::kEntryName, "ExtractionLongestTaskTime", 1);
ExpectUKMCount(ExtractionEntry::kEntryName, "ExtractionTotalTasksTime", 1);
ExpectUKMCount(ExtractionEntry::kEntryName, "ExtractionElapsedTime", 1);
ExpectUKMCount(ExtractionEntry::kEntryName, "ExtractionTimedOut", 1);
SendXHR("/add-to-cart", "product: 123");
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 2);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, ExtractCart_ScriptFromComponent) {
// Initialize component with a dummy script that returns immediately.
std::string extraction_script = R"###(
async function extractAllItems(root) {
return {
"products":[
{
"imageUrl": "https://foo.com/bar/image",
"price": "$10",
"title": "Foo bar",
"url": "https://foo.com/bar",
}
]
};
}
extracted_results_promise = extractAllItems(document);
)###";
std::string product_id_json = "{\"foo.com\": \"test\"}";
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), "{}", "{}", std::move(product_id_json),
std::move(extraction_script));
DCHECK(is_populated);
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts("guitarcenter.com",
"https://www.guitarcenter.com/cart.html",
{"https://foo.com/bar/image"});
const ShoppingCarts expected_carts = {
{"guitarcenter.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
#endif
WaitForUmaBucketCount("Commerce.Heuristics.CartExtractionScriptSource",
int(CommerceHeuristicsDataMetricsHelper::
HeuristicsSource::FROM_COMPONENT),
1);
WaitForUmaBucketCount("Commerce.Heuristics.ProductIDExtractionPatternSource",
int(CommerceHeuristicsDataMetricsHelper::
HeuristicsSource::FROM_COMPONENT),
1);
}
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest,
ExtractCart_ProductIDFromComponent) {
std::string global_heuristics = R"###(
{
"rule_discount_partner_merchant_regex": "(guitarcenter.com)"
}
)###";
std::string product_id_json = R"###(
{
"product_element": {"www.guitarcenter.com": "<a href=\"#modal-(\\w+)"}
}
)###";
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), "{}", global_heuristics,
std::move(product_id_json), "");
DCHECK(is_populated);
// This page has two products.
NavigateToURL("https://www.guitarcenter.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"aaa.com", "https://www.guitarcenter.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_1", "bar_1"});
const ShoppingCarts expected_carts = {
{"guitarcenter.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
WaitForUmaBucketCount(
"Commerce.Heuristics.CartExtractionScriptSource",
int(CommerceHeuristicsDataMetricsHelper::HeuristicsSource::FROM_RESOURCE),
1);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, AddCartFromComponent) {
bool is_populated =
commerce_hint_service_->InitializeCommerceHeuristicsForTesting(
base::Version("0.0.0.1"), R"###(
{
"guitarcenter.com": {
"merchant_name" : "SPECIAL_NAME",
"cart_url" : "https://www.guitarcenter.com/special_cart"
}
}
)###",
"{}", "", "");
DCHECK(is_populated);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
// Browser-side commerce heuristics are still correct despite being
// used to populate renderer side commerce heuristics.
cart_db::ChromeCartContentProto expected_cart_protos = BuildProto(
"guitarcenter.com", "https://www.guitarcenter.com/special_cart");
expected_cart_protos.set_merchant("SPECIAL_NAME");
const ShoppingCarts expected_carts = {
{"guitarcenter.com", expected_cart_protos}};
WaitForCarts(expected_carts);
}
class CommerceHintNoRateControlTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"cart-extraction-gap-time", "0s"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// TODO(crbug.com/1241582): Add the rate control back for this test after
// figuring out why rate control makes this test flaky.
// Disabled due to failing tests. https://crbug.com/1254802
IN_PROC_BROWSER_TEST_F(CommerceHintNoRateControlTest, DISABLED_CartPriority) {
NavigateToURL("https://www.guitarcenter.com/");
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
WaitForCartCount(kExpectedExampleFallbackCart);
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForCarts(kExpectedExample);
NavigateToURL("https://www.guitarcenter.com/");
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
WaitForCarts(kExpectedExample);
}
#endif // !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, VisitCheckout) {
#if !BUILDFLAG(IS_ANDROID)
service_->AddCart(kMockExample, absl::nullopt, kMockExampleProto);
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
NavigateToURL("https://www.guitarcenter.com/");
NavigateToURL("https://www.guitarcenter.com/123/checkout/456");
// URL is checked against checkout twice.
WaitForUmaCount("Commerce.Carts.VisitCheckout", 2);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, PurchaseByURL) {
#if !BUILDFLAG(IS_ANDROID)
service_->AddCart(kMockAmazon, absl::nullopt, kMockAmazonProto);
WaitForCartCount(kExpectedAmazon);
#endif
NavigateToURL("http://amazon.com/");
NavigateToURL(
"http://amazon.com/gp/buy/spc/handlers/static-submit-decoupled.html");
WaitForUmaCount("Commerce.Carts.PurchaseByURL", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
}
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, PurchaseByForm) {
#if !BUILDFLAG(IS_ANDROID)
service_->AddCart(kMockExample, absl::nullopt, kMockExampleProto);
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
NavigateToURL("https://www.guitarcenter.com/purchase.html");
std::string script = "document.getElementById('submit').click()";
ASSERT_TRUE(ExecJs(web_contents(), script));
content::TestNavigationObserver load_observer(web_contents());
load_observer.WaitForNavigationFinished();
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
ExpectUKMCount(FormSubmittedEntry::kEntryName, "IsTransaction", 1);
}
// TODO(crbug.com/1180268): CrOS multi-profiles implementation is different from
// the rest and below tests don't work on CrOS yet. Re-enable them on CrOS after
// figuring out the reason for failure.
// Signing out on Lacros is not possible.
// TODO(crbug.com/1332878): Intentionally skip below two tests for Android for
// now.
#if !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID)
// TODO(crbug/1258803): Skip work on non-eligible profiles.
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, NonSignInUser) {
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
ASSERT_TRUE(identity_manager);
signin::ClearPrimaryAccount(identity_manager);
NavigateToURL("https://www.guitarcenter.com/cart");
WaitForCartCount(kEmptyExpected);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForCartCount(kEmptyExpected);
SendXHR("/add-to-cart", "product: 123");
WaitForCartCount(kEmptyExpected);
signin::SetPrimaryAccount(identity_manager, "[email protected]",
signin::ConsentLevel::kSync);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
WaitForCartCount(kExpectedExampleFallbackCart);
}
// TODO(crbug/1258803): Skip work on non-eligible profiles.
// Flaky on Linux Asan and Mac: https://crbug.com/1306908.
#if (BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER)) || BUILDFLAG(IS_MAC)
#define MAYBE_MultipleProfiles DISABLED_MultipleProfiles
#else
#define MAYBE_MultipleProfiles MultipleProfiles
#endif
IN_PROC_BROWSER_TEST_F(CommerceHintAgentTest, MAYBE_MultipleProfiles) {
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
auto* identity_manager = IdentityManagerFactory::GetForProfile(profile);
ProfileManager* profile_manager = g_browser_process->profile_manager();
ASSERT_TRUE(identity_manager);
ASSERT_EQ(profile_manager->GetNumberOfProfiles(), 1U);
signin::ClearPrimaryAccount(identity_manager);
NavigateToURL("https://www.guitarcenter.com/cart");
WaitForCartCount(kEmptyExpected);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForCartCount(kEmptyExpected);
SendXHR("/add-to-cart", "product: 123");
WaitForCartCount(kEmptyExpected);
// Create another profile.
base::FilePath profile_path2 =
profile_manager->GenerateNextProfileDirectoryPath();
profiles::testing::CreateProfileSync(profile_manager, profile_path2);
ASSERT_EQ(profile_manager->GetNumberOfProfiles(), 2U);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
WaitForCartCount(kExpectedExampleFallbackCart);
}
#endif // !BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_ANDROID)
class CommerceHintCacaoTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeatures(
{ntp_features::kNtpChromeCartModule,
optimization_guide::features::kOptimizationHints},
{});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintCacaoTest, Passed) {
auto* optimization_guide_decider =
#if !BUILDFLAG(IS_ANDROID)
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
#else
OptimizationGuideKeyedServiceFactory::GetForProfile(
chrome_test_utils::GetProfile(this));
#endif
// Need the non-default port here.
optimization_guide_decider->AddHintForTesting(
https_server_.GetURL("www.guitarcenter.com", "/"),
optimization_guide::proto::SHOPPING_PAGE_PREDICTOR, absl::nullopt);
optimization_guide_decider->AddHintForTesting(
GURL("https://www.guitarcenter.com/cart"),
optimization_guide::proto::SHOPPING_PAGE_PREDICTOR, absl::nullopt);
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
}
// If command line argument "optimization_guide_hints_override" is not given,
// nothing is specified in AddHintForTesting(), and the real hints are not
// downloaded, all the URLs are considered non-shopping.
IN_PROC_BROWSER_TEST_F(CommerceHintCacaoTest, Rejected) {
NavigateToURL("https://www.guitarcenter.com/cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
SendXHR("/add-to-cart", "product: 123");
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout() * 30);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 0);
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.VisitCart", 0);
}
class CommerceHintOptimizeRendererDisabledTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"optimize-renderer-signal", "false"}}},
{optimization_guide::features::kOptimizationHints, {{}}}},
{});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// If command line argument "optimization_guide_hints_override" is not given,
// nothing is specified in AddHintForTesting(), and the real hints are not
// downloaded, all the URLs are considered non-shopping.
IN_PROC_BROWSER_TEST_F(CommerceHintOptimizeRendererDisabledTest, Rejected) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout() * 30);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
// The cart won't be added on browser side because of Cacao rejection either
// way, but when optimize-renderer-signal is disabled, renderer will still
// observer and process commerce signals on this site.
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
}
#if !BUILDFLAG(IS_ANDROID)
class CommerceHintProductInfoTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{ntp_features::kNtpChromeCartModule,
{{ntp_features::kNtpChromeCartModuleAbandonedCartDiscountParam,
"true"},
{"partner-merchant-pattern",
"(guitarcenter.com|aaa.com|bbb.com|ccc.com|ddd.com)"},
{"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"},
{"product-id-pattern-mapping",
R"###(
{
"product_element":
{"www.aaa.com": "<a href=\"#modal-(\\w+)"},
"product_image_url":
{"www.bbb.com": "(\\w+)-\\d+-medium",
"www.ddd.com": ["(\\w+)-\\d+-medium", 0]
},
"product_url":
{"www.ccc.com": "products-(\\w+)",
"www.guitarcenter.com": "products-(\\w+)"}
}
)###"},
// Extend timeout to avoid flakiness.
{"cart-extraction-timeout", "1m"}}},
{commerce::kRetailCoupons,
{{"coupon-partner-merchant-pattern", "(eee.com)"},
{"coupon-product-id-pattern-mapping",
R"###(
{"product_url": {"www.eee.com": "products-(\\w+)"}}
)###"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest, AddToCartByForm_CaptureId) {
NavigateToURL("https://www.guitarcenter.com/product.html");
SendXHR("/cart/update", "product_id=id_foo&add_to_cart=true");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(kMockExample, kMockExampleLinkURL, {}, {"id_foo"});
const ShoppingCarts expected_carts = {{kMockExample, expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest, AddToCartByURL_CaptureId) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart?pr1id=id_foo", "");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(kMockExample, kMockExampleFallbackURL, {},
{"id_foo"});
const ShoppingCarts expected_carts = {{kMockExample, expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
ExtractCart_CaptureId_FromElement) {
// This page has two products.
NavigateToURL("https://www.aaa.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"aaa.com", "https://www.aaa.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_1", "bar_1"});
const ShoppingCarts expected_carts = {{"aaa.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
ExtractCart_CaptureId_FromImageURL) {
// This page has two products.
NavigateToURL("https://www.bbb.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"bbb.com", "https://www.bbb.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_2", "bar_2"});
const ShoppingCarts expected_carts = {{"bbb.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
ExtractCart_CaptureId_FromProductURL) {
// This page has two products.
NavigateToURL("https://www.ccc.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"ccc.com", "https://www.ccc.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_3", "bar_3"});
const ShoppingCarts expected_carts = {{"ccc.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
ExtractCart_CaptureId_CaptureGroupIndex) {
// This page has two products.
NavigateToURL("https://www.ddd.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"ddd.com", "https://www.ddd.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_2-0-medium", "bar_2-0-medium"});
const ShoppingCarts expected_carts = {{"ddd.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
ExtractCart_CaptureId_CouponPartnerMerchants) {
// This page has two products.
NavigateToURL("https://www.eee.com/shopping-cart.html");
const cart_db::ChromeCartContentProto expected_cart_protos =
BuildProtoWithProducts(
"eee.com", "https://www.eee.com/shopping-cart.html",
{"https://static.guitarcenter.com/product-image/foo_2-0-medium",
"https://static.guitarcenter.com/product-image/bar_2-0-medium"},
{"foo_3", "bar_3"});
const ShoppingCarts expected_carts = {{"eee.com", expected_cart_protos}};
WaitForProductCount(expected_carts);
}
IN_PROC_BROWSER_TEST_F(CommerceHintProductInfoTest,
RBDPartnerCartURLNotOverwrite) {
Profile* profile =
Profile::FromBrowserContext(web_contents()->GetBrowserContext());
profile->GetPrefs()->SetBoolean(prefs::kCartDiscountEnabled, true);
EXPECT_TRUE(service_->IsCartDiscountEnabled());
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/add-to-cart", "product: 123");
WaitForCartCount(kExpectedExampleFallbackCart);
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForCartCount(kExpectedExampleFallbackCart);
}
#endif // !BUILDFLAG(IS_ANDROID)
// Product extraction would always timeout and return empty results.
class CommerceHintTimeoutTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"cart-extraction-timeout", "0"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Flaky on Linux, ChromeOS and Windows: https://crbug.com/1257964.
// Falky on Mac: https://crbug.com/1312849.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_WIN) || \
BUILDFLAG(IS_MAC)
#define MAYBE_ExtractCart DISABLED_ExtractCart
#else
#define MAYBE_ExtractCart ExtractCart
#endif
IN_PROC_BROWSER_TEST_F(CommerceHintTimeoutTest, MAYBE_ExtractCart) {
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 1, 1);
}
class CommerceHintMaxCountTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"cart-extraction-max-count", "1"},
// Extend timeout to avoid flakiness.
{"cart-extraction-timeout", "1m"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Flaky on Linux: https://crbug.com/1257964.
// See definition of MAYBE_ExtractCart above.
IN_PROC_BROWSER_TEST_F(CommerceHintMaxCountTest, MAYBE_ExtractCart) {
NavigateToURL("https://www.guitarcenter.com/cart.html");
// Wait for trying to fetch extraction script from browser process.
base::PlatformThread::Sleep(TestTimeouts::tiny_timeout() * 30);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleWithProducts);
#endif
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 1);
// This would have triggered another extraction if not limited by max count
// per navigation.
SendXHR("/add-to-cart", "product: 123");
// Navigation resets count, so can do another extraction.
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 2);
}
// Override add-to-cart pattern.
class CommerceHintAddToCartPatternTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"add-to-cart-pattern", "(special|text)"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintAddToCartPatternTest, AddToCartByURL) {
NavigateToURL("https://www.guitarcenter.com/Special?product=1");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
NavigateToURL("https://www.guitarcenter.com/add-to-cart?product=1");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 1);
NavigateToURL("https://www.guitarcenter.com/Text?product=1");
WaitForUmaCount("Commerce.Carts.AddToCartByURL", 2);
}
IN_PROC_BROWSER_TEST_F(CommerceHintAddToCartPatternTest, AddToCartByForm) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_Special");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_Text");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 2);
}
// Override per-domain add-to-cart pattern.
class CommerceHintSkippAddToCartTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"skip-add-to-cart-mapping", R"({"guitarcenter.com": ".*"})"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintSkippAddToCartTest, AddToCartByForm) {
NavigateToURL("https://www.guitarcenter.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 0);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
// Test AddToCart that is supposed to be skipped based on resources is now
// overwritten.
const cart_db::ChromeCartContentProto qvc_cart =
BuildProto("qvc.com", "https://www.qvc.com/checkout/cart.html");
const ShoppingCarts result = {{"qvc.com", qvc_cart}};
#endif
NavigateToURL("https://www.qvc.com/");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(result);
#endif
}
#if BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER)
// Override per-domain and generic cart pattern.
class CommerceHintCartPatternTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"cart-pattern", "chicken|egg"},
{"cart-pattern-mapping",
R"({"guitarcenter.com": "(special|text)lol"})"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// TODO(https://crbug.com/1362442): Deflake this test.
IN_PROC_BROWSER_TEST_F(CommerceHintCartPatternTest, DISABLED_VisitCart) {
// The test is flaky with same-site back/forward cache, presumably because it
// doesn't expect a RenderView change on same-site navigations.
// TODO(https://crbug.com/1302902): Investigate and fix this.
content::DisableBackForwardCacheForTesting(
web_contents(),
content::BackForwardCache::TEST_ASSUMES_NO_RENDER_FRAME_CHANGE);
NavigateToURL("https://www.guitarcenter.com/SpecialLoL");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/cart.html");
NavigateToURL("https://www.guitarcenter.com/chicken");
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
NavigateToURL("https://www.guitarcenter.com/TextLoL");
WaitForUmaCount("Commerce.Carts.VisitCart", 2);
// Unspecified domains fall back to generic pattern.
NavigateToURL("https://www.example.com/SpecialLoL");
NavigateToURL("https://www.example.com/cart.html");
NavigateToURL("https://www.example.com/TextLoL");
WaitForUmaCount("Commerce.Carts.VisitCart", 2);
NavigateToURL("https://www.example.com/Chicken");
WaitForUmaCount("Commerce.Carts.VisitCart", 3);
NavigateToURL("https://www.example.com/Egg");
WaitForUmaCount("Commerce.Carts.VisitCart", 4);
}
#endif // BUILDFLAG(IS_LINUX) && defined(ADDRESS_SANITIZER)
// Override per-domain and generic checkout pattern.
class CommerceHintCheckoutPatternTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"checkout-pattern", "meow|purr"},
{"checkout-pattern-mapping",
R"({"guitarcenter.com": "special|text"})"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintCheckoutPatternTest, VisitCheckout) {
NavigateToURL("https://www.guitarcenter.com/Special");
// URLs are checked against checkout twice.
WaitForUmaCount("Commerce.Carts.VisitCheckout", 2);
NavigateToURL("https://www.guitarcenter.com/checkout/");
NavigateToURL("https://www.guitarcenter.com/meow/");
NavigateToURL("https://www.guitarcenter.com/purr/");
WaitForUmaCount("Commerce.Carts.VisitCheckout", 2);
NavigateToURL("https://www.guitarcenter.com/Text");
WaitForUmaCount("Commerce.Carts.VisitCheckout", 4);
// Unspecified domains fall back to generic pattern.
NavigateToURL("https://www.example.com/Special");
NavigateToURL("https://www.example.com/checkout/");
NavigateToURL("https://www.example.com/Text");
WaitForUmaCount("Commerce.Carts.VisitCheckout", 4);
NavigateToURL("https://www.example.com/Meow");
WaitForUmaCount("Commerce.Carts.VisitCheckout", 6);
NavigateToURL("https://www.example.com/Purr");
WaitForUmaCount("Commerce.Carts.VisitCheckout", 8);
}
// Override per-domain and generic purchase button pattern.
class CommerceHintPurchaseButtonPatternTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"purchase-button-pattern", "meow|purr"},
{"purchase-button-pattern-mapping",
R"({"guitarcenter.com": "woof|bark"})"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintPurchaseButtonPatternTest, PurchaseByForm) {
std::string url;
auto test_button = [&](const char* button_text) {
NavigateToURL(url);
const std::string& script = base::StringPrintf(
R"(
const btn = document.getElementById('submit');
btn.innerText = "%s";
btn.click();
)",
button_text);
ASSERT_TRUE(ExecJs(web_contents(), script));
content::TestNavigationObserver load_observer(web_contents());
load_observer.WaitForNavigationFinished();
};
url = "https://www.guitarcenter.com/purchase.html";
test_button("Woof");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 1);
test_button("Meow");
test_button("Pay now");
test_button("Purr");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 1);
test_button("Bark");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 2);
// Unspecified domains fall back to generic pattern.
url = "https://www.example.com/purchase.html";
test_button("Meow");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 3);
test_button("Woof");
test_button("Pay now");
test_button("Bark");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 3);
test_button("Purr");
WaitForUmaCount("Commerce.Carts.PurchaseByPOST", 4);
}
class CommerceHintPurchaseURLPatternTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"purchase-url-pattern-mapping",
R"({"guitarcenter.com": "special|text"})"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintPurchaseURLPatternTest, PurchaseByURL) {
NavigateToURL("https://www.guitarcenter.com/Special");
WaitForUmaCount("Commerce.Carts.PurchaseByURL", 1);
NavigateToURL("https://www.guitarcenter.com/Text");
WaitForUmaCount("Commerce.Carts.PurchaseByURL", 2);
}
class CommerceHintOptimizeRendererTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"cart-extraction-gap-time", "0s"}}},
{optimization_guide::features::kOptimizationHints, {{}}}},
{});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Times out on multiple platforms. https://crbug.com/1258553
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || \
BUILDFLAG(IS_ANDROID)
#define MAYBE_CartExtractionSkipped DISABLED_CartExtractionSkipped
#else
#define MAYBE_CartExtractionSkipped CartExtractionSkipped
#endif
IN_PROC_BROWSER_TEST_F(CommerceHintOptimizeRendererTest,
MAYBE_CartExtractionSkipped) {
// Without adding testing hints, all the URLs are considered non-shopping.
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
SendXHR("/add-to-cart", "product: 123");
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 0);
auto* optimization_guide_decider =
#if !BUILDFLAG(IS_ANDROID)
OptimizationGuideKeyedServiceFactory::GetForProfile(browser()->profile());
#else
OptimizationGuideKeyedServiceFactory::GetForProfile(
chrome_test_utils::GetProfile(this));
#endif
// Need the non-default port here.
optimization_guide_decider->AddHintForTesting(
https_server_.GetURL("www.guitarcenter.com", "/cart.html"),
optimization_guide::proto::SHOPPING_PAGE_PREDICTOR, absl::nullopt);
NavigateToURL("https://www.guitarcenter.com/cart.html");
#if !BUILDFLAG(IS_ANDROID)
WaitForCarts(kExpectedExample);
#endif
SendXHR("/add-to-cart", "product: 123");
WaitForUmaBucketCount("Commerce.Carts.ExtractionTimedOut", 0, 2);
}
#if !BUILDFLAG(IS_CHROMEOS)
// TODO(crbug/1310497): This test is flaky on ChromeOS.
class CommerceHintAgentFencedFrameTest : public CommerceHintAgentTest {
public:
CommerceHintAgentFencedFrameTest() {
scoped_feature_list_.InitWithFeatures(
{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule
#else
commerce::kCommerceHintAndroid
#endif
},
{optimization_guide::features::kOptimizationHints});
}
void SetUpInProcessBrowserTestFixture() override {}
content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
return fenced_frame_helper_;
}
private:
content::test::FencedFrameTestHelper fenced_frame_helper_;
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintAgentFencedFrameTest,
VisitCartInFencedFrame) {
// For add-to-cart by URL, normally a URL in that domain has already been
// committed.
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
// Create a fenced frame.
GURL fenced_frame_url =
https_server_.GetURL("www.guitarcenter.com", "/cart.html");
content::RenderFrameHost* fenced_frame_host =
fenced_frame_test_helper().CreateFencedFrame(
web_contents()->GetPrimaryMainFrame(), fenced_frame_url);
EXPECT_NE(nullptr, fenced_frame_host);
// Do not affect counts.
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
}
class CommerceHintAgentPortalBrowserTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{blink::features::kPortals, {}},
{blink::features::kPortalsCrossOrigin, {}},
{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{{"product-skip-pattern", "(^|\\W)(?i)(skipped)(\\W|$)"},
// Extend timeout to avoid flakiness.
{"cart-extraction-timeout", "1m"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintAgentPortalBrowserTest, VisitCartInPortal) {
// For add-to-cart by URL, normally a URL in that domain has already been
// committed.
NavigateToURL("https://www.guitarcenter.com/cart-in-portal.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
EXPECT_EQ(true, content::EvalJs(web_contents(), "loadPromise"));
EXPECT_EQ(true, content::EvalJs(web_contents(), "activate()"));
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
}
#endif // !BUILDFLAG(IS_CHROMEOS)
#if !BUILDFLAG(IS_ANDROID)
class CommerceHintFeatureDefaultWithoutGeoTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{}, {optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintFeatureDefaultWithoutGeoTest,
DisableWithoutGeo) {
ASSERT_FALSE(IsCartModuleEnabled());
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 0);
WaitForCartCount(kEmptyExpected);
}
class CommerceHintFeatureDefaultWithGeoTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{}, {optimization_guide::features::kOptimizationHints});
}
void SetUpCommandLine(base::CommandLine* command_line) override {
CommerceHintAgentTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
variations::switches::kVariationsOverrideCountry, "us");
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintFeatureDefaultWithGeoTest, EnableWithGeo) {
auto locale = std::make_unique<ScopedBrowserLocale>("en-US");
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
ASSERT_TRUE(IsCartModuleEnabled());
NavigateToURL("https://www.guitarcenter.com/cart.html");
WaitForUmaCount("Commerce.Carts.VisitCart", 1);
#else
ASSERT_FALSE(IsCartModuleEnabled());
WaitForUmaCount("Commerce.Carts.VisitCart", 0);
WaitForCartCount(kEmptyExpected);
#endif
}
#endif
class CommerceHintDOMBasedHeuristicsTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{}},
{commerce::kChromeCartDomBasedHeuristics,
{{"add-to-cart-button-active-time", "2s"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintDOMBasedHeuristicsTest,
DetectionRequiresAddToCartActive) {
NavigateToURL("https://www.guitarcenter.com/product-page.html");
// AddToCart requests without active AddToCart button focus.
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 0);
// Focus on an AddToCart button and then send AddToCart requests.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonOne\")"));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 1);
}
IN_PROC_BROWSER_TEST_F(CommerceHintDOMBasedHeuristicsTest,
DetectionInactiveForWrongButton) {
NavigateToURL("https://www.guitarcenter.com/product-page.html");
// Focus on a non-AddToCart button and then send AddToCart requests.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonTwo\")"));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 0);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 1);
// Focus on an AddToCart button and then send AddToCart requests.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonOne\")"));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 2);
}
IN_PROC_BROWSER_TEST_F(CommerceHintDOMBasedHeuristicsTest,
AddToCartActiveExpires) {
NavigateToURL("https://www.guitarcenter.com/product-page.html");
// Focus on an AddToCart button, but wait until it's no longer active and then
// send AddToCart requests.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonOne\")"));
base::PlatformThread::Sleep(base::Seconds(2));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kEmptyExpected);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 0);
// Focus on an AddToCart button and then send AddToCart requests.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonTwo\")"));
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonOne\")"));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 3);
}
class CommerceHintDOMBasedHeuristicsSkipTest : public CommerceHintAgentTest {
public:
void SetUpInProcessBrowserTestFixture() override {
scoped_feature_list_.InitWithFeaturesAndParameters(
{{
#if !BUILDFLAG(IS_ANDROID)
ntp_features::kNtpChromeCartModule,
#else
commerce::kCommerceHintAndroid,
#endif
{}},
{commerce::kChromeCartDomBasedHeuristics,
{{"skip-heuristics-domain-pattern", "guitarcenter"},
{"add-to-cart-button-active-time", "0s"}}}},
{optimization_guide::features::kOptimizationHints});
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(CommerceHintDOMBasedHeuristicsSkipTest,
SkipDOMBasedHeuristics) {
// Send AddToCart requests on a skipped domain without active AddToCart
// button.
NavigateToURL("https://www.guitarcenter.com/product-page.html");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 1);
// Send AddToCart requests on a skipped domain after focusing on a invalid
// AddToCart button.
EXPECT_EQ(nullptr,
content::EvalJs(web_contents(), "focusElement(\"buttonTwo\")"));
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 2);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 0);
// Send AddToCart requests on a non-skipped domain without active AddToCart
// button.
NavigateToURL("https://www.example.com/product-page.html");
SendXHR("/wp-admin/admin-ajax.php", "action: woocommerce_add_to_cart");
#if !BUILDFLAG(IS_ANDROID)
WaitForCartCount(kExpectedExampleFallbackCart);
#endif
WaitForUmaCount("Commerce.Carts.AddToCartByPOST", 2);
WaitForUmaCount("Commerce.Carts.AddToCartButtonDetection", 0);
}
} // namespace
| {'content_hash': 'e1a69a0ad41521361f42bc7bbd80553f', 'timestamp': '', 'source': 'github', 'line_count': 1805, 'max_line_length': 80, 'avg_line_length': 36.639335180055404, 'alnum_prop': 0.6931230531950283, 'repo_name': 'chromium/chromium', 'id': '29d58cc2bfeced749b5d65c895627b6d2e13ec09', 'size': '68794', 'binary': False, 'copies': '5', 'ref': 'refs/heads/main', 'path': 'chrome/renderer/cart/commerce_hint_agent_browsertest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.CodeAnalysis;
using Syncfusion.Windows.Forms.Edit;
using Syncfusion.Windows.Forms.Edit.Enums;
namespace JDunkerley.AlteryxAddIns.Roslyn
{
public partial class RoslynEditor : UserControl
{
private readonly EditControl _textBox;
private string _code;
public RoslynEditor()
{
this.InitializeComponent();
// Set up text box
this._textBox = new EditControl { Dock = DockStyle.Fill };
this._textBox.ApplyConfiguration(KnownLanguages.CSharp);
this._textBox.TextChanged += (sender, args) =>
{
this._code = this._textBox.Text;
this.CodeChanged(this, args);
};
this.Controls.Add(this._textBox);
}
public string Code
{
get => this._code;
set
{
this._code = value;
this._textBox.Text = value;
}
}
/// <summary>
/// Event When Code Changed
/// </summary>
public event EventHandler CodeChanged = delegate { };
/// <summary>
/// Sets the Error Messages
/// </summary>
public void SetMessages(IEnumerable<Diagnostic> value, int startLine, int startCharacter)
{
this.dgvErrors.DataSource = value.Select(
d =>
{
var start = d.Location.SourceTree.GetLineSpan(d.Location.SourceSpan);
return new DiagnosticMessate
{
Severity = d.Severity,
Message = d.GetMessage(),
StartLine = start.StartLinePosition.Line - startLine,
StartCharacter =
start.StartLinePosition.Character
- (start.StartLinePosition.Line == startLine
? startCharacter
: 0)
};
})
.ToArray();
}
private class DiagnosticMessate
{
// ReSharper disable UnusedAutoPropertyAccessor.Local
public DiagnosticSeverity Severity { get; set; }
public string Message { get; set; }
public int StartLine { get; set; }
public int StartCharacter { get; set; }
// ReSharper restore UnusedAutoPropertyAccessor.Local
}
}
} | {'content_hash': '9268e05dc46cb7d60f928fa56d5f0fa9', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 97, 'avg_line_length': 32.839080459770116, 'alnum_prop': 0.4672733636681834, 'repo_name': 'jdunkerley/AlteryxAddIns', 'id': 'adcfe0d241cff48faf624584badb56a35a1263e1', 'size': '2859', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AlteryxAddIns.Roslyn/RoslynEditor.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '6885'}, {'name': 'C', 'bytes': '739'}, {'name': 'C#', 'bytes': '216264'}, {'name': 'C++', 'bytes': '11216'}, {'name': 'CSS', 'bytes': '8549'}, {'name': 'HTML', 'bytes': '8604'}, {'name': 'JavaScript', 'bytes': '374008'}, {'name': 'PowerShell', 'bytes': '24355'}, {'name': 'Python', 'bytes': '12993'}, {'name': 'TypeScript', 'bytes': '3496'}]} |
import 'core-js';
import 'zone.js';
import 'hammerjs';
import $ from 'jquery';
import NfRegistryModule from 'nf-registry.module';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode, TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from '@angular/core';
// import all of the static files we need resolved via the webpack file-loader
import 'font-awesome/fonts/fontawesome-webfont.woff2';
import 'font-awesome/fonts/fontawesome-webfont.woff';
import 'font-awesome/fonts/fontawesome-webfont.ttf';
import '@covalent/core/common/styles/font/MaterialIcons-Regular.woff2';
import '@covalent/core/common/styles/font/MaterialIcons-Regular.woff';
import '@covalent/core/common/styles/font/MaterialIcons-Regular.ttf';
import 'images/registry-logo-web-app.svg';
import 'images/registry-background-logo.svg';
// Comment out this line when developing to assert for unidirectional data flow
enableProdMode();
// Get the locale id from the global
const locale = navigator.language.toLowerCase();
const providers = [];
// No locale or U.S. English: no translation providers so go ahead and bootstrap the app
if (!locale || locale === 'en-us') {
bootstrapModule();
} else { //load the translation providers and bootstrap the module
var translationFile = 'locale/messages.' + locale + '.xlf';
$.ajax({
url: translationFile,
dataType: 'text'
}).done(function (translations) {
// add providers if translation file for locale is loaded
if (translations) {
providers.push({provide: TRANSLATIONS, useValue: translations});
providers.push({provide: TRANSLATIONS_FORMAT, useValue: 'xlf'});
providers.push({provide: LOCALE_ID, useValue: locale});
}
bootstrapModule();
}).fail(function () {
bootstrapModule();
});
}
function bootstrapModule() {
platformBrowserDynamic().bootstrapModule(NfRegistryModule, {providers: providers});
}
| {'content_hash': 'f4c26c4dcab3c19cecf7a3ad90b8cb44', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 93, 'avg_line_length': 36.666666666666664, 'alnum_prop': 0.7161616161616161, 'repo_name': 'bbende/nifi-registry', 'id': '4ad63a80856087006b87afc0382db9d06de22498', 'size': '2781', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'nifi-registry-core/nifi-registry-web-ui/src/main/webapp/nf-registry-bootstrap.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '7365'}, {'name': 'CSS', 'bytes': '55670'}, {'name': 'Dockerfile', 'bytes': '2599'}, {'name': 'Groovy', 'bytes': '115972'}, {'name': 'HTML', 'bytes': '142672'}, {'name': 'Java', 'bytes': '3183707'}, {'name': 'JavaScript', 'bytes': '720609'}, {'name': 'PLpgSQL', 'bytes': '1211'}, {'name': 'Shell', 'bytes': '35772'}, {'name': 'TSQL', 'bytes': '43657'}]} |
#include <string.h>
#include <CoreFoundation/CFBase.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSZone.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSException.h>
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSInvocation.h>
#import <Foundation/NSString.h>
#import <Foundation/NSMethodSignature.h>
#import <objc/message.h>
#import <objc/objc-internal.h>
#import "NSInternal.h"
//TODO implement NSMethodSignature / NSInvocation stuff
//@interface NSInvocation (private)
//+(NSInvocation*)invocationWithMethodSignature:(NSMethodSignature*)signature arguments:(void*)arguments;
//@end
typedef struct {
volatile int32_t references;
} __NSObjectHead;
static inline __NSObjectHead* __GetHeadForObject(id object) {
return object ? ((__NSObjectHead*)object - 1) : NULL;
}
static inline id __GetObjectForHead(__NSObjectHead* head) {
return head ? (id)(head + 1) : NULL;
}
static void RaisePerformSelectorException() {
[NSException raise:NSInvalidArgumentException
format:@"peformSelector called with nil selector!"];
}
/*
* NSObject
*/
@implementation NSObject
+(NSInteger)version {
return class_getVersion(self);
}
+(void)setVersion:(NSInteger)version {
class_setVersion(self, version);
}
+(void)load {
}
+(void)initialize {
}
+(Class)superclass {
return class_getSuperclass(self);
}
+(Class)class {
return self;
}
+(BOOL)isSubclassOfClass:(Class)cls {
Class i = [self class];
while (i != Nil) {
i = class_getSuperclass(i);
if (i == cls) {
return YES;
}
}
return NO;
}
+(BOOL)instancesRespondToSelector:(SEL)selector {
return class_respondsToSelector(self, selector);
}
+(BOOL)conformsToProtocol:(Protocol*)protocol {
Class i = [self class];
while (i != Nil) {
if (class_conformsToProtocol(i, protocol)) {
return YES;
}
i = class_getSuperclass(i);
}
return NO;
}
+(IMP)methodForSelector:(SEL)selector {
return class_getMethodImplementation(object_getClass(self), selector);
}
+(IMP)instanceMethodForSelector:(SEL)selector {
return class_getMethodImplementation(self, selector);
}
+(NSMethodSignature*)instanceMethodSignatureForSelector:(SEL)selector {
Method method = class_getInstanceMethod(self, selector);
const char* types = method_getTypeEncoding(method);
return types ? [NSMethodSignature signatureWithObjCTypes:types] : (NSMethodSignature*)nil;
}
+(BOOL)resolveClassMethod:(SEL)selector {
//do nothing
return NO;
}
+(BOOL)resolveInstanceMethod:(SEL)selector {
//do nothing
return NO;
}
+copyWithZone:(NSZone*)zone {
return self;
}
+mutableCopyWithZone:(NSZone*)zone {
NS_ABSTRACT_METHOD_BODY
}
+(NSString*)description {
return NSStringFromClass(self);
}
+alloc {
return [self allocWithZone:NULL];
}
+allocWithZone:(NSZone*)zone {
return NSAllocateObject([self class], 0, zone);
}
-(void)dealloc {
NSDeallocateObject(self);
}
-(void)finalize {
//do nothing
}
-init {
return self;
}
+new {
return [[self allocWithZone:NULL] init];
}
+(void)dealloc {
}
-copy {
return [(id<NSCopying>)self copyWithZone:NULL];
}
-mutableCopy {
return [(id<NSMutableCopying>)self mutableCopyWithZone:NULL];
}
-(Class)classForCoder {
return isa;
}
-(Class)classForArchiver {
return [self classForCoder];
}
-replacementObjectForCoder:(NSCoder*)coder {
return self;
}
-awakeAfterUsingCoder:(NSCoder*)coder {
return self;
}
-(IMP)methodForSelector:(SEL)selector {
return class_getMethodImplementation(isa, selector);
}
-(void)doesNotRecognizeSelector:(SEL)selector {
[NSException raise:NSInvalidArgumentException
format:@"%c[%@ %@]: selector not recognized",
class_isMetaClass(isa) ? '+' : '-',
NSStringFromClass(isa),
NSStringFromSelector(selector)];
}
-(NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
Method method = class_getInstanceMethod(isa, selector);
const char* types = method_getTypeEncoding(method);
return types ? [NSMethodSignature signatureWithObjCTypes:types] : (NSMethodSignature*)nil;
}
-(void)forwardInvocation:(NSInvocation*)invocation {
[self doesNotRecognizeSelector:[invocation selector]];
}
-(id)forward:(SEL)selector:(marg_list)margs {
NSLog(@"%s: ignoring forward request for '%s'.", object_getClassName(self), sel_getName(selector));
return nil;
}
-(id)forwardSelector:(SEL)selector arguments:(void*)arguments {
return nil;
// NSMethodSignature* signature = [self methodSignatureForSelector:selector];
// if (signature == nil) {
// [self doesNotRecognizeSelector:selector];
// return nil;
// } else {
// NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature arguments:arguments];
// id result;
//
// [self forwardInvocation:invocation];
// [invocation getReturnValue:&result];
//
// return result;
// }
}
-(NSUInteger)hash {
return ((NSUInteger)self) * 2654435761u;
}
-(BOOL)isEqual:object {
return (self == object) ? YES : NO;
}
-self {
return self;
}
-(Class)class {
return isa;
}
-(Class)superclass {
return class_getSuperclass(isa);
}
-(NSZone*)zone {
return NSZoneFromPointer(self);
}
-performSelector:(SEL)selector {
if (selector) {
return objc_msgSend(self, selector);
} else {
RaisePerformSelectorException();
}
}
-performSelector:(SEL)selector withObject:object {
if (selector) {
return objc_msgSend(self, selector, object);
} else {
RaisePerformSelectorException();
}
}
-performSelector:(SEL)selector withObject:object1 withObject:object2 {
if (selector) {
return objc_msgSend(self, selector, object1, object2);
} else {
RaisePerformSelectorException();
}
}
-(BOOL)isProxy {
return NO;
}
-(BOOL)isKindOfClass:(Class)cls {
Class i=[self class];
while (i != Nil) {
if (i == cls) {
return YES;
}
i = class_getSuperclass(i);
}
return NO;
}
-(BOOL)isMemberOfClass:(Class)class {
return (isa == class);
}
-(BOOL)conformsToProtocol:(Protocol*)protocol {
return [isa conformsToProtocol:protocol];
}
-(BOOL)respondsToSelector:(SEL)selector {
return class_respondsToSelector(isa, selector);
}
-autorelease {
[NSAutoreleasePool addObject:self];
return self;
}
+autorelease {
return self;
}
-(oneway void)release {
if (NSDecrementExtraRefCountWasZero(self)) {
[self dealloc];
}
}
+(oneway void)release {
}
-retain {
NSIncrementExtraRefCount(self);
return self;
}
+retain {
return self;
}
-(NSUInteger)retainCount {
return NSExtraRefCount(self);
}
+(NSString*)className {
return NSStringFromClass(self);
}
-(NSString*)className {
return NSStringFromClass(isa);
}
-(NSString*)description {
return [NSString stringWithFormat:@"<%@ 0x%08x>", [self class], self];
}
-(CFTypeID)_cfTypeID {
return CFTypeGetTypeID();
}
-(NSString*)_cfCopyDescription {
NSString* description = [self description];
return [description retain];
}
@end
/*
* NSObject functions
*/
id NSAllocateObject(Class class, NSUInteger extraBytes, NSZone* zone) {
NSUInteger size = class_getInstanceSize(class) + extraBytes + sizeof(__NSObjectHead);
__NSObjectHead* head = (__NSObjectHead*)NSZoneMalloc(zone, size);
if (!head) {
return Nil;
}
memset(head, 0, size);
id nsobject = objc_constructInstance(class, __GetObjectForHead(head));
if (!nsobject) {
//Exception occured during initialization of the object.
NSZoneFree(zone, head);
return Nil;
}
head->references = 0;
return nsobject;
}
void NSDeallocateObject(id object) {
__NSObjectHead* head = __GetHeadForObject(object);
if (head) {
//TODO implement zombie support
// Can't use object_dispose() because 'head' must be
// passed to free(), not 'object'. Note that we use
// free() instead of malloc_zone_free() - it is what
// object_dispose() does.
objc_destructInstance(object);
free(head);
}
}
id NSCopyObject(id object, NSUInteger extraBytes, NSZone* zone) {
if (!zone) {
zone = NSDefaultMallocZone();
}
return object_copyFromZone(object, extraBytes, zone);
}
BOOL NSShouldRetainWithZone(id object, NSZone* zone) {
if (!zone) {
zone = NSDefaultMallocZone();
}
return zone == NSZoneFromPointer(object);
}
void NSIncrementExtraRefCount(id object) {
__NSObjectHead* head = __GetHeadForObject(object);
if (head) {
OSAtomicIncrement32(&head->references);
}
}
BOOL NSDecrementExtraRefCountWasZero(id object) {
__NSObjectHead* head = __GetHeadForObject(object);
return head && OSAtomicDecrement32(&head->references) < 0;
}
NSUInteger NSExtraRefCount(id object) {
__NSObjectHead* head = __GetHeadForObject(object);
return head ? head->references : 0;
}
| {'content_hash': 'cdda7d365b3343ae2b540ecfc759794d', 'timestamp': '', 'source': 'github', 'line_count': 419, 'max_line_length': 112, 'avg_line_length': 21.718377088305488, 'alnum_prop': 0.666923076923077, 'repo_name': 'DmitrySkiba/itoa-foundation', 'id': 'f7d4c0a18fe9160538b3eb8df594caa3659c072b', 'size': '10276', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Foundation/NSObject.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '73135'}, {'name': 'Objective-C', 'bytes': '1655140'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="Bangkok Pool League" content="">
<title>Pickle - {{title}}</title>
<!-- Bootstrap core CSS -->
<link href="/assets/css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
{% if useDatePicker == 1 %}
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/bootstrap-datepicker.min.js"></script>
<link id="bsdp-css" href="/assets/css/bootstrap-datepicker3.min.css" rel="stylesheet">
{% endif %}
</head>
<body>
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">BKK Pool League</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
{% if user %}
{% if user.isAdmin() %}
<li><a href="/admin/league/list">League days</a></li>
<li><a href="/admin/score/list">Scores</a></li>
<li><a href="/admin/team/list">Teams</a></li>
<li><a href="/admin/user/list">Users</a></li>
{% endif %}
{% if user.isCaptain() %}
<li><a href="/yourteam">Your team</a></li>
<li><a href="/enterscore">Enter Score</a></li>
{% endif %}
<li><a href="/ranking">Ranking</a></li>
<li><a href="/profile">Account</a></li>
<li><a href="/logout">Logout</a></li>
{% else %}
<li><a href="/ranking">Ranking</a></li>
<li><a href="/leaguedays">League Days</a></li>
<li><a href="/login">Login</a></li>
{% endif %}
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</nav>
<section>
<div class="container">
<div class="row">
{% include "partials/flash.html" with { "type": "info" } %}
{% include "partials/flash.html" with { "type": "success" } %}
{% include "partials/flash.html" with { "type": "warning" } %}
{% include "partials/flash.html" with { "type": "error", class: "danger" } %}
{% block content %}{% endblock %}
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<p>© Copyright 2015 by <a href="https://bkkpool.com">BKK Pool League</a>.</p>
</div>
</div>
</footer>
</div> <!-- /container -->
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/bootstrap.min.js"></script>
<script src="/assets/js/ie10-viewport-bug-workaround.js"></script>
<script>{% block morejs%}{% endblock %}</script>
</body>
</html>
| {'content_hash': '492cc5ce7de69c73229fc3404e1791ab', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 156, 'avg_line_length': 43.822916666666664, 'alnum_prop': 0.4844307107202282, 'repo_name': 'pierrejoye/poolleague', 'id': 'ee334ba95c253e159a13d878a84ae4c3c3d491af', 'size': '4208', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'templates/index.html', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '2078'}, {'name': 'HTML', 'bytes': '41645'}, {'name': 'JavaScript', 'bytes': '5448'}, {'name': 'PHP', 'bytes': '79450'}]} |
require 'bookle/google_books_api'
# Enables Ruby code interact with the Google Books API.
class Bookle
# Returns an instance of the class that interacts with the Google Books API.
#
# @return [Google::Books::API] -- An instance of the class that interacts with the Google Books API.
def self.api(google_books_api_key)
Google::Books::API.new(google_books_api_key)
end
end
| {'content_hash': '0169e4bb0871a95b891129fcdf127a98', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 102, 'avg_line_length': 30.384615384615383, 'alnum_prop': 0.7189873417721518, 'repo_name': 'pepehipolito/bookle', 'id': '1bdfe400aad4a679da6a6bf62ff5008b9a8bba6f', 'size': '395', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/bookle.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '13966'}]} |
module Makara
module Errors
class BlacklistConnection < MakaraError
attr_reader :original_error
def initialize(connection, error)
@original_error = error
super "[Makara/#{connection._makara_name}] #{error.message}"
end
end
end
end
| {'content_hash': 'ec37937ba04a9f7cfc6ebad54dc1c9b5', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 68, 'avg_line_length': 23.166666666666668, 'alnum_prop': 0.658273381294964, 'repo_name': 'instacart/makara', 'id': '2756607d2570475e15370884a2da0e686b889947', 'size': '278', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/makara/errors/blacklist_connection.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '135061'}]} |
<?php
namespace Mmlinks\MyanmarLocationApi\Model;
class Quarter extends AbstractBaseModel
{
public $id;
public $name;
public function __construct($data)
{
$this->id = $data->_id;
$this->name = $data->name;
}
}
| {'content_hash': 'd98446786083d2382cc869648d1b527e', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 43, 'avg_line_length': 15.625, 'alnum_prop': 0.604, 'repo_name': 'botrelli/location-php-api', 'id': 'b91a752f7eb1b99503b6256bfabf1609b4ad73ac', 'size': '552', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Model/Quarter.php', 'mode': '33188', 'license': 'mit', 'language': []} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '058f529730f6daf851ecf549efccbe72', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '7bc6bc5048b1d714a44f22dfceceafd350fb0cc8', 'size': '167', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Grewia/Grewia rothii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using NMFExamples.Pcm.Core;
using NMFExamples.Pcm.Core.Entity;
using NMFExamples.Pcm.Parameter;
using NMFExamples.Pcm.Protocol;
using NMFExamples.Pcm.Reliability;
using NMFExamples.Pcm.Resourcetype;
using NMFExamples.Pcm.Seff;
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using global::System.Collections;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace NMFExamples.Pcm.Repository
{
[ModelRepresentationClassAttribute("http://sdq.ipd.uka.de/PalladioComponentModel/5.0#//repository/ComponentType")]
public enum ComponentType
{
BUSINESS_COMPONENT = 0,
INFRASTRUCTURE_COMPONENT = 1,
}
}
| {'content_hash': 'a8f536f144f87c3a4428cea07de5cd0f', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 118, 'avg_line_length': 26.333333333333332, 'alnum_prop': 0.7811934900542495, 'repo_name': 'NMFCode/NMF', 'id': 'd204c37f6a1df5b399339e49bd3cb54fcbf139ae', 'size': '1541', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'IntegrationTests/ComponentBasedSoftwareArchitectures/Pcm/Repository/ComponentType.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '16018474'}, {'name': 'Smalltalk', 'bytes': '57321'}]} |
package org.testng.internal.thread;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.testng.TestNGException;
/**
* An <code>IPooledExecutor</code> implementation based on JDK1.5 native support.
*
* @author <a href="mailto:[email protected]>the_mindstorm</a>
*/
public class PooledExecutorAdapter extends ThreadPoolExecutor implements IPooledExecutor {
public PooledExecutorAdapter(int noThreads) {
super(noThreads,
noThreads,
0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
}
public void execute(Runnable command) {
try {
super.execute(command);
}
catch(RejectedExecutionException ree) {
throw new TestNGException("Task was not accepted for execution", ree);
}
}
public void awaitTermination(long timeout) throws InterruptedException {
super.awaitTermination(timeout, TimeUnit.MILLISECONDS);
}
}
| {'content_hash': '5bd4b2390e016cfe9b4492d554b37d34', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 90, 'avg_line_length': 30.444444444444443, 'alnum_prop': 0.7226277372262774, 'repo_name': 'ludovicc/testng-debian', 'id': 'd4533de513291ca28b0457600ff33725e8284e60', 'size': '1096', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/jdk15/org/testng/internal/thread/PooledExecutorAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2128721'}, {'name': 'JavaScript', 'bytes': '95052'}, {'name': 'Shell', 'bytes': '952'}]} |
.class public final Landroid/provider/ContactsContract$DataUsageFeedback;
.super Ljava/lang/Object;
.source "ContactsContract.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/provider/ContactsContract;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x19
name = "DataUsageFeedback"
.end annotation
# static fields
.field public static final DELETE_USAGE_URI:Landroid/net/Uri;
.field public static final FEEDBACK_URI:Landroid/net/Uri;
.field public static final USAGE_TYPE:Ljava/lang/String; = "type"
.field public static final USAGE_TYPE_CALL:Ljava/lang/String; = "call"
.field public static final USAGE_TYPE_LONG_TEXT:Ljava/lang/String; = "long_text"
.field public static final USAGE_TYPE_SHORT_TEXT:Ljava/lang/String; = "short_text"
# direct methods
.method static constructor <clinit>()V
.locals 2
.prologue
.line 8020
sget-object v0, Landroid/provider/ContactsContract$Data;->CONTENT_URI:Landroid/net/Uri;
const-string/jumbo v1, "usagefeedback"
invoke-static {v0, v1}, Landroid/net/Uri;->withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;
move-result-object v0
sput-object v0, Landroid/provider/ContactsContract$DataUsageFeedback;->FEEDBACK_URI:Landroid/net/Uri;
.line 8028
sget-object v0, Landroid/provider/ContactsContract$Contacts;->CONTENT_URI:Landroid/net/Uri;
const-string v1, "delete_usage"
invoke-static {v0, v1}, Landroid/net/Uri;->withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;
move-result-object v0
sput-object v0, Landroid/provider/ContactsContract$DataUsageFeedback;->DELETE_USAGE_URI:Landroid/net/Uri;
return-void
.end method
.method public constructor <init>()V
.locals 0
.prologue
.line 8014
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
| {'content_hash': 'b046ea59dc7ed41e10c39056270b035c', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 117, 'avg_line_length': 27.855072463768117, 'alnum_prop': 0.7486992715920916, 'repo_name': 'Liberations/Flyme5_devices_base_cm', 'id': '941ea266926eac3c99009731cc4cc1bd1eca0175', 'size': '1922', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'vendor/aosp/framework.jar.out/smali/android/provider/ContactsContract$DataUsageFeedback.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '1500'}, {'name': 'HTML', 'bytes': '96769'}, {'name': 'Makefile', 'bytes': '11209'}, {'name': 'Python', 'bytes': '1195'}, {'name': 'Shell', 'bytes': '55270'}, {'name': 'Smali', 'bytes': '160321888'}]} |
namespace MassTransit.Configuration
{
public class ConsumerEndpointDefinition<TConsumer> :
SettingsEndpointDefinition<TConsumer>
where TConsumer : class, IConsumer
{
public ConsumerEndpointDefinition(IEndpointSettings<IEndpointDefinition<TConsumer>> settings)
: base(settings)
{
}
protected override string FormatEndpointName(IEndpointNameFormatter formatter)
{
return formatter.Consumer<TConsumer>();
}
}
}
| {'content_hash': '9c62bf0464a068ed6821883a74612b63', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 101, 'avg_line_length': 29.941176470588236, 'alnum_prop': 0.6738703339882122, 'repo_name': 'phatboyg/MassTransit', 'id': '5840562e32e238ad90f849c9f7ef6e14a3c2a7f7', 'size': '509', 'binary': False, 'copies': '3', 'ref': 'refs/heads/develop', 'path': 'src/MassTransit.Abstractions/Configuration/DependencyInjection/Configuration/ConsumerEndpointDefinition.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '12646003'}, {'name': 'Dockerfile', 'bytes': '781'}, {'name': 'PowerShell', 'bytes': '3303'}, {'name': 'Shell', 'bytes': '907'}, {'name': 'Smalltalk', 'bytes': '4'}]} |
from filebeat import BaseTest
import os
"""
Tests for the JSON decoding functionality.
"""
class Test(BaseTest):
def test_docker_logs(self):
"""
Should be able to interpret docker logs.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(message_key="log")
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/docker.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=21),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()
assert len(output) == 21
assert all("json.log" in o for o in output)
assert all("json.time" in o for o in output)
assert all(o["json.stream"] == "stdout" for o in output)
def test_docker_logs_filtering(self):
"""
Should be able to do line filtering on docker logs.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(message_key="log", keys_under_root=True),
exclude_lines=["windows"]
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/docker.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=19),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()
assert len(output) == 19
assert all("log" in o for o in output)
assert all("time" in o for o in output)
assert all(o["stream"] == "stdout" for o in output)
assert all("windows" not in o["log"] for o in output)
def test_docker_logs_multiline(self):
"""
Should be able to do multiline on docker logs.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(message_key="log", keys_under_root=True),
multiline=True,
pattern="^\[log\]",
match="after",
negate="true"
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/docker_multiline.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=3),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()
assert len(output) == 3
assert all("time" in o for o in output)
assert all("log" in o for o in output)
assert all("message" not in o for o in output)
assert all(o["stream"] == "stdout" for o in output)
assert output[1]["log"] == \
"[log] This one is\n on multiple\n lines"
def test_simple_json_overwrite(self):
"""
Should be able to overwrite keys when requested.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(
message_key="message",
keys_under_root=True,
overwrite_keys=True),
exclude_lines=["windows"]
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/json_override.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=1),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()[0]
assert output["source"] == "hello"
assert output["message"] == "test source"
def test_config_no_msg_key_filtering(self):
"""
Should raise an error if line filtering and JSON are defined,
but the message key is not defined.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(
keys_under_root=True),
exclude_lines=["windows"]
)
proc = self.start_beat()
status = proc.wait()
assert status != 0
assert self.log_contains("When using the JSON decoder and line" +
" filtering together, you need to specify" +
" a message_key value")
def test_config_no_msg_key_multiline(self):
"""
Should raise an error if line filtering and JSON are defined,
but the message key is not defined.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(
keys_under_root=True),
multiline=True,
pattern="^["
)
proc = self.start_beat()
status = proc.wait()
assert status != 0
assert self.log_contains("When using the JSON decoder and multiline" +
" together, you need to specify a" +
" message_key value")
def test_timestamp_in_message(self):
"""
Should be able to make use of a `@timestamp` field if it exists in the
message.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(
message_key="msg",
keys_under_root=True,
overwrite_keys=True
),
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/json_timestamp.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=3),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()
assert len(output) == 3
assert all(isinstance(o["@timestamp"], basestring) for o in output)
assert all(isinstance(o["type"], basestring) for o in output)
assert output[0]["@timestamp"] == "2016-04-05T18:47:18.444Z"
assert output[1]["@timestamp"] != "invalid"
assert output[1]["json_error"] == \
"@timestamp not overwritten (parse error on invalid)"
assert output[2]["json_error"] == \
"@timestamp not overwritten (not string)"
def test_type_in_message(self):
"""
If overwrite_keys is true and type is in the message, we have to
be careful to keep it as a valid type name.
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*",
json=dict(
message_key="msg",
keys_under_root=True,
overwrite_keys=True
),
)
os.mkdir(self.working_dir + "/log/")
self.copy_files(["logs/json_type.log"],
source_dir="../files",
target_dir="log")
proc = self.start_beat()
self.wait_until(
lambda: self.output_has(lines=3),
max_timeout=10)
proc.check_kill_and_wait()
output = self.read_output()
assert len(output) == 3
assert all(isinstance(o["@timestamp"], basestring) for o in output)
assert all(isinstance(o["type"], basestring) for o in output)
assert output[0]["type"] == "test"
assert output[1]["type"] == "log"
assert output[1]["json_error"] == \
"type not overwritten (not string)"
assert output[2]["type"] == "log"
assert output[2]["json_error"] == \
"type not overwritten (not string)"
| {'content_hash': 'd85d6eae922f2d568ebd3824eb73f64d', 'timestamp': '', 'source': 'github', 'line_count': 243, 'max_line_length': 78, 'avg_line_length': 33.053497942386834, 'alnum_prop': 0.5164342629482072, 'repo_name': 'ninjasftw/libertyproxybeat', 'id': '2f15615fbe9b6246ef1fb3b30921223d7cbf92ed', 'size': '8032', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/elastic/beats/filebeat/tests/system/test_json.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '10091'}, {'name': 'Makefile', 'bytes': '1640'}]} |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.2.0
Version: 3.2.0
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: [email protected]
Follow: www.twitter.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title>历史数据</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="__PUBLIC__/Style/assets/global/fonts/2.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css">
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link rel="stylesheet" type="text/css" href="__PUBLIC__/Style/assets/global/plugins/select2/select2.css"/>
<link rel="stylesheet" type="text/css" href="__PUBLIC__/Style/assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.css"/>
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME STYLES -->
<link href="__PUBLIC__/Style/assets/global/css/components.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/global/css/plugins.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/admin/layout3/css/layout.css" rel="stylesheet" type="text/css">
<link href="__PUBLIC__/Style/assets/admin/layout3/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color">
<link href="__PUBLIC__/Style/assets/admin/layout3/css/custom.css" rel="stylesheet" type="text/css">
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<!-- DOC: Apply "page-header-menu-fixed" class to set the mega menu fixed -->
<!-- DOC: Apply "page-header-top-fixed" class to set the top menu fixed -->
<body>
<!-- BEGIN HEADER -->
<div class="page-header">
<!-- BEGIN HEADER TOP -->
<include file="./Application/Admin/View/Public/tpl/header.html" />
<!-- END HEADER TOP -->
<!-- BEGIN HEADER MENU -->
<include file="./Application/Admin/View/Public/tpl/nav.html" />
<!-- END HEADER MENU -->
</div>
<!-- END HEADER -->
<!-- BEGIN PAGE CONTAINER -->
<div class="page-container">
<!-- BEGIN PAGE HEAD -->
<div class="page-head">
<div class="container">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>历史数据<small>历史数据列表信息</small></h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<include file="./Application/Admin/View/Public/tpl/settings.html" />
<!-- END PAGE TOOLBAR -->
</div>
</div>
<!-- END PAGE HEAD -->
<!-- BEGIN PAGE CONTENT -->
<div class="page-content">
<div class="container">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Widget settings form goes here
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Save changes</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<!-- BEGIN PAGE BREADCRUMB -->
<ul class="page-breadcrumb breadcrumb" style="display:none;">
<li>
<a href="#">Home</a><i class="fa fa-circle"></i>
</li>
<li>
<a href="table_managed.html">Extra</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="table_managed.html">Data Tables</a>
<i class="fa fa-circle"></i>
</li>
<li class="active">
Managed Datatables
</li>
</ul>
<!-- END PAGE BREADCRUMB -->
<!-- BEGIN PAGE CONTENT INNER -->
<div class="row">
<div class="col-md-12 col-sm-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-bug font-green-sharp"></i>
<span class="caption-subject font-green-sharp bold uppercase">历史杀死害虫数</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<ul class="nav nav-pills">
<li class="active">
<a href="#tab_2_1" data-toggle="tab">
按天计算 </a>
</li>
<li>
<a href="#tab_2_2" data-toggle="tab">
按月计算 </a>
</li>
<li>
<a href="#tab_2_5" data-toggle="tab">
按年计算 </a>
</li>
<li class="dropdown hide">
<a href="#" id="myTabDrop1" class="dropdown-toggle" data-toggle="dropdown">
Dropdown <i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1">
<li>
<a href="#tab_2_3" tabindex="-1" data-toggle="tab">
Option 1 </a>
</li>
<li>
<a href="#tab_2_4" tabindex="-1" data-toggle="tab">
Option 2 </a>
</li>
<li>
<a href="#tab_2_3" tabindex="-1" data-toggle="tab">
Option 3 </a>
</li>
<li>
<a href="#tab_2_4" tabindex="-1" data-toggle="tab">
Option 4 </a>
</li>
</ul>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade active in" id="tab_2_1">
<table class="table table-striped table-bordered table-hover" id="sample_2">
<thead>
<tr>
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes"/>
</th>
<th>编号</th><th>设备名称</th><th>日期</th><th>放电次数</th><th>杀死害虫数</th><th>拥有者</th>
</tr>
</thead>
<tbody>
<volist name="dayData" id="vo">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1"/>
</td>
<td>{$vo.deviceSN}</td><td>{$vo.deviceName}</td><td>{$vo.daychar}</td><td>{$vo.electricShockCount}</td><td>{$vo.bugCount}</td><td>{$users[$vo['UserId']]['realname']|default=""}</td>
</tr>
</volist>
</tbody>
</table>
</div>
<div class="tab-pane fade" id="tab_2_2">
<table class="table table-striped table-bordered table-hover" id="sample_2_month">
<thead>
<tr>
<th class="table-checkbox" style="width: 24.2px;">
<input type="checkbox" class="group-checkable" data-set="#sample_2_month .checkboxes"/>
</th>
<th >编号</th><th>设备名称</th><th>日期</th><th>放电次数</th><th>杀死害虫数</th><th>拥有者</th>
</tr>
</thead>
<tbody>
<volist name="monthData" id="vo">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1"/>
</td>
<td>{$vo.deviceSN}</td><td>{$vo.deviceName}</td><td>{$vo.monthchar}</td><td>{$vo.electricShockCount}</td><td>{$vo.bugCount}</td><td>{$users[$vo['UserId']]['realname']|default=""}</td>
</tr>
</volist>
</tbody>
</table>
</div>
<div class="tab-pane fade" id="tab_2_3">
<p>
Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.
</p>
</div>
<div class="tab-pane fade" id="tab_2_4">
<p>
Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.
</p>
</div>
<div class="tab-pane fade" id="tab_2_5">
<table class="table table-striped table-bordered table-hover" id="sample_2_year">
<thead>
<tr>
<th class="table-checkbox" style="width: 24.2px;">
<input type="checkbox" class="group-checkable" data-set="#sample_2_year .checkboxes"/>
</th>
<th style="width: 24.2px;">编号</th><th>设备名称</th><th>日期</th><th>放电次数</th><th>杀死害虫数</th><th>拥有者</th>
</tr>
</thead>
<tbody>
<volist name="yearData" id="vo">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1"/>
</td>
<td>{$vo.deviceSN}</td><td>{$vo.deviceName}</td><td>{$vo.year}</td><td>{$vo.electricShockCount}</td><td>{$vo.bugCount}</td><td>{$users[$vo['UserId']]['realname']|default=""}</td>
</tr>
</volist>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
<div class="col-md-12 col-sm-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-lightbulb-o font-green-sharp"></i>
<span class="caption-subject font-green-sharp bold uppercase">历史杀虫灯数据</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_2_2">
<thead>
<tr>
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_2_2 .checkboxes"/>
</th>
<th>编号</th>
<th>设备名称</th>
<th>
开灯时间
</th>
<th>关灯时间</th>
<th>
开灯时长
</th>
<th>放电次数</th>
<th>杀死害虫数</th>
<th>拥有者</th>
</tr>
</thead>
<tbody>
<volist name="lampData" id="vo">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1"/>
</td>
<td>{$vo.deviceSN}</td>
<td>{$vo.deviceName}</td>
<td>
{$vo.lampOnTime}
</td>
<td>
{$vo.lampOffTime}
</td>
<td><?php echo intval(( strtotime($vo['lampOffTime'])-strtotime($vo['lampOnTime']) )/3600);?>小时</td>
<td>{$vo.electricShockCount}</td>
<td>{$vo.bugCount}</td>
<td>{$users[$vo['UserId']]['realname']|default=""}</td>
</tr>
</volist>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
<div class="col-md-12 col-sm-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-bolt font-green-sharp"></i>
<span class="caption-subject font-green-sharp bold uppercase">历史放电次数据</span>
</div>
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
<a href="javascript:;" class="reload">
</a>
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_2_1">
<thead>
<tr>
<th class="table-checkbox">
<input type="checkbox" class="group-checkable" data-set="#sample_2_1 .checkboxes"/>
</th>
<th>编号</th>
<th>设备名称</th>
<th>
放电时间
</th>
<th>电压值</th>
<th>
杀死害虫数
</th>
<th>拥有者</th>
</tr>
</thead>
<tbody>
<volist name="electricShockData" id="vo">
<tr class="odd gradeX">
<td>
<input type="checkbox" class="checkboxes" value="1"/>
</td>
<td>{$vo.deviceSN}</td>
<td>
{$vo.deviceName}
</td>
<td>
{$vo.LogTime}
</td>
<td>
{$vo.voltage}V
</td>
<td>
{$vo.bugCount|default=1}
</td>
<td>{$users[$vo['UserId']]['realname']|default=""}</td>
</tr>
</volist>
</tbody>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
<!-- END PAGE CONTENT INNER -->
</div>
</div>
<!-- END PAGE CONTENT -->
</div>
<!-- END PAGE CONTAINER -->
<!-- BEGIN FOOTER -->
<include file="./Application/Admin/View/Public/tpl/footer.html" />
<!-- END FOOTER -->
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="__PUBLIC__/Style/assets/global/plugins/respond.min.js"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="__PUBLIC__/Style/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui-1.10.3.custom.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="__PUBLIC__/Style/assets/global/plugins/jquery-ui/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="__PUBLIC__/Style/assets/global/plugins/select2/select2.min.js"></script>
<script type="text/javascript" src="__PUBLIC__/Style/assets/global/plugins/datatables/media/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="__PUBLIC__/Style/assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="__PUBLIC__/Style/assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/admin/layout3/scripts/layout.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/admin/layout3/scripts/demo.js" type="text/javascript"></script>
<script src="__PUBLIC__/Style/assets/admin/pages/scripts/table-managed.js"></script>
<script>
jQuery(document).ready(function() {
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
Demo.init(); // init demo features
TableManaged.init();
});
</script>
</body>
<!-- END BODY -->
</html> | {'content_hash': 'da440787587cc0e9c5c63d4702318754', 'timestamp': '', 'source': 'github', 'line_count': 451, 'max_line_length': 588, 'avg_line_length': 39.60532150776053, 'alnum_prop': 0.5681334676967865, 'repo_name': 'niceguy-php/beyond', 'id': 'cb568148f06aa1ec22e7cf7d939d26fe71c36d80', 'size': '18186', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Application/Admin/View/device/historyData.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '298'}, {'name': 'C', 'bytes': '10209'}, {'name': 'CSS', 'bytes': '2857013'}, {'name': 'CoffeeScript', 'bytes': '83631'}, {'name': 'Go', 'bytes': '7075'}, {'name': 'Java', 'bytes': '81125'}, {'name': 'JavaScript', 'bytes': '6666606'}, {'name': 'PHP', 'bytes': '3048050'}, {'name': 'Python', 'bytes': '5844'}, {'name': 'Shell', 'bytes': '1934'}]} |
from distutils.version import StrictVersion
import functools
from http import client as http_client
import json
import logging
import re
import textwrap
import time
from urllib import parse as urlparse
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as kexc
from ironicclient.common import filecache
from ironicclient.common.i18n import _
from ironicclient import exc
# NOTE(deva): Record the latest version that this client was tested with.
# We still have a lot of work to do in the client to implement
# microversion support in the client properly! See
# http://specs.openstack.org/openstack/ironic-specs/specs/kilo/api-microversions.html # noqa
# for full details.
DEFAULT_VER = '1.9'
LAST_KNOWN_API_VERSION = 78
LATEST_VERSION = '1.{}'.format(LAST_KNOWN_API_VERSION)
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-ironicclient'
CHUNKSIZE = 1024 * 64 # 64kB
_MAJOR_VERSION = 1
API_VERSION = '/v%d' % _MAJOR_VERSION
API_VERSION_SELECTED_STATES = ('user', 'negotiated', 'cached', 'default')
DEFAULT_MAX_RETRIES = 5
DEFAULT_RETRY_INTERVAL = 2
SENSITIVE_HEADERS = ('X-Auth-Token',)
SUPPORTED_ENDPOINT_SCHEME = ('http', 'https')
_API_VERSION_RE = re.compile(r'/+(v%d)?/*$' % _MAJOR_VERSION)
def _trim_endpoint_api_version(url):
"""Trim API version and trailing slash from endpoint."""
return re.sub(_API_VERSION_RE, '', url)
def _extract_error_json(body):
"""Return error_message from the HTTP response body."""
try:
body_json = json.loads(body)
except ValueError:
return {}
if 'error_message' not in body_json:
return {}
try:
error_json = json.loads(body_json['error_message'])
except ValueError:
return body_json
err_msg = (error_json.get('faultstring') or error_json.get('description'))
if err_msg:
body_json['error_message'] = err_msg
return body_json
def get_server(url):
"""Extract and return the server & port."""
if url is None:
return None, None
parts = urlparse.urlparse(url)
return parts.hostname, str(parts.port)
class VersionNegotiationMixin(object):
def negotiate_version(self, conn, resp):
"""Negotiate the server version
Assumption: Called after receiving a 406 error when doing a request.
:param conn: A connection object
:param resp: The response object from http request
"""
def _query_server(conn):
if (self.os_ironic_api_version
and not isinstance(self.os_ironic_api_version, list)
and self.os_ironic_api_version != 'latest'):
base_version = ("/v%s" %
str(self.os_ironic_api_version).split('.')[0])
else:
base_version = API_VERSION
# Raise exception on client or server error.
resp = self._make_simple_request(conn, 'GET', base_version)
if not resp.ok:
raise exc.from_response(resp, method='GET', url=base_version)
return resp
version_overridden = False
if (resp and hasattr(resp, 'request')
and hasattr(resp.request, 'headers')):
orig_hdr = resp.request.headers
# Get the version of the client's last request and fallback
# to the default for things like unit tests to not cause
# migraines.
req_api_ver = orig_hdr.get('X-OpenStack-Ironic-API-Version',
self.os_ironic_api_version)
else:
req_api_ver = self.os_ironic_api_version
if (resp and req_api_ver != self.os_ironic_api_version
and self.api_version_select_state == 'negotiated'):
# If we have a non-standard api version on the request,
# but we think we've negotiated, then the call was overridden.
# We should report the error with the called version
requested_version = req_api_ver
# And then we shouldn't save the newly negotiated
# version of this negotiation because we have been
# overridden a request.
version_overridden = True
else:
requested_version = self.os_ironic_api_version
if not resp:
resp = _query_server(conn)
if self.api_version_select_state not in API_VERSION_SELECTED_STATES:
raise RuntimeError(
_('Error: self.api_version_select_state should be one of the '
'values in: "%(valid)s" but had the value: "%(value)s"') %
{'valid': ', '.join(API_VERSION_SELECTED_STATES),
'value': self.api_version_select_state})
min_ver, max_ver = self._parse_version_headers(resp)
# NOTE: servers before commit 32fb6e99 did not return version headers
# on error, so we need to perform a GET to determine
# the supported version range
if not max_ver:
LOG.debug('No version header in response, requesting from server')
resp = _query_server(conn)
min_ver, max_ver = self._parse_version_headers(resp)
# Reset the maximum version that we permit
if StrictVersion(max_ver) > StrictVersion(LATEST_VERSION):
LOG.debug("Remote API version %(max_ver)s is greater than the "
"version supported by ironicclient. Maximum available "
"version is %(client_ver)s",
{'max_ver': max_ver,
'client_ver': LATEST_VERSION})
max_ver = LATEST_VERSION
# If the user requested an explicit version or we have negotiated a
# version and still failing then error now. The server could
# support the version requested but the requested operation may not
# be supported by the requested version.
# TODO(TheJulia): We should break this method into several parts,
# such as a sanity check/error method.
if ((self.api_version_select_state == 'user'
and not self._must_negotiate_version())
or (self.api_version_select_state == 'negotiated'
and version_overridden)):
raise exc.UnsupportedVersion(textwrap.fill(
_("Requested API version %(req)s is not supported by the "
"server, client, or the requested operation is not "
"supported by the requested version. "
"Supported version range is %(min)s to "
"%(max)s")
% {'req': requested_version,
'min': min_ver, 'max': max_ver}))
if (self.api_version_select_state == 'negotiated'):
raise exc.UnsupportedVersion(textwrap.fill(
_("No API version was specified or the requested operation "
"was not supported by the client's negotiated API version "
"%(req)s. Supported version range is: %(min)s to %(max)s")
% {'req': requested_version,
'min': min_ver, 'max': max_ver}))
if isinstance(requested_version, str):
if requested_version == 'latest':
negotiated_ver = max_ver
else:
negotiated_ver = str(
min(StrictVersion(requested_version),
StrictVersion(max_ver)))
elif isinstance(requested_version, list):
if 'latest' in requested_version:
raise ValueError(textwrap.fill(
_("The 'latest' API version can not be requested "
"in a list of versions. Please explicitly request "
"'latest' or request only versios between "
"%(min)s to %(max)s")
% {'min': min_ver, 'max': max_ver}))
versions = []
for version in requested_version:
if min_ver <= StrictVersion(version) <= max_ver:
versions.append(StrictVersion(version))
if versions:
negotiated_ver = str(max(versions))
else:
raise exc.UnsupportedVersion(textwrap.fill(
_("Requested API version specified and the requested "
"operation was not supported by the client's "
"requested API version %(req)s. Supported "
"version range is: %(min)s to %(max)s")
% {'req': requested_version,
'min': min_ver, 'max': max_ver}))
else:
raise ValueError(textwrap.fill(
_("Requested API version %(req)s type is unsupported. "
"Valid types are Strings such as '1.1', 'latest' "
"or a list of string values representing API versions.")
% {'req': requested_version}))
if StrictVersion(negotiated_ver) < StrictVersion(min_ver):
negotiated_ver = min_ver
# server handles microversions, but doesn't support
# the requested version, so try a negotiated version
self.api_version_select_state = 'negotiated'
self.os_ironic_api_version = negotiated_ver
LOG.debug('Negotiated API version is %s', negotiated_ver)
# Cache the negotiated version for this server
endpoint_override = getattr(self, 'endpoint_override', None)
host, port = get_server(endpoint_override)
filecache.save_data(host=host, port=port, data=negotiated_ver)
return negotiated_ver
def _generic_parse_version_headers(self, accessor_func):
min_ver = accessor_func('X-OpenStack-Ironic-API-Minimum-Version',
None)
max_ver = accessor_func('X-OpenStack-Ironic-API-Maximum-Version',
None)
return min_ver, max_ver
def _parse_version_headers(self, accessor_func):
# NOTE(jlvillal): Declared for unit testing purposes
raise NotImplementedError()
def _make_simple_request(self, conn, method, url):
# NOTE(jlvillal): Declared for unit testing purposes
raise NotImplementedError()
def _must_negotiate_version(self):
return (self.api_version_select_state == 'user'
and (self.os_ironic_api_version == 'latest'
or isinstance(self.os_ironic_api_version, list)))
_RETRY_EXCEPTIONS = (exc.Conflict, exc.ServiceUnavailable,
exc.ConnectionRefused, kexc.RetriableConnectionFailure)
def with_retries(func):
"""Wrapper for _http_request adding support for retries."""
@functools.wraps(func)
def wrapper(self, url, method, **kwargs):
if self.conflict_max_retries is None:
self.conflict_max_retries = DEFAULT_MAX_RETRIES
if self.conflict_retry_interval is None:
self.conflict_retry_interval = DEFAULT_RETRY_INTERVAL
num_attempts = self.conflict_max_retries + 1
for attempt in range(1, num_attempts + 1):
try:
return func(self, url, method, **kwargs)
except _RETRY_EXCEPTIONS as error:
msg = ("Error contacting Ironic server: %(error)s. "
"Attempt %(attempt)d of %(total)d" %
{'attempt': attempt,
'total': num_attempts,
'error': error})
if attempt == num_attempts:
LOG.error(msg)
raise
else:
LOG.debug(msg)
time.sleep(self.conflict_retry_interval)
return wrapper
class SessionClient(VersionNegotiationMixin, adapter.LegacyJsonAdapter):
"""HTTP client based on Keystone client session."""
def __init__(self,
os_ironic_api_version,
api_version_select_state,
max_retries,
retry_interval,
**kwargs):
self.os_ironic_api_version = os_ironic_api_version
self.api_version_select_state = api_version_select_state
self.conflict_max_retries = max_retries
self.conflict_retry_interval = retry_interval
if isinstance(kwargs.get('endpoint_override'), str):
kwargs['endpoint_override'] = _trim_endpoint_api_version(
kwargs['endpoint_override'])
super(SessionClient, self).__init__(**kwargs)
endpoint_filter = self._get_endpoint_filter()
endpoint = self.get_endpoint(**endpoint_filter)
if endpoint is None:
raise exc.EndpointNotFound(
_('The Bare Metal API endpoint cannot be detected and was '
'not provided explicitly'))
self.endpoint_trimmed = _trim_endpoint_api_version(endpoint)
def _parse_version_headers(self, resp):
return self._generic_parse_version_headers(resp.headers.get)
def _get_endpoint_filter(self):
return {
'interface': self.interface,
'service_type': self.service_type,
'region_name': self.region_name
}
def _make_simple_request(self, conn, method, url):
# NOTE: conn is self.session for this class
return conn.request(url, method, raise_exc=False,
user_agent=USER_AGENT,
endpoint_filter=self._get_endpoint_filter(),
endpoint_override=self.endpoint_override)
@with_retries
def _http_request(self, url, method, **kwargs):
# NOTE(TheJulia): self.os_ironic_api_version is reset in
# the self.negotiate_version() call if negotiation occurs.
if self.os_ironic_api_version and self._must_negotiate_version():
self.negotiate_version(self.session, None)
kwargs.setdefault('user_agent', USER_AGENT)
kwargs.setdefault('auth', self.auth)
if isinstance(self.endpoint_override, str):
kwargs.setdefault('endpoint_override', self.endpoint_override)
if getattr(self, 'os_ironic_api_version', None):
kwargs['headers'].setdefault('X-OpenStack-Ironic-API-Version',
self.os_ironic_api_version)
for k, v in self.additional_headers.items():
kwargs['headers'].setdefault(k, v)
if self.global_request_id is not None:
kwargs['headers'].setdefault(
"X-OpenStack-Request-ID", self.global_request_id)
endpoint_filter = kwargs.setdefault('endpoint_filter', {})
endpoint_filter.setdefault('interface', self.interface)
endpoint_filter.setdefault('service_type', self.service_type)
endpoint_filter.setdefault('region_name', self.region_name)
resp = self.session.request(url, method,
raise_exc=False, **kwargs)
if resp.status_code == http_client.NOT_ACCEPTABLE:
negotiated_ver = self.negotiate_version(self.session, resp)
kwargs['headers']['X-OpenStack-Ironic-API-Version'] = (
negotiated_ver)
return self._http_request(url, method, **kwargs)
if resp.status_code >= http_client.BAD_REQUEST:
error_json = _extract_error_json(resp.content)
raise exc.from_response(resp, error_json.get('error_message'),
error_json.get('debuginfo'), method, url)
elif resp.status_code in (http_client.MOVED_PERMANENTLY,
http_client.FOUND, http_client.USE_PROXY):
# Redirected. Reissue the request to the new location.
location = resp.headers.get('location')
resp = self._http_request(location, method, **kwargs)
elif resp.status_code == http_client.MULTIPLE_CHOICES:
raise exc.from_response(resp, method=method, url=url)
return resp
def json_request(self, method, url, **kwargs):
kwargs.setdefault('headers', {})
kwargs['headers'].setdefault('Content-Type', 'application/json')
kwargs['headers'].setdefault('Accept', 'application/json')
if 'body' in kwargs:
kwargs['json'] = kwargs.pop('body')
resp = self._http_request(url, method, **kwargs)
body = resp.content
content_type = resp.headers.get('content-type', None)
status = resp.status_code
if (status in (http_client.NO_CONTENT, http_client.RESET_CONTENT)
or content_type is None):
return resp, list()
if 'application/json' in content_type:
try:
body = resp.json()
except ValueError:
LOG.error('Could not decode response body as JSON')
else:
body = None
return resp, body
def raw_request(self, method, url, **kwargs):
kwargs.setdefault('headers', {})
kwargs['headers'].setdefault('Content-Type',
'application/octet-stream')
return self._http_request(url, method, **kwargs)
def _construct_http_client(session,
token=None,
auth_ref=None,
os_ironic_api_version=DEFAULT_VER,
api_version_select_state='default',
max_retries=DEFAULT_MAX_RETRIES,
retry_interval=DEFAULT_RETRY_INTERVAL,
timeout=600,
ca_file=None,
cert_file=None,
key_file=None,
insecure=None,
**kwargs):
kwargs.setdefault('service_type', 'baremetal')
kwargs.setdefault('user_agent', 'python-ironicclient')
kwargs.setdefault('interface', kwargs.pop('endpoint_type',
'publicURL'))
ignored = {'token': token,
'auth_ref': auth_ref,
'timeout': timeout != 600,
'ca_file': ca_file,
'cert_file': cert_file,
'key_file': key_file,
'insecure': insecure}
dvars = [k for k, v in ignored.items() if v]
if dvars:
LOG.warning('The following arguments are ignored when using '
'the session to construct a client: %s',
', '.join(dvars))
return SessionClient(session=session,
os_ironic_api_version=os_ironic_api_version,
api_version_select_state=api_version_select_state,
max_retries=max_retries,
retry_interval=retry_interval,
**kwargs)
| {'content_hash': '520898256d34b58413a6d719991d7de6', 'timestamp': '', 'source': 'github', 'line_count': 453, 'max_line_length': 104, 'avg_line_length': 41.65562913907285, 'alnum_prop': 0.5733439321674616, 'repo_name': 'openstack/python-ironicclient', 'id': '0608e3a4a39504098a28c1b44442b8cfc044898a', 'size': '19500', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ironicclient/common/http.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '1240609'}, {'name': 'Shell', 'bytes': '218'}]} |
package org.ml4j.nn.components.builders.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import org.ml4j.nn.axons.FullyConnectedAxonsConfig;
import org.ml4j.nn.components.NeuralComponent;
import org.ml4j.nn.components.builders.Base3DGraphBuilderState;
import org.ml4j.nn.components.builders.axons.Axons3DBuilder;
import org.ml4j.nn.components.builders.axons.AxonsBuilder;
import org.ml4j.nn.components.builders.common.ComponentsContainer;
import org.ml4j.nn.components.factories.NeuralComponentFactory;
import org.ml4j.nn.components.manytoone.PathCombinationStrategy;
import org.ml4j.nn.neurons.Neurons;
import org.ml4j.nn.neurons.Neurons3D;
public abstract class BaseNested3DGraphBuilderImpl<P extends ComponentsContainer<Neurons3D, T>, C extends Axons3DBuilder<T>, D extends AxonsBuilder<T>, T extends NeuralComponent<?>>
extends Base3DGraphBuilderImpl<C, D, T> {
protected Supplier<P> parent3DGraph;
private boolean pathEnded;
private boolean pathsEnded;
public BaseNested3DGraphBuilderImpl(Supplier<P> parent3DGraph, NeuralComponentFactory<T> directedComponentFactory,
Base3DGraphBuilderState builderState,
List<T> components) {
super(directedComponentFactory, builderState, components);
this.parent3DGraph = parent3DGraph;
}
protected abstract C createNewNestedGraphBuilder();
protected void completeNestedGraph(boolean addSkipConnection) {
if (!pathEnded) {
Neurons3D initialNeurons = getComponentsGraphNeurons().getCurrentNeurons();
addAxonsIfApplicable();
Neurons3D endNeurons = getComponentsGraphNeurons().getCurrentNeurons();
T chain = directedComponentFactory.createDirectedComponentChain(getComponents());
this.parent3DGraph.get().getChains().add(chain);
this.parent3DGraph.get().getEndNeurons().add(getComponentsGraphNeurons().getCurrentNeurons());
if (addSkipConnection) {
if (initialNeurons.getNeuronCountIncludingBias() == endNeurons.getNeuronCountIncludingBias()) {
T skipConnectionAxons = directedComponentFactory.createPassThroughAxonsComponent("SkipConnection-" + UUID.randomUUID().toString(), initialNeurons,
endNeurons);
T skipConnection = directedComponentFactory
.createDirectedComponentChain(Arrays.asList(skipConnectionAxons));
this.parent3DGraph.get().getChains().add(skipConnection);
} else {
T skipConnectionAxons = directedComponentFactory.createFullyConnectedAxonsComponent("SkipConnection-" + UUID.randomUUID().toString(),
FullyConnectedAxonsConfig.create(new Neurons(initialNeurons.getNeuronCountExcludingBias(), true), endNeurons), null, null);
T skipConnection = directedComponentFactory
.createDirectedComponentChain(Arrays.asList(skipConnectionAxons));
this.parent3DGraph.get().getChains().add(skipConnection);
}
}
pathEnded = true;
}
}
protected void completeNestedGraphs(String name, PathCombinationStrategy pathCombinationStrategy) {
if (!pathsEnded) {
if (pathCombinationStrategy == PathCombinationStrategy.FILTER_CONCAT) {
Neurons3D previousNeurons = null;
int totalDepth = 0;
for (Neurons3D endNeuronsInstance : this.parent3DGraph.get().getEndNeurons()) {
if (previousNeurons != null) {
if (previousNeurons.getWidth() != endNeuronsInstance.getWidth()) {
throw new IllegalStateException("Width doesn't match");
}
if (previousNeurons.getHeight() != endNeuronsInstance.getHeight()) {
throw new IllegalStateException("Height doesn't match");
}
}
totalDepth = totalDepth + endNeuronsInstance.getDepth();
previousNeurons = endNeuronsInstance;
}
parent3DGraph.get().getComponentsGraphNeurons()
.setCurrentNeurons(new Neurons3D(previousNeurons.getWidth(), previousNeurons.getHeight(),
totalDepth, previousNeurons.hasBiasUnit()));
parent3DGraph.get().getComponentsGraphNeurons()
.setRightNeurons(getComponentsGraphNeurons().getRightNeurons());
parent3DGraph.get().getComponentsGraphNeurons()
.setHasBiasUnit(getComponentsGraphNeurons().hasBiasUnit());
} else {
parent3DGraph.get().getComponentsGraphNeurons()
.setCurrentNeurons(getComponentsGraphNeurons().getCurrentNeurons());
parent3DGraph.get().getComponentsGraphNeurons()
.setRightNeurons(getComponentsGraphNeurons().getRightNeurons());
parent3DGraph.get().getComponentsGraphNeurons()
.setHasBiasUnit(getComponentsGraphNeurons().hasBiasUnit());
}
List<T> chainsList = new ArrayList<>();
chainsList.addAll(this.parent3DGraph.get().getChains());
Neurons graphInputNeurons = chainsList.get(0).getInputNeurons();
// ComponentChainBatchDefinition batch =
// directedComponentFactory.createDirectedComponentChainBatch(chainsList);
parent3DGraph.get()
.addComponent(directedComponentFactory.createDirectedComponentBipoleGraph(name, graphInputNeurons,
parent3DGraph.get().getComponentsGraphNeurons().getCurrentNeurons(), chainsList,
pathCombinationStrategy));
parent3DGraph.get().getEndNeurons().clear();
parent3DGraph.get().getChains().clear();
pathsEnded = true;
}
}
public P endParallelPaths(String name, PathCombinationStrategy pathCombinationStrategy) {
completeNestedGraph(false);
completeNestedGraphs(name, pathCombinationStrategy);
return parent3DGraph.get();
}
}
| {'content_hash': 'c8c63b2705140e943045ae7add847c6f', 'timestamp': '', 'source': 'github', 'line_count': 122, 'max_line_length': 181, 'avg_line_length': 44.204918032786885, 'alnum_prop': 0.7756350825143705, 'repo_name': 'ml4j/ml4j-impl', 'id': '18a11fb213ad7abb5aab8386604d72b514848cc9', 'size': '5997', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ml4j-builders-impl/src/main/java/org/ml4j/nn/components/builders/base/BaseNested3DGraphBuilderImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '831249'}]} |
require 'set'
module Ethereum
module SPV
class ProofVerifier < Proof
def initialize(nodes, exempts: [])
nodes = nodes.map {|n| RLP.encode(n) }.to_set
super(nodes: nodes, exempts: exempts)
end
def grabbing(node)
raise InvalidSPVProof unless nodes.include?(FastRLP.encode(node))
end
def store(node)
add_node node.dup
end
end
end
end
| {'content_hash': 'ef641dce5ffdd0f21869c74b91da0df5', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 73, 'avg_line_length': 18.90909090909091, 'alnum_prop': 0.6081730769230769, 'repo_name': 'cryptape/ruby-ethereum', 'id': 'dad95de68e4dab7b8da9212d0ba1ac83eef04271', 'size': '449', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'lib/ethereum/spv/proof_verifier.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '417299'}]} |
/* An example of starting a change stream with startAtOperationTime. */
#include <mongoc/mongoc.h>
int
main ()
{
int exit_code = EXIT_FAILURE;
const char *uri_string;
mongoc_uri_t *uri = NULL;
bson_error_t error;
mongoc_client_t *client = NULL;
mongoc_collection_t *coll = NULL;
bson_t pipeline = BSON_INITIALIZER;
bson_t opts = BSON_INITIALIZER;
mongoc_change_stream_t *stream = NULL;
bson_iter_t iter;
const bson_t *doc;
bson_value_t cached_operation_time = {0};
int i;
bool r;
mongoc_init ();
uri_string = "mongodb://localhost:27017/db?replicaSet=rs0";
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
goto cleanup;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
goto cleanup;
}
/* insert five documents. */
coll = mongoc_client_get_collection (client, "db", "coll");
for (i = 0; i < 5; i++) {
bson_t reply;
bson_t *insert_cmd = BCON_NEW ("insert",
"coll",
"documents",
"[",
"{",
"x",
BCON_INT64 (i),
"}",
"]");
r = mongoc_collection_write_command_with_opts (
coll, insert_cmd, NULL, &reply, &error);
bson_destroy (insert_cmd);
if (!r) {
bson_destroy (&reply);
fprintf (stderr, "failed to insert: %s\n", error.message);
goto cleanup;
}
if (i == 0) {
/* cache the operation time in the first reply. */
if (bson_iter_init_find (&iter, &reply, "operationTime")) {
bson_value_copy (bson_iter_value (&iter), &cached_operation_time);
} else {
fprintf (stderr, "reply does not contain operationTime.");
bson_destroy (&reply);
goto cleanup;
}
}
bson_destroy (&reply);
}
/* start a change stream at the first returned operationTime. */
BSON_APPEND_VALUE (&opts, "startAtOperationTime", &cached_operation_time);
stream = mongoc_collection_watch (coll, &pipeline, &opts);
/* since the change stream started at the operation time of the first
* insert, the five inserts are returned. */
printf ("listening for changes on db.coll:\n");
while (mongoc_change_stream_next (stream, &doc)) {
char *as_json;
as_json = bson_as_canonical_extended_json (doc, NULL);
printf ("change received: %s\n", as_json);
bson_free (as_json);
}
exit_code = EXIT_SUCCESS;
cleanup:
mongoc_uri_destroy (uri);
bson_destroy (&pipeline);
bson_destroy (&opts);
if (cached_operation_time.value_type) {
bson_value_destroy (&cached_operation_time);
}
mongoc_change_stream_destroy (stream);
mongoc_collection_destroy (coll);
mongoc_client_destroy (client);
mongoc_cleanup ();
return exit_code;
} | {'content_hash': '69ed939b20077f6eac2c56bd42bc793b', 'timestamp': '', 'source': 'github', 'line_count': 103, 'max_line_length': 78, 'avg_line_length': 31.145631067961165, 'alnum_prop': 0.5395885286783042, 'repo_name': 'acmorrow/mongo-c-driver', 'id': '9330b1cb45d93e75f0e53b81d2b4b21f4de37ab4', 'size': '3208', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/libmongoc/examples/example-start-at-optime.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '89079'}, {'name': 'Assembly', 'bytes': '141281'}, {'name': 'Batchfile', 'bytes': '24538'}, {'name': 'C', 'bytes': '6497908'}, {'name': 'C#', 'bytes': '55627'}, {'name': 'C++', 'bytes': '147334'}, {'name': 'CMake', 'bytes': '141306'}, {'name': 'CSS', 'bytes': '4293'}, {'name': 'DIGITAL Command Language', 'bytes': '27303'}, {'name': 'GDB', 'bytes': '4512'}, {'name': 'HTML', 'bytes': '31887'}, {'name': 'M4', 'bytes': '787'}, {'name': 'Makefile', 'bytes': '9216'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'Objective-C', 'bytes': '33138'}, {'name': 'Pascal', 'bytes': '75208'}, {'name': 'Perl', 'bytes': '3895'}, {'name': 'Python', 'bytes': '105411'}, {'name': 'Roff', 'bytes': '7800'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Shell', 'bytes': '87399'}]} |
<component name="libraryTable">
<library name="library-circular-1.1.0">
<CLASSES>
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.castorflex.smoothprogressbar/library-circular/1.1.0/res" />
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.castorflex.smoothprogressbar/library-circular/1.1.0/classes.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component> | {'content_hash': '3125c3121bbb84bc78888dad6dbdee00', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 154, 'avg_line_length': 46.1, 'alnum_prop': 0.702819956616052, 'repo_name': 'blackadmin/limetray-tweety-android', 'id': '4d0afc176eca6f3e2f2ab6a14ecdf9fdcf124fdd', 'size': '461', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '.idea/libraries/library_circular_1_1_0.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '97874'}]} |
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
<string name="config_share_file_dir" translatable="false">original_images/</string>
<string name="config_share_file_auth" translatable="false">com.renard.ocr.fileprovider</string>
</resources> | {'content_hash': '2c2aca2fefe2a62a8601f9c75d3f8a2e', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 99, 'avg_line_length': 53.4, 'alnum_prop': 0.7303370786516854, 'repo_name': 'dankito/TextFairyPlugin', 'id': 'bec9f8f4dfcb08aca4ee754b3e69fb9dc8b4bfa2', 'size': '267', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/values/config_strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '21530'}, {'name': 'C', 'bytes': '2145626'}, {'name': 'C++', 'bytes': '443967'}, {'name': 'Groff', 'bytes': '30721'}, {'name': 'HTML', 'bytes': '305090'}, {'name': 'Java', 'bytes': '509688'}, {'name': 'Makefile', 'bytes': '7169'}, {'name': 'Module Management System', 'bytes': '13253'}, {'name': 'Objective-C', 'bytes': '469'}, {'name': 'PostScript', 'bytes': '3630'}, {'name': 'SAS', 'bytes': '13756'}, {'name': 'Shell', 'bytes': '132288'}, {'name': 'Smalltalk', 'bytes': '1353'}]} |
/*
* W.J. van der Laan 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#include <QFile>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) {
// Message from network thread
if (guiref) {
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
} else {
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired) {
if (!guiref)
return false;
if (nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message) {
if (splashref) {
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom | Qt::AlignHCenter, QColor(255, 255, 255));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz) {
return QCoreApplication::translate("AtheistCoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e) {
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. AtheistCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[]) {
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
QFile styleFile(":/qss/default");
if (styleFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
app.setStyleSheet(styleFile.readAll());
styleFile.close();
}
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then AtheistCoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false))) {
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in AtheistCoin.conf in the data directory)
QMessageBox::critical(0, "AtheistCoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("AtheistCoin");
QApplication::setOrganizationDomain("AtheistCoin.org");
if (GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("AtheistCoin-Qt-testnet");
else
QApplication::setApplicationName("AtheistCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help")) {
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if (GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) {
splash.show();
splash.setAutoFillBackground(false);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try {
// Regenerate startup link, to fix links to old versions
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if (AppInit2(threadGroup)) {
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.addWallet("~Default", &walletModel);
window.setCurrentWallet("~Default");
// If -min option passed, start window minimized.
if (GetBoolArg("-min")) {
window.showMinimized();
} else {
window.show();
}
// Now that initialization/startup is done, process any command-line
// AtheistCoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
}
// Shutdown the core and its threads, but don't exit AtheistCoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
} else {
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| {'content_hash': '3b06c692f19ab14452542027112b05f6', 'timestamp': '', 'source': 'github', 'line_count': 292, 'max_line_length': 209, 'avg_line_length': 35.25, 'alnum_prop': 0.6537452637714952, 'repo_name': 'AtheistCoin/atheistcoin', 'id': '7ff417755da3fa5959e7f2bab940654fa71acb28', 'size': '10293', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/bitcoin.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '320774'}, {'name': 'C++', 'bytes': '2402114'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'Objective-C++', 'bytes': '6080'}, {'name': 'Python', 'bytes': '3773'}, {'name': 'Shell', 'bytes': '1144'}, {'name': 'TypeScript', 'bytes': '607184'}]} |
require './lib/second_curtain/upload'
require 'uri'
describe Upload do
it "should have instance variables set correctly upon initialization" do
upload = Upload.new('expected', 'actual')
expect(upload.expected_path).to eq('expected')
expect(upload.actual_path).to eq('actual')
end
it "should upload properly" do
path = "test/folder"
expected_double = double()
actual_double = double()
bucket = double()
doubles = {
"test/folder/expected.png" => expected_double,
"test/folder/actual.png" => actual_double
}
expect(bucket).to receive(:objects).twice.and_return(doubles)
expect(expected_double).to receive(:write).with(anything)
expect(actual_double).to receive(:write).with(anything)
upload = Upload.new('/path/to/expected.png', '/path/to/actual.png')
upload.upload(bucket, path)
expect(upload.uploaded_expected_url).to eq("expected.png")
expect(upload.uploaded_actual_url).to eq("actual.png")
end
end
| {'content_hash': '11944a1ee897a42a1665bd5e4a2ae28b', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 74, 'avg_line_length': 30.90625, 'alnum_prop': 0.6865520728008089, 'repo_name': 'ashfurrow/second_curtain', 'id': '4d95eda36091cf10e4df68852faea90344ff7f42', 'size': '989', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/second_shutter/upload_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1039'}, {'name': 'HTML', 'bytes': '11074'}, {'name': 'Makefile', 'bytes': '418'}, {'name': 'Objective-C', 'bytes': '160975'}, {'name': 'Ruby', 'bytes': '17323'}, {'name': 'Shell', 'bytes': '3552'}]} |
<?php
require("inc_header_ps.php");
require("aware_report.php");
require_once('../lib/GPS.php');
mysql_select_db($db_name, $oConn);
// 2014-12-02 Updated ^CS
// 2014-10-03 TEST FILE ^CS
// Hardcoded Data, use dropdowns in implementation to get actual truck # and GPS ID
// Upon Select Date, pick start and end times for the route, 24 hour period by default
$GPSID = isset($_REQUEST['TruckID']) ? $_REQUEST['TruckID'] : -1;
if ($GPSID != -1)
{
$TruckDriver = GPSMaps::GetTruckDriver($GPSID);
}
else
{
$TruckDriver = -1;
}
$StartDate = isset($_REQUEST['Day']) ? $_REQUEST['Day'] : date('Y-m-d');
$FinishDate = isset($_REQUEST['Day']) ? $_REQUEST['Day'] : date('Y-m-d');
if ($StartDate == '')
{
$StartDate = $_POST['Day'];
$FinishDate = $_POST['Day'];
}
$Speed = array();
$Braking = array();
$Accel = array();
$SpeedAlert = 0;
$CurrentLat = $CurrentLng = $PrevLat = $PrevLng = $CurrentTimeStamp = $PrevTimeStamp = "";
$coords = GPSMaps::GetData($GPSID, $StartDate, $FinishDate);
$coordtotal = $coords->RowCount();
$TruckList = GPSMaps::GetTruckDropDown($_SESSION['customerId'], 'yes');
$TList = array();
while ($TL = $TruckList->fetch(PDO::FETCH_OBJ))
{
if ($TL->TruckDriver == $TruckDriver)
{
$selected = "selected='selected'";
}
else
{
$selected = "";
}
$TList[] = "<option value='$TL->TruckID' $selected >$TL->TruckName ($TL->TruckSerial)</option>";
}
$Grade = 100;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php require("inc_page_head.php"); ?>
<style>
#TruckReport{
border-radius:10px;
border: 1px solid #000000;
color:#000;
font:normal 12px Verdana, Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<a id="joblogo" href="index.php">JobReady</a>
<div id="header">
<?php require("inc_nav_menu.php"); ?>
</div>
<div style="clear: both;"> </div>
<div id="container">
<div id='loading'> </div>
<div id="wrapper">
<div id="sidebar">
<?php require("inc_alerts.php"); ?>
</div>
<div id="content">
<div id="page_header">
<span>Truck Driving Report</span>
<div class="headerlink"><a href='maps_reporting.php'>Return to Map Reporting</a></div>
</div> <!-- end page_header -->
<div style="clear: both;"> </div>
<fieldset class="TruckMenu" id="TruckReport">
<legend>Select Truck and Date</legend>
<form action="map_report_driving_details.php" method="post" enctype="application/x-www-form-urlencoded">
Date :<input id="Day" name="Day" value="<?php echo $StartDate; ?>"><button type="button" onclick="displayDatePicker('Day', false, 'ymd', '-');"><img src="../images/SmallCalendar.gif"></button>
Truck : <select id="Truck" name="TruckID" class="TruckMenu">
<option value="-1">Select A Truck</option>
<option value="-2">----------</option>
<?php echo implode('', $TList); ?>
</select>
<input type="hidden" name="run" value="1" />
<input type="submit" value="Search" />
</form>
</fieldset>
<div style="clear: both;"> </div>
<?php
while ($c = $coords->fetch(PDO::FETCH_OBJ))
{
$CurrentLat = $c->Latitude;
$CurrentLng = $c->Longitude;
$CurrentTimeStamp = $c->TimeStamp;
if ($PrevTimeStamp == "")
{
$PrevLat = $c->Latitude;
$PrevLng = $c->Longitude;
$PrevTimeStamp = $c->TimeStamp;
}
$TimeDiff = strtotime($CurrentTimeStamp) - strtotime($PrevTimeStamp);
$PosDiff = GPSMaps::VGCD($CurrentLat, $CurrentLng, $PrevLat, $PrevLng);
if ($TimeDiff == 0 || $PosDiff == 0)
{
// Do Nothing
}
else
{
$MilesPerHour = round((($PosDiff/$TimeDiff) * 2.2369362920544), 2);
if ($MilesPerHour > 10 && $MilesPerHour < 100)
{
$Speed[] = $MilesPerHour;
if ($MilesPerHour > 75)
{
$SpeedAlert++;
}
}
else
{
$coordtotal--;
}
if ($PrevMPH <> '')
{
if (abs($PrevMPH - $MilesPerHour) > 30)
{
$HarshBrakingFastAccel++;
}
}
$PrevMPH = $MilesPerHour;
}
// Set Current to Previous for Next Calculation
$PrevLat = $CurrentLat;
$PrevLng = $CurrentLng;
$PrevTimeStamp = $CurrentTimeStamp;
}
$SpeedTotal = 0;
rsort($Speed);
for($i = 0; $i < $coordtotal; $i++)
{
$SpeedTotal += $Speed[$i];
}
if ($GPSID != -1)
{
echo "<fieldset id='TruckReport'>";
echo "Average Truck Speed : " . round($SpeedTotal/$coordtotal, 2) . " MPH | ";
echo "Raw Truck Speed * : " . GPSMaps::GetAverageSpeed($GPSID) . " MPH <br /><br />";
echo "Number of Fast Accel/Harsh Braking Alerts : $HarshBrakingFastAccel<br />";
echo "Number of Driving Alerts : $SpeedAlert <br /><br />";
echo "Top Daily Speeds : <br />$Speed[0] MPH <br />$Speed[1] MPH <br />$Speed[2] MPH <br />$Speed[3] MPH <br />$Speed[4] MPH <br /><br />";
echo "Driving Grade : ". round($Grade - (($SpeedAlert*1) + ($HarshBrakingFastAccel*2)),2) ."<br />";
echo "</fieldset>";
echo '<div style="clear: both;"> </div>';
echo "<fieldset id='TruckReport'>";
echo "<legend>Definitions</legend>";
echo "Raw Truck Speed - Recorded Speed in MPH by the trucks onboard device.<br />";
echo "Average Truck Speed - Calibrated Speed in MPH from the LAT and LNG of all recorded positions of the truck.<br />";
echo "Fast Acceleration / Harsh Braking - Noted when the truck increases or decreases by 30 MPH between Raw Truck Speed recordings.<br />";
echo "Driving Alerts - Noted when the truck increases over the speed of 75 MPH.<br />";
echo "</fieldset>";
}
?>
<div style="clear: both;"> </div>
</div> <!-- end content -->
<div style="clear: both;"> </div>
</div> <!-- end wrapper -->
<div style="clear: both;"> </div>
</div> <!-- end container -->
<iframe src="../keep_alive.php" width="0px" height="0px" frameborder="0" style="visibility:hidden"></iframe>
</body>
</html>
| {'content_hash': 'f579c366c6ea10207b55531c19016e48', 'timestamp': '', 'source': 'github', 'line_count': 198, 'max_line_length': 200, 'avg_line_length': 32.54040404040404, 'alnum_prop': 0.5498991153189507, 'repo_name': 'MyJobReady/gps-truck-tracking', 'id': 'fda81bae58d74a6129d180ad71403e50ddbcf955', 'size': '6443', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'gps/dev/map_report_driving_details.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '46258'}, {'name': 'PHP', 'bytes': '130038'}]} |
import React, {Component} from 'react';
import StopWatch from './component/StopWatch/StopWatch';
import StopWatchEvent from './events/ClockEvent';
import './App.css';
let timeAdjustTimer = 0;
const ticker = () => {
window.clearTimeout(timeAdjustTimer);
(new StopWatchEvent()).addSeconds(1);
timeAdjustTimer = window.setTimeout(ticker, 1000);
};
class App extends Component {
componentDidMount() {
ticker();
}
setTime() {
StopWatchEvent.setTime(
this.hours.value || 0,
this.minutes.value || 0,
this.seconds.value || 0
);
//OR
/*
(new StopWatchEvent({seconds: parseInt(seconds) + minutes * 60 + hours * 60 * 60})).dispatch()
*/
}
render() {
return (
<div className="App">
<StopWatch />
<StopWatch />
<StopWatch />
<StopWatch />
<br/>
<input type="button" value="reset" onClick={() => (new StopWatchEvent()).reset()}/>-
<input type="button" value="add 1 second" onClick={() => (new StopWatchEvent()).addSeconds(1)}/>-
<input type="button" value="add 1 minute" onClick={() => (new StopWatchEvent()).addSeconds(60)}/>-
<input type="button" value="add 1 hour" onClick={() => (new StopWatchEvent()).addSeconds(60 * 60)}/>
<br/>
<br/>
<input type="number" placeholder="00" max="60" min="0" ref={(inp) => this.hours = inp}/>:
<input type="number" placeholder="00" max="60" min="0" ref={(inp) => this.minutes = inp}/>:
<input type="number" placeholder="00" min="0" ref={(inp) => this.seconds = inp}/>-
<input type="button" value="set" onClick={() => this.setTime()}/>
</div>
);
}
}
export default App;
| {'content_hash': '23cc1faaa59c9de2f329ba705c4708b7', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 116, 'avg_line_length': 35.333333333333336, 'alnum_prop': 0.5209643605870021, 'repo_name': 'howtoclient/react-evix-examples', 'id': 'c0f153c0f8b04a0c5437fdd83a51e2e45aef54b2', 'size': '1908', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'many-clocks/src/App.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '972'}, {'name': 'HTML', 'bytes': '2274'}, {'name': 'JavaScript', 'bytes': '7281'}]} |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='airaverage',
old_name='definition',
new_name='level',
),
migrations.RenameField(
model_name='aircondition',
old_name='definition',
new_name='level',
),
]
| {'content_hash': '0985d2bb19f30544635abdf3ac304748', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 40, 'avg_line_length': 21.82608695652174, 'alnum_prop': 0.545816733067729, 'repo_name': 'banbanchs/leda', 'id': '910e99369f70d140532bba8913d01061e8f6fdb9', 'size': '526', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'api/migrations/0002_auto_20141112_1403.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9067'}, {'name': 'HTML', 'bytes': '5602'}, {'name': 'JavaScript', 'bytes': '12230'}, {'name': 'Python', 'bytes': '18502'}]} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sistemapagoimpuestos.Dto;
/**
*
* @author Gabriel
*/
public class DTOParametroCalculoEditable {
private double siEditablePCEditable;
private double noEditablePCEditable;
//constructor
public DTOParametroCalculoEditable() {
}
//getter
public double getSiEditablePCEditable() {
return siEditablePCEditable;
}
public double getNoEditablePCEditable() {
return noEditablePCEditable;
}
//setter
public void setSiEditablePCEditable(double siEditablePCEditable) {
this.siEditablePCEditable = siEditablePCEditable;
}
public void setNoEditablePCEditable(double noEditablePCEditable) {
this.noEditablePCEditable = noEditablePCEditable;
}
}
| {'content_hash': 'faf6706be36b1902def2a586ecfec8b6', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 79, 'avg_line_length': 22.357142857142858, 'alnum_prop': 0.711395101171459, 'repo_name': 'turing2017/Dise-o-2017', 'id': '1882c0d43176a5e299f746bf7b55ec42a820560e', 'size': '939', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SistemaPagoImpuestos/src/sistemapagoimpuestos/Dto/DTOParametroCalculoEditable.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '651901'}]} |
using namespace std;
int main(int argc, char* argv[])
{
string action = argv[1];
string game_state_json;
getline(cin, game_state_json);
json::Value game_state = json::Deserialize(game_state_json);
if(action == "bet_request")
{
cout << Player::betRequest(game_state);
}
else if(action == "showdown")
{
Player::showdown(game_state);
}
else if(action == "version")
{
cout << Player::VERSION;
}
return 0;
}
| {'content_hash': '6884922a9a351f627ba24c454d774900', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 64, 'avg_line_length': 19.76923076923077, 'alnum_prop': 0.5389105058365758, 'repo_name': 'NathanH581/poker-player-nottingting', 'id': '34e5dc3e3c22cf8bfd5e81e0ec558d9e29ec20c3', 'size': '592', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'main.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '47099'}, {'name': 'Makefile', 'bytes': '273'}, {'name': 'Python', 'bytes': '1549'}]} |
package org.ensembl.healthcheck.testcase.eg_compara;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.AbstractTemplatedTestCase;
public class EGCheckNoTreeStableIds extends AbstractTemplatedTestCase {
public EGCheckNoTreeStableIds() {
setTeamResponsible(Team.ENSEMBL_GENOMES);
appliesToType(DatabaseType.COMPARA);
setDescription("Checks that all protein gene trees have a stable id");
}
private final static String COUNT_NULLS = "SELECT COUNT(*) " +
"FROM gene_tree_root " +
"WHERE member_type = 'protein' " +
"AND tree_type = 'tree' " +
"AND clusterset_id='default' " +
"AND stable_id IS NULL";
@Override
protected boolean runTest(DatabaseRegistryEntry dbre) {
boolean pass = true;
Integer count = getTemplate(dbre).queryForDefaultObject(COUNT_NULLS, Integer.class);
if(count > 0) {
String message = String.format("%d protein gene tree(s) lacked a stable ID. Sql to check is '%s'", count, COUNT_NULLS);
ReportManager.problem(this, dbre.getConnection(), message);
pass = false;
}
return pass;
}
}
| {'content_hash': '3472edb2c9a91b029d0d00679beebd57', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 122, 'avg_line_length': 32.8421052631579, 'alnum_prop': 0.7355769230769231, 'repo_name': 'thomasmaurel/ensj-healthcheck', 'id': '3703f2a61116f1c01b44ef2f67d39a0a93faaacf', 'size': '1984', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/org/ensembl/healthcheck/testcase/eg_compara/EGCheckNoTreeStableIds.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4402'}, {'name': 'HTML', 'bytes': '5026'}, {'name': 'Java', 'bytes': '2900462'}, {'name': 'Perl', 'bytes': '110619'}, {'name': 'Shell', 'bytes': '24836'}, {'name': 'Smalltalk', 'bytes': '1162'}]} |
/**
* @file
* This file implements the Energy Scan Server.
*/
#include "energy_scan_server.hpp"
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "meshcop/meshcop.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/thread_netif.hpp"
#include "thread/thread_uri_paths.hpp"
namespace ot {
EnergyScanServer::EnergyScanServer(Instance &aInstance)
: InstanceLocator(aInstance)
, Notifier::Receiver(aInstance, EnergyScanServer::HandleNotifierEvents)
, mChannelMask(0)
, mChannelMaskCurrent(0)
, mPeriod(0)
, mScanDuration(0)
, mCount(0)
, mActive(false)
, mScanResultsLength(0)
, mTimer(aInstance, EnergyScanServer::HandleTimer, this)
, mEnergyScan(OT_URI_PATH_ENERGY_SCAN, &EnergyScanServer::HandleRequest, this)
{
Get<Coap::Coap>().AddResource(mEnergyScan);
}
void EnergyScanServer::HandleRequest(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
static_cast<EnergyScanServer *>(aContext)->HandleRequest(*static_cast<Coap::Message *>(aMessage),
*static_cast<const Ip6::MessageInfo *>(aMessageInfo));
}
void EnergyScanServer::HandleRequest(Coap::Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
uint8_t count;
uint16_t period;
uint16_t scanDuration;
Ip6::MessageInfo responseInfo(aMessageInfo);
uint32_t mask;
VerifyOrExit(aMessage.GetCode() == OT_COAP_CODE_POST, OT_NOOP);
SuccessOrExit(Tlv::FindUint8Tlv(aMessage, MeshCoP::Tlv::kCount, count));
SuccessOrExit(Tlv::FindUint16Tlv(aMessage, MeshCoP::Tlv::kPeriod, period));
SuccessOrExit(Tlv::FindUint16Tlv(aMessage, MeshCoP::Tlv::kScanDuration, scanDuration));
VerifyOrExit((mask = MeshCoP::ChannelMaskTlv::GetChannelMask(aMessage)) != 0, OT_NOOP);
mChannelMask = mask;
mChannelMaskCurrent = mChannelMask;
mCount = count;
mPeriod = period;
mScanDuration = scanDuration;
mScanResultsLength = 0;
mActive = true;
mTimer.Start(kScanDelay);
mCommissioner = aMessageInfo.GetPeerAddr();
if (aMessage.IsConfirmable() && !aMessageInfo.GetSockAddr().IsMulticast())
{
SuccessOrExit(Get<Coap::Coap>().SendEmptyAck(aMessage, responseInfo));
otLogInfoMeshCoP("sent energy scan query response");
}
exit:
return;
}
void EnergyScanServer::HandleTimer(Timer &aTimer)
{
aTimer.GetOwner<EnergyScanServer>().HandleTimer();
}
void EnergyScanServer::HandleTimer(void)
{
VerifyOrExit(mActive, OT_NOOP);
if (mCount)
{
// grab the lowest channel to scan
uint32_t channelMask = mChannelMaskCurrent & ~(mChannelMaskCurrent - 1);
IgnoreError(Get<Mac::Mac>().EnergyScan(channelMask, mScanDuration, HandleScanResult, this));
}
else
{
SendReport();
}
exit:
return;
}
void EnergyScanServer::HandleScanResult(Mac::EnergyScanResult *aResult, void *aContext)
{
static_cast<EnergyScanServer *>(aContext)->HandleScanResult(aResult);
}
void EnergyScanServer::HandleScanResult(Mac::EnergyScanResult *aResult)
{
VerifyOrExit(mActive, OT_NOOP);
if (aResult)
{
VerifyOrExit(mScanResultsLength < OPENTHREAD_CONFIG_TMF_ENERGY_SCAN_MAX_RESULTS, OT_NOOP);
mScanResults[mScanResultsLength++] = aResult->mMaxRssi;
}
else
{
// clear the lowest channel to scan
mChannelMaskCurrent &= mChannelMaskCurrent - 1;
if (mChannelMaskCurrent == 0)
{
mChannelMaskCurrent = mChannelMask;
mCount--;
}
if (mCount)
{
mTimer.Start(mPeriod);
}
else
{
mTimer.Start(kReportDelay);
}
}
exit:
return;
}
void EnergyScanServer::SendReport(void)
{
otError error = OT_ERROR_NONE;
MeshCoP::ChannelMaskTlv channelMask;
MeshCoP::EnergyListTlv energyList;
Ip6::MessageInfo messageInfo;
Coap::Message * message;
VerifyOrExit((message = MeshCoP::NewMeshCoPMessage(Get<Coap::Coap>())) != nullptr, error = OT_ERROR_NO_BUFS);
SuccessOrExit(error = message->Init(OT_COAP_TYPE_CONFIRMABLE, OT_COAP_CODE_POST, OT_URI_PATH_ENERGY_REPORT));
SuccessOrExit(error = message->SetPayloadMarker());
channelMask.Init();
channelMask.SetChannelMask(mChannelMask);
SuccessOrExit(error = channelMask.AppendTo(*message));
energyList.Init();
energyList.SetLength(mScanResultsLength);
SuccessOrExit(error = message->Append(&energyList, sizeof(energyList)));
SuccessOrExit(error = message->Append(mScanResults, mScanResultsLength));
messageInfo.SetSockAddr(Get<Mle::MleRouter>().GetMeshLocal16());
messageInfo.SetPeerAddr(mCommissioner);
messageInfo.SetPeerPort(kCoapUdpPort);
SuccessOrExit(error = Get<Coap::Coap>().SendMessage(*message, messageInfo));
otLogInfoMeshCoP("sent scan results");
exit:
if (error != OT_ERROR_NONE)
{
otLogInfoMeshCoP("Failed to send scan results: %s", otThreadErrorToString(error));
if (message != nullptr)
{
message->Free();
}
}
mActive = false;
}
void EnergyScanServer::HandleNotifierEvents(Notifier::Receiver &aReceiver, Events aEvents)
{
static_cast<EnergyScanServer &>(aReceiver).HandleNotifierEvents(aEvents);
}
void EnergyScanServer::HandleNotifierEvents(Events aEvents)
{
if (aEvents.Contains(kEventThreadNetdataChanged) && !mActive &&
Get<NetworkData::Leader>().GetCommissioningData() == nullptr)
{
mActive = false;
mTimer.Stop();
}
}
} // namespace ot
| {'content_hash': 'b00eaf42135d2a2a2c8311c85713a702', 'timestamp': '', 'source': 'github', 'line_count': 204, 'max_line_length': 115, 'avg_line_length': 28.63235294117647, 'alnum_prop': 0.6678650915939052, 'repo_name': 'librasungirl/openthread', 'id': '06fba97977e9f05844ca014b5eed46ceb4c2c8d5', 'size': '7449', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/core/thread/energy_scan_server.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '50'}, {'name': 'C', 'bytes': '1097261'}, {'name': 'C++', 'bytes': '5055434'}, {'name': 'CMake', 'bytes': '71815'}, {'name': 'Dockerfile', 'bytes': '10705'}, {'name': 'M4', 'bytes': '36363'}, {'name': 'Makefile', 'bytes': '154858'}, {'name': 'Python', 'bytes': '2672448'}, {'name': 'Shell', 'bytes': '110491'}]} |
package com.paypal.selion.elements;
import com.paypal.selion.plugins.GUIObjectDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class BaseMobileSeLionElementSet extends SeLionElementSet {
public BaseMobileSeLionElementSet(Collection<SeLionElement> elements) {
super(elements);
}
public List<GUIObjectDetails> getGUIObjectList(List<String> keys) {
List<GUIObjectDetails> mobileObjectDetailsList = new ArrayList<>();
for (String key : keys) {
SeLionElement element = findMatch(key);
if (element != null && element.isUIElement()) {
GUIObjectDetails mobileObjectDetails =
new GUIObjectDetails(element.getElementClass(), key, element.getElementPackage());
mobileObjectDetailsList.add(mobileObjectDetails);
}
}
return mobileObjectDetailsList;
}
public boolean add(String element) {
return super.add(new SeLionElement(element));
}
}
| {'content_hash': '86abad93374649d1484a5db0d099b946', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 102, 'avg_line_length': 31.515151515151516, 'alnum_prop': 0.6807692307692308, 'repo_name': 'paypal/SeLion', 'id': 'bf3e9a83246a29334f45cf02715dca9e7031ba16', 'size': '2719', 'binary': False, 'copies': '3', 'ref': 'refs/heads/develop', 'path': 'codegen/src/main/java/com/paypal/selion/elements/BaseMobileSeLionElementSet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '53471'}, {'name': 'HTML', 'bytes': '88618'}, {'name': 'Java', 'bytes': '3238900'}, {'name': 'JavaScript', 'bytes': '158386'}, {'name': 'Objective-C', 'bytes': '24249'}, {'name': 'Shell', 'bytes': '10114'}]} |
- Know how to define a Haskell module / Haskell file.
- Know how to export functions for use by other modules.
- Know how to define a constant.
- Know how to define a function.
- Know how to indent code.
- Know how to use basic math operators on numbers.
- Know how to define single- and multiline comments.
## Out of scope
- The IO module, which is required to define a minimal Haskell application with a "main", but involves more concepts.
## Concepts
- `basics`
## Prequisites
There are no prerequisites.
## Analyzer
This exercise could benefit from an analyser that includes the following rules:
- Verify that the whitespace adheres to community defaults.
- Verify that functions are re-used in other functions. | {'content_hash': '5ae9d15d9cceac8065fd05cb3a18a1b2', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 117, 'avg_line_length': 27.846153846153847, 'alnum_prop': 0.7582872928176796, 'repo_name': 'exercism/xhaskell', 'id': 'aebf06ce1e2c529cbb572de8a90768293aea9e5d', 'size': '758', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'exercises/concept/lucians-luscious-lasagna/.meta/design.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Haskell', 'bytes': '535257'}, {'name': 'Shell', 'bytes': '9373'}]} |
package com.github.krr.mongodb.aggregate.support.repository.nonreactive;
import com.github.krr.mongodb.aggregate.support.DummyAnnotation;
import com.github.krr.mongodb.aggregate.support.annotations.*;
import com.github.krr.mongodb.aggregate.support.beans.TestAggregateAnnotation2FieldsBean;
import java.util.List;
import java.util.Map;
/**
* Created by rkolliva on 4/172015.
*
*/
public interface TestAggregateRepository22 extends TestMongoRepository<TestAggregateAnnotation2FieldsBean, String> {
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Map.class)
@Match(query = "{'randomAttribute2':?0}", order = 0)
@Project(query = "{'randomAttribute' : '$randomAttribute1', '_id' : 0}", order = 1)
List<Map<String, String>> aggregateQueryWithMatchAndProjection(int value);
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Map.class)
@Match(query = "{'randomAttribute2':?0}", order = 0)
@Limit(query = "?1", order = 1)
List<Map<String, String>> aggregateQueryWithMatchAndLimit(int value, int limit);
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = TestAggregateAnnotation2FieldsBean.class)
@Out(query = "?0")
void aggregateQueryWithOut(String outputRepository);
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = TestAggregateAnnotation2FieldsBean.class)
@Match(query = "{'randomAttribute1':?0}", order = 0)
@Out(query = "?1")
void aggregateQueryWithMatchAndOut(String randomAttribute, String outputRepository);
// THESE METHODS TEST DIFFERENT ANNOTATION COMBINATIONS
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Void.class)
@Match(query = "dont care", order = 0)
void aggregateQueryWithMatchOnly();
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Void.class)
@Match(query = "dont care", order = 0)
@Match(query = "dont care1", order = 1)
void aggregateQueryWithMultipleMatchQueries();
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Void.class)
@Match(query = "dont care", order = 0)
@Group(query = "dont care", order = 1)
@Match(query = "dont care1", order = 2)
void aggregateQueryWithMultipleMatchQueriesInNonContiguousOrder();
@Aggregate(inputType = TestAggregateAnnotation2FieldsBean.class, outputBeanType = Void.class)
@Match(query = "dont care", order = 0)
@Group(query = "dont care", order = 1)
@DummyAnnotation
@Match(query = "dont care1", order = 2)
void aggregateQueryWithMultipleMatchQueriesInNonContiguousOrderWithNonAggAnnotations();
} | {'content_hash': 'fe81022c645fb9553b970acc5cbf3591', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 125, 'avg_line_length': 45.152542372881356, 'alnum_prop': 0.7706456456456456, 'repo_name': 'krraghavan/mongodb-aggregate-query-support', 'id': '79752d423015022616a1bddcf742263684bd6ce8', 'size': '3303', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mongodb-aggregate-query-support-reactive/src/test/java/com/github/krr/mongodb/aggregate/support/repository/nonreactive/TestAggregateRepository22.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '856401'}]} |
'use strict';
angular.module('app', ['ngRoute', 'ui.bootstrap', 'angular-clipboard'])
| {'content_hash': '37efd42013f7cf692e064648bdda0257', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 71, 'avg_line_length': 29.0, 'alnum_prop': 0.6781609195402298, 'repo_name': 'whitney-mitchell/height-to-human', 'id': 'e4de0a300583af063d5e5e7e73640ea28d5a8b98', 'size': '87', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/app/main.js', 'mode': '33188', 'license': 'mit', 'language': []} |
const fs = require('fs');
const cmd = require('./commands');
const settings = require('../settings');
const msgFilter = require('./messageFeatures/messageFilter');
const autoReact = require('./messageFeatures/autoReact');
const extEmoji = require('./messageFeatures/extendedEmoji');
const { getGuildCommandPrefix } = require('../handlers/GuildSettings');
const RegExExtendedEmojis = /:\w+:(?!\d+>)/g;
module.exports = (message) => {
if (message.author.bot && process.env.NODE_ENV !== 'test') return; // Ignore other bots' messages
const updatedSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
const prefix = getGuildCommandPrefix(message.client, message);
if (message.channel.type === 'text') {
if (message.guild.id === settings.mainGuild || message.guild.id === settings.testGuild) {
let deleted;
if (settings.rules.filters) {
deleted = msgFilter(message, settings);
} else {
deleted = false;
}
if (!deleted) {
// If message *is not* filtered from above, check through autoReact and extEmoji functions
const extEmojiOn = updatedSettings.rules.extendedEmoji.enable;
const autoReactOn = updatedSettings.rules.autoReact.enable;
if (!message.content.startsWith(prefix)) {
if (message.content.toString().match(RegExExtendedEmojis) && extEmojiOn) {
extEmoji(message, settings).then().catch(console.error);
}
if (autoReactOn) {
autoReact(message, settings).then().catch(console.error);
}
}
cmd(message.client, message, settings, prefix);
}
} else {
cmd(message.client, message, settings, prefix);
}
} else {
cmd(message.client, message, settings, prefix);
}
};
| {'content_hash': '221dc411f1f53ca826af487032dba931', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 99, 'avg_line_length': 37.041666666666664, 'alnum_prop': 0.6484814398200225, 'repo_name': 'malouro/ggis-bot', 'id': '0a07f567c4b15bb8c40f054ca638f92eff8a7f62', 'size': '1952', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'events/message.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '228714'}]} |
package com.google.cloud.servicedirectory.v1.samples;
// [START servicedirectory_v1_generated_RegistrationService_GetNamespace_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.servicedirectory.v1.GetNamespaceRequest;
import com.google.cloud.servicedirectory.v1.Namespace;
import com.google.cloud.servicedirectory.v1.NamespaceName;
import com.google.cloud.servicedirectory.v1.RegistrationServiceClient;
public class AsyncGetNamespace {
public static void main(String[] args) throws Exception {
asyncGetNamespace();
}
public static void asyncGetNamespace() throws Exception {
// This snippet has been automatically generated and should be regarded as a code template only.
// It will require modifications to work:
// - It may require correct/in-range values for request initialization.
// - It may require specifying regional endpoints when creating the service client as shown in
// https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
try (RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.create()) {
GetNamespaceRequest request =
GetNamespaceRequest.newBuilder()
.setName(NamespaceName.of("[PROJECT]", "[LOCATION]", "[NAMESPACE]").toString())
.build();
ApiFuture<Namespace> future =
registrationServiceClient.getNamespaceCallable().futureCall(request);
// Do something.
Namespace response = future.get();
}
}
}
// [END servicedirectory_v1_generated_RegistrationService_GetNamespace_async]
| {'content_hash': '0131661019e3272bda5d7cae23e66cc5', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 100, 'avg_line_length': 44.19444444444444, 'alnum_prop': 0.7536140791954745, 'repo_name': 'googleapis/google-cloud-java', 'id': '0c9bb1d18124e7dfbec6e0bc9b14ad821c2013a7', 'size': '2186', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'java-servicedirectory/samples/snippets/generated/com/google/cloud/servicedirectory/v1/registrationservice/getnamespace/AsyncGetNamespace.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '2614'}, {'name': 'HCL', 'bytes': '28592'}, {'name': 'Java', 'bytes': '826434232'}, {'name': 'Jinja', 'bytes': '2292'}, {'name': 'Python', 'bytes': '200408'}, {'name': 'Shell', 'bytes': '97954'}]} |
package alluxio.security;
import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.security.authentication.AuthType;
import alluxio.security.login.AppLoginModule;
import alluxio.security.login.LoginModuleConfiguration;
import java.io.IOException;
import java.util.Set;
import javax.annotation.concurrent.ThreadSafe;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
/**
* A Singleton of LoginUser, which is an instance of {@link alluxio.security.User}. It represents
* the user of Alluxio client, when connecting to Alluxio service.
*
* The implementation of getting a login user supports Windows, Unix, and Kerberos login modules.
*
* This singleton uses lazy initialization.
*/
@ThreadSafe
public final class LoginUser {
/** User instance of the login user in Alluxio client process. */
private static User sLoginUser;
private LoginUser() {} // prevent instantiation
/**
* Gets current singleton login user. This method is called to identify the singleton user who
* runs Alluxio client. When Alluxio client gets a user by this method and connects to Alluxio
* service, this user represents the client and is maintained in service.
*
* @return the login user
* @throws IOException if login fails
*/
public static User get() throws IOException {
if (sLoginUser == null) {
synchronized (LoginUser.class) {
if (sLoginUser == null) {
sLoginUser = login();
}
}
}
return sLoginUser;
}
/**
* Logs in based on the LoginModules.
*
* @return the login user
* @throws IOException if login fails
*/
private static User login() throws IOException {
AuthType authType =
Configuration.getEnum(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.class);
checkSecurityEnabled(authType);
Subject subject = new Subject();
try {
CallbackHandler callbackHandler = null;
if (authType.equals(AuthType.SIMPLE) || authType.equals(AuthType.CUSTOM)) {
callbackHandler = new AppLoginModule.AppCallbackHandler();
}
// Create LoginContext based on authType, corresponding LoginModule should be registered
// under the authType name in LoginModuleConfiguration.
LoginContext loginContext =
new LoginContext(authType.getAuthName(), subject, callbackHandler,
new LoginModuleConfiguration());
loginContext.login();
} catch (LoginException e) {
throw new IOException("Failed to login: " + e.getMessage(), e);
}
Set<User> userSet = subject.getPrincipals(User.class);
if (userSet.isEmpty()) {
throw new IOException("Failed to login: No Alluxio User is found.");
}
if (userSet.size() > 1) {
StringBuilder msg = new StringBuilder(
"Failed to login: More than one Alluxio Users are found:");
for (User user : userSet) {
msg.append(" ").append(user.toString());
}
throw new IOException(msg.toString());
}
return userSet.iterator().next();
}
/**
* Checks whether Alluxio is running in secure mode, such as {@link AuthType#SIMPLE},
* {@link AuthType#KERBEROS}, {@link AuthType#CUSTOM}.
*
* @param authType the authentication type in configuration
*/
private static void checkSecurityEnabled(AuthType authType) {
// TODO(dong): add Kerberos condition check.
if (authType != AuthType.SIMPLE && authType != AuthType.CUSTOM) {
throw new UnsupportedOperationException("User is not supported in " + authType.getAuthName()
+ " mode");
}
}
}
| {'content_hash': '940ea37bcfcf3ee063dd0a8128f1c6cf', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 98, 'avg_line_length': 33.34234234234234, 'alnum_prop': 0.6976492839773034, 'repo_name': 'yuluo-ding/alluxio', 'id': '837ea046cc63189d595de6ffe2146c519d989462', 'size': '4213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/common/src/main/java/alluxio/security/LoginUser.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '599'}, {'name': 'Java', 'bytes': '5846202'}, {'name': 'JavaScript', 'bytes': '1079'}, {'name': 'Protocol Buffer', 'bytes': '9229'}, {'name': 'Python', 'bytes': '11471'}, {'name': 'Roff', 'bytes': '5796'}, {'name': 'Ruby', 'bytes': '23034'}, {'name': 'Shell', 'bytes': '102910'}, {'name': 'Thrift', 'bytes': '27552'}]} |
<include file="Public:head" />
<!-- <script type="text/javascript" src="__PUBLIC__/admin/scripts/ThinkBox/jquery.ThinkBox.js"></script>
<link rel="stylesheet" type="text/css" href="__PUBLIC__/admin/scripts/ThinkBox/CSS/ThinkBox.css" media="all"> -->
<body>
<div id="body-wrapper">
<div id="sidebar">
<div id="sidebar-wrapper">
<include file="Public:left-nav" />
</div>
</div>
<!-- End #sidebar -->
<!-- <script type="text/javascript" src="__ROOT__/ueditor/editor_config.js"></script>
<script type="text/javascript" src="__ROOT__/ueditor/editor_all_min.js"></script> -->
<div id="main-content">
<!-- End .clear -->
<div class="content-box">
<!-- Start Content Box -->
<div class="content-box-header">
<h4><a href="__APP__/User">返回用户管理</a></h4>
</div>
<!-- End .content-box-header -->
<script type="text/javascript">
$(document).ready(function(){
$('select[name=statuspdf]').val({$list.statuspdf});
});
</script>
<div class="content-box-content">
<form method="post" action="__URL__/savepdf">
<div class="tab-content default-tab" style="width:720px;margin:0 auto;">
<input type="hidden" name="id" value="{$list.id}">
<span style="margin-bottom:5px;display:block;"><b>员工编号:</b>{$list.username}</span><br>
<span style="margin-bottom:5px;display:block;"><b>员工姓名:</b>{$list.yourname}</span><br>
<span style="margin-bottom:5px;display:block;"><b>猎头等级:</b>
<select name="statuspdf" style="width:80px;">
<option value="0" >入门
<option value="1">中级
<option value="2">高级
<option value="3">资深
</select>
<br>
<div class="tab-content default-tab" style="width:720px;margin:0 auto;">
<input type="submit" value="确定修改" style="font-size:18px;">
</div>
</form>
</div>
<!-- End .content-box-content -->
</div>
<div id="footer"> <small>
© Copyright 2010 Your Company | Powered by <a href="#">admin templates</a> | <a href="#">Top</a> </small>
</div>
<!-- End #footer -->
</div>
<!-- End #main-content -->
</div>
<!-- End #body-wrapper-->
</body>
</html>
| {'content_hash': '7d975939d56d69c1f99bfef2cc24dfb5', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 117, 'avg_line_length': 36.96491228070175, 'alnum_prop': 0.5994304698623636, 'repo_name': 'sunyang3721/tjd-timehr', 'id': 'ec86252296ef71eccb062c6311fb4c7ab8c1f208', 'size': '2173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'admin/Tpl/User/editpdf.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '182'}, {'name': 'CSS', 'bytes': '290033'}, {'name': 'HTML', 'bytes': '1091436'}, {'name': 'JavaScript', 'bytes': '1462878'}, {'name': 'PHP', 'bytes': '1804816'}, {'name': 'Smarty', 'bytes': '8718'}]} |
using System;
using NUnit.Framework;
using PeanutButter.DuckTyping.Exceptions;
using PeanutButter.DuckTyping.Shimming;
using PeanutButter.RandomGenerators;
using NExpect;
using static NExpect.Expectations;
// ReSharper disable RedundantArgumentDefaultValue
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable PossibleNullReferenceException
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnassignedGetOnlyAutoProperty
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
namespace PeanutButter.DuckTyping.Tests.Shimming
{
[TestFixture]
public class TestShimSham
{
// Most of ShimSham is tested indirectly throug tests on TypeMaker
// However I'd like to start testing more from basics (:
public class Cow
{
public string LastPitch { get; set; }
public int LastCount { get; set; }
public void Moo(int howManyTimes, string withPitch)
{
LastCount = howManyTimes;
LastPitch = withPitch;
}
}
[Test]
public void CallThrough_GivenParameterOrderMisMatch_WhenConstructedWithFlimFlamFalse_ShouldExplode()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var sut = Create(toWrap, false);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() =>
sut.CallThrough("Moo", new object[] {"high-pitched", 2})
)
.To.Throw<ArgumentException>();
//--------------- Assert -----------------------
}
[Test]
public void CallThrough_GivenParameterOrderMismatch_WhenConstructedWithFlimFlamTrue_ShouldPerformTheCall()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var sut = Create(toWrap, true);
var expectedPitch = RandomValueGen.GetRandomString();
var expectedCount = RandomValueGen.GetRandomInt();
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() =>
sut.CallThrough("Moo", new object[] {expectedPitch, expectedCount})
)
.Not.To.Throw();
//--------------- Assert -----------------------
Expect(toWrap.LastPitch).To.Equal(expectedPitch);
Expect(toWrap.LastCount).To.Equal(expectedCount);
}
[Test]
public void GetPropertyValue_WhenConstructedWith_FuzzyFalse_AndPropertyCaseMisMatch_ShouldFail()
{
//--------------- Arrange -------------------
var toWrap = new Cow
{
LastPitch = RandomValueGen.GetRandomString()
};
var sut = Create(toWrap, false);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() =>
sut.GetPropertyValue("lastPitch")
)
.To.Throw<PropertyNotFoundException>();
//--------------- Assert -----------------------
}
[Test]
public void GetPropertyValue_WhenConstructedWith_FuzzyTrue_AndPropertyCaseMismatch_ShouldReturnPropertyValue()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var expected = RandomValueGen.GetRandomString();
toWrap.LastPitch = expected;
var sut = Create(toWrap, true);
//--------------- Assume ----------------
//--------------- Act ----------------------
var result = sut.GetPropertyValue("lastPitch");
//--------------- Assert -----------------------
Expect(result).To.Equal(expected);
}
[Test]
public void SetPropertyValue_WhenConstructedWith_FuzzyTrue_AndPropertyCaseMismatch_ShouldSetProperty()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var expected = RandomValueGen.GetRandomString();
var sut = Create(toWrap, true);
//--------------- Assume ----------------
//--------------- Act ----------------------
sut.SetPropertyValue("LasTpItch", expected);
//--------------- Assert -----------------------
Expect(toWrap.LastPitch).To.Equal(expected);
}
[Test]
public void SetPropertyValue_WhenConstructedWith_FuzzyFalse_AndPropertyCaseMismatch_ShouldThrow()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var expected = RandomValueGen.GetRandomString();
var sut = Create(toWrap, false);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() =>
sut.SetPropertyValue("LasTpItch", expected)
)
.To.Throw<PropertyNotFoundException>();
//--------------- Assert -----------------------
}
[Test]
public void CallThrough_WhenConstructedWith_FuzzyFalse_AndMethodNameCaseMismatch_ShouldThrow()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var pitch = RandomValueGen.GetRandomString();
var count = RandomValueGen.GetRandomInt();
var sut = Create(toWrap, false);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() =>
sut.CallThrough("mOo", new object[] {count, pitch})
)
.To.Throw<MethodNotFoundException>();
//--------------- Assert -----------------------
}
[Test]
public void CallThrough_WhenConstructedWith_FuzzyTrue_AndMethodNameCaseMismatch_ShoulCallThrough()
{
//--------------- Arrange -------------------
var toWrap = new Cow();
var pitch = RandomValueGen.GetRandomString();
var count = RandomValueGen.GetRandomInt();
var sut = Create(toWrap, true);
//--------------- Assume ----------------
//--------------- Act ----------------------
sut.CallThrough("mOo", new object[] {count, pitch});
//--------------- Assert -----------------------
Expect(toWrap.LastCount).To.Equal(count);
Expect(toWrap.LastPitch).To.Equal(pitch);
}
public interface IFarmAnimal
{
int Legs { get; set; }
}
public interface ISingleAnimalFarm
{
IFarmAnimal Animal { get; set; }
}
[Test]
public void GettingPropertyValuesFromNestedMismatchingTypes()
{
//--------------- Arrange -------------------
var toWrap = new
{
Animal = new SomeArbitraryAnimal() {Legs = 4}
};
var sut = Create(toWrap, typeof(ISingleAnimalFarm), false);
//--------------- Assume ----------------
//--------------- Act ----------------------
var result = sut.GetPropertyValue("Animal") as IFarmAnimal;
//--------------- Assert -----------------------
Expect(result).Not.To.Be.Null();
// ReSharper disable once PossibleNullReferenceException
Expect(result.Legs).To.Equal(4);
}
public class SomeSingleAnimalFarm
{
public object Animal { get; set; }
}
public class SomeArbitraryAnimal
{
public int Legs { get; set; }
}
[Test]
public void SettingPropertyValuesOnNestedMismatchingTypes()
{
//--------------- Arrange -------------------
var toWrap = new SomeSingleAnimalFarm() {Animal = new SomeArbitraryAnimal() {Legs = 4}};
var sut = Create(toWrap, typeof(ISingleAnimalFarm), false);
var newAnimal = new SomeArbitraryAnimal() {Legs = 100};
//--------------- Assume ----------------
//--------------- Act ----------------------
sut.SetPropertyValue("Animal", newAnimal);
var result = sut.GetPropertyValue("Animal") as IFarmAnimal;
//--------------- Assert -----------------------
Expect(result).Not.To.Be.Null();
// ReSharper disable once PossibleNullReferenceException
Expect(result.Legs).To.Equal(100);
result.Legs = 123;
var newResult = sut.GetPropertyValue("Animal") as IFarmAnimal;
Expect(newResult).Not.To.Be.Null();
Expect(newResult.Legs).To.Equal(123);
}
public interface IHasGuidId
{
Guid Id { get; }
}
[Test]
public void WhenFuzzy_GetPropertyValue_ShouldBeAbleToConvertFromSource_Guid_ToTarget_String()
{
//--------------- Arrange -------------------
var guid = Guid.NewGuid();
var toWrap = new
{
Id = guid.ToString()
};
var sut = Create(toWrap, typeof(IHasGuidId), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
var result = sut.GetPropertyValue("Id");
//--------------- Assert -----------------------
Expect(result).To.Equal(guid);
}
public class WithStringId
{
public string id { get; set; }
}
public interface IHasReadWriteGuidId
{
Guid Id { get; set; }
}
[Test]
public void WhenFuzzy_SetPropertyValue_ShouldBeAbleToConvertFromSouce_Guid_ToTarget_String()
{
//--------------- Arrange -------------------
var guid = Guid.NewGuid();
var toWrap = new WithStringId();
var sut = Create(toWrap, typeof(IHasReadWriteGuidId), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
sut.SetPropertyValue("id", guid);
//--------------- Assert -----------------------
Expect(toWrap.id).To.Equal(guid.ToString());
}
public class WithIntId
{
public int Id { get; set; }
}
public interface IWithIntId
{
int Id { get; set; }
}
[Test]
public void SetPropertyValue_WhenUnderlyingFieldIsNotNullable_GivenNull_ShouldSetDefaultValueForFieldType()
{
//--------------- Arrange -------------------
var inner = new WithIntId() {Id = 12};
var sut = Create(inner, typeof(IWithIntId), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
sut.SetPropertyValue("Id", null);
//--------------- Assert -----------------------
Expect(inner.Id).To.Equal(0);
}
public interface IWithWriteOnlyId
{
int Id { set; }
}
public class WithWriteOnlyId
{
public int Id { private get; set; }
}
[Test]
public void GetPropertyValue_WhenPropertyIsWriteOnly_ShouldThrow()
{
//--------------- Arrange -------------------
var sut = Create(new WithWriteOnlyId(), typeof(IWithWriteOnlyId), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() => sut.GetPropertyValue("Id"))
.To.Throw<WriteOnlyPropertyException>();
//--------------- Assert -----------------------
}
public interface IWithReadOnlyId
{
int Id { get; }
}
public class WithReadOnlyId
{
public int Id { get; }
}
[Test]
public void SetPropertyValue_WhenPropertyIsReadOnly_ShouldThrow()
{
//--------------- Arrange -------------------
var sut = Create(new WithReadOnlyId(), typeof(IWithReadOnlyId), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
Expect(() => sut.SetPropertyValue("Id", 1))
.To.Throw<ReadOnlyPropertyException>();
//--------------- Assert -----------------------
}
public class UnderlyingWithNull
{
public object Foo { get; set; }
}
public interface IOverlyingNotNullable
{
int Foo { get; set; }
}
[Test]
public void
GetPropertyValue_WhenUnderlyingValueNotNull_AndPropertyTypeIsNotNullable_AndNoConverter_ShouldReturnDefaultValue()
{
//--------------- Arrange -------------------
var sut = Create(new UnderlyingWithNull() {Foo = null}, typeof(IOverlyingNotNullable), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
var result = sut.GetPropertyValue("Foo");
//--------------- Assert -----------------------
Expect(result).To.Equal(0);
}
[Test]
public void
GetPropertyValue_WhenUnderlyingValueIsNotNull_AndPropertyTypeIsNotNullable_AndNoConverter_ShouldReturnDefaultValue()
{
//--------------- Arrange -------------------
var sut = Create(new UnderlyingWithNull() {Foo = new object()}, typeof(IOverlyingNotNullable), true);
//--------------- Assume ----------------
//--------------- Act ----------------------
var result = sut.GetPropertyValue("Foo");
//--------------- Assert -----------------------
Expect(result).To.Equal(0);
}
private ShimSham Create(object toWrap, Type toMimic, bool isFuzzy = false, bool allowReadonlyDefaultMembers = false)
{
return new ShimSham(new[] {toWrap}, toMimic, isFuzzy, allowReadonlyDefaultMembers);
}
private ShimSham Create(Cow toWrap, bool fuzzy)
{
return new ShimSham(new object[] {toWrap}, toWrap.GetType(), fuzzy, false);
}
}
} | {'content_hash': '3be993827968f50a20a74bf66585bc95', 'timestamp': '', 'source': 'github', 'line_count': 442, 'max_line_length': 128, 'avg_line_length': 33.38235294117647, 'alnum_prop': 0.44737377160284647, 'repo_name': 'fluffynuts/PeanutButter', 'id': '29c0b381861e789688a8fd98d7945113a52567a7', 'size': '14757', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/Utils/PeanutButter.DuckTyping.Tests/Shimming/TestShimSham.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '384'}, {'name': 'C#', 'bytes': '4976711'}, {'name': 'Inno Setup', 'bytes': '1774'}, {'name': 'JavaScript', 'bytes': '18778'}, {'name': 'PowerShell', 'bytes': '2399'}, {'name': 'Shell', 'bytes': '741'}, {'name': 'TSQL', 'bytes': '20441'}, {'name': 'Visual Basic .NET', 'bytes': '253266'}]} |
var express = require('express');
var sag = require('sag');
var app = express();
app.use(express.bodyParser());
var couch = sag.server('localhost', '5984');
couch.setDatabase('dna', true, function(exists) {
if(exists) {
// the database was either just created or already existed
console.log('time to do work!');
}
else {
console.log('whoops, there was an error creating the db!');
}
});
app.get('/login', function(req, res){
var body = 'Hello World';
res.send(body);
});
app.post('/json', function(req, res){
console.log(req.body);
var request = req.body;
res.header("Access-Control-Allow-Origin", "*");
if(request.endpoint != undefined && request.process != undefined )
{
couch.post({
data :{
_id : "root/" + request.endpoint,
type : "process",
domain : "root",
endpoint : request.endpoint,
process : request.process
},
callback :function(resp, success) {
console.log(resp); //string
if(success)
{
res.end(JSON.stringify({status: 200, body: resp.body}));
}
else
{
res.end(JSON.stringify({status: resp._HTTP.status, body: resp.body}));
}
}
});
}
});
app.listen(3000);
console.log('Listening on port 3000'); | {'content_hash': 'c83ceb274e1bf1b400769fb4807a040b', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 75, 'avg_line_length': 22.72222222222222, 'alnum_prop': 0.6145069274653626, 'repo_name': 'omkarkhair/dna', 'id': '19f7b1562ab368da7af46ce10a9c4b2c8ba6085c', 'size': '1227', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dev/server.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2929'}]} |
<A Name="directAST"/>
## Example defining directly using AST
Defining flow directly using the AST. Additional DSL interfaces can be built by simply having them build the proper AST.
```javascript
var autoflow = require('autoflow');
function load(res, cb) { setTimeout(cb, 100, null, res + '-loaded'); }
function prefix(prefstr, str, cb) { setTimeout(cb, 100, null, prefstr + str); }
function postfix(str, poststr, cb) { setTimeout(cb, 100, null, str + poststr); }
function upper(str) { return str.toUpperCase(); }
var fn = autoflow();
var errors = fn.setAndValidateAST({
inParams: ['res', 'prefstr', 'poststr'],
tasks: [
{ f: load, a: ['res'], out: ['lres'] },
{ f: upper, a: ['lres'], out: ['ulres'], type: 'ret' },
{ f: prefix, a: ['prefstr', 'ulres'], out: ['plres'] },
{ f: postfix, a: ['plres', 'poststr'], out: ['plresp'] }
],
outTask: { a: ['plresp'] }
});
console.error('errors:', errors); // []
fn('foo', 'pre-', '-post', function cb(err, lres) {
console.error('err:', err); // null
console.error('lres:', lres); // pre-FOO-LOADED-post
});
```
## AST Definition
The abstract syntax tree or AST provided by autoflow represents the data necessary to define the flow. By abstracting this from the DSL, it allows new skins or interfaces to be developed without need to change the core engine.
The AST is normally created at parse time when the autoflow main function is called (or one of the alternate DSL's is called). This can be done a module load time such that after loading the autoflow defined flow function's AST is generated and ready to process eliminating parsing and validation overhead when it is invoked in the future. This has the added advantage that since validation has also been performed that additional syntax issues or incomplete flow defintion errors can be caught quickly.
After the flow function has been created, you can review the generated AST for a function by accessing the ast.
```javascript
var autoflow = require('autoflow');
var fn = autoflow('my-flow-name', 'paramName1, paramName2, cb -> err, outParamName1, outParamName2',
functionRefOrMethodStr, 'paramName1, cb -> err, outParamName2', // async cb task
functionRefOrMethodStr2, 'paramName2, paramName1 -> outParamName1' // sync task
);
console.error(fn.ast); // output the generated AST
```
The AST contains the following pieces:
```javascript
var ast = {
name: flowName,
inParams: [],
tasks: [],
outTask: {},
locals: {}
};
```
- **name** - string - represents the name of the flow or function that will be created. autoflow will use the name when generating events so you can monitor progress and performance and also when errors occur.
- **InParams** - array of strings - the flow input parameter names (excluding the callback param)
- **tasks** - array of task defintion objects - each containing:
- **f** - function reference or method string - async or sync function to be used for this task
- **a** - array of input parameter names (excluding the callback param)
- **out** - array of output parameter names (excluding the err parame)
- **type** - type of function determining how function is invoked and its output style - one of: ('cb', 'ret', 'promise', 'when')
- **name** - string - unique name for each task provided or generated by autoflow
- **OutTask** - task definition object specifying the flow's output style and parameters containing:
- **f** - will contain reference to the callback function at runtime
- **a** - parameters being passed as output from the flow
- **locals** - object provided which contains additional values that will become part of the autoflow variable space like input parameters but can be defined in advance at flow definition. This can be used to provide functions and objects to autoflow enabling string based DSL's. The global variables are already built-in, but any locals that are needed would be specified here.
## Plugins (optional requires which turn on additional functionality)
Additional functionality which is not enabled by default but available by requiring additional modules.
<a name="LogEvents"/>
### LogEvents - log autoflow progress to stderr
For convenience in debugging or in monitoring flow and performance, autoflow has a built-in plugin for easily logging progress to stderr which is loaded and activated calling the autoflow method `logEvents`. It can be specified to log globally for all autoflow functions or only for particular autoflow functions. You also may optionally listen to select events rather than all flow and task events.
```Javascript
var autoflow = require('autoflow');
autoflow.logEvents(); // turn on flow and task logging for all autoflow functions
// OR
autoflow.logEvents(myautoflowFn); // turn on flow and task logging for a specific function, repeat as needed
autoflow.LogEvents(myautoflowFn).logEvents(myautoflowFn2); // can also chain
// Both methods can also take an optional event wildcard to specify what you want to listen to
autoflow.logEvents('flow.*'); // turn on flow logging for all autoflow functions
autoflow.logEvents(myautoflowFn, 'task.*'); // turn on task logging for myautoflowFn
```
To turn off logging
```javascript
autoflow.logEvents(false); // turn off logging
```
Available Events that can be logged:
- flow.begin - flow execution has started (receives a flow env)
- flow.complete - flow execution has successfully completed (receives a flow env)
- flow.errored - flow execution has errored (receives a flow env)
- task.begin - task has started (receives task)
- task.complete - task has successfully complted (receives task)
- task.errored - task has errored (receives task)
### Automatic Promise Resolution for inputs
If you want to automatically resolve promises in autoflow without having to manually call `when` or `then`, autoflow provides a plugin which will detect the existence of a `then` method (indicating a promise) at runtime from any inputs to the flow and will internally create `when` tasks to resolve them before passing the values to other tasks. This built-in plugin is not loaded normally but is loaded by invoking the autoflow method `resolvePromises`. External plugins like `autoflow-deferred` and `autoflow-q` also enable this but also provide additional promise integration. See https://github.com/jeffbski/autoflow-deferred and https://github.com/jeffbski/autoflow-q
```Javascript
var autoflow = require('autoflow');
autoflow.resolvePromises(); // turn on automatic promise detection and resolution
```
### Track tasks - enable task tracking
Instead of only logging events to stderr (like LogEvents), this built-in plugin fires events that can be directly monitored. The LogEvent plugin uses this internally to get access to the metrics.
Enable this like the other built-in plugins using the method `trackTasks`
```javascript
var autoflow = require('autoflow');
autoflow.trackTasks(); // turn on flow and task tracking events
```
Available Events that can be consumed
- ast.defined - ast was defined (receives the ast)
- flow.begin - flow execution has started (receives a flow env)
- flow.complete - flow execution has successfully completed (receives a flow env)
- flow.errored - flow execution has errored (receives a flow env)
- task.begin - task has started (receives task)
- task.complete - task has successfully complted (receives task)
- task.errored - task has errored (receives task)
### EventCollector - simple event accumulator for debug use
When developing or debugging it is often useful to accumulate events and then interrogate them to verify operation, especially in testing.
To make this easier to accomplish, this plugin provides a simple event accumulator for development use. Note that this accumulator is designed for short term debug use, as it will continue to accumulate events and does not have any size restrictions, it should not be used in production since it will just continue to grow in size unless manually cleared.
```javascript
var autoflow = require('autoflow');
var collector = autoflow.createEventCollector();
collector.capture(); // capture all flow and task events for all autoflow flows
collector.capture('flow.*'); // capture all flow events for all autoflow flows
collector.capture(flowFn, 'task.*'); // capture task events on a flow
collector.capture(flowFn, 'flow.*'); // add capture flow events on a flow
var events = collector.list(); // retrieve the list of events
collector.clear(); // clear the list of events;
```
### External Plugins
- https://github.com/jeffbski/autoflow-deferred - integrates jQuery style Deferred/Promises with autoflow, providing automatic promise resolution and optional usage for autoflow functions where by calling without a callback returns a promise.
- https://github.com/jeffbski/autoflow-q - integrates Q-style Deferred/Promises with autoflow, providing automatic promise resolution and optional usage for autoflow functions where by calling without a callback returns a promise.
| {'content_hash': 'a15b49217665ccab73c0e8d2f42a60b4', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 672, 'avg_line_length': 52.49132947976879, 'alnum_prop': 0.746173328928532, 'repo_name': 'jeffbski/autoflow', 'id': '530b9ed7b92bfa128cdb5f7a4a18af078b517c22', 'size': '9102', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/advanced.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8977'}, {'name': 'JavaScript', 'bytes': '168927'}]} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.funger.bbks"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- 网络检查 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 创建快捷方式权限 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!-- <uses-permission android:name="android.permission.CALL_PHONE" /> -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Vpon所需权限 -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="false" />
<application
android:name="com.funger.bbks.app.AppContext"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name">
<activity
android:name="com.funger.bbks.WelcomeActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.funger.bbks.MainActivity"/>
<activity android:name="com.funger.bbks.LoginActivity"/>
<activity android:name="com.funger.bbks.LoginDialog" android:theme="@style/Dialog"/>
<activity android:name="com.funger.bbks.TweetPub"/>
<activity android:name="com.funger.bbks.BookDetailActivity"/>
<!-- ebook -->
<activity android:name="com.funger.ebook.ac.Read" android:configChanges="keyboardHidden|orientation" android:screenOrientation="portrait" />
<activity android:name="com.funger.ebook.ac.InActivity" android:screenOrientation="portrait" />
<activity android:name="com.funger.ebook.ac.BookListActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar" android:configChanges="keyboardHidden|orientation"/>
</application>
</manifest> | {'content_hash': '0e1466eaa9b19861096e49fb20d5453b', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 207, 'avg_line_length': 48.7027027027027, 'alnum_prop': 0.6859045504994451, 'repo_name': 'cncduLee/bbks-andr', 'id': '97c2aca6149d2dd92e6cd0b5b29068b1326c071d', 'size': '3636', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AndroidManifest.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '700323'}]} |
"""Support for the DOODS service."""
import io
import logging
import time
from PIL import Image, ImageDraw
from pydoods import PyDOODS
import voluptuous as vol
from homeassistant.components.image_processing import (
CONF_CONFIDENCE,
CONF_ENTITY_ID,
CONF_NAME,
CONF_SOURCE,
PLATFORM_SCHEMA,
ImageProcessingEntity,
)
from homeassistant.const import CONF_TIMEOUT
from homeassistant.core import split_entity_id
from homeassistant.helpers import template
import homeassistant.helpers.config_validation as cv
from homeassistant.util.pil import draw_box
_LOGGER = logging.getLogger(__name__)
ATTR_MATCHES = "matches"
ATTR_SUMMARY = "summary"
ATTR_TOTAL_MATCHES = "total_matches"
CONF_URL = "url"
CONF_AUTH_KEY = "auth_key"
CONF_DETECTOR = "detector"
CONF_LABELS = "labels"
CONF_AREA = "area"
CONF_COVERS = "covers"
CONF_TOP = "top"
CONF_BOTTOM = "bottom"
CONF_RIGHT = "right"
CONF_LEFT = "left"
CONF_FILE_OUT = "file_out"
AREA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_BOTTOM, default=1): cv.small_float,
vol.Optional(CONF_LEFT, default=0): cv.small_float,
vol.Optional(CONF_RIGHT, default=1): cv.small_float,
vol.Optional(CONF_TOP, default=0): cv.small_float,
vol.Optional(CONF_COVERS, default=True): cv.boolean,
}
)
LABEL_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_AREA): AREA_SCHEMA,
vol.Optional(CONF_CONFIDENCE): vol.Range(min=0, max=100),
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_DETECTOR): cv.string,
vol.Required(CONF_TIMEOUT, default=90): cv.positive_int,
vol.Optional(CONF_AUTH_KEY, default=""): cv.string,
vol.Optional(CONF_FILE_OUT, default=[]): vol.All(cv.ensure_list, [cv.template]),
vol.Optional(CONF_CONFIDENCE, default=0.0): vol.Range(min=0, max=100),
vol.Optional(CONF_LABELS, default=[]): vol.All(
cv.ensure_list, [vol.Any(cv.string, LABEL_SCHEMA)]
),
vol.Optional(CONF_AREA): AREA_SCHEMA,
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Doods client."""
url = config[CONF_URL]
auth_key = config[CONF_AUTH_KEY]
detector_name = config[CONF_DETECTOR]
timeout = config[CONF_TIMEOUT]
doods = PyDOODS(url, auth_key, timeout)
response = doods.get_detectors()
if not isinstance(response, dict):
_LOGGER.warning("Could not connect to doods server: %s", url)
return
detector = {}
for server_detector in response["detectors"]:
if server_detector["name"] == detector_name:
detector = server_detector
break
if not detector:
_LOGGER.warning(
"Detector %s is not supported by doods server %s", detector_name, url
)
return
entities = []
for camera in config[CONF_SOURCE]:
entities.append(
Doods(
hass,
camera[CONF_ENTITY_ID],
camera.get(CONF_NAME),
doods,
detector,
config,
)
)
add_entities(entities)
class Doods(ImageProcessingEntity):
"""Doods image processing service client."""
def __init__(self, hass, camera_entity, name, doods, detector, config):
"""Initialize the DOODS entity."""
self.hass = hass
self._camera_entity = camera_entity
if name:
self._name = name
else:
name = split_entity_id(camera_entity)[1]
self._name = f"Doods {name}"
self._doods = doods
self._file_out = config[CONF_FILE_OUT]
self._detector_name = detector["name"]
# detector config and aspect ratio
self._width = None
self._height = None
self._aspect = None
if detector["width"] and detector["height"]:
self._width = detector["width"]
self._height = detector["height"]
self._aspect = self._width / self._height
# the base confidence
dconfig = {}
confidence = config[CONF_CONFIDENCE]
# handle labels and specific detection areas
labels = config[CONF_LABELS]
self._label_areas = {}
self._label_covers = {}
for label in labels:
if isinstance(label, dict):
label_name = label[CONF_NAME]
if label_name not in detector["labels"] and label_name != "*":
_LOGGER.warning("Detector does not support label %s", label_name)
continue
# If label confidence is not specified, use global confidence
label_confidence = label.get(CONF_CONFIDENCE)
if not label_confidence:
label_confidence = confidence
if label_name not in dconfig or dconfig[label_name] > label_confidence:
dconfig[label_name] = label_confidence
# Label area
label_area = label.get(CONF_AREA)
self._label_areas[label_name] = [0, 0, 1, 1]
self._label_covers[label_name] = True
if label_area:
self._label_areas[label_name] = [
label_area[CONF_TOP],
label_area[CONF_LEFT],
label_area[CONF_BOTTOM],
label_area[CONF_RIGHT],
]
self._label_covers[label_name] = label_area[CONF_COVERS]
else:
if label not in detector["labels"] and label != "*":
_LOGGER.warning("Detector does not support label %s", label)
continue
self._label_areas[label] = [0, 0, 1, 1]
self._label_covers[label] = True
if label not in dconfig or dconfig[label] > confidence:
dconfig[label] = confidence
if not dconfig:
dconfig["*"] = confidence
# Handle global detection area
self._area = [0, 0, 1, 1]
self._covers = True
area_config = config.get(CONF_AREA)
if area_config:
self._area = [
area_config[CONF_TOP],
area_config[CONF_LEFT],
area_config[CONF_BOTTOM],
area_config[CONF_RIGHT],
]
self._covers = area_config[CONF_COVERS]
template.attach(hass, self._file_out)
self._dconfig = dconfig
self._matches = {}
self._total_matches = 0
self._last_image = None
@property
def camera_entity(self):
"""Return camera entity id from process pictures."""
return self._camera_entity
@property
def name(self):
"""Return the name of the image processor."""
return self._name
@property
def state(self):
"""Return the state of the entity."""
return self._total_matches
@property
def device_state_attributes(self):
"""Return device specific state attributes."""
return {
ATTR_MATCHES: self._matches,
ATTR_SUMMARY: {
label: len(values) for label, values in self._matches.items()
},
ATTR_TOTAL_MATCHES: self._total_matches,
}
def _save_image(self, image, matches, paths):
img = Image.open(io.BytesIO(bytearray(image))).convert("RGB")
img_width, img_height = img.size
draw = ImageDraw.Draw(img)
# Draw custom global region/area
if self._area != [0, 0, 1, 1]:
draw_box(
draw, self._area, img_width, img_height, "Detection Area", (0, 255, 255)
)
for label, values in matches.items():
# Draw custom label regions/areas
if label in self._label_areas and self._label_areas[label] != [0, 0, 1, 1]:
box_label = f"{label.capitalize()} Detection Area"
draw_box(
draw,
self._label_areas[label],
img_width,
img_height,
box_label,
(0, 255, 0),
)
# Draw detected objects
for instance in values:
box_label = f'{label} {instance["score"]:.1f}%'
# Already scaled, use 1 for width and height
draw_box(
draw,
instance["box"],
img_width,
img_height,
box_label,
(255, 255, 0),
)
for path in paths:
_LOGGER.info("Saving results image to %s", path)
img.save(path)
def process_image(self, image):
"""Process the image."""
img = Image.open(io.BytesIO(bytearray(image)))
img_width, img_height = img.size
if self._aspect and abs((img_width / img_height) - self._aspect) > 0.1:
_LOGGER.debug(
"The image aspect: %s and the detector aspect: %s differ by more than 0.1",
(img_width / img_height),
self._aspect,
)
# Run detection
start = time.monotonic()
response = self._doods.detect(
image, dconfig=self._dconfig, detector_name=self._detector_name
)
_LOGGER.debug(
"doods detect: %s response: %s duration: %s",
self._dconfig,
response,
time.monotonic() - start,
)
matches = {}
total_matches = 0
if not response or "error" in response:
if "error" in response:
_LOGGER.error(response["error"])
self._matches = matches
self._total_matches = total_matches
return
for detection in response["detections"]:
score = detection["confidence"]
boxes = [
detection["top"],
detection["left"],
detection["bottom"],
detection["right"],
]
label = detection["label"]
# Exclude unlisted labels
if "*" not in self._dconfig and label not in self._dconfig:
continue
# Exclude matches outside global area definition
if self._covers:
if (
boxes[0] < self._area[0]
or boxes[1] < self._area[1]
or boxes[2] > self._area[2]
or boxes[3] > self._area[3]
):
continue
else:
if (
boxes[0] > self._area[2]
or boxes[1] > self._area[3]
or boxes[2] < self._area[0]
or boxes[3] < self._area[1]
):
continue
# Exclude matches outside label specific area definition
if self._label_areas.get(label):
if self._label_covers[label]:
if (
boxes[0] < self._label_areas[label][0]
or boxes[1] < self._label_areas[label][1]
or boxes[2] > self._label_areas[label][2]
or boxes[3] > self._label_areas[label][3]
):
continue
else:
if (
boxes[0] > self._label_areas[label][2]
or boxes[1] > self._label_areas[label][3]
or boxes[2] < self._label_areas[label][0]
or boxes[3] < self._label_areas[label][1]
):
continue
if label not in matches:
matches[label] = []
matches[label].append({"score": float(score), "box": boxes})
total_matches += 1
# Save Images
if total_matches and self._file_out:
paths = []
for path_template in self._file_out:
if isinstance(path_template, template.Template):
paths.append(
path_template.render(camera_entity=self._camera_entity)
)
else:
paths.append(path_template)
self._save_image(image, matches, paths)
self._matches = matches
self._total_matches = total_matches
| {'content_hash': '29a752ec451843b1bddc6d53877f9c6a', 'timestamp': '', 'source': 'github', 'line_count': 378, 'max_line_length': 91, 'avg_line_length': 33.34656084656085, 'alnum_prop': 0.5181277270924236, 'repo_name': 'postlund/home-assistant', 'id': '65a32938140ef1a41e104023f55779296562ed3f', 'size': '12605', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dev', 'path': 'homeassistant/components/doods/image_processing.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '20215859'}, {'name': 'Shell', 'bytes': '6663'}]} |
Contributing
=========
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. [Add tests for your changes](https://github.com/djoos-cookbooks/newrelic/blob/master/TESTING.md)
4. Push your changes to your feature branch (`git push origin my-new-feature`)
5. Create a new PR (Pull Request)
## Testing
Contributions will only be accepted if they are fully tested as specified in [TESTING.md](https://github.com/djoos-cookbooks/newrelic/blob/master/TESTING.md).
## metadata.rb
Please do not modify the version number in the metadata.rb; not all changes to the cookbook may be merged and released in the same version. We will handle the version updates during the release process.
| {'content_hash': 'bce1aeda2c0b3aa5b4d2ab7ab20412ca', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 202, 'avg_line_length': 50.93333333333333, 'alnum_prop': 0.7604712041884817, 'repo_name': 'djoos-cookbooks/newrelic', 'id': '032bcc1f9acc7185042f27d79860c6a144e99156', 'size': '764', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CONTRIBUTING.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '78783'}, {'name': 'JavaScript', 'bytes': '1618'}, {'name': 'Ruby', 'bytes': '138171'}]} |
/*
+----------------------------------------------------------------------+
| PHP-OpenCV |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: HaiHao Zhou <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "../../../php_opencv.h"
#include "../../../opencv_exception.h"
#include "opencv_type.h"
#include <algorithm>
#include <iostream>
zend_class_entry *opencv_point_ce;
zend_class_entry *opencv_scalar_ce;
zend_class_entry *opencv_size_ce;
zend_class_entry *opencv_rect_ce;
zend_class_entry *opencv_rotated_rect_ce;
/**
* -----------------------------------【CV\Point】--------------------------------------
*
* -------------------------------------------------------------------------------------
*/
zend_object_handlers opencv_point_object_handlers;
/**
* Point __construct
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_point, __construct)
{
long x=0, y=0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ll", &x, &y) == FAILURE) {
RETURN_NULL();
}
opencv_point_object *obj = Z_PHP_POINT_OBJ_P(getThis());
Point point = Point((int)x, (int)y);
obj->point = new Point(point);
opencv_point_update_property_by_c_point(getThis(),obj->point);
}
void opencv_point_update_property_by_c_point(zval *z, Point *point){
zend_update_property_long(opencv_point_ce, z, "x", sizeof("x")-1, point->x);
zend_update_property_long(opencv_point_ce, z, "y", sizeof("y")-1, point->y);
}
/**
* print Point data
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_point, print)
{
opencv_point_object *obj = Z_PHP_POINT_OBJ_P(getThis());
std::cout <<*(obj->point)<< std::endl;
RETURN_NULL();
}
/**
* opencv_point_methods[]
*/
const zend_function_entry opencv_point_methods[] = {
PHP_ME(opencv_point, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(opencv_point, print, NULL, ZEND_ACC_PUBLIC) //todo why Point print method can effect Mat print method
PHP_FE_END
};
/* }}} */
zend_object* opencv_point_create_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_point_object);
opencv_point_object *obj = (opencv_point_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_point_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_point_object_handlers;
return &obj->std;
}
void opencv_point_free_obj(zend_object *object)
{
opencv_point_object *obj;
obj = get_point_obj(object);
delete obj->point;
zend_object_std_dtor(object);
}
/**
* Point Class write_property
* @param object
* @param member
* @param value
* @param cache_slot
*/
void opencv_point_write_property(zval *object, zval *member, zval *value, void **cache_slot){
zend_string *str = zval_get_string(member);
char *memberName=ZSTR_VAL(str);
opencv_point_object *obj = Z_PHP_POINT_OBJ_P(object);
if(strcmp(memberName, "x") == 0 && obj->point->x!=(int)zval_get_long(value)){
obj->point->x=(int)zval_get_long(value);
}else if(strcmp(memberName, "y") == 0 && obj->point->y!=(int)zval_get_long(value)){
obj->point->y=(int)zval_get_long(value);
}
zend_string_release(str);//free zend_string not memberName(zend_string->val)
std_object_handlers.write_property(object,member,value,cache_slot);
}
/**
* Point Init
*/
void opencv_point_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_NS, "Point", opencv_point_methods);
opencv_point_ce = zend_register_internal_class(&ce);
opencv_point_ce->create_object = opencv_point_create_handler;
memcpy(&opencv_point_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_point_object_handlers.clone_obj = NULL;
opencv_point_object_handlers.write_property = opencv_point_write_property;
opencv_point_object_handlers.free_obj = opencv_point_free_obj;
}
/**
* -----------------------------------【CV\Scalar】--------------------------------------
*
* -------------------------------------------------------------------------------------
*/
zend_object_handlers opencv_scalar_object_handlers;
zend_object* opencv_scalar_create_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_scalar_object);
opencv_scalar_object *obj = (opencv_scalar_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_scalar_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_scalar_object_handlers;
return &obj->std;
}
void opencv_scalar_free_obj(zend_object *object)
{
opencv_scalar_object *obj;
obj = get_scalar_obj(object);
delete obj->scalar;
zend_object_std_dtor(object);
}
void opencv_scalar_update_property_by_c_scalar(zval *z,Scalar *scalar){
zval val;
array_init(&val);
add_next_index_double(&val,scalar->val[0]);
add_next_index_double(&val,scalar->val[1]);
add_next_index_double(&val,scalar->val[2]);
add_next_index_double(&val,scalar->val[3]);
zend_update_property(opencv_scalar_ce, z, "val", sizeof("val")-1, &val);
/**
* 数组val在array_init()后refcount=1,
* 插入成员属性zend_update_property()会自动加一次,变为2,
* 对象销毁后只会减1,需要要在zend_update_property()后主动减一次引用
*/
Z_DELREF(val);
}
/**
* Scalar __construct
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_scalar, __construct)
{
double value1 = 0, value2 = 0, value3 = 0, value4 = 0;//value: 8bit=0~255 16bit=0~65535...
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|dddd", &value1, &value2, &value3, &value4) == FAILURE) {
RETURN_NULL();
}
opencv_scalar_object *obj = Z_PHP_SCALAR_OBJ_P(getThis());
Scalar scalar = Scalar((int)value1, (int)value2, (int)value3, (int)value4);
obj->scalar = new Scalar(scalar);
opencv_scalar_update_property_by_c_scalar(getThis(), obj->scalar);
}
/**
* print Scalar data
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_scalar, print)
{
opencv_scalar_object *obj = Z_PHP_SCALAR_OBJ_P(getThis());
std::cout <<*(obj->scalar)<< std::endl;
RETURN_NULL();
}
/**
* opencv_scalar_methods[]
*/
const zend_function_entry opencv_scalar_methods[] = {
PHP_ME(opencv_scalar, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(opencv_scalar, print, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/**
* Scalar Init
*/
void opencv_scalar_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_NS, "Scalar", opencv_scalar_methods);
opencv_scalar_ce = zend_register_internal_class(&ce);
opencv_scalar_ce->create_object = opencv_scalar_create_handler;
memcpy(&opencv_scalar_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_scalar_object_handlers.clone_obj = NULL;
opencv_scalar_object_handlers.free_obj = opencv_scalar_free_obj;
}
//-----------------------------------【CV\Size】---------------------------------------
//
//-------------------------------------------------------------------------------------
zend_object_handlers opencv_size_object_handlers;
zend_object* opencv_size_create_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_size_object);
opencv_size_object *obj = (opencv_size_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_size_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_size_object_handlers;
return &obj->std;
}
void opencv_size_free_obj(zend_object *object)
{
opencv_size_object *obj;
obj = get_size_obj(object);
delete obj->size;
zend_object_std_dtor(object);
}
void opencv_size_update_property_by_c_size(zval *z, Size *size){
zend_update_property_long(opencv_size_ce, z, "width", sizeof("width")-1, size->width);
zend_update_property_long(opencv_size_ce, z, "height", sizeof("height")-1, size->height);
}
/**
* Size __construct
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_size, __construct)
{
long width=0, height = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ll", &width, &height) == FAILURE) {
RETURN_NULL();
}
opencv_size_object *obj = Z_PHP_SIZE_OBJ_P(getThis());
Size size = Size((int)width, (int)height);
obj->size = new Size(size);
opencv_size_update_property_by_c_size(getThis(), obj->size);
}
/**
* print Size data
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_size, print)
{
opencv_size_object *obj = Z_PHP_SIZE_OBJ_P(getThis());
std::cout <<*(obj->size)<< std::endl;
RETURN_NULL();
}
/**
* opencv_size_methods[]
*/
const zend_function_entry opencv_size_methods[] = {
PHP_ME(opencv_size, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(opencv_size, print, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/**
* Size Class write_property
* @param object
* @param member
* @param value
* @param cache_slot
*/
void opencv_size_write_property(zval *object, zval *member, zval *value, void **cache_slot){
zend_string *str = zval_get_string(member);
char *memberName=ZSTR_VAL(str);
opencv_size_object *obj = Z_PHP_SIZE_OBJ_P(object);
if(strcmp(memberName, "width") == 0 && obj->size->width!=(int)zval_get_long(value)){
obj->size->width=(int)zval_get_long(value);
}else if(strcmp(memberName, "height") == 0 && obj->size->height!=(int)zval_get_long(value)){
obj->size->height=(int)zval_get_long(value);
}
zend_string_release(str);//free zend_string not memberName(zend_string->val)
std_object_handlers.write_property(object,member,value,cache_slot);
}
/**
* Size Init
*/
void opencv_size_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_NS, "Size", opencv_size_methods);
opencv_size_ce = zend_register_internal_class(&ce);
opencv_size_ce->create_object = opencv_size_create_handler;
memcpy(&opencv_size_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_size_object_handlers.clone_obj = NULL;
opencv_size_object_handlers.write_property = opencv_size_write_property;
opencv_size_object_handlers.free_obj = opencv_size_free_obj;
}
//-----------------------------------【CV\Rect】---------------------------------------
//
//-------------------------------------------------------------------------------------
zend_object_handlers opencv_rect_object_handlers;
zend_object* opencv_rect_create_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_rect_object);
opencv_rect_object *obj = (opencv_rect_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_rect_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_rect_object_handlers;
return &obj->std;
}
void opencv_rect_free_obj(zend_object *object)
{
opencv_rect_object *obj;
obj = get_rect_obj(object);
delete obj->rect;
zend_object_std_dtor(object);
}
void opencv_rect_update_property_by_c_rect(zval *z, Rect *rect){
zend_update_property_long(opencv_rect_ce, z, "x", sizeof("x")-1, rect->x);
zend_update_property_long(opencv_rect_ce, z, "y", sizeof("y")-1, rect->y);
zend_update_property_long(opencv_rect_ce, z, "width", sizeof("width")-1, rect->width);
zend_update_property_long(opencv_rect_ce, z, "height", sizeof("height")-1, rect->height);
}
/**
* Rect __construct
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, __construct)
{
long x = 0, y = 0, width = 0, height = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|llll", &x, &y, &width, &height) == FAILURE) {
RETURN_NULL();
}
opencv_rect_object *obj = Z_PHP_RECT_OBJ_P(getThis());
Rect rect = Rect((int)x, (int)y, (int)width, (int)height);
obj->rect = new Rect(rect);
opencv_rect_update_property_by_c_rect(getThis(),obj->rect);
}
/**
* print Rect data
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, print)
{
opencv_rect_object *obj = Z_PHP_RECT_OBJ_P(getThis());
std::cout <<*(obj->rect)<< std::endl;
RETURN_NULL();
}
/**
* ! the top-left corner
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, tl)
{
opencv_rect_object *rect_obj = Z_PHP_RECT_OBJ_P(getThis());
zval point_zval;
object_init_ex(&point_zval,opencv_point_ce);
opencv_point_object *point_obj = Z_PHP_POINT_OBJ_P(&point_zval);
point_obj->point = new Point(rect_obj->rect->tl());
opencv_point_update_property_by_c_point(&point_zval,point_obj->point);
RETURN_ZVAL(&point_zval,0,0); //return php Point object
}
/**
* ! the bottom-right corner
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, br)
{
opencv_rect_object *rect_obj = Z_PHP_RECT_OBJ_P(getThis());
zval point_zval;
object_init_ex(&point_zval,opencv_point_ce);
opencv_point_object *point_obj = Z_PHP_POINT_OBJ_P(&point_zval);
point_obj->point = new Point(rect_obj->rect->br());
opencv_point_update_property_by_c_point(&point_zval,point_obj->point);
RETURN_ZVAL(&point_zval,0,0); //return php Point object
}
/**
* size (width, height) of the rectangle
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, size)
{
opencv_rect_object *rect_obj = Z_PHP_RECT_OBJ_P(getThis());
zval size_zval;
object_init_ex(&size_zval,opencv_size_ce);
opencv_size_object *size_obj = Z_PHP_SIZE_OBJ_P(&size_zval);
size_obj->size = new Size(rect_obj->rect->size());
opencv_size_update_property_by_c_size(&size_zval,size_obj->size);
RETURN_ZVAL(&size_zval,0,0); //return php Point object
}
/**
* ! area (width*height) of the rectangle
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rect, area)
{
opencv_rect_object *rect_obj = Z_PHP_RECT_OBJ_P(getThis());
long area = rect_obj->rect->area();
RETURN_LONG(area);
}
/**
* opencv_rect_methods[]
*/
const zend_function_entry opencv_rect_methods[] = {
PHP_ME(opencv_rect, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(opencv_rect, print, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_rect, tl, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_rect, br, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_rect, size, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_rect, area, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/**
* Rect Class write_property
* @param object
* @param member
* @param value
* @param cache_slot
*/
void opencv_rect_write_property(zval *object, zval *member, zval *value, void **cache_slot){
zend_string *str = zval_get_string(member);
char *memberName=ZSTR_VAL(str);
opencv_rect_object *obj = Z_PHP_RECT_OBJ_P(object);
if(strcmp(memberName, "x") == 0 && obj->rect->x!=(int)zval_get_long(value)){
obj->rect->x=(int)zval_get_long(value);
}else if(strcmp(memberName, "y") == 0 && obj->rect->y!=(int)zval_get_long(value)){
obj->rect->y=(int)zval_get_long(value);
}else if(strcmp(memberName, "width") == 0 && obj->rect->width!=(int)zval_get_long(value)){
obj->rect->width=(int)zval_get_long(value);
}else if(strcmp(memberName, "height") == 0 && obj->rect->height!=(int)zval_get_long(value)){
obj->rect->height=(int)zval_get_long(value);
}
zend_string_release(str);//free zend_string not memberName(zend_string->val)
std_object_handlers.write_property(object,member,value,cache_slot);
}
/**
* Rect Init
*/
void opencv_rect_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_NS, "Rect", opencv_rect_methods);
opencv_rect_ce = zend_register_internal_class(&ce);
opencv_rect_ce->create_object = opencv_rect_create_handler;
memcpy(&opencv_rect_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_rect_object_handlers.clone_obj = NULL;
opencv_rect_object_handlers.write_property = opencv_rect_write_property;
opencv_rect_object_handlers.free_obj = opencv_rect_free_obj;
}
//-----------------------------------【CV\RotatedRect】--------------------------------
//
//-------------------------------------------------------------------------------------
zend_object_handlers opencv_rotated_rect_object_handlers;
zend_object* opencv_rotated_rect_create_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_rotated_rect_object);
opencv_rotated_rect_object *obj = (opencv_rotated_rect_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_rotated_rect_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_rotated_rect_object_handlers;
return &obj->std;
}
/**
* //todo $rotatedRect->property = &$a
* RotatedRect Class write_property
* @param object
* @param member
* @param value
* @param cache_slot
*/
void opencv_rotated_rect_write_property(zval *object, zval *member, zval *value, void **cache_slot){
zend_string *str = zval_get_string(member);
char *memberName = ZSTR_VAL(str);
opencv_rotated_rect_object *obj = Z_PHP_ROTATED_RECT_OBJ_P(object);
if(strcmp(memberName, "angle") == 0 && obj->rotatedRect->angle != (int)zval_get_long(value)){
obj->rotatedRect->angle = (float)zval_get_long(value);
}else if(strcmp(memberName, "center") == 0 ){
if(Z_TYPE_P(value) == IS_OBJECT && Z_OBJCE_P(value) == opencv_point_ce){
opencv_point_object *value_object = Z_PHP_POINT_OBJ_P(value);
if(Point2f(*value_object->point) != obj->rotatedRect->center){
obj->rotatedRect->center = Point2f(*value_object->point);
}
}else{
opencv_throw_exception("set property center only expect param is Point object.");
}
}else if(strcmp(memberName, "size") == 0 ){
if(Z_TYPE_P(value) == IS_OBJECT && Z_OBJCE_P(value) == opencv_size_ce){
opencv_size_object *value_object = Z_PHP_SIZE_OBJ_P(value);
if(Size2f(*value_object->size) != obj->rotatedRect->size){
obj->rotatedRect->size = Size2f(*value_object->size);
}
}else{
opencv_throw_exception("set property size only expect param is Size object.");
}
}
zend_string_release(str);//free zend_string not memberName(zend_string->val)
std_object_handlers.write_property(object,member,value,cache_slot);
}
void opencv_rotated_rect_free_obj(zend_object *object)
{
opencv_rotated_rect_object *obj;
obj = get_rotated_rect_obj(object);
delete obj->rotatedRect;
zend_object_std_dtor(object);
}
void opencv_rotated_rect_update_property_by_c_rotated_rect(zval *z, RotatedRect *rotatedRect){
//RotatedRect->angle
zend_update_property_double(opencv_rotated_rect_ce, z, "angle", sizeof("angle")-1, rotatedRect->angle);
//RotatedRect->center
zval center_zval;
object_init_ex(¢er_zval, opencv_point_ce);
opencv_point_object *center_object = Z_PHP_POINT_OBJ_P(¢er_zval);
center_object->point = new Point(rotatedRect->center.x,rotatedRect->center.y);
opencv_point_update_property_by_c_point(¢er_zval, center_object->point);
zend_update_property(opencv_rotated_rect_ce, z, "center", sizeof("center")-1, ¢er_zval);
//RotatedRect->size
zval size_zval;
object_init_ex(&size_zval, opencv_size_ce);
opencv_size_object *size_object = Z_PHP_SIZE_OBJ_P(&size_zval);
size_object->size = new Size(rotatedRect->size);
opencv_size_update_property_by_c_size(&size_zval, size_object->size);
zend_update_property(opencv_rotated_rect_ce, z, "size", sizeof("size")-1, &size_zval);
/**
* 数组center_zval在object_init_ex()后refcount=1,
* 插入成员属性zend_update_property()会自动加一次,变为2,
* 对象销毁后只会减1,需要要在zend_update_property()后主动减一次引用
*/
Z_DELREF(center_zval);
Z_DELREF(size_zval);
}
/**
* todo center is Point2f and size is Size2f
* RotatedRect __construct
* @param execute_data
* @param return_value
*/
PHP_METHOD(opencv_rotated_rect, __construct)
{
zval *center_zval = NULL, *size_zval;
double angle = 0.0;
Point center = Point();
Size size = Size();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|OOd",
¢er_zval, opencv_point_ce,
&size_zval, opencv_size_ce,
&angle) == FAILURE) {
RETURN_NULL();
}
if(center_zval != NULL){
opencv_point_object *center_object = Z_PHP_POINT_OBJ_P(center_zval);
center = *center_object->point;
}
if(size_zval != NULL){
opencv_size_object *size_object = Z_PHP_SIZE_OBJ_P(size_zval);
size = *size_object->size;
}
opencv_rotated_rect_object *obj = Z_PHP_ROTATED_RECT_OBJ_P(getThis());
obj->rotatedRect = new RotatedRect(center, size, (float)angle);
opencv_rotated_rect_update_property_by_c_rotated_rect(getThis(), obj->rotatedRect);
}
PHP_METHOD(opencv_rotated_rect, points)
{
opencv_rotated_rect_object *this_object = Z_PHP_ROTATED_RECT_OBJ_P(getThis());
cv::Point2f pts[4];
this_object->rotatedRect->points(pts);
zval instance;
array_init(&instance);
for (int i = 0; i < 4; i++) {
zval OPENCV_CONNECT(point_zval,i);
object_init_ex(&OPENCV_CONNECT(point_zval,i), opencv_point_ce);
Z_PHP_POINT_OBJ_P(&OPENCV_CONNECT(point_zval,i))->point = new Point(pts[i]);
opencv_point_update_property_by_c_point(&OPENCV_CONNECT(point_zval,i), Z_PHP_POINT_OBJ_P(&OPENCV_CONNECT(point_zval,i))->point);
add_next_index_zval(&instance,&OPENCV_CONNECT(point_zval,i));
}
RETURN_ZVAL(&instance,0,0);
}
/**
* opencv_rect_methods[]
*/
const zend_function_entry opencv_rotated_rect_methods[] = {
PHP_ME(opencv_rotated_rect, __construct, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(opencv_rotated_rect, points, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
void opencv_rotated_rect_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_NS, "RotatedRect", opencv_rotated_rect_methods);
opencv_rotated_rect_ce = zend_register_internal_class(&ce);
opencv_rotated_rect_ce->create_object = opencv_rotated_rect_create_handler;
memcpy(&opencv_rotated_rect_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_rotated_rect_object_handlers.clone_obj = NULL;
opencv_rotated_rect_object_handlers.write_property = opencv_rotated_rect_write_property;
opencv_rotated_rect_object_handlers.free_obj = opencv_rotated_rect_free_obj;
}
/**
* Type Init
*/
void opencv_type_init(int module_number){
opencv_point_init(module_number);
opencv_scalar_init(module_number);
opencv_size_init(module_number);
opencv_rect_init(module_number);
opencv_rotated_rect_init(module_number);
} | {'content_hash': '60f0fcd721d614c3caaad80efc3a0520', 'timestamp': '', 'source': 'github', 'line_count': 747, 'max_line_length': 136, 'avg_line_length': 32.07095046854083, 'alnum_prop': 0.6191092373836456, 'repo_name': 'hihozhou/php-opencv', 'id': '1c8697d12a67f3ce51d165d497c2913f675e4eff', 'size': '24145', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/opencv2/core/opencv_type.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '32703'}, {'name': 'C++', 'bytes': '250862'}, {'name': 'Dockerfile', 'bytes': '424'}, {'name': 'JavaScript', 'bytes': '2572'}, {'name': 'M4', 'bytes': '2951'}, {'name': 'PHP', 'bytes': '17304'}, {'name': 'Shell', 'bytes': '2007'}]} |
package org.hawkular.metrics.core.impl.cassandra;
import static java.util.stream.Collectors.toMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import org.hawkular.metrics.core.api.AggregationTemplate;
import org.hawkular.metrics.core.api.Availability;
import org.hawkular.metrics.core.api.AvailabilityMetric;
import org.hawkular.metrics.core.api.Counter;
import org.hawkular.metrics.core.api.Interval;
import org.hawkular.metrics.core.api.Metric;
import org.hawkular.metrics.core.api.MetricData;
import org.hawkular.metrics.core.api.MetricId;
import org.hawkular.metrics.core.api.MetricType;
import org.hawkular.metrics.core.api.NumericData;
import org.hawkular.metrics.core.api.NumericMetric;
import org.hawkular.metrics.core.api.Retention;
import org.hawkular.metrics.core.api.RetentionSettings;
import org.hawkular.metrics.core.api.Tenant;
import org.hawkular.metrics.core.api.TimeUUIDUtils;
import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSetFuture;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.TupleType;
import com.datastax.driver.core.TupleValue;
import com.datastax.driver.core.UDTValue;
import com.datastax.driver.core.UserType;
import com.datastax.driver.core.utils.UUIDs;
/**
*
* @author John Sanda
*/
public class DataAccessImpl implements DataAccess {
private Session session;
private PreparedStatement insertTenant;
private PreparedStatement findAllTenantIds;
private PreparedStatement findTenant;
private PreparedStatement insertIntoMetricsIndex;
private PreparedStatement findMetric;
private PreparedStatement addMetricTagsToDataTable;
private PreparedStatement addMetadataAndDataRetention;
private PreparedStatement deleteMetricTagsFromDataTable;
private PreparedStatement insertNumericData;
private PreparedStatement findNumericDataByDateRangeExclusive;
private PreparedStatement findNumericDataWithWriteTimeByDateRangeExclusive;
private PreparedStatement findNumericDataByDateRangeInclusive;
private PreparedStatement findNumericDataWithWriteTimeByDateRangeInclusive;
private PreparedStatement findAvailabilityByDateRangeInclusive;
private PreparedStatement deleteNumericMetric;
private PreparedStatement findNumericMetrics;
private PreparedStatement updateCounter;
private PreparedStatement findCountersByGroup;
private PreparedStatement findCountersByGroupAndName;
private PreparedStatement insertNumericTags;
private PreparedStatement insertAvailabilityTags;
private PreparedStatement updateDataWithTags;
private PreparedStatement findNumericDataByTag;
private PreparedStatement findAvailabilityByTag;
private PreparedStatement insertAvailability;
private PreparedStatement findAvailabilities;
private PreparedStatement updateMetricsIndex;
private PreparedStatement addTagsToMetricsIndex;
private PreparedStatement deleteTagsFromMetricsIndex;
private PreparedStatement readMetricsIndex;
private PreparedStatement findAvailabilitiesWithWriteTime;
private PreparedStatement updateRetentionsIndex;
private PreparedStatement findDataRetentions;
private PreparedStatement insertMetricsTagsIndex;
private PreparedStatement deleteMetricsTagsIndex;
private PreparedStatement findMetricsByTagName;
public DataAccessImpl(Session session) {
this.session = session;
initPreparedStatements();
}
protected void initPreparedStatements() {
insertTenant = session.prepare(
"INSERT INTO tenants (id, retentions, aggregation_templates) " +
"VALUES (?, ?, ?) " +
"IF NOT EXISTS");
findAllTenantIds = session.prepare("SELECT DISTINCT id FROM tenants");
findTenant = session.prepare("SELECT id, retentions, aggregation_templates FROM tenants WHERE id = ?");
findMetric = session.prepare(
"SELECT tenant_id, type, metric, interval, dpart, m_tags, data_retention " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ?");
addMetricTagsToDataTable = session.prepare(
"UPDATE data " +
"SET m_tags = m_tags + ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ?");
addMetadataAndDataRetention = session.prepare(
"UPDATE data " +
"SET m_tags = m_tags + ?, data_retention = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ?");
deleteMetricTagsFromDataTable = session.prepare(
"UPDATE data " +
"SET m_tags = m_tags - ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ?");
insertIntoMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, interval, metric, data_retention, tags) " +
"VALUES (?, ?, ?, ?, ?, ?) " +
"IF NOT EXISTS");
updateMetricsIndex = session.prepare(
"INSERT INTO metrics_idx (tenant_id, type, interval, metric) VALUES (?, ?, ?, ?)");
addTagsToMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags + ? " +
"WHERE tenant_id = ? AND type = ? AND interval = ? AND metric = ?");
deleteTagsFromMetricsIndex = session.prepare(
"UPDATE metrics_idx " +
"SET tags = tags - ?" +
"WHERE tenant_id = ? AND type = ? AND interval = ? AND metric = ?");
readMetricsIndex = session.prepare(
"SELECT metric, interval, tags, data_retention " +
"FROM metrics_idx " +
"WHERE tenant_id = ? AND type = ?");
insertNumericData = session.prepare(
"UPDATE data " +
"USING TTL ?" +
"SET m_tags = m_tags + ?, n_value = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time = ? ");
findNumericDataByDateRangeExclusive = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, n_value, tags " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time < ?");
findNumericDataWithWriteTimeByDateRangeExclusive = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, n_value, tags,"
+ " WRITETIME(n_value) " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time < ?");
findNumericDataByDateRangeInclusive = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, n_value, tags " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time <= ?");
findNumericDataWithWriteTimeByDateRangeInclusive = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, n_value, tags,"
+ " WRITETIME(n_value) " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time <= ?");
findAvailabilityByDateRangeInclusive = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, availability, tags,"
+ " WRITETIME(availability) " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time <= ?");
deleteNumericMetric = session.prepare(
"DELETE FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ?");
findNumericMetrics = session.prepare(
"SELECT DISTINCT tenant_id, type, metric, interval, dpart FROM data;");
updateCounter = session.prepare(
"UPDATE counters " +
"SET c_value = c_value + ? " +
"WHERE tenant_id = ? AND group = ? AND c_name = ?");
findCountersByGroup = session.prepare(
"SELECT tenant_id, group, c_name, c_value FROM counters WHERE tenant_id = ? AND group = ?");
findCountersByGroupAndName = session.prepare(
"SELECT tenant_id, group, c_name, c_value FROM counters WHERE tenant_id = ? AND group = ? AND c_name IN ?");
insertNumericTags = session.prepare(
"INSERT INTO tags (tenant_id, tname, tvalue, type, metric, interval, time, n_value) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
"USING TTL ?");
insertAvailabilityTags = session.prepare(
"INSERT INTO tags (tenant_id, tname, tvalue, type, metric, interval, time, availability) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
"USING TTL ?");
updateDataWithTags = session.prepare(
"UPDATE data " +
"SET tags = tags + ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time = ?");
findNumericDataByTag = session.prepare(
"SELECT tenant_id, tname, tvalue, type, metric, interval, time, n_value " +
"FROM tags " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ?");
findAvailabilityByTag = session.prepare(
"SELECT tenant_id, tname, tvalue, type, metric, interval, time, availability " +
"FROM tags " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ?");
insertAvailability = session.prepare(
"UPDATE data " +
"USING TTL ? " +
"SET m_tags = m_tags + ?, availability = ? " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time = ?");
findAvailabilities = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, availability, tags " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time < ?");
findAvailabilitiesWithWriteTime = session.prepare(
"SELECT tenant_id, metric, interval, dpart, time, m_tags, data_retention, availability, tags,"
+ " WRITETIME(availability) " +
"FROM data " +
"WHERE tenant_id = ? AND type = ? AND metric = ? AND interval = ? AND dpart = ? AND time >= ?"
+ " AND time < ?");
updateRetentionsIndex = session.prepare(
"INSERT INTO retentions_idx (tenant_id, type, interval, metric, retention) VALUES (?, ?, ?, ?, ?)");
findDataRetentions = session.prepare(
"SELECT tenant_id, type, interval, metric, retention " +
"FROM retentions_idx " +
"WHERE tenant_id = ? AND type = ?");
insertMetricsTagsIndex = session.prepare(
"INSERT INTO metrics_tags_idx (tenant_id, tname, tvalue, type, metric, interval) VALUES " +
"(?, ?, ?, ?, ?, ?)");
deleteMetricsTagsIndex = session.prepare(
"DELETE FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ? AND tvalue = ? AND type = ? AND metric = ? AND interval = ?");
findMetricsByTagName = session.prepare(
"SELECT tvalue, type, metric, interval " +
"FROM metrics_tags_idx " +
"WHERE tenant_id = ? AND tname = ?");
}
@Override
public ResultSetFuture insertTenant(Tenant tenant) {
UserType aggregationTemplateType = getKeyspace().getUserType("aggregation_template");
List<UDTValue> templateValues = new ArrayList<>(tenant.getAggregationTemplates().size());
for (AggregationTemplate template : tenant.getAggregationTemplates()) {
UDTValue value = aggregationTemplateType.newValue();
value.setInt("type", template.getType().getCode());
value.setString("interval", template.getInterval().toString());
value.setSet("fns", template.getFunctions());
templateValues.add(value);
}
Map<TupleValue, Integer> retentions = new HashMap<>();
for (RetentionSettings.RetentionKey key : tenant.getRetentionSettings().keySet()) {
TupleType metricType = TupleType.of(DataType.cint(), DataType.text());
TupleValue tuple = metricType.newValue();
tuple.setInt(0, key.metricType.getCode());
if (key.interval == null) {
tuple.setString(1, null);
} else {
tuple.setString(1, key.interval.toString());
}
retentions.put(tuple, tenant.getRetentionSettings().get(key));
}
return session.executeAsync(insertTenant.bind(tenant.getId(), retentions, templateValues));
}
@Override
public ResultSetFuture findAllTenantIds() {
return session.executeAsync(findAllTenantIds.bind());
}
@Override
public ResultSetFuture findTenant(String id) {
return session.executeAsync(findTenant.bind(id));
}
@Override
public ResultSetFuture insertMetricInMetricsIndex(Metric<?> metric) {
return session.executeAsync(insertIntoMetricsIndex.bind(metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName(), metric.getDataRetention(),
getTags(metric)));
}
private Map<String, String> getTags(Metric<? extends MetricData> metric) {
return metric.getTags().entrySet().stream().collect(toMap(Map.Entry::getKey, e -> e.getValue()));
}
@Override
public ResultSetFuture findMetric(String tenantId, MetricType type, MetricId id, long dpart) {
return session.executeAsync(findMetric.bind(tenantId, type.getCode(), id.getName(),
id.getInterval().toString(), dpart));
}
// This method updates the metric tags and data retention in the data table. In the
// long term after we add support for bucketing/date partitioning I am not sure that we
// will store metric tags and data retention in the data table. We would have to
// determine when we start writing data to a new partition, e.g., the start of the next
// day, and then add the tags and retention to the new partition.
@Override
public ResultSetFuture addTagsAndDataRetention(Metric metric) {
return session.executeAsync(addMetadataAndDataRetention.bind(getTags(metric), metric.getDataRetention(),
metric.getTenantId(), metric.getType().getCode(), metric.getId().getName(),
metric.getId().getInterval().toString(), metric.getDpart()));
}
@Override
public ResultSetFuture addTags(Metric<?> metric, Map<String, String> tags) {
BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED);
batch.add(addMetricTagsToDataTable.bind(tags, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getName(), metric.getId().getInterval().toString(), metric.getDpart()));
batch.add(addTagsToMetricsIndex.bind(tags, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName()));
return session.executeAsync(batch);
}
@Override
public ResultSetFuture deleteTags(Metric<?> metric, Set<String> tags) {
BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED);
batch.add(deleteMetricTagsFromDataTable.bind(tags, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getName(), metric.getId().getInterval().toString(), metric.getDpart()));
batch.add(deleteTagsFromMetricsIndex.bind(tags, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName()));
return session.executeAsync(batch);
}
@Override
public ResultSetFuture updateTagsInMetricsIndex(Metric<?> metric, Map<String, String> additions,
Set<String> deletions) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED)
.add(addTagsToMetricsIndex.bind(additions, metric.getTenantId(),
metric.getType().getCode(), metric.getId().getInterval().toString(), metric.getId().getName()))
.add(deleteTagsFromMetricsIndex.bind(deletions, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName()));
return session.executeAsync(batchStatement);
}
@Override
public <T extends Metric<?>> ResultSetFuture updateMetricsIndex(List<T> metrics) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (T metric : metrics) {
batchStatement.add(updateMetricsIndex.bind(metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture findMetricsInMetricsIndex(String tenantId, MetricType type) {
return session.executeAsync(readMetricsIndex.bind(tenantId, type.getCode()));
}
@Override
public ResultSetFuture insertData(NumericMetric metric, int ttl) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (NumericData d : metric.getData()) {
batchStatement.add(insertNumericData.bind(ttl, getTags(metric), d.getValue(), metric.getTenantId(),
metric.getType().getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), d.getTimeUUID()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture findData(NumericMetric metric, long startTime, long endTime) {
return findData(metric, startTime, endTime, false);
}
@Override
public ResultSetFuture findData(NumericMetric metric, long startTime, long endTime, boolean includeWriteTime) {
if (includeWriteTime) {
return session.executeAsync(findNumericDataWithWriteTimeByDateRangeExclusive.bind(metric.getTenantId(),
MetricType.NUMERIC.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), TimeUUIDUtils.getTimeUUID(startTime), TimeUUIDUtils.getTimeUUID(endTime)));
} else {
return session.executeAsync(findNumericDataByDateRangeExclusive.bind(metric.getTenantId(),
MetricType.NUMERIC.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), TimeUUIDUtils.getTimeUUID(startTime), TimeUUIDUtils.getTimeUUID(endTime)));
}
}
@Override
public ResultSetFuture findData(NumericMetric metric, long timestamp, boolean includeWriteTime) {
if (includeWriteTime) {
return session.executeAsync(findNumericDataWithWriteTimeByDateRangeInclusive.bind(metric.getTenantId(),
MetricType.NUMERIC.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), UUIDs.startOf(timestamp), UUIDs.endOf(timestamp)));
} else {
return session.executeAsync(findNumericDataByDateRangeInclusive.bind(metric.getTenantId(),
MetricType.NUMERIC.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), UUIDs.startOf(timestamp), UUIDs.endOf(timestamp)));
}
}
@Override
public ResultSetFuture findData(AvailabilityMetric metric, long startTime, long endTime) {
return findData(metric, startTime, endTime, false);
}
@Override
public ResultSetFuture findData(AvailabilityMetric metric, long startTime, long endTime, boolean includeWriteTime) {
if (includeWriteTime) {
return session.executeAsync(findAvailabilitiesWithWriteTime.bind(metric.getTenantId(),
MetricType.AVAILABILITY.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), TimeUUIDUtils.getTimeUUID(startTime), TimeUUIDUtils.getTimeUUID(endTime)));
} else {
return session.executeAsync(findAvailabilities.bind(metric.getTenantId(), MetricType.AVAILABILITY.getCode(),
metric.getId().getName(), metric.getId().getInterval().toString(), metric.getDpart(),
TimeUUIDUtils.getTimeUUID(startTime), TimeUUIDUtils.getTimeUUID(endTime)));
}
}
@Override
public ResultSetFuture findData(AvailabilityMetric metric, long timestamp) {
return session.executeAsync(findAvailabilityByDateRangeInclusive.bind(metric.getTenantId(),
MetricType.AVAILABILITY.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), UUIDs.startOf(timestamp), UUIDs.endOf(timestamp)));
}
@Override
public ResultSetFuture deleteNumericMetric(String tenantId, String metric, Interval interval, long dpart) {
return session.executeAsync(deleteNumericMetric.bind(tenantId, MetricType.NUMERIC.getCode(), metric,
interval.toString(), dpart));
}
@Override
public ResultSetFuture findAllNumericMetrics() {
return session.executeAsync(findNumericMetrics.bind());
}
@Override
public ResultSetFuture insertNumericTag(String tag, String tagValue, NumericMetric metric,
List<NumericData> data) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (NumericData d : data) {
batchStatement.add(insertNumericTags.bind(metric.getTenantId(), tag, tagValue,
MetricType.NUMERIC.getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
d.getTimeUUID(), d.getValue(), d.getTTL()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture insertAvailabilityTag(String tag, String tagValue, AvailabilityMetric metric,
List<Availability> data) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (Availability a : data) {
batchStatement.add(insertAvailabilityTags.bind(metric.getTenantId(), tag, tagValue,
MetricType.AVAILABILITY.getCode(), metric.getId().getName(), metric.getId().getInterval()
.toString(), a.getTimeUUID(), a.getBytes(), a.getTTL()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture updateDataWithTag(Metric<?> metric, MetricData data, Map<String, String> tags) {
return session.executeAsync(updateDataWithTags.bind(tags, metric.getTenantId(), metric.getType().getCode(),
metric.getId().getName(), metric.getId().getInterval().toString(), metric.getDpart(),
data.getTimeUUID()));
}
@Override
public ResultSetFuture findNumericDataByTag(String tenantId, String tag, String tagValue) {
return session.executeAsync(findNumericDataByTag.bind(tenantId, tag, tagValue));
}
@Override
public ResultSetFuture findAvailabilityByTag(String tenantId, String tag, String tagValue) {
return session.executeAsync(findAvailabilityByTag.bind(tenantId, tag, tagValue));
}
@Override
public ResultSetFuture insertData(AvailabilityMetric metric, int ttl) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (Availability a : metric.getData()) {
batchStatement.add(insertAvailability.bind(ttl, metric.getTags(), a.getBytes(), metric.getTenantId(),
metric.getType().getCode(), metric.getId().getName(), metric.getId().getInterval().toString(),
metric.getDpart(), a.getTimeUUID()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture findAvailabilityData(AvailabilityMetric metric, long startTime, long endTime) {
return session.executeAsync(findAvailabilities.bind(metric.getTenantId(), MetricType.AVAILABILITY.getCode(),
metric.getId().getName(), metric.getId().getInterval().toString(), metric.getDpart(),
TimeUUIDUtils.getTimeUUID(startTime), TimeUUIDUtils.getTimeUUID(endTime)));
}
@Override
public ResultSetFuture updateCounter(Counter counter) {
BoundStatement statement = updateCounter.bind(counter.getValue(), counter.getTenantId(), counter.getGroup(),
counter.getName());
return session.executeAsync(statement);
}
@Override
public ResultSetFuture updateCounters(Collection<Counter> counters) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.COUNTER);
for (Counter counter : counters) {
batchStatement.add(updateCounter.bind(counter.getValue(), counter.getTenantId(), counter.getGroup(),
counter.getName()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture findDataRetentions(String tenantId, MetricType type) {
return session.executeAsync(findDataRetentions.bind(tenantId, type.getCode()));
}
@Override
public ResultSetFuture updateRetentionsIndex(String tenantId, MetricType type, Set<Retention> retentions) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
for (Retention r : retentions) {
batchStatement.add(updateRetentionsIndex.bind(tenantId, type.getCode(), r.getId().getInterval().toString(),
r.getId().getName(), r.getValue()));
}
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture insertIntoMetricsTagsIndex(Metric<?> metric, Map<String, String> tags) {
return executeTagsBatch(tags, (name, value) -> insertMetricsTagsIndex.bind(metric.getTenantId(), name, value,
metric.getType().getCode(), metric.getId().getName(), metric.getId().getInterval().toString()));
}
@Override
public ResultSetFuture deleteFromMetricsTagsIndex(Metric<?> metric, Map<String, String> tags) {
return executeTagsBatch(tags, (name, value) -> deleteMetricsTagsIndex.bind(metric.getTenantId(), name, value,
metric.getType().getCode(), metric.getId().getName(), metric.getId().getInterval().toString()));
}
private ResultSetFuture executeTagsBatch(Map<String, String> tags,
BiFunction<String, String, BoundStatement> bindVars) {
BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
tags.entrySet().stream().forEach(entry -> batchStatement.add(bindVars.apply(entry.getKey(), entry.getValue())));
return session.executeAsync(batchStatement);
}
@Override
public ResultSetFuture findMetricsByTag(String tenantId, String tag) {
return session.executeAsync(findMetricsByTagName.bind(tenantId, tag));
}
@Override
public ResultSetFuture updateRetentionsIndex(Metric<?> metric) {
return session.executeAsync(updateRetentionsIndex.bind(metric.getTenantId(), metric.getType().getCode(),
metric.getId().getInterval().toString(), metric.getId().getName(), metric.getDataRetention()));
}
public ResultSetFuture findCounters(String tenantId, String group) {
BoundStatement statement = findCountersByGroup.bind(tenantId, group);
return session.executeAsync(statement);
}
public ResultSetFuture findCounters(String tenantId, String group, List<String> names) {
BoundStatement statement = findCountersByGroupAndName.bind(tenantId, group, names);
return session.executeAsync(statement);
}
private KeyspaceMetadata getKeyspace() {
return session.getCluster().getMetadata().getKeyspace(session.getLoggedKeyspace());
}
}
| {'content_hash': '812603b4173cf529ce51ef5f0d82ac7c', 'timestamp': '', 'source': 'github', 'line_count': 630, 'max_line_length': 120, 'avg_line_length': 45.87301587301587, 'alnum_prop': 0.6621107266435986, 'repo_name': 'jsanda/hawkular-metrics', 'id': 'b23c575c2811025c01a2c4247fdf8584d3a2ec6a', 'size': '29582', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/metrics-core-impl/src/main/java/org/hawkular/metrics/core/impl/cassandra/DataAccessImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4006'}, {'name': 'ApacheConf', 'bytes': '6747'}, {'name': 'CSS', 'bytes': '7561'}, {'name': 'Groovy', 'bytes': '36406'}, {'name': 'HTML', 'bytes': '32702'}, {'name': 'Java', 'bytes': '803474'}, {'name': 'JavaScript', 'bytes': '16473'}, {'name': 'Shell', 'bytes': '15094'}, {'name': 'TypeScript', 'bytes': '43472'}, {'name': 'XSLT', 'bytes': '19675'}]} |
module StatsD::Instrument::Helpers
def capture_statsd_calls(&block)
mock_backend = StatsD::Instrument::Backends::CaptureBackend.new
old_backend, StatsD.backend = StatsD.backend, mock_backend
block.call
mock_backend.collected_metrics
ensure
if old_backend.kind_of?(StatsD::Instrument::Backends::CaptureBackend)
old_backend.collected_metrics.concat(mock_backend.collected_metrics)
end
StatsD.backend = old_backend
end
end
| {'content_hash': '03c3fead93d373af63678ddce9587494', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 74, 'avg_line_length': 32.92857142857143, 'alnum_prop': 0.7440347071583514, 'repo_name': 'yakovenkodenis/statsd-instrument', 'id': '0183a8c0f6d38d4b8fa41fbab3950810ad9f9e6b', 'size': '461', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/statsd/instrument/helpers.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '62436'}]} |
package org.apache.flink.api.java.typeutils.runtime;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.ComparatorTestBase;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.types.Row;
import org.junit.jupiter.api.BeforeAll;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.assertj.core.api.Assertions.assertThat;
/** Tests {@link org.apache.flink.api.java.typeutils.runtime.RowComparator} for wide rows. */
class RowComparatorWithManyFieldsTests extends ComparatorTestBase<Row> {
private static final int numberOfFields = 10;
private static RowTypeInfo typeInfo;
private static final Row[] data =
new Row[] {
createRow(null, "b0", "c0", "d0", "e0", "f0", "g0", "h0", "i0", "j0"),
createRow("a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", "i1", "j1"),
createRow("a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "i2", "j2"),
createRow("a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "i3", "j3")
};
@BeforeAll
static void setUp() throws Exception {
TypeInformation<?>[] fieldTypes = new TypeInformation[numberOfFields];
for (int i = 0; i < numberOfFields; i++) {
fieldTypes[i] = BasicTypeInfo.STRING_TYPE_INFO;
}
typeInfo = new RowTypeInfo(fieldTypes);
}
@Override
protected void deepEquals(String message, Row should, Row is) {
int arity = should.getArity();
assertThat(is.getArity()).as(message).isEqualTo(arity);
for (int i = 0; i < arity; i++) {
Object copiedValue = should.getField(i);
Object element = is.getField(i);
assertThat(element).as(message).isEqualTo(copiedValue);
}
}
@Override
protected TypeComparator<Row> createComparator(boolean ascending) {
return typeInfo.createComparator(
new int[] {0}, new boolean[] {ascending}, 0, new ExecutionConfig());
}
@Override
protected TypeSerializer<Row> createSerializer() {
return typeInfo.createSerializer(new ExecutionConfig());
}
@Override
protected Row[] getSortedTestData() {
return data;
}
@Override
protected boolean supportsNullKeys() {
return true;
}
private static Row createRow(Object... values) {
checkNotNull(values);
checkArgument(values.length == numberOfFields);
Row row = new Row(numberOfFields);
for (int i = 0; i < values.length; i++) {
row.setField(i, values[i]);
}
return row;
}
}
| {'content_hash': 'bddfb723d851d80c6b0a6dd6c488ea5d', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 93, 'avg_line_length': 36.36585365853659, 'alnum_prop': 0.6395036887994634, 'repo_name': 'apache/flink', 'id': '5ae5f8075bc093acbf83331912d49f9c84e2d160', 'size': '3787', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/RowComparatorWithManyFieldsTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '20596'}, {'name': 'Batchfile', 'bytes': '1863'}, {'name': 'C', 'bytes': '847'}, {'name': 'Cython', 'bytes': '137975'}, {'name': 'Dockerfile', 'bytes': '6723'}, {'name': 'FreeMarker', 'bytes': '101034'}, {'name': 'GAP', 'bytes': '139876'}, {'name': 'HTML', 'bytes': '188809'}, {'name': 'HiveQL', 'bytes': '215858'}, {'name': 'Java', 'bytes': '95993077'}, {'name': 'JavaScript', 'bytes': '7038'}, {'name': 'Less', 'bytes': '84321'}, {'name': 'Makefile', 'bytes': '5134'}, {'name': 'Python', 'bytes': '3100407'}, {'name': 'Scala', 'bytes': '10653766'}, {'name': 'Shell', 'bytes': '516779'}, {'name': 'TypeScript', 'bytes': '381920'}, {'name': 'q', 'bytes': '16945'}]} |
<html>
<head>
<title>Documentation : Migrating to Apache Geronimo</title>
<link rel="stylesheet" href="styles/site.css" type="text/css" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff">
<tr>
<td valign="top" class="pagebody">
<div class="pageheader">
<span class="pagetitle">
Documentation : Migrating to Apache Geronimo
</span>
</div>
<div class="pagesubheading">
This page last changed on Dec 14, 2005 by <font color="#0050B2">[email protected]</font>.
</div>
<p><a name="MigratingtoApacheGeronimo-top"></a><br/>
<em><b>Article donated by:</b> <a href="mailto:[email protected]" title="Send mail to Hernan Cunico">Hernan Cunico</a></em></p>
<h1><a name="MigratingtoApacheGeronimo-MigratingtoApacheGeronimo"></a>Migrating to Apache Geronimo </h1>
<p>The following are a series of articles to assist you to migrate applications from JBoss v4 to Apache Geronimo. At the time of writing these articles JBoss v4.0.2 and Apache Geronimo M5 was used.</p>
<p>There are several articles focusing on different features/functionalities of the J2EE specification. All these articles are self contained and fully independent from each other. They provide feature-to-feature comparison analysis between the differences in the implementation from JBoss to Apache Geronimo, this will particularly help you when doing the migration planning.</p>
<p>Additionally, each article provides a sample application for you to practice and gain experience migrating from one platform to another. All these articles have the same internal structure so it will be easier for you to find similar information about different topics across the articles.</p>
<p>Available articles:</p>
<ol>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - Servlets and JSPs Migration.html" title="JBoss to Geronimo - Servlets and JSPs Migration">JBoss to Geronimo \- Servlets and JSPs Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - JDBC Migration.html" title="JBoss to Geronimo - JDBC Migration">JBoss to Geronimo \- JDBC Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - Security Migration.html" title="JBoss to Geronimo - Security Migration">JBoss to Geronimo \- Security Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - JCA Migration.html" title="JBoss to Geronimo - JCA Migration">JBoss to Geronimo \- JCA Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - Web Services Migration.html" title="JBoss to Geronimo - Web Services Migration">JBoss to Geronimo \- Web Services Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - EJB-BMP Migration.html" title="JBoss to Geronimo - EJB-BMP Migration">JBoss to Geronimo \- EJB\-BMP Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - EJB-MDB Migration.html" title="JBoss to Geronimo - EJB-MDB Migration">JBoss to Geronimo \- EJB\-MDB Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - EJB-Session Beans Migration.html" title="JBoss to Geronimo - EJB-Session Beans Migration">JBoss to Geronimo \- EJB\-Session Beans Migration</a></li>
<li><img class="emoticon" src="./icons/emoticons/check.gif" height="16" width="16" align="absmiddle" alt="" border="0"/> <a href="JBoss to Geronimo - EJB-CMP Migration.html" title="JBoss to Geronimo - EJB-CMP Migration">JBoss to Geronimo \- EJB\-CMP Migration</a></li>
</ol>
</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td height="12" background="border/border_bottom.gif"><img src="border/spacer.gif" width="1" height="1" border="0"/></td>
</tr>
<tr>
<td align="center"><font color="grey">Document generated by Confluence on Dec 15, 2005 19:14</font></td>
</tr>
</table>
</body>
</html> | {'content_hash': '23630c84c341600abbca005faa6677d9', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 381, 'avg_line_length': 85.12068965517241, 'alnum_prop': 0.6848288434271825, 'repo_name': 'meetdestiny/geronimo-trader', 'id': '4667c10883de4a6ea6db89da91b70dd7ae28a9b8', 'size': '4937', 'binary': False, 'copies': '2', 'ref': 'refs/heads/1.0', 'path': 'modules/scripts/src/resources/docs/Migrating to Apache Geronimo.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '47972'}, {'name': 'Java', 'bytes': '8387339'}, {'name': 'JavaScript', 'bytes': '906'}, {'name': 'Shell', 'bytes': '62441'}, {'name': 'XSLT', 'bytes': '4468'}]} |
import React from 'react'
import PropTypes from 'prop-types'
import cn from 'classnames'
import CaretDownSvg from '../svgs/caret-down.svg'
const baseCn = 'mo-nav__primary'
export const Primary = ({ openSections, toggleSection, children }) => (
<ul className={baseCn}>
{React.Children.map(children, child =>
// Cloning each child is the only way to apply props that were passed into the parent
React.cloneElement(child, { openSections, toggleSection })
)}
</ul>
)
Primary.propTypes = {
openSections: PropTypes.array.isRequired,
toggleSection: PropTypes.func.isRequired,
children: PropTypes.node
}
const Section = ({ openSections, toggleSection, name, children }) => {
const dropdownCn = section =>
cn('mo-nav__dropdown', {
'nav__dropdown--expanded': openSections.indexOf(section) !== -1
})
return (
<li className={dropdownCn(name)}>
<a onClick={toggleSection(name)}>
{name}
<button className={`${baseCn}__caret`}>
<CaretDownSvg />
</button>
</a>
<ul className={`${baseCn}__subnav`}>{children}</ul>
</li>
)
}
Primary.Section = Section
Section.propTypes = {
openSections: PropTypes.array,
toggleSection: PropTypes.func,
name: PropTypes.string,
children: PropTypes.node
}
| {'content_hash': 'e951530a73f23151d97555c9a954e024', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 91, 'avg_line_length': 25.88, 'alnum_prop': 0.6599690880989181, 'repo_name': 'MoveOnOrg/mop-frontend', 'id': '49cbb46d0b48e2acec6958850d1fc76d7a284152', 'size': '1294', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'src/giraffe-ui/nav/primary.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '274104'}, {'name': 'HTML', 'bytes': '3511'}, {'name': 'JavaScript', 'bytes': '502190'}]} |
package check
import (
"math"
)
// Returns true if got is within epsilon of want. Useful for comparing
// the results of floating point arithmetic. If got and want are both
// NaN, +Inf, or -Inf this function returns true.
func EqualWithin(got, want, epsilon float64) bool {
if math.IsNaN(want) {
return math.IsNaN(got)
} else if math.IsNaN(got) {
return false
}
if math.IsInf(want, 1) {
return math.IsInf(got, 1)
} else if math.IsInf(got, 1) {
return false
}
if math.IsInf(want, -1) {
return math.IsInf(got, -1)
} else if math.IsInf(got, -1) {
return false
}
if got == want {
return true
}
return math.Abs(got-want) <= math.Abs(epsilon)
}
| {'content_hash': '7111a8d10fba8a49600938aafb7190fe', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 70, 'avg_line_length': 18.75, 'alnum_prop': 0.6666666666666666, 'repo_name': 'turbinelabs/test', 'id': 'e90917a787f6b15134fdc2c6b76f2d9884f5a787', 'size': '1239', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'check/numeric.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '249508'}, {'name': 'Shell', 'bytes': '953'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_22) on Thu Nov 11 09:12:14 EST 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.mortbay.naming Class Hierarchy (Jetty Server Project 6.1.26 API)
</TITLE>
<META NAME="date" CONTENT="2010-11-11">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../javadoc.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.mortbay.naming Class Hierarchy (Jetty Server Project 6.1.26 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/mortbay/management/package-tree.html"><B>PREV</B></A>
<A HREF="../../../org/mortbay/naming/factories/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/mortbay/naming/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package org.mortbay.naming
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.Object<UL>
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/ContextFactory.html" title="class in org.mortbay.naming"><B>ContextFactory</B></A> (implements javax.naming.spi.ObjectFactory)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/InitialContextFactory.html" title="class in org.mortbay.naming"><B>InitialContextFactory</B></A> (implements javax.naming.spi.InitialContextFactory)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/InitialContextFactory.DefaultParser.html" title="class in org.mortbay.naming"><B>InitialContextFactory.DefaultParser</B></A> (implements javax.naming.NameParser)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/NamingContext.html" title="class in org.mortbay.naming"><B>NamingContext</B></A> (implements java.lang.Cloneable, javax.naming.Context)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/NamingContext.BindingEnumeration.html" title="class in org.mortbay.naming"><B>NamingContext.BindingEnumeration</B></A> (implements javax.naming.NamingEnumeration<T>)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/NamingContext.NameEnumeration.html" title="class in org.mortbay.naming"><B>NamingContext.NameEnumeration</B></A> (implements javax.naming.NamingEnumeration<T>)
<LI TYPE="circle">org.mortbay.naming.<A HREF="../../../org/mortbay/naming/NamingUtil.html" title="class in org.mortbay.naming"><B>NamingUtil</B></A></UL>
</UL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/mortbay/management/package-tree.html"><B>PREV</B></A>
<A HREF="../../../org/mortbay/naming/factories/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/mortbay/naming/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 1995-2010 <a href="http://www.mortbay.com">Mort Bay Consulting</a>. All Rights Reserved.
</BODY>
</HTML>
| {'content_hash': 'b7687d5f41ed2bc248c4dd0d47474acc', 'timestamp': '', 'source': 'github', 'line_count': 160, 'max_line_length': 245, 'avg_line_length': 47.2375, 'alnum_prop': 0.6491135220957925, 'repo_name': 'napcs/qedserver', 'id': 'c893d30e618ce44f4b9d6d4df16269cba42ee291', 'size': '7558', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jetty/javadoc/org/mortbay/naming/package-tree.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '16295'}, {'name': 'CSS', 'bytes': '14847'}, {'name': 'Groovy', 'bytes': '7099'}, {'name': 'HTML', 'bytes': '14346'}, {'name': 'Java', 'bytes': '5514807'}, {'name': 'JavaScript', 'bytes': '34952'}, {'name': 'Ruby', 'bytes': '53583'}, {'name': 'Shell', 'bytes': '68984'}, {'name': 'XSLT', 'bytes': '7153'}]} |
`azk` lets developers easily and quickly install and configure their development environments. Period.

## Quick start
### Installing
```
$ curl -Ls http://azk.io/install.sh | bash
```
Requirements:
* **Mac OS X:** [VirtualBox](https://www.virtualbox.org/), version 4.3.6+
* **Linux:** [Docker][docker], version 1.2+
For further details, please see the [docs](http://docs.azk.io/en/installation/index.html).
### Using `azk`
#### Starting a new project
If you are starting a new application project, you can already use `azk` to obtain the proper runtime as well the corresponding generators for your chosen language and then generate the application's basic structure. An example in Node.js would look like this:
```bash
$ cd ~/projects
$ azk shell --image azukiapp/node # obtaining the runtime
# mkdir app-name
# npm init # building the application's basic structure
...
# exit
$ cd app-name
$ azk init
azk: `node` system was detected at 'app-name'
azk: 'Azkfile.js' generated
$ azk start
```
#### Using `azk` with an existing project
When you have an application project that's already started, and want to use `azk` to streamline its development environment, all you have to do is:
```bash
$ cd [my_application_folder]
$ azk init
azk: 'Azkfile.js' generated
...
$ azk start
```
## Main features
* Multiplatform: Works both on Linux & Mac OS X (requires 64-bit platform);
* Windows planned. Want azk to run in Windows? Thumbs up here: https://github.com/azukiapp/azk/issues/334
* Images: via [azk images][azk_images], [Docker Registry][docker_registry] or run your own Dockerfile;
* Built-in load-balancer;
* Built-in file sync;
* Automatic start-up (and reload) script;
* Logging;
* And simple and easy to use DSL to describe systems architecture;
## Documentation
You can find our documentation online at: http://docs.azk.io/
## `Run Project` button
Clicking the `Run Project` button (or "azk button") on a GitHub repo is the best way to quickly and safely run its code on your local machine.

To add a `Run Project` button to a repo, you'll just need to add an Azkfile.js to the project and put the following badge in your README.md file (the following example is for a hypothetical repository with the URL `https://github.com/username/repo` and a branch called `azkfile` containing the Azkfile.js):
```
[](http://run.azk.io/start/?repo=username/repo&ref=azkfile)
```
Check out the [`Run Project` Gallery][run_project_gallery] for examples of up to date forks of popular projects using it.
## Deploying
After you locally run a project using [`Run Project` button](#run-project-button), deploying it to [DigitalOcean](http://digitalocean.com/) is very simple.
First, put your [personal access token](https://cloud.digitalocean.com/settings/applications) into a `.env` file:
```bash
$ cd path/to/the/project
$ echo "DEPLOY_API_TOKEN=<YOUR-PERSONAL-ACCESS-TOKEN>" >> .env
```
Then, just run the following:
```bash
$ azk shell deploy
```
Find further instructions on how to deploy to DigitalOcean using `azk` [here](http://docs.azk.io/en/deploy/README.html).
### Basic Vocabulary
#### System of Systems
`azk` is based on the concept of [System of Systems][sos]. Accordingly, applications (your code), services and workers (such as databases, webservers and queue systems) are treated as systems that communicate with each other and together make the primary system. Using this paradigm, `azk` installs and manages development environments. While this may seem overkill at first, it actually makes it a lot easier to manage the development and execution environments of an application (in its parts - the "systems" - or in its entirety - the full "system of systems").
#### Images
In order to automate the provisioning of development environments, `azk` uses pre-built custom images. These images follow the [Docker][docker] standard and can be found in: [azk images][azk_images], [Docker Index][docker_hub] or [Dockerfile][dockerfile].
#### Azkfile.js
`Azkfile.js` files are the cornerstone of how to use `azk`. These simple manifest files describe the systems that make your system of systems as well as the images used in their execution. They also describe parameters and execution options.
More information [here][azkfile].
## Contributions
Check our [Contributing Guide](CONTRIBUTING.md) for instructions on how to help the project!
Share the love and star us here in Github!
## License
"Azuki", "azk" and the Azuki logo are copyright (c) 2013-2015 Azuki Serviços de Internet LTDA.
**azk** source code is released under Apache 2 License.
Check LEGAL and LICENSE files for more information.
[sos]: http://en.wikipedia.org/wiki/System_of_systems
[docker]: http://docker.com
[azk_images]: http://images.azk.io
[docker_hub]: https://registry.hub.docker.com/
[dockerfile]: http://dockerfile.github.io
[docker_registry]: http://registry.hub.docker.com
[azkfile]: http://docs.azk.io/en/azkfilejs/README.html
[run_project_gallery]: https://github.com/run-project/gallery | {'content_hash': 'bc504b79d12505a61438dc51d036341d', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 564, 'avg_line_length': 38.61594202898551, 'alnum_prop': 0.7397260273972602, 'repo_name': 'renanmpimentel/azk', 'id': 'c563dee4771dbaec03e032dc90882fcea2815c37', 'size': '5668', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '624890'}, {'name': 'Makefile', 'bytes': '6286'}, {'name': 'Shell', 'bytes': '97109'}]} |
Release History
===============
0.0.5
-----
.. TODO
* Still a heavy work in progress; stay tuned!
| {'content_hash': 'de2ca86cac3c812cf3ce0ba7660f5959', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 45, 'avg_line_length': 11.222222222222221, 'alnum_prop': 0.5445544554455446, 'repo_name': 'eddowh/openkongqi', 'id': '91efff61284ec54088efc91e9424c04974a6de56', 'size': '101', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'docs/changes.rst', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '19035'}, {'name': 'Python', 'bytes': '69198'}]} |
(function (container) {
"use strict";
requirejs.config({
"paths": {
"vue": "/lib/vue/dist/vue",
"vue-resource": "/lib/vue-resource/dist/vue-resource"
}
});
require(['vue', 'vue-resource'],
(Vue, VueResource) => {
Vue.use(VueResource);
var model = new Vue({
el: "#app",
data: {
image: null,
imageHeight: 0,
imageWidth: 0,
uploadedFile: null,
upscaledFileUrl: null,
scale: 2,
progressRatio: 0,
progressMessage: null,
upscalledImage: null,
isRunning: false,
isShownModified: false,
progressPooling: null,
ticket: null,
totalBlocks: null
},
computed: {
cancelButtonText() {
return this.isRunning ? "Cancel" : "Remove image";
},
toggleButtonText() {
return this.isShownModified ? "Show original" : "Show modified";
},
isReady() {
return !this.isRunning && this.upscaledFileUrl !== null;
},
getImagePreviewSource() {
if (this.image !== null) {
return this.isShownModified ? this.upscaledFileUrl : this.image.src;
} else {
return null;
}
},
currentImageHeight() {
return this.isShownModified ? this.imageHeight * 2 : this.imageHeight;
},
currentImageWidth() {
return this.isShownModified ? this.imageWidth * 2 : this.imageWidth;
}
},
methods: {
toggleImage() {
this.isShownModified = !this.isShownModified;
},
uploadFile() {
this.$http.post("/api/Upscalling/Upload", this.uploadedFile)
.then(response => {
this.ticket = response.body;
}, response => console.error("Upload Fail"));
},
getProgress() {
this.$http.get("/api/Upscalling/GetProgress", { params: { ticket: this.ticket } })
.then(response => {
if (response.body) {
console.log(response.body);
let statusObject = this.getTaskStatus(response.body);
this.handleProgress(statusObject);
}
}, response => console.error("Progress failed"));
},
clearEvents() {
this.$http.post("/api/Upscalling/Clear", `=${this.ticket}`)
.then(response => {
if (response.body === true) {
console.log("Data was cleared")
} else {
console.error("Data wasn't cleared")
}
}, response => console.error("Clearing failed"));
},
getTaskStatus(messages = []) {
const status = {
isReceived: false,
isDecomposing: false,
isUpscalling: false,
isComposing: false,
isReady: false
}
let totalBLocks = null;
const blocksProcessed = [];
messages.forEach(message => {
switch (message.status) {
//Image received
case 0:
status.isReceived = true;
break;
//Decomposing
case 1:
status.isDecomposing = true;
break;
//Upscalling blocks
case 2:
status.isUpscalling = true;
totalBLocks = message.blocksCount;
blocksProcessed.push(message.blockNumber);
break;
//Composing
case 3:
status.isComposing = true;
break;
//Upscaled image was sent
case 4:
status.isReady = true;
break;
}
});
return {
status,
totalBLocks,
blocksProcessed
}
},
handleProgress(taskStatusObject) {
let text = "Waiting";
let url = null;
if (taskStatusObject.status.isReceived) {
text = "Image was received";
}
if (taskStatusObject.status.isDecomposing) {
text = "Decomposing";
}
if (taskStatusObject.status.isUpscalling) {
text = `Upscalling: ${taskStatusObject.blocksProcessed.length} of ${taskStatusObject.totalBLocks}`;
}
if (taskStatusObject.status.isComposing) {
text = "Composing";
}
if (taskStatusObject.status.isReady) {
text = "Ready";
this.stopPooling();
this.getResult();
}
this.progressMessage = text;
},
getResult() {
this.$http.get("/api/Upscalling/GetResult", { params: { ticket: this.ticket } })
.then(response => {
if (response.body) {
console.log(response.body);
this.upscaledFileUrl = response.body.filePath;
this.clearEvents();
}
}, response => console.log("Rusult Fail"));
},
initPooling() {
this.progressPooling = setInterval(() => this.getProgress(), 2500);
},
stopPooling() {
clearInterval(this.progressPooling);
this.isRunning = false;
},
startProcess() {
this.progressMessage = null;
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.width = this.imageWidth;
canvas.height = this.imageHeight;
context.drawImage(this.image, 0, 0);
let imageData = context.getImageData(0, 0, this.imageWidth, this.imageHeight);
this.uploadFile();
this.isRunning = true;
this.initPooling();
},
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
const uploadedFile = new FormData();
uploadedFile.append("Image", files[0]);
this.uploadedFile = uploadedFile;
},
createImage(file) {
const reader = new FileReader();
const vm = this;
reader.onload = (file) => {
this.image = new Image();
this.image.onload = function() {
vm.imageWidth = this.naturalWidth;
vm.imageHeight = this.naturalHeight;
};
this.image.src = file.target.result;
};
reader.readAsDataURL(file);
},
cancel() {
this.stopPooling();
this.image = null;
this.upscaledFileUrl = null;
this.progressMessage = null;
this.isShownModified = false;
}
},
mounted() {
}
});
});
})(window);
| {'content_hash': '34a100fb2fd497ec9cb92419dc982ad3', 'timestamp': '', 'source': 'github', 'line_count': 215, 'max_line_length': 127, 'avg_line_length': 46.08372093023256, 'alnum_prop': 0.34467097295115057, 'repo_name': 'AxelUser/SRCNN', 'id': '9d46a9356ff28333f5441edd416ca34dc6de633f', 'size': '9910', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/ImageSuperResolution/src/ImageSuperResolution.Web/wwwroot/js/site.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '68577'}, {'name': 'CSS', 'bytes': '2706'}, {'name': 'HTML', 'bytes': '8335'}, {'name': 'JavaScript', 'bytes': '10366'}]} |
using System.Collections.Generic;
namespace Stripe.Tests.test_data
{
public class stripe_recipient_update_options
{
public static StripeRecipientUpdateOptions Valid()
{
var stripeRecipientUpdateOptions = new StripeRecipientUpdateOptions()
{
Name = "Billy Madison",
TaxId = "000000000",
Email = "[email protected]",
Description = "Conditioner is better, it makes the hair silky and smooth",
Metadata = new Dictionary<string, string>
{
{ "A", "Value-A" },
{ "B", "Value-B" },
{ "C", "Value-C" }
}
};
return stripeRecipientUpdateOptions;
}
}
} | {'content_hash': '66f38470ea08e4219dd52fbdd67c2f47', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 90, 'avg_line_length': 30.73076923076923, 'alnum_prop': 0.49937421777221525, 'repo_name': 'matthewcorven/stripe.net', 'id': '6ba877753cb5506e3328cea4f959732f28eb3e33', 'size': '801', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'src/Stripe.Tests/recipients/test_data/stripe_recipient_update_options.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '98'}, {'name': 'Batchfile', 'bytes': '56'}, {'name': 'C#', 'bytes': '345008'}, {'name': 'Ruby', 'bytes': '1244'}]} |
'use strict';
// Done this way to make the Browserify build smaller
var _ = {
cloneDeep: require('lodash-compat/lang/cloneDeep'),
each: require('lodash-compat/collection/each'),
isArray: require('lodash-compat/lang/isArray'),
isBoolean: require('lodash-compat/lang/isBoolean'),
isDate: require('lodash-compat/lang/isDate'),
isFinite: require('lodash-compat/lang/isFinite'),
isNull: require('lodash-compat/lang/isNull'),
isNumber: require('lodash-compat/lang/isNumber'),
isPlainObject: require('lodash-compat/lang/isPlainObject'),
isString: require('lodash-compat/lang/isString'),
isUndefined: require('lodash-compat/lang/isUndefined'),
map: require('lodash-compat/collection/map'),
union: require('lodash-compat/array/union'),
uniq: require('lodash-compat/array/uniq')
};
var helpers = require('./helpers');
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateRegExp = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/;
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTimeRegExp = /^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$/;
var isValidDate = function (date) {
var day;
var matches;
var month;
if (_.isDate(date)) {
return true;
}
if (!_.isString(date)) {
date = date.toString();
}
matches = dateRegExp.exec(date);
if (matches === null) {
return false;
}
day = matches[3];
month = matches[2];
if (month < '01' || month > '12' || day < '01' || day > '31') {
return false;
}
return true;
};
var isValidDateTime = function (dateTime) {
var hour;
var date;
var time;
var matches;
var minute;
var parts;
var second;
if (_.isDate(dateTime)) {
return true;
}
if (!_.isString(dateTime)) {
dateTime = dateTime.toString();
}
parts = dateTime.toLowerCase().split('t');
date = parts[0];
time = parts.length > 1 ? parts[1] : undefined;
if (!isValidDate(date)) {
return false;
}
matches = dateTimeRegExp.exec(time);
if (matches === null) {
return false;
}
hour = matches[1];
minute = matches[2];
second = matches[3];
if (hour > '23' || minute > '59' || second > '59') {
return false;
}
return true;
};
var throwErrorWithCode = function (code, msg) {
var err = new Error(msg);
err.code = code;
err.failedValidation = true;
throw err;
};
module.exports.validateAgainstSchema = function (schemaOrName, data, validator) {
var sanitizeError = function (obj) {
// Make anyOf/oneOf errors more human readable (Issue 200)
var defType = ['additionalProperties', 'items'].indexOf(obj.path[obj.path.length - 1]) > -1 ?
'schema' :
obj.path[obj.path.length - 2];
if (['ANY_OF_MISSING', 'ONE_OF_MISSING'].indexOf(obj.code) > -1) {
switch (defType) {
case 'parameters':
defType = 'parameter';
break;
case 'responses':
defType = 'response';
break;
case 'schema':
defType += ' ' + obj.path[obj.path.length - 1];
// no default
}
obj.message = 'Not a valid ' + defType + ' definition';
}
// Remove the params portion of the error
delete obj.params;
delete obj.schemaId;
if (obj.inner) {
_.each(obj.inner, function (nObj) {
sanitizeError(nObj);
});
}
};
var schema = _.isPlainObject(schemaOrName) ? _.cloneDeep(schemaOrName) : schemaOrName;
// We don't check this due to internal usage but if validator is not provided, schemaOrName must be a schema
if (_.isUndefined(validator)) {
validator = helpers.createJsonValidator([schema]);
}
var valid = validator.validate(data, schema);
if (!valid) {
try {
throwErrorWithCode('SCHEMA_VALIDATION_FAILED', 'Failed schema validation');
} catch (err) {
err.results = {
errors: _.map(validator.getLastErrors(), function (err) {
sanitizeError(err);
return err;
}),
warnings: []
};
throw err;
}
}
};
/**
* Validates a schema of type array is properly formed (when necessar).
*
* *param {object} schema - The schema object to validate
*
* @throws Error if the schema says it's an array but it is not formed properly
*
* @see {@link https://github.com/swagger-api/swagger-spec/issues/174}
*/
var validateArrayType = module.exports.validateArrayType = function (schema) {
// We have to do this manually for now
if (schema.type === 'array' && _.isUndefined(schema.items)) {
throwErrorWithCode('OBJECT_MISSING_REQUIRED_PROPERTY', 'Missing required property: items');
}
};
/**
* Validates the request or response content type (when necessary).
*
* @param {string[]} gPOrC - The valid consumes at the API scope
* @param {string[]} oPOrC - The valid consumes at the operation scope
* @param {object} reqOrRes - The request or response
*
* @throws Error if the content type is invalid
*/
module.exports.validateContentType = function (gPOrC, oPOrC, reqOrRes) {
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1
var isResponse = typeof reqOrRes.end === 'function';
var contentType = isResponse ? reqOrRes.getHeader('content-type') : reqOrRes.headers['content-type'];
var pOrC = _.map(_.union(gPOrC, oPOrC), function (contentType) {
return contentType.split(';')[0];
});
if (!contentType) {
if (isResponse) {
contentType = 'text/plain';
} else {
contentType = 'application/octet-stream';
}
}
contentType = contentType.split(';')[0];
if (pOrC.length > 0 && (isResponse ?
true :
['POST', 'PUT'].indexOf(reqOrRes.method) !== -1) && pOrC.indexOf(contentType) === -1) {
throw new Error('Invalid content type (' + contentType + '). These are valid: ' + pOrC.join(', '));
}
};
/**
* Validates the value against the allowable values (when necessary).
*
* @param {*} val - The parameter value
* @param {string[]} allowed - The allowable values
*
* @throws Error if the value is not allowable
*/
var validateEnum = module.exports.validateEnum = function (val, allowed) {
if (!_.isUndefined(allowed) && !_.isUndefined(val) && allowed.indexOf(val) === -1) {
throwErrorWithCode('ENUM_MISMATCH', 'Not an allowable value (' + allowed.join(', ') + '): ' + val);
}
};
/**
* Validates the value is less than the maximum (when necessary).
*
* @param {*} val - The parameter value
* @param {string} maximum - The maximum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the maximum in its comparison
*
* @throws Error if the value is greater than the maximum
*/
var validateMaximum = module.exports.validateMaximum = function (val, maximum, type, exclusive) {
var code = exclusive === true ? 'MAXIMUM_EXCLUSIVE' : 'MAXIMUM';
var testMax;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(maximum)) {
testMax = parseFloat(maximum);
if (exclusive && testVal >= testMax) {
throwErrorWithCode(code, 'Greater than or equal to the configured maximum (' + maximum + '): ' + val);
} else if (testVal > testMax) {
throwErrorWithCode(code, 'Greater than the configured maximum (' + maximum + '): ' + val);
}
}
};
/**
* Validates the array count is less than the maximum (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} maxItems - The maximum number of items
*
* @throws Error if the value contains more items than allowable
*/
var validateMaxItems = module.exports.validateMaxItems = function (val, maxItems) {
if (!_.isUndefined(maxItems) && val.length > maxItems) {
throwErrorWithCode('ARRAY_LENGTH_LONG', 'Array is too long (' + val.length + '), maximum ' + maxItems);
}
};
/**
* Validates the value length is less than the maximum (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} maxLength - The maximum length
*
* @throws Error if the value's length is greater than the maximum
*/
var validateMaxLength = module.exports.validateMaxLength = function (val, maxLength) {
if (!_.isUndefined(maxLength) && val.length > maxLength) {
throwErrorWithCode('MAX_LENGTH', 'String is too long (' + val.length + ' chars), maximum ' + maxLength);
}
};
/**
* Validates the value's property count is greater than the maximum (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} minProperties - The maximum number of properties
*
* @throws Error if the value's property count is less than the maximum
*/
var validateMaxProperties = module.exports.validateMaxProperties = function (val, maxProperties) {
var propCount = _.isPlainObject(val) ? Object.keys(val).length : 0;
if (!_.isUndefined(maxProperties) && propCount > maxProperties) {
throwErrorWithCode('MAX_PROPERTIES',
'Number of properties is too many (' + propCount + ' properties), maximum ' + maxProperties);
}
};
/**
* Validates the value array count is greater than the minimum (when necessary).
*
* @param {*} val - The parameter value
* @param {string} minimum - The minimum value
* @param {boolean} [exclusive=false] - Whether or not the value includes the minimum in its comparison
*
* @throws Error if the value is less than the minimum
*/
var validateMinimum = module.exports.validateMinimum = function (val, minimum, type, exclusive) {
var code = exclusive === true ? 'MINIMUM_EXCLUSIVE' : 'MINIMUM';
var testMin;
var testVal;
if (_.isUndefined(exclusive)) {
exclusive = false;
}
if (type === 'integer') {
testVal = parseInt(val, 10);
} else if (type === 'number') {
testVal = parseFloat(val);
}
if (!_.isUndefined(minimum)) {
testMin = parseFloat(minimum);
if (exclusive && testVal <= testMin) {
throwErrorWithCode(code, 'Less than or equal to the configured minimum (' + minimum + '): ' + val);
} else if (testVal < testMin) {
throwErrorWithCode(code, 'Less than the configured minimum (' + minimum + '): ' + val);
}
}
};
/**
* Validates the value value contains fewer items than allowed (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} minItems - The minimum number of items
*
* @throws Error if the value contains fewer items than allowable
*/
var validateMinItems = module.exports.validateMinItems = function (val, minItems) {
if (!_.isUndefined(minItems) && val.length < minItems) {
throwErrorWithCode('ARRAY_LENGTH_SHORT', 'Array is too short (' + val.length + '), minimum ' + minItems);
}
};
/**
* Validates the value length is less than the minimum (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} minLength - The minimum length
*
* @throws Error if the value's length is less than the minimum
*/
var validateMinLength = module.exports.validateMinLength = function (val, minLength) {
if (!_.isUndefined(minLength) && val.length < minLength) {
throwErrorWithCode('MIN_LENGTH', 'String is too short (' + val.length + ' chars), minimum ' + minLength);
}
};
/**
* Validates the value's property count is less than or equal to the minimum (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} minProperties - The minimum number of properties
*
* @throws Error if the value's property count is less than the minimum
*/
var validateMinProperties = module.exports.validateMinProperties = function (val, minProperties) {
var propCount = _.isPlainObject(val) ? Object.keys(val).length : 0;
if (!_.isUndefined(minProperties) && propCount < minProperties) {
throwErrorWithCode('MIN_PROPERTIES',
'Number of properties is too few (' + propCount + ' properties), minimum ' + minProperties);
}
};
/**
* Validates the value is a multiple of the provided number (when necessary).
*
* @param {*[]} val - The parameter value
* @param {number} multipleOf - The number that should divide evenly into the value
*
* @throws Error if the value contains fewer items than allowable
*/
var validateMultipleOf = module.exports.validateMultipleOf = function (val, multipleOf) {
if (!_.isUndefined(multipleOf) && val % multipleOf !== 0) {
throwErrorWithCode('MULTIPLE_OF', 'Not a multiple of ' + multipleOf);
}
};
/**
* Validates the value matches a pattern (when necessary).
*
* @param {string} name - The parameter name
* @param {*} val - The parameter value
* @param {string} pattern - The pattern
*
* @throws Error if the value does not match the pattern
*/
var validatePattern = module.exports.validatePattern = function (val, pattern) {
if (!_.isUndefined(pattern) && _.isNull(val.match(new RegExp(pattern)))) {
throwErrorWithCode('PATTERN', 'Does not match required pattern: ' + pattern);
}
};
/**
* Validates the value requiredness (when necessary).
*
* @param {*} val - The parameter value
* @param {boolean} required - Whether or not the parameter is required
*
* @throws Error if the value is required but is not present
*/
module.exports.validateRequiredness = function (val, required) {
if (!_.isUndefined(required) && required === true && _.isUndefined(val)) {
throwErrorWithCode('REQUIRED', 'Is required');
}
};
/**
* Validates the value type and format (when necessary).
*
* @param {string} version - The Swagger version
* @param {*} val - The parameter value
* @param {string} type - The parameter type
* @param {string} format - The parameter format
* @param {boolean} [skipError=false] - Whether or not to skip throwing an error (Useful for validating arrays)
*
* @throws Error if the value is not the proper type or format
*/
var validateTypeAndFormat = module.exports.validateTypeAndFormat =
function validateTypeAndFormat (version, val, type, format, allowEmptyValue, skipError) {
var result = true;
var oVal = val;
// If there is an empty value and we allow empty values, the value is always valid
if (allowEmptyValue === true && val === '') {
return;
}
if (_.isArray(val)) {
_.each(val, function (aVal, index) {
if (!validateTypeAndFormat(version, aVal, type, format, allowEmptyValue, true)) {
throwErrorWithCode('INVALID_TYPE', 'Value at index ' + index + ' is not a valid ' + type + ': ' + aVal);
}
});
} else {
switch (type) {
case 'boolean':
// Coerce the value only for Swagger 1.2
if (version === '1.2' && _.isString(val)) {
if (val === 'false') {
val = false;
} else if (val === 'true') {
val = true;
}
}
result = _.isBoolean(val);
break;
case 'integer':
// Coerce the value only for Swagger 1.2
if (version === '1.2' && _.isString(val)) {
val = Number(val);
}
result = _.isFinite(val) && (Math.round(val) === val);
break;
case 'number':
// Coerce the value only for Swagger 1.2
if (version === '1.2' && _.isString(val)) {
val = Number(val);
}
result = _.isFinite(val);
break;
case 'string':
if (!_.isUndefined(format)) {
switch (format) {
case 'date':
result = isValidDate(val);
break;
case 'date-time':
result = isValidDateTime(val);
break;
}
}
break;
case 'void':
result = _.isUndefined(val);
break;
}
}
if (skipError) {
return result;
} else if (!result) {
throwErrorWithCode('INVALID_TYPE',
type !== 'void' ?
'Not a valid ' + (_.isUndefined(format) ? '' : format + ' ') + type + ': ' + oVal :
'Void does not allow a value');
}
};
/**
* Validates the value values are unique (when necessary).
*
* @param {string[]} val - The parameter value
* @param {boolean} isUnique - Whether or not the parameter values are unique
*
* @throws Error if the value has duplicates
*/
var validateUniqueItems = module.exports.validateUniqueItems = function (val, isUnique) {
if (!_.isUndefined(isUnique) && _.uniq(val).length !== val.length) {
throwErrorWithCode('ARRAY_UNIQUE', 'Does not allow duplicate values: ' + val.join(', '));
}
};
/**
* Validates the value against the schema.
*
* @param {string} version - The Swagger version
* @param {object} schema - The schema to use to validate things
* @param {string[]} path - The path to the schema
* @param {*} [val] - The value to validate or undefined to use the default value provided by the schema
*
* @throws Error if any validation failes
*/
var validateSchemaConstraints = module.exports.validateSchemaConstraints = function (version, schema, path, val) {
var resolveSchema = function (schema) {
var resolved = schema;
if (resolved.schema) {
path = path.concat(['schema']);
resolved = resolveSchema(resolved.schema);
}
return resolved;
};
var type = schema.type;
var allowEmptyValue;
if (!type) {
if (!schema.schema) {
if (path[path.length - 2] === 'responses') {
type = 'void';
} else {
type = 'object';
}
} else {
schema = resolveSchema(schema);
type = schema.type || 'object';
}
}
allowEmptyValue = schema ? schema.allowEmptyValue === true : false;
try {
// Always perform this check even if there is no value
if (type === 'array') {
validateArrayType(schema);
}
// Default to default value if necessary
if (_.isUndefined(val)) {
val = version === '1.2' ? schema.defaultValue : schema.default;
path = path.concat([version === '1.2' ? 'defaultValue' : 'default']);
}
// If there is no explicit default value, return as all validations will fail
if (_.isUndefined(val)) {
return;
}
if (type === 'array') {
_.each(val, function (val, index) {
try {
validateSchemaConstraints(version, schema.items || {}, path.concat(index.toString()), val);
} catch (err) {
err.message = 'Value at index ' + index + ' ' + (err.code === 'INVALID_TYPE' ? 'is ' : '') +
err.message.charAt(0).toLowerCase() + err.message.substring(1);
throw err;
}
});
} else {
validateTypeAndFormat(version, val, type, schema.format, allowEmptyValue);
}
// Validate enum
validateEnum(val, schema.enum);
// Validate maximum
validateMaximum(val, schema.maximum, type, schema.exclusiveMaximum);
// Validate maxItems (Swagger 2.0+)
validateMaxItems(val, schema.maxItems);
// Validate maxLength (Swagger 2.0+)
validateMaxLength(val, schema.maxLength);
// Validate maxProperties (Swagger 2.0+)
validateMaxProperties(val, schema.maxProperties);
// Validate minimum
validateMinimum(val, schema.minimum, type, schema.exclusiveMinimum);
// Validate minItems
validateMinItems(val, schema.minItems);
// Validate minLength (Swagger 2.0+)
validateMinLength(val, schema.minLength);
// Validate minProperties (Swagger 2.0+)
validateMinProperties(val, schema.minProperties);
// Validate multipleOf (Swagger 2.0+)
validateMultipleOf(val, schema.multipleOf);
// Validate pattern (Swagger 2.0+)
validatePattern(val, schema.pattern);
// Validate uniqueItems
validateUniqueItems(val, schema.uniqueItems);
} catch (err) {
err.path = path;
throw err;
}
};
| {'content_hash': 'e59354f356a0a9edabb808cf4df36fd5', 'timestamp': '', 'source': 'github', 'line_count': 652, 'max_line_length': 116, 'avg_line_length': 30.207055214723926, 'alnum_prop': 0.6308707793856309, 'repo_name': 'nampreetsarao/billingAPI', 'id': 'd669a91692ac33a268663c57f76c1414c9919264', 'size': '20845', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'node_modules/swagger-tools/lib/validators.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '28326'}]} |
// ==ORIGINAL==
function /*[#|*/f/*|]*/() {
return fetch('https://typescriptlang.org').then(result => { console.log(result) });
}
// ==ASYNC FUNCTION::Convert to async function==
async function f() {
const result = await fetch('https://typescriptlang.org');
console.log(result);
} | {'content_hash': '9ffa5a34ba048ce1b3c36f979756637d', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 87, 'avg_line_length': 26.727272727272727, 'alnum_prop': 0.6258503401360545, 'repo_name': 'minestarks/TypeScript', 'id': '8aec78c6670660c847b7767bb949a8cc8b381446', 'size': '294', 'binary': False, 'copies': '26', 'ref': 'refs/heads/master', 'path': 'tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_basicNoReturnTypeAnnotation.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '3630'}, {'name': 'JavaScript', 'bytes': '175'}, {'name': 'PowerShell', 'bytes': '2855'}, {'name': 'Shell', 'bytes': '47'}, {'name': 'TypeScript', 'bytes': '90205277'}]} |
package com.arjuna.dbsupport.jeebatch;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.batch.api.BatchProperty;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
public class BatchDataConsumerMap
{
private static final Logger logger = Logger.getLogger(BatchDataConsumerMap.class.getName());
public static final String ID_PROPERTYNAME = "dataconsumer_id";
private BatchDataConsumerMap()
{
_batchDataConsumerMap = new HashMap<String, BatchDataConsumer>();
}
public void add(BatchDataConsumer batchDataConsumer)
{
_batchDataConsumerMap.put(batchDataConsumer.getId(), batchDataConsumer);
}
public BatchDataConsumer get(String id)
{
return _batchDataConsumerMap.get(id);
}
public boolean remove(BatchDataConsumer batchDataConsumer)
{
return (_batchDataConsumerMap.remove(batchDataConsumer.getId()) != null);
}
public static BatchDataConsumerMap getBatchDataConsumerMap()
{
logger.log(Level.FINE, "BatchDataConsumerMap.getBatchDataConsumerMap");
synchronized (_syncObject)
{
if (_instance == null)
_instance = new BatchDataConsumerMap();
}
logger.log(Level.FINE, "BatchDataConsumerMap.getBatchDataConsumerMap: returns = " + _instance);
return _instance;
}
@Produces
@BatchProperty
public BatchDataConsumerMap getBatchDataConsumerMap(final InjectionPoint injectionPoint)
{
logger.log(Level.FINE, "BatchDataConsumerMap.getBatchDataConsumerMap");
synchronized (_syncObject)
{
if (_instance == null)
_instance = new BatchDataConsumerMap();
}
logger.log(Level.FINE, "BatchDataConsumerMap.getBatchDataConsumerMap: returns = " + _instance);
return _instance;
}
private static Object _syncObject = new Object();
private static BatchDataConsumerMap _instance;
private Map<String, BatchDataConsumer> _batchDataConsumerMap;
}
| {'content_hash': 'e398015f0060da02d6bc6c7e2202527e', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 103, 'avg_line_length': 28.613333333333333, 'alnum_prop': 0.6919850885368126, 'repo_name': 'arjuna-technologies/JEEBatch_DataBroker_Support', 'id': '3268fc557c5ec0feaf8be21e59e76e4fcfb95861', 'size': '2255', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jeebatch-support/src/main/java/com/arjuna/dbsupport/jeebatch/BatchDataConsumerMap.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '29732'}]} |
<!--- Licensed to the Apache Software Foundation (ASF) under one -->
<!--- or more contributor license agreements. See the NOTICE file -->
<!--- distributed with this work for additional information -->
<!--- regarding copyright ownership. The ASF licenses this file -->
<!--- to you under the Apache License, Version 2.0 (the -->
<!--- "License"); you may not use this file except in compliance -->
<!--- with the License. You may obtain a copy of the License at -->
<!--- http://www.apache.org/licenses/LICENSE-2.0 -->
<!--- Unless required by applicable law or agreed to in writing, -->
<!--- software distributed under the License is distributed on an -->
<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->
<!--- KIND, either express or implied. See the License for the -->
<!--- specific language governing permissions and limitations -->
<!--- under the License. -->
# Image Classication using pretrained ResNet-50 model on Jetson module
This tutorial shows how to install MXNet v1.6 with Jetson support and use it to deploy a pre-trained MXNet model for image classification on a Jetson module.
## What's in this tutorial?
This tutorial shows how to:
1. Install MXNet v1.6 along with its dependencies on a Jetson module (This tutorial has been tested on Jetson Xavier AGX and Jetson Nano modules)
2. Deploy a pre-trained MXNet model for image classifcation on the module
## Who's this tutorial for?
This tutorial would benefit developers working on Jetson modules implementing deep learning applications. It assumes that readers have a Jetson module setup with Jetpack installed, are familiar with the Jetson working environment and are somewhat familiar with deep learning using MXNet.
## Prerequisites
To complete this tutorial, you need:
* A [Jetson module](https://developer.nvidia.com/embedded/develop/hardware) setup with [Jetpack 4.4](https://docs.nvidia.com/jetson/jetpack/release-notes/) installed using NVIDIA [SDK Manager](https://developer.nvidia.com/nvidia-sdk-manager)
* An SSH connection to the module OR display and keyboard setup to directly open shell on the module
* [Swapfile](https://help.ubuntu.com/community/SwapFaq) installed, especially on Jetson Nano for additional memory (increase memory if the inference script terminates with a `Killed` message)
## Installing MXNet v1.6 with Jetson support
To install MXNet with Jetson support, you can follow the [installation guide](https://mxnet.apache.org/get_started/jetson_setup) on MXNet official website.
Alternatively, you can also directly install MXNet v1.6 wheel with Jetson support, hosted on a public s3 bucket. Here are the steps to install this wheel:
*WARNING: this MXNet wheel is provided for your convenience but it contains packages that are not provided nor endorsed by the Apache Software Foundation.
As such, they might contain software components with more restrictive licenses than the Apache License and you'll need to decide whether they are appropriate for your usage. Like all Apache Releases, the
official Apache MXNet (incubating) releases consist of source code only and are found at https://mxnet.apache.org/get_started/download .*
We start by installing MXNet dependencies
```bash
sudo apt-get update
sudo apt-get install -y git build-essential libopenblas-dev libopencv-dev python3-pip
sudo pip3 install -U pip
```
Then we download and install MXNet v1.6 wheel with Jetson support
```bash
wget https://mxnet-public.s3.us-east-2.amazonaws.com/install/jetson/1.6.0/mxnet_cu102-1.6.0-py2.py3-none-linux_aarch64.whl
sudo pip3 install mxnet_cu102-1.6.0-py2.py3-none-linux_aarch64.whl
```
And we are done. You can test the installation now by importing mxnet from python3
```bash
>>> python3 -c 'import mxnet'
```
## Running a pre-trained ResNet-50 model on Jetson
We are now ready to run a pre-trained model and run inference on a Jetson module. In this tutorial we are using ResNet-50 model trained on Imagenet dataset. We run the following classification script with either cpu/gpu device using python3.
```{.python .input}
from mxnet import gluon
import mxnet as mx
# set device
gpus = mx.test_utils.list_gpus()
device = mx.gpu() if gpus else mx.cpu()
# load pre-trained model
net = gluon.model_zoo.vision.resnet50_v1(pretrained=True, device=device)
net.hybridize(static_alloc=True, static_shape=True)
# load labels
lbl_path = gluon.utils.download('http://data.mxnet.io/models/imagenet/synset.txt')
with open(lbl_path, 'r') as f:
labels = [l.rstrip() for l in f]
# download and format image as (batch, RGB, width, height)
img_path = gluon.utils.download('https://github.com/dmlc/web-data/blob/master/mxnet/doc/tutorials/python/predict_image/cat.jpg?raw=true')
img = mx.image.imread(img_path)
img = mx.image.imresize(img, 224, 224) # resize
img = mx.image.color_normalize(img.astype(dtype='float32')/255,
mean=mx.np.array([0.485, 0.456, 0.406]),
std=mx.np.array([0.229, 0.224, 0.225])) # normalize
img = img.transpose((2, 0, 1)) # channel first
img = mx.np.expand_dims(img, axis=0) # batchify
img = img.to_device(device)
prob = mx.npx.softmax(net(img)) # predict and normalize output
idx = mx.npx.topk(prob, k=5)[0] # get top 5 result
for i in idx:
i = int(i.item())
print('With prob = %.5f, it contains %s' % (prob[0,i].item(), labels[i]))
```
After running the above script, you should get the following output showing the five classes that the image most relates to with probability:
```bash
With prob = 0.41940, it contains n02119789 kit fox, Vulpes macrotis
With prob = 0.28096, it contains n02119022 red fox, Vulpes vulpes
With prob = 0.06857, it contains n02124075 Egyptian cat
With prob = 0.03046, it contains n02120505 grey fox, gray fox, Urocyon cinereoargenteus
With prob = 0.02770, it contains n02441942 weasel
```
| {'content_hash': '7c727f48b4fd628bbc757012a5a3d4df', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 287, 'avg_line_length': 49.6271186440678, 'alnum_prop': 0.7440232240437158, 'repo_name': 'apache/incubator-mxnet', 'id': '8787b2a7c53b640720803fa30b135bd3190fa5c8', 'size': '5856', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'docs/python_docs/python/tutorials/deploy/inference/image_classification_jetson.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '151356'}, {'name': 'C++', 'bytes': '12059300'}, {'name': 'CMake', 'bytes': '213440'}, {'name': 'Cuda', 'bytes': '1528224'}, {'name': 'Cython', 'bytes': '26285'}, {'name': 'Dockerfile', 'bytes': '54893'}, {'name': 'Groovy', 'bytes': '132682'}, {'name': 'Jupyter Notebook', 'bytes': '1889643'}, {'name': 'Makefile', 'bytes': '8991'}, {'name': 'PowerShell', 'bytes': '6699'}, {'name': 'Python', 'bytes': '8626713'}, {'name': 'Shell', 'bytes': '172547'}]} |
package jetbrains.exodus.tree.patricia;
import jetbrains.exodus.tree.ITree;
import jetbrains.exodus.tree.ITreeMutable;
import jetbrains.exodus.tree.TreeAddressIteratorTest;
public class PatriciaTreeAddressIteratorTest extends TreeAddressIteratorTest {
@Override
protected ITree createEmpty() {
return new PatriciaTreeEmpty(log, 0, false);
}
@Override
protected ITreeMutable createMutableTree(final boolean hasDuplicates, final int structureId) {
return null;
}
@Override
protected ITree openTree(long address, boolean hasDuplicates) {
return null;
}
}
| {'content_hash': '1a0f65d95beef22cad94140fe3d89711', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 98, 'avg_line_length': 25.75, 'alnum_prop': 0.7443365695792881, 'repo_name': 'morj/xodus', 'id': 'baa6a0a460ae87aca8bb08b712e5f02fb1e2967c', 'size': '1221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'environment/src/test/java/jetbrains/exodus/tree/patricia/PatriciaTreeAddressIteratorTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '3525709'}, {'name': 'JavaScript', 'bytes': '8532'}]} |
/*
* Copyright (C) 2004,
*
* Arjuna Technologies Ltd,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: xidcheck.java 2342 2006-03-30 13:06:17Z $
*/
package com.arjuna.ats.jta.xa.performance;
import io.narayana.perf.Measurement;
import io.narayana.perf.Worker;
import org.junit.Assert;
import org.junit.Test;
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.hp.mwtests.ts.jta.common.SampleOnePhaseResource;
import com.hp.mwtests.ts.jta.common.SampleOnePhaseResource.ErrorType;
public class OnePhase2PCPerformanceDefaultUnitTest
{
public static void main (String[] args)
{
OnePhase2PCPerformanceDefaultUnitTest obj = new OnePhase2PCPerformanceDefaultUnitTest();
obj.test();
}
@Test
public void test()
{
int warmUpCount = 0;
int numberOfThreads = 10;
int batchSize = 1000;
int numberOfTransactions = numberOfThreads * batchSize;
Measurement measurement = new Measurement.Builder(getClass().getName() + "_test1")
.maxTestTime(0L).numberOfCalls(numberOfTransactions)
.numberOfThreads(numberOfThreads).batchSize(batchSize)
.numberOfWarmupCalls(warmUpCount).build().measure(worker, worker);
System.out.printf("%s%n", measurement.getInfo());
Assert.assertEquals(0, measurement.getNumberOfErrors());
Assert.assertFalse(measurement.getInfo(), measurement.shouldFail());
long timeTaken = measurement.getTotalMillis();
System.out.println("ObjectStore used: "+arjPropertyManager.getObjectStoreEnvironmentBean().getObjectStoreType());
System.out.println("time for " + numberOfTransactions + " write transactions is " + timeTaken);
System.out.println("number of transactions: " + numberOfTransactions);
System.out.println("throughput: " + (float) (numberOfTransactions / (timeTaken / 1000.0)));
}
Worker<Void> worker = new Worker<Void>() {
javax.transaction.TransactionManager tm;
@Override
public void init() {
arjPropertyManager.getCoordinatorEnvironmentBean().setCommitOnePhase(false);
tm = com.arjuna.ats.jta.TransactionManager.transactionManager();
}
@Override
public void fini() {
}
@Override
public Void doWork(Void context, int batchSize, Measurement<Void> measurement) {
for (int i = 0; i < batchSize; i++)
{
try
{
tm.begin();
tm.getTransaction().enlistResource(new SampleOnePhaseResource(ErrorType.none, false));
tm.commit();
}
catch (Exception e)
{
if (measurement.getNumberOfErrors() == 0)
e.printStackTrace();
measurement.incrementErrorCount();
}
}
return context;
}
@Override
public void finishWork(Measurement<Void> measurement) {
}
};
}
| {'content_hash': '1a7a4e3e83aeec1cd30f11da936e6833', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 121, 'avg_line_length': 31.282828282828284, 'alnum_prop': 0.6186632224733614, 'repo_name': 'nmcl/wfswarm-example-arjuna-old', 'id': 'b7c1bff8fdb52d741bae2fab07db762022491c1c', 'size': '4082', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'graalvm/transactions/fork/narayana/ArjunaJTA/jta/tests/classes/com/arjuna/ats/jta/xa/performance/OnePhase2PCPerformanceDefaultUnitTest.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '6903'}]} |
"""
COMMAND-LINE SPECIFIC STUFF
=============================================================================
"""
import markdown
import sys
import optparse
import logging
from logging import DEBUG, INFO, CRITICAL
logger = logging.getLogger('MARKDOWN')
def parse_options():
"""
Define and parse `optparse` options for command-line usage.
"""
usage = """%prog [options] [INPUTFILE]
(STDIN is assumed if no INPUTFILE is given)"""
desc = "A Python implementation of John Gruber's Markdown. " \
"http://packages.python.org/Markdown/"
ver = "%%prog %s" % markdown.version
parser = optparse.OptionParser(usage=usage, description=desc, version=ver)
parser.add_option("-f", "--file", dest="filename", default=None,
help="Write output to OUTPUT_FILE. Defaults to STDOUT.",
metavar="OUTPUT_FILE")
parser.add_option("-e", "--encoding", dest="encoding",
help="Encoding for input and output files.",)
parser.add_option("-q", "--quiet", default = CRITICAL,
action="store_const", const=CRITICAL+10, dest="verbose",
help="Suppress all warnings.")
parser.add_option("-v", "--verbose",
action="store_const", const=INFO, dest="verbose",
help="Print all warnings.")
parser.add_option("-s", "--safe", dest="safe", default=False,
metavar="SAFE_MODE",
help="'replace', 'remove' or 'escape' HTML tags in input")
parser.add_option("-o", "--output_format", dest="output_format",
default='xhtml1', metavar="OUTPUT_FORMAT",
help="'xhtml1' (default), 'html4' or 'html5'.")
parser.add_option("--noisy",
action="store_const", const=DEBUG, dest="verbose",
help="Print debug messages.")
parser.add_option("-x", "--extension", action="append", dest="extensions",
help = "Load extension EXTENSION.", metavar="EXTENSION")
parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol",
action='store_false', default=True,
help="Observe number of first item of ordered lists.")
(options, args) = parser.parse_args()
if len(args) == 0:
input_file = None
else:
input_file = args[0]
if not options.extensions:
options.extensions = []
return {'input': input_file,
'output': options.filename,
'safe_mode': options.safe,
'extensions': options.extensions,
'encoding': options.encoding,
'output_format': options.output_format,
'lazy_ol': options.lazy_ol}, options.verbose
def run():
"""Run Markdown from the command line."""
# Parse options and adjust logging level if necessary
options, logging_level = parse_options()
if not options: sys.exit(2)
logger.setLevel(logging_level)
logger.addHandler(logging.StreamHandler())
# Run
markdown.markdownFromFile(**options)
if __name__ == '__main__':
# Support running module as a commandline command.
# Python 2.5 & 2.6 do: `python -m markdown.__main__ [options] [args]`.
# Python 2.7 & 3.x do: `python -m markdown [options] [args]`.
run()
| {'content_hash': 'f132678af78d8a637b7fb79f394e33e6', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 80, 'avg_line_length': 38.49425287356322, 'alnum_prop': 0.5634517766497462, 'repo_name': 'ryfeus/lambda-packs', 'id': '8ee8c8222ead206f5e837062fa3d9f8665edb886', 'size': '3349', 'binary': False, 'copies': '75', 'ref': 'refs/heads/master', 'path': 'Tensorflow_LightGBM_Scipy_nightly/source/markdown/__main__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '9768343'}, {'name': 'C++', 'bytes': '76566960'}, {'name': 'CMake', 'bytes': '191097'}, {'name': 'CSS', 'bytes': '153538'}, {'name': 'Cuda', 'bytes': '61768'}, {'name': 'Cython', 'bytes': '3110222'}, {'name': 'Fortran', 'bytes': '110284'}, {'name': 'HTML', 'bytes': '248658'}, {'name': 'JavaScript', 'bytes': '62920'}, {'name': 'MATLAB', 'bytes': '17384'}, {'name': 'Makefile', 'bytes': '152150'}, {'name': 'Python', 'bytes': '549307737'}, {'name': 'Roff', 'bytes': '26398'}, {'name': 'SWIG', 'bytes': '142'}, {'name': 'Shell', 'bytes': '7790'}, {'name': 'Smarty', 'bytes': '4090'}, {'name': 'TeX', 'bytes': '152062'}, {'name': 'XSLT', 'bytes': '305540'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta name="generator" content="PHPDoctor 2RC4 (http://phpdoctor.sourceforge.net/)">
<meta name="when" content="Wed, 14 Apr 2010 15:12:05 +0000">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css">
<link rel="start" href="../../../overview-summary.html">
<title>Entity (Doctrine)</title>
</head>
<body id="definition" onload="parent.document.title=document.title;">
<div class="header">
<h1>Doctrine</h1>
<ul>
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../../../doctrine/orm/mapping/package-summary.html">Namespace</a></li>
<li class="active">Class</li>
<li><a href="../../../doctrine/orm/mapping/package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="small_links">
<a href="../../../index.html" target="_top">Frames</a>
<a href="../../../doctrine/orm/mapping/entity.html" target="_top">No frames</a>
</div>
<div class="small_links">
Summary: <a href="#summary_field">Field</a> | <a href="#summary_method">Method</a> | <a href="#summary_constr">Constr</a>
Detail: <a href="#detail_field">Field</a> | <a href="#detail_method">Method</a> | <a href="#summary_constr">Constr</a>
</div>
<hr>
<div class="qualifiedName">Doctrine\ORM\Mapping\Entity</div>
<div class="location">/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php at line 28</div>
<h1>Class Entity</h1>
<pre class="tree">Class:Entity - Superclass: Annotation
<a href="../../../doctrine/common/annotations/annotation.html">Annotation</a><br> ⌊ <strong>Entity</strong><br /></pre>
<hr>
<p class="signature">public final class <strong>Entity</strong><br>extends <a href="../../../doctrine/common/annotations/annotation.html">Annotation</a>
</p>
<div class="comment" id="overview_description"><p>Annotations class</p></div>
<dl>
<dt>License:</dt>
<dd>http://www.opensource.org/licenses/lgpl-license.php LGPL</dd>
<dt>See Also:</dt>
<dd><code>www.doctrine-project.org</code></dd>
<dt>Since:</dt>
<dd>2.0</dd>
<dt>Version:</dt>
<dd>$Revision: 3938 $</dd>
<dt>Author:</dt>
<dd>Guilherme Blanco <[email protected]></dd>
<dd>Jonathan Wage <[email protected]></dd>
<dd>Roman Borschel <[email protected]></dd>
</dl>
<hr>
<table id="summary_field">
<tr><th colspan="2">Field Summary</th></tr>
<tr>
<td class="type"> mixed</td>
<td class="description"><p class="name"><a href="#repositoryClass">$repositoryClass</a></p></td>
</tr>
</table>
<table class="inherit">
<tr><th colspan="2">Fields inherited from Doctrine\Common\Annotations\Annotation</th></tr>
<tr><td><a href="../../../doctrine/common/annotations/annotation.html#value">value</a></td></tr></table>
<h2 id="detail_field">Field Detail</h2>
<div class="location">/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php at line 29</div>
<h3 id="repositoryClass">repositoryClass</h3>
<code class="signature">public mixed <strong>$repositoryClass</strong></code>
<div class="details">
</div>
<hr>
<div class="header">
<h1>Doctrine</h1>
<ul>
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../../../doctrine/orm/mapping/package-summary.html">Namespace</a></li>
<li class="active">Class</li>
<li><a href="../../../doctrine/orm/mapping/package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
</ul>
</div>
<div class="small_links">
<a href="../../../index.html" target="_top">Frames</a>
<a href="../../../doctrine/orm/mapping/entity.html" target="_top">No frames</a>
</div>
<div class="small_links">
Summary: <a href="#summary_field">Field</a> | <a href="#summary_method">Method</a> | <a href="#summary_constr">Constr</a>
Detail: <a href="#detail_field">Field</a> | <a href="#detail_method">Method</a> | <a href="#summary_constr">Constr</a>
</div>
<hr>
<p id="footer">This document was generated by <a href="http://peej.github.com/phpdoctor/">PHPDoctor: The PHP Documentation Creator</a></p>
</body>
</html> | {'content_hash': '7254836d1f17654c67b8d9ea154434d7', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 153, 'avg_line_length': 35.30508474576271, 'alnum_prop': 0.6622659625540086, 'repo_name': 'j13k/doctrine1', 'id': 'b923a39b27138957981fe73fd17a88ba130efa42', 'size': '4166', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/api/doctrine/orm/mapping/entity.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6908'}, {'name': 'JavaScript', 'bytes': '3353'}, {'name': 'PHP', 'bytes': '3138805'}]} |
<?php
namespace Phlexible\Bundle\ElementtypeBundle\Field;
/**
* Base field.
*
* @author Stephan Wentz <[email protected]>
*/
abstract class Field
{
/**
* @var bool
*/
protected $isField = false;
/**
* @var bool
*/
protected $isContainer = false;
/**
* @return string
*/
public function getIcon()
{
return 'p-elementtypes-field_fallback.gif';
}
/**
* @return bool
*/
abstract public function isContainer();
/**
* @return bool
*/
abstract public function isField();
/**
* @return bool
*/
public function hasContent()
{
return !$this->isContainer();
}
}
| {'content_hash': '2cbe3a8eae374fcb5ef8a605f74939a8', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 51, 'avg_line_length': 14.346938775510203, 'alnum_prop': 0.5305832147937412, 'repo_name': 'phlexible/phlexible', 'id': 'f2779e923b103e4b04cd1e451b48d8b2e8b071e6', 'size': '929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Phlexible/Bundle/ElementtypeBundle/Field/Field.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '340698'}, {'name': 'HTML', 'bytes': '18550'}, {'name': 'JavaScript', 'bytes': '5384154'}, {'name': 'PHP', 'bytes': '2551770'}]} |
using namespace MediaFoundationSamples;
#define CHECK_HR(hr) IF_FAILED_GOTO(hr, done)
typedef ComPtrList<IMFSample> VideoSampleList;
// Custom Attributes
// MFSamplePresenter_SampleCounter
// Data type: UINT32
//
// Version number for the video samples. When the presenter increments the version
// number, all samples with the previous version number are stale and should be
// discarded.
static const GUID MFSamplePresenter_SampleCounter =
{ 0xb0bb83cc, 0xf10f, 0x4e2e, { 0xaa, 0x2b, 0x29, 0xea, 0x5e, 0x92, 0xef, 0x85 } };
// MFSamplePresenter_SampleSwapChain
// Data type: IUNKNOWN
//
// Pointer to a Direct3D swap chain.
static const GUID MFSamplePresenter_SampleSwapChain =
{ 0xad885bd1, 0x7def, 0x414a, { 0xb5, 0xb0, 0xd3, 0xd2, 0x63, 0xd6, 0xe9, 0x6d } };
// Project headers.
#include "Helpers.h"
#include "Scheduler.h"
#include "PresentEngine.h"
#include "ISTVEVRPrstr.h"
#include "Presenter.h"
| {'content_hash': '06eb59fc40fad4c9bbee5ba15f3af3c9', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 83, 'avg_line_length': 28.060606060606062, 'alnum_prop': 0.7429805615550756, 'repo_name': 'jlverhagen/sagetv', 'id': '1201a2582d82b0678ca56ac2f77a6b04e691d0e6', 'size': '1278', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'third_party/Microsoft/EVRPresenter/EVRPresenter.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '91'}, {'name': 'C', 'bytes': '3926142'}, {'name': 'C++', 'bytes': '2474761'}, {'name': 'Java', 'bytes': '10567793'}, {'name': 'Makefile', 'bytes': '30486'}, {'name': 'NSIS', 'bytes': '1224'}, {'name': 'Objective-C', 'bytes': '1918'}, {'name': 'Shell', 'bytes': '44749'}]} |
package org.zstack.header.configuration;
import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.APIDeleteMessage;
import org.zstack.header.message.APIEvent;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;
import org.zstack.header.rest.RestRequest;
@Action(category = ConfigurationConstant.ACTION_CATEGORY)
@RestRequest(
path = "/instance-offerings/{uuid}",
method = HttpMethod.DELETE,
responseClass = APIDeleteInstanceOfferingEvent.class
)
public class APIDeleteInstanceOfferingMsg extends APIDeleteMessage implements InstanceOfferingMessage {
@APIParam(resourceType = InstanceOfferingVO.class, successIfResourceNotExisting = true,
checkAccount = true, operationTarget = true)
private String uuid;
public APIDeleteInstanceOfferingMsg() {
}
public APIDeleteInstanceOfferingMsg(String uuid) {
super();
this.uuid = uuid;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String getInstanceOfferingUuid() {
return uuid;
}
public static APIDeleteInstanceOfferingMsg __example__() {
APIDeleteInstanceOfferingMsg msg = new APIDeleteInstanceOfferingMsg();
msg.setUuid(uuid());
return msg;
}
}
| {'content_hash': '11fbba9593b7c28bccdbd18a7bf257c6', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 103, 'avg_line_length': 29.06122448979592, 'alnum_prop': 0.7183988764044944, 'repo_name': 'AlanJager/zstack', 'id': '449de230f3b06159cca4cd67e1f7bd6fa1379ce9', 'size': '1424', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'header/src/main/java/org/zstack/header/configuration/APIDeleteInstanceOfferingMsg.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4616'}, {'name': 'AspectJ', 'bytes': '74681'}, {'name': 'Batchfile', 'bytes': '2932'}, {'name': 'Groovy', 'bytes': '6776667'}, {'name': 'Java', 'bytes': '26341557'}, {'name': 'Python', 'bytes': '1062162'}, {'name': 'Shell', 'bytes': '176428'}]} |
/*
* 展覧会のシミュレーション
* ギャラリー内に複数のディスプレイを配置
*/
package simulation;
import net.unitedfield.cc.PAppletDisplayGeometry;
import test.p5.ColorBarsPApplet;
import test.p5.GravitySim;
import test.p5.ParticleSphere;
import com.jme3.app.SimpleApplication;
import com.jme3.light.AmbientLight;
import com.jme3.light.PointLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
public class ExhibitionPlaningSimlation extends SimpleApplication {
@Override
// アプリケーションの初期化
public void simpleInitApp() {
setupEnvironment();
setupObject();
}
public void setupEnvironment(){
// カメラの位置を設定
cam.setLocation(new Vector3f(4.0f, 1.5f, 22f));
cam.lookAtDirection(new Vector3f(10.0f, 0.0f, 0.0f), Vector3f.UNIT_Y);
flyCam.setDragToRotate(true);
// 環境光
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(0.5f));
this.rootNode.addLight(al);
// ギャラリーに等間隔にポイントライトを配置
PointLight light;
for(int j = 0; j < 5; j++){
for(int i = 0; i < 5; i++){
light = new PointLight();
light.setPosition(new Vector3f(i * 20.0f, 4.0f, j * 20.0f));
light.setColor(ColorRGBA.White.mult(0.06f));
rootNode.addLight(light);
}
}
// 壁のマテリアル
Material wall_mat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
wall_mat.setFloat("Shininess", 1);
wall_mat.setBoolean("UseMaterialColors", true);
wall_mat.setColor("Ambient", ColorRGBA.White);
wall_mat.setColor("Diffuse", ColorRGBA.White);
wall_mat.setColor("Specular", ColorRGBA.White);
// 配置
Spatial object = (Spatial) assetManager.loadModel("myAssets/Models/MOT_B2F_plain/MOT_B2F_plain.obj");
object.setMaterial(wall_mat);
rootNode.attachChild(object);
}
public void setupObject(){
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display1 = new PAppletDisplayGeometry("display", assetManager, 3.2f, 2.4f, new ColorBarsPApplet(), 400, 300, false);
display1.setLocalTranslation(10, 2.0f, 16f);
rootNode.attachChild(display1);
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display2 = new PAppletDisplayGeometry("display", assetManager, 3.2f, 2.4f, new ColorBarsPApplet(), 400, 300, false);
display2.setLocalTranslation(15, 2.0f, 16f);
rootNode.attachChild(display2);
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display3 = new PAppletDisplayGeometry("display", assetManager, 3.2f, 2.4f, new ColorBarsPApplet(), 400, 300, false);
display3.setLocalTranslation(20, 2.0f, 16f);
rootNode.attachChild(display3);
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display4 = new PAppletDisplayGeometry("display", assetManager, 3.2f, 2.4f, new ColorBarsPApplet(), 400, 300, false);
display4.setLocalTranslation(25, 2.0f, 16f);
rootNode.attachChild(display4);
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display5 = new PAppletDisplayGeometry("display", assetManager, 8f, 3f, new GravitySim(), 800, 600, false);
display5.setLocalTranslation(15f, 2.0f, 30.5f);
rootNode.attachChild(display5);
// ディスプレイをギャラリーに配置
PAppletDisplayGeometry display6 = new PAppletDisplayGeometry("display", assetManager, 4.8f, 3.6f, new ParticleSphere(), 400, 300, true);
display6.setLocalTranslation(31f, 2.0f, 22f);
display6.rotate(0, FastMath.PI * 0.5f, 0);
rootNode.attachChild(display6);
// 20人の女性をランダムにシーンに追加
for(int i = 0; i<20; i++){
Spatial girl = assetManager.loadModel("myAssets/Models/WalkingGirl/WalkingGirl.obj");
girl.rotate(0, (float)(Math.random()) * 180f, 0);
girl.setLocalTranslation((float)(Math.random()) * 30f, 0.1f, (float)(Math.random()) * 12f + 17);
this.rootNode.attachChild(girl);
}
}
@Override
// 状態の更新(アニメーション)
public void simpleUpdate(float tpf) {
}
@Override
public void destroy() {
super.destroy();
System.exit(0);
}
// メイン関数
public static void main(String[] args){
// アプリケーションのスタート
ExhibitionPlaningSimlation app = new ExhibitionPlaningSimlation();
app.setPauseOnLostFocus(false);
app.start();
}
}
| {'content_hash': '7ee9f09f921aa465561fd35e82c4e058', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 142, 'avg_line_length': 31.614173228346456, 'alnum_prop': 0.7287671232876712, 'repo_name': 'tado/CC4p52b6', 'id': 'd6a1927814e0ceb186afc00ff67d44541a4265f8', 'size': '4455', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/simulation/ExhibitionPlaningSimlation.java', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Groovy', 'bytes': '285'}, {'name': 'Java', 'bytes': '389726'}, {'name': 'Perl', 'bytes': '3564'}, {'name': 'Racket', 'bytes': '2260'}, {'name': 'Shell', 'bytes': '1693'}]} |
#ifndef STAN_MATH_PRIM_FUN_ONES_ROW_VECTOR_HPP
#define STAN_MATH_PRIM_FUN_ONES_ROW_VECTOR_HPP
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
namespace stan {
namespace math {
/**
* Return a row vector of ones
*
* @param K size of the row vector
* @return A row vector of size K with all elements initialised to 1.
* @throw std::domain_error if K is negative.
*/
inline auto ones_row_vector(int K) {
check_nonnegative("ones_row_vector", "size", K);
return Eigen::RowVectorXd::Constant(K, 1);
}
} // namespace math
} // namespace stan
#endif
| {'content_hash': '10e04965bf11d314d1ebc41c0c183357', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 69, 'avg_line_length': 23.36, 'alnum_prop': 0.7003424657534246, 'repo_name': 'stan-dev/math', 'id': 'd85b4364a387df70ecd60e03a9ca84a9c445c74c', 'size': '584', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'stan/math/prim/fun/ones_row_vector.hpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Ada', 'bytes': '89079'}, {'name': 'Assembly', 'bytes': '566183'}, {'name': 'Batchfile', 'bytes': '33076'}, {'name': 'C', 'bytes': '7093229'}, {'name': 'C#', 'bytes': '54013'}, {'name': 'C++', 'bytes': '166268432'}, {'name': 'CMake', 'bytes': '820167'}, {'name': 'CSS', 'bytes': '11283'}, {'name': 'Cuda', 'bytes': '342187'}, {'name': 'DIGITAL Command Language', 'bytes': '32438'}, {'name': 'Dockerfile', 'bytes': '118'}, {'name': 'Fortran', 'bytes': '2299405'}, {'name': 'HTML', 'bytes': '8320473'}, {'name': 'JavaScript', 'bytes': '38507'}, {'name': 'M4', 'bytes': '10525'}, {'name': 'Makefile', 'bytes': '74538'}, {'name': 'Meson', 'bytes': '4233'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'NASL', 'bytes': '106079'}, {'name': 'Objective-C', 'bytes': '420'}, {'name': 'Objective-C++', 'bytes': '420'}, {'name': 'Pascal', 'bytes': '75208'}, {'name': 'Perl', 'bytes': '47080'}, {'name': 'Python', 'bytes': '1958975'}, {'name': 'QMake', 'bytes': '18714'}, {'name': 'Roff', 'bytes': '30570'}, {'name': 'Ruby', 'bytes': '5532'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'SWIG', 'bytes': '5501'}, {'name': 'Shell', 'bytes': '187001'}, {'name': 'Starlark', 'bytes': '29435'}, {'name': 'XSLT', 'bytes': '567938'}, {'name': 'Yacc', 'bytes': '22343'}]} |
<?php
/**
** A base module for [select] and [select*]
**/
/* Shortcode handler */
add_action( 'wpcf7_init', 'wpcf7_add_shortcode_select' );
function wpcf7_add_shortcode_select() {
wpcf7_add_shortcode( array( 'select', 'select*' ),
'wpcf7_select_shortcode_handler', true );
}
function wpcf7_select_shortcode_handler( $tag ) {
$tag = new WPCF7_Shortcode( $tag );
if ( empty( $tag->name ) )
return '';
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error )
$class .= ' wpcf7-not-valid';
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );
if ( $tag->is_required() )
$atts['aria-required'] = 'true';
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$multiple = $tag->has_option( 'multiple' );
$include_blank = $tag->has_option( 'include_blank' );
$first_as_label = $tag->has_option( 'first_as_label' );
$values = $tag->values;
$labels = $tag->labels;
if ( $data = (array) $tag->get_data_option() ) {
$values = array_merge( $values, array_values( $data ) );
$labels = array_merge( $labels, array_values( $data ) );
}
$defaults = array();
$default_choice = $tag->get_default_option( null, 'multiple=1' );
foreach ( $default_choice as $value ) {
$key = array_search( $value, $values, true );
if ( false !== $key ) {
$defaults[] = (int) $key + 1;
}
}
if ( $matches = $tag->get_first_match_option( '/^default:([0-9_]+)$/' ) ) {
$defaults = array_merge( $defaults, explode( '_', $matches[1] ) );
}
$defaults = array_unique( $defaults );
$shifted = false;
if ( $include_blank || empty( $values ) ) {
array_unshift( $labels, '---' );
array_unshift( $values, '' );
$shifted = true;
} elseif ( $first_as_label ) {
$values[0] = '';
}
$html = '';
$hangover = wpcf7_get_hangover( $tag->name );
foreach ( $values as $key => $value ) {
$selected = false;
if ( $hangover ) {
if ( $multiple ) {
$selected = in_array( esc_sql( $value ), (array) $hangover );
} else {
$selected = ( $hangover == esc_sql( $value ) );
}
} else {
if ( ! $shifted && in_array( (int) $key + 1, (array) $defaults ) ) {
$selected = true;
} elseif ( $shifted && in_array( (int) $key, (array) $defaults ) ) {
$selected = true;
}
}
$item_atts = array(
'value' => $value,
'selected' => $selected ? 'selected' : '' );
$item_atts = wpcf7_format_atts( $item_atts );
$label = isset( $labels[$key] ) ? $labels[$key] : $value;
$html .= sprintf( '<option %1$s>%2$s</option>',
$item_atts, esc_html( $label ) );
}
if ( $multiple )
$atts['multiple'] = 'multiple';
$atts['name'] = $tag->name . ( $multiple ? '[]' : '' );
$atts = wpcf7_format_atts( $atts );
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
sanitize_html_class( $tag->name ), $atts, $html, $validation_error );
return $html;
}
/* Validation filter */
add_filter( 'wpcf7_validate_select', 'wpcf7_select_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_select*', 'wpcf7_select_validation_filter', 10, 2 );
function wpcf7_select_validation_filter( $result, $tag ) {
$tag = new WPCF7_Shortcode( $tag );
$name = $tag->name;
if ( isset( $_POST[$name] ) && is_array( $_POST[$name] ) ) {
foreach ( $_POST[$name] as $key => $value ) {
if ( '' === $value )
unset( $_POST[$name][$key] );
}
}
$empty = ! isset( $_POST[$name] ) || empty( $_POST[$name] ) && '0' !== $_POST[$name];
if ( $tag->is_required() && $empty ) {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
}
return $result;
}
/* Tag generator */
add_action( 'admin_init', 'wpcf7_add_tag_generator_menu', 25 );
function wpcf7_add_tag_generator_menu() {
if ( ! function_exists( 'wpcf7_add_tag_generator' ) )
return;
wpcf7_add_tag_generator( 'menu', __( 'Drop-down menu', 'contact-form-7' ),
'wpcf7-tg-pane-menu', 'wpcf7_tg_pane_menu' );
}
function wpcf7_tg_pane_menu( $contact_form ) {
?>
<div id="wpcf7-tg-pane-menu" class="hidden">
<form action="">
<table>
<tr><td><input type="checkbox" name="required" /> <?php echo esc_html( __( 'Required field?', 'contact-form-7' ) ); ?></td></tr>
<tr><td><?php echo esc_html( __( 'Name', 'contact-form-7' ) ); ?><br /><input type="text" name="name" class="tg-name oneline" /></td><td></td></tr>
</table>
<table>
<tr>
<td><code>id</code> (<?php echo esc_html( __( 'optional', 'contact-form-7' ) ); ?>)<br />
<input type="text" name="id" class="idvalue oneline option" /></td>
<td><code>class</code> (<?php echo esc_html( __( 'optional', 'contact-form-7' ) ); ?>)<br />
<input type="text" name="class" class="classvalue oneline option" /></td>
</tr>
<tr>
<td><?php echo esc_html( __( 'Choices', 'contact-form-7' ) ); ?><br />
<textarea name="values"></textarea><br />
<span style="font-size: smaller"><?php echo esc_html( __( "* One choice per line.", 'contact-form-7' ) ); ?></span>
</td>
<td>
<br /><input type="checkbox" name="multiple" class="option" /> <?php echo esc_html( __( 'Allow multiple selections?', 'contact-form-7' ) ); ?>
<br /><input type="checkbox" name="include_blank" class="option" /> <?php echo esc_html( __( 'Insert a blank item as the first option?', 'contact-form-7' ) ); ?>
</td>
</tr>
</table>
<div class="tg-tag"><?php echo esc_html( __( "Copy this code and paste it into the form left.", 'contact-form-7' ) ); ?><br /><input type="text" name="select" class="tag wp-ui-text-highlight code" readonly="readonly" onfocus="this.select()" /></div>
<div class="tg-mail-tag"><?php echo esc_html( __( "And, put this code into the Mail fields below.", 'contact-form-7' ) ); ?><br /><input type="text" class="mail-tag wp-ui-text-highlight code" readonly="readonly" onfocus="this.select()" /></div>
</form>
</div>
<?php
}
?> | {'content_hash': '9829e45f1216495cc56352505fa2167c', 'timestamp': '', 'source': 'github', 'line_count': 204, 'max_line_length': 249, 'avg_line_length': 29.205882352941178, 'alnum_prop': 0.5911379657603223, 'repo_name': 'kydrenw/showas', 'id': '835d05cbf496df97a80e100eefdd2c3fe7a10d0b', 'size': '5958', 'binary': False, 'copies': '431', 'ref': 'refs/heads/master', 'path': 'thietke143/wp-content/plugins/contact-form-7/modules/select.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '32078'}, {'name': 'ApacheConf', 'bytes': '1388'}, {'name': 'CSS', 'bytes': '11422906'}, {'name': 'EmberScript', 'bytes': '932'}, {'name': 'HTML', 'bytes': '442506'}, {'name': 'Handlebars', 'bytes': '1284'}, {'name': 'JavaScript', 'bytes': '7882326'}, {'name': 'PHP', 'bytes': '26329753'}, {'name': 'Ruby', 'bytes': '15558'}, {'name': 'Shell', 'bytes': '1369'}]} |
#ifndef __TASK_MANAGER_INTERNAL_H__
#define __TASK_MANAGER_INTERNAL_H__
#include <tinyara/config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#ifndef CONFIG_DISABLE_PTHREAD
#include <pthread.h>
#endif
#include <queue.h>
#include <sys/types.h>
#include <task_manager/task_manager.h>
/* Command Types */
#define TASKMGRCMD_REGISTER_BUILTIN 0
#define TASKMGRCMD_UNREGISTER 1
#define TASKMGRCMD_START 2
#define TASKMGRCMD_STOP 3
#define TASKMGRCMD_RESTART 4
#define TASKMGRCMD_PAUSE 5
#define TASKMGRCMD_RESUME 6
#define TASKMGRCMD_UNICAST_SYNC 7
#define TASKMGRCMD_UNICAST_ASYNC 8
#define TASKMGRCMD_BROADCAST 9
#define TASKMGRCMD_SET_UNICAST_CB 10
#define TASKMGRCMD_SET_BROADCAST_CB 11
#define TASKMGRCMD_SCAN_NAME 12
#define TASKMGRCMD_SCAN_HANDLE 13
#define TASKMGRCMD_SCAN_GROUP 14
#define TASKMGRCMD_REGISTER_TASK 15
#ifndef CONFIG_DISABLE_PTHREAD
#define TASKMGRCMD_REGISTER_PTHREAD 16
#endif
#define TASKMGRCMD_SET_STOP_CB 17
#define TASKMGRCMD_SET_EXIT_CB 18
#define TASKMGRCMD_ALLOC_BROADCAST_MSG 19
#define TASKMGRCMD_UNSET_BROADCAST_CB 20
#define TASKMGRCMD_DEALLOC_BROADCAST_MSG 21
#define TASKMGRCMD_SCAN_PID 22
/* Task Type */
#define TM_BUILTIN_TASK 0
#define TM_TASK 1
#ifndef CONFIG_DISABLE_PTHREAD
#define TM_PTHREAD 2
#endif
/* Message Queue Values */
#define TM_MQ_PRIO 50
#define TM_PUBLIC_MQ "tm_public_mq"
#define TM_PRIVATE_MQ "tm_priv_mq"
#define TM_UNICAST_MQ "tm_unicast_mq"
/* Wrapper of allocation APIs */
#define TM_ALLOC(a) malloc(a)
#define TM_FREE(a) free(a)
#define TM_ZALLOC(a) zalloc(a)
#ifdef CONFIG_CPP_HAVE_VARARGS
#define TM_ASPRINTF(p, f, ...) asprintf(p, f, ##__VA_ARGS__)
#else
#define TM_ASPRINTF asprintf
#endif
/**
* @brief Late Unregister Options
*/
#ifdef CONFIG_SCHED_LPWORK
#define TM_LATE_UNREGISTER_PRIO CONFIG_SCHED_LPWORKPRIORITY
#else
#define TM_LATE_UNREGISTER_PRIO 50
#endif
#define TM_INTERVAL_TRY_UNREGISTER 3
/**
* @brief Unicast Type
*/
#define TM_UNICAST_SYNC (0)
#define TM_UNICAST_ASYNC (1)
/**
* @brief Represent the msg size when input is NULL
*/
#define TM_NULL_MSG_SIZE (-1)
struct tm_termination_info_s {
tm_termination_callback_t cb;
tm_msg_t *cb_data;
};
typedef struct tm_termination_info_s tm_termination_info_t;
struct app_list_s {
int pid;
void *addr;
};
typedef struct app_list_s app_list_t;
struct app_list_data_s {
int type;
int idx;
int pid;
int tm_gid;
int status;
int permission;
tm_unicast_callback_t unicast_cb;
sq_queue_t broadcast_info_list;
tm_termination_info_t *stop_cb_info;
tm_termination_info_t *exit_cb_info;
};
typedef struct app_list_data_s app_list_data_t;
struct tm_request_s {
int cmd;
int caller_pid;
int handle;
int timeout;
char *q_name;
void* data;
};
typedef struct tm_request_s tm_request_t;
struct tm_response_s {
int status;
void *data;
};
typedef struct tm_response_s tm_response_t;
struct tm_broadcast_info_s {
struct tm_broadcast_info_s *flink;
int msg;
tm_broadcast_callback_t cb;
tm_msg_t *cb_data;
};
typedef struct tm_broadcast_info_s tm_broadcast_info_t;
struct tm_task_info_s {
char *name;
int priority;
int stack_size;
main_t entry;
char **argv;
};
typedef struct tm_task_info_s tm_task_info_t;
#ifndef CONFIG_DISABLE_PTHREAD
struct tm_pthread_info_s {
char *name;
pthread_attr_t *attr;
pthread_startroutine_t entry;
pthread_addr_t arg;
};
typedef struct tm_pthread_info_s tm_pthread_info_t;
#endif
struct tm_internal_msg_s {
int msg_size;
void *msg;
int type;
};
typedef struct tm_internal_msg_s tm_internal_msg_t;
struct tm_broadcast_internal_msg_s {
int size;
void *user_data;
tm_broadcast_info_t *cb_info;
};
typedef struct tm_broadcast_internal_msg_s tm_broadcast_internal_msg_t;
#define IS_INVALID_HANDLE(i) (i < 0 || i >= CONFIG_TASK_MANAGER_MAX_TASKS)
app_list_t *taskmger_get_applist(int handle);
#define TM_LIST_ADDR(handle) ((app_list_data_t *)taskmger_get_applist(handle)->addr)
#define TM_PID(handle) taskmger_get_applist(handle)->pid
#define TM_TYPE(handle) TM_LIST_ADDR(handle)->type
#define TM_IDX(handle) TM_LIST_ADDR(handle)->idx
#define TM_GID(handle) TM_LIST_ADDR(handle)->tm_gid
#define TM_STATUS(handle) TM_LIST_ADDR(handle)->status
#define TM_PERMISSION(handle) TM_LIST_ADDR(handle)->permission
#define TM_UNICAST_CB(handle) TM_LIST_ADDR(handle)->unicast_cb
#define TM_BROADCAST_INFO_LIST(handle) TM_LIST_ADDR(handle)->broadcast_info_list
#define TM_STOP_CB_INFO(handle) TM_LIST_ADDR(handle)->stop_cb_info
#define TM_EXIT_CB_INFO(handle) TM_LIST_ADDR(handle)->exit_cb_info
#define SET_QUEUE_NAME_WITH_DEALLOC_DATA(request_msg, timeout) \
do { \
if (timeout != TM_NO_RESPONSE) { \
TM_ASPRINTF(&request_msg.q_name, "%s%d", TM_PRIVATE_MQ, request_msg.caller_pid); \
if (request_msg.q_name == NULL) { \
if (request_msg.data != NULL) { \
TM_FREE(request_msg.data); \
} \
return TM_OUT_OF_MEMORY; \
} \
} \
} while (0)
#define SEND_REQUEST_TO_TM_WITH_DEALLOC_DATA(request_msg, status) \
do { \
status = taskmgr_send_request(&request_msg); \
if (status < 0) { \
if (request_msg.data != NULL) { \
TM_FREE(request_msg.data); \
} \
if (request_msg.q_name != NULL) { \
TM_FREE(request_msg.q_name); \
} \
return status; \
} \
} while (0)
#define RECV_RESPONSE_FROM_TM(request_msg, response_msg, status, timeout) \
do { \
status = taskmgr_receive_response(request_msg.q_name, &response_msg, timeout); \
TM_FREE(request_msg.q_name); \
} while (0)
#define SET_TERMINATION_CB(cb) \
do { \
act.sa_sigaction = (_sa_sigaction_t)cb; \
act.sa_flags = 0; \
(void)sigemptyset(&act.sa_mask); \
\
ret = sigaddset(&act.sa_mask, SIGTM_TERMINATION); \
if (ret < 0) { \
tmdbg("Failed to add signal set\n"); \
return TM_OPERATION_FAIL; \
} \
\
ret = sigaction(SIGTM_TERMINATION, &act, NULL); \
if (ret == (int)SIG_ERR) { \
tmdbg("sigaction Failed\n"); \
return TM_OPERATION_FAIL; \
} \
} while (0)
int taskmgr_send_request(tm_request_t *request_msg);
void taskmgr_send_response(char *q_name, int timeout, tm_response_t *response_msg, int ret_status);
int taskmgr_receive_response(char *q_name, tm_response_t *response_msg, int timeout);
bool taskmgr_is_permitted(int handle, pid_t pid);
int taskmgr_get_task_state(int handle);
int taskmgr_get_drvfd(void);
int taskmgr_get_handle_by_pid(int pid);
int taskmgr_calc_time(struct timespec *time, int timeout);
int taskmgr_get_task_manager_pid(void);
#endif
| {'content_hash': 'abe06730a9f9dbd9168865c1ac289b24', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 99, 'avg_line_length': 28.424, 'alnum_prop': 0.6425555868280326, 'repo_name': 'jsdosa/TizenRT', 'id': 'e2c3aa2c221df121dc0ca094be8f56906c15d23f', 'size': '7881', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'framework/src/task_manager/task_manager_internal.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2044301'}, {'name': 'Batchfile', 'bytes': '42646'}, {'name': 'C', 'bytes': '75170908'}, {'name': 'C++', 'bytes': '813875'}, {'name': 'HTML', 'bytes': '2990'}, {'name': 'Java', 'bytes': '63595'}, {'name': 'Makefile', 'bytes': '815989'}, {'name': 'Perl', 'bytes': '4361'}, {'name': 'PowerShell', 'bytes': '8511'}, {'name': 'Python', 'bytes': '263462'}, {'name': 'Roff', 'bytes': '4401'}, {'name': 'Shell', 'bytes': '233556'}, {'name': 'Tcl', 'bytes': '163693'}]} |
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
describe "Observer#notify_observers" do
before :each do
@observable = ObservableSpecs.new
@observer = ObserverCallbackSpecs.new
@observable.add_observer(@observer)
end
it "must call changed before notifying observers" do
@observer.value.should == nil
@observable.notify_observers("test")
@observer.value.should == nil
end
it "verifies observer responds to update" do
-> {
@observable.add_observer(@observable)
}.should raise_error(NoMethodError)
end
it "receives the callback" do
@observer.value.should == nil
@observable.changed
@observable.notify_observers("test")
@observer.value.should == "test"
end
end
| {'content_hash': '368090a9e5c5736d7b3d5d9263846e99', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 54, 'avg_line_length': 24.419354838709676, 'alnum_prop': 0.7001321003963011, 'repo_name': 'pmq20/ruby-compiler', 'id': '31f82e9266d7601a6f62e0ee48d94043da766f92', 'size': '757', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'ruby/spec/ruby/library/observer/notify_observers_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '35'}, {'name': 'Assembly', 'bytes': '545193'}, {'name': 'Awk', 'bytes': '750'}, {'name': 'Batchfile', 'bytes': '10078'}, {'name': 'C', 'bytes': '31431383'}, {'name': 'C++', 'bytes': '170471'}, {'name': 'CSS', 'bytes': '15720'}, {'name': 'Emacs Lisp', 'bytes': '122830'}, {'name': 'GDB', 'bytes': '29782'}, {'name': 'HTML', 'bytes': '22578'}, {'name': 'JavaScript', 'bytes': '18023'}, {'name': 'M4', 'bytes': '74049'}, {'name': 'Makefile', 'bytes': '320959'}, {'name': 'Perl', 'bytes': '302'}, {'name': 'Perl 6', 'bytes': '636'}, {'name': 'Python', 'bytes': '7484'}, {'name': 'Ragel', 'bytes': '24937'}, {'name': 'Roff', 'bytes': '3385688'}, {'name': 'Ruby', 'bytes': '18904964'}, {'name': 'Scheme', 'bytes': '668'}, {'name': 'Scilab', 'bytes': '745'}, {'name': 'Shell', 'bytes': '362849'}, {'name': 'TeX', 'bytes': '323102'}, {'name': 'XSLT', 'bytes': '13913'}, {'name': 'Yacc', 'bytes': '512205'}]} |
/*
libco.x86 (2009-10-12)
author: byuu
license: public domain
*/
#define LIBCO_C
#include "libco.h"
#include <assert.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
#if defined(_MSC_VER)
#define fastcall __fastcall
#elif defined(__GNUC__)
#define fastcall __attribute__((fastcall))
#else
#error "libco: please define fastcall macro"
#endif
static thread_local long co_active_buffer[64];
static thread_local cothread_t co_active_handle = 0;
static void (fastcall *co_swap)(cothread_t, cothread_t) = 0;
//ABI: fastcall
static unsigned char co_swap_function[] = {
0x89, 0x22, 0x8B, 0x21, 0x58, 0x89, 0x6A, 0x04, 0x89, 0x72, 0x08, 0x89, 0x7A, 0x0C, 0x89, 0x5A,
0x10, 0x8B, 0x69, 0x04, 0x8B, 0x71, 0x08, 0x8B, 0x79, 0x0C, 0x8B, 0x59, 0x10, 0xFF, 0xE0,
};
#ifdef _WIN32
#include <windows.h>
void co_init() {
DWORD old_privileges;
VirtualProtect(co_swap_function, sizeof co_swap_function, PAGE_EXECUTE_READWRITE, &old_privileges);
}
#else
#include <unistd.h>
#include <sys/mman.h>
void co_init() {
unsigned long addr = (unsigned long)co_swap_function;
unsigned long base = addr - (addr % sysconf(_SC_PAGESIZE));
unsigned long size = (addr - base) + sizeof co_swap_function;
mprotect((void*)base, size, PROT_READ | PROT_WRITE | PROT_EXEC);
}
#endif
static void crash() {
assert(0); /* called only if cothread_t entrypoint returns */
}
cothread_t co_active() {
if(!co_active_handle) co_active_handle = &co_active_buffer;
return co_active_handle;
}
cothread_t co_create(unsigned int size, void (*entrypoint)(void)) {
cothread_t handle;
if(!co_swap) {
co_init();
co_swap = (void (fastcall*)(cothread_t, cothread_t))co_swap_function;
}
if(!co_active_handle) co_active_handle = &co_active_buffer;
size += 256; /* allocate additional space for storage */
size &= ~15; /* align stack to 16-byte boundary */
if(handle = (cothread_t)malloc(size)) {
long *p = (long*)((char*)handle + size); /* seek to top of stack */
*--p = (long)crash; /* crash if entrypoint returns */
*--p = (long)entrypoint; /* start of function */
*(long*)handle = (long)p; /* stack pointer */
}
return handle;
}
void co_delete(cothread_t handle) {
free(handle);
}
void co_switch(cothread_t handle) {
register cothread_t co_previous_handle = co_active_handle;
co_swap(co_active_handle = handle, co_previous_handle);
}
#ifdef __cplusplus
}
#endif
| {'content_hash': 'fe61f5d0f8e80e33a18bc6d324adde05', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 103, 'avg_line_length': 26.78494623655914, 'alnum_prop': 0.6503412284223203, 'repo_name': 'nkatsaros/stronglink', 'id': 'd8f820b066554e39dcf4bae73eaf68d6c9018089', 'size': '2491', 'binary': False, 'copies': '22', 'ref': 'refs/heads/master', 'path': 'deps/libco/x86.c', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '851390'}, {'name': 'CSS', 'bytes': '2373'}, {'name': 'HTML', 'bytes': '11403'}, {'name': 'JavaScript', 'bytes': '64836'}, {'name': 'Makefile', 'bytes': '12684'}, {'name': 'Objective-C', 'bytes': '58055'}, {'name': 'PLSQL', 'bytes': '2911'}]} |
struct coordinate {
int y;
int x;
map* pointer;
coordinate* up;
coordinate* down;
};
// A game area - for reference, an island
class map {
public:
// -- ESSENTIAL
const unsigned int worldSeed;
const unsigned int seed;
const map* parentM;
map* left;
map* right;
map* down;
map* up;
int activated;
std::list<map*>::iterator xConnector; // For quick list accessing
std::list<std::list<map*>>::iterator yConnector;
// -- ESSENTIAL
// -- Settings
const size_t mapSide;
const size_t tileSide;
const size_t battlefieldSide;
const int y;
const int x;
const double push;
const bool diagonal;
const bool debug;
// -- Settings
// -- cordLists for randLine
std::vector<int> ySpareList;
std::vector<int> xSpareList;
// -- cordLists for randLine
// -- Maps
int* seedMap;
int* heightMap;
int* regionMemoryMap;
std::vector<tile> regionMap; // Darn naming -- http://stackoverflow.com/questions/15802006/how-can-i-create-objects-while-adding-them-into-a-vector
// -- Maps
map(unsigned int worldSeedInput, int yInput, int xInput, const double pushInput, size_t mapSideInput,
size_t tileSideInput, size_t battlefieldSideInput, const bool diagonalInput, const bool debugInput);
map(const map* parentMInput, int yDir, int xDir);
map(map const& src);
~map();
void deactivate();
bool activate();
};
| {'content_hash': '9fe5afe7c6f8e503709f04de67107970', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 148, 'avg_line_length': 22.76271186440678, 'alnum_prop': 0.6984363365599404, 'repo_name': 'artisauce/bold', 'id': '7aa8aa763683dc45e864d418dc21f267eafd5682', 'size': '1364', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/map.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '426182'}, {'name': 'C++', 'bytes': '174864'}, {'name': 'CMake', 'bytes': '6446'}]} |
{{#intro}}
Here's a hot tip: **line one**
Here's a hot tip: line two
{{/intro}}
| {'content_hash': '1e590b8a4bc554255d97edf0385125a3', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 30, 'avg_line_length': 13.666666666666666, 'alnum_prop': 0.5853658536585366, 'repo_name': 'gjtorikian/bartleby', 'id': '4613a7e0f7ddbdfede7f53a010edbb1eb3b54a47', 'size': '82', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/fixtures/render/intro.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '26598'}, {'name': 'Shell', 'bytes': '25'}]} |
/* ==========================================================================
Base styles: opinionated defaults
========================================================================== */
html,button,input,select,textarea {
color:#222;
}
html {
font-size:1em;
line-height:1.4;
}
/*
* Remove text-shadow in selection highlight: h5bp.com/i
* These selection rule sets have to be separate.
* Customize the background color to match your design.
*/
::-moz-selection {
background: #b3d4fc;
text-shadow: none;
}
::selection {
background: #b3d4fc;
text-shadow: none;
}
/*
* A better looking default horizontal rule
*/
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #ccc;
margin: 1em 0;
padding: 0;
}
/*
* Remove the gap between images, videos, audio and canvas and the bottom of
* their containers: h5bp.com/i/440
*/
audio,canvas,img,video {
vertical-align:middle;
}
/*
* Remove default fieldset styles.
*/
fieldset {
border:0;
margin:0;
padding:0;
}
/*
* Allow only vertical resizing of textareas.
*/
textarea {
resize:vertical;
}
/* ==========================================================================
Main styles
========================================================================== */
@font-face {
font-family: 'bariol_regularregular';
src: url('fonts/bariol_regular-webfont.eot');
src: url('fonts/bariol_regular-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/bariol_regular-webfont.woff2') format('woff2'),
url('fonts/bariol_regular-webfont.woff') format('woff'),
url('fonts/bariol_regular-webfont.ttf') format('truetype'),
url('fonts/bariol_regular-webfont.svg#bariol_regularregular') format('svg');
font-weight: normal;
font-style: normal;
}
html{-webkit-tap-highlight-color: rgba(0,0,0,0);-webkit-user-select: none;-webkit-touch-callout:none; background:#553984;}
/*-- Percent Loader -- */
#mainLoader{position:absolute;z-index:5; display:none; font-size:50px; line-height:50px; color:#FFF; text-align:center; width:100%; font-family:'bariol_regularregular';}
/*-- Content Wrapper -- */
#mainHolder{position:absolute; width:100%;height:100%;}
/*-- Browser Not Support -- */
#notSupportHolder{ width:90%; margin:5% auto; position:relative; color:#FFF; text-align:center; font-size:25px; font-family:'bariol_regularregular'; display:none;}
.notSupport{margin-top:200px;}
/*-- Mobile Rotate Instruction -- */
#rotateHolder{position:absolute;width:100%;height:100%;background-color:#0A1529;z-index:1000; display:none;}
.mobileRotate{width:200px;height:auto;position:absolute;text-align:center;}
.rotateDesc{color:#fff; font-size:15px; line-height:15px; font-family:'bariol_regularregular';}
/*-- Canvas Wrapper -- */
#canvasHolder{ display:none; width:100%; max-width:1024px; height:100%; margin:auto; position:relative;}
#gameCanvas, #box2dCanvas{ position:absolute;}
/*-- Form Wrapper -- */
#editWrapper{ display:none;}
#floatForm{ position:fixed; left:0; top:0; z-index:100; background:#755FBE; padding:15px; color:#FFF; width:280px; border:#fff solid 2px;}
#floatForm{ font-size:14px;}
#floatForm #questionWrapper, #floatForm #answersWrapper{ background:#553984; padding:10px;}
#floatForm input.button, #floatForm select.half, #floatForm label{ width:49%;}
#floatForm .formRow input, #floatForm .formRow select{ float:right; width:48%;}
#floatForm .formRow label{ float:left; width:48%;}
#floatForm input{ width:100%;}
#floatForm textarea{ float:left; width:100%;}
#floatForm select, #floatForm option{ width:100%;}
@-webkit-viewport{width:device-width}
@-moz-viewport{width:device-width}
@-ms-viewport{width:device-width}
@-o-viewport{width:device-width}
@viewport{width:device-width}
/* ==========================================================================
Helper classes
========================================================================== */
/*
* Image replacement
*/
.ir {
background-color: transparent;
border: 0;
overflow: hidden;
/* IE 6/7 fallback */
*text-indent: -9999px;
}
.ir:before {
content: "";
display: block;
width: 0;
height: 150%;
}
/*
* Hide from both screenreaders and browsers: h5bp.com/u
*/
.hidden {
display: none !important;
visibility: hidden;
}
/*
* Hide only visually, but have it available for screenreaders: h5bp.com/v
*/
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
/*
* Extends the .visuallyhidden class to allow the element to be focusable
* when navigated to via the keyboard: h5bp.com/p
*/
.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus {
clip: auto;
height: auto;
margin: 0;
overflow: visible;
position: static;
width: auto;
}
/*
* Hide visually and from screenreaders, but maintain layout
*/
.invisible {
visibility: hidden;
}
/*
* Clearfix: contain floats
*
* For modern browsers
* 1. The space content is one way to avoid an Opera bug when the
* `contenteditable` attribute is included anywhere else in the document.
* Otherwise it causes space to appear at the top and bottom of elements
* that receive the `clearfix` class.
* 2. The use of `table` rather than `block` is only necessary if using
* `:before` to contain the top-margins of child elements.
*/
.clearfix:before,.clearfix:after{
content: " "; /* 1 */
display: table; /* 2 */
}
.clearfix:after{
clear: both;
}
/*
* For IE 6/7 only
* Include this rule to trigger hasLayout and contain floats.
*/
.clearfix{
*zoom: 1;
}
/* ==========================================================================
EXAMPLE Media Queries for Responsive Design.
These examples override the primary ('mobile first') styles.
Modify as content requires.
========================================================================== */
@media only screen and (min-width: 35em) {
/* Style adjustments for viewports that meet the condition */
}
@media print,
(-o-min-device-pixel-ratio: 5/4),
(-webkit-min-device-pixel-ratio: 1.25),
(min-resolution: 120dpi) {
/* Style adjustments for high resolution devices */
}
/* ==========================================================================
Print styles.
Inlined to avoid required HTTP connection: h5bp.com/r
========================================================================== */
@media print{
* {
background:transparent!important;
color:#000!important;
box-shadow:none!important;
text-shadow:none!important;
}
a,a:visited {
text-decoration:underline;
}
a[href]:after {
content:" (" attr(href) ")";
}
abbr[title]:after {
content:" (" attr(title) ")";
}
.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after {
content:"";
}
pre,blockquote {
border:1px solid #999;
page-break-inside:avoid;
}
thead {
display:table-header-group;
}
tr,img {
page-break-inside:avoid;
}
img {
max-width:100%!important;
}
@page {
margin:.5cm;
}
p,h2,h3 {
orphans:3;
widows:3;
}
h2,h3 {
page-break-after:avoid;
}
}
| {'content_hash': 'e9300973209a57d3bcc118f50437f257', 'timestamp': '', 'source': 'github', 'line_count': 280, 'max_line_length': 169, 'avg_line_length': 25.03214285714286, 'alnum_prop': 0.6247681552289913, 'repo_name': 'tanu1993/Smart-Kids', 'id': '1cabf6d3a2819011ebe6fa4d759e3f3148e7ae2c', 'size': '7009', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'css/main.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '52889'}, {'name': 'HTML', 'bytes': '29820'}, {'name': 'JavaScript', 'bytes': '188213'}, {'name': 'PHP', 'bytes': '728'}, {'name': 'Ruby', 'bytes': '752'}]} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/mm_listitem"
android:gravity="center_vertical" >
<RelativeLayout
android:id="@+id/rl_group"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/avatar"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="4dp"
android:padding="5dp"
android:src="@drawable/roominfo_add_btn" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="7dp"
android:layout_toRightOf="@id/avatar"
android:text="@string/newchat"
android:textColor="#8C8C8C"
android:textSize="18sp" />
</RelativeLayout>
<TextView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/rl_group"
android:background="#E0E0E0"
android:visibility="gone" />
</RelativeLayout> | {'content_hash': '583b39c2744b15e4d9823340f2c7e0ec', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 74, 'avg_line_length': 35.595238095238095, 'alnum_prop': 0.5919732441471572, 'repo_name': 'leoliew/EasemobSample', 'id': 'e5ea92cb0242d55007f93655508cff6160bea0ca', 'size': '1495', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'res/layout/row_add_group.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '789852'}]} |
egret_h5.startGame = function () {
var context = egret.MainContext.instance;
context.touchContext = new egret.HTML5TouchContext();
context.deviceContext = new egret.HTML5DeviceContext();
context.netContext = new egret.HTML5NetContext();
egret.StageDelegate.getInstance().setDesignSize(480, 800);
context.stage = new egret.Stage();
var scaleMode = egret.MainContext.deviceType == egret.MainContext.DEVICE_MOBILE ? egret.StageScaleMode.SHOW_ALL : egret.StageScaleMode.NO_SCALE;
context.stage.scaleMode = scaleMode;
//WebGL is a Egret's beta property. It's off by default.
//WebGL是egret的Beta特性,默认关闭
var rendererType = 0;
if (rendererType == 1) {// egret.WebGLUtils.checkCanUseWebGL()) {
console.log("Use WebGL mode");
context.rendererContext = new egret.WebGLRenderer();
}
else {
context.rendererContext = new egret.HTML5CanvasRenderer();
}
egret.MainContext.instance.rendererContext.texture_scale_factor = 1;
context.run();
var rootClass;
if(document_class){
rootClass = egret.getDefinitionByName(document_class);
}
if(rootClass) {
var rootContainer = new rootClass();
if(rootContainer instanceof egret.DisplayObjectContainer){
context.stage.addChild(rootContainer);
}
else{
throw new Error("Document Class must be the subclass to egret.DisplayObjectContainer!");
}
}
else{
throw new Error("Document Class is not found!");
}
//处理屏幕大小改变
//implement for screen size change
var resizeTimer = null;
var doResize = function () {
context.stage.changeSize();
resizeTimer = null;
};
window.onresize = function () {
if (resizeTimer == null) {
resizeTimer = setTimeout(doResize, 300);
}
};
}; | {'content_hash': '759e1d9fad5429a6b6555b77628e154d', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 149, 'avg_line_length': 32.64912280701754, 'alnum_prop': 0.6523374529822676, 'repo_name': 'sleep2death/HelloEgretFromAtom', 'id': '4950d791cf25abcc026250d86e1a947aa1ee7d72', 'size': '3480', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'launcher/egret_loader.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4136'}, {'name': 'JavaScript', 'bytes': '993733'}, {'name': 'TypeScript', 'bytes': '10780'}]} |
#include "curl_setup.h"
#ifdef USE_WINDOWS_SSPI
#include <curl/curl.h>
#include "curl_sspi.h"
#include "curl_multibyte.h"
#include "system_win32.h"
#include "version_win32.h"
#include "warnless.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
/* We use our own typedef here since some headers might lack these */
typedef PSecurityFunctionTable (APIENTRY *INITSECURITYINTERFACE_FN)(VOID);
/* See definition of SECURITY_ENTRYPOINT in sspi.h */
#ifdef UNICODE
# ifdef _WIN32_WCE
# define SECURITYENTRYPOINT L"InitSecurityInterfaceW"
# else
# define SECURITYENTRYPOINT "InitSecurityInterfaceW"
# endif
#else
# define SECURITYENTRYPOINT "InitSecurityInterfaceA"
#endif
/* Handle of security.dll or secur32.dll, depending on Windows version */
HMODULE s_hSecDll = NULL;
/* Pointer to SSPI dispatch table */
PSecurityFunctionTable s_pSecFn = NULL;
/*
* Curl_sspi_global_init()
*
* This is used to load the Security Service Provider Interface (SSPI)
* dynamic link library portably across all Windows versions, without
* the need to directly link libcurl, nor the application using it, at
* build time.
*
* Once this function has been executed, Windows SSPI functions can be
* called through the Security Service Provider Interface dispatch table.
*
* Parameters:
*
* None.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_sspi_global_init(void)
{
INITSECURITYINTERFACE_FN pInitSecurityInterface;
/* If security interface is not yet initialized try to do this */
if(!s_hSecDll) {
/* Security Service Provider Interface (SSPI) functions are located in
* security.dll on WinNT 4.0 and in secur32.dll on Win9x. Win2K and XP
* have both these DLLs (security.dll forwards calls to secur32.dll) */
/* Load SSPI dll into the address space of the calling process */
if(curlx_verify_windows_version(4, 0, 0, PLATFORM_WINNT, VERSION_EQUAL))
s_hSecDll = Curl_load_library(TEXT("security.dll"));
else
s_hSecDll = Curl_load_library(TEXT("secur32.dll"));
if(!s_hSecDll)
return CURLE_FAILED_INIT;
/* Get address of the InitSecurityInterfaceA function from the SSPI dll */
pInitSecurityInterface =
CURLX_FUNCTION_CAST(INITSECURITYINTERFACE_FN,
(GetProcAddress(s_hSecDll, SECURITYENTRYPOINT)));
if(!pInitSecurityInterface)
return CURLE_FAILED_INIT;
/* Get pointer to Security Service Provider Interface dispatch table */
s_pSecFn = pInitSecurityInterface();
if(!s_pSecFn)
return CURLE_FAILED_INIT;
}
return CURLE_OK;
}
/*
* Curl_sspi_global_cleanup()
*
* This deinitializes the Security Service Provider Interface from libcurl.
*
* Parameters:
*
* None.
*/
void Curl_sspi_global_cleanup(void)
{
if(s_hSecDll) {
FreeLibrary(s_hSecDll);
s_hSecDll = NULL;
s_pSecFn = NULL;
}
}
/*
* Curl_create_sspi_identity()
*
* This is used to populate a SSPI identity structure based on the supplied
* username and password.
*
* Parameters:
*
* userp [in] - The user name in the format User or Domain\User.
* passwdp [in] - The user's password.
* identity [in/out] - The identity structure.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_create_sspi_identity(const char *userp, const char *passwdp,
SEC_WINNT_AUTH_IDENTITY *identity)
{
xcharp_u useranddomain;
xcharp_u user, dup_user;
xcharp_u domain, dup_domain;
xcharp_u passwd, dup_passwd;
size_t domlen = 0;
domain.const_tchar_ptr = TEXT("");
/* Initialize the identity */
memset(identity, 0, sizeof(*identity));
useranddomain.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)userp);
if(!useranddomain.tchar_ptr)
return CURLE_OUT_OF_MEMORY;
user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('\\'));
if(!user.const_tchar_ptr)
user.const_tchar_ptr = _tcschr(useranddomain.const_tchar_ptr, TEXT('/'));
if(user.tchar_ptr) {
domain.tchar_ptr = useranddomain.tchar_ptr;
domlen = user.tchar_ptr - useranddomain.tchar_ptr;
user.tchar_ptr++;
}
else {
user.tchar_ptr = useranddomain.tchar_ptr;
domain.const_tchar_ptr = TEXT("");
domlen = 0;
}
/* Setup the identity's user and length */
dup_user.tchar_ptr = _tcsdup(user.tchar_ptr);
if(!dup_user.tchar_ptr) {
curlx_unicodefree(useranddomain.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
identity->User = dup_user.tbyte_ptr;
identity->UserLength = curlx_uztoul(_tcslen(dup_user.tchar_ptr));
dup_user.tchar_ptr = NULL;
/* Setup the identity's domain and length */
dup_domain.tchar_ptr = malloc(sizeof(TCHAR) * (domlen + 1));
if(!dup_domain.tchar_ptr) {
curlx_unicodefree(useranddomain.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
_tcsncpy(dup_domain.tchar_ptr, domain.tchar_ptr, domlen);
*(dup_domain.tchar_ptr + domlen) = TEXT('\0');
identity->Domain = dup_domain.tbyte_ptr;
identity->DomainLength = curlx_uztoul(domlen);
dup_domain.tchar_ptr = NULL;
curlx_unicodefree(useranddomain.tchar_ptr);
/* Setup the identity's password and length */
passwd.tchar_ptr = curlx_convert_UTF8_to_tchar((char *)passwdp);
if(!passwd.tchar_ptr)
return CURLE_OUT_OF_MEMORY;
dup_passwd.tchar_ptr = _tcsdup(passwd.tchar_ptr);
if(!dup_passwd.tchar_ptr) {
curlx_unicodefree(passwd.tchar_ptr);
return CURLE_OUT_OF_MEMORY;
}
identity->Password = dup_passwd.tbyte_ptr;
identity->PasswordLength = curlx_uztoul(_tcslen(dup_passwd.tchar_ptr));
dup_passwd.tchar_ptr = NULL;
curlx_unicodefree(passwd.tchar_ptr);
/* Setup the identity's flags */
identity->Flags = SECFLAG_WINNT_AUTH_IDENTITY;
return CURLE_OK;
}
/*
* Curl_sspi_free_identity()
*
* This is used to free the contents of a SSPI identifier structure.
*
* Parameters:
*
* identity [in/out] - The identity structure.
*/
void Curl_sspi_free_identity(SEC_WINNT_AUTH_IDENTITY *identity)
{
if(identity) {
Curl_safefree(identity->User);
Curl_safefree(identity->Password);
Curl_safefree(identity->Domain);
}
}
#endif /* USE_WINDOWS_SSPI */
| {'content_hash': 'cc9050986fcd7e1c9442de85d9de836a', 'timestamp': '', 'source': 'github', 'line_count': 217, 'max_line_length': 78, 'avg_line_length': 28.170506912442395, 'alnum_prop': 0.6918043513823, 'repo_name': 'chaigler/Torque3D', 'id': '33108c48e97b31aa69c9ebda7e1fa403e0a27672', 'size': '7169', 'binary': False, 'copies': '9', 'ref': 'refs/heads/development', 'path': 'Engine/lib/curl/lib/curl_sspi.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '89079'}, {'name': 'Assembly', 'bytes': '199191'}, {'name': 'Awk', 'bytes': '42982'}, {'name': 'Batchfile', 'bytes': '68732'}, {'name': 'C', 'bytes': '44024765'}, {'name': 'C#', 'bytes': '54021'}, {'name': 'C++', 'bytes': '59643860'}, {'name': 'CMake', 'bytes': '988394'}, {'name': 'CSS', 'bytes': '55472'}, {'name': 'D', 'bytes': '101732'}, {'name': 'DIGITAL Command Language', 'bytes': '240259'}, {'name': 'Dockerfile', 'bytes': '988'}, {'name': 'GLSL', 'bytes': '515671'}, {'name': 'HLSL', 'bytes': '501593'}, {'name': 'HTML', 'bytes': '1664814'}, {'name': 'Java', 'bytes': '192558'}, {'name': 'JavaScript', 'bytes': '73468'}, {'name': 'Lex', 'bytes': '18784'}, {'name': 'Lua', 'bytes': '1288'}, {'name': 'M4', 'bytes': '885777'}, {'name': 'Makefile', 'bytes': '4069931'}, {'name': 'Metal', 'bytes': '3691'}, {'name': 'Module Management System', 'bytes': '15326'}, {'name': 'NSIS', 'bytes': '1193756'}, {'name': 'Objective-C', 'bytes': '685452'}, {'name': 'Objective-C++', 'bytes': '119396'}, {'name': 'Pascal', 'bytes': '48918'}, {'name': 'Perl', 'bytes': '720596'}, {'name': 'PowerShell', 'bytes': '12518'}, {'name': 'Python', 'bytes': '298716'}, {'name': 'Raku', 'bytes': '7894'}, {'name': 'Rich Text Format', 'bytes': '4380'}, {'name': 'Roff', 'bytes': '2152001'}, {'name': 'SAS', 'bytes': '13756'}, {'name': 'Shell', 'bytes': '1392232'}, {'name': 'Smalltalk', 'bytes': '6201'}, {'name': 'StringTemplate', 'bytes': '4329'}, {'name': 'WebAssembly', 'bytes': '13560'}, {'name': 'Yacc', 'bytes': '19731'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.