code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
| line_mean
float64 0.5
100
| line_max
int64 1
1k
| alpha_frac
float64 0.25
1
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|
/*
* smartMenu.js 智能上下文菜单插件
*
* Copyright 2011, zhangxinxu
*
* 2011-05-26 v1.0 编写
* 2011-06-03 v1.1 修复func中this失准问题
* 2011-10-10 v1.2 修复脚本放在<head>标签中层无法隐藏的问题
* 2011-10-30 v1.3 修复IE6~7下二级菜单移到第二项隐藏的问题
*/
(function($) {
var D = $(document).data("func", {});
$.smartMenu = $.noop;
$.fn.smartMenu = function(data, options) {
var B = $("body"), defaults = {
name: "",
offsetX: 2,
offsetY: 2,
textLimit: 6,
beforeShow: $.noop,
afterShow: $.noop
};
var params = $.extend(defaults, options || {});
var htmlCreateMenu = function(datum) {
var dataMenu = datum || data, nameMenu = datum? Math.random().toString(): params.name, htmlMenu = "", htmlCorner = "", clKey = "smart_menu_";
if ($.isArray(dataMenu) && dataMenu.length) {
htmlMenu = '<div id="smartMenu_'+ nameMenu +'" class="'+ clKey +'box">' +
'<div class="'+ clKey +'body">' +
'<ul class="'+ clKey +'ul">';
$.each(dataMenu, function(i, arr) {
if (i) {
htmlMenu = htmlMenu + '<li class="'+ clKey +'li_separate"> </li>';
}
if ($.isArray(arr)) {
$.each(arr, function(j, obj) {
var text = obj.text, htmlMenuLi = "", strTitle = "", rand = Math.random().toString().replace(".", "");
if (text) {
if (text.length > params.textLimit) {
text = text.slice(0, params.textLimit) + "…";
strTitle = ' title="'+ obj.text +'"';
}
if ($.isArray(obj.data) && obj.data.length) {
htmlMenuLi = '<li class="'+ clKey +'li" data-hover="true">' + htmlCreateMenu(obj.data) +
'<a href="javascript:" class="'+ clKey +'a"'+ strTitle +' data-key="'+ rand +'"><i class="'+ clKey +'triangle"></i>'+ text +'</a>' +
'</li>';
} else {
htmlMenuLi = '<li class="'+ clKey +'li">' +
'<a href="javascript:" class="'+ clKey +'a"'+ strTitle +' data-key="'+ rand +'">'+ text +'</a>' +
'</li>';
}
htmlMenu += htmlMenuLi;
var objFunc = D.data("func");
objFunc[rand] = obj.func;
D.data("func", objFunc);
}
});
}
});
htmlMenu = htmlMenu + '</ul>' +
'</div>' +
'</div>';
}
return htmlMenu;
}, funSmartMenu = function() {
var idKey = "#smartMenu_", clKey = "smart_menu_", jqueryMenu = $(idKey + params.name);
if (!jqueryMenu.size()) {
$("body").append(htmlCreateMenu());
//事件
$(idKey + params.name +" a").bind("click", function() {
var key = $(this).attr("data-key"),
callback = D.data("func")[key];
if ($.isFunction(callback)) {
callback.call(D.data("trigger"));
}
$.smartMenu.hide();
return false;
});
$(idKey + params.name +" li").each(function() {
var isHover = $(this).attr("data-hover"), clHover = clKey + "li_hover";
$(this).hover(function() {
var jqueryHover = $(this).siblings("." + clHover);
jqueryHover.removeClass(clHover).children("."+ clKey +"box").hide();
jqueryHover.children("."+ clKey +"a").removeClass(clKey +"a_hover");
if (isHover) {
$(this).addClass(clHover).children("."+ clKey +"box").show();
$(this).children("."+ clKey +"a").addClass(clKey +"a_hover");
}
});
});
return $(idKey + params.name);
}
return jqueryMenu;
};
$(this).each(function() {
this.oncontextmenu = function(e) {
//回调
if ($.isFunction(params.beforeShow)) {
params.beforeShow.call(this);
}
e = e || window.event;
//阻止冒泡
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
//隐藏当前上下文菜单,确保页面上一次只有一个上下文菜单
$.smartMenu.hide();
var st = D.scrollTop();
var jqueryMenu = funSmartMenu();
if (jqueryMenu) {
jqueryMenu.css({
display: "block",
left: e.clientX + params.offsetX,
top: e.clientY + st + params.offsetY
});
D.data("target", jqueryMenu);
D.data("trigger", this);
//回调
if ($.isFunction(params.afterShow)) {
params.afterShow.call(this);
}
return false;
}
};
});
if (!B.data("bind")) {
B.bind("click", $.smartMenu.hide).data("bind", true);
}
};
$.extend($.smartMenu, {
hide: function() {
var target = D.data("target");
if (target && target.css("display") === "block") {
target.hide();
}
},
remove: function() {
var target = D.data("target");
if (target) {
target.remove();
}
}
});
})(jQuery);
|
linmingling/demo
|
zt/task_mage/smartMenu.js
|
JavaScript
|
apache-2.0
| 4,697 | 27.974359 | 144 | 0.523567 | false |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0) on Mon Jan 13 19:53:40 EST 2014 -->
<title>Uses of Package org.drip.quant.calculus</title>
<meta name="date" content="2014-01-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.drip.quant.calculus";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/quant/calculus/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.drip.quant.calculus" class="title">Uses of Package<br>org.drip.quant.calculus</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.analytics.rates">org.drip.analytics.rates</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.drip.product.credit">org.drip.product.credit</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.product.definition">org.drip.product.definition</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.drip.product.rates">org.drip.product.rates</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.quant.calculus">org.drip.quant.calculus</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.drip.quant.common">org.drip.quant.common</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.quant.function1D">org.drip.quant.function1D</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.drip.spline.grid">org.drip.spline.grid</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.spline.segment">org.drip.spline.segment</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.drip.spline.stretch">org.drip.spline.stretch</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.drip.state.curve">org.drip.state.curve</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.analytics.rates">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/analytics/rates/package-summary.html">org.drip.analytics.rates</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.analytics.rates">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.product.credit">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/product/credit/package-summary.html">org.drip.product.credit</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.product.credit">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.product.definition">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/product/definition/package-summary.html">org.drip.product.definition</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.product.definition">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.product.rates">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/product/rates/package-summary.html">org.drip.product.rates</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.product.rates">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.quant.calculus">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.quant.calculus">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.quant.common">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/quant/common/package-summary.html">org.drip.quant.common</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.quant.common">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.quant.function1D">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/quant/function1D/package-summary.html">org.drip.quant.function1D</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/DerivativeControl.html#org.drip.quant.function1D">DerivativeControl</a>
<div class="block">DerivativeControl provides bumps needed for numerically approximating derivatives.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/Differential.html#org.drip.quant.function1D">Differential</a>
<div class="block">Differential holds the incremental differentials for the variate and the objective function.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.spline.grid">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/spline/grid/package-summary.html">org.drip.spline.grid</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.spline.grid">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.spline.segment">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/spline/segment/package-summary.html">org.drip.spline.segment</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.spline.segment">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.spline.stretch">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/spline/stretch/package-summary.html">org.drip.spline.stretch</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.spline.stretch">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.drip.state.curve">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/drip/quant/calculus/package-summary.html">org.drip.quant.calculus</a> used by <a href="../../../../org/drip/state/curve/package-summary.html">org.drip.state.curve</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/drip/quant/calculus/class-use/WengertJacobian.html#org.drip.state.curve">WengertJacobian</a>
<div class="block">WengertJacobian contains the Jacobian of the given set of Wengert variables to the set of parameters.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/quant/calculus/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
tectronics/splinelibrary
|
2.3/docs/Javadoc/org/drip/quant/calculus/package-use.html
|
HTML
|
apache-2.0
| 15,928 | 41.638356 | 282 | 0.655638 | false |
// Karma configuration
// Generated on Sat Oct 18 2014 17:38:05 GMT-0700 (PDT)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'requirejs'],
// list of files / patterns to load in the browser
files: [
{pattern: 'node_modules/chai/chai.js', included: false},
{pattern: 'node_modules/lodash/lodash.js', included: false},
{pattern: 'build/graphlib*.js', included: false},
{pattern: 'test/bundle.amd-test.js', included: false},
'test/test-main.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'Firefox', 'Safari'],
plugins: [
'karma-*'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
|
lqjack/blog
|
node_modules/graphlibrary/karma.amd.conf.js
|
JavaScript
|
apache-2.0
| 1,880 | 29.322581 | 120 | 0.654255 | false |
/*
* 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.
*/
package org.apache.spark.deploy.worker
import java.lang.management.ManagementFactory
import org.apache.spark.util.{IntParam, MemoryParam, Utils}
import org.apache.spark.SparkConf
/**
* Command-line parser for the worker.
*/
private[spark] class WorkerArguments(args: Array[String], conf: SparkConf) {
var host = Utils.localHostName()
var port = 0
var webUiPort = 8081
var cores = inferDefaultCores()
var memory = inferDefaultMemory()
var masters: Array[String] = null
var workDir: String = null
var propertiesFile: String = null
// Check for settings in environment variables
if (System.getenv("SPARK_WORKER_PORT") != null) {
port = System.getenv("SPARK_WORKER_PORT").toInt
}
if (System.getenv("SPARK_WORKER_CORES") != null) {
cores = System.getenv("SPARK_WORKER_CORES").toInt
}
if (conf.getenv("SPARK_WORKER_MEMORY") != null) {
memory = Utils.memoryStringToMb(conf.getenv("SPARK_WORKER_MEMORY"))
}
if (System.getenv("SPARK_WORKER_WEBUI_PORT") != null) {
webUiPort = System.getenv("SPARK_WORKER_WEBUI_PORT").toInt
}
if (System.getenv("SPARK_WORKER_DIR") != null) {
workDir = System.getenv("SPARK_WORKER_DIR")
}
parse(args.toList)
// This mutates the SparkConf, so all accesses to it must be made after this line
propertiesFile = Utils.loadDefaultSparkProperties(conf, propertiesFile)
if (conf.contains("spark.worker.ui.port")) {
webUiPort = conf.get("spark.worker.ui.port").toInt
}
checkWorkerMemory()
def parse(args: List[String]): Unit = args match {
case ("--ip" | "-i") :: value :: tail =>
Utils.checkHost(value, "ip no longer supported, please use hostname " + value)
host = value
parse(tail)
case ("--host" | "-h") :: value :: tail =>
Utils.checkHost(value, "Please use hostname " + value)
host = value
parse(tail)
case ("--port" | "-p") :: IntParam(value) :: tail =>
port = value
parse(tail)
case ("--cores" | "-c") :: IntParam(value) :: tail =>
cores = value
parse(tail)
case ("--memory" | "-m") :: MemoryParam(value) :: tail =>
memory = value
parse(tail)
case ("--work-dir" | "-d") :: value :: tail =>
workDir = value
parse(tail)
case "--webui-port" :: IntParam(value) :: tail =>
webUiPort = value
parse(tail)
case ("--properties-file") :: value :: tail =>
propertiesFile = value
parse(tail)
case ("--help") :: tail =>
printUsageAndExit(0)
case value :: tail =>
if (masters != null) { // Two positional arguments were given
printUsageAndExit(1)
}
masters = value.stripPrefix("spark://").split(",").map("spark://" + _)
parse(tail)
case Nil =>
if (masters == null) { // No positional argument was given
printUsageAndExit(1)
}
case _ =>
printUsageAndExit(1)
}
/**
* Print usage and exit JVM with the given exit code.
*/
def printUsageAndExit(exitCode: Int) {
System.err.println(
"Usage: Worker [options] <master>\n" +
"\n" +
"Master must be a URL of the form spark://hostname:port\n" +
"\n" +
"Options:\n" +
" -c CORES, --cores CORES Number of cores to use\n" +
" -m MEM, --memory MEM Amount of memory to use (e.g. 1000M, 2G)\n" +
" -d DIR, --work-dir DIR Directory to run apps in (default: SPARK_HOME/work)\n" +
" -i HOST, --ip IP Hostname to listen on (deprecated, please use --host or -h)\n" +
" -h HOST, --host HOST Hostname to listen on\n" +
" -p PORT, --port PORT Port to listen on (default: random)\n" +
" --webui-port PORT Port for web UI (default: 8081)\n" +
" --properties-file FILE Path to a custom Spark properties file.\n" +
" Default is conf/spark-defaults.conf.")
System.exit(exitCode)
}
def inferDefaultCores(): Int = {
Runtime.getRuntime.availableProcessors()
}
def inferDefaultMemory(): Int = {
val ibmVendor = System.getProperty("java.vendor").contains("IBM")
var totalMb = 0
try {
val bean = ManagementFactory.getOperatingSystemMXBean()
if (ibmVendor) {
val beanClass = Class.forName("com.ibm.lang.management.OperatingSystemMXBean")
val method = beanClass.getDeclaredMethod("getTotalPhysicalMemory")
totalMb = (method.invoke(bean).asInstanceOf[Long] / 1024 / 1024).toInt
} else {
val beanClass = Class.forName("com.sun.management.OperatingSystemMXBean")
val method = beanClass.getDeclaredMethod("getTotalPhysicalMemorySize")
totalMb = (method.invoke(bean).asInstanceOf[Long] / 1024 / 1024).toInt
}
} catch {
case e: Exception => {
totalMb = 2*1024
System.out.println("Failed to get total physical memory. Using " + totalMb + " MB")
}
}
// Leave out 1 GB for the operating system, but don't return a negative memory size
math.max(totalMb - 1024, 512)
}
def checkWorkerMemory(): Unit = {
if (memory <= 0) {
val message = "Memory can't be 0, missing a M or G on the end of the memory specification?"
throw new IllegalStateException(message)
}
}
}
|
Dax1n/spark-core
|
core/src/main/scala/org/apache/spark/deploy/worker/WorkerArguments.scala
|
Scala
|
apache-2.0
| 6,032 | 33.272727 | 98 | 0.635279 | false |
/* Licensed 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.
*/
package org.flowable.common.engine.impl.agenda;
import org.flowable.common.engine.impl.interceptor.CommandContext;
/**
* @author Joram Barrez
*/
@FunctionalInterface
public interface AgendaOperationRunner {
void executeOperation(CommandContext commandContext, Runnable runnable);
}
|
flowable/flowable-engine
|
modules/flowable-engine-common/src/main/java/org/flowable/common/engine/impl/agenda/AgendaOperationRunner.java
|
Java
|
apache-2.0
| 852 | 33.08 | 76 | 0.762911 | false |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services.
/// </summary>
/// <remarks>
/// Although the service itself is host agnotic, some of the services it consumes are only available in particular hosts (like Visual Studio).
/// Therefore this service doesn't export <see cref="IEditAndContinueService"/> on its own. Each host that supports EnC shall implement
/// a subclass that exports <see cref="IEditAndContinueService"/>.
/// </remarks>
internal class EditAndContinueService : IEditAndContinueService
{
private readonly IActiveStatementProvider _activeStatementProvider;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private DebuggingSession _debuggingSession;
private EditSession _editSession;
// TODO:
// Maps active statement instructions to their latest spans.
//
// Consider a function F containing a call to function G that is updated a couple of times
// before the thread returns from G and is remapped to the latest version of F.
// '>' indicates an active statement instruction.
//
// F v1: F v2: F v3:
// 0: nop 0: nop 0: nop
// 1> G() 1: nop 1: nop
// 2: nop 2: G() 2: nop
// 3: nop 3: nop 3> G()
//
// When entering a break state we query the debugger for current active statements.
// The returned statements reflect the current state of the threads in the runtime.
// When a change is successfully applied we remember changes in active statement spans.
// These changes are passed to the next edit session.
// We use them to map the spans for active statements returned by the debugger.
//
// In the above case the sequence of events is
// 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date
// 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2
// 2nd break: previously updated statements contains (F, v=1, il=1)->span2
// get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements
// 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3
// 3rd break: previously updated statements contains (F, v=1, il=1)->span3
// get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date
//
private ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions;
internal EditAndContinueService(IDiagnosticAnalyzerService diagnosticService, IActiveStatementProvider activeStatementProvider)
{
Debug.Assert(diagnosticService != null);
Debug.Assert(activeStatementProvider != null);
_diagnosticService = diagnosticService;
_activeStatementProvider = activeStatementProvider;
_nonRemappableRegions = ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>>.Empty;
}
public DebuggingSession DebuggingSession => _debuggingSession;
public EditSession EditSession => _editSession;
public void StartDebuggingSession(Solution currentSolution)
{
Contract.ThrowIfNull(currentSolution);
var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(currentSolution), null);
Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended.");
// TODO(tomat): allow changing documents
}
public void StartEditSession(
Solution currentSolution,
ImmutableDictionary<ProjectId, ProjectReadOnlyReason> projects,
bool stoppedAtException)
{
Contract.ThrowIfNull(currentSolution);
var newSession = new EditSession(
currentSolution,
_debuggingSession,
_activeStatementProvider,
projects,
_nonRemappableRegions,
stoppedAtException);
var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null);
Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended.");
// TODO(tomat): allow changing documents
// TODO(tomat): document added
}
public void EndEditSession(ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>> newRemappableRegionsOpt)
{
// first, publish null session:
var session = Interlocked.Exchange(ref _editSession, null);
Contract.ThrowIfNull(session, "Edit session has not started.");
// then cancel all ongoing work bound to the session:
session.Cancellation.Cancel();
// then clear all reported rude edits:
_diagnosticService.Reanalyze(_debuggingSession.InitialSolution.Workspace, documentIds: session.GetDocumentsWithReportedRudeEdits());
// Save new non-remappable regions for the next edit session.
// If no edits were made keep the previous regions.
if (newRemappableRegionsOpt != null)
{
_nonRemappableRegions = newRemappableRegionsOpt;
}
// TODO(tomat): allow changing documents
}
public void EndDebuggingSession()
{
var session = Interlocked.Exchange(ref _debuggingSession, null);
Contract.ThrowIfNull(session, "Debugging session has not started.");
}
public bool IsProjectReadOnly(ProjectId id, out SessionReadOnlyReason sessionReason, out ProjectReadOnlyReason projectReason)
{
if (_debuggingSession == null)
{
projectReason = ProjectReadOnlyReason.None;
sessionReason = SessionReadOnlyReason.None;
return false;
}
// run mode - all documents that belong to the workspace shall be read-only:
var editSession = _editSession;
if (editSession == null)
{
projectReason = ProjectReadOnlyReason.None;
sessionReason = SessionReadOnlyReason.Running;
return true;
}
// break mode and stopped at exception - all documents shall be read-only:
if (editSession.StoppedAtException)
{
projectReason = ProjectReadOnlyReason.None;
sessionReason = SessionReadOnlyReason.StoppedAtException;
return true;
}
// normal break mode - if the document belongs to a project that hasn't entered the edit session it shall be read-only:
if (editSession.Projects.TryGetValue(id, out projectReason))
{
sessionReason = SessionReadOnlyReason.None;
return projectReason != ProjectReadOnlyReason.None;
}
sessionReason = SessionReadOnlyReason.None;
projectReason = ProjectReadOnlyReason.MetadataNotAvailable;
return true;
}
public async Task<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
// It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so.
// We return null since there the concept of active statement only makes sense during break mode.
if (_editSession == null)
{
return null;
}
Debug.Assert(_debuggingSession != null);
// TODO: Avoid enumerating active statements for unchanged documents.
// We would need to add a document path parameter to be able to find the document we need to check for changes.
// https://github.com/dotnet/roslyn/issues/24324
var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
Document primaryDocument = _debuggingSession.InitialSolution.Workspace.CurrentSolution.GetDocument(baseActiveStatement.PrimaryDocumentId);
var documentAnalysis = await _editSession.GetDocumentAnalysis(primaryDocument).GetValueAsync(cancellationToken).ConfigureAwait(false);
var currentActiveStatements = documentAnalysis.ActiveStatements;
if (currentActiveStatements.IsDefault)
{
// The document has syntax errors.
return null;
}
return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return null;
}
}
public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken)
{
try
{
if (_editSession == null)
{
return null;
}
Debug.Assert(_debuggingSession != null);
// TODO: Avoid enumerating active statements for unchanged documents.
// We would need to add a document path parameter to be able to find the document we need to check for changes.
// https://github.com/dotnet/roslyn/issues/24324
var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement))
{
return null;
}
// TODO: avoid waiting for ERs of all active statements to be calculated and just calculate the one we are interested in at this moment:
// https://github.com/dotnet/roslyn/issues/24324
var baseExceptionRegions = await _editSession.BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false);
return baseExceptionRegions[baseActiveStatement.Ordinal].IsActiveStatementCovered;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return null;
}
}
}
}
|
paulvanbrenk/roslyn
|
src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs
|
C#
|
apache-2.0
| 11,707 | 46.971311 | 161 | 0.638531 | false |
#
# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
#
import json
import gevent
from kube_monitor import KubeMonitor
from kube_manager.common.kube_config_db import PodKM
class PodMonitor(KubeMonitor):
def __init__(self, args=None, logger=None, q=None):
super(PodMonitor, self).__init__(args, logger, q, PodKM,
resource_name='pods')
self.init_monitor()
self.logger.info("PodMonitor init done.");
def process_event(self, event):
pod_data = event['object']
event_type = event['type']
kind = event['object'].get('kind')
if event_type != 'DELETED':
if pod_data['spec'].get('hostNetwork'):
return
if not pod_data['spec'].get('nodeName'):
return
namespace = pod_data['metadata'].get('namespace')
pod_name = pod_data['metadata'].get('name')
if not namespace or not pod_name:
return
if self.db:
pod_uuid = self.db.get_uuid(event['object'])
if event_type != 'DELETED':
# Update Pod DB.
pod = self.db.locate(pod_uuid)
pod.update(pod_data)
else:
# Remove the entry from Pod DB.
self.db.delete(pod_uuid)
else:
pod_uuid = pod_data['metadata'].get('uid')
print("%s - Got %s %s %s:%s:%s"
%(self.name, event_type, kind, namespace, pod_name, pod_uuid))
self.logger.debug("%s - Got %s %s %s:%s:%s"
%(self.name, event_type, kind, namespace, pod_name, pod_uuid))
self.q.put(event)
def event_callback(self):
while True:
self.process()
gevent.sleep(0)
|
nischalsheth/contrail-controller
|
src/container/kube-manager/kube_manager/kube/pod_monitor.py
|
Python
|
apache-2.0
| 1,752 | 31.444444 | 76 | 0.540525 | false |
/*
* 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.
*/
package org.apache.camel.component.file.remote;
/**
* Abstract base class for unit testing using a secure FTP Server over SSL
* (explicit) and without client authentication.
*/
public abstract class FtpsServerExplicitSSLWithoutClientAuthTestSupport extends FtpsServerTestSupport {
/*
* @see org.apache.camel.component.file.remote.FtpServerSecureTestSupport#
* getClientAuth()
*/
@Override
protected String getClientAuth() {
return "false";
}
/*
* @see org.apache.camel.component.file.remote.FtpServerSecureTestSupport#
* useImplicit()
*/
@Override
protected boolean useImplicit() {
return false;
}
/*
* @see org.apache.camel.component.file.remote.FtpServerSecureTestSupport#
* getAuthValue()
*/
@Override
protected String getAuthValue() {
return AUTH_VALUE_SSL;
}
}
|
DariusX/camel
|
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpsServerExplicitSSLWithoutClientAuthTestSupport.java
|
Java
|
apache-2.0
| 1,693 | 32.196078 | 103 | 0.713526 | false |
package org.arquillian.cube.docker.drone.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.arquillian.cube.docker.drone.CubeDroneConfiguration;
import org.jboss.arquillian.test.spi.event.suite.After;
public class VideoFileDestination {
private static final File DEFAULT_LOCATION_OUTPUT_MAVEN = new File("target");
private static final File DEFAULT_LOCATION_OUTPUT_GRADLE = new File("build");
private VideoFileDestination() {
super();
}
public static Path getFinalLocation(After afterTestMethod, CubeDroneConfiguration cubeDroneConfiguration) {
return resolveTargetDirectory(cubeDroneConfiguration).resolve(getFinalVideoName(afterTestMethod));
}
public static Path resolveTargetDirectory(CubeDroneConfiguration cubeDroneConfiguration) {
Path output;
if (cubeDroneConfiguration.isVideoOutputDirectorySet()) {
output = Paths.get(cubeDroneConfiguration.getFinalDirectory());
} else {
if (DEFAULT_LOCATION_OUTPUT_GRADLE.exists()) {
output = DEFAULT_LOCATION_OUTPUT_GRADLE.toPath().resolve("reports").resolve("videos");
} else {
if (DEFAULT_LOCATION_OUTPUT_MAVEN.exists()) {
output = DEFAULT_LOCATION_OUTPUT_MAVEN.toPath().resolve("reports").resolve("videos");
} else {
if (!DEFAULT_LOCATION_OUTPUT_MAVEN.mkdirs()) {
throw new IllegalArgumentException("Couldn't create directory for storing videos");
}
output = DEFAULT_LOCATION_OUTPUT_MAVEN.toPath().resolve("reports").resolve("videos");
}
}
}
try {
Files.createDirectories(output);
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't create directory for storing videos");
}
return output;
}
private static String getFinalVideoName(After afterTestMethod) {
final String className = afterTestMethod.getTestClass().getName().replace('.', '_');
final String methodName = afterTestMethod.getTestMethod().getName();
return className + "_" + methodName + ".flv";
}
}
|
arquillian/arquillian-cube
|
docker/drone/src/main/java/org/arquillian/cube/docker/drone/util/VideoFileDestination.java
|
Java
|
apache-2.0
| 2,322 | 37.065574 | 111 | 0.655039 | false |
/**
* 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.
*/
#include "wx_debug_js_bridge.h"
#include "android/base/string/string_utils.h"
#include "android/wrap/wx_bridge.h"
#include "base/android/jniprebuild/jniheader/WXDebugJsBridge_jni.h"
#include "base/android/jni/jbytearray_ref.h"
#include "base/make_copyable.h"
#include "base/thread/waitable_event.h"
#include "base/string_util.h"
#include "core/render/manager/render_manager.h"
#include "core/bridge/platform_bridge.h"
#include "core/common/view_utils.h"
#include "core/manager/weex_core_manager.h"
#include "third_party/IPC/IPCResult.h"
#include "wson/wson_parser.h"
using namespace WeexCore;
namespace WeexCore {
bool RegisterWXDebugJsBridge(JNIEnv *env) {
return RegisterNativesImpl(env);
}
}
void resetWXBridge(JNIEnv *env, jobject object, jobject bridge, jstring className) {
ScopedJStringUTF8 classNameRef = ScopedJStringUTF8(env, className);
WXBridge::Instance()->Reset(env, bridge);
WXBridge::Instance()->reset_clazz(env, classNameRef.getChars());
}
void jsHandleSetJSVersion(JNIEnv *env, jobject object, jstring jsVersion) {
ScopedJStringUTF8 js_version_ref = ScopedJStringUTF8(env, jsVersion);
WeexCoreManager::Instance()->script_bridge()->core_side()->SetJSVersion(
js_version_ref.getChars());
}
void jsHandleReportException(JNIEnv *env, jobject object, jstring instanceId, jstring func,
jstring exceptionjstring) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
ScopedJStringUTF8 func_ref = ScopedJStringUTF8(env, func);
ScopedJStringUTF8 exception_string = ScopedJStringUTF8(env, exceptionjstring);
WeexCoreManager::Instance()
->script_bridge()
->core_side()
->ReportException(page_id_ref.getChars(), func_ref.getChars(), exception_string.getChars());
}
void jsHandleCallNative(JNIEnv *env, jobject object, jstring instanceId, jbyteArray tasks,
jstring callback) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
JByteArrayRef tasks_ref = JByteArrayRef(env, tasks);
ScopedJStringUTF8 callbask_ref = ScopedJStringUTF8(env, callback);
WeexCoreManager::Instance()->script_bridge()->core_side()->CallNative(page_id_ref.getChars(),
tasks_ref.getBytes(),
callbask_ref.getChars());
}
void jsHandleCallNativeModule(JNIEnv *env, jobject object, jstring instanceId, jstring module,
jstring method, jbyteArray arguments, jbyteArray options,
jboolean from) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
ScopedJStringUTF8 module_ref = ScopedJStringUTF8(env, module);
ScopedJStringUTF8 method_ref = ScopedJStringUTF8(env, method);
JByteArrayRef arg = JByteArrayRef(env, arguments);
JByteArrayRef opt = JByteArrayRef(env, options);
std::string ret_str = "";
std::unique_ptr<ValueWithType> ret = WeexCoreManager::Instance()
->script_bridge()
->core_side()
->CallNativeModule(page_id_ref.getChars(), module_ref.getChars(), method_ref.getChars(),
arg.getBytes(), arg.length(),
opt.getBytes(), opt.length());
switch (ret.get()->type) {
case ParamsType::INT32:
ret_str = to_string(ret.get()->value.int32Value);
break;
case ParamsType::INT64:
ret_str = to_string(ret.get()->value.int64Value);
break;
case ParamsType::FLOAT:
case ParamsType::DOUBLE:
ret_str = to_string(ret.get()->value.doubleValue);
break;
case ParamsType::VOID:
break;
case ParamsType::BYTEARRAY:
//ret.get()->value.byteArray->content;
//ret.get()->value.byteArray->length;
break;
case ParamsType::JSONSTRING:
weex::base::to_utf8(ret.get()->value.string->content, ret.get()->value.string->length);
break;
case ParamsType::STRING:
weex::base::to_utf8(ret.get()->value.string->content, ret.get()->value.string->length);
break;
default:
break;
}
}
void jsHandleCallNativeComponent(JNIEnv *env, jobject object, jstring instanceId, jstring componentRef,
jstring method,
jbyteArray arguments, jbyteArray options, jboolean from) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
ScopedJStringUTF8 component_ref_ref = ScopedJStringUTF8(env, componentRef);
ScopedJStringUTF8 method_ref = ScopedJStringUTF8(env, method);
JByteArrayRef arg = JByteArrayRef(env, arguments);
JByteArrayRef opt = JByteArrayRef(env, options);
WeexCoreManager::Instance()
->script_bridge()
->core_side()
->CallNativeComponent(page_id_ref.getChars(), component_ref_ref.getChars(),
method_ref.getChars(),
arg.getBytes(), arg.length(), opt.getBytes(), opt.length());
}
void jsHandleCallAddElement(JNIEnv *env, jobject object, jstring instanceId, jstring ref, jbyteArray dom,
jstring index) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
JByteArrayRef dom_ref = JByteArrayRef(env, dom);
ScopedJStringUTF8 index_ref = ScopedJStringUTF8(env, index);
WeexCoreManager::Instance()->script_bridge()->core_side()->AddElement(page_id_ref.getChars(),
ref_ref.getChars(),
dom_ref.getBytes(),
dom_ref.length(),
index_ref.getChars());
}
void jsHandleSetTimeout(JNIEnv *env, jobject object, jstring callbackId, jstring time) {
ScopedJStringUTF8 callback_id_ref = ScopedJStringUTF8(env, callbackId);
ScopedJStringUTF8 time_ref = ScopedJStringUTF8(env, time);
WeexCoreManager::Instance()->script_bridge()->core_side()->SetTimeout(callback_id_ref.getChars(),
time_ref.getChars());
}
void jsHandleCallNativeLog(JNIEnv *env, jobject object, jbyteArray str_array) {
JByteArrayRef str_array_ref = JByteArrayRef(env, str_array);
WeexCoreManager::Instance()->script_bridge()->core_side()->NativeLog(str_array_ref.getBytes());
}
void jsHandleCallCreateBody(JNIEnv *env, jobject object, jstring pageId, jbyteArray domStr,
jboolean from) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
JByteArrayRef dom_str_ref = JByteArrayRef(env, domStr);
WeexCoreManager::Instance()->script_bridge()->core_side()->CreateBody(page_id_ref.getChars(),
dom_str_ref.getBytes(),
dom_str_ref.length());
}
void jsHandleCallUpdateFinish(JNIEnv *env, jobject object, jstring instanceId, jbyteArray tasks,
jstring callback) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
JByteArrayRef tasks_ref = JByteArrayRef(env, tasks);
ScopedJStringUTF8 callback_ref = ScopedJStringUTF8(env, callback);
int result = -1;
result = WeexCoreManager::Instance()
->script_bridge()
->core_side()
->UpdateFinish(page_id_ref.getChars(), tasks_ref.getBytes(), tasks_ref.length(),
callback_ref.getChars(), strlen(callback_ref.getChars()));
}
void jsHandleCallCreateFinish(JNIEnv *env, jobject object, jstring pageId) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
WeexCoreManager::Instance()->script_bridge()->core_side()->CreateFinish(page_id_ref.getChars());
}
void jsHandleCallRefreshFinish(JNIEnv *env, jobject object, jstring instanceId, jbyteArray tasks,
jstring callback) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, instanceId);
JByteArrayRef tasks_ref = JByteArrayRef(env, tasks);
ScopedJStringUTF8 callback_ref = ScopedJStringUTF8(env, callback);
WeexCoreManager::Instance()
->script_bridge()
->core_side()
->RefreshFinish(page_id_ref.getChars(), tasks_ref.getBytes(), callback_ref.getChars());
}
void jsHandleCallUpdateAttrs(JNIEnv *env, jobject object, jstring pageId, jstring ref, jbyteArray data,
jboolean from) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
JByteArrayRef data_ref = JByteArrayRef(env, data);
WeexCoreManager::Instance()->script_bridge()->core_side()->UpdateAttrs(page_id_ref.getChars(),
ref_ref.getChars(),
data_ref.getBytes(),
data_ref.length());
}
void jsHandleCallUpdateStyle(JNIEnv *env, jobject object, jstring pageId, jstring ref, jbyteArray data,
jboolean from) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
JByteArrayRef data_ref = JByteArrayRef(env, data);
WeexCoreManager::Instance()->script_bridge()->core_side()->UpdateStyle(page_id_ref.getChars(),
ref_ref.getChars(),
data_ref.getBytes(),
data_ref.length());
}
void jsHandleCallRemoveElement(JNIEnv *env, jobject object, jstring pageId, jstring ref) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
WeexCoreManager::Instance()
->script_bridge()
->core_side()
->RemoveElement(page_id_ref.getChars(),
ref_ref.getChars());
}
void jsHandleCallMoveElement(JNIEnv *env, jobject object, jstring pageId, jstring ref,
jstring parentRef, jstring index_str) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
ScopedJStringUTF8 parent_ref_ref = ScopedJStringUTF8(env, parentRef);
ScopedJStringUTF8 index_str_ref = ScopedJStringUTF8(env, index_str);
int index_number = atoi(index_str_ref.getChars());
WeexCoreManager::Instance()->script_bridge()->core_side()->MoveElement(
page_id_ref.getChars(),
ref_ref.getChars(),
parent_ref_ref.getChars(),
index_number);
}
void jsHandleCallAddEvent(JNIEnv *env, jobject object, jstring pageId, jstring ref, jstring event) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
ScopedJStringUTF8 event_ref = ScopedJStringUTF8(env, event);
WeexCoreManager::Instance()->script_bridge()->core_side()->AddEvent(page_id_ref.getChars(),
ref_ref.getChars(),
event_ref.getChars());
}
void jsHandleCallRemoveEvent(JNIEnv *env, jobject object, jstring pageId, jstring ref,
jstring event) {
ScopedJStringUTF8 page_id_ref = ScopedJStringUTF8(env, pageId);
ScopedJStringUTF8 ref_ref = ScopedJStringUTF8(env, ref);
ScopedJStringUTF8 event_ref = ScopedJStringUTF8(env, event);
WeexCoreManager::Instance()->script_bridge()->core_side()->RemoveEvent(page_id_ref.getChars(),
ref_ref.getChars(),
event_ref.getChars());
}
void jsHandleSetInterval(JNIEnv *env, jobject object, jstring instanceId, jstring callbackId,
jstring time) {}
void jsHandleClearInterval(JNIEnv *env, jobject object, jstring instanceId, jstring callbackId) {}
void jsHandleCallGCanvasLinkNative(JNIEnv *env, jobject object, jstring contextId, int type,
jstring val) {}
|
alibaba/weex
|
weex_core/Source/android/wrap/wx_debug_js_bridge.cpp
|
C++
|
apache-2.0
| 13,266 | 43.367893 | 105 | 0.631992 | false |
/*
Derby - Class com.pivotal.gemfirexd.internal.client.am.SectionManager
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.
*/
package com.pivotal.gemfirexd.internal.client.am;
import java.lang.ref.WeakReference;
import com.pivotal.gemfirexd.internal.shared.common.reference.SQLState;
public class SectionManager {
String collection_;
Agent agent_;
// Cursor holdability attributes used as package cluster indices.
// Not defined in PackageBindOptions because this attribute is part of the
// declare cursor [with hold] sql string based on section binds.
// By convention, we bind all sections in the same package with
// the same holdability.
final static int HOLD = 0;
final static int NO_HOLD = 1;
// The following stack of available sections is
// for pooling and recycling previously used sections.
// For performance, the section objects themselves are pooled,
// rather than just keeping track of free section numbers;
// this way, we don't have to new-up a section if one is available in the pool.
java.util.Stack freeSectionsNonHold_ = null;
java.util.Stack freeSectionsHold_ = null;
int nextAvailableSectionNumber_ = 1;
// store package consistency token information and initialized in
// setPKGNAMCBytes
// holdPKGNAMCBytes stores PKGNAMCBytes when holdability is hold
// noHoldPKGNAMCBytes stores PKGNAMCBytes when holdability is no hold
public byte[] holdPKGNAMCBytes = null;
public byte[] noHoldPKGNAMCBytes = null;
final static String packageNameWithHold__ = "SYSLH000";
final static String packageNameWithNoHold__ = "SYSLN000";
final static String cursorNamePrefixWithHold__ = "SQL_CURLH000C";
final static String cursorNamePrefixWithNoHold__ = "SQL_CURLN000C";
// Jdbc 1 positioned updates are implemented via
// sql scan for "...where current of <users-cursor-name>",
// the addition of mappings from cursor names to query sections,
// and the subtitution of <users-cursor-name> with <canned-cursor-name> in the pass-thru sql string
// "...where current of <canned-cursor-name>" when user-defined cursor names are used.
// Both "canned" cursor names (from our jdbc package set) and user-defined cursor names are mapped.
// Statement.cursorName_ is initialized to null until the cursor name is requested or set.
// When set (s.setCursorName()) with a user-defined name, then it is added to the cursor map at that time;
// When requested (rs.getCursorName()), if the cursor name is still null,
// then is given the canned cursor name as defined by our jdbc package set and added to the cursor map.
// Still need to consider how positioned updates should interact with multiple result sets from a stored.
private java.util.Hashtable positionedUpdateCursorNameToQuerySection_ = new java.util.Hashtable();
// Cursor name to ResultSet mapping is needed for positioned updates to check whether
// a ResultSet is scrollable. If so, exception is thrown.
private java.util.Hashtable positionedUpdateCursorNameToResultSet_ = new java.util.Hashtable();
String databaseName;
int maxNumSections_ = 32768;
public SectionManager(String collection, Agent agent, String databaseName) {
collection_ = collection;
agent_ = agent;
this.databaseName = databaseName;
freeSectionsNonHold_ = new java.util.Stack();
freeSectionsHold_ = new java.util.Stack();
}
/**
* Store the Packagename and consistency token information This is called from Section.setPKGNAMCBytes
*
* @param b bytearray that has the PKGNAMC information to be stored
* @param resultSetHoldability depending on the holdability store it in the correct byte array packagename and
* consistency token information for when holdability is set to HOLD_CURSORS_OVER_COMMIT
* is stored in holdPKGNAMCBytes and in noHoldPKGNAMCBytes when holdability is set to
* CLOSE_CURSORS_AT_COMMIT
*/
public void setPKGNAMCBytes(byte[] b, int resultSetHoldability) {
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT) {
agent_.sectionManager_.holdPKGNAMCBytes = b;
} else if (resultSetHoldability == ResultSet.CLOSE_CURSORS_AT_COMMIT) {
agent_.sectionManager_.noHoldPKGNAMCBytes = b;
}
}
//------------------------entry points----------------------------------------
// Get a section for either a jdbc update or query statement.
public Section getDynamicSection(int resultSetHoldability) throws SqlException {
int cursorHoldIndex;
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT) {
return getSection(freeSectionsHold_, packageNameWithHold__, cursorNamePrefixWithHold__, resultSetHoldability);
} else if (resultSetHoldability == ResultSet.CLOSE_CURSORS_AT_COMMIT) {
return getSection(freeSectionsNonHold_, packageNameWithNoHold__, cursorNamePrefixWithNoHold__, resultSetHoldability);
} else {
throw new SqlException(agent_.logWriter_,
new ClientMessageId(SQLState.UNSUPPORTED_HOLDABILITY_PROPERTY),
new Integer(resultSetHoldability));
}
}
protected Section getSection(java.util.Stack freeSections, String packageName, String cursorNamePrefix, int resultSetHoldability) throws SqlException {
if (!freeSections.empty()) {
return (Section) freeSections.pop();
} else if (nextAvailableSectionNumber_ < (maxNumSections_ - 1)) {
String cursorName = cursorNamePrefix + nextAvailableSectionNumber_;
Section section = new Section(agent_, packageName, nextAvailableSectionNumber_, cursorName, resultSetHoldability);
nextAvailableSectionNumber_++;
return section;
} else
// unfortunately we have run out of sections
{
throw new SqlException(agent_.logWriter_,
new ClientMessageId(SQLState.EXCEEDED_MAX_SECTIONS),
"32k");
}
}
public void freeSection(Section section, int resultSetHoldability) {
if (resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT) {
this.freeSectionsHold_.push(section);
} else if (resultSetHoldability == ResultSet.CLOSE_CURSORS_AT_COMMIT) {
this.freeSectionsNonHold_.push(section);
}
}
// Get a section for a jdbc 2 positioned update/delete for the corresponding query.
// A positioned update section must come from the same package as its query section.
Section getPositionedUpdateSection(Section querySection) throws SqlException {
Connection connection = agent_.connection_;
return getDynamicSection(connection.holdability());
}
// Get a section for a jdbc 1 positioned update/delete for the corresponding query.
// A positioned update section must come from the same package as its query section.
Section getPositionedUpdateSection(String cursorName, boolean useExecuteImmediateSection) throws SqlException {
Section querySection = (Section) positionedUpdateCursorNameToQuerySection_.get(cursorName);
// If querySection is null, then the user must have provided a bad cursor name.
// Otherwise, get a new section and save the client's cursor name and the server's
// cursor name to the new section.
if (querySection != null) {
Section section = getPositionedUpdateSection(querySection);
// getPositionedUpdateSection gets the next available section from the query
// package, and it has a different cursor name associated with the section.
// We need to save the client's cursor name and server's cursor name to the
// new section.
section.setClientCursorName(querySection.getClientCursorName());
section.serverCursorNameForPositionedUpdate_ = querySection.getServerCursorName();
return section;
} else {
return null;
}
}
void mapCursorNameToQuerySection(String cursorName, Section section) {
positionedUpdateCursorNameToQuerySection_.put(cursorName, section);
}
void mapCursorNameToResultSet(String cursorName, ResultSet resultSet) {
// DERBY-3316. Needs WeakReference so that ResultSet can be garbage collected
positionedUpdateCursorNameToResultSet_.put(cursorName, new WeakReference(resultSet));
}
ResultSet getPositionedUpdateResultSet(String cursorName) throws SqlException {
ResultSet rs = (ResultSet) ((WeakReference) (positionedUpdateCursorNameToResultSet_.get(cursorName))).get();
if (rs == null) {
throw new SqlException(agent_.logWriter_,
new ClientMessageId(SQLState.CLIENT_RESULT_SET_NOT_OPEN));
}
return (rs.resultSetType_ == java.sql.ResultSet.TYPE_FORWARD_ONLY) ? null : rs;
}
void removeCursorNameToResultSetMapping(String clientCursorName,
String serverCursorName) {
if (clientCursorName != null) {
positionedUpdateCursorNameToResultSet_.remove(clientCursorName);
}
if (serverCursorName != null) {
positionedUpdateCursorNameToResultSet_.remove(serverCursorName);
}
}
void removeCursorNameToQuerySectionMapping(String clientCursorName,
String serverCursorName) {
if (clientCursorName != null) {
positionedUpdateCursorNameToQuerySection_.remove(clientCursorName);
}
if (serverCursorName != null) {
positionedUpdateCursorNameToQuerySection_.remove(serverCursorName);
}
}
}
|
papicella/snappy-store
|
gemfirexd/client/src/main/java/com/pivotal/gemfirexd/internal/client/am/SectionManager.java
|
Java
|
apache-2.0
| 10,665 | 47.040541 | 155 | 0.691889 | false |
//===--- SubstitutionMap.h - Swift Substitution Map ASTs --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the SubstitutionMap class.
//
// This is a data structure type describing the mapping of abstract types to
// replacement types, together with associated conformances to use for deriving
// nested types.
//
// Depending on how the SubstitutionMap is constructed, the abstract types are
// either archetypes or interface types. Care must be exercised to only look up
// one or the other.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_AST_SUBSTITUTION_MAP_H
#define SWIFT_AST_SUBSTITUTION_MAP_H
#include "swift/AST/ProtocolConformanceRef.h"
#include "swift/AST/Type.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
namespace swift {
class SubstitutionMap {
using ParentType = std::pair<CanType, AssociatedTypeDecl *>;
llvm::DenseMap<TypeBase *, Type> subMap;
llvm::DenseMap<TypeBase *, ArrayRef<ProtocolConformanceRef>> conformanceMap;
llvm::DenseMap<TypeBase *, SmallVector<ParentType, 1>> parentMap;
Optional<ProtocolConformanceRef>
lookupConformance(ProtocolDecl *proto,
ArrayRef<ProtocolConformanceRef> conformances) const;
template<typename Fn>
Optional<ProtocolConformanceRef> forEachParent(CanType type, Fn fn) const;
public:
Optional<ProtocolConformanceRef>
lookupConformance(CanType type, ProtocolDecl *proto) const;
const llvm::DenseMap<TypeBase *, Type> &getMap() const {
return subMap;
}
void addSubstitution(CanType type, Type replacement);
void addConformances(CanType type, ArrayRef<ProtocolConformanceRef> conformances);
void addParent(CanType type, CanType parent,
AssociatedTypeDecl *assocType);
void removeType(CanType type);
};
} // end namespace swift
#endif
|
IngmarStein/swift
|
include/swift/AST/SubstitutionMap.h
|
C
|
apache-2.0
| 2,340 | 31.957746 | 84 | 0.691453 | false |
// -----------------------------------------------------------------------
// <copyright file="ClientRefreshTokenStoreBase.cs" company="OSharp开源团队">
// Copyright (c) 2014-2015 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2015-11-10 3:03</last-date>
// -----------------------------------------------------------------------
using System;
using System.Linq;
using System.Threading.Tasks;
using OSharp.Core.Data;
using OSharp.Core.Dependency;
using OSharp.Core.Identity.Models;
using OSharp.Core.Security.Models;
namespace OSharp.Core.Security
{
/// <summary>
/// 刷新Token存储基类
/// </summary>
public abstract class OAuthClientRefreshTokenStoreBase<TClientRefreshToken, TClientRefreshTokenKey, TClient, TClientKey, TUser, TUserKey>
: IOAuthClientRefreshTokenStore, IScopeDependency
where TClientRefreshToken : OAuthClientRefreshTokenBase<TClientRefreshTokenKey, TClient, TClientKey, TUser, TUserKey>, new()
where TClient : IOAuthClient<TClientKey>
where TUser : UserBase<TUserKey>
where TUserKey : IEquatable<TUserKey>
{
/// <summary>
/// 获取或设置 客户端刷新Token仓储对象
/// </summary>
public IRepository<TClientRefreshToken, TClientRefreshTokenKey> ClientRefreshTokenRepository { get; set; }
/// <summary>
/// 获取或设置 客户端仓储对象
/// </summary>
public IRepository<TClient, TClientKey> ClientRepository { get; set; }
/// <summary>
/// 获取或设置 用户仓储对象
/// </summary>
public IRepository<TUser, TUserKey> UserRepository { get; set; }
#region Implementation of IClientRefreshTokenStore
/// <summary>
/// 获取刷新Token
/// </summary>
/// <param name="value">token值</param>
/// <returns></returns>
public virtual Task<RefreshTokenInfo> GetTokenInfo(string value)
{
var tokenInfo = ClientRefreshTokenRepository.Entities.Where(m => m.Value == value).Select(m => new RefreshTokenInfo()
{
Value = m.Value,
IssuedUtc = m.IssuedUtc,
ExpiresUtc = m.ExpiresUtc,
ProtectedTicket = m.ProtectedTicket,
ClientId = m.Client.ClientId,
UserName = m.User.UserName
}).FirstOrDefault();
return Task.FromResult(tokenInfo);
}
/// <summary>
/// 保存刷新Token信息
/// </summary>
/// <param name="tokenInfo">Token信息</param>
/// <returns></returns>
public async virtual Task<bool> SaveToken(RefreshTokenInfo tokenInfo)
{
TClientRefreshToken token = new TClientRefreshToken()
{
Value = tokenInfo.Value,
ProtectedTicket = tokenInfo.ProtectedTicket,
IssuedUtc = tokenInfo.IssuedUtc,
ExpiresUtc = tokenInfo.ExpiresUtc
};
TClient client = ClientRepository.TrackEntities.Where(m => m.ClientId == tokenInfo.ClientId).FirstOrDefault();
if (client == null)
{
return false;
}
token.Client = client;
TUser user = UserRepository.TrackEntities.Where(m => m.UserName == tokenInfo.UserName).FirstOrDefault();
if (user == null)
{
return false;
}
token.User = user;
int result = await ClientRefreshTokenRepository.InsertAsync(token);
return result > 0;
}
/// <summary>
/// 移除刷新Token
/// </summary>
/// <param name="value">Token值</param>
/// <returns></returns>
public async virtual Task<bool> Remove(string value)
{
var token = ClientRefreshTokenRepository.Entities.Where(m => m.Value == value)
.Select(m => new { UserId = m.User.Id }).FirstOrDefault();
if (token == null)
{
return false;
}
TUserKey userId = token.UserId;
int result = await ClientRefreshTokenRepository.DeleteDirectAsync(m => m.User.Id.Equals(userId));
return result > 0;
}
#endregion
}
}
|
vebin/osharp-1
|
src/OSharp.Permissions.OAuth/OAuthClientRefreshTokenStoreBase.cs
|
C#
|
apache-2.0
| 4,424 | 35.330508 | 141 | 0.562996 | false |
function createTestData() {
var result = {};
function makeVoxels(l, h, f) {
var d = [ h[0]-l[0], h[1]-l[1], h[2]-l[2] ]
, v = new Int32Array(d[0]*d[1]*d[2])
, n = 0;
for(var k=l[2]; k<h[2]; ++k)
for(var j=l[1]; j<h[1]; ++j)
for(var i=l[0]; i<h[0]; ++i, ++n) {
v[n] = f(i,j,k);
}
return {voxels:v, dims:d};
}
var colorTab = [
0xff0000,
0x00ff00,
0x0000ff,
0xff00ff,
0xffff00,
0x00ffff,
0x000001,
0xffffff
];
for(var i=1,c=0; i<=16; i<<=1,++c) {
result[i + 'x' + i + 'x' + i] = makeVoxels([0,0,0], [i,i,i], function() { return colorTab[c]; });
}
result['Sphere'] = makeVoxels([-16,-16,-16], [16,16,16], function(i,j,k) {
return i*i+j*j+k*k <= 16*16 ? 0x113344 : 0;
});
result['I-Shape'] = makeVoxels([0,-1,-1], [1,2,2], function(i,j,k) {
if((j === -1 && k === 0) ||
(j === 1 && k === 0) ) {
return 0;
}
return 1;
});
result['Tiny Button'] = makeVoxels([-1,-1,-1],[1,2,2], function(i,j,k) {
if(i === 0) {
return (j === 0 && k === 0) ? 0xff0000 : 0;
}
return 1;
});
result['Noise'] = makeVoxels([0,0,0], [16,16,16], function(i,j,k) {
return Math.random() < 0.1 ? Math.random() * 0xffffff : 0;
});
result['Dense Noise'] = makeVoxels([0,0,0], [16,16,16], function(i,j,k) {
return Math.round(Math.random() * 0xffffff);
});
result['16 Color Noise'] = makeVoxels([0,0,0], [16,16,16], function(i,j,k) {
return Math.random() < 0.1 ? colorTab[Math.floor(Math.random() * colorTab.length)] : 0;
});
result['Hole'] = makeVoxels([0,0,0], [16,16,1], function(i,j,k) {
return Math.abs(i-7) > 3 || Math.abs(j-7) > 3 ? 1 : 0;
});
result['Boss'] = makeVoxels([0,0,0], [16,16,4], function(i,j,k) {
if(k === 0) {
return 0x0000ff;
} else if(Math.abs(i-4) < 2 && Math.abs(j-5) < 2 && k< 2) {
return 0x00ff00;
} else if(10 <= i && i < 14 && 2 <= j && j < 15) {
return 0xff0000;
}
return 0;
});
result['T-Shape'] = makeVoxels([0,0,0], [16,16,3], function(i,j,k) {
return (( 6 <= i && i < 10 && 2 <= j && j < 13) ||
( 2 <= i && i < 14 && 8 <= j && j < 13)) ? 0xcc00dd : 0;
});
result['HollowCube'] = makeVoxels([0,0,0], [16,16,16], function(i,j,k) {
if(i < 1) {
return 0xff0000;
} else if(i >= 15) {
return 0x00ffff;
} else if(j < 1) {
return 0x00ff00;
} else if(j >= 15) {
return 0xff00ff;
} else if(k < 1) {
return 0x0000ff;
} else if(k >= 15) {
return 0xffff00;
} else {
return 0;
}
});
result['Clover'] = makeVoxels([0,0,0], [17,17,1], function(i,j,k) {
if(i == 0 && Math.abs(j-8) <= 2) {
return 0;
} else if(i == 16 && Math.abs(j-8) <= 2) {
return 0;
} else if(j == 0 && Math.abs(i-8) <= 2) {
return 0;
} else if(j == 16 && Math.abs(i-8) <= 2) {
return 0;
} else {
return 0x10de60;
}
});
result['Triangle'] = makeVoxels([0,0,0], [17,17,1], function(i,j,k) {
return (i < j) ? 0xff00ff : 0;
});
result['Saw'] = makeVoxels([0,0,0], [17,3,1], function(i,j,k) {
if( j > 0 || !!(i & 1) ) {
return 0x00ffff;
}
return 0;
});
result['4Dots'] = makeVoxels([0,0,0], [7,7,1], function(i,j,k) {
if( (i == 2 && j == 1) ||
(i == 5 && j == 2) ||
(i == 1 && j == 4) ||
(i == 4 && j == 5) ) {
return 0x00ff;
}
return 0xeedd00;
});
result['Checker'] = makeVoxels([0,0,0], [8,8,8], function(i,j,k) {
return !!((i+j+k)&1) ? (((i^j^k)&2) ? 1 : 0xffffff) : 0;
});
result["Matt's Example"] = makeVoxels([0,0,0], [4,5,1], function(i,j,k) {
if( (i == 1 && j == 1) ||
(i == 2 && j == 3) ) {
return 0xee5533;
}
return 0x128844;
});
result['Benchmark (SLOW!)'] = makeVoxels([-32, -32, -32], [33, 33, 33], function(x, y, z) {
var s = 2.0 * Math.PI / 32.0;
return Math.sin(s * x) + Math.sin(s * y) + Math.sin(s * z) < 0 ? 1 : 0;
});
result['Hill'] = makeVoxels([-16, 0, -16], [16,16,16], function(i,j,k) {
return j <= 16 * Math.exp(-(i*i + k*k) / 64) ? 0x118822 : 0;
});
result['Valley'] = makeVoxels([0,0,0], [32,32,32], function(i,j,k) {
return j <= (i*i + k*k) * 31 / (32*32*2) + 1 ? 0x118822 : 0;
});
result['Hilly Terrain'] = makeVoxels([0, 0, 0], [32,32,32], function(i,j,k) {
var h0 = 3.0 * Math.sin(Math.PI * i / 12.0 - Math.PI * k * 0.1) + 27;
if(j > h0+1) {
return 0;
}
if(h0 <= j) {
return 0x23dd31;
}
var h1 = 2.0 * Math.sin(Math.PI * i * 0.25 - Math.PI * k * 0.3) + 20;
if(h1 <= j) {
return 0x964B00;
}
if(2 < j) {
return Math.random() < 0.1 ? 0x222222 : 0xaaaaaa;
}
return 0xff0000;
});
result['Empty'] = { voxels : [], dims : [0,0,0] };
return result;
}
|
alfonsoaranzazu/132-Visual-Dashboard
|
voxel/vendor/testData.js
|
JavaScript
|
apache-2.0
| 4,903 | 25.219251 | 101 | 0.458291 | false |
/*
* 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.
*/
package org.apache.cassandra.repair.messages;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.dht.AbstractBounds;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.repair.RepairJobDesc;
import org.apache.cassandra.streaming.PreviewKind;
import static org.apache.cassandra.locator.InetAddressAndPort.Serializer.inetAddressAndPortSerializer;
public class AsymmetricSyncRequest extends RepairMessage
{
public static MessageSerializer serializer = new SyncRequestSerializer();
public final InetAddressAndPort initiator;
public final InetAddressAndPort fetchingNode;
public final InetAddressAndPort fetchFrom;
public final Collection<Range<Token>> ranges;
public final PreviewKind previewKind;
public AsymmetricSyncRequest(RepairJobDesc desc, InetAddressAndPort initiator, InetAddressAndPort fetchingNode, InetAddressAndPort fetchFrom, Collection<Range<Token>> ranges, PreviewKind previewKind)
{
super(Type.ASYMMETRIC_SYNC_REQUEST, desc);
this.initiator = initiator;
this.fetchingNode = fetchingNode;
this.fetchFrom = fetchFrom;
this.ranges = ranges;
this.previewKind = previewKind;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof AsymmetricSyncRequest))
return false;
AsymmetricSyncRequest req = (AsymmetricSyncRequest)o;
return messageType == req.messageType &&
desc.equals(req.desc) &&
initiator.equals(req.initiator) &&
fetchingNode.equals(req.fetchingNode) &&
fetchFrom.equals(req.fetchFrom) &&
ranges.equals(req.ranges);
}
@Override
public int hashCode()
{
return Objects.hash(messageType, desc, initiator, fetchingNode, fetchFrom, ranges);
}
public static class SyncRequestSerializer implements MessageSerializer<AsymmetricSyncRequest>
{
public void serialize(AsymmetricSyncRequest message, DataOutputPlus out, int version) throws IOException
{
RepairJobDesc.serializer.serialize(message.desc, out, version);
inetAddressAndPortSerializer.serialize(message.initiator, out, version);
inetAddressAndPortSerializer.serialize(message.fetchingNode, out, version);
inetAddressAndPortSerializer.serialize(message.fetchFrom, out, version);
out.writeInt(message.ranges.size());
for (Range<Token> range : message.ranges)
{
IPartitioner.validate(range);
AbstractBounds.tokenSerializer.serialize(range, out, version);
}
out.writeInt(message.previewKind.getSerializationVal());
}
public AsymmetricSyncRequest deserialize(DataInputPlus in, int version) throws IOException
{
RepairJobDesc desc = RepairJobDesc.serializer.deserialize(in, version);
InetAddressAndPort owner = inetAddressAndPortSerializer.deserialize(in, version);
InetAddressAndPort src = inetAddressAndPortSerializer.deserialize(in, version);
InetAddressAndPort dst = inetAddressAndPortSerializer.deserialize(in, version);
int rangesCount = in.readInt();
List<Range<Token>> ranges = new ArrayList<>(rangesCount);
for (int i = 0; i < rangesCount; ++i)
ranges.add((Range<Token>) AbstractBounds.tokenSerializer.deserialize(in, IPartitioner.global(), version));
PreviewKind previewKind = PreviewKind.deserialize(in.readInt());
return new AsymmetricSyncRequest(desc, owner, src, dst, ranges, previewKind);
}
public long serializedSize(AsymmetricSyncRequest message, int version)
{
long size = RepairJobDesc.serializer.serializedSize(message.desc, version);
size += inetAddressAndPortSerializer.serializedSize(message.initiator, version);
size += inetAddressAndPortSerializer.serializedSize(message.fetchingNode, version);
size += inetAddressAndPortSerializer.serializedSize(message.fetchFrom, version);
size += TypeSizes.sizeof(message.ranges.size());
for (Range<Token> range : message.ranges)
size += AbstractBounds.tokenSerializer.serializedSize(range, version);
size += TypeSizes.sizeof(message.previewKind.getSerializationVal());
return size;
}
}
public String toString()
{
return "AsymmetricSyncRequest{" +
"initiator=" + initiator +
", fetchingNode=" + fetchingNode +
", fetchFrom=" + fetchFrom +
", ranges=" + ranges +
", previewKind=" + previewKind +
", desc="+desc+
'}';
}
}
|
cooldoger/cassandra
|
src/java/org/apache/cassandra/repair/messages/AsymmetricSyncRequest.java
|
Java
|
apache-2.0
| 6,003 | 43.466667 | 203 | 0.694653 | false |
// -----------------------------------------------------------------------------
// Copyright 2011 Patrick Näf ([email protected])
//
// Licensed 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.
// -----------------------------------------------------------------------------
// Project includes
#import "CommandBase.h"
// Forward declarations
@class ArchiveGame;
// -----------------------------------------------------------------------------
/// @brief The RenameGameCommand class is responsible for renaming an .sgf file
/// in the documents folder.
// -----------------------------------------------------------------------------
@interface RenameGameCommand : CommandBase
{
}
- (id) initWithGame:(ArchiveGame*)aGame newName:(NSString*)aNewName;
@property(nonatomic, retain) ArchiveGame* game;
@property(nonatomic, retain) NSString* theNewName;
@end
|
puremourning/littlego
|
src/command/game/RenameGameCommand.h
|
C
|
apache-2.0
| 1,357 | 34.684211 | 80 | 0.575221 | false |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed 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.
*/
package com.vaadin.tests.server.component.gridlayout;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.tests.server.component.DeclarativeMarginTestBase;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.declarative.Design;
import com.vaadin.ui.declarative.DesignContext;
public class GridLayoutDeclarativeTest
extends DeclarativeMarginTestBase<GridLayout> {
@Test
public void testMargins() {
testMargins("vaadin-grid-layout", new MarginInfo(false));
}
@Test
public void testSimpleGridLayout() {
Button b1 = new Button("Button 0,0");
Button b2 = new Button("Button 0,1");
Button b3 = new Button("Button 1,0");
Button b4 = new Button("Button 1,1");
b1.setCaptionAsHtml(true);
b2.setCaptionAsHtml(true);
b3.setCaptionAsHtml(true);
b4.setCaptionAsHtml(true);
String design = "<vaadin-grid-layout><row>" //
+ "<column expand=1.0>" + writeChild(b1) + "</column>" //
+ "<column expand=3.3>" + writeChild(b2) + "</column>" //
+ "</row><row>" //
+ "<column>" + writeChild(b3) + "</column>" //
+ "<column>" + writeChild(b4) + "</column>" //
+ "</row></vaadin-grid-layout>";
GridLayout gl = new GridLayout(2, 2);
gl.addComponent(b1);
gl.addComponent(b2);
gl.addComponent(b3);
gl.addComponent(b4);
gl.setColumnExpandRatio(0, 1f);
gl.setColumnExpandRatio(1, 3.3f);
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testReadIntegerExpandRatioGridLayout() {
// To make sure that it can read from old declarative which use
// integer expand ratio
Button b1 = new Button("Button 0,0");
b1.setCaptionAsHtml(true);
String design = "<vaadin-grid-layout><row expand=3>" //
+ "<column expand=1>" + writeChild(b1) + "</column>" //
+ "</row>"//
+ "</vaadin-grid-layout>";
GridLayout gl = new GridLayout(1, 1);
gl.addComponent(b1);
gl.setColumnExpandRatio(0, 1.0f);
gl.setRowExpandRatio(0, 3.0f);
testRead(design, gl);
}
@Test
public void testOneBigComponentGridLayout() {
Button b1 = new Button("Button 0,0 -> 1,1");
b1.setCaptionAsHtml(true);
String design = "<vaadin-grid-layout><row>" //
+ "<column colspan=2 rowspan=2>" + writeChild(b1) + "</column>" //
+ "</row><row expand=2>" //
+ "</row></vaadin-grid-layout>";
GridLayout gl = new GridLayout(2, 2);
gl.addComponent(b1, 0, 0, 1, 1);
gl.setRowExpandRatio(1, 2);
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testMultipleSpannedComponentsGridLayout() {
GridLayout gl = new GridLayout(5, 5);
Button b1 = new Button("Button 0,0 -> 0,2");
b1.setCaptionAsHtml(true);
gl.addComponent(b1, 0, 0, 2, 0);
Button b2 = new Button("Button 0,3 -> 3,3");
b2.setCaptionAsHtml(true);
gl.addComponent(b2, 3, 0, 3, 3);
Button b3 = new Button("Button 0,4 -> 1,4");
b3.setCaptionAsHtml(true);
gl.addComponent(b3, 4, 0, 4, 1);
Button b4 = new Button("Button 1,0 -> 3,1");
b4.setCaptionAsHtml(true);
gl.addComponent(b4, 0, 1, 1, 3);
Button b5 = new Button("Button 2,2");
b5.setCaptionAsHtml(true);
gl.addComponent(b5, 2, 2);
Button b6 = new Button("Button 3,4 -> 4,4");
b6.setCaptionAsHtml(true);
gl.addComponent(b6, 4, 3, 4, 4);
Button b7 = new Button("Button 4,1 -> 4,2");
b7.setCaptionAsHtml(true);
gl.addComponent(b7, 2, 4, 3, 4);
/*
* Buttons in the GridLayout
*/
// 1 1 1 2 3
// 4 4 - 2 3
// 4 4 5 2 -
// 4 4 - 2 6
// - - 7 7 6
String design = "<vaadin-grid-layout><row>" //
+ "<column colspan=3>" + writeChild(b1) + "</column>" //
+ "<column rowspan=4>" + writeChild(b2) + "</column>" //
+ "<column rowspan=2>" + writeChild(b3) + "</column>" //
+ "</row><row>" //
+ "<column rowspan=3 colspan=2>" + writeChild(b4) + "</column>" //
+ "</row><row>" //
+ "<column>" + writeChild(b5) + "</column>" //
+ "</row><row>" //
+ "<column />" // Empty placeholder
+ "<column rowspan=2>" + writeChild(b6) + "</column>" //
+ "</row><row>" //
+ "<column colspan=2 />" // Empty placeholder
+ "<column colspan=2>" + writeChild(b7) + "</column>" //
+ "</row></vaadin-grid-layout>";
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testManyExtraGridLayoutSlots() {
GridLayout gl = new GridLayout(5, 5);
Button b1 = new Button("Button 0,4 -> 4,4");
b1.setCaptionAsHtml(true);
gl.addComponent(b1, 4, 0, 4, 4);
gl.setColumnExpandRatio(2, 2.0f);
String design = "<vaadin-grid-layout><row>" //
+ "<column colspan=4 rowspan=5 expand='0.0,0.0,2.0,0.0' />" //
+ "<column rowspan=5>" + writeChild(b1) + "</column>" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row></vaadin-grid-layout>";
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testManyEmptyColumnsWithOneExpand() {
GridLayout gl = new GridLayout(5, 5);
Button b1 = new Button("Button 0,4 -> 4,4");
b1.setCaptionAsHtml(true);
gl.addComponent(b1, 0, 0, 0, 4);
gl.setColumnExpandRatio(4, 2.0f);
String design = "<vaadin-grid-layout><row>" //
+ "<column rowspan=5>" + writeChild(b1) + "</column>" //
+ "<column colspan=4 rowspan=5 expand='0.0,0.0,0.0,2.0' />" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row><row>" //
+ "</row></vaadin-grid-layout>";
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testEmptyGridLayout() {
GridLayout gl = new GridLayout();
String design = "<vaadin-grid-layout />";
testWrite(design, gl);
testRead(design, gl);
}
private String writeChild(Component childComponent) {
return new DesignContext().createElement(childComponent).toString();
}
@Override
public GridLayout testRead(String design, GridLayout expected) {
expected.setCursorX(0);
expected.setCursorY(expected.getRows());
GridLayout result = super.testRead(design, expected);
for (int row = 0; row < expected.getRows(); ++row) {
Assert.assertEquals(expected.getRowExpandRatio(row),
result.getRowExpandRatio(row), 0.00001);
}
for (int col = 0; col < expected.getColumns(); ++col) {
Assert.assertEquals(expected.getColumnExpandRatio(col),
result.getColumnExpandRatio(col), 0.00001);
}
for (int row = 0; row < expected.getRows(); ++row) {
for (int col = 0; col < expected.getColumns(); ++col) {
Component eC = expected.getComponent(col, row);
Component rC = result.getComponent(col, row);
assertEquals(eC, rC);
if (eC == null) {
continue;
}
assertEquals(expected.getComponentAlignment(eC),
result.getComponentAlignment(rC));
}
}
return result;
}
@Test
public void testNestedGridLayouts() {
String design = "<!DOCTYPE html>" + //
"<html>" + //
" <body> " + //
" <vaadin-grid-layout> " + //
" <row> " + //
" <column> " + //
" <vaadin-grid-layout> " + //
" <row> " + //
" <column> " + //
" <vaadin-button>" + //
" Button " + //
" </vaadin-button> " + //
" </column> " + //
" </row> " + //
" </vaadin-grid-layout> " + //
" </column> " + //
" </row> " + //
" </vaadin-grid-layout> " + //
" </body>" + //
"</html>";
GridLayout outer = new GridLayout();
GridLayout inner = new GridLayout();
Button b = new Button("Button");
b.setCaptionAsHtml(true);
inner.addComponent(b);
outer.addComponent(inner);
testRead(design, outer);
testWrite(design, outer);
}
@Test
public void testEmptyGridLayoutWithColsAndRowsSet() throws IOException {
GridLayout layout = new GridLayout();
layout.setRows(2);
layout.setColumns(2);
ByteArrayOutputStream out = new ByteArrayOutputStream();
DesignContext context = new DesignContext();
context.setRootComponent(layout);
Design.write(context, out);
ByteArrayInputStream input = new ByteArrayInputStream(
out.toByteArray());
Component component = Design.read(input);
GridLayout readLayout = (GridLayout) component;
assertEquals(layout.getRows(), readLayout.getRows());
}
@Test
public void testGridLayoutAlignments() {
String design = "<vaadin-grid-layout><row>" //
+ "<column><vaadin-label :middle>0</label></column>"//
+ "<column><vaadin-label :right>1</label>"//
+ "</row><row>" //
+ "<column><vaadin-label :bottom :center>2</label></column>"//
+ "<column><vaadin-label :middle :center>3</label>" //
+ "</row></vaadin-grid-layout>";
GridLayout gl = new GridLayout(2, 2);
Alignment[] alignments = { Alignment.MIDDLE_LEFT, Alignment.TOP_RIGHT,
Alignment.BOTTOM_CENTER, Alignment.MIDDLE_CENTER };
for (int i = 0; i < 4; i++) {
Label child = new Label("" + i, ContentMode.HTML);
gl.addComponent(child);
gl.setComponentAlignment(child, alignments[i]);
}
testWrite(design, gl);
testRead(design, gl);
}
@Test
public void testGridLayoutMargins() throws IOException {
String design = "<vaadin-grid-layout _id=\"marginComponent\"margin>"
+ "<row><column><vaadin-grid-layout _id=\"marginLeftComponent\" margin-left></vaadin-grid-layout></column></row>"
+ "<row><column><vaadin-grid-layout _id=\"marginRightComponent\" margin-right></vaadin-grid-layout></column></row>"
+ "<row><column><vaadin-grid-layout _id=\"marginTopComponent\" margin-top></vaadin-grid-layout></column></row>"
+ "<row><column><vaadin-grid-layout _id=\"marginBottomComponent\" margin-bottom></vaadin-grid-layout></column></row>"
+ "</vaadin-grid-layout>";
DesignContext context = Design
.read(new ByteArrayInputStream(design.getBytes(UTF_8)), null);
assertEquals(null, context.getCustomAttributes(
context.getComponentByLocalId("marginComponent")));
assertEquals(null, context.getCustomAttributes(
context.getComponentByLocalId("marginLeftComponent")));
assertEquals(null, context.getCustomAttributes(
context.getComponentByLocalId("marginRightComponent")));
assertEquals(null, context.getCustomAttributes(
context.getComponentByLocalId("marginTopComponent")));
assertEquals(null, context.getCustomAttributes(
context.getComponentByLocalId("marginBottomComponent")));
}
@Test
public void designWithPreconfiguredGridLayout() throws Exception {
String design = "<html>" //
+ "<head>" //
+ "<meta name='package-mapping' content='my:com.vaadin.tests.server.component.gridlayout'>"
+ "</meta>" + "</head>" + "<body>"
+ "<my-preconfigured-grid-layout></my-preconfigured-grid-layout>";
PreconfiguredGridLayout myLayout = (PreconfiguredGridLayout) Design
.read(new ByteArrayInputStream(design.getBytes(UTF_8)));
assertEquals(2, myLayout.getRows());
assertEquals(2, myLayout.getColumns());
}
}
|
Darsstar/framework
|
server/src/test/java/com/vaadin/tests/server/component/gridlayout/GridLayoutDeclarativeTest.java
|
Java
|
apache-2.0
| 13,841 | 37.234807 | 133 | 0.545842 | false |
/* custom site styles */
h1, h2, h3 {font-family: Verdana, sans-serif; color: #000099; text-align: left;}
h1 {font-size: 1.4em; margin-top: 2em;}
h2 {font-size: 1.2em;}
h3 {font-size: 1em; margin-bottom: 0.5em;}
pre { margin-top: 1em; margin-bottom: 1em; }
.figure {margin-top: 2em; margin-bottom: 2em; text-align:center;}
|
opengeospatial/ets-19139
|
src/site/resources/css/site.css
|
CSS
|
apache-2.0
| 323 | 45.142857 | 80 | 0.678019 | false |
from ..baz import *
|
supercheetah/diceroller
|
pyinstaller/buildtests/import/relimp2/bar/bar2/__init__.py
|
Python
|
artistic-2.0
| 20 | 19 | 19 | 0.65 | false |
# Documentation links
* [ALGORITHMS.md](ALGORITHMS.md)
* [BUILD.md](BUILD.md)
* [RELEASE.md](RELEASE.md)
* [C_Examples.md](C_Examples.md)
* [CPP_Examples.md](CPP_Examples.md)
|
kimwalisch/primesum
|
lib/primesieve/doc/README.md
|
Markdown
|
bsd-2-clause
| 176 | 24.142857 | 36 | 0.693182 | false |
#!/usr/bin/env sh
rootfolder=/nfs/hn46/xiaolonw/cnncode/caffe-3dnormal_r
GLOG_logtostderr=1 $rootfolder/build/examples/3dnormal/convert_normalReg.bin /nfs/hn46/xiaolonw/cnncode/viewer/croptest /nfs/hn46/xiaolonw/cnncode/viewer/train_test_3dnormal_reg/smallTestLabels.txt $rootfolder/models/3d_normal_db_r/3d_test_db_small 0 0 55 55 /nfs/hn46/xiaolonw/cnncode/viewer/genTestforReg/reg_test
#GLOG_logtostderr=1 $rootfolder/build/examples/3dnormal/convert_normal.bin /nfs/hn46/dfouhey/deepProcessed/data/ /nfs/hn46/xiaolonw/cnncode/viewer/train_test_3dnormal/testLabels.txt $rootfolder/models/3d_normal_db/3d_test_db 0 0 55 55
|
xiaolonw/caffe-3dnormal_joint_past
|
scripts/older/3dnormal_r_n_acos/convert_3dnormal_test.sh
|
Shell
|
bsd-2-clause
| 627 | 88.571429 | 315 | 0.814992 | false |
class Whiteclock < Cask
version '2.0'
sha256 '9ad4a713dca77cfbca5bf4d8d1263126ec2b95fa588ad80be4f5a79140eefb6d'
url "http://www.taimila.com/downloads/WhiteClock#{version.to_i}.zip"
homepage 'http://www.taimila.com/?p=1221'
license :unknown
app 'WhiteClock.app'
end
|
sarcx/homebrew-cask
|
Casks/whiteclock.rb
|
Ruby
|
bsd-2-clause
| 279 | 26.9 | 75 | 0.763441 | false |
// Copyright (c) 2013 Jeff Heckey jheckey(at)ece(dot)ucsb(dot)edu
// This file uses SQCT, Copyright (c) 2012 Vadym Kliuchnikov, Dmitri Maslov, Michele Mosca;
// SQCT is distributed under LGPL v3
//
#include "sk.h"
#include "netgenerator.h"
#include <fstream>
#include <sstream>
#ifndef EAPP_H
#define EAPP_H
/// \brief Options for epsilon net generation
struct enetOptions
{
/// \brief If one element specified -- upper bound for sde of epsilon net to be
/// generated. If two elements specified -- interval of sde to be generated.
std::vector<int> epsilon_net_layers;
};
////////////////////////////////////////////////////////////////////
struct enetApplication
{
enetApplication( const enetOptions& options ) :
m_options(options)
{}
/// \brief Checks if all layers generated on initial state are available
void check_initial()
{
initial_ok = true;
if( m_layers[0] == 0 )
initial_ok = false;
for( int i = 2; (i < initial_end) && initial_ok ; ++i )
if( m_layers[i] == 0 ) initial_ok = false;
}
/// \brief Collects information about parts of epsilon net available
void check_files()
{
m_layers.resize(100,0);
// collect information about available layers
for( int i = 0; i < 100; ++i )
{
std::string name = netGenerator::fileName(i);
std::ifstream ifs(name);
if( !ifs )
m_layers[i] = 0;
else
m_layers[i] = 1;
}
}
/// \brief Generates all layers with \f$ sde(|\cdot|^2) \f$ in the interval [st,end)
void generate( int st, int end )
{
if( ! initial_ok && st < initial_end )
m_ng.generateInitial();
for( int i = std::max(initial_end,st) ; i < end; ++i )
{
if( m_layers[i] == 0 )
{
//std::cout << "\tGenerating Layer " << i << " of " << end << std::endl;
epsilonnet base_net;
base_net.loadFromFile( netGenerator::fileName(i-1).c_str() );
std::unique_ptr<epsilonnet> res( netGenerator::generate( base_net ) );
res->saveToFile( netGenerator::fileName(i).c_str() );
}
}
}
/// \brief Do the work
void process()
{
check_files();
check_initial();
int sz = m_options.epsilon_net_layers.size();
int b = m_options.epsilon_net_layers[0];
switch( sz )
{
case 1:
generate(0,b + 1);
break;
case 2:
generate(b,m_options.epsilon_net_layers[1] + 1);
break;
default:
std::cerr << "Wrong number of parameters. See help." << std::endl;
}
}
void print_error_message()
{
std::cout << "Epsilon net files a not available, use --epsilon-net option" << std::endl
<< "to generate them." << std::endl;
}
bool check()
{
int st = 0;
int end = m_options.epsilon_net_layers[0] + 1;
check_files();
check_initial();
if( ! initial_ok && st < initial_end )
{
//print_error_message();
return false;
}
for( int i = std::max(initial_end,st) ; i < end; ++i )
{
if( m_layers[i] == 0 )
{
print_error_message();
return false;
}
}
return true;
}
const enetOptions& m_options; ///< Application options
std::vector<int> m_layers; ///< Ones for available layers, zeros for not availible layers
static const int initial_end; ///< Maximal layer generated on initial state
bool initial_ok; ///< If all initial layers are availible
netGenerator m_ng; ///< Epsilon net generator
};
const int enetApplication::initial_end = 21;
#endif // EAPP_H
|
hoangt/ScaffCC
|
Rotations/sqct/eapp.h
|
C
|
bsd-2-clause
| 3,992 | 27.927536 | 102 | 0.513778 | false |
package vcard
type ContentLine struct {
Group, Name string
Params map[string]Value
Value StructuredValue
}
// values separated by ';' has a structural meaning
type StructuredValue []Value
// values seprated by ',' is a multi value
type Value []string
func (sv StructuredValue) GetTextList() []string {
var textList []string
for _, v := range sv {
for _, s := range v {
textList = append(textList, s)
}
}
return textList
}
func (v StructuredValue) GetText() string {
if len(v) > 0 && len(v[0]) > 0 {
return v[0][0]
}
return ""
}
func (v Value) GetText() string {
if len(v) > 0 {
return v[0]
}
return ""
}
|
mdzz/vcard
|
content_line.go
|
GO
|
bsd-2-clause
| 645 | 16.432432 | 51 | 0.63876 | false |
class AstrometryNet < Formula
include Language::Python::Virtualenv
desc "Automatic identification of astronomical images"
homepage "https://github.com/dstndstn/astrometry.net"
url "https://github.com/dstndstn/astrometry.net/releases/download/0.85/astrometry.net-0.85.tar.gz"
sha256 "e5aa28cbd6c5dd2eaf6df68f95398c3cae190668d86e9922521d29689fc27221"
license "BSD-3-Clause"
revision 1
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, arm64_big_sur: "83e1307f40aa32d8815abc05f871386ae9d21e02dac40a4a42135e5701328154"
sha256 cellar: :any, big_sur: "48ce09c0a007ff83c025e87f62ae388ef70c855f1ce5fbb507228b2b9384d13b"
sha256 cellar: :any, catalina: "812735fc4b3038e7004693d8f59bd81e434edc0ed2b5334e634259fdf8071074"
sha256 cellar: :any, mojave: "ec10f1e44c5dfdb49e290cb180d30945d69c100514a07b2c3a07da3f9dff88db"
sha256 cellar: :any_skip_relocation, x86_64_linux: "a12548d700b89741f91aa2d9371fac5a95aca3066d5d2769eb9c0b58226aca90"
end
depends_on "pkg-config" => :build
depends_on "swig" => :build
depends_on "cairo"
depends_on "cfitsio"
depends_on "gsl"
depends_on "jpeg"
depends_on "libpng"
depends_on "netpbm"
depends_on "numpy"
depends_on "[email protected]"
depends_on "wcslib"
resource "fitsio" do
url "https://files.pythonhosted.org/packages/98/2b/0b36a6d039d10da5bfa96d0d6206523f8787fbcc4b8aa0b8107e5139b8b4/fitsio-1.1.4.tar.gz"
sha256 "59c281648ea8fe50ed557857b201eacb21671b83ae60956a7e22c2a7e2a82b9d"
end
def install
# astrometry-net doesn't support parallel build
# See https://github.com/dstndstn/astrometry.net/issues/178#issuecomment-592741428
ENV.deparallelize
ENV["NETPBM_INC"] = "-I#{Formula["netpbm"].opt_include}/netpbm"
ENV["NETPBM_LIB"] = "-L#{Formula["netpbm"].opt_lib} -lnetpbm"
ENV["SYSTEM_GSL"] = "yes"
ENV["PYTHON"] = Formula["[email protected]"].opt_bin/"python3"
venv = virtualenv_create(libexec, Formula["[email protected]"].opt_bin/"python3")
venv.pip_install resources
ENV["INSTALL_DIR"] = prefix
xy = Language::Python.major_minor_version Formula["[email protected]"].opt_bin/"python3"
ENV["PY_BASE_INSTALL_DIR"] = libexec/"lib/python#{xy}/site-packages/astrometry"
ENV["PY_BASE_LINK_DIR"] = libexec/"lib/python#{xy}/site-packages/astrometry"
ENV["PYTHON_SCRIPT"] = libexec/"bin/python3"
system "make"
system "make", "py"
system "make", "install"
rm prefix/"doc/report.txt"
end
test do
system "#{bin}/image2pnm", "-h"
system "#{bin}/build-astrometry-index", "-d", "3", "-o", "index-9918.fits",
"-P", "18", "-S", "mag", "-B", "0.1",
"-s", "0", "-r", "1", "-I", "9918", "-M",
"-i", "#{prefix}/examples/tycho2-mag6.fits"
(testpath/"99.cfg").write <<~EOS
add_path .
inparallel
index index-9918.fits
EOS
system "#{bin}/solve-field", "--config", "99.cfg", "#{prefix}/examples/apod4.jpg",
"--continue", "--dir", "."
assert_predicate testpath/"apod4.solved", :exist?
assert_predicate testpath/"apod4.wcs", :exist?
end
end
|
nandub/homebrew-core
|
Formula/astrometry-net.rb
|
Ruby
|
bsd-2-clause
| 3,313 | 38.915663 | 136 | 0.650166 | false |
package com.samsung.sec.dexter.executor.peerreview;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.samsung.sec.dexter.core.config.PeerReviewHome;
import com.samsung.sec.dexter.core.config.PeerReviewWatch;
import com.samsung.sec.dexter.core.exception.DexterRuntimeException;
import com.samsung.sec.dexter.executor.cli.AnalyzedFileInfo;
import com.samsung.sec.dexter.executor.peerreview.cli.PeerReviewCLIAnalyzer;
public class PeerReviewHomeMonitor implements Runnable {
private final static Logger log = Logger.getLogger(PeerReviewHomeMonitor.class);
private final ExecutorService executorService;
final WatchService watchService;
private final PeerReviewCLIAnalyzer peerReviewCLIAnalyzer;
private Map<WatchKey, PeerReviewWatch> peerReviewWatchMap;
private Future<?> monitoringFuture;
private MonitoringState monitoringState;
private final AnalyzedFileInfo lastAnalyzedFileInfo;
public enum MonitoringState { STOP, RUNNING, CANCEL };
private final static long WATCH_POLL_TIMEOUT = 5;
public PeerReviewHomeMonitor(ExecutorService excutorService, WatchService watchService, PeerReviewCLIAnalyzer peerReviewCLIAnalyzer) {
this.executorService = excutorService;
this.watchService = watchService;
this.peerReviewCLIAnalyzer = peerReviewCLIAnalyzer;
this.peerReviewWatchMap = new HashMap<WatchKey, PeerReviewWatch>();
monitoringFuture = null;
monitoringState = MonitoringState.STOP;
lastAnalyzedFileInfo = new AnalyzedFileInfo();
}
public void restart(List<PeerReviewHome> peerReviewHomeList) {
cancelMonitoring();
updatePeerReviewHomeMap(peerReviewHomeList);
startMonitoring();
}
private void updatePeerReviewHomeMap(List<PeerReviewHome> peerReviewHomeList) {
peerReviewWatchMap = registerHomeListForWatch(peerReviewHomeList);
}
private Map<WatchKey, PeerReviewWatch> registerHomeListForWatch(List<PeerReviewHome> peerReviewHomeList) {
Map<WatchKey, PeerReviewWatch> peerReviewWatchMap = new HashMap<WatchKey, PeerReviewWatch>();
for (PeerReviewHome home : peerReviewHomeList) {
registerHomeForWatch(home, peerReviewWatchMap);
}
return peerReviewWatchMap;
}
private void registerHomeForWatch(final PeerReviewHome home, final Map<WatchKey, PeerReviewWatch> peerReviewWatchMap) {
try {
registerPathForWatch(Paths.get(home.getSourceDir()), home, peerReviewWatchMap);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private void registerPathForWatch(final Path dir, final PeerReviewHome home, final Map<WatchKey, PeerReviewWatch> peerReviewWatchMap) {
try {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
peerReviewWatchMap.put(key, new PeerReviewWatch(home, dir));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException io) {
log.error("Access failed >> " + io.getMessage());
return FileVisitResult.SKIP_SUBTREE;
}
});
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new DexterRuntimeException("IOException occurred on registering peer-review home with watch");
}
}
private void cancelMonitoring() {
if (monitoringFuture != null) {
monitoringState = MonitoringState.CANCEL;
try {
// DPR: get 을 cancel 로 테스트
monitoringFuture.get();
} catch (InterruptedException | ExecutionException e) {
log.error(e.getMessage(), e);
} finally {
log.info("Monitoring is canceled.");
}
}
}
private void startMonitoring() {
log.info("Start monitoring...");
monitoringFuture = executorService.submit(this);
}
public Map<WatchKey, PeerReviewWatch> getPeerReviewWatchMap() {
return peerReviewWatchMap;
}
@Override
public void run() {
monitoringState = MonitoringState.RUNNING;
try {
while(true) {
processWatchEvents();
if (monitoringState == MonitoringState.CANCEL) {
log.info("Stop monitoring");
break;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
Thread.currentThread().interrupt();
} finally {
monitoringState = MonitoringState.STOP;
}
}
private void processWatchEvents() throws InterruptedException {
WatchKey key = watchService.poll(WATCH_POLL_TIMEOUT, TimeUnit.SECONDS);
if (key == null) return;
PeerReviewWatch peerReviewWatch = peerReviewWatchMap.get(key);
List<String> changedFileList = new ArrayList<String>();
for (WatchEvent<?> event: key.pollEvents()) {
Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
Path filePath = getFilePathFromWatchEvent(event, peerReviewWatch.getWatchingPath());
log.debug(String.format("Watched >> %s: %s%n", event.kind().name(), filePath));
if (kind == ENTRY_CREATE && Files.isDirectory(filePath, NOFOLLOW_LINKS)) {
registerPathForWatch(filePath, peerReviewWatch.getHome(), peerReviewWatchMap);
}
if (isValidSourceFile(filePath) && !lastAnalyzedFileInfo.equals(filePath)) {
changedFileList.add(filePath.toString());
lastAnalyzedFileInfo.set(filePath);
}
}
key.reset();
if (changedFileList.size() > 0) {
log.info("Changed source list : " + changedFileList.toString());
peerReviewCLIAnalyzer.analyze(changedFileList, peerReviewWatch.getHome());
}
}
@SuppressWarnings("unchecked")
private Path getFilePathFromWatchEvent(WatchEvent<?> event, Path parentPath) {
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path fileName = ev.context();
return parentPath.resolve(fileName);
}
private boolean isValidSourceFile(Path filePath) {
Pattern pattern = Pattern.compile(
"^\\w+.*\\.(cpp|c\\+\\+|c|h|hpp|h\\+\\+|java|cs|js|html)$",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(filePath.getFileName().toString());
long fileSize;
try {
fileSize = Files.size(filePath);
} catch (IOException e) {
fileSize = 0;
}
return Files.isRegularFile(filePath, NOFOLLOW_LINKS) && matcher.matches() && fileSize > 0;
}
public MonitoringState getMonitoringState() {
return monitoringState;
}
public void cancel() {
cancelMonitoring();
}
}
|
Minjung-Baek/Dexter
|
project/dexter-executor/src/java/com/samsung/sec/dexter/executor/peerreview/PeerReviewHomeMonitor.java
|
Java
|
bsd-2-clause
| 6,918 | 30.688073 | 136 | 0.737985 | false |
class Qrupdate < Formula
desc "Fast updates of QR and Cholesky decompositions"
homepage "https://sourceforge.net/projects/qrupdate/"
url "https://downloads.sourceforge.net/qrupdate/qrupdate-1.1.2.tar.gz"
sha256 "e2a1c711dc8ebc418e21195833814cb2f84b878b90a2774365f0166402308e08"
revision 11
bottle do
cellar :any
sha256 "e275c1facc9afebb6884c4dff4fce18c2ddd7be138502971fcfcf81ab36caab2" => :catalina
sha256 "e509deee8107d09eaff0e02cbe38bbe27abfb5bed32b3766be83207fccc00320" => :mojave
sha256 "743423a355fe7fcd2e43f3056829227d3d957f717b08d956d9cee1902bbbaafc" => :high_sierra
sha256 "835f8dbf0f30b16079b35eba39ad788dfdb3834bf6ab9acdcc8d2083f9199b5c" => :sierra
end
depends_on "gcc" # for gfortran
depends_on "openblas"
def install
# Parallel compilation not supported. Reported on 2017-07-21 at
# https://sourceforge.net/p/qrupdate/discussion/905477/thread/d8f9c7e5/
ENV.deparallelize
system "make", "lib", "solib",
"BLAS=-L#{Formula["openblas"].opt_lib} -lopenblas"
# Confuses "make install" on case-insensitive filesystems
rm "INSTALL"
# BSD "install" does not understand GNU -D flag.
# Create the parent directory ourselves.
inreplace "src/Makefile", "install -D", "install"
lib.mkpath
system "make", "install", "PREFIX=#{prefix}"
pkgshare.install "test/tch1dn.f", "test/utils.f"
end
test do
system "gfortran", "-o", "test", pkgshare/"tch1dn.f", pkgshare/"utils.f",
"-L#{lib}", "-lqrupdate",
"-L#{Formula["openblas"].opt_lib}", "-lopenblas"
assert_match "PASSED 4 FAILED 0", shell_output("./test")
end
end
|
wolffaxn/homebrew-core
|
Formula/qrupdate.rb
|
Ruby
|
bsd-2-clause
| 1,690 | 36.555556 | 93 | 0.698225 | false |
<?php
/**
* ShopMember provides customisations to {@link Member} for shop purposes
*
* @package shop
*/
class ShopMember extends DataExtension {
private static $has_many = array(
'AddressBook' => 'Address'
);
private static $has_one = array(
'DefaultShippingAddress' => 'Address',
'DefaultBillingAddress' => 'Address'
);
/**
* Get member by unique field.
* @return Member|null
*/
public static function get_by_identifier($idvalue) {
return Member::get()->filter(
Member::config()->unique_identifier_field,
$idvalue
)->first();
}
public function updateCMSFields(FieldList $fields) {
$fields->removeByName('Country');
$fields->removeByName("DefaultShippingAddressID");
$fields->removeByName("DefaultBillingAddressID");
$fields->addFieldToTab('Root.Main',
new DropdownField('Country', 'Country',
SiteConfig::current_site_config()->getCountriesList()
)
);
}
public function updateMemberFormFields($fields) {
$fields->removeByName('DefaultShippingAddressID');
$fields->removeByName('DefaultBillingAddressID');
if($gender=$fields->fieldByName('Gender')){
$gender->setHasEmptyDefault(true);
}
}
/**
* Link the current order to the current member on login,
* if there is one, and if configuration is set to do so.
*/
public function memberLoggedIn() {
if(Member::config()->login_joins_cart && $order = ShoppingCart::singleton()->current()){
$order->MemberID = $this->owner->ID;
$order->write();
}
}
/**
* Clear the cart, and session variables on member logout
*/
public function memberLoggedOut() {
if(Member::config()->login_joins_cart){
ShoppingCart::singleton()->clear();
OrderManipulation::clear_session_order_ids();
}
}
/**
* Get the past orders for this member
* @return DataList list of orders
*/
public function getPastOrders() {
return Order::get()
->filter("MemberID", $this->owner->ID)
->filter("Status:not", Order::config()->hidden_status);
}
}
|
hailwood/silverstripe-shop
|
code/model/ShopMember.php
|
PHP
|
bsd-2-clause
| 1,981 | 24.075949 | 90 | 0.679455 | false |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <dbt.h>
#include <setupapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <strsafe.h>
#include "targetver.h"
#include "utils.h"
#include "service.h"
#include "device.h"
#include "memstat.h"
#include "public.h"
// TODO: reference additional headers your program requires here
|
YanVugenfirer/virtio-win-arm
|
Balloon/app/stdafx.h
|
C
|
bsd-2-clause
| 526 | 19.230769 | 66 | 0.728137 | false |
cask 'font-allan' do
# version '1.004'
version :latest
sha256 :no_check
url 'https://github.com/google/fonts/trunk/ofl/allan',
using: :svn,
revision: '50',
trust_cert: true
homepage 'http://www.google.com/fonts/specimen/Allan'
license :ofl
font 'Allan-Bold.ttf'
font 'Allan-Regular.ttf'
end
|
RJHsiao/homebrew-fonts
|
Casks/font-allan.rb
|
Ruby
|
bsd-2-clause
| 334 | 21.266667 | 56 | 0.640719 | false |
import Map from '../src/ol/Map.js';
import OSM from '../src/ol/source/OSM.js';
import TileLayer from '../src/ol/layer/Tile.js';
import View from '../src/ol/View.js';
import {ScaleLine, defaults as defaultControls} from '../src/ol/control.js';
import {
getPointResolution,
get as getProjection,
transform,
} from '../src/ol/proj.js';
const viewProjSelect = document.getElementById('view-projection');
const projection = getProjection(viewProjSelect.value);
const scaleControl = new ScaleLine({
units: 'metric',
bar: true,
steps: 4,
text: true,
minWidth: 140,
});
const map = new Map({
controls: defaultControls().extend([scaleControl]),
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: 'map',
view: new View({
center: transform([0, 52], 'EPSG:4326', projection),
zoom: 6,
projection: projection,
}),
});
function onChangeProjection() {
const currentView = map.getView();
const currentProjection = currentView.getProjection();
const newProjection = getProjection(viewProjSelect.value);
const currentResolution = currentView.getResolution();
const currentCenter = currentView.getCenter();
const currentRotation = currentView.getRotation();
const newCenter = transform(currentCenter, currentProjection, newProjection);
const currentPointResolution = getPointResolution(
currentProjection,
1,
currentCenter,
'm'
);
const newPointResolution = getPointResolution(
newProjection,
1,
newCenter,
'm'
);
const newResolution =
(currentResolution * currentPointResolution) / newPointResolution;
const newView = new View({
center: newCenter,
resolution: newResolution,
rotation: currentRotation,
projection: newProjection,
});
map.setView(newView);
}
viewProjSelect.addEventListener('change', onChangeProjection);
|
stweil/openlayers
|
examples/projection-and-scale.js
|
JavaScript
|
bsd-2-clause
| 1,851 | 26.220588 | 79 | 0.706105 | false |
cask 'image2icon' do
version '2.11'
sha256 'a76038dd4d2cb3741235f00f2cc5dcd2f92c42a7e60c4981e17332a7fce3d721'
# sf-applications.s3.amazonaws.com/Image2Icon was verified as official when first introduced to the cask
url "https://sf-applications.s3.amazonaws.com/Image2Icon/app-releases/Image2icon#{version}.zip"
appcast 'http://apps.shinynode.com/apps/image2icon_appcast.xml'
name 'Image2Icon'
homepage 'http://www.img2icnsapp.com/'
app 'Image2Icon.app'
zap trash: [
'~/Library/Caches/net.shinyfrog.image2icon',
'~/Library/Preferences/net.shinyfrog.image2icon.plist',
'~/Library/Containers/net.shinyfrog.image2icon',
'~/Library/Containers/net.shinyfrog.image2icon.templateRenderer',
'~/Library/Containers/net.shinyfrog.templateRenderer',
'~/Library/Saved Application State/net.shinyfrog.image2icon.savedState',
]
end
|
troyxmccall/homebrew-cask
|
Casks/image2icon.rb
|
Ruby
|
bsd-2-clause
| 940 | 43.761905 | 106 | 0.702128 | false |
<?php
namespace SilverShop\Checkout\Component;
class BillingAddress extends Address
{
protected $addresstype = 'Billing';
}
|
hpeide/silverstripe-shop
|
src/Checkout/Component/BillingAddress.php
|
PHP
|
bsd-2-clause
| 130 | 15.25 | 40 | 0.761538 | false |
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>${title}</title>
<script src="AC_OETags.js" language="javascript"></script>
<style>
body { margin: 0px; overflow:hidden }
</style>
<script language="JavaScript" type="text/javascript">
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = ${version_major};
// Minor version of Flash required
var requiredMinorVersion = ${version_minor};
// Minor version of Flash required
var requiredRevision = ${version_revision};
// -----------------------------------------------------------------------------
// -->
</script>
</head>
<body scroll="no">
<script language="JavaScript" type="text/javascript">
<!--
// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
var hasProductInstall = DetectFlashVer(6, 0, 65);
// Version check based upon the values defined in globals
var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
// Check to see if a player with Flash Product Install is available and the version does not meet the requirements for playback
if ( hasProductInstall && !hasRequestedVersion ) {
// MMdoctitle is the stored document.title value used by the installation process to close the window that started the process
// This is necessary in order to close browser windows that are still utilizing the older version of the player after installation has completed
// DO NOT MODIFY THE FOLLOWING FOUR LINES
// Location visited after installation is complete if installation is required
var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
var MMredirectURL = encodeURI(window.location);
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
var MMdoctitle = document.title;
AC_FL_RunContent(
"src", "playerProductInstall",
"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
"width", "${width}",
"height", "${height}",
"align", "middle",
"id", "${application}",
"quality", "high",
"bgcolor", "${bgcolor}",
"name", "${application}",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else if (hasRequestedVersion) {
// if we've detected an acceptable version
// embed the Flash Content SWF when all tests are passed
AC_FL_RunContent(
"src", "${swf}",
"width", "${width}",
"height", "${height}",
"align", "middle",
"id", "${application}",
"quality", "high",
"bgcolor", "${bgcolor}",
"name", "${application}",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else { // flash is too old or we can't detect the plugin
var alternateContent = 'Alternate HTML content should be placed here. '
+ 'This content requires the Adobe Flash Player. '
+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
document.write(alternateContent); // insert non-flash content
}
// -->
</script>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="${application}" width="${width}" height="${height}"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="${swf}.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="${bgcolor}" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="${swf}.swf" quality="high" bgcolor="${bgcolor}"
width="${width}" height="${height}" name="${application}" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
</noscript>
</body>
</html>
|
geoffhom/face-memory2
|
flex-starts-here/html-template/face-memory.template.html
|
HTML
|
bsd-2-clause
| 4,347 | 36.8 | 145 | 0.673568 | false |
"""Provide CommentForest for Submission comments."""
from heapq import heappop, heappush
from .reddit.more import MoreComments
class CommentForest(object):
"""A forest of comments starts with multiple top-level comments.
Each of these comments can be a tree of replies.
"""
@staticmethod
def _gather_more_comments(tree, parent_tree=None):
"""Return a list of MoreComments objects obtained from tree."""
more_comments = []
queue = [(None, x) for x in tree]
while queue:
parent, comment = queue.pop(0)
if isinstance(comment, MoreComments):
heappush(more_comments, comment)
if parent:
comment._remove_from = parent.replies._comments
else:
comment._remove_from = parent_tree or tree
else:
for item in comment.replies:
queue.append((comment, item))
return more_comments
def __getitem__(self, index):
"""Return the comment at position ``index`` in the list.
This method is to be used like an array access, such as:
.. code:: python
first_comment = submission.comments[0]
Alternatively, the presence of this method enables one to iterate over
all top_level comments, like so:
.. code:: python
for comment in submission.comments:
print(comment.body)
"""
return self._comments[index]
def __init__(self, submission, comments=None):
"""Initialize a CommentForest instance.
:param submission: An instance of :class:`~.Subreddit` that is the
parent of the comments.
:param comments: Initialize the Forest with a list of comments
(default: None).
"""
self._comments = comments
self._submission = submission
def __len__(self):
"""Return the number of top-level comments in the forest."""
return len(self._comments)
def _insert_comment(self, comment):
assert comment.name not in self._submission._comments_by_id
comment.submission = self._submission
if isinstance(comment, MoreComments) or comment.is_root:
self._comments.append(comment)
else:
assert comment.parent_id in self._submission._comments_by_id
parent = self._submission._comments_by_id[comment.parent_id]
parent.replies._comments.append(comment)
def _update(self, comments):
self._comments = comments
for comment in comments:
comment.submission = self._submission
def list(self):
"""Return a flattened list of all Comments.
This list may contain :class:`.MoreComments` instances if
:meth:`.replace_more` was not called first.
"""
comments = []
queue = list(self)
while queue:
comment = queue.pop(0)
comments.append(comment)
if not isinstance(comment, MoreComments):
queue.extend(comment.replies)
return comments
def replace_more(self, limit=32, threshold=0):
"""Update the comment forest by resolving instances of MoreComments.
:param limit: The maximum number of :class:`.MoreComments` instances to
replace. Each replacement requires 1 API request. Set to ``None``
to have no limit, or to ``0`` to remove all :class:`.MoreComments`
instances without additional requests (default: 32).
:param threshold: The minimum number of children comments a
:class:`.MoreComments` instance must have in order to be
replaced. :class:`.MoreComments` instances that represent "continue
this thread" links unfortunately appear to have 0
children. (default: 0).
:returns: A list of :class:`.MoreComments` instances that were not
replaced.
For example, to replace up to 32 :class:`.MoreComments` instances of a
submission try:
.. code:: python
submission = reddit.submission('3hahrw')
submission.comments.replace_more()
Alternatively, to replace :class:`.MoreComments` instances within the
replies of a single comment try:
.. code:: python
comment = reddit.comment('d8r4im1')
comment.refresh()
comment.replies.replace_more()
.. note:: This method can take a long time as each replacement will
discover at most 20 new :class:`.Comment` or
:class:`.MoreComments` instances. As a result, consider
looping and handling exceptions until the method returns
successfully. For example:
.. code:: python
while True:
try:
submission.comments.replace_more()
break
except PossibleExceptions:
print('Handling replace_more exception')
sleep(1)
"""
remaining = limit
more_comments = self._gather_more_comments(self._comments)
skipped = []
# Fetch largest more_comments until reaching the limit or the threshold
while more_comments:
item = heappop(more_comments)
if remaining is not None and remaining <= 0 or \
item.count < threshold:
skipped.append(item)
item._remove_from.remove(item)
continue
new_comments = item.comments(update=False)
if remaining is not None:
remaining -= 1
# Add new MoreComment objects to the heap of more_comments
for more in self._gather_more_comments(new_comments,
self._comments):
more.submission = self._submission
heappush(more_comments, more)
# Insert all items into the tree
for comment in new_comments:
self._insert_comment(comment)
# Remove from forest
item._remove_from.remove(item)
return more_comments + skipped
|
13steinj/praw
|
praw/models/comment_forest.py
|
Python
|
bsd-2-clause
| 6,333 | 34.578652 | 79 | 0.577925 | false |
cask 'freefilesync' do
version '10.4'
sha256 '57e00106e0ae4e215ea97c89cdf2680db5ffba8caa8d97176da9bc54ccee9ac7'
url "https://www.freefilesync.org/download/FreeFileSync_#{version}_macOS.zip",
user_agent: :fake
name 'FreeFileSync'
homepage 'https://www.freefilesync.org/'
pkg "FreeFileSync_#{version}_macOS.pkg"
uninstall pkgutil: [
'org.freefilesync.pkg.FreeFileSync',
'org.freefilesync.pkg.RealTimeSync',
]
end
|
nathanielvarona/homebrew-cask
|
Casks/freefilesync.rb
|
Ruby
|
bsd-2-clause
| 501 | 30.3125 | 80 | 0.654691 | false |
!! Convenient definitions of numerical constants. This should not
!! be considered an exhaustive list of such constants.
module bl_constants_module
use bl_types
implicit none
real(kind = dp_t), parameter :: ZERO = 0.0_dp_t
real(kind = dp_t), parameter :: ONE = 1.0_dp_t
real(kind = dp_t), parameter :: TWO = 2.0_dp_t
real(kind = dp_t), parameter :: THREE = 3.0_dp_t
real(kind = dp_t), parameter :: FOUR = 4.0_dp_t
real(kind = dp_t), parameter :: FIVE = 5.0_dp_t
real(kind = dp_t), parameter :: SIX = 6.0_dp_t
real(kind = dp_t), parameter :: SEVEN = 7.0_dp_t
real(kind = dp_t), parameter :: EIGHT = 8.0_dp_t
real(kind = dp_t), parameter :: NINE = 9.0_dp_t
real(kind = dp_t), parameter :: TEN = 10.0_dp_t
!$acc declare copyin(ONE)
real(kind = dp_t), parameter :: ELEVEN = 11.0_dp_t
real(kind = dp_t), parameter :: TWELVE = 12.0_dp_t
real(kind = dp_t), parameter :: FIFTEEN = 15.0_dp_t
real(kind = dp_t), parameter :: SIXTEEN = 16.0_dp_t
real(kind = dp_t), parameter :: HALF = 0.5_dp_t
real(kind = dp_t), parameter :: THIRD = ONE/THREE
real(kind = dp_t), parameter :: FOURTH = 0.25_dp_t
real(kind = dp_t), parameter :: FIFTH = ONE/FIVE
real(kind = dp_t), parameter :: SIXTH = ONE/SIX
real(kind = dp_t), parameter :: SEVENTH = ONE/SEVEN
real(kind = dp_t), parameter :: EIGHTH = 0.125_dp_t
real(kind = dp_t), parameter :: NINETH = ONE/NINE
real(kind = dp_t), parameter :: TENTH = 0.10_dp_t
real(kind = dp_t), parameter :: TWELFTH = ONE/TWELVE
real(kind = dp_t), parameter :: TWO3RD = TWO/THREE
real(kind = dp_t), parameter :: FOUR3RD = FOUR/THREE
real(kind = dp_t), parameter :: FIVE3RD = FIVE/THREE
real(kind = dp_t), parameter :: THREE4TH = 0.75_dp_t
real(kind = dp_t), parameter :: SEVEN12TH = SEVEN/TWELVE
!! Pi
real(kind = dp_t), parameter :: M_PI = &
3.141592653589793238462643383279502884197_dp_t
real(kind = dp_t), parameter :: M_SQRT_PI = &
1.772453850905516027298167483341145182798_dp_t
!! Roots
real(kind = dp_t), parameter :: M_SQRT_2 = &
1.414213562373095048801688724209698078570_dp_t
end module bl_constants_module
|
dwillcox/ode-openacc
|
boxlib/bl_constants.f90
|
FORTRAN
|
bsd-2-clause
| 2,206 | 38.392857 | 66 | 0.613327 | false |
/*
* SPDX-License-Identifier: BSD-2-Clause
* Copyright 2018, Fraunhofer SIT sponsored by Infineon Technologies AG
* Copyright 2019, Intel Corporation
* All rights reserved.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <setjmp.h>
#include <cmocka.h>
#include "tss2_tcti.h"
#include "tss2-tcti/tctildr-interface.h"
#include "tss2-tcti/tctildr-nodl.h"
#define LOGMODULE test
#include "util/log.h"
TSS2_RC
__wrap_Tss2_Tcti_Device_Init(TSS2_TCTI_CONTEXT *tctiContext, size_t *size,
const char *config)
{
return TSS2_RC_SUCCESS;
}
TSS2_RC
__wrap_Tss2_Tcti_Mssim_Init(TSS2_TCTI_CONTEXT *tctiContext, size_t *size,
const char *config)
{
return TSS2_RC_SUCCESS;
}
TSS2_RC
__wrap_tcti_from_init(TSS2_TCTI_INIT_FUNC init,
const char* conf,
TSS2_TCTI_CONTEXT **tcti)
{
if (tcti != NULL)
*tcti = mock_type (TSS2_TCTI_CONTEXT*);
return mock_type (TSS2_RC);
}
void
test_tctildr_get_default_null_param (void **state)
{
TSS2_RC rc;
rc = tctildr_get_default (NULL, NULL);
assert_int_equal (rc, TSS2_TCTI_RC_BAD_REFERENCE);
}
void
test_tctildr_get_default_all_fail (void **state)
{
TSS2_RC rc;
TSS2_TCTI_CONTEXT *tcti_ctx = NULL;
#define TEST_RC 0x65203563
/* device:/dev/tpm0 */
will_return (__wrap_tcti_from_init, tcti_ctx);
will_return (__wrap_tcti_from_init, TEST_RC);
/* device:/dev/tpmrm0 */
will_return (__wrap_tcti_from_init, tcti_ctx);
will_return (__wrap_tcti_from_init, TEST_RC);
/* swtpm */
will_return (__wrap_tcti_from_init, tcti_ctx);
will_return (__wrap_tcti_from_init, TEST_RC);
#if defined (TCTI_MSSIM) && defined (TCTI_SWTPM)
/* second swtpm if enabled */
will_return (__wrap_tcti_from_init, tcti_ctx);
will_return (__wrap_tcti_from_init, TEST_RC);
#endif
rc = tctildr_get_default (&tcti_ctx, NULL);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
static TSS2_TCTI_CONTEXT_COMMON_V2 test_ctx = { 0, };
void
test_get_tcti_null_tcti (void **state)
{
TSS2_RC rc = tctildr_get_tcti (NULL, NULL, NULL, NULL);
assert_int_equal (rc, TSS2_TCTI_RC_BAD_REFERENCE);
}
void
test_get_tcti_default_success (void **state)
{
TSS2_RC rc;
TSS2_TCTI_CONTEXT *tcti_ctx = NULL;
will_return (__wrap_tcti_from_init, &test_ctx);
will_return (__wrap_tcti_from_init, TSS2_RC_SUCCESS);
rc = tctildr_get_tcti (NULL, NULL, &tcti_ctx, NULL);
assert_int_equal (rc, TSS2_RC_SUCCESS);
assert_ptr_equal (tcti_ctx, &test_ctx);
}
void
test_get_tcti_match_second (void **state)
{
TSS2_RC rc;
TSS2_TCTI_CONTEXT *tcti_ctx = NULL;
will_return (__wrap_tcti_from_init, &test_ctx);
will_return (__wrap_tcti_from_init, TSS2_RC_SUCCESS);
rc = tctildr_get_tcti ("libtss2-tcti-device.so", NULL, &tcti_ctx, NULL);
assert_int_equal (rc, TSS2_RC_SUCCESS);
assert_ptr_equal (tcti_ctx, &test_ctx);
}
void
test_get_tcti_match_none (void **state)
{
TSS2_RC rc;
TSS2_TCTI_CONTEXT *tcti_ctx = NULL;
rc = tctildr_get_tcti ("foo", NULL, &tcti_ctx, NULL);
assert_int_equal (rc, TSS2_TCTI_RC_IO_ERROR);
}
void
test_finalize_data (void **state)
{
tctildr_finalize_data (NULL);
}
void
test_get_info (void **state)
{
TSS2_RC rc = tctildr_get_info (NULL, NULL, NULL);
assert_int_equal (rc, TSS2_TCTI_RC_NOT_SUPPORTED);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test (test_tctildr_get_default_null_param),
cmocka_unit_test (test_tctildr_get_default_all_fail),
cmocka_unit_test (test_get_tcti_null_tcti),
cmocka_unit_test (test_get_tcti_default_success),
cmocka_unit_test (test_get_tcti_match_second),
cmocka_unit_test (test_get_tcti_match_none),
cmocka_unit_test (test_finalize_data),
cmocka_unit_test (test_get_info),
};
return cmocka_run_group_tests (tests, NULL, NULL);
}
|
01org/TPM2.0-TSS
|
test/unit/tctildr-nodl.c
|
C
|
bsd-2-clause
| 4,017 | 25.959732 | 76 | 0.643017 | false |
# The set of languages for which implicit dependencies are needed:
SET(CMAKE_DEPENDS_LANGUAGES
)
# The set of files for implicit dependencies of each language:
# Preprocessor definitions for this target.
SET(CMAKE_TARGET_DEFINITIONS
"CORO_ASM"
"_FILE_OFFSET_BITS=64"
"_GNU_SOURCE"
"__STDC_CONSTANT_MACROS=1"
"__STDC_FORMAT_MACROS=1"
"__STDC_LIMIT_MACROS=1"
)
# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
"src"
"src/lib"
"."
"third_party/luajit/src"
)
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
|
venkatarajasekhar/bee
|
test/CMakeFiles/test.dir/DependInfo.cmake
|
CMake
|
bsd-2-clause
| 779 | 25.862069 | 69 | 0.727856 | false |
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2016 Laurent Gomila ([email protected])
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_JOYSTICKIMPLIOS_HPP
#define SFML_JOYSTICKIMPLIOS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/JoystickImpl.hpp>
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
/// \brief iOS implementation of joysticks
///
////////////////////////////////////////////////////////////
class JoystickImpl
{
public:
////////////////////////////////////////////////////////////
/// \brief Perform the global initialization of the joystick module
///
////////////////////////////////////////////////////////////
static void initialize();
////////////////////////////////////////////////////////////
/// \brief Perform the global cleanup of the joystick module
///
////////////////////////////////////////////////////////////
static void cleanup();
////////////////////////////////////////////////////////////
/// \brief Check if a joystick is currently connected
///
/// \param index Index of the joystick to check
///
/// \return True if the joystick is connected, false otherwise
///
////////////////////////////////////////////////////////////
static bool isConnected(unsigned int index);
////////////////////////////////////////////////////////////
/// \brief Open the joystick
///
/// \param index Index assigned to the joystick
///
/// \return True on success, false on failure
///
////////////////////////////////////////////////////////////
bool open(unsigned int index);
////////////////////////////////////////////////////////////
/// \brief Close the joystick
///
////////////////////////////////////////////////////////////
void close();
////////////////////////////////////////////////////////////
/// \brief Get the joystick capabilities
///
/// \return Joystick capabilities
///
////////////////////////////////////////////////////////////
JoystickCaps getCapabilities() const;
////////////////////////////////////////////////////////////
/// \brief Get the joystick identification
///
/// \return Joystick identification
///
////////////////////////////////////////////////////////////
Joystick::Identification getIdentification() const;
////////////////////////////////////////////////////////////
/// \brief Update the joystick and get its new state
///
/// \return Joystick state
///
////////////////////////////////////////////////////////////
JoystickState update();
};
} // namespace priv
} // namespace sf
#endif // SFML_JOYSTICKIMPLIOS_HPP
|
evanbowman/FLIGHT
|
deps/SFML-2.4.1/src/SFML/Window/iOS/JoystickImpl.hpp
|
C++
|
bsd-2-clause
| 3,852 | 32.789474 | 101 | 0.43432 | false |
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Hoogle
-- Copyright : (c) Neil Mitchell 2006-2008
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Write out Hoogle compatible documentation
-- http://www.haskell.org/hoogle/
-----------------------------------------------------------------------------
module Haddock.Backends.Hoogle (
ppHoogle
) where
import BasicTypes (OverlapFlag(..), OverlapMode(..))
import InstEnv (ClsInst(..))
import Haddock.GhcUtils
import Haddock.Types hiding (Version)
import Haddock.Utils hiding (out)
import Bag
import GHC
import Outputable
import NameSet
import Data.Char
import Data.List
import Data.Maybe
import Data.Version
import System.FilePath
import System.IO
prefix :: [String]
prefix = ["-- Hoogle documentation, generated by Haddock"
,"-- See Hoogle, http://www.haskell.org/hoogle/"
,""]
ppHoogle :: DynFlags -> String -> Version -> String -> Maybe (Doc RdrName) -> [Interface] -> FilePath -> IO ()
ppHoogle dflags package version synopsis prologue ifaces odir = do
let filename = package ++ ".txt"
contents = prefix ++
docWith dflags (drop 2 $ dropWhile (/= ':') synopsis) prologue ++
["@package " ++ package] ++
["@version " ++ showVersion version
| not (null (versionBranch version)) ] ++
concat [ppModule dflags i | i <- ifaces, OptHide `notElem` ifaceOptions i]
h <- openFile (odir </> filename) WriteMode
hSetEncoding h utf8
hPutStr h (unlines contents)
hClose h
ppModule :: DynFlags -> Interface -> [String]
ppModule dflags iface =
"" : ppDocumentation dflags (ifaceDoc iface) ++
["module " ++ moduleString (ifaceMod iface)] ++
concatMap (ppExport dflags) (ifaceExportItems iface) ++
concatMap (ppInstance dflags) (ifaceInstances iface)
---------------------------------------------------------------------
-- Utility functions
dropHsDocTy :: HsType a -> HsType a
dropHsDocTy = f
where
g (L src x) = L src (f x)
f (HsForAllTy a b c d e) = HsForAllTy a b c d (g e)
f (HsBangTy a b) = HsBangTy a (g b)
f (HsAppTy a b) = HsAppTy (g a) (g b)
f (HsFunTy a b) = HsFunTy (g a) (g b)
f (HsListTy a) = HsListTy (g a)
f (HsPArrTy a) = HsPArrTy (g a)
f (HsTupleTy a b) = HsTupleTy a (map g b)
f (HsOpTy a b c) = HsOpTy (g a) b (g c)
f (HsParTy a) = HsParTy (g a)
f (HsKindSig a b) = HsKindSig (g a) b
f (HsDocTy a _) = f $ unL a
f x = x
outHsType :: OutputableBndr a => DynFlags -> HsType a -> String
outHsType dflags = out dflags . dropHsDocTy
makeExplicit :: HsType a -> HsType a
makeExplicit (HsForAllTy _ a b c d) = HsForAllTy Explicit a b c d
makeExplicit x = x
makeExplicitL :: LHsType a -> LHsType a
makeExplicitL (L src x) = L src (makeExplicit x)
dropComment :: String -> String
dropComment (' ':'-':'-':' ':_) = []
dropComment (x:xs) = x : dropComment xs
dropComment [] = []
outWith :: Outputable a => (SDoc -> String) -> a -> [Char]
outWith p = f . unwords . map (dropWhile isSpace) . lines . p . ppr
where
f xs | " <document comment>" `isPrefixOf` xs = f $ drop 19 xs
f (x:xs) = x : f xs
f [] = []
out :: Outputable a => DynFlags -> a -> String
out dflags = outWith $ showSDocUnqual dflags
operator :: String -> String
operator (x:xs) | not (isAlphaNum x) && x `notElem` "_' ([{" = '(' : x:xs ++ ")"
operator x = x
commaSeparate :: Outputable a => DynFlags -> [a] -> String
commaSeparate dflags = showSDocUnqual dflags . interpp'SP
---------------------------------------------------------------------
-- How to print each export
ppExport :: DynFlags -> ExportItem Name -> [String]
ppExport dflags ExportDecl { expItemDecl = L _ decl
, expItemMbDoc = (dc, _)
, expItemSubDocs = subdocs
, expItemFixities = fixities
} = ppDocumentation dflags dc ++ f decl
where
f (TyClD d@DataDecl{}) = ppData dflags d subdocs
f (TyClD d@SynDecl{}) = ppSynonym dflags d
f (TyClD d@ClassDecl{}) = ppClass dflags d subdocs
f (ForD (ForeignImport name typ _ _)) = ppSig dflags $ TypeSig [name] typ []
f (ForD (ForeignExport name typ _ _)) = ppSig dflags $ TypeSig [name] typ []
f (SigD sig) = ppSig dflags sig ++ ppFixities
f _ = []
ppFixities = concatMap (ppFixity dflags) fixities
ppExport _ _ = []
ppSigWithDoc :: DynFlags -> Sig Name -> [(Name, DocForDecl Name)] -> [String]
ppSigWithDoc dflags (TypeSig names sig _) subdocs
= concatMap mkDocSig names
where
mkDocSig n = concatMap (ppDocumentation dflags) (getDoc n)
++ [mkSig n]
mkSig n = operator (out dflags n) ++ " :: " ++ outHsType dflags typ
getDoc :: Located Name -> [Documentation Name]
getDoc n = maybe [] (return . fst) (lookup (unL n) subdocs)
typ = case unL sig of
HsForAllTy Explicit a b c d -> HsForAllTy Implicit a b c d
HsForAllTy Qualified a b c d -> HsForAllTy Implicit a b c d
x -> x
ppSigWithDoc _ _ _ = []
ppSig :: DynFlags -> Sig Name -> [String]
ppSig dflags x = ppSigWithDoc dflags x []
-- note: does not yet output documentation for class methods
ppClass :: DynFlags -> TyClDecl Name -> [(Name, DocForDecl Name)] -> [String]
ppClass dflags decl subdocs = (out dflags decl' ++ ppTyFams) : ppMethods
where
decl' = decl
{ tcdSigs = [], tcdMeths = emptyBag
, tcdATs = [], tcdATDefs = []
}
ppMethods = concat . map (ppSig' . unLoc) $ tcdSigs decl
ppSig' = flip (ppSigWithDoc dflags) subdocs . addContext
ppTyFams
| null $ tcdATs decl = ""
| otherwise = (" " ++) . showSDocUnqual dflags . whereWrapper $ concat
[ map ppr (tcdATs decl)
, map (ppr . tyFamEqnToSyn . unLoc) (tcdATDefs decl)
]
whereWrapper elems = vcat'
[ text "where" <+> lbrace
, nest 4 . vcat . map (<> semi) $ elems
, rbrace
]
addContext (TypeSig name (L l sig) nwcs) = TypeSig name (L l $ f sig) nwcs
addContext (MinimalSig src sig) = MinimalSig src sig
addContext _ = error "expected TypeSig"
f (HsForAllTy a b c con d) = HsForAllTy a b c (reL (context : unLoc con)) d
f t = HsForAllTy Implicit Nothing emptyHsQTvs (reL [context]) (reL t)
context = nlHsTyConApp (tcdName decl)
(map (reL . HsTyVar . hsTyVarName . unL) (hsQTvBndrs (tyClDeclTyVars decl)))
tyFamEqnToSyn :: TyFamDefltEqn Name -> TyClDecl Name
tyFamEqnToSyn tfe = SynDecl
{ tcdLName = tfe_tycon tfe
, tcdTyVars = tfe_pats tfe
, tcdRhs = tfe_rhs tfe
, tcdFVs = emptyNameSet
}
ppInstance :: DynFlags -> ClsInst -> [String]
ppInstance dflags x =
[dropComment $ outWith (showSDocForUser dflags alwaysQualify) cls]
where
-- As per #168, we don't want safety information about the class
-- in Hoogle output. The easiest way to achieve this is to set the
-- safety information to a state where the Outputable instance
-- produces no output which means no overlap and unsafe (or [safe]
-- is generated).
cls = x { is_flag = OverlapFlag { overlapMode = NoOverlap mempty
, isSafeOverlap = False } }
ppSynonym :: DynFlags -> TyClDecl Name -> [String]
ppSynonym dflags x = [out dflags x]
ppData :: DynFlags -> TyClDecl Name -> [(Name, DocForDecl Name)] -> [String]
ppData dflags decl@(DataDecl { tcdDataDefn = defn }) subdocs
= showData decl{ tcdDataDefn = defn { dd_cons=[],dd_derivs=Nothing }} :
concatMap (ppCtor dflags decl subdocs . unL) (dd_cons defn)
where
-- GHC gives out "data Bar =", we want to delete the equals
-- also writes data : a b, when we want data (:) a b
showData d = unwords $ map f $ if last xs == "=" then init xs else xs
where
xs = words $ out dflags d
nam = out dflags $ tyClDeclLName d
f w = if w == nam then operator nam else w
ppData _ _ _ = panic "ppData"
-- | for constructors, and named-fields...
lookupCon :: DynFlags -> [(Name, DocForDecl Name)] -> Located Name -> [String]
lookupCon dflags subdocs (L _ name) = case lookup name subdocs of
Just (d, _) -> ppDocumentation dflags d
_ -> []
ppCtor :: DynFlags -> TyClDecl Name -> [(Name, DocForDecl Name)] -> ConDecl Name -> [String]
ppCtor dflags dat subdocs con
= concatMap (lookupCon dflags subdocs) (con_names con) ++ f (con_details con)
where
f (PrefixCon args) = [typeSig name $ args ++ [resType]]
f (InfixCon a1 a2) = f $ PrefixCon [a1,a2]
f (RecCon (L _ recs)) = f (PrefixCon $ map cd_fld_type (map unLoc recs)) ++ concat
[(concatMap (lookupCon dflags subdocs) (cd_fld_names r)) ++
[out dflags (map unL $ cd_fld_names r) `typeSig` [resType, cd_fld_type r]]
| r <- map unLoc recs]
funs = foldr1 (\x y -> reL $ HsFunTy (makeExplicitL x) (makeExplicitL y))
apps = foldl1 (\x y -> reL $ HsAppTy x y)
typeSig nm flds = operator nm ++ " :: " ++ outHsType dflags (makeExplicit $ unL $ funs flds)
-- We print the constructors as comma-separated list. See GHC
-- docs for con_names on why it is a list to begin with.
name = commaSeparate dflags . map unL $ con_names con
resType = case con_res con of
ResTyH98 -> apps $ map (reL . HsTyVar) $
(tcdName dat) : [hsTyVarName v | L _ v@(UserTyVar _) <- hsQTvBndrs $ tyClDeclTyVars dat]
ResTyGADT _ x -> x
ppFixity :: DynFlags -> (Name, Fixity) -> [String]
ppFixity dflags (name, fixity) = [out dflags (FixitySig [noLoc name] fixity)]
---------------------------------------------------------------------
-- DOCUMENTATION
ppDocumentation :: Outputable o => DynFlags -> Documentation o -> [String]
ppDocumentation dflags (Documentation d w) = mdoc dflags d ++ doc dflags w
doc :: Outputable o => DynFlags -> Maybe (Doc o) -> [String]
doc dflags = docWith dflags ""
mdoc :: Outputable o => DynFlags -> Maybe (MDoc o) -> [String]
mdoc dflags = docWith dflags "" . fmap _doc
docWith :: Outputable o => DynFlags -> String -> Maybe (Doc o) -> [String]
docWith _ [] Nothing = []
docWith dflags header d
= ("":) $ zipWith (++) ("-- | " : repeat "-- ") $
lines header ++ ["" | header /= "" && isJust d] ++
maybe [] (showTags . markup (markupTag dflags)) d
data Tag = TagL Char [Tags] | TagP Tags | TagPre Tags | TagInline String Tags | Str String
deriving Show
type Tags = [Tag]
box :: (a -> b) -> a -> [b]
box f x = [f x]
str :: String -> [Tag]
str a = [Str a]
-- want things like paragraph, pre etc to be handled by blank lines in the source document
-- and things like \n and \t converted away
-- much like blogger in HTML mode
-- everything else wants to be included as tags, neatly nested for some (ul,li,ol)
-- or inlne for others (a,i,tt)
-- entities (&,>,<) should always be appropriately escaped
markupTag :: Outputable o => DynFlags -> DocMarkup o [Tag]
markupTag dflags = Markup {
markupParagraph = box TagP,
markupEmpty = str "",
markupString = str,
markupAppend = (++),
markupIdentifier = box (TagInline "a") . str . out dflags,
markupIdentifierUnchecked = box (TagInline "a") . str . out dflags . snd,
markupModule = box (TagInline "a") . str,
markupWarning = box (TagInline "i"),
markupEmphasis = box (TagInline "i"),
markupBold = box (TagInline "b"),
markupMonospaced = box (TagInline "tt"),
markupPic = const $ str " ",
markupUnorderedList = box (TagL 'u'),
markupOrderedList = box (TagL 'o'),
markupDefList = box (TagL 'u') . map (\(a,b) -> TagInline "i" a : Str " " : b),
markupCodeBlock = box TagPre,
markupHyperlink = \(Hyperlink url mLabel) -> (box (TagInline "a") . str) (fromMaybe url mLabel),
markupAName = const $ str "",
markupProperty = box TagPre . str,
markupExample = box TagPre . str . unlines . map exampleToString,
markupHeader = \(Header l h) -> box (TagInline $ "h" ++ show l) h
}
showTags :: [Tag] -> [String]
showTags = intercalate [""] . map showBlock
showBlock :: Tag -> [String]
showBlock (TagP xs) = showInline xs
showBlock (TagL t xs) = ['<':t:"l>"] ++ mid ++ ['<':'/':t:"l>"]
where mid = concatMap (showInline . box (TagInline "li")) xs
showBlock (TagPre xs) = ["<pre>"] ++ showPre xs ++ ["</pre>"]
showBlock x = showInline [x]
asInline :: Tag -> Tags
asInline (TagP xs) = xs
asInline (TagPre xs) = [TagInline "pre" xs]
asInline (TagL t xs) = [TagInline (t:"l") $ map (TagInline "li") xs]
asInline x = [x]
showInline :: [Tag] -> [String]
showInline = unwordsWrap 70 . words . concatMap f
where
fs = concatMap f
f (Str x) = escape x
f (TagInline s xs) = "<"++s++">" ++ (if s == "li" then trim else id) (fs xs) ++ "</"++s++">"
f x = fs $ asInline x
trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse
showPre :: [Tag] -> [String]
showPre = trimFront . trimLines . lines . concatMap f
where
trimLines = dropWhile null . reverse . dropWhile null . reverse
trimFront xs = map (drop i) xs
where
ns = [length a | x <- xs, let (a,b) = span isSpace x, b /= ""]
i = if null ns then 0 else minimum ns
fs = concatMap f
f (Str x) = escape x
f (TagInline s xs) = "<"++s++">" ++ fs xs ++ "</"++s++">"
f x = fs $ asInline x
unwordsWrap :: Int -> [String] -> [String]
unwordsWrap n = f n []
where
f _ s [] = [g s | s /= []]
f i s (x:xs) | nx > i = g s : f (n - nx - 1) [x] xs
| otherwise = f (i - nx - 1) (x:s) xs
where nx = length x
g = unwords . reverse
escape :: String -> String
escape = concatMap f
where
f '<' = "<"
f '>' = ">"
f '&' = "&"
f x = [x]
-- | Just like 'vcat' but uses '($+$)' instead of '($$)'.
vcat' :: [SDoc] -> SDoc
vcat' = foldr ($+$) empty
|
lamefun/haddock
|
haddock-api/src/Haddock/Backends/Hoogle.hs
|
Haskell
|
bsd-2-clause
| 14,777 | 35.667494 | 112 | 0.563105 | false |
cask 'routeconverter' do
version '2.23'
sha256 'd1eef2e465017b9e69f1d8283b2394899eaf4cfa2b604114095c1b7f25917eca'
url "https://static.routeconverter.com/download/previous-releases/#{version}/RouteConverterMac.app.zip"
appcast 'https://static.routeconverter.com/download/previous-releases/'
name 'RouteConverter'
homepage 'https://www.routeconverter.com/'
auto_updates true
app 'RouteConverterMac.app'
end
|
nathanielvarona/homebrew-cask
|
Casks/routeconverter.rb
|
Ruby
|
bsd-2-clause
| 424 | 31.615385 | 105 | 0.792453 | false |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Filter;
use Zend\Filter\StringTrim;
use stdClass;
/**
* @covers \Zend\Filter\StringTrim
*/
class StringTrimTest extends \PHPUnit_Framework_TestCase
{
/**
* @var StringTrim
*/
protected $_filter;
/**
* Creates a new Zend\Filter\StringTrim object for each test method
*
* @return void
*/
public function setUp()
{
$this->_filter = new StringTrim();
}
/**
* Ensures that the filter follows expected behavior
*
* @return void
*/
public function testBasic()
{
$filter = $this->_filter;
$valuesExpected = [
'string' => 'string',
' str ' => 'str',
"\ns\t" => 's'
];
foreach ($valuesExpected as $input => $output) {
$this->assertEquals($output, $filter($input));
}
}
/**
* Ensures that the filter follows expected behavior
*
* @return void
*/
public function testUtf8()
{
$this->assertEquals('a', $this->_filter->filter(utf8_encode("\xa0a\xa0")));
}
/**
* Ensures that getCharList() returns expected default value
*
* @return void
*/
public function testGetCharList()
{
$this->assertEquals(null, $this->_filter->getCharList());
}
/**
* Ensures that setCharList() follows expected behavior
*
* @return void
*/
public function testSetCharList()
{
$this->_filter->setCharList('&');
$this->assertEquals('&', $this->_filter->getCharList());
}
/**
* Ensures expected behavior under custom character list
*
* @return void
*/
public function testCharList()
{
$filter = $this->_filter;
$filter->setCharList('&');
$this->assertEquals('a&b', $filter('&&a&b&&'));
}
/**
* @group ZF-7183
*/
public function testZF7183()
{
$filter = $this->_filter;
$this->assertEquals('Зенд', $filter('Зенд'));
}
/**
* @group ZF2-170
*/
public function testZF2170()
{
$filter = $this->_filter;
$this->assertEquals('Расчет', $filter('Расчет'));
}
/**
* @group ZF-7902
*/
public function testZF7902()
{
$filter = $this->_filter;
$this->assertEquals('/', $filter('/'));
}
/**
* @group ZF-10891
*/
public function testZF10891()
{
$filter = $this->_filter;
$this->assertEquals('Зенд', $filter(' Зенд '));
$this->assertEquals('Зенд', $filter('Зенд '));
$this->assertEquals('Зенд', $filter(' Зенд'));
$trim_charlist = " \t\n\r\x0B・。";
$filter = new StringTrim($trim_charlist);
$this->assertEquals('Зенд', $filter->filter('。 Зенд 。'));
}
public function getNonStringValues()
{
return [
[1],
[1.0],
[true],
[false],
[null],
[[1, 2, 3]],
[new stdClass()],
];
}
/**
* @dataProvider getNonStringValues
*/
public function testShouldNotFilterNonStringValues($value)
{
$filtered = $this->_filter->filter($value);
$this->assertSame($value, $filtered);
}
/**
* Ensures expected behavior with '0' as character list
*
* @group 6261
*/
public function testEmptyCharList()
{
$filter = $this->_filter;
$filter->setCharList('0');
$this->assertEquals('a0b', $filter('00a0b00'));
$filter->setCharList('');
$this->assertEquals('str', $filter(' str '));
}
}
|
Maks3w/zend-filter
|
test/StringTrimTest.php
|
PHP
|
bsd-3-clause
| 4,042 | 21.754286 | 86 | 0.523355 | false |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/ime_adapter_android.h"
#include <algorithm>
#include <android/input.h>
#include <vector>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/feature_list.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "content/common/frame_messages.h"
#include "content/common/input_messages.h"
#include "content/common/view_messages.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "jni/ImeAdapter_jni.h"
#include "third_party/WebKit/public/web/WebCompositionUnderline.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebTextInputType.h"
using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF16;
namespace content {
namespace {
// Maps a java KeyEvent into a NativeWebKeyboardEvent.
// |java_key_event| is used to maintain a globalref for KeyEvent.
// |action| will help determine the WebInputEvent type.
// type, |modifiers|, |time_ms|, |key_code|, |unicode_char| is used to create
// WebKeyboardEvent. |key_code| is also needed ad need to treat the enter key
// as a key press of character \r.
NativeWebKeyboardEvent NativeWebKeyboardEventFromKeyEvent(
JNIEnv* env,
jobject java_key_event,
int action,
int modifiers,
long time_ms,
int key_code,
int scan_code,
bool is_system_key,
int unicode_char) {
blink::WebInputEvent::Type type = blink::WebInputEvent::Undefined;
if (action == AKEY_EVENT_ACTION_DOWN)
type = blink::WebInputEvent::RawKeyDown;
else if (action == AKEY_EVENT_ACTION_UP)
type = blink::WebInputEvent::KeyUp;
else
NOTREACHED() << "Invalid Android key event action: " << action;
return NativeWebKeyboardEvent(java_key_event, type, modifiers,
time_ms / 1000.0, key_code, scan_code, unicode_char, is_system_key);
}
} // anonymous namespace
bool RegisterImeAdapter(JNIEnv* env) {
return RegisterNativesImpl(env);
}
// Callback from Java to convert BackgroundColorSpan data to a
// blink::WebCompositionUnderline instance, and append it to |underlines_ptr|.
void AppendBackgroundColorSpan(JNIEnv*,
const JavaParamRef<jclass>&,
jlong underlines_ptr,
jint start,
jint end,
jint background_color) {
DCHECK_GE(start, 0);
DCHECK_GE(end, 0);
// Do not check |background_color|.
std::vector<blink::WebCompositionUnderline>* underlines =
reinterpret_cast<std::vector<blink::WebCompositionUnderline>*>(
underlines_ptr);
underlines->push_back(
blink::WebCompositionUnderline(static_cast<unsigned>(start),
static_cast<unsigned>(end),
SK_ColorTRANSPARENT,
false,
static_cast<unsigned>(background_color)));
}
// Callback from Java to convert UnderlineSpan data to a
// blink::WebCompositionUnderline instance, and append it to |underlines_ptr|.
void AppendUnderlineSpan(JNIEnv*,
const JavaParamRef<jclass>&,
jlong underlines_ptr,
jint start,
jint end) {
DCHECK_GE(start, 0);
DCHECK_GE(end, 0);
std::vector<blink::WebCompositionUnderline>* underlines =
reinterpret_cast<std::vector<blink::WebCompositionUnderline>*>(
underlines_ptr);
underlines->push_back(
blink::WebCompositionUnderline(static_cast<unsigned>(start),
static_cast<unsigned>(end),
SK_ColorBLACK,
false,
SK_ColorTRANSPARENT));
}
ImeAdapterAndroid::ImeAdapterAndroid(RenderWidgetHostViewAndroid* rwhva)
: rwhva_(rwhva) {
}
ImeAdapterAndroid::~ImeAdapterAndroid() {
JNIEnv* env = AttachCurrentThread();
base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env);
if (!obj.is_null())
Java_ImeAdapter_detach(env, obj.obj());
}
bool ImeAdapterAndroid::SendSyntheticKeyEvent(JNIEnv*,
const JavaParamRef<jobject>&,
int type,
long time_ms,
int key_code,
int modifiers,
int text) {
NativeWebKeyboardEvent event(static_cast<blink::WebInputEvent::Type>(type),
modifiers, time_ms / 1000.0, key_code, 0,
text, false /* is_system_key */);
rwhva_->SendKeyEvent(event);
return true;
}
bool ImeAdapterAndroid::SendKeyEvent(
JNIEnv* env,
const JavaParamRef<jobject>&,
const JavaParamRef<jobject>& original_key_event,
int action,
int modifiers,
long time_ms,
int key_code,
int scan_code,
bool is_system_key,
int unicode_char) {
NativeWebKeyboardEvent event = NativeWebKeyboardEventFromKeyEvent(
env, original_key_event, action, modifiers,
time_ms, key_code, scan_code, is_system_key, unicode_char);
bool key_down_text_insertion =
event.type == blink::WebInputEvent::RawKeyDown && event.text[0];
// If we are going to follow up with a synthetic Char event, then that's the
// one we expect to test if it's handled or unhandled, so skip handling the
// "real" event in the browser.
event.skip_in_browser = key_down_text_insertion;
rwhva_->SendKeyEvent(event);
if (key_down_text_insertion) {
// Send a Char event, but without an os_event since we don't want to
// roundtrip back to java such synthetic event.
NativeWebKeyboardEvent char_event(blink::WebInputEvent::Char, modifiers,
time_ms / 1000.0, key_code, scan_code,
unicode_char,
is_system_key);
char_event.skip_in_browser = key_down_text_insertion;
rwhva_->SendKeyEvent(char_event);
}
return true;
}
void ImeAdapterAndroid::SetComposingText(JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jobject>& text,
const JavaParamRef<jstring>& text_str,
int new_cursor_pos) {
RenderWidgetHostImpl* rwhi = GetRenderWidgetHostImpl();
if (!rwhi)
return;
base::string16 text16 = ConvertJavaStringToUTF16(env, text_str);
std::vector<blink::WebCompositionUnderline> underlines;
// Iterate over spans in |text|, dispatch those that we care about (e.g.,
// BackgroundColorSpan) to a matching callback (e.g.,
// AppendBackgroundColorSpan()), and populate |underlines|.
Java_ImeAdapter_populateUnderlinesFromSpans(
env, obj, text, reinterpret_cast<jlong>(&underlines));
// Default to plain underline if we didn't find any span that we care about.
if (underlines.empty()) {
underlines.push_back(blink::WebCompositionUnderline(
0, text16.length(), SK_ColorBLACK, false, SK_ColorTRANSPARENT));
}
// Sort spans by |.startOffset|.
std::sort(underlines.begin(), underlines.end());
// new_cursor_position is as described in the Android API for
// InputConnection#setComposingText, whereas the parameters for
// ImeSetComposition are relative to the start of the composition.
if (new_cursor_pos > 0)
new_cursor_pos = text16.length() + new_cursor_pos - 1;
rwhi->ImeSetComposition(text16, underlines, gfx::Range::InvalidRange(),
new_cursor_pos, new_cursor_pos);
}
void ImeAdapterAndroid::CommitText(JNIEnv* env,
const JavaParamRef<jobject>&,
const JavaParamRef<jstring>& text_str) {
RenderWidgetHostImpl* rwhi = GetRenderWidgetHostImpl();
if (!rwhi)
return;
base::string16 text16 = ConvertJavaStringToUTF16(env, text_str);
rwhi->ImeConfirmComposition(text16, gfx::Range::InvalidRange(), false);
}
void ImeAdapterAndroid::FinishComposingText(JNIEnv* env,
const JavaParamRef<jobject>&) {
RenderWidgetHostImpl* rwhi = GetRenderWidgetHostImpl();
if (!rwhi)
return;
rwhi->ImeConfirmComposition(base::string16(), gfx::Range::InvalidRange(),
true);
}
void ImeAdapterAndroid::AttachImeAdapter(
JNIEnv* env,
const JavaParamRef<jobject>& java_object) {
java_ime_adapter_ = JavaObjectWeakGlobalRef(env, java_object);
}
void ImeAdapterAndroid::CancelComposition() {
base::android::ScopedJavaLocalRef<jobject> obj =
java_ime_adapter_.get(AttachCurrentThread());
if (!obj.is_null())
Java_ImeAdapter_cancelComposition(AttachCurrentThread(), obj.obj());
}
void ImeAdapterAndroid::FocusedNodeChanged(bool is_editable_node) {
base::android::ScopedJavaLocalRef<jobject> obj =
java_ime_adapter_.get(AttachCurrentThread());
if (!obj.is_null()) {
Java_ImeAdapter_focusedNodeChanged(AttachCurrentThread(),
obj.obj(),
is_editable_node);
}
}
void ImeAdapterAndroid::SetEditableSelectionOffsets(
JNIEnv*,
const JavaParamRef<jobject>&,
int start,
int end) {
RenderFrameHost* rfh = GetFocusedFrame();
if (!rfh)
return;
rfh->Send(new FrameMsg_SetEditableSelectionOffsets(rfh->GetRoutingID(),
start, end));
}
void ImeAdapterAndroid::SetComposingRegion(JNIEnv*,
const JavaParamRef<jobject>&,
int start,
int end) {
RenderFrameHost* rfh = GetFocusedFrame();
if (!rfh)
return;
std::vector<blink::WebCompositionUnderline> underlines;
underlines.push_back(blink::WebCompositionUnderline(
0, end - start, SK_ColorBLACK, false, SK_ColorTRANSPARENT));
rfh->Send(new InputMsg_SetCompositionFromExistingText(
rfh->GetRoutingID(), start, end, underlines));
}
void ImeAdapterAndroid::DeleteSurroundingText(JNIEnv*,
const JavaParamRef<jobject>&,
int before,
int after) {
RenderFrameHostImpl* rfh =
static_cast<RenderFrameHostImpl*>(GetFocusedFrame());
if (rfh)
rfh->ExtendSelectionAndDelete(before, after);
}
bool ImeAdapterAndroid::RequestTextInputStateUpdate(
JNIEnv* env,
const JavaParamRef<jobject>&) {
RenderWidgetHostImpl* rwhi = GetRenderWidgetHostImpl();
if (!rwhi)
return false;
rwhi->Send(new InputMsg_RequestTextInputStateUpdate(rwhi->GetRoutingID()));
return true;
}
bool ImeAdapterAndroid::IsImeThreadEnabled(
JNIEnv* env,
const base::android::JavaParamRef<jobject>&) {
return base::FeatureList::IsEnabled(features::kImeThread);
}
void ImeAdapterAndroid::ResetImeAdapter(JNIEnv* env,
const JavaParamRef<jobject>&) {
java_ime_adapter_.reset();
}
RenderWidgetHostImpl* ImeAdapterAndroid::GetRenderWidgetHostImpl() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(rwhva_);
RenderWidgetHost* rwh = rwhva_->GetRenderWidgetHost();
if (!rwh)
return nullptr;
return RenderWidgetHostImpl::From(rwh);
}
RenderFrameHost* ImeAdapterAndroid::GetFocusedFrame() {
RenderWidgetHostImpl* rwh = GetRenderWidgetHostImpl();
if (!rwh)
return nullptr;
RenderViewHost* rvh = RenderViewHost::From(rwh);
if (!rvh)
return nullptr;
FrameTreeNode* focused_frame =
rvh->GetDelegate()->GetFrameTree()->GetFocusedFrame();
if (!focused_frame)
return nullptr;
return focused_frame->current_frame_host();
}
WebContents* ImeAdapterAndroid::GetWebContents() {
RenderWidgetHostImpl* rwh = GetRenderWidgetHostImpl();
if (!rwh)
return nullptr;
return WebContents::FromRenderViewHost(RenderViewHost::From(rwh));
}
} // namespace content
|
ds-hwang/chromium-crosswalk
|
content/browser/renderer_host/ime_adapter_android.cc
|
C++
|
bsd-3-clause
| 13,137 | 36.75 | 79 | 0.637512 | false |
<?php
namespace rest\models\master;
use Yii;
/**
* This is the model class for table "{{%customer_detail}}".
*
* @property integer $id
* @property integer $distric_id
* @property string $addr1
* @property string $addr2
* @property double $latitude
* @property double $longtitude
* @property integer $kab_id
* @property integer $kec_id
* @property integer $kel_id
* @property string $created_at
* @property integer $created_by
* @property string $updated_at
* @property integer $updated_by
*
* @property Customer $id0
*
* @author Misbahul D Munir <[email protected]>
* @since 3.0
*/
class CustomerDetail extends \rest\classes\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%customer_detail}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'required'],
[['id', 'distric_id', 'kab_id', 'kec_id', 'kel_id', 'created_by', 'updated_by'], 'integer'],
[['latitude', 'longtitude'], 'number'],
[['created_at', 'updated_at'], 'safe'],
[['addr1', 'addr2'], 'string', 'max' => 128]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'distric_id' => 'Distric ID',
'addr1' => 'Addr1',
'addr2' => 'Addr2',
'latitude' => 'Latitude',
'longtitude' => 'Longtitude',
'kab_id' => 'Kab ID',
'kec_id' => 'Kec ID',
'kel_id' => 'Kel ID',
'created_at' => 'Created At',
'created_by' => 'Created By',
'updated_at' => 'Updated At',
'updated_by' => 'Updated By',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getId0()
{
return $this->hasOne(Customer::className(), ['id' => 'id']);
}
/**
* @inheritdoc
*/
public function behaviors()
{
return[
'yii\behaviors\TimestampBehavior',
'yii\behaviors\BlameableBehavior'
];
}
}
|
deesoft/yii2-application
|
rest/models/master/CustomerDetail.php
|
PHP
|
bsd-3-clause
| 2,167 | 22.301075 | 104 | 0.505307 | false |
module Plugin where
resource :: Num t => t
resource = 0xBAD
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/testsuite/pdynload/badint/Plugin.hs
|
Haskell
|
bsd-3-clause
| 61 | 14.25 | 22 | 0.704918 | false |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This header is logically internal, but is made public because it is used
// from protocol-compiler-generated code, which may reside in other components.
#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__
#include <string>
#include <vector>
#include <google/protobuf/stubs/casts.h>
#include <google/protobuf/stubs/common.h>
// TODO(jasonh): Remove this once the compiler change to directly include this
// is released to components.
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/message.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/unknown_field_set.h>
namespace google {
namespace upb {
namespace google_opensource {
class GMR_Handlers;
} // namespace google_opensource
} // namespace upb
namespace protobuf {
class DescriptorPool;
class MapKey;
class MapValueRef;
}
namespace protobuf {
namespace internal {
class DefaultEmptyOneof;
// Defined in this file.
class GeneratedMessageReflection;
// Defined in other files.
class ExtensionSet; // extension_set.h
// THIS CLASS IS NOT INTENDED FOR DIRECT USE. It is intended for use
// by generated code. This class is just a big hack that reduces code
// size.
//
// A GeneratedMessageReflection is an implementation of Reflection
// which expects all fields to be backed by simple variables located in
// memory. The locations are given using a base pointer and a set of
// offsets.
//
// It is required that the user represents fields of each type in a standard
// way, so that GeneratedMessageReflection can cast the void* pointer to
// the appropriate type. For primitive fields and string fields, each field
// should be represented using the obvious C++ primitive type. Enums and
// Messages are different:
// - Singular Message fields are stored as a pointer to a Message. These
// should start out NULL, except for in the default instance where they
// should start out pointing to other default instances.
// - Enum fields are stored as an int. This int must always contain
// a valid value, such that EnumDescriptor::FindValueByNumber() would
// not return NULL.
// - Repeated fields are stored as RepeatedFields or RepeatedPtrFields
// of whatever type the individual field would be. Strings and
// Messages use RepeatedPtrFields while everything else uses
// RepeatedFields.
class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection {
public:
// Constructs a GeneratedMessageReflection.
// Parameters:
// descriptor: The descriptor for the message type being implemented.
// default_instance: The default instance of the message. This is only
// used to obtain pointers to default instances of embedded
// messages, which GetMessage() will return if the particular
// sub-message has not been initialized yet. (Thus, all
// embedded message fields *must* have non-NULL pointers
// in the default instance.)
// offsets: An array of ints giving the byte offsets, relative to
// the start of the message object, of each field. These can
// be computed at compile time using the
// GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET() macro, defined
// below.
// has_bits_offset: Offset in the message of an array of uint32s of size
// descriptor->field_count()/32, rounded up. This is a
// bitfield where each bit indicates whether or not the
// corresponding field of the message has been initialized.
// The bit for field index i is obtained by the expression:
// has_bits[i / 32] & (1 << (i % 32))
// unknown_fields_offset: Offset in the message of the UnknownFieldSet for
// the message.
// extensions_offset: Offset in the message of the ExtensionSet for the
// message, or -1 if the message type has no extension
// ranges.
// pool: DescriptorPool to search for extension definitions. Only
// used by FindKnownExtensionByName() and
// FindKnownExtensionByNumber().
// factory: MessageFactory to use to construct extension messages.
// object_size: The size of a message object of this type, as measured
// by sizeof().
GeneratedMessageReflection(const Descriptor* descriptor,
const Message* default_instance,
const int offsets[],
int has_bits_offset,
int unknown_fields_offset,
int extensions_offset,
const DescriptorPool* pool,
MessageFactory* factory,
int object_size,
int arena_offset,
int is_default_instance_offset = -1);
// Similar with the construction above. Call this construction if the
// message has oneof definition.
// Parameters:
// offsets: An array of ints giving the byte offsets.
// For each oneof field, the offset is relative to the
// default_oneof_instance. These can be computed at compile
// time using the
// PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET() macro.
// For each none oneof field, the offset is related to
// the start of the message object. These can be computed
// at compile time using the
// GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET() macro.
// Besides offsets for all fields, this array also contains
// offsets for oneof unions. The offset of the i-th oneof
// union is offsets[descriptor->field_count() + i].
// default_oneof_instance: The default instance of the oneofs. It is a
// struct holding the default value of all oneof fields
// for this message. It is only used to obtain pointers
// to default instances of oneof fields, which Get
// methods will return if the field is not set.
// oneof_case_offset: Offset in the message of an array of uint32s of
// size descriptor->oneof_decl_count(). Each uint32
// indicates what field is set for each oneof.
// other parameters are the same with the construction above.
GeneratedMessageReflection(const Descriptor* descriptor,
const Message* default_instance,
const int offsets[],
int has_bits_offset,
int unknown_fields_offset,
int extensions_offset,
const void* default_oneof_instance,
int oneof_case_offset,
const DescriptorPool* pool,
MessageFactory* factory,
int object_size,
int arena_offset,
int is_default_instance_offset = -1);
~GeneratedMessageReflection();
// Shorter-to-call helpers for the above two constructions that work if the
// pool and factory are the usual, namely, DescriptorPool::generated_pool()
// and MessageFactory::generated_factory().
static GeneratedMessageReflection* NewGeneratedMessageReflection(
const Descriptor* descriptor,
const Message* default_instance,
const int offsets[],
int has_bits_offset,
int unknown_fields_offset,
int extensions_offset,
const void* default_oneof_instance,
int oneof_case_offset,
int object_size,
int arena_offset,
int is_default_instance_offset = -1);
static GeneratedMessageReflection* NewGeneratedMessageReflection(
const Descriptor* descriptor,
const Message* default_instance,
const int offsets[],
int has_bits_offset,
int unknown_fields_offset,
int extensions_offset,
int object_size,
int arena_offset,
int is_default_instance_offset = -1);
// implements Reflection -------------------------------------------
const UnknownFieldSet& GetUnknownFields(const Message& message) const;
UnknownFieldSet* MutableUnknownFields(Message* message) const;
int SpaceUsed(const Message& message) const;
bool HasField(const Message& message, const FieldDescriptor* field) const;
int FieldSize(const Message& message, const FieldDescriptor* field) const;
void ClearField(Message* message, const FieldDescriptor* field) const;
bool HasOneof(const Message& message,
const OneofDescriptor* oneof_descriptor) const;
void ClearOneof(Message* message, const OneofDescriptor* field) const;
void RemoveLast(Message* message, const FieldDescriptor* field) const;
Message* ReleaseLast(Message* message, const FieldDescriptor* field) const;
void Swap(Message* message1, Message* message2) const;
void SwapFields(Message* message1, Message* message2,
const vector<const FieldDescriptor*>& fields) const;
void SwapElements(Message* message, const FieldDescriptor* field,
int index1, int index2) const;
void ListFields(const Message& message,
vector<const FieldDescriptor*>* output) const;
int32 GetInt32 (const Message& message,
const FieldDescriptor* field) const;
int64 GetInt64 (const Message& message,
const FieldDescriptor* field) const;
uint32 GetUInt32(const Message& message,
const FieldDescriptor* field) const;
uint64 GetUInt64(const Message& message,
const FieldDescriptor* field) const;
float GetFloat (const Message& message,
const FieldDescriptor* field) const;
double GetDouble(const Message& message,
const FieldDescriptor* field) const;
bool GetBool (const Message& message,
const FieldDescriptor* field) const;
string GetString(const Message& message,
const FieldDescriptor* field) const;
const string& GetStringReference(const Message& message,
const FieldDescriptor* field,
string* scratch) const;
const EnumValueDescriptor* GetEnum(const Message& message,
const FieldDescriptor* field) const;
int GetEnumValue(const Message& message,
const FieldDescriptor* field) const;
const Message& GetMessage(const Message& message,
const FieldDescriptor* field,
MessageFactory* factory = NULL) const;
const FieldDescriptor* GetOneofFieldDescriptor(
const Message& message,
const OneofDescriptor* oneof_descriptor) const;
private:
bool ContainsMapKey(const Message& message,
const FieldDescriptor* field,
const MapKey& key) const;
bool InsertOrLookupMapValue(Message* message,
const FieldDescriptor* field,
const MapKey& key,
MapValueRef* val) const;
bool DeleteMapValue(Message* message,
const FieldDescriptor* field,
const MapKey& key) const;
MapIterator MapBegin(
Message* message,
const FieldDescriptor* field) const;
MapIterator MapEnd(
Message* message,
const FieldDescriptor* field) const;
int MapSize(const Message& message, const FieldDescriptor* field) const;
public:
void SetInt32 (Message* message,
const FieldDescriptor* field, int32 value) const;
void SetInt64 (Message* message,
const FieldDescriptor* field, int64 value) const;
void SetUInt32(Message* message,
const FieldDescriptor* field, uint32 value) const;
void SetUInt64(Message* message,
const FieldDescriptor* field, uint64 value) const;
void SetFloat (Message* message,
const FieldDescriptor* field, float value) const;
void SetDouble(Message* message,
const FieldDescriptor* field, double value) const;
void SetBool (Message* message,
const FieldDescriptor* field, bool value) const;
void SetString(Message* message,
const FieldDescriptor* field,
const string& value) const;
void SetEnum (Message* message, const FieldDescriptor* field,
const EnumValueDescriptor* value) const;
void SetEnumValue(Message* message, const FieldDescriptor* field,
int value) const;
Message* MutableMessage(Message* message, const FieldDescriptor* field,
MessageFactory* factory = NULL) const;
void SetAllocatedMessage(Message* message,
Message* sub_message,
const FieldDescriptor* field) const;
Message* ReleaseMessage(Message* message, const FieldDescriptor* field,
MessageFactory* factory = NULL) const;
int32 GetRepeatedInt32 (const Message& message,
const FieldDescriptor* field, int index) const;
int64 GetRepeatedInt64 (const Message& message,
const FieldDescriptor* field, int index) const;
uint32 GetRepeatedUInt32(const Message& message,
const FieldDescriptor* field, int index) const;
uint64 GetRepeatedUInt64(const Message& message,
const FieldDescriptor* field, int index) const;
float GetRepeatedFloat (const Message& message,
const FieldDescriptor* field, int index) const;
double GetRepeatedDouble(const Message& message,
const FieldDescriptor* field, int index) const;
bool GetRepeatedBool (const Message& message,
const FieldDescriptor* field, int index) const;
string GetRepeatedString(const Message& message,
const FieldDescriptor* field, int index) const;
const string& GetRepeatedStringReference(const Message& message,
const FieldDescriptor* field,
int index, string* scratch) const;
const EnumValueDescriptor* GetRepeatedEnum(const Message& message,
const FieldDescriptor* field,
int index) const;
int GetRepeatedEnumValue(const Message& message,
const FieldDescriptor* field,
int index) const;
const Message& GetRepeatedMessage(const Message& message,
const FieldDescriptor* field,
int index) const;
// Set the value of a field.
void SetRepeatedInt32 (Message* message,
const FieldDescriptor* field, int index, int32 value) const;
void SetRepeatedInt64 (Message* message,
const FieldDescriptor* field, int index, int64 value) const;
void SetRepeatedUInt32(Message* message,
const FieldDescriptor* field, int index, uint32 value) const;
void SetRepeatedUInt64(Message* message,
const FieldDescriptor* field, int index, uint64 value) const;
void SetRepeatedFloat (Message* message,
const FieldDescriptor* field, int index, float value) const;
void SetRepeatedDouble(Message* message,
const FieldDescriptor* field, int index, double value) const;
void SetRepeatedBool (Message* message,
const FieldDescriptor* field, int index, bool value) const;
void SetRepeatedString(Message* message,
const FieldDescriptor* field, int index,
const string& value) const;
void SetRepeatedEnum(Message* message, const FieldDescriptor* field,
int index, const EnumValueDescriptor* value) const;
void SetRepeatedEnumValue(Message* message, const FieldDescriptor* field,
int index, int value) const;
// Get a mutable pointer to a field with a message type.
Message* MutableRepeatedMessage(Message* message,
const FieldDescriptor* field,
int index) const;
void AddInt32 (Message* message,
const FieldDescriptor* field, int32 value) const;
void AddInt64 (Message* message,
const FieldDescriptor* field, int64 value) const;
void AddUInt32(Message* message,
const FieldDescriptor* field, uint32 value) const;
void AddUInt64(Message* message,
const FieldDescriptor* field, uint64 value) const;
void AddFloat (Message* message,
const FieldDescriptor* field, float value) const;
void AddDouble(Message* message,
const FieldDescriptor* field, double value) const;
void AddBool (Message* message,
const FieldDescriptor* field, bool value) const;
void AddString(Message* message,
const FieldDescriptor* field, const string& value) const;
void AddEnum(Message* message,
const FieldDescriptor* field,
const EnumValueDescriptor* value) const;
void AddEnumValue(Message* message,
const FieldDescriptor* field,
int value) const;
Message* AddMessage(Message* message, const FieldDescriptor* field,
MessageFactory* factory = NULL) const;
void AddAllocatedMessage(
Message* message, const FieldDescriptor* field,
Message* new_entry) const;
const FieldDescriptor* FindKnownExtensionByName(const string& name) const;
const FieldDescriptor* FindKnownExtensionByNumber(int number) const;
bool SupportsUnknownEnumValues() const;
// This value for arena_offset_ indicates that there is no arena pointer in
// this message (e.g., old generated code).
static const int kNoArenaPointer = -1;
// This value for unknown_field_offset_ indicates that there is no
// UnknownFieldSet in this message, and that instead, we are using the
// Zero-Overhead Arena Pointer trick. When this is the case, arena_offset_
// actually indexes to an InternalMetadataWithArena instance, which can return
// either an arena pointer or an UnknownFieldSet or both. It is never the case
// that unknown_field_offset_ == kUnknownFieldSetInMetadata && arena_offset_
// == kNoArenaPointer.
static const int kUnknownFieldSetInMetadata = -1;
protected:
void* MutableRawRepeatedField(
Message* message, const FieldDescriptor* field, FieldDescriptor::CppType,
int ctype, const Descriptor* desc) const;
const void* GetRawRepeatedField(
const Message& message, const FieldDescriptor* field,
FieldDescriptor::CppType, int ctype,
const Descriptor* desc) const;
virtual MessageFactory* GetMessageFactory() const;
virtual void* RepeatedFieldData(
Message* message, const FieldDescriptor* field,
FieldDescriptor::CppType cpp_type,
const Descriptor* message_type) const;
private:
friend class GeneratedMessage;
// To parse directly into a proto2 generated class, the class GMR_Handlers
// needs access to member offsets and hasbits.
friend class upb::google_opensource::GMR_Handlers;
const Descriptor* descriptor_;
const Message* default_instance_;
const void* default_oneof_instance_;
const int* offsets_;
int has_bits_offset_;
int oneof_case_offset_;
int unknown_fields_offset_;
int extensions_offset_;
int arena_offset_;
int is_default_instance_offset_;
int object_size_;
static const int kHasNoDefaultInstanceField = -1;
const DescriptorPool* descriptor_pool_;
MessageFactory* message_factory_;
template <typename Type>
inline const Type& GetRaw(const Message& message,
const FieldDescriptor* field) const;
template <typename Type>
inline Type* MutableRaw(Message* message,
const FieldDescriptor* field) const;
template <typename Type>
inline const Type& DefaultRaw(const FieldDescriptor* field) const;
template <typename Type>
inline const Type& DefaultOneofRaw(const FieldDescriptor* field) const;
inline const uint32* GetHasBits(const Message& message) const;
inline uint32* MutableHasBits(Message* message) const;
inline uint32 GetOneofCase(
const Message& message,
const OneofDescriptor* oneof_descriptor) const;
inline uint32* MutableOneofCase(
Message* message,
const OneofDescriptor* oneof_descriptor) const;
inline const ExtensionSet& GetExtensionSet(const Message& message) const;
inline ExtensionSet* MutableExtensionSet(Message* message) const;
inline Arena* GetArena(Message* message) const;
inline const internal::InternalMetadataWithArena&
GetInternalMetadataWithArena(const Message& message) const;
inline internal::InternalMetadataWithArena*
MutableInternalMetadataWithArena(Message* message) const;
inline bool GetIsDefaultInstance(const Message& message) const;
inline bool HasBit(const Message& message,
const FieldDescriptor* field) const;
inline void SetBit(Message* message,
const FieldDescriptor* field) const;
inline void ClearBit(Message* message,
const FieldDescriptor* field) const;
inline void SwapBit(Message* message1,
Message* message2,
const FieldDescriptor* field) const;
// This function only swaps the field. Should swap corresponding has_bit
// before or after using this function.
void SwapField(Message* message1,
Message* message2,
const FieldDescriptor* field) const;
void SwapOneofField(Message* message1,
Message* message2,
const OneofDescriptor* oneof_descriptor) const;
inline bool HasOneofField(const Message& message,
const FieldDescriptor* field) const;
inline void SetOneofCase(Message* message,
const FieldDescriptor* field) const;
inline void ClearOneofField(Message* message,
const FieldDescriptor* field) const;
template <typename Type>
inline const Type& GetField(const Message& message,
const FieldDescriptor* field) const;
template <typename Type>
inline void SetField(Message* message,
const FieldDescriptor* field, const Type& value) const;
template <typename Type>
inline Type* MutableField(Message* message,
const FieldDescriptor* field) const;
template <typename Type>
inline const Type& GetRepeatedField(const Message& message,
const FieldDescriptor* field,
int index) const;
template <typename Type>
inline const Type& GetRepeatedPtrField(const Message& message,
const FieldDescriptor* field,
int index) const;
template <typename Type>
inline void SetRepeatedField(Message* message,
const FieldDescriptor* field, int index,
Type value) const;
template <typename Type>
inline Type* MutableRepeatedField(Message* message,
const FieldDescriptor* field,
int index) const;
template <typename Type>
inline void AddField(Message* message,
const FieldDescriptor* field, const Type& value) const;
template <typename Type>
inline Type* AddField(Message* message,
const FieldDescriptor* field) const;
int GetExtensionNumberOrDie(const Descriptor* type) const;
// Internal versions of EnumValue API perform no checking. Called after checks
// by public methods.
void SetEnumValueInternal(Message* message,
const FieldDescriptor* field,
int value) const;
void SetRepeatedEnumValueInternal(Message* message,
const FieldDescriptor* field,
int index,
int value) const;
void AddEnumValueInternal(Message* message,
const FieldDescriptor* field,
int value) const;
Message* UnsafeArenaReleaseMessage(Message* message,
const FieldDescriptor* field,
MessageFactory* factory = NULL) const;
void UnsafeArenaSetAllocatedMessage(Message* message,
Message* sub_message,
const FieldDescriptor* field) const;
internal::MapFieldBase* MapData(
Message* message, const FieldDescriptor* field) const;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratedMessageReflection);
};
// Returns the offset of the given field within the given aggregate type.
// This is equivalent to the ANSI C offsetof() macro. However, according
// to the C++ standard, offsetof() only works on POD types, and GCC
// enforces this requirement with a warning. In practice, this rule is
// unnecessarily strict; there is probably no compiler or platform on
// which the offsets of the direct fields of a class are non-constant.
// Fields inherited from superclasses *can* have non-constant offsets,
// but that's not what this macro will be used for.
//
// Note that we calculate relative to the pointer value 16 here since if we
// just use zero, GCC complains about dereferencing a NULL pointer. We
// choose 16 rather than some other number just in case the compiler would
// be confused by an unaligned pointer.
#if defined(__clang__)
// For Clang we use __builtin_offsetof() and suppress the warning,
// to avoid Control Flow Integrity and UBSan vptr sanitizers from
// crashing while trying to validate the invalid reinterpet_casts.
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(TYPE, FIELD) \
_Pragma("clang diagnostic pop")
#else
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \
static_cast<int>( \
reinterpret_cast<const char*>( \
&reinterpret_cast<const TYPE*>(16)->FIELD) - \
reinterpret_cast<const char*>(16))
#endif
#define PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(ONEOF, FIELD) \
static_cast<int>( \
reinterpret_cast<const char*>(&(ONEOF->FIELD)) \
- reinterpret_cast<const char*>(ONEOF))
// There are some places in proto2 where dynamic_cast would be useful as an
// optimization. For example, take Message::MergeFrom(const Message& other).
// For a given generated message FooMessage, we generate these two methods:
// void MergeFrom(const FooMessage& other);
// void MergeFrom(const Message& other);
// The former method can be implemented directly in terms of FooMessage's
// inline accessors, but the latter method must work with the reflection
// interface. However, if the parameter to the latter method is actually of
// type FooMessage, then we'd like to be able to just call the other method
// as an optimization. So, we use dynamic_cast to check this.
//
// That said, dynamic_cast requires RTTI, which many people like to disable
// for performance and code size reasons. When RTTI is not available, we
// still need to produce correct results. So, in this case we have to fall
// back to using reflection, which is what we would have done anyway if the
// objects were not of the exact same class.
//
// dynamic_cast_if_available() implements this logic. If RTTI is
// enabled, it does a dynamic_cast. If RTTI is disabled, it just returns
// NULL.
//
// If you need to compile without RTTI, simply #define GOOGLE_PROTOBUF_NO_RTTI.
// On MSVC, this should be detected automatically.
template<typename To, typename From>
inline To dynamic_cast_if_available(From from) {
#if defined(GOOGLE_PROTOBUF_NO_RTTI) || (defined(_MSC_VER)&&!defined(_CPPRTTI))
return NULL;
#else
return dynamic_cast<To>(from);
#endif
}
// Tries to downcast this message to a generated message type.
// Returns NULL if this class is not an instance of T.
//
// This is like dynamic_cast_if_available, except it works even when
// dynamic_cast is not available by using Reflection. However it only works
// with Message objects.
//
// TODO(haberman): can we remove dynamic_cast_if_available in favor of this?
template <typename T>
T* DynamicCastToGenerated(const Message* from) {
// Compile-time assert that T is a generated type that has a
// default_instance() accessor, but avoid actually calling it.
const T&(*get_default_instance)() = &T::default_instance;
(void)get_default_instance;
// Compile-time assert that T is a subclass of google::protobuf::Message.
const Message* unused = static_cast<T*>(NULL);
(void)unused;
#if defined(GOOGLE_PROTOBUF_NO_RTTI) || \
(defined(_MSC_VER) && !defined(_CPPRTTI))
bool ok = &T::default_instance() ==
from->GetReflection()->GetMessageFactory()->GetPrototype(
from->GetDescriptor());
return ok ? down_cast<T*>(from) : NULL;
#else
return dynamic_cast<T*>(from);
#endif
}
template <typename T>
T* DynamicCastToGenerated(Message* from) {
const Message* message_const = from;
return const_cast<T*>(DynamicCastToGenerated<const T>(message_const));
}
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__
|
axinging/chromium-crosswalk
|
third_party/protobuf/src/google/protobuf/generated_message_reflection.h
|
C
|
bsd-3-clause
| 32,352 | 46.298246 | 86 | 0.650161 | false |
# -*- coding: utf-8 -*-
import json
import logging
import time
from os.path import dirname
try:
from PIL import Image
except ImportError:
import Image
from django.conf import settings
from django.core.management import call_command
from django.db.models import loading
from django.core.files.base import ContentFile
from django.http import HttpRequest
from django.test.client import Client
from django.core import mail
from nose.tools import assert_equal, with_setup, assert_false, eq_, ok_
from nose.plugins.attrib import attr
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
else:
notification = None
try:
from funfactory.urlresolvers import reverse
except ImportError:
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from . import BadgerTestCase, patch_settings
import badger
from badger.models import (Badge, Award, Nomination, Progress, DeferredAward,
BadgeAwardNotAllowedException,
BadgeAlreadyAwardedException,
DeferredAwardGrantNotAllowedException,
NominationApproveNotAllowedException,
NominationAcceptNotAllowedException,
NominationRejectNotAllowedException,
SITE_ISSUER, slugify)
from badger_example.models import GuestbookEntry
BASE_URL = 'http://example.com'
BADGE_IMG_FN = "%s/fixtures/default-badge.png" % dirname(dirname(__file__))
class BadgerBadgeTest(BadgerTestCase):
def test_get_badge(self):
"""Can create a badge"""
badge = self._get_badge()
eq_(slugify(badge.title), badge.slug)
ok_(badge.created is not None)
ok_(badge.modified is not None)
eq_(badge.created.year, badge.modified.year)
eq_(badge.created.month, badge.modified.month)
eq_(badge.created.day, badge.modified.day)
def test_unicode_slug(self):
"""Issue #124: django slugify function turns up blank slugs"""
badge = self._get_badge()
badge.title = u'弁護士バッジ(レプリカ)'
badge.slug = ''
img_data = open(BADGE_IMG_FN, 'r').read()
badge.image.save('', ContentFile(img_data), True)
badge.save()
ok_(badge.slug != '')
eq_(slugify(badge.title), badge.slug)
def test_award_badge(self):
"""Can award a badge to a user"""
badge = self._get_badge()
user = self._get_user()
ok_(not badge.is_awarded_to(user))
badge.award_to(awardee=user, awarder=badge.creator)
ok_(badge.is_awarded_to(user))
def test_award_unique_duplication(self):
"""Only one award for a unique badge can be created"""
user = self._get_user()
b = Badge.objects.create(slug='one-and-only', title='One and Only',
unique=True, creator=user)
a = Award.objects.create(badge=b, user=user)
# award_to should not trigger the exception by default
b.award_to(awardee=user)
try:
b.award_to(awardee=user, raise_already_awarded=True)
ok_(False, 'BadgeAlreadyAwardedException should have been raised')
except BadgeAlreadyAwardedException:
# The raise_already_awarded flag should raise the exception
pass
try:
a = Award.objects.create(badge=b, user=user)
ok_(False, 'BadgeAlreadyAwardedException should have been raised')
except BadgeAlreadyAwardedException:
# But, directly creating another award should trigger the exception
pass
eq_(1, Award.objects.filter(badge=b, user=user).count())
class BadgerOBITest(BadgerTestCase):
def test_baked_award_image(self):
"""Award gets image baked with OBI assertion"""
# Get the source for a sample badge image
img_data = open(BADGE_IMG_FN, 'r').read()
# Make a badge with a creator
user_creator = self._get_user(username="creator")
badge = self._get_badge(title="Badge with Creator",
creator=user_creator)
badge.image.save('', ContentFile(img_data), True)
# Get some users who can award any badge
user_1 = self._get_user(username="superuser_1",
is_superuser=True)
user_2 = self._get_user(username="superuser_2",
is_superuser=True)
# Get some users who can receive badges
user_awardee_1 = self._get_user(username="awardee_1")
user_awardee_2 = self._get_user(username="awardee_1")
# Try awarding the badge once with baking enabled and once without
for enabled in (True, False):
with patch_settings(BADGER_BAKE_AWARD_IMAGES=enabled):
award_1 = badge.award_to(awardee=user_awardee_1)
if not enabled:
ok_(not award_1.image)
else:
ok_(award_1.image)
img = Image.open(award_1.image.file)
hosted_assertion_url = img.info['openbadges']
expected_url = '%s%s' % (
BASE_URL, reverse('badger.award_detail_json',
args=(award_1.badge.slug,
award_1.id)))
eq_(expected_url, hosted_assertion_url)
award_1.delete()
class BadgerProgressTest(BadgerTestCase):
def test_progress_badge_already_awarded(self):
"""New progress toward an awarded unique badge cannot be recorded"""
user = self._get_user()
b = Badge.objects.create(slug='one-and-only', title='One and Only',
unique=True, creator=user)
p = b.progress_for(user)
p.update_percent(100)
try:
p = Progress.objects.create(badge=b, user=user)
ok_(False, 'BadgeAlreadyAwardedException should have been raised')
except BadgeAlreadyAwardedException:
pass
# None, because award deletes progress.
eq_(0, Progress.objects.filter(badge=b, user=user).count())
class BadgerDeferredAwardTest(BadgerTestCase):
def test_claim_by_code(self):
"""Can claim a deferred award by claim code"""
user = self._get_user()
awardee = self._get_user(username='winner1',
email='[email protected]')
badge1 = self._get_badge(title="Test A", creator=user)
ok_(not badge1.is_awarded_to(awardee))
da = DeferredAward(badge=badge1)
da.save()
code = da.claim_code
eq_(1, DeferredAward.objects.filter(claim_code=code).count())
DeferredAward.objects.claim_by_code(awardee, code)
eq_(0, DeferredAward.objects.filter(claim_code=code).count())
ok_(badge1.is_awarded_to(awardee))
# Ensure the award was marked with the claim code.
award = Award.objects.get(claim_code=code)
eq_(award.badge.pk, badge1.pk)
def test_claim_by_email(self):
"""Can claim all deferred awards by email address"""
deferred_email = '[email protected]'
user = self._get_user()
titles = ("Test A", "Test B", "Test C")
badges = (self._get_badge(title=title, creator=user)
for title in titles)
deferreds = []
# Issue deferred awards for each of the badges.
for badge in badges:
result = badge.award_to(email=deferred_email, awarder=user)
deferreds.append(result)
ok_(hasattr(result, 'claim_code'))
# Scour the mail outbox for claim messages.
if notification:
for deferred in deferreds:
found = False
for msg in mail.outbox:
if (deferred.badge.title in msg.subject and
deferred.get_claim_url() in msg.body):
found = True
ok_(found, '%s should have been found in subject' %
deferred.badge.title)
# Register an awardee user with the email address, but the badge should
# not have been awarded yet.
awardee = self._get_user(username='winner2', email=deferred_email)
for badge in badges:
ok_(not badge.is_awarded_to(awardee))
# Now, claim the deferred awards, and they should all self-destruct
eq_(3, DeferredAward.objects.filter(email=awardee.email).count())
DeferredAward.objects.claim_by_email(awardee)
eq_(0, DeferredAward.objects.filter(email=awardee.email).count())
# After claiming, the awards should exist.
for badge in badges:
ok_(badge.is_awarded_to(awardee))
def test_reusable_claim(self):
"""Can repeatedly claim a reusable deferred award"""
user = self._get_user()
awardee = self._get_user(username='winner1',
email='[email protected]')
badge1 = self._get_badge(title="Test A", creator=user, unique=False)
ok_(not badge1.is_awarded_to(awardee))
da = DeferredAward(badge=badge1, reusable=True)
da.save()
code = da.claim_code
for i in range(0, 5):
eq_(1, DeferredAward.objects.filter(claim_code=code).count())
DeferredAward.objects.claim_by_code(awardee, code)
ok_(badge1.is_awarded_to(awardee))
eq_(5, Award.objects.filter(badge=badge1, user=awardee).count())
def test_disallowed_claim(self):
"""Deferred award created by someone not allowed to award a badge
cannot be claimed"""
user = self._get_user()
random_guy = self._get_user(username='random_guy',
is_superuser=False)
awardee = self._get_user(username='winner1',
email='[email protected]')
badge1 = self._get_badge(title="Test A", creator=user)
ok_(not badge1.is_awarded_to(awardee))
da = DeferredAward(badge=badge1, creator=random_guy)
da.save()
code = da.claim_code
eq_(1, DeferredAward.objects.filter(claim_code=code).count())
result = DeferredAward.objects.claim_by_code(awardee, code)
eq_(0, DeferredAward.objects.filter(claim_code=code).count())
ok_(not badge1.is_awarded_to(awardee))
def test_granted_claim(self):
"""Reusable deferred award can be granted to someone by email"""
# Assemble the characters involved...
creator = self._get_user()
random_guy = self._get_user(username='random_guy',
email='[email protected]',
is_superuser=False)
staff_person = self._get_user(username='staff_person',
email='[email protected]',
is_staff=True)
grantee_email = '[email protected]'
grantee = self._get_user(username='winner1',
email=grantee_email)
# Create a consumable award claim
badge1 = self._get_badge(title="Test A", creator=creator)
original_email = '[email protected]'
da = DeferredAward(badge=badge1, creator=creator, email=original_email)
claim_code = da.claim_code
da.save()
# Grant the deferred award, ensure the existing one is modified.
new_da = da.grant_to(email=grantee_email, granter=staff_person)
ok_(claim_code != new_da.claim_code)
ok_(da.email != original_email)
eq_(da.pk, new_da.pk)
eq_(new_da.email, grantee_email)
# Claim the deferred award, assert that the appropriate deferred award
# was destroyed
eq_(1, DeferredAward.objects.filter(pk=da.pk).count())
eq_(1, DeferredAward.objects.filter(pk=new_da.pk).count())
DeferredAward.objects.claim_by_email(grantee)
eq_(0, DeferredAward.objects.filter(pk=da.pk).count())
eq_(0, DeferredAward.objects.filter(pk=new_da.pk).count())
# Finally, assert the award condition
ok_(badge1.is_awarded_to(grantee))
# Create a reusable award claim
badge2 = self._get_badge(title="Test B", creator=creator)
da = DeferredAward(badge=badge2, creator=creator, reusable=True)
claim_code = da.claim_code
da.save()
# Grant the deferred award, ensure a new deferred award is generated.
new_da = da.grant_to(email=grantee_email, granter=staff_person)
ok_(claim_code != new_da.claim_code)
ok_(da.pk != new_da.pk)
eq_(new_da.email, grantee_email)
# Claim the deferred award, assert that the appropriate deferred award
# was destroyed
eq_(1, DeferredAward.objects.filter(pk=da.pk).count())
eq_(1, DeferredAward.objects.filter(pk=new_da.pk).count())
DeferredAward.objects.claim_by_email(grantee)
eq_(1, DeferredAward.objects.filter(pk=da.pk).count())
eq_(0, DeferredAward.objects.filter(pk=new_da.pk).count())
# Finally, assert the award condition
ok_(badge2.is_awarded_to(grantee))
# Create one more award claim
badge3 = self._get_badge(title="Test C", creator=creator)
da = DeferredAward(badge=badge3, creator=creator)
claim_code = da.claim_code
da.save()
# Grant the deferred award, ensure a new deferred award is generated.
try:
new_da = da.grant_to(email=grantee_email, granter=random_guy)
is_ok = False
except Exception, e:
ok_(type(e) is DeferredAwardGrantNotAllowedException)
is_ok = True
ok_(is_ok, "Permission should be required for granting")
def test_mass_generate_claim_codes(self):
"""Claim codes can be generated in mass for a badge"""
# Assemble the characters involved...
creator = self._get_user()
random_guy = self._get_user(username='random_guy',
email='[email protected]',
is_superuser=False)
staff_person = self._get_user(username='staff_person',
email='[email protected]',
is_staff=True)
# Create a consumable award claim
badge1 = self._get_badge(title="Test A", creator=creator)
eq_(0, len(badge1.claim_groups))
# Generate a number of groups of varying size
num_awards = (10, 20, 40, 80, 100)
num_groups = len(num_awards)
groups_generated = dict()
for x in range(0, num_groups):
num = num_awards[x]
cg = badge1.generate_deferred_awards(user=creator, amount=num)
time.sleep(1.0)
groups_generated[cg] = num
eq_(num, DeferredAward.objects.filter(claim_group=cg).count())
# Ensure the expected claim groups are available
if False:
# FIXME: Seems like the claim groups count doesn't work with
# sqlite3 tests
eq_(num_groups, len(badge1.claim_groups))
for item in badge1.claim_groups:
cg = item['claim_group']
eq_(groups_generated[cg], item['count'])
# Delete deferred awards found in the first claim group
cg_1 = badge1.claim_groups[0]['claim_group']
badge1.delete_claim_group(user=creator, claim_group=cg_1)
# Assert that the claim group is gone, and now there's one less.
eq_(num_groups - 1, len(badge1.claim_groups))
def test_deferred_award_unique_duplication(self):
"""Only one deferred award for a unique badge can be created"""
deferred_email = '[email protected]'
user = self._get_user()
b = Badge.objects.create(slug='one-and-only', title='One and Only',
unique=True, creator=user)
a = Award.objects.create(badge=b, user=user)
b.award_to(email=deferred_email, awarder=user)
# There should be one deferred award for the email.
eq_(1, DeferredAward.objects.filter(email=deferred_email).count())
# Award again. Tt should raise an exception and there still should
# be one deferred award.
self.assertRaises(
BadgeAlreadyAwardedException,
lambda: b.award_to(email=deferred_email, awarder=user))
eq_(1, DeferredAward.objects.filter(email=deferred_email).count())
def test_only_first_deferred_sends_email(self):
"""Only the first deferred award will trigger an email."""
deferred_email = '[email protected]'
user = self._get_user()
b1 = Badge.objects.create(slug='one-and-only', title='One and Only',
unique=True, creator=user)
b1.award_to(email=deferred_email, awarder=user)
# There should be one deferred award and one email in the outbox.
eq_(1, DeferredAward.objects.filter(email=deferred_email).count())
eq_(1, len(mail.outbox))
# Award a second badge and there should be two deferred awards and
# still only one email in the outbox.
b2 = Badge.objects.create(slug='another-one', title='Another One',
unique=True, creator=user)
b2.award_to(email=deferred_email, awarder=user)
eq_(2, DeferredAward.objects.filter(email=deferred_email).count())
eq_(1, len(mail.outbox))
class BadgerMultiplayerBadgeTest(BadgerTestCase):
def setUp(self):
self.user_1 = self._get_user(username="user_1",
email="[email protected]", password="user_1_pass")
self.stranger = self._get_user(username="stranger",
email="[email protected]",
password="stranger_pass")
def tearDown(self):
Nomination.objects.all().delete()
Award.objects.all().delete()
Badge.objects.all().delete()
def test_nominate_badge(self):
"""Can nominate a user for a badge"""
badge = self._get_badge()
nominator = self._get_user(username="nominator",
email="[email protected]", password="nomnom1")
nominee = self._get_user(username="nominee",
email="[email protected]", password="nomnom2")
ok_(not badge.is_nominated_for(nominee))
nomination = badge.nominate_for(nominator=nominator, nominee=nominee)
ok_(badge.is_nominated_for(nominee))
def test_approve_nomination(self):
"""A nomination can be approved"""
nomination = self._create_nomination()
eq_(False, nomination.allows_approve_by(self.stranger))
eq_(True, nomination.allows_approve_by(nomination.badge.creator))
ok_(not nomination.is_approved)
nomination.approve_by(nomination.badge.creator)
ok_(nomination.is_approved)
def test_autoapprove_nomination(self):
"""All nominations should be auto-approved for a badge flagged for
auto-approval"""
badge = self._get_badge()
badge.nominations_autoapproved = True
badge.save()
nomination = self._create_nomination()
ok_(nomination.is_approved)
def test_accept_nomination(self):
"""A nomination can be accepted"""
nomination = self._create_nomination()
eq_(False, nomination.allows_accept(self.stranger))
eq_(True, nomination.allows_accept(nomination.nominee))
ok_(not nomination.is_accepted)
nomination.accept(nomination.nominee)
ok_(nomination.is_accepted)
def test_approve_accept_nomination(self):
"""A nomination that is approved and accepted results in an award"""
nomination = self._create_nomination()
ok_(not nomination.badge.is_awarded_to(nomination.nominee))
nomination.approve_by(nomination.badge.creator)
nomination.accept(nomination.nominee)
ok_(nomination.badge.is_awarded_to(nomination.nominee))
ct = Award.objects.filter(nomination=nomination).count()
eq_(1, ct, "There should be an award associated with the nomination")
def test_reject_nomination(self):
SAMPLE_REASON = "Just a test anyway"
nomination = self._create_nomination()
rejected_by = nomination.badge.creator
eq_(False, nomination.allows_reject_by(self.stranger))
eq_(True, nomination.allows_reject_by(nomination.badge.creator))
eq_(True, nomination.allows_reject_by(nomination.nominee))
nomination.reject_by(rejected_by, reason=SAMPLE_REASON)
eq_(rejected_by, nomination.rejected_by)
ok_(nomination.is_rejected)
eq_(SAMPLE_REASON, nomination.rejected_reason)
eq_(False, nomination.allows_reject_by(self.stranger))
eq_(False, nomination.allows_reject_by(nomination.badge.creator))
eq_(False, nomination.allows_reject_by(nomination.nominee))
eq_(False, nomination.allows_accept(self.stranger))
eq_(False, nomination.allows_accept(nomination.nominee))
eq_(False, nomination.allows_approve_by(self.stranger))
eq_(False, nomination.allows_approve_by(nomination.badge.creator))
def test_disallowed_nomination_approval(self):
"""By default, only badge creator should be allowed to approve a
nomination."""
nomination = self._create_nomination()
other_user = self._get_user(username="other")
try:
nomination = nomination.approve_by(other_user)
ok_(False, "Nomination should not have succeeded")
except NominationApproveNotAllowedException:
ok_(True)
def test_disallowed_nomination_accept(self):
"""By default, only nominee should be allowed to accept a
nomination."""
nomination = self._create_nomination()
other_user = self._get_user(username="other")
try:
nomination = nomination.accept(other_user)
ok_(False, "Nomination should not have succeeded")
except NominationAcceptNotAllowedException:
ok_(True)
def _get_user(self, username="tester", email="[email protected]",
password="trustno1"):
(user, created) = User.objects.get_or_create(username=username,
defaults=dict(email=email))
if created:
user.set_password(password)
user.save()
return user
def test_nomination_badge_already_awarded(self):
"""New nomination for an awarded unique badge cannot be created"""
user = self._get_user()
b = Badge.objects.create(slug='one-and-only', title='One and Only',
unique=True, creator=user)
n = b.nominate_for(user)
n.accept(user)
n.approve_by(user)
try:
n = Nomination.objects.create(badge=b, nominee=user)
ok_(False, 'BadgeAlreadyAwardedException should have been raised')
except BadgeAlreadyAwardedException:
pass
# Nominations stick around after award.
eq_(1, Nomination.objects.filter(badge=b, nominee=user).count())
def _get_badge(self, title="Test Badge",
description="This is a test badge", creator=None):
creator = creator or self.user_1
(badge, created) = Badge.objects.get_or_create(title=title,
defaults=dict(description=description, creator=creator))
return badge
def _create_nomination(self, badge=None, nominator=None, nominee=None):
badge = badge or self._get_badge()
nominator = nominator or self._get_user(username="nominator",
email="[email protected]", password="nomnom1")
nominee = nominee or self._get_user(username="nominee",
email="[email protected]", password="nomnom2")
nomination = badge.nominate_for(nominator=nominator, nominee=nominee)
return nomination
|
mozilla/django-badger
|
badger/tests/test_models.py
|
Python
|
bsd-3-clause
| 24,044 | 38.184339 | 79 | 0.612198 | false |
---
title: Pipes
---
# Pipes
#### Motivation
Output data transformations. They ensure data is in a desirable format by the time it loads onto the user’s screen. Normally data transforms behind the scenes. With pipes, transforming data can take place in the template HTML. Pipes transform template data directly.
Pipes look nice and are convenient. They help keep the component’s class lean of basic transformations. To put it technically, pipes encapsulate data transformation logic.
#### Output Transformation
As mentioned in the prior section, pipes transform data inline. The syntax of pipes correlate shell scripting. In many scripts, the output of one part of the command gets *piped* as output into the next part as input. That same trend characterizes Angular pipes.
In Angular, there exists many ways to interact with data in the template HTML. Pipes can apply anywhere data gets parsed into the template HTML. They can occur within microsyntax logic and innerHTML variable interpolations. Pipes account for all transformations without adding onto the component class.
Pipes are also *chainable*. You can integrate pipes one after the other to perform increasingly complex transformations. As specialized data transformers, pipes are hardly trivial.
#### Use Cases
Angular comes prepackaged with a basic set of pipes. Working with a couple of them will develop the intuition to handle the rest. The following list provides two examples.
* AsyncPipe
* DatePipe
These two perform simple tasks. Their simplicity is massively beneficial.
##### AsyncPipe
This sections requires a basic understanding of Promises or Observables to fully appreciate. The AsyncPipe operates on either of the two. AsyncPipe extracts data from Promises/Observables as output for whatever comes next.
In the case of Obervables, AsyncPipe subscribes automatically to the data source. Regardless of where the data comes from, the AsyncPipe subscribes to the source observable. `async` is the syntactical name of AsyncPipe as shown below.
```html
<ul *ngFor=“let potato of (potatoSack$ | async); let i=index”>
<li>Potatoe {{i + 1}}: {{potato}}</li>
</ul>
```
In the example, `potatoSack$` is an Observable pending an upload of potatoes. Once the potatoes arrive, either synchronously or asynchronously, the AsyncPipe receives them as an *iterable* array. The list element then fills up with potatoes.
##### DatePipe
Formatting date strings takes a fair bit of hacking with the JavaScript `Date` object. The DatePipe provides a powerful way to format dates assuming the given input is a valid time format.
```typescript
// example.component.ts
@Component({
templateUrl: './example.component.html'
})
export class ExampleComponent {
timestamp:string = ‘2018-05-24T19:38:11.103Z’;
}
```
```html
<!-- example.component.html -->
<div>Current Time: {{timestamp | date:‘short’}}</div>
```
The format of the above `timestamp` is [ISO 8601<sup>1</sup>](https://en.wikipedia.org/wiki/ISO_8601)—not the easiest to read. The DatePipe (`date`) transforms the ISO date format into a more conventional `mm/dd/yy, hh:mm AM|PM`. There are many other formatting options. All these options are in the [official documentation](https://angular.io/api/common/DatePipe).
#### Creating Pipes
While Angular only has a set number of pipes, the `@Pipe` decorator lets developers create their own. The process begins with `ng generate pipe [name-of-pipe]`, replacing `[name-of-pipe]` with a preferable filename. This is an [Angular CLI](https://cli.angular.io) command. It yields the following.
```typescript
import { Pipe, PipeTransform } from ‘@angular/core’;
@Pipe({
name: 'example'
})
export class ExamplePipe implements PipeTransform {
transform(value: any, args?: any): any {
return null;
}
}
```
This pipe template simplifies custom pipe creation. The `@Pipe` decorator tells Angular the class is a pipe. The value of `name: ‘example’`, in this case being `example`, is the value Angular recognizes when scanning template HTML for custom pipes.
On to the class logic. The `PipeTransform` implementation provides the instructions for the `transform` function. This function has special meaning within context of the `@Pipe` decorator. It receives two parameters by default.
`value: any` is the output that the pipe receives. Think of `<div>{{ someValue | example }}</div>`. The value of someValue gets passed to the `transform` function’s `value: any` parameter. This is the same `transform` function defined in the ExamplePipe class.
`args?: any` is any argument that the pipe optionally receives. Think of `<div>{{ someValue | example:[some-argument] }}</div>`. `[some-argument]` can be replace by any one value. This value gets passed to the `transform` function’s `args?: any` parameter. That is, the `transform` function defined in ExamplePipe's class.
Whatever the function returns (`return null;`) becomes the output of the pipe operation. Take a look at the next example to see a complete example of ExamplePipe. Depending on the variable the pipe receives, it either uppercases or lowercases the input as new output. An invalid or nonexistent argument will cause the pipe to return the same input as output.
```typescript
// example.pipe.ts
@Pipe({
name: 'example'
})
export class ExamplePipe implements PipeTransform {
transform(value:string, args?:string): any {
switch(args || null) {
case 'uppercase':
return value.toUpperCase();
case 'lowercase':
return value.toLowerCase();
default:
return value;
}
}
}
```
```typescript
// app.component.ts
@Component({
templateUrl: 'app.component.html'
})
export class AppComponent {
someValue:string = "HeLlO WoRlD!";
}
```
```html
<!-- app.component.html -->
<!-- Outputs “HeLlO WoRlD!” -->
<h6>{{ someValue | example }}</h6>
<!-- Outputs “HELLO WORLD!” -->
<h6>{{ someValue | example:‘uppercase’ }}</h6>
<!-- Outputs “hello world!” -->
<h6>{{ someValue | example:‘lowercase’ }}</h6>
```
Understanding the above example means you understand Angular pipes. There is only one more topic left to discuss.
#### Pure and Impure Pipes
Everything you have seen so far has been a *pure* pipe. `pure: true` is set by default in the `@Pipe` decorator's metadata. The difference between the two constitutes Angular’s change detection.
Pure pipes update automatically whenever the value of its derived input changes. The pipe will re-execute to produce new output upon a detectable change in the input value. Detectable changes are determined by Angular’s change detection loop.
Impure pipes update automatically whenever a change detection cycle occurs. Angular’s change detection happens quite often. It signals if changes have occurred in the component class’ member data. If so, the template HTML updates with the updated data. Otherwise, nothing will happen.
In the case of an impure pipe, it will update regardless of whether there is a detectable change or not. An impure pipe updates whenever change detection loops. Impure pipes usually consume lots of resources and are generally ill-advised. That said, they operate more as an escape hatch. If you ever need a detection-sensitive pipe, toggle `pure: false` in the `@Pipe` decorator’s metadata.
#### Conclusion
That covers pipes. Pipes have plenty of potential beyond the scope of this article. Pipes contribute succinct data transformations to your components’ template HTML. They are good practice in situations where data must undergo small transformations.
## Sources
1. [Wiki Community. *ISO 8601*. Wikipedia. Accessed 27 May 2018](https://en.wikipedia.org/wiki/ISO_8601)
## Resources
- [Angular Documentation](https://angular.io/guide/pipes)
- [Angular GitHub Repository](https://github.com/angular/angular)
- [List of Pipes Pre-packaged with Angular](https://angular.io/api?query=pipe)
- [Angular CLI](https://cli.angular.io)
|
otavioarc/freeCodeCamp
|
guide/english/angular/pipes/index.md
|
Markdown
|
bsd-3-clause
| 7,979 | 48.173913 | 390 | 0.755968 | false |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Form
*/
namespace Zend\Form\Annotation;
/**
* Filter annotation
*
* Expects an associative array defining the filter. Typically, this includes
* the "name" with an associated string value indicating the filter name or
* class, and optionally an "options" key with an object/associative array value
* of options to pass to the filter constructor.
*
* This annotation may be specified multiple times; filters will be added
* to the filter chain in the order specified.
*
* @Annotation
* @package Zend_Form
* @subpackage Annotation
*/
class Filter extends AbstractArrayAnnotation
{
/**
* Retrieve the filter specification
*
* @return null|array
*/
public function getFilter()
{
return $this->value;
}
}
|
rvdpol/gh18
|
vendor/zendframework/zendframework/library/Zend/Form/Annotation/Filter.php
|
PHP
|
bsd-3-clause
| 1,128 | 26.923077 | 86 | 0.672872 | false |
/*
* Copyright (c) 2013-2016, Wind River Systems, Inc.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3) Neither the name of Wind River Systems nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "guest_heartbeat_event_script.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "guest_types.h"
#include "guest_debug.h"
#include "guest_script.h"
#include "guest_heartbeat_types.h"
static GuestScriptIdT _script_id = GUEST_SCRIPT_ID_INVALID;
static GuestHeartbeatEventT _event;
static GuestHeartbeatNotifyT _notify;
static GuestHeartbeatEventScriptCallbackT _callback = NULL;
// ****************************************************************************
// Guest Heartbeat Event Script - Event Argument
// =============================================
const char* guest_heartbeat_event_script_event_arg( GuestHeartbeatEventT event )
{
switch (event)
{
case GUEST_HEARTBEAT_EVENT_STOP: return "stop";
case GUEST_HEARTBEAT_EVENT_REBOOT: return "reboot";
case GUEST_HEARTBEAT_EVENT_SUSPEND: return "suspend";
case GUEST_HEARTBEAT_EVENT_PAUSE: return "pause";
case GUEST_HEARTBEAT_EVENT_UNPAUSE: return "unpause";
case GUEST_HEARTBEAT_EVENT_RESUME: return "resume";
case GUEST_HEARTBEAT_EVENT_RESIZE_BEGIN: return "resize_begin";
case GUEST_HEARTBEAT_EVENT_RESIZE_END: return "resize_end";
case GUEST_HEARTBEAT_EVENT_LIVE_MIGRATE_BEGIN: return "live_migrate_begin";
case GUEST_HEARTBEAT_EVENT_LIVE_MIGRATE_END: return "live_migrate_end";
case GUEST_HEARTBEAT_EVENT_COLD_MIGRATE_BEGIN: return "cold_migrate_begin";
case GUEST_HEARTBEAT_EVENT_COLD_MIGRATE_END: return "cold_migrate_end";
default:
return NULL;
}
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Notify Argument
// ==============================================
const char* guest_heartbeat_event_script_notify_arg( GuestHeartbeatNotifyT notify )
{
switch (notify)
{
case GUEST_HEARTBEAT_NOTIFY_REVOCABLE: return "revocable";
case GUEST_HEARTBEAT_NOTIFY_IRREVOCABLE: return "irrevocable";
default:
return NULL;
}
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Abort
// ====================================
void guest_heartbeat_event_script_abort( void )
{
if (GUEST_SCRIPT_ID_INVALID != _script_id)
{
DPRINTFI("Aborting event script for event %s, notification=%s, "
"script_id=%i.", guest_heartbeat_event_str(_event),
guest_heartbeat_notify_str(_notify), _script_id);
guest_script_abort(_script_id);
_script_id = GUEST_SCRIPT_ID_INVALID;
}
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Callback
// =======================================
static void guest_heartbeat_event_script_callback(
GuestScriptIdT script_id, int exit_code, char* log_msg )
{
GuestHeartbeatVoteResultT vote_result;
if (script_id == _script_id)
{
switch (exit_code)
{
case 0:
vote_result = GUEST_HEARTBEAT_VOTE_RESULT_ACCEPT;
break;
case 1:
vote_result = GUEST_HEARTBEAT_VOTE_RESULT_REJECT;
break;
default:
vote_result = GUEST_HEARTBEAT_VOTE_RESULT_ERROR;
break;
}
if (NULL != _callback)
_callback(_event, _notify, vote_result, log_msg);
_script_id = GUEST_SCRIPT_ID_INVALID;
}
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Invoke
// =====================================
GuestErrorT guest_heartbeat_event_script_invoke(
char script[], GuestHeartbeatEventT event, GuestHeartbeatNotifyT notify,
GuestHeartbeatEventScriptCallbackT callback)
{
const char* event_arg = guest_heartbeat_event_script_event_arg(event);
const char* notify_arg = guest_heartbeat_event_script_notify_arg(notify);
const char* script_argv[] = {script, notify_arg, event_arg, NULL};
GuestErrorT error;
_event = event;
_notify = notify;
_callback = callback;
if (NULL == event_arg)
{
DPRINTFE("Event argument invalid, event=%s.",
guest_heartbeat_event_str(event));
return GUEST_FAILED;
}
if (NULL == notify_arg)
{
DPRINTFE("Notify argument invalid, event=%s.",
guest_heartbeat_notify_str(notify));
return GUEST_FAILED;
}
error = guest_script_invoke(script, (char**) script_argv,
guest_heartbeat_event_script_callback,
&_script_id);
if (GUEST_OKAY != error)
{
DPRINTFE("Failed to invoke script %s, error=%s.", script,
guest_error_str(error));
return error;
}
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Initialize
// =========================================
GuestErrorT guest_heartbeat_event_script_initialize( void )
{
_script_id = GUEST_SCRIPT_ID_INVALID;
return GUEST_OKAY;
}
// ****************************************************************************
// ****************************************************************************
// Guest Heartbeat Event Script - Finalize
// =======================================
GuestErrorT guest_heartbeat_event_script_finalize( void )
{
guest_heartbeat_event_script_abort();
_script_id = GUEST_SCRIPT_ID_INVALID;
return GUEST_OKAY;
}
// ****************************************************************************
|
Wind-River/titanium-server
|
guest-API-SDK/17.06/wrs-guest-heartbeat-3.0.1/guest_client/src/heartbeat/guest_heartbeat_event_script.c
|
C
|
bsd-3-clause
| 7,924 | 37.843137 | 87 | 0.545558 | false |
/*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the necessary hooks for mbedTLS.
*/
#include "dtls.hpp"
#include <mbedtls/debug.h>
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#include <mbedtls/pem.h>
#endif
#include <openthread/platform/radio.h>
#include "common/as_core_type.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
#include "common/locator_getters.hpp"
#include "common/log.hpp"
#include "common/timer.hpp"
#include "crypto/mbedtls.hpp"
#include "crypto/sha256.hpp"
#include "thread/thread_netif.hpp"
#if OPENTHREAD_CONFIG_DTLS_ENABLE
namespace ot {
namespace MeshCoP {
RegisterLogModule("Dtls");
#if (MBEDTLS_VERSION_NUMBER >= 0x03010000)
const uint16_t Dtls::sGroups[] = {MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1, MBEDTLS_SSL_IANA_TLS_GROUP_NONE};
#else
const mbedtls_ecp_group_id Dtls::sCurves[] = {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE};
#endif
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) || defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
const int Dtls::sHashes[] = {MBEDTLS_MD_SHA256, MBEDTLS_MD_NONE};
#endif
Dtls::Dtls(Instance &aInstance, bool aLayerTwoSecurity)
: InstanceLocator(aInstance)
, mState(kStateClosed)
, mPskLength(0)
, mVerifyPeerCertificate(true)
, mTimer(aInstance, Dtls::HandleTimer, this)
, mTimerIntermediate(0)
, mTimerSet(false)
, mLayerTwoSecurity(aLayerTwoSecurity)
, mReceiveMessage(nullptr)
, mConnectedHandler(nullptr)
, mReceiveHandler(nullptr)
, mContext(nullptr)
, mSocket(aInstance)
, mTransportCallback(nullptr)
, mTransportContext(nullptr)
, mMessageSubType(Message::kSubTypeNone)
, mMessageDefaultSubType(Message::kSubTypeNone)
{
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
#ifdef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
mPreSharedKey = nullptr;
mPreSharedKeyIdentity = nullptr;
mPreSharedKeyIdLength = 0;
mPreSharedKeyLength = 0;
#endif
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
mCaChainSrc = nullptr;
mCaChainLength = 0;
mOwnCertSrc = nullptr;
mOwnCertLength = 0;
mPrivateKeySrc = nullptr;
mPrivateKeyLength = 0;
memset(&mCaChain, 0, sizeof(mCaChain));
memset(&mOwnCert, 0, sizeof(mOwnCert));
memset(&mPrivateKey, 0, sizeof(mPrivateKey));
#endif
#endif
memset(mCipherSuites, 0, sizeof(mCipherSuites));
memset(mPsk, 0, sizeof(mPsk));
memset(&mSsl, 0, sizeof(mSsl));
memset(&mConf, 0, sizeof(mConf));
#ifdef MBEDTLS_SSL_COOKIE_C
memset(&mCookieCtx, 0, sizeof(mCookieCtx));
#endif
}
void Dtls::FreeMbedtls(void)
{
#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_COOKIE_C)
mbedtls_ssl_cookie_free(&mCookieCtx);
#endif
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
mbedtls_x509_crt_free(&mCaChain);
mbedtls_x509_crt_free(&mOwnCert);
mbedtls_pk_free(&mPrivateKey);
#endif
#endif
mbedtls_ssl_config_free(&mConf);
mbedtls_ssl_free(&mSsl);
}
Error Dtls::Open(ReceiveHandler aReceiveHandler, ConnectedHandler aConnectedHandler, void *aContext)
{
Error error;
VerifyOrExit(mState == kStateClosed, error = kErrorAlready);
SuccessOrExit(error = mSocket.Open(&Dtls::HandleUdpReceive, this));
mReceiveHandler = aReceiveHandler;
mConnectedHandler = aConnectedHandler;
mContext = aContext;
mState = kStateOpen;
exit:
return error;
}
Error Dtls::Connect(const Ip6::SockAddr &aSockAddr)
{
Error error;
VerifyOrExit(mState == kStateOpen, error = kErrorInvalidState);
mMessageInfo.SetPeerAddr(aSockAddr.GetAddress());
mMessageInfo.SetPeerPort(aSockAddr.mPort);
error = Setup(true);
exit:
return error;
}
void Dtls::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
static_cast<Dtls *>(aContext)->HandleUdpReceive(AsCoreType(aMessage), AsCoreType(aMessageInfo));
}
void Dtls::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
switch (mState)
{
case MeshCoP::Dtls::kStateClosed:
ExitNow();
case MeshCoP::Dtls::kStateOpen:
IgnoreError(mSocket.Connect(Ip6::SockAddr(aMessageInfo.GetPeerAddr(), aMessageInfo.GetPeerPort())));
mMessageInfo.SetPeerAddr(aMessageInfo.GetPeerAddr());
mMessageInfo.SetPeerPort(aMessageInfo.GetPeerPort());
mMessageInfo.SetIsHostInterface(aMessageInfo.IsHostInterface());
if (Get<ThreadNetif>().HasUnicastAddress(aMessageInfo.GetSockAddr()))
{
mMessageInfo.SetSockAddr(aMessageInfo.GetSockAddr());
}
mMessageInfo.SetSockPort(aMessageInfo.GetSockPort());
SuccessOrExit(Setup(false));
break;
default:
// Once DTLS session is started, communicate only with a peer.
VerifyOrExit((mMessageInfo.GetPeerAddr() == aMessageInfo.GetPeerAddr()) &&
(mMessageInfo.GetPeerPort() == aMessageInfo.GetPeerPort()));
break;
}
#ifdef MBEDTLS_SSL_SRV_C
if (mState == MeshCoP::Dtls::kStateConnecting)
{
IgnoreError(SetClientId(mMessageInfo.GetPeerAddr().mFields.m8, sizeof(mMessageInfo.GetPeerAddr().mFields)));
}
#endif
Receive(aMessage);
exit:
return;
}
uint16_t Dtls::GetUdpPort(void) const
{
return mSocket.GetSockName().GetPort();
}
Error Dtls::Bind(uint16_t aPort)
{
Error error;
VerifyOrExit(mState == kStateOpen, error = kErrorInvalidState);
VerifyOrExit(mTransportCallback == nullptr, error = kErrorAlready);
SuccessOrExit(error = mSocket.Bind(aPort, OT_NETIF_UNSPECIFIED));
exit:
return error;
}
Error Dtls::Bind(TransportCallback aCallback, void *aContext)
{
Error error = kErrorNone;
VerifyOrExit(mState == kStateOpen, error = kErrorInvalidState);
VerifyOrExit(!mSocket.IsBound(), error = kErrorAlready);
VerifyOrExit(mTransportCallback == nullptr, error = kErrorAlready);
mTransportCallback = aCallback;
mTransportContext = aContext;
exit:
return error;
}
Error Dtls::Setup(bool aClient)
{
int rval;
// do not handle new connection before guard time expired
VerifyOrExit(mState == kStateOpen, rval = MBEDTLS_ERR_SSL_TIMEOUT);
mState = kStateInitializing;
mbedtls_ssl_init(&mSsl);
mbedtls_ssl_config_init(&mConf);
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
mbedtls_x509_crt_init(&mCaChain);
mbedtls_x509_crt_init(&mOwnCert);
mbedtls_pk_init(&mPrivateKey);
#endif
#endif
#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_COOKIE_C)
mbedtls_ssl_cookie_init(&mCookieCtx);
#endif
rval = mbedtls_ssl_config_defaults(&mConf, aClient ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_PRESET_DEFAULT);
VerifyOrExit(rval == 0);
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
if (mVerifyPeerCertificate && mCipherSuites[0] == MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8)
{
mbedtls_ssl_conf_authmode(&mConf, MBEDTLS_SSL_VERIFY_REQUIRED);
}
else
{
mbedtls_ssl_conf_authmode(&mConf, MBEDTLS_SSL_VERIFY_NONE);
}
#else
OT_UNUSED_VARIABLE(mVerifyPeerCertificate);
#endif
mbedtls_ssl_conf_rng(&mConf, Crypto::MbedTls::CryptoSecurePrng, nullptr);
mbedtls_ssl_conf_min_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_max_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
OT_ASSERT(mCipherSuites[1] == 0);
mbedtls_ssl_conf_ciphersuites(&mConf, mCipherSuites);
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
#if (MBEDTLS_VERSION_NUMBER >= 0x03010000)
mbedtls_ssl_conf_groups(&mConf, sGroups);
#else
mbedtls_ssl_conf_curves(&mConf, sCurves);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) || defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
mbedtls_ssl_conf_sig_hashes(&mConf, sHashes);
#endif
}
#if (MBEDTLS_VERSION_NUMBER >= 0x03000000)
mbedtls_ssl_set_export_keys_cb(&mSsl, HandleMbedtlsExportKeys, this);
#else
mbedtls_ssl_conf_export_keys_cb(&mConf, HandleMbedtlsExportKeys, this);
#endif
mbedtls_ssl_conf_handshake_timeout(&mConf, 8000, 60000);
mbedtls_ssl_conf_dbg(&mConf, HandleMbedtlsDebug, this);
#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_COOKIE_C)
if (!aClient)
{
rval = mbedtls_ssl_cookie_setup(&mCookieCtx, Crypto::MbedTls::CryptoSecurePrng, nullptr);
VerifyOrExit(rval == 0);
mbedtls_ssl_conf_dtls_cookies(&mConf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &mCookieCtx);
}
#endif
rval = mbedtls_ssl_setup(&mSsl, &mConf);
VerifyOrExit(rval == 0);
mbedtls_ssl_set_bio(&mSsl, this, &Dtls::HandleMbedtlsTransmit, HandleMbedtlsReceive, nullptr);
mbedtls_ssl_set_timer_cb(&mSsl, this, &Dtls::HandleMbedtlsSetTimer, HandleMbedtlsGetTimer);
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
rval = mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength);
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
rval = SetApplicationCoapSecureKeys();
}
#endif
VerifyOrExit(rval == 0);
mReceiveMessage = nullptr;
mMessageSubType = Message::kSubTypeNone;
mState = kStateConnecting;
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
LogInfo("DTLS started");
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
LogInfo("Application Coap Secure DTLS started");
}
#endif
mState = kStateConnecting;
Process();
exit:
if ((mState == kStateInitializing) && (rval != 0))
{
mState = kStateOpen;
FreeMbedtls();
}
return Crypto::MbedTls::MapError(rval);
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
int Dtls::SetApplicationCoapSecureKeys(void)
{
int rval = 0;
switch (mCipherSuites[0])
{
case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
if (mCaChainSrc != nullptr)
{
rval = mbedtls_x509_crt_parse(&mCaChain, static_cast<const unsigned char *>(mCaChainSrc),
static_cast<size_t>(mCaChainLength));
VerifyOrExit(rval == 0);
mbedtls_ssl_conf_ca_chain(&mConf, &mCaChain, nullptr);
}
if (mOwnCertSrc != nullptr && mPrivateKeySrc != nullptr)
{
rval = mbedtls_x509_crt_parse(&mOwnCert, static_cast<const unsigned char *>(mOwnCertSrc),
static_cast<size_t>(mOwnCertLength));
VerifyOrExit(rval == 0);
#if (MBEDTLS_VERSION_NUMBER >= 0x03000000)
rval = mbedtls_pk_parse_key(&mPrivateKey, static_cast<const unsigned char *>(mPrivateKeySrc),
static_cast<size_t>(mPrivateKeyLength), nullptr, 0,
Crypto::MbedTls::CryptoSecurePrng, nullptr);
#else
rval = mbedtls_pk_parse_key(&mPrivateKey, static_cast<const unsigned char *>(mPrivateKeySrc),
static_cast<size_t>(mPrivateKeyLength), nullptr, 0);
#endif
VerifyOrExit(rval == 0);
rval = mbedtls_ssl_conf_own_cert(&mConf, &mOwnCert, &mPrivateKey);
VerifyOrExit(rval == 0);
}
#endif
break;
case MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8:
#ifdef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
rval = mbedtls_ssl_conf_psk(&mConf, static_cast<const unsigned char *>(mPreSharedKey), mPreSharedKeyLength,
static_cast<const unsigned char *>(mPreSharedKeyIdentity), mPreSharedKeyIdLength);
VerifyOrExit(rval == 0);
#endif
break;
default:
LogCrit("Application Coap Secure: Not supported cipher.");
rval = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
ExitNow();
break;
}
exit:
return rval;
}
#endif // OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
void Dtls::Close(void)
{
Disconnect();
mState = kStateClosed;
mTransportCallback = nullptr;
mTransportContext = nullptr;
mTimerSet = false;
IgnoreError(mSocket.Close());
mTimer.Stop();
}
void Dtls::Disconnect(void)
{
VerifyOrExit(mState == kStateConnecting || mState == kStateConnected);
mbedtls_ssl_close_notify(&mSsl);
mState = kStateCloseNotify;
mTimer.Start(kGuardTimeNewConnectionMilli);
mMessageInfo.Clear();
IgnoreError(mSocket.Connect());
FreeMbedtls();
exit:
return;
}
Error Dtls::SetPsk(const uint8_t *aPsk, uint8_t aPskLength)
{
Error error = kErrorNone;
VerifyOrExit(aPskLength <= sizeof(mPsk), error = kErrorInvalidArgs);
memcpy(mPsk, aPsk, aPskLength);
mPskLength = aPskLength;
mCipherSuites[0] = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8;
mCipherSuites[1] = 0;
exit:
return error;
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
void Dtls::SetCertificate(const uint8_t *aX509Certificate,
uint32_t aX509CertLength,
const uint8_t *aPrivateKey,
uint32_t aPrivateKeyLength)
{
OT_ASSERT(aX509CertLength > 0);
OT_ASSERT(aX509Certificate != nullptr);
OT_ASSERT(aPrivateKeyLength > 0);
OT_ASSERT(aPrivateKey != nullptr);
mOwnCertSrc = aX509Certificate;
mOwnCertLength = aX509CertLength;
mPrivateKeySrc = aPrivateKey;
mPrivateKeyLength = aPrivateKeyLength;
mCipherSuites[0] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
mCipherSuites[1] = 0;
}
void Dtls::SetCaCertificateChain(const uint8_t *aX509CaCertificateChain, uint32_t aX509CaCertChainLength)
{
OT_ASSERT(aX509CaCertChainLength > 0);
OT_ASSERT(aX509CaCertificateChain != nullptr);
mCaChainSrc = aX509CaCertificateChain;
mCaChainLength = aX509CaCertChainLength;
}
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#ifdef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
void Dtls::SetPreSharedKey(const uint8_t *aPsk, uint16_t aPskLength, const uint8_t *aPskIdentity, uint16_t aPskIdLength)
{
OT_ASSERT(aPsk != nullptr);
OT_ASSERT(aPskIdentity != nullptr);
OT_ASSERT(aPskLength > 0);
OT_ASSERT(aPskIdLength > 0);
mPreSharedKey = aPsk;
mPreSharedKeyLength = aPskLength;
mPreSharedKeyIdentity = aPskIdentity;
mPreSharedKeyIdLength = aPskIdLength;
mCipherSuites[0] = MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8;
mCipherSuites[1] = 0;
}
#endif
#if defined(MBEDTLS_BASE64_C) && defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
Error Dtls::GetPeerCertificateBase64(unsigned char *aPeerCert, size_t *aCertLength, size_t aCertBufferSize)
{
Error error = kErrorNone;
VerifyOrExit(mState == kStateConnected, error = kErrorInvalidState);
#if (MBEDTLS_VERSION_NUMBER >= 0x03010000)
VerifyOrExit(mbedtls_base64_encode(aPeerCert, aCertBufferSize, aCertLength,
mSsl.MBEDTLS_PRIVATE(session)->MBEDTLS_PRIVATE(peer_cert)->raw.p,
mSsl.MBEDTLS_PRIVATE(session)->MBEDTLS_PRIVATE(peer_cert)->raw.len) == 0,
error = kErrorNoBufs);
#else
VerifyOrExit(
mbedtls_base64_encode(
aPeerCert, aCertBufferSize, aCertLength,
mSsl.MBEDTLS_PRIVATE(session)->MBEDTLS_PRIVATE(peer_cert)->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p),
mSsl.MBEDTLS_PRIVATE(session)->MBEDTLS_PRIVATE(peer_cert)->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len)) == 0,
error = kErrorNoBufs);
#endif
exit:
return error;
}
#endif // defined(MBEDTLS_BASE64_C) && defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
#endif // OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
#ifdef MBEDTLS_SSL_SRV_C
Error Dtls::SetClientId(const uint8_t *aClientId, uint8_t aLength)
{
int rval = mbedtls_ssl_set_client_transport_id(&mSsl, aClientId, aLength);
return Crypto::MbedTls::MapError(rval);
}
#endif
Error Dtls::Send(Message &aMessage, uint16_t aLength)
{
Error error = kErrorNone;
uint8_t buffer[kApplicationDataMaxLength];
VerifyOrExit(aLength <= kApplicationDataMaxLength, error = kErrorNoBufs);
// Store message specific sub type.
if (aMessage.GetSubType() != Message::kSubTypeNone)
{
mMessageSubType = aMessage.GetSubType();
}
aMessage.ReadBytes(0, buffer, aLength);
SuccessOrExit(error = Crypto::MbedTls::MapError(mbedtls_ssl_write(&mSsl, buffer, aLength)));
aMessage.Free();
exit:
return error;
}
void Dtls::Receive(Message &aMessage)
{
mReceiveMessage = &aMessage;
Process();
mReceiveMessage = nullptr;
}
int Dtls::HandleMbedtlsTransmit(void *aContext, const unsigned char *aBuf, size_t aLength)
{
return static_cast<Dtls *>(aContext)->HandleMbedtlsTransmit(aBuf, aLength);
}
int Dtls::HandleMbedtlsTransmit(const unsigned char *aBuf, size_t aLength)
{
Error error;
int rval = 0;
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
LogDebg("HandleMbedtlsTransmit");
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
LogDebg("ApplicationCoapSecure HandleMbedtlsTransmit");
}
#endif
error = HandleDtlsSend(aBuf, static_cast<uint16_t>(aLength), mMessageSubType);
// Restore default sub type.
mMessageSubType = mMessageDefaultSubType;
switch (error)
{
case kErrorNone:
rval = static_cast<int>(aLength);
break;
case kErrorNoBufs:
rval = MBEDTLS_ERR_SSL_WANT_WRITE;
break;
default:
LogWarn("HandleMbedtlsTransmit: %s error", ErrorToString(error));
rval = MBEDTLS_ERR_NET_SEND_FAILED;
break;
}
return rval;
}
int Dtls::HandleMbedtlsReceive(void *aContext, unsigned char *aBuf, size_t aLength)
{
return static_cast<Dtls *>(aContext)->HandleMbedtlsReceive(aBuf, aLength);
}
int Dtls::HandleMbedtlsReceive(unsigned char *aBuf, size_t aLength)
{
int rval;
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
LogDebg("HandleMbedtlsReceive");
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
LogDebg("ApplicationCoapSecure HandleMbedtlsReceive");
}
#endif
VerifyOrExit(mReceiveMessage != nullptr && (rval = mReceiveMessage->GetLength() - mReceiveMessage->GetOffset()) > 0,
rval = MBEDTLS_ERR_SSL_WANT_READ);
if (aLength > static_cast<size_t>(rval))
{
aLength = static_cast<size_t>(rval);
}
rval = mReceiveMessage->ReadBytes(mReceiveMessage->GetOffset(), aBuf, static_cast<uint16_t>(aLength));
mReceiveMessage->MoveOffset(rval);
exit:
return rval;
}
int Dtls::HandleMbedtlsGetTimer(void *aContext)
{
return static_cast<Dtls *>(aContext)->HandleMbedtlsGetTimer();
}
int Dtls::HandleMbedtlsGetTimer(void)
{
int rval;
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
LogDebg("HandleMbedtlsGetTimer");
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
LogDebg("ApplicationCoapSecure HandleMbedtlsGetTimer");
}
#endif
if (!mTimerSet)
{
rval = -1;
}
else if (!mTimer.IsRunning())
{
rval = 2;
}
else if (mTimerIntermediate <= TimerMilli::GetNow())
{
rval = 1;
}
else
{
rval = 0;
}
return rval;
}
void Dtls::HandleMbedtlsSetTimer(void *aContext, uint32_t aIntermediate, uint32_t aFinish)
{
static_cast<Dtls *>(aContext)->HandleMbedtlsSetTimer(aIntermediate, aFinish);
}
void Dtls::HandleMbedtlsSetTimer(uint32_t aIntermediate, uint32_t aFinish)
{
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
LogDebg("SetTimer");
}
#if OPENTHREAD_CONFIG_COAP_SECURE_API_ENABLE
else
{
LogDebg("ApplicationCoapSecure SetTimer");
}
#endif
if (aFinish == 0)
{
mTimerSet = false;
mTimer.Stop();
}
else
{
mTimerSet = true;
mTimer.Start(aFinish);
mTimerIntermediate = TimerMilli::GetNow() + aIntermediate;
}
}
#if (MBEDTLS_VERSION_NUMBER >= 0x03000000)
void Dtls::HandleMbedtlsExportKeys(void * aContext,
mbedtls_ssl_key_export_type aType,
const unsigned char * aMasterSecret,
size_t aMasterSecretLen,
const unsigned char aClientRandom[32],
const unsigned char aServerRandom[32],
mbedtls_tls_prf_types aTlsPrfType)
{
static_cast<Dtls *>(aContext)->HandleMbedtlsExportKeys(aType, aMasterSecret, aMasterSecretLen, aClientRandom,
aServerRandom, aTlsPrfType);
}
void Dtls::HandleMbedtlsExportKeys(mbedtls_ssl_key_export_type aType,
const unsigned char * aMasterSecret,
size_t aMasterSecretLen,
const unsigned char aClientRandom[32],
const unsigned char aServerRandom[32],
mbedtls_tls_prf_types aTlsPrfType)
{
Crypto::Sha256::Hash kek;
Crypto::Sha256 sha256;
unsigned char keyBlock[kDtlsKeyBlockSize];
unsigned char randBytes[2 * kDtlsRandomBufferSize];
VerifyOrExit(mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8);
VerifyOrExit(aType == MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET);
memcpy(randBytes, aServerRandom, kDtlsRandomBufferSize);
memcpy(randBytes + kDtlsRandomBufferSize, aClientRandom, kDtlsRandomBufferSize);
// Retrieve the Key block from Master secret
mbedtls_ssl_tls_prf(aTlsPrfType, aMasterSecret, aMasterSecretLen, "key expansion", randBytes, sizeof(randBytes),
keyBlock, sizeof(keyBlock));
sha256.Start();
sha256.Update(keyBlock, kDtlsKeyBlockSize);
sha256.Finish(kek);
LogDebg("Generated KEK");
Get<KeyManager>().SetKek(kek.GetBytes());
exit:
return;
}
#else
int Dtls::HandleMbedtlsExportKeys(void * aContext,
const unsigned char *aMasterSecret,
const unsigned char *aKeyBlock,
size_t aMacLength,
size_t aKeyLength,
size_t aIvLength)
{
return static_cast<Dtls *>(aContext)->HandleMbedtlsExportKeys(aMasterSecret, aKeyBlock, aMacLength, aKeyLength,
aIvLength);
}
int Dtls::HandleMbedtlsExportKeys(const unsigned char *aMasterSecret,
const unsigned char *aKeyBlock,
size_t aMacLength,
size_t aKeyLength,
size_t aIvLength)
{
OT_UNUSED_VARIABLE(aMasterSecret);
Crypto::Sha256::Hash kek;
Crypto::Sha256 sha256;
VerifyOrExit(mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8);
sha256.Start();
sha256.Update(aKeyBlock, 2 * static_cast<uint16_t>(aMacLength + aKeyLength + aIvLength));
sha256.Finish(kek);
LogDebg("Generated KEK");
Get<KeyManager>().SetKek(kek.GetBytes());
exit:
return 0;
}
#endif // (MBEDTLS_VERSION_NUMBER >= 0x03000000)
void Dtls::HandleTimer(Timer &aTimer)
{
static_cast<Dtls *>(static_cast<TimerMilliContext &>(aTimer).GetContext())->HandleTimer();
}
void Dtls::HandleTimer(void)
{
switch (mState)
{
case kStateConnecting:
case kStateConnected:
Process();
break;
case kStateCloseNotify:
mState = kStateOpen;
mTimer.Stop();
if (mConnectedHandler != nullptr)
{
mConnectedHandler(mContext, false);
}
break;
default:
OT_ASSERT(false);
OT_UNREACHABLE_CODE(break);
}
}
void Dtls::Process(void)
{
uint8_t buf[OPENTHREAD_CONFIG_DTLS_MAX_CONTENT_LEN];
bool shouldDisconnect = false;
int rval;
while ((mState == kStateConnecting) || (mState == kStateConnected))
{
if (mState == kStateConnecting)
{
rval = mbedtls_ssl_handshake(&mSsl);
if (mSsl.MBEDTLS_PRIVATE(state) == MBEDTLS_SSL_HANDSHAKE_OVER)
{
mState = kStateConnected;
if (mConnectedHandler != nullptr)
{
mConnectedHandler(mContext, true);
}
}
}
else
{
rval = mbedtls_ssl_read(&mSsl, buf, sizeof(buf));
}
if (rval > 0)
{
if (mReceiveHandler != nullptr)
{
mReceiveHandler(mContext, buf, static_cast<uint16_t>(rval));
}
}
else if (rval == 0 || rval == MBEDTLS_ERR_SSL_WANT_READ || rval == MBEDTLS_ERR_SSL_WANT_WRITE)
{
break;
}
else
{
switch (rval)
{
case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
mbedtls_ssl_close_notify(&mSsl);
ExitNow(shouldDisconnect = true);
OT_UNREACHABLE_CODE(break);
case MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED:
break;
case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
mbedtls_ssl_close_notify(&mSsl);
ExitNow(shouldDisconnect = true);
OT_UNREACHABLE_CODE(break);
case MBEDTLS_ERR_SSL_INVALID_MAC:
if (mSsl.MBEDTLS_PRIVATE(state) != MBEDTLS_SSL_HANDSHAKE_OVER)
{
mbedtls_ssl_send_alert_message(&mSsl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC);
ExitNow(shouldDisconnect = true);
}
break;
default:
if (mSsl.MBEDTLS_PRIVATE(state) != MBEDTLS_SSL_HANDSHAKE_OVER)
{
mbedtls_ssl_send_alert_message(&mSsl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
ExitNow(shouldDisconnect = true);
}
break;
}
mbedtls_ssl_session_reset(&mSsl);
if (mCipherSuites[0] == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
{
mbedtls_ssl_set_hs_ecjpake_password(&mSsl, mPsk, mPskLength);
}
break;
}
}
exit:
if (shouldDisconnect)
{
Disconnect();
}
}
void Dtls::HandleMbedtlsDebug(void *aContext, int aLevel, const char *aFile, int aLine, const char *aStr)
{
static_cast<Dtls *>(aContext)->HandleMbedtlsDebug(aLevel, aFile, aLine, aStr);
}
void Dtls::HandleMbedtlsDebug(int aLevel, const char *aFile, int aLine, const char *aStr)
{
OT_UNUSED_VARIABLE(aStr);
OT_UNUSED_VARIABLE(aFile);
OT_UNUSED_VARIABLE(aLine);
switch (aLevel)
{
case 1:
LogCrit("[%hu] %s", mSocket.GetSockName().mPort, aStr);
break;
case 2:
LogWarn("[%hu] %s", mSocket.GetSockName().mPort, aStr);
break;
case 3:
LogInfo("[%hu] %s", mSocket.GetSockName().mPort, aStr);
break;
case 4:
default:
LogDebg("[%hu] %s", mSocket.GetSockName().mPort, aStr);
break;
}
}
Error Dtls::HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, Message::SubType aMessageSubType)
{
Error error = kErrorNone;
ot::Message *message = nullptr;
VerifyOrExit((message = mSocket.NewMessage(0)) != nullptr, error = kErrorNoBufs);
message->SetSubType(aMessageSubType);
message->SetLinkSecurityEnabled(mLayerTwoSecurity);
SuccessOrExit(error = message->AppendBytes(aBuf, aLength));
// Set message sub type in case Joiner Finalize Response is appended to the message.
if (aMessageSubType != Message::kSubTypeNone)
{
message->SetSubType(aMessageSubType);
}
if (mTransportCallback)
{
SuccessOrExit(error = mTransportCallback(mTransportContext, *message, mMessageInfo));
}
else
{
SuccessOrExit(error = mSocket.SendTo(*message, mMessageInfo));
}
exit:
FreeMessageOnError(message, error);
return error;
}
} // namespace MeshCoP
} // namespace ot
#endif // OPENTHREAD_CONFIG_DTLS_ENABLE
|
jwhui/openthread
|
src/core/meshcop/dtls.cpp
|
C++
|
bsd-3-clause
| 30,606 | 28.859512 | 120 | 0.63762 | false |
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkSGColorFilter.h"
#include "SkColorData.h"
#include "SkColorFilter.h"
#include "SkSGColor.h"
#include "SkTableColorFilter.h"
#include <cmath>
namespace sksg {
ColorFilter::ColorFilter(sk_sp<RenderNode> child)
: INHERITED(std::move(child)) {}
void ColorFilter::onRender(SkCanvas* canvas, const RenderContext* ctx) const {
const auto local_ctx = ScopedRenderContext(canvas, ctx).modulateColorFilter(fColorFilter);
this->INHERITED::onRender(canvas, local_ctx);
}
const RenderNode* ColorFilter::onNodeAt(const SkPoint& p) const {
// TODO: we likely need to do something more sophisticated than delegate to descendants here.
return this->INHERITED::onNodeAt(p);
}
SkRect ColorFilter::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
SkASSERT(this->hasInval());
fColorFilter = this->onRevalidateFilter();
return this->INHERITED::onRevalidate(ic, ctm);
}
sk_sp<ModeColorFilter> ModeColorFilter::Make(sk_sp<RenderNode> child, sk_sp<Color> color,
SkBlendMode mode) {
return (child && color) ? sk_sp<ModeColorFilter>(new ModeColorFilter(std::move(child),
std::move(color), mode))
: nullptr;
}
ModeColorFilter::ModeColorFilter(sk_sp<RenderNode> child, sk_sp<Color> color, SkBlendMode mode)
: INHERITED(std::move(child))
, fColor(std::move(color))
, fMode(mode) {
this->observeInval(fColor);
}
ModeColorFilter::~ModeColorFilter() {
this->unobserveInval(fColor);
}
sk_sp<SkColorFilter> ModeColorFilter::onRevalidateFilter() {
fColor->revalidate(nullptr, SkMatrix::I());
return SkColorFilter::MakeModeFilter(fColor->getColor(), fMode);
}
sk_sp<GradientColorFilter> GradientColorFilter::Make(sk_sp<RenderNode> child,
sk_sp<Color> c0, sk_sp<Color> c1) {
return Make(std::move(child), { std::move(c0), std::move(c1) });
}
sk_sp<GradientColorFilter> GradientColorFilter::Make(sk_sp<RenderNode> child,
std::vector<sk_sp<Color>> colors) {
return (child && colors.size() > 1)
? sk_sp<GradientColorFilter>(new GradientColorFilter(std::move(child), std::move(colors)))
: nullptr;
}
GradientColorFilter::GradientColorFilter(sk_sp<RenderNode> child, std::vector<sk_sp<Color>> colors)
: INHERITED(std::move(child))
, fColors(std::move(colors)) {
for (const auto& color : fColors) {
this->observeInval(color);
}
}
GradientColorFilter::~GradientColorFilter() {
for (const auto& color : fColors) {
this->unobserveInval(color);
}
}
namespace {
sk_sp<SkColorFilter> Make2ColorGradient(const sk_sp<Color>& color0, const sk_sp<Color>& color1) {
const auto c0 = SkColor4f::FromColor(color0->getColor()),
c1 = SkColor4f::FromColor(color1->getColor());
const auto dR = c1.fR - c0.fR,
dG = c1.fG - c0.fG,
dB = c1.fB - c0.fB;
// A 2-color gradient can be expressed as a color matrix (and combined with the luminance
// calculation). First, the luminance:
//
// L = [r,g,b] . [kR,kG,kB]
//
// We can compute it using a color matrix (result stored in R):
//
// | kR, kG, kB, 0, 0 | r' = L
// | 0, 0, 0, 0, 0 | g' = 0
// | 0, 0, 0, 0, 0 | b' = 0
// | 0, 0, 0, 1, 0 | a' = a
//
// Then we want to interpolate component-wise, based on L:
//
// r' = c0.r + (c1.r - c0.r) * L = c0.r + dR*L
// g' = c0.g + (c1.g - c0.g) * L = c0.g + dG*L
// b' = c0.b + (c1.b - c0.b) * L = c0.b + dB*L
// a' = a
//
// This can be expressed as another color matrix (when L is stored in R):
//
// | dR, 0, 0, 0, c0.r |
// | dG, 0, 0, 0, c0.g |
// | dB, 0, 0, 0, c0.b |
// | 0, 0, 0, 1, 0 |
//
// Composing these two, we get the total tint matrix:
const SkScalar tint_matrix[] = {
dR*SK_LUM_COEFF_R, dR*SK_LUM_COEFF_G, dR*SK_LUM_COEFF_B, 0, c0.fR * 255,
dG*SK_LUM_COEFF_R, dG*SK_LUM_COEFF_G, dG*SK_LUM_COEFF_B, 0, c0.fG * 255,
dB*SK_LUM_COEFF_R, dB*SK_LUM_COEFF_G, dB*SK_LUM_COEFF_B, 0, c0.fB * 255,
0, 0, 0, 1, 0,
};
return SkColorFilter::MakeMatrixFilterRowMajor255(tint_matrix);
}
sk_sp<SkColorFilter> MakeNColorGradient(const std::vector<sk_sp<Color>>& colors) {
// For N colors, we build a gradient color table.
uint8_t rTable[256], gTable[256], bTable[256];
SkASSERT(colors.size() > 2);
const auto span_count = colors.size() - 1;
size_t span_start = 0;
for (size_t i = 0; i < span_count; ++i) {
const auto span_stop = static_cast<size_t>(std::round((i + 1) * 255.0f / span_count)),
span_size = span_stop - span_start;
if (span_start > span_stop) {
// Degenerate case.
continue;
}
SkASSERT(span_stop <= 255);
// Fill the gradient in [span_start,span_stop] -> [c0,c1]
const SkColor c0 = colors[i ]->getColor(),
c1 = colors[i + 1]->getColor();
float r = SkColorGetR(c0),
g = SkColorGetG(c0),
b = SkColorGetB(c0);
const float dR = (SkColorGetR(c1) - r) / span_size,
dG = (SkColorGetG(c1) - g) / span_size,
dB = (SkColorGetB(c1) - b) / span_size;
for (size_t j = span_start; j <= span_stop; ++j) {
rTable[j] = static_cast<uint8_t>(std::round(r));
gTable[j] = static_cast<uint8_t>(std::round(g));
bTable[j] = static_cast<uint8_t>(std::round(b));
r += dR;
g += dG;
b += dB;
}
// Ensure we always advance.
span_start = span_stop + 1;
}
SkASSERT(span_start == 256);
const SkScalar luminance_matrix[] = {
SK_LUM_COEFF_R, SK_LUM_COEFF_G, SK_LUM_COEFF_B, 0, 0, // r' = L
SK_LUM_COEFF_R, SK_LUM_COEFF_G, SK_LUM_COEFF_B, 0, 0, // g' = L
SK_LUM_COEFF_R, SK_LUM_COEFF_G, SK_LUM_COEFF_B, 0, 0, // b' = L
0, 0, 0, 1, 0, // a' = a
};
return SkTableColorFilter::MakeARGB(nullptr, rTable, gTable, bTable)
->makeComposed(SkColorFilter::MakeMatrixFilterRowMajor255(luminance_matrix));
}
} // namespace
sk_sp<SkColorFilter> GradientColorFilter::onRevalidateFilter() {
for (const auto& color : fColors) {
color->revalidate(nullptr, SkMatrix::I());
}
if (fWeight <= 0) {
return nullptr;
}
SkASSERT(fColors.size() > 1);
auto gradientCF = (fColors.size() > 2) ? MakeNColorGradient(fColors)
: Make2ColorGradient(fColors[0], fColors[1]);
return SkColorFilter::MakeLerp(nullptr, std::move(gradientCF), fWeight);
}
} // namespace sksg
|
Hikari-no-Tenshi/android_external_skia
|
modules/sksg/src/SkSGColorFilter.cpp
|
C++
|
bsd-3-clause
| 7,194 | 33.586538 | 99 | 0.561301 | false |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
AlertIOS,
Platform,
ToastAndroid,
Text,
View,
} = ReactNative;
var TimerMixin = require('react-timer-mixin');
var UIExplorerButton = require('./UIExplorerButton');
var performanceNow = require('fbjs/lib/performanceNow');
function burnCPU(milliseconds) {
const start = performanceNow();
while (performanceNow() < (start + milliseconds)) {}
}
var RequestIdleCallbackTester = React.createClass({
_idleTimer: (null: any),
_iters: 0,
getInitialState() {
return {
message: '-',
};
},
componentWillUnmount() {
cancelIdleCallback(this._idleTimer);
},
render() {
return (
<View>
<UIExplorerButton onPress={this._run.bind(this, false)}>
Run requestIdleCallback
</UIExplorerButton>
<UIExplorerButton onPress={this._run.bind(this, true)}>
Burn CPU inside of requestIdleCallback
</UIExplorerButton>
<UIExplorerButton onPress={this._runBackground}>
Run background task
</UIExplorerButton>
<UIExplorerButton onPress={this._stopBackground}>
Stop background task
</UIExplorerButton>
<Text>{this.state.message}</Text>
</View>
);
},
_run(shouldBurnCPU) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = requestIdleCallback((deadline) => {
let message = '';
if (shouldBurnCPU) {
burnCPU(10);
message = 'Burned CPU for 10ms,';
}
this.setState({message: `${message} ${deadline.timeRemaining()}ms remaining in frame`});
});
},
_runBackground() {
cancelIdleCallback(this._idleTimer);
const handler = (deadline) => {
while (deadline.timeRemaining() > 5) {
burnCPU(5);
this.setState({message: `Burned CPU for 5ms ${this._iters++} times, ${deadline.timeRemaining()}ms remaining in frame`});
}
this._idleTimer = requestIdleCallback(handler);
};
this._idleTimer = requestIdleCallback(handler);
},
_stopBackground() {
this._iters = 0;
cancelIdleCallback(this._idleTimer);
}
});
var TimerTester = React.createClass({
mixins: [TimerMixin],
_ii: 0,
_iters: 0,
_start: 0,
_timerFn: (null : ?(() => any)),
_handle: (null : any),
render: function() {
var args = 'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : '');
return (
<UIExplorerButton onPress={this._run}>
Measure: {this.props.type}({args}) - {this._ii || 0}
</UIExplorerButton>
);
},
_run: function() {
if (!this._start) {
var d = new Date();
this._start = d.getTime();
this._iters = 100;
this._ii = 0;
if (this.props.type === 'setTimeout') {
if (this.props.dt < 1) {
this._iters = 5000;
} else if (this.props.dt > 20) {
this._iters = 10;
}
this._timerFn = () => this.setTimeout(this._run, this.props.dt);
} else if (this.props.type === 'requestAnimationFrame') {
this._timerFn = () => this.requestAnimationFrame(this._run);
} else if (this.props.type === 'setImmediate') {
this._iters = 5000;
this._timerFn = () => this.setImmediate(this._run);
} else if (this.props.type === 'setInterval') {
this._iters = 30; // Only used for forceUpdate periodicidy
this._timerFn = null;
this._handle = this.setInterval(this._run, this.props.dt);
}
}
if (this._ii >= this._iters && !this._handle) {
var d = new Date();
var e = (d.getTime() - this._start);
var msg = 'Finished ' + this._ii + ' ' + this.props.type + ' calls.\n' +
'Elapsed time: ' + e + ' ms\n' + (e / this._ii) + ' ms / iter';
console.log(msg);
if (Platform.OS === 'ios') {
AlertIOS.alert(msg);
} else if (Platform.OS === 'android') {
ToastAndroid.show(msg, ToastAndroid.SHORT);
}
this._start = 0;
this.forceUpdate(() => { this._ii = 0; });
return;
}
this._ii++;
// Only re-render occasionally so we don't slow down timers.
if (this._ii % (this._iters / 5) === 0) {
this.forceUpdate();
}
this._timerFn && this._timerFn();
},
clear: function() {
this.clearInterval(this._handle); // invalid handles are ignored
if (this._handle) {
// Configure things so we can do a final run to update UI and reset state.
this._handle = null;
this._iters = this._ii;
this._run();
}
},
});
exports.framework = 'React';
exports.title = 'Timers, TimerMixin';
exports.description = 'The TimerMixin provides timer functions for executing ' +
'code in the future that are safely cleaned up when the component unmounts.';
exports.examples = [
{
title: 'this.setTimeout(fn, t)',
description: 'Execute function fn t milliseconds in the future. If ' +
't === 0, it will be enqueued immediately in the next event loop. ' +
'Larger values will fire on the closest frame.',
render: function() {
return (
<View>
<TimerTester type="setTimeout" dt={0} />
<TimerTester type="setTimeout" dt={1} />
<TimerTester type="setTimeout" dt={100} />
</View>
);
},
},
{
title: 'this.requestAnimationFrame(fn)',
description: 'Execute function fn on the next frame.',
render: function() {
return (
<View>
<TimerTester type="requestAnimationFrame" />
</View>
);
},
},
{
title: 'this.requestIdleCallback(fn)',
description: 'Execute function fn on the next JS frame that has idle time',
render: function() {
return (
<View>
<RequestIdleCallbackTester />
</View>
);
},
},
{
title: 'this.setImmediate(fn)',
description: 'Execute function fn at the end of the current JS event loop.',
render: function() {
return (
<View>
<TimerTester type="setImmediate" />
</View>
);
},
},
{
title: 'this.setInterval(fn, t)',
description: 'Execute function fn every t milliseconds until cancelled ' +
'or component is unmounted.',
render: function(): ReactElement<any> {
var IntervalExample = React.createClass({
getInitialState: function() {
return {
showTimer: true,
};
},
render: function() {
if (this.state.showTimer) {
var timer = [
<TimerTester ref="interval" dt={25} type="setInterval" />,
<UIExplorerButton onPress={() => this.refs.interval.clear() }>
Clear interval
</UIExplorerButton>
];
var toggleText = 'Unmount timer';
} else {
var timer = null;
var toggleText = 'Mount new timer';
}
return (
<View>
{this.state.showTimer && this._renderTimer()}
<UIExplorerButton onPress={this._toggleTimer}>
{this.state.showTimer ? 'Unmount timer' : 'Mount new timer'}
</UIExplorerButton>
</View>
);
},
_renderTimer: function() {
return (
<View>
<TimerTester ref="interval" dt={25} type="setInterval" />
<UIExplorerButton onPress={() => this.refs.interval.clear() }>
Clear interval
</UIExplorerButton>
</View>
);
},
_toggleTimer: function() {
this.setState({showTimer: !this.state.showTimer});
},
});
return <IntervalExample />;
},
},
];
|
jhen0409/react-native
|
Examples/UIExplorer/js/TimerExample.js
|
JavaScript
|
bsd-3-clause
| 8,667 | 28.280405 | 128 | 0.577247 | false |
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __SSL_TRANSPORT_SECURITY_H_
#define __SSL_TRANSPORT_SECURITY_H_
#include "src/core/tsi/transport_security_interface.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Value for the TSI_CERTIFICATE_TYPE_PEER_PROPERTY property for X509 certs. */
#define TSI_X509_CERTIFICATE_TYPE "X509"
/* This property is of type TSI_PEER_PROPERTY_STRING. */
#define TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY "x509_subject_common_name"
/* This property is of type TSI_PEER_PROPERTY_LIST and the children contain
unnamed (name == NULL) properties of type TSI_PEER_PROPERTY_STRING. */
#define TSI_X509_SUBJECT_ALTERNATIVE_NAMES_PEER_PROPERTY \
"x509_subject_alternative_names"
/* This property is of type TSI_PEER_PROPERTY_STRING. */
#define TSI_SSL_ALPN_SELECTED_PROTOCOL "ssl_alpn_selected_protocol"
/* --- tsi_ssl_handshaker_factory object ---
This object creates tsi_handshaker objects implemented in terms of the
TLS 1.2 specificiation. */
typedef struct tsi_ssl_handshaker_factory tsi_ssl_handshaker_factory;
/* Creates a client handshaker factory.
- pem_private_key is the buffer containing the PEM encoding of the client's
private key. This parameter can be NULL if the client does not have a
private key.
- pem_private_key_size is the size of the associated buffer.
- pem_cert_chain is the buffer containing the PEM encoding of the client's
certificate chain. This parameter can be NULL if the client does not have
a certificate chain.
- pem_cert_chain_size is the size of the associated buffer.
- pem_roots_cert is the buffer containing the PEM encoding of the server
root certificates. This parameter cannot be NULL.
- pem_roots_cert_size is the size of the associated buffer.
- cipher_suites contains an optional list of the ciphers that the client
supports. The format of this string is described in:
https://www.openssl.org/docs/apps/ciphers.html.
This parameter can be set to NULL to use the default set of ciphers.
TODO(jboeuf): Revisit the format of this parameter.
- alpn_protocols is an array containing the protocol names that the
handshakers created with this factory support. This parameter can be NULL.
- alpn_protocols_lengths is an array containing the lengths of the alpn
protocols specified in alpn_protocols. This parameter can be NULL.
- num_alpn_protocols is the number of alpn protocols and associated lengths
specified. If this parameter is 0, the other alpn parameters must be NULL.
- factory is the address of the factory pointer to be created.
- This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
where a parameter is invalid. */
tsi_result tsi_create_ssl_client_handshaker_factory(
const unsigned char* pem_private_key, size_t pem_private_key_size,
const unsigned char* pem_cert_chain, size_t pem_cert_chain_size,
const unsigned char* pem_root_certs, size_t pem_root_certs_size,
const char* cipher_suites, const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory);
/* Creates a server handshaker factory.
- version indicates which version of the specification to use.
- pem_private_keys is an array containing the PEM encoding of the server's
private keys. This parameter cannot be NULL. The size of the array is
given by the key_cert_pair_count parameter.
- pem_private_keys_sizes is the array containing the sizes of the associated
buffers.
- pem_cert_chains is an array containing the PEM encoding of the server's
cert chains. This parameter cannot be NULL. The size of the array is
given by the key_cert_pair_count parameter.
- pem_cert_chains_sizes is the array containing the sizes of the associated
buffers.
- key_cert_pair_count indicates the number of items in the private_key_files
and cert_chain_files parameters.
- pem_client_roots is the buffer containing the PEM encoding of the client
root certificates. This parameter may be NULL in which case the server
will not ask the client to authenticate itself with a certificate (server-
only authentication mode).
- pem_client_roots_size is the size of the associated buffer.
- cipher_suites contains an optional list of the ciphers that the server
supports. The format of this string is described in:
https://www.openssl.org/docs/apps/ciphers.html.
This parameter can be set to NULL to use the default set of ciphers.
TODO(jboeuf): Revisit the format of this parameter.
- alpn_protocols is an array containing the protocol names that the
handshakers created with this factory support. This parameter can be NULL.
- alpn_protocols_lengths is an array containing the lengths of the alpn
protocols specified in alpn_protocols. This parameter can be NULL.
- num_alpn_protocols is the number of alpn protocols and associated lengths
specified. If this parameter is 0, the other alpn parameters must be NULL.
- factory is the address of the factory pointer to be created.
- This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
where a parameter is invalid. */
tsi_result tsi_create_ssl_server_handshaker_factory(
const unsigned char** pem_private_keys,
const size_t* pem_private_keys_sizes, const unsigned char** pem_cert_chains,
const size_t* pem_cert_chains_sizes, size_t key_cert_pair_count,
const unsigned char* pem_client_root_certs,
size_t pem_client_root_certs_size, const char* cipher_suites,
const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory);
/* Creates a handshaker.
- self is the factory from which the handshaker will be created.
- server_name_indication indicates the name of the server the client is
trying to connect to which will be relayed to the server using the SNI
extension.
This parameter must be NULL for a server handshaker factory.
- handhshaker is the address of the handshaker pointer to be created.
- This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
where a parameter is invalid. */
tsi_result tsi_ssl_handshaker_factory_create_handshaker(
tsi_ssl_handshaker_factory* self, const char* server_name_indication,
tsi_handshaker** handshaker);
/* Destroys the handshaker factory. WARNING: it is unsafe to destroy a factory
while handshakers created with this factory are still in use. */
void tsi_ssl_handshaker_factory_destroy(tsi_ssl_handshaker_factory* self);
/* Util that checks that an ssl peer matches a specific name.
Still TODO(jboeuf):
- handle mixed case.
- handle %encoded chars.
- handle public suffix wildchar more strictly (e.g. *.co.uk)
- handle IP addresses in SAN. */
int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name);
#ifdef __cplusplus
}
#endif
#endif /* __SSL_TRANSPORT_SECURITY_H_ */
|
nathanielmanistaatgoogle/grpc
|
src/core/tsi/ssl_transport_security.h
|
C
|
bsd-3-clause
| 8,635 | 48.913295 | 80 | 0.747192 | false |
// -*-Mode: C++;-*- // technically C99
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2015, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *
/*
* Declarations used by interval splay tree code.
*
*/
#ifndef _SPLAY_H_
#define _SPLAY_H_
#include "splay-interval.h"
/*
* As a slicky trick, interval_tree_node overlays with
* unwind_interval_t where next = right and prev = left.
* (May not want to keep this.)
*/
typedef struct splay_interval_s interval_tree_node;
#define START(n) (n)->start
#define END(n) (n)->end
#define RIGHT(n) (n)->next
#define LEFT(n) (n)->prev
#define SSTART(n) (n).start
#define SEND(n) (n).end
#define SRIGHT(n) (n).next
#define SLEFT(n) (n).prev
// FIXME: STOP embedding pointer info in type!!
//
typedef interval_tree_node *interval_tree_node_t;
interval_tree_node *interval_tree_lookup(interval_tree_node **root, void *addr);
int interval_tree_insert(interval_tree_node **root, interval_tree_node *node);
void interval_tree_delete(interval_tree_node **root, interval_tree_node **del_tree,
void *start, void *end);
void interval_tree_verify(interval_tree_node *root, const char *label);
#define SUCCESS 0
#define FAILURE 1
#endif /* !_SPLAY_H_ */
|
zcth428/hpctoolkit111
|
src/tool/hpcrun/unwind/common/splay.h
|
C
|
bsd-3-clause
| 3,200 | 34.555556 | 83 | 0.664688 | false |
TC_NAME = syno-$(TC_ARCH)
TC_ARCH = braswell
TC_VERS = 6.1
TC_FIRMWARE = 6.1-15047
TC_DIST = braswell-gcc493_glibc220_linaro_x86_64-GPL
TC_EXT = txz
TC_DIST_NAME = $(TC_DIST).$(TC_EXT)
TC_DIST_SITE = https://sourceforge.net/projects/dsgpl/files/DSM%206.1%20Tool%20Chains/Intel%20x86%20Linux%203.10.102%20%28Braswell%29
TC_BASE_DIR = x86_64-pc-linux-gnu
TC_PREFIX = x86_64-pc-linux-gnu
TC_TARGET = x86_64-pc-linux-gnu
TC_CFLAGS = -I$(WORK_DIR)/$(TC_BASE_DIR)/$(TC_BASE_DIR)/sys-root/usr/include
TC_CPPFLAGS = -I$(WORK_DIR)/$(TC_BASE_DIR)/$(TC_BASE_DIR)/sys-root/usr/include
TC_CXXFLAGS = -I$(WORK_DIR)/$(TC_BASE_DIR)/$(TC_BASE_DIR)/sys-root/usr/include
TC_LDFLAGS = -L$(WORK_DIR)/$(TC_BASE_DIR)/$(TC_BASE_DIR)/sys-root/lib
FIX_TARGET = myFix
include ../../mk/spksrc.tc.mk
.PHONY: myFix
myFix:
chmod -R u+w $(WORK_DIR)
@find $(WORK_DIR)/$(TC_BASE_DIR) -type f -name '*.la' -exec sed -i -e "s|^libdir=.*$$|libdir='$(WORK_DIR)/$(TC_BASE_DIR)/$(TC_BASE_DIR)/sys-root/lib'|" {} \;
|
saschpe/spksrc
|
toolchains/syno-braswell-6.1/Makefile
|
Makefile
|
bsd-3-clause
| 984 | 34.142857 | 158 | 0.666667 | false |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/animation/compositor_keyframe_model.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/animation/compositor_float_animation_curve.h"
namespace blink {
TEST(WebCompositorAnimationTest, DefaultSettings) {
auto curve = std::make_unique<CompositorFloatAnimationCurve>();
auto keyframe_model = std::make_unique<CompositorKeyframeModel>(
*curve, 0, 1,
CompositorKeyframeModel::TargetPropertyId(
compositor_target_property::OPACITY));
// Ensure that the defaults are correct.
EXPECT_EQ(1, keyframe_model->Iterations());
EXPECT_EQ(0, keyframe_model->StartTime());
EXPECT_EQ(0, keyframe_model->TimeOffset());
EXPECT_EQ(CompositorKeyframeModel::Direction::NORMAL,
keyframe_model->GetDirection());
}
TEST(WebCompositorAnimationTest, ModifiedSettings) {
auto curve = std::make_unique<CompositorFloatAnimationCurve>();
auto keyframe_model = std::make_unique<CompositorKeyframeModel>(
*curve, 0, 1,
CompositorKeyframeModel::TargetPropertyId(
compositor_target_property::OPACITY));
keyframe_model->SetIterations(2);
keyframe_model->SetStartTime(2);
keyframe_model->SetTimeOffset(base::Seconds(2));
keyframe_model->SetDirection(CompositorKeyframeModel::Direction::REVERSE);
EXPECT_EQ(2, keyframe_model->Iterations());
EXPECT_EQ(2, keyframe_model->StartTime());
EXPECT_EQ(2, keyframe_model->TimeOffset());
EXPECT_EQ(CompositorKeyframeModel::Direction::REVERSE,
keyframe_model->GetDirection());
}
} // namespace blink
|
scheib/chromium
|
third_party/blink/renderer/platform/animation/compositor_keyframe_model_test.cc
|
C++
|
bsd-3-clause
| 1,767 | 38.266667 | 91 | 0.74137 | false |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBKIT_BROWSER_CHROMEOS_FILEAPI_REMOTE_FILE_STREAM_WRITER_H_
#define WEBKIT_BROWSER_CHROMEOS_FILEAPI_REMOTE_FILE_STREAM_WRITER_H_
#include "base/basictypes.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/platform_file.h"
#include "webkit/browser/fileapi/file_stream_writer.h"
#include "webkit/browser/fileapi/file_system_context.h"
#include "webkit/browser/fileapi/file_system_url.h"
namespace net {
class IOBuffer;
}
namespace webkit_blob {
class ShareableFileReference;
}
namespace fileapi {
class RemoteFileSystemProxyInterface;
// FileStreamWriter interface for writing to a file on remote file system.
class RemoteFileStreamWriter : public fileapi::FileStreamWriter {
public:
// Creates a writer for a file on |remote_filesystem| with path url |url|
// (like "filesystem:chrome-extension://id/external/drive/...") that
// starts writing from |offset|. When invalid parameters are set, the first
// call to Write() method fails.
// Uses |local_task_runner| for local file operations.
RemoteFileStreamWriter(
const scoped_refptr<RemoteFileSystemProxyInterface>& remote_filesystem,
const FileSystemURL& url,
int64 offset,
base::TaskRunner* local_task_runner);
virtual ~RemoteFileStreamWriter();
// FileWriter override.
virtual int Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int Cancel(const net::CompletionCallback& callback) OVERRIDE;
virtual int Flush(const net::CompletionCallback& callback) OVERRIDE;
private:
// Callback function to do the continuation of the work of the first Write()
// call, which tries to open the local copy of the file before writing.
void OnFileOpened(
net::IOBuffer* buf,
int buf_len,
const net::CompletionCallback& callback,
base::PlatformFileError open_result,
const base::FilePath& local_path,
const scoped_refptr<webkit_blob::ShareableFileReference>& file_ref);
// Calls |pending_cancel_callback_|, assuming it is non-null.
void InvokePendingCancelCallback(int result);
scoped_refptr<RemoteFileSystemProxyInterface> remote_filesystem_;
scoped_refptr<base::TaskRunner> local_task_runner_;
const FileSystemURL url_;
const int64 initial_offset_;
scoped_ptr<fileapi::FileStreamWriter> local_file_writer_;
scoped_refptr<webkit_blob::ShareableFileReference> file_ref_;
bool has_pending_create_snapshot_;
net::CompletionCallback pending_cancel_callback_;
base::WeakPtrFactory<RemoteFileStreamWriter> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(RemoteFileStreamWriter);
};
} // namespace fileapi
#endif // WEBKIT_BROWSER_CHROMEOS_FILEAPI_REMOTE_FILE_STREAM_WRITER_H_
|
pozdnyakov/chromium-crosswalk
|
webkit/browser/chromeos/fileapi/remote_file_stream_writer.h
|
C
|
bsd-3-clause
| 2,947 | 36.303797 | 78 | 0.751951 | false |
<?php
/**
* @author oba.ou
*/
use \kartik\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
/* @var $searchModel mdm\admin\models\searchs\Assignment */
/* @var $usernameField string */
/* @var $extraColumns string[] */
$this->title = Yii::t('rbac-admin', 'Assignments');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="assignment-index">
<?php
Pjax::begin([
'enablePushState'=>false,
]);
$columns =
[
['class' => 'yii\grid\SerialColumn'],
$usernameField,
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{view}',
'buttons'=>[
'view'=>function ($url, $model, $key) {
return Html::a(Html::icon('eye-open'), \yii\helpers\Url::to(['/rbac/assignment/view','id'=>$model->getId()]));
}
]
],
];
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $columns,
]);
Pjax::end();
?>
</div>
|
oyoy8629/yii-core
|
core/rbac/views/index.php
|
PHP
|
bsd-3-clause
| 1,194 | 25.533333 | 134 | 0.50335 | false |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.sync.ui;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.sync.internal_api.pub.PassphraseType;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
/**
* Dialog to ask the user select what type of password to use for encryption.
*/
public class PassphraseTypeDialogFragment extends DialogFragment implements
DialogInterface.OnClickListener, OnItemClickListener {
private static final String TAG = "PassphraseTypeDialogFragment";
interface Listener {
void onPassphraseTypeSelected(PassphraseType type);
}
private static class PassphraseTypeUiElement {
private final PassphraseType mPassphraseType;
private final String mDisplayName;
private int mPosition;
private PassphraseTypeUiElement(PassphraseType passphraseType, String displayName) {
mPassphraseType = passphraseType;
mDisplayName = displayName;
// Default position to an invalid value.
mPosition = -1;
}
}
private static class PassphraseTypeUiElementContainer {
private final ArrayList<PassphraseTypeUiElement> mElements =
new ArrayList<PassphraseTypeUiElement>();
public void add(PassphraseTypeUiElement element) {
// Now that we know where we will insert the element, we can update its position member.
element.mPosition = mElements.size();
mElements.add(element);
}
public ArrayList<PassphraseTypeUiElement> getElements() {
return mElements;
}
public String[] getDisplayNames() {
String[] strings = new String[mElements.size()];
for (int i = 0; i < mElements.size(); i++) {
strings[i] = mElements.get(i).mDisplayName;
}
return strings;
}
}
private String textForPassphraseType(PassphraseType type) {
switch (type) {
case IMPLICIT_PASSPHRASE: // Intentional fall through.
case KEYSTORE_PASSPHRASE:
return getString(R.string.sync_passphrase_type_keystore);
case FROZEN_IMPLICIT_PASSPHRASE:
String passphraseDate = getPassphraseDateStringFromArguments();
String frozenPassphraseString = getString(R.string.sync_passphrase_type_frozen);
return String.format(frozenPassphraseString, passphraseDate);
case CUSTOM_PASSPHRASE:
return getString(R.string.sync_passphrase_type_custom);
default:
return "";
}
}
private Adapter createAdapter(PassphraseType currentType) {
PassphraseTypeUiElementContainer container = new PassphraseTypeUiElementContainer();
for (PassphraseType type : currentType.getVisibleTypes()) {
container.add(new PassphraseTypeUiElement(type, textForPassphraseType(type)));
}
return new Adapter(container, container.getDisplayNames());
}
/**
* The adapter for our ListView; only visible for testing purposes.
*/
@VisibleForTesting
public class Adapter extends ArrayAdapter<String> {
private final PassphraseTypeUiElementContainer mElementsContainer;
/**
* Do not call this constructor directly. Instead use
* {@link PassphraseTypeDialogFragment#createAdapter}.
*/
private Adapter(PassphraseTypeUiElementContainer elementsContainer,
String[] elementStrings) {
super(getActivity(), R.layout.passphrase_type_item, elementStrings);
mElementsContainer = elementsContainer;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public long getItemId(int position) {
return getType(position).internalValue();
}
public PassphraseType getType(int position) {
return mElementsContainer.getElements().get(position).mPassphraseType;
}
public int getPositionForType(PassphraseType type) {
for (PassphraseTypeUiElement element : mElementsContainer.getElements()) {
if (element.mPassphraseType == type) {
return element.mPosition;
}
}
return -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckedTextView view = (CheckedTextView) super.getView(position, convertView, parent);
PassphraseType positionType = getType(position);
PassphraseType currentType = getCurrentTypeFromArguments();
Set<PassphraseType> allowedTypes = currentType.getAllowedTypes(
getEncryptEverythingAllowedFromArguments());
// Set the item to checked it if it is the currently selected encryption type.
view.setChecked(positionType == currentType);
// Allow user to click on enabled types for the current type.
view.setEnabled(allowedTypes.contains(positionType));
return view;
}
}
/**
* This argument should contain a single value of type {@link PassphraseType}.
*/
private static final String ARG_CURRENT_TYPE = "arg_current_type";
private static final String ARG_PASSPHRASE_TIME = "arg_passphrase_time";
private static final String ARG_ENCRYPT_EVERYTHING_ALLOWED = "arg_encrypt_everything_allowed";
static PassphraseTypeDialogFragment create(PassphraseType currentType,
long passphraseTime,
boolean encryptEverythingAllowed) {
PassphraseTypeDialogFragment dialog = new PassphraseTypeDialogFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_CURRENT_TYPE, currentType);
args.putLong(ARG_PASSPHRASE_TIME, passphraseTime);
args.putBoolean(ARG_ENCRYPT_EVERYTHING_ALLOWED, encryptEverythingAllowed);
dialog.setArguments(args);
return dialog;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Configure the passphrase type list
ListView list = new ListView(getActivity());
Adapter adapter = createAdapter(getCurrentTypeFromArguments());
list.setAdapter(adapter);
list.setId(R.id.passphrase_type_list);
list.setOnItemClickListener(this);
list.setDividerHeight(0);
PassphraseType currentType = getCurrentTypeFromArguments();
list.setSelection(adapter.getPositionForType(currentType));
// Create and return the dialog
return new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme)
.setNegativeButton(R.string.cancel, this)
.setTitle(R.string.sync_passphrase_type_title)
.setView(list)
.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dismiss();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long typeId) {
PassphraseType currentType = getCurrentTypeFromArguments();
// We know this conversion from long to int is safe, because it represents very small
// enum values.
PassphraseType type = PassphraseType.fromInternalValue((int) typeId);
boolean encryptEverythingAllowed = getEncryptEverythingAllowedFromArguments();
if (currentType.getAllowedTypes(encryptEverythingAllowed).contains(type)) {
if (typeId != currentType.internalValue()) {
Listener listener = (Listener) getTargetFragment();
listener.onPassphraseTypeSelected(type);
}
dismiss();
}
}
@VisibleForTesting
public PassphraseType getCurrentTypeFromArguments() {
PassphraseType currentType = getArguments().getParcelable(ARG_CURRENT_TYPE);
if (currentType == null) {
throw new IllegalStateException("Unable to find argument with current type.");
}
return currentType;
}
private String getPassphraseDateStringFromArguments() {
long passphraseTime = getArguments().getLong(ARG_PASSPHRASE_TIME);
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
return df.format(new Date(passphraseTime));
}
private boolean getEncryptEverythingAllowedFromArguments() {
return getArguments().getBoolean(ARG_ENCRYPT_EVERYTHING_ALLOWED);
}
}
|
guorendong/iridium-browser-ubuntu
|
chrome/android/java/src/org/chromium/chrome/browser/sync/ui/PassphraseTypeDialogFragment.java
|
Java
|
bsd-3-clause
| 9,350 | 38.121339 | 100 | 0.66492 | false |
/*!
backbone.fetch-cache v1.4.0
by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
*/
// AMD wrapper from https://github.com/umdjs/umd/blob/master/amdWebGlobal.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module and set browser global
define(['underscore', 'backbone', 'jquery'], function (_, Backbone, $) {
return (root.Backbone = factory(_, Backbone, $));
});
} else {
// Browser globals
root.Backbone = factory(root._, root.Backbone, root.jQuery);
}
}(this, function (_, Backbone, $) {
// Setup
var superMethods = {
modelFetch: Backbone.Model.prototype.fetch,
modelSync: Backbone.Model.prototype.sync,
collectionFetch: Backbone.Collection.prototype.fetch
},
supportLocalStorage = (function() {
var supported = typeof window.localStorage !== 'undefined';
if (supported) {
try {
// impossible to write on some platforms when private browsing is on and
// throws an exception = local storage not supported.
localStorage.setItem("test_support", "test_support");
localStorage.removeItem("test_support");
} catch (e) {
supported = false;
}
}
return supported;
})();
Backbone.fetchCache = (Backbone.fetchCache || {});
Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});
Backbone.fetchCache.priorityFn = function(a, b) {
if (!a || !a.expires || !b || !b.expires) {
return a;
}
return a.expires - b.expires;
};
Backbone.fetchCache._prioritize = function() {
var sorted = _.values(this._cache).sort(this.priorityFn);
var index = _.indexOf(_.values(this._cache), sorted[0]);
return _.keys(this._cache)[index];
};
Backbone.fetchCache._deleteCacheWithPriority = function() {
Backbone.fetchCache._cache[this._prioritize()] = null;
delete Backbone.fetchCache._cache[this._prioritize()];
Backbone.fetchCache.setLocalStorage();
};
Backbone.fetchCache.getLocalStorageKey = function() {
return 'backboneCache';
};
if (typeof Backbone.fetchCache.localStorage === 'undefined') {
Backbone.fetchCache.localStorage = true;
}
// Shared methods
function getCacheKey(instance, opts) {
var url;
if(opts && opts.url) {
url = opts.url;
} else {
url = _.isFunction(instance.url) ? instance.url() : instance.url;
}
// Need url to use as cache key so return if we can't get it
if(!url) { return; }
if(opts && opts.data) {
return url + "?" + $.param(opts.data);
}
return url;
}
function setCache(instance, opts, attrs) {
opts = (opts || {});
var key = Backbone.fetchCache.getCacheKey(instance, opts),
expires = false;
// Need url to use as cache key so return if we can't get it
if (!key) { return; }
// Never set the cache if user has explicitly said not to
if (opts.cache === false) { return; }
// Don't set the cache unless cache: true or prefill: true option is passed
if (!(opts.cache || opts.prefill)) { return; }
if (opts.expires !== false) {
expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
}
Backbone.fetchCache._cache[key] = {
expires: expires,
value: attrs
};
Backbone.fetchCache.setLocalStorage();
}
function clearItem(key) {
if (_.isFunction(key)) { key = key(); }
delete Backbone.fetchCache._cache[key];
Backbone.fetchCache.setLocalStorage();
}
function setLocalStorage() {
if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
try {
localStorage.setItem(Backbone.fetchCache.getLocalStorageKey(), JSON.stringify(Backbone.fetchCache._cache));
} catch (err) {
var code = err.code || err.number || err.message;
if (code === 22) {
this._deleteCacheWithPriority();
} else {
throw(err);
}
}
}
function getLocalStorage() {
if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
var json = localStorage.getItem(Backbone.fetchCache.getLocalStorageKey()) || '{}';
Backbone.fetchCache._cache = JSON.parse(json);
}
function nextTick(fn) {
return window.setTimeout(fn, 0);
}
// Instance methods
Backbone.Model.prototype.fetch = function(opts) {
opts = _.defaults(opts || {}, { parse: true });
var key = Backbone.fetchCache.getCacheKey(this, opts),
data = Backbone.fetchCache._cache[key],
expired = false,
attributes = false,
deferred = new $.Deferred(),
self = this;
function setData() {
if (opts.parse) {
attributes = self.parse(attributes, opts);
}
self.set(attributes, opts);
if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(self, attributes, opts); }
// Trigger sync events
self.trigger('cachesync', self, attributes, opts);
self.trigger('sync', self, attributes, opts);
// Notify progress if we're still waiting for an AJAX call to happen...
if (opts.prefill) { deferred.notify(self); }
// ...finish and return if we're not
else {
if (_.isFunction(opts.success)) { opts.success(self, attributes, opts); }
deferred.resolve(self);
}
}
if (data) {
expired = data.expires;
expired = expired && data.expires < (new Date()).getTime();
attributes = data.value;
}
if (!expired && (opts.cache || opts.prefill) && attributes) {
// Ensure that cache resolution adhers to async option, defaults to true.
if (opts.async == null) { opts.async = true; }
if (opts.async) {
nextTick(setData);
} else {
setData();
}
if (!opts.prefill) {
return deferred;
}
}
// Delegate to the actual fetch method and store the attributes in the cache
superMethods.modelFetch.apply(this, arguments)
// resolve the returned promise when the AJAX call completes
.done( _.bind(deferred.resolve, this, this) )
// Set the new data in the cache
.done( _.bind(Backbone.fetchCache.setCache, null, this, opts) )
// Reject the promise on fail
.fail( _.bind(deferred.reject, this, this) );
// return a promise which provides the same methods as a jqXHR object
return deferred;
};
// Override Model.prototype.sync and try to clear cache items if it looks
// like they are being updated.
Backbone.Model.prototype.sync = function(method, model, options) {
// Only empty the cache if we're doing a create, update, patch or delete.
if (method === 'read') {
return superMethods.modelSync.apply(this, arguments);
}
var collection = model.collection,
keys = [],
i, len;
// Build up a list of keys to delete from the cache, starting with this
keys.push(Backbone.fetchCache.getCacheKey(model, options));
// If this model has a collection, also try to delete the cache for that
if (!!collection) {
keys.push(Backbone.fetchCache.getCacheKey(collection));
}
// Empty cache for all found keys
for (i = 0, len = keys.length; i < len; i++) { clearItem(keys[i]); }
return superMethods.modelSync.apply(this, arguments);
};
Backbone.Collection.prototype.fetch = function(opts) {
opts = _.defaults(opts || {}, { parse: true });
var key = Backbone.fetchCache.getCacheKey(this, opts),
data = Backbone.fetchCache._cache[key],
expired = false,
attributes = false,
deferred = new $.Deferred(),
self = this;
function setData() {
self[opts.reset ? 'reset' : 'set'](attributes, opts);
if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(self); }
// Trigger sync events
self.trigger('cachesync', self, attributes, opts);
self.trigger('sync', self, attributes, opts);
// Notify progress if we're still waiting for an AJAX call to happen...
if (opts.prefill) { deferred.notify(self); }
// ...finish and return if we're not
else {
if (_.isFunction(opts.success)) { opts.success(self, attributes, opts); }
deferred.resolve(self);
}
}
if (data) {
expired = data.expires;
expired = expired && data.expires < (new Date()).getTime();
attributes = data.value;
}
if (!expired && (opts.cache || opts.prefill) && attributes) {
// Ensure that cache resolution adhers to async option, defaults to true.
if (opts.async == null) { opts.async = true; }
if (opts.async) {
nextTick(setData);
} else {
setData();
}
if (!opts.prefill) {
return deferred;
}
}
// Delegate to the actual fetch method and store the attributes in the cache
superMethods.collectionFetch.apply(this, arguments)
// resolve the returned promise when the AJAX call completes
.done( _.bind(deferred.resolve, this, this) )
// Set the new data in the cache
.done( _.bind(Backbone.fetchCache.setCache, null, this, opts) )
// Reject the promise on fail
.fail( _.bind(deferred.reject, this, this) );
// return a promise which provides the same methods as a jqXHR object
return deferred;
};
// Prime the cache from localStorage on initialization
getLocalStorage();
// Exports
Backbone.fetchCache._superMethods = superMethods;
Backbone.fetchCache.setCache = setCache;
Backbone.fetchCache.getCacheKey = getCacheKey;
Backbone.fetchCache.clearItem = clearItem;
Backbone.fetchCache.setLocalStorage = setLocalStorage;
Backbone.fetchCache.getLocalStorage = getLocalStorage;
return Backbone;
}));
|
openbudgets/openbudgets
|
openbudgets/commons/static/vendor/backbone-fetch-cache/backbone.fetch-cache.js
|
JavaScript
|
bsd-3-clause
| 9,735 | 30.302251 | 113 | 0.628968 | false |
<!DOCTYPE html>
<html dir="ltr" lang="de">
<head>
<title>Anhang B - Literaturverzeichnis - Rubinius</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta content='de' http-equiv='content-language'>
<meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'>
<link href='/' rel='home'>
<link href='/' rel='start'>
<link href='/doc/de/appendix-a-glossary' rel='prev' title='Anhang A - Glossar'>
<link href='/doc/de/index-of-terms' rel='next' title='Begriffsindex'>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]-->
<script src="/javascripts/jquery-1.3.2.js"></script>
<script src="/javascripts/paging_keys.js"></script>
<script src="/javascripts/application.js"></script>
<style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style>
<link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" />
<link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" />
<!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]-->
<link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" />
</head>
<body>
<div class='container'>
<div class='span-21 doc_menu'>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a id="blog" href="/blog">Blog</a></li>
<li><a id="documentation" href="/doc/en">Documentation</a></li>
<li><a href="/projects">Projects</a></li>
<li><a href="/roadmap">Roadmap</a></li>
<li><a href="/releases">Releases</a></li>
</ul>
</nav>
</header>
</div>
<div class='span-3 last'>
<div id='version'>
<a href="/releases/1.2.4">1.2.4</a>
</div>
</div>
</div>
<div class="container languages">
<nav>
<span class="label">Sprachen:</span>
<ul>
<li><a href="/doc/de/appendix-b-reading-list/"
class="current"
>de</a></li>
<li><a href="/doc/en/appendix-b-reading-list/"
>en</a></li>
<li><a href="/doc/es/appendix-b-reading-list/"
>es</a></li>
<li><a href="/doc/fr/appendix-b-reading-list/"
>fr</a></li>
<li><a href="/doc/ja/appendix-b-reading-list/"
>ja</a></li>
<li><a href="/doc/pl/appendix-b-reading-list/"
>pl</a></li>
<li><a href="/doc/pt-br/appendix-b-reading-list/"
>pt-br</a></li>
<li><a href="/doc/ru/appendix-b-reading-list/"
>ru</a></li>
</ul>
</nav>
</div>
<div class="container doc_page_nav">
<span class="label">Vorherige:</span>
<a href="/doc/de/appendix-a-glossary">Anhang A - Glossar</a>
<span class="label">Aufwärts:</span>
<a href="/doc/de/">Inhaltsverzeichnis</a>
<span class="label">Nächste:</span>
<a href="/doc/de/index-of-terms">Begriffsindex</a>
</div>
<div class="container documentation">
<h2>Anhang B - Literaturverzeichnis</h2>
<div class="review">
<p>This topic has missing or partial documentation. Please help us improve it.</p>
<p>
See <a href="/doc/de/how-to/write-documentation">How-To - Write Documentation</a>
</p>
</div>
<p>Die Entwicklung von Virtuellen Maschinen im Allgemeinen und
Programmiersprachenimplementierungen im Speziellen bedarf einiges an
Wissen. Das Ziel von Rubinius ist es, den Einstieg in das Thema
einfach zu halten. Dazu verfolgt Rubinius u.a. das Ziel, so viel wie
möglich in Ruby selbst zu implementieren. Um aber am Garbage Collector
mitzuentwickeln, muss man wissen was hinter den High-level Konzepten
steckt.</p>
<p>Diese Seite enthält Verweise auf Bücher, online Literatur, Blogposts
und sonstige Publikationen die bei der Entwicklung an Rubinius
behilflich sein können.</p>
<p>Beachte, dass sich einige dieser Links auf veraltete Informationen
bzgl. Rubinius beziehen können.</p>
<h2 id="virtuelle-maschine">Virtuelle Maschine</h2>
<ul>
<li><a href="http://tinyurl.com/3a2pdq">Smalltalk-80: language and its
implementation</a> by Goldberg, Robson,
Harrison (aka “The Blue Book”), Kapitel zur Implementierung der VM
aus Teil IV sind <a href="http://tinyurl.com/6zlsd">online verfügbar</a></li>
<li><a href="http://tinyurl.com/3ydkqg">Virtual machines</a> by Iain D. Craig</li>
<li>Sehr gute Posts von Adam Gardiner: <a href="http://tinyurl.com/35y2jh">introduction</a>,
<a href="http://tinyurl.com/34c6e8">How send sites work</a></li>
</ul>
<h2 id="garbage-collection">Garbage collection</h2>
<ul>
<li><a href="http://tinyurl.com/3dygmo">Garbage Collection: Algorithms for Automatic Dynamic Memory
Management</a> by Richard Jones</li>
<li><a href="http://tinyurl.com/2mhek4">Garbage collection lectures</a></li>
</ul>
<h2 id="primitive-methods">Primitive methods</h2>
<ul>
<li><a href="http://talklikeaduck.denhaven2.com/articles/2007/06/04/ruby-extensions-vs-smalltalk-primitives">Ruby extensions and Smalltalk
primitives</a></li>
<li><a href="http://www.fit.vutbr.cz/study/courses/OMP/public/software/sqcdrom2/Tutorials/SqOnlineBook_(SOB)/englisch/sqk/sqk00083.htm">Guide to Squeak
primitives</a></li>
</ul>
<h2 id="ffi">FFI</h2>
<ul>
<li><a href="http://redartisan.com/2007/10/11/rubinius-coding">Implementing File#link using
FFI</a></li>
<li><a href="http://blog.segment7.net/articles/2008/01/15/rubinius-foreign-function-interface">Rubinius’ foreign function
interface</a></li>
</ul>
</div>
<div class="container doc_page_nav">
<span class="label">Vorherige:</span>
<a href="/doc/de/appendix-a-glossary">Anhang A - Glossar</a>
<span class="label">Aufwärts:</span>
<a href="/doc/de/">Inhaltsverzeichnis</a>
<span class="label">Nächste:</span>
<a href="/doc/de/index-of-terms">Begriffsindex</a>
</div>
<div class="container">
<div id="disqus_thread"></div>
<script type="text/javascript">
var disqus_shortname = 'rubinius';
var disqus_identifier = '/doc/de/appendix-b-reading-list/';
var disqus_url = 'http://rubini.us/doc/de/appendix-b-reading-list/';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
<footer>
<div class='container'>
<nav>
<ul>
<li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li>
<li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li>
<li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li>
</ul>
</nav>
</div>
</footer>
<script>
var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
|
travis-repos/rubinius
|
web/_site/doc/de/appendix-b-reading-list/index.html
|
HTML
|
bsd-3-clause
| 8,009 | 29.414449 | 338 | 0.643955 | false |
z.visitor = z.Storage('visitor');
z.currentVisit = z.SessionStorage('current-visit');
function initBanners() {
var $body = $(document.body);
if ($body.hasClass('editor-tools')) {
// Don't bother showing those on editor tools, it has a bunch of weird
// styles for the menu that don't play nice with those banners.
return;
}
// Show the various banners, but only one at a time, and only if they
// haven't been dimissed before.
// To reset dismissal state: z.visitor.remove('xx')
// Show the bad-browser message
if (
!z.visitor.get('seen_badbrowser_warning') &&
$body.hasClass('badbrowser')
) {
$('#site-nonfx').show();
}
// Show the first visit banner.
else if (!z.visitor.get('seen_impala_first_visit')) {
$body.addClass('firstvisit');
z.visitor.set('seen_impala_first_visit', 1);
}
// Show the link to try the new frontend (only on the homepage for now).
else if (!z.visitor.get('seen_try_new_frontend') && $body.hasClass('home')) {
$('#try-new-frontend').show();
}
// Show the ACR pitch if it has not been dismissed.
else if (!z.visitor.get('seen_acr_pitch') && $body.hasClass('acr-pitch')) {
$body.find('#acr-pitch').show();
}
// Allow dismissal of site-balloons.
$body.on(
'click',
'.site-balloon .close, .site-tip .close',
_pd(function () {
var $parent = $(this).closest('.site-balloon, .site-tip');
$parent.fadeOut();
if ($parent.is('#site-nonfx')) {
z.visitor.set('seen_badbrowser_warning', 1);
} else if ($parent.is('#acr-pitch')) {
z.visitor.set('seen_acr_pitch', 1);
} else if ($parent.is('#appruntime-pitch')) {
z.visitor.set('seen_appruntime_pitch', 1);
} else if ($parent.is('#try-new-frontend')) {
z.visitor.set('seen_try_new_frontend', 1);
}
}),
);
}
|
bqbn/addons-server
|
static/js/common/banners.js
|
JavaScript
|
bsd-3-clause
| 1,846 | 31.964286 | 79 | 0.609426 | false |
KERNEL_ARCH = hi3535
KERNEL_VERS = 6.1
KERNEL_BUILD = 15152
KERNEL_DIST = linux-3.4.x
KERNEL_BASE_ARCH = arm
include ../../mk/spksrc.kernel.mk
|
Zetten/spksrc
|
kernel/syno-hi3535-6.1/Makefile
|
Makefile
|
bsd-3-clause
| 144 | 19.571429 | 33 | 0.708333 | false |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.llvm;
import org.lwjgl.system.*;
import org.lwjgl.system.libffi.*;
import static org.lwjgl.system.APIUtil.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.libffi.LibFFI.*;
/**
* Instances of this interface may be passed to the {@link ClangIndex#clang_Type_visitFields Type_visitFields} method.
*
* <h3>Type</h3>
*
* <pre><code>
* enum CXVisitorResult (*{@link #invoke}) (
* CXCursor C,
* CXClientData client_data
* )</code></pre>
*/
@FunctionalInterface
@NativeType("enum CXVisitorResult (*) (CXCursor, CXClientData)")
public interface CXFieldVisitorI extends CallbackI {
FFICIF CIF = apiCreateCIF(
FFI_DEFAULT_ABI,
ffi_type_uint32,
apiCreateStruct(ffi_type_uint32, ffi_type_sint32, apiCreateArray(ffi_type_pointer, 3)), ffi_type_pointer
);
@Override
default FFICIF getCallInterface() { return CIF; }
@Override
default void callback(long ret, long args) {
int __result = invoke(
CXCursor.create(memGetAddress(args)),
memGetAddress(memGetAddress(args + POINTER_SIZE))
);
apiClosureRet(ret, __result);
}
/**
* Visitor invoked for each field found by a traversal.
*
* <p>This visitor function will be invoked for each field found by {@link ClangIndex#clang_Type_visitFields Type_visitFields}. Its first argument is the cursor being visited, its second argument
* is the client data provided to {@code clang_Type_visitFields}.</p>
*
* <p>The visitor should return one of the {@code CXVisitorResult} values to direct {@code {@link ClangIndex#clang_Type_visitFields Type_visitFields}}.</p>
*/
@NativeType("enum CXVisitorResult") int invoke(CXCursor C, @NativeType("CXClientData") long client_data);
}
|
LWJGL-CI/lwjgl3
|
modules/lwjgl/llvm/src/generated/java/org/lwjgl/llvm/CXFieldVisitorI.java
|
Java
|
bsd-3-clause
| 1,950 | 32.637931 | 199 | 0.685641 | false |
#!/usr/bin/env bash
# installation settings
PROJECT='workspace' # we would want a name passed to it via te first argument,
DB='fcc_provision' # the name of postgreSQL DB we need to provision, maybe
# This file is executed by root user - sudo not needed
# But do not create any directory
# which vagrant user might need access to later in su mode
# use su - vagrant -c syntax
export DEBIAN_FRONTEND=noninteractive
echo ---------------------------------------------
echo Running vagrant provisioning
echo ---------------------------------------------
# install heroku toolbelt
echo -------------- Installing heroku toolbelt -------------------------
#wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh
# These shell script snippets are directly taken from heroku installation script
# We want to avoid the apt-get update
# add heroku repository to apt
echo deb http://toolbelt.heroku.com/ubuntu ./ > /etc/apt/sources.list.d/heroku.list
# install heroku's release key for package verification
wget -O- https://toolbelt.heroku.com/apt/release.key 2>&1 | apt-key add -
# install jdk
apt-get update -y
apt-get install software-properties-common build-essential dos2unix man curl heroku-toolbelt postgresql postgresql-contrib -y --no-install-recommends
echo -------------- Installing Java --------------------------------------
add-apt-repository ppa:openjdk-r/ppa -y > /dev/null 2>&1
# This is a must or the next install won't work
apt-get update -y
apt-get install openjdk-8-jdk -y --no-install-recommends
# install jetty
apt-get install jetty libjetty8-extra-java libjetty8-java libjetty-extra-java libjetty-extra libjetty-java-doc jetty8 libjetty8-java-doc libjetty-java jsvc default-jre-headless apache2-utils adduser -y --no-install-recommends # wow!
# install the cli
echo -------------- Installing Heroku CLI ---------------------------------
su - vagrant -c "heroku --version > /dev/null 2>&1"
echo -------------- Installing Clojure ------------------------------------
# install leiningen
su - vagrant << END_OF_LEIN
echo 'Downloading lein installer...'
sudo curl -o /usr/local/bin/lein https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein > /dev/null 2>&1
sudo chown vagrant /usr/local/bin/lein
chmod a+x /usr/local/bin/lein
echo 'Installing clojure and compojure'
cd /vagrant/${PROJECT} && lein deps > /dev/null 2>&1
END_OF_LEIN
echo -------------- Setting Up PostgreSQL ------------------------------------
# TODO: change the password encryption in pg_hba.conf to md5
# so that authentication works right.
su - postgres -c "createuser -s vagrant"
su - vagrant -c "createdb ${DB}"
echo -------------- Setting Up Bashrc ------------------------------------
su - vagrant -c "cp /vagrant/.bashrc /home/vagrant/"
su - vagrant -c "mkdir /home/vagrant/.configs"
su - vagrant -c "cp /vagrant/zeus.sh /home/vagrant/.configs/zeus"
# If you are on Windows host, with Git checkout windows line terminator style CRLF
# this comes in handy
su - vagrant -c "dos2unix /home/vagrant/.bashrc > /dev/null 2>&1"
# Make sure on first login, user gets to workspace
echo "cd /vagrant/${PROJECT} >> /home/vagrant/.bashrc"
echo "---------------------------------------------"
echo " Done! Run vagrant ssh to start working "
echo "---------------------------------------------"
|
byteknacker/fcc-python-vagrant
|
clojure/clojure-provision.sh
|
Shell
|
bsd-3-clause
| 3,301 | 44.847222 | 232 | 0.645865 | false |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.CP.FD.Example
-- path :: ModelInt -> ModelCol -> (ModelInt -> ModelInt) -> (ModelInt -> ModelInt) -> ModelCol
-- row :: ModelInt -> ModelCol -> ModelInt -> ModelCol
-- col :: ModelInt -> ModelCol -> ModelInt -> ModelCol
path nc ne l r c = slice l $ xmap (\k -> nc*(r k)+(c k)) (0 @.. (ne-1))
row nc ne l i = path nc ne l (const i) id
col nc ne l i = path nc ne l id (const i)
model :: ExampleModel (ModelInt,ModelInt,ModelInt)
model (v,k,lambda) = exists $ \mm -> do
let b = (v*(v-1)*lambda) `div` (k*(k-1))
let r = (lambda*(v-1)) `div` (k-1)
size mm @= b*v
let p r c = mm!(r*b+c)
mm `allin` (cte 0,cte 1)
loopall (0,v-1) $ \rr -> xsum (row b b mm rr) @= r
loopall (0,b-1) $ \cc -> xsum (col b v mm cc) @= k
loopall (0,v-1) $ \r1 -> do
loopall (r1+1,v-1) $ \r2 -> do
xsum (xmap (\i -> (p r1 i) * (p r2 i)) (0 @.. (b-1))) @= lambda
return mm
main = example_sat_main_void (\_ -> model (6,3,2))
|
neothemachine/monadiccp
|
examples/BIBD.hs
|
Haskell
|
bsd-3-clause
| 1,005 | 33.655172 | 95 | 0.559204 | false |
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H
#define GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H
#include <grpc/grpc_security.h>
#include <grpc++/support/config.h>
#include <grpc++/credentials.h>
namespace grpc {
class SecureCredentials GRPC_FINAL : public Credentials {
public:
explicit SecureCredentials(grpc_credentials* c_creds) : c_creds_(c_creds) {}
~SecureCredentials() GRPC_OVERRIDE { grpc_credentials_release(c_creds_); }
grpc_credentials* GetRawCreds() { return c_creds_; }
bool ApplyToCall(grpc_call* call) GRPC_OVERRIDE;
std::shared_ptr<grpc::Channel> CreateChannel(
const string& target, const grpc::ChannelArguments& args) GRPC_OVERRIDE;
SecureCredentials* AsSecureCredentials() GRPC_OVERRIDE { return this; }
private:
grpc_credentials* const c_creds_;
};
} // namespace grpc
#endif // GRPC_INTERNAL_CPP_CLIENT_SECURE_CREDENTIALS_H
|
fichter/grpc
|
src/cpp/client/secure_credentials.h
|
C
|
bsd-3-clause
| 2,459 | 39.311475 | 78 | 0.755998 | false |
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class RangeTests(TranspileTestCase):
pass
class BuiltinRangeFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["range"]
not_implemented = [
'test_bool',
]
|
cflee/voc
|
tests/builtins/test_range.py
|
Python
|
bsd-3-clause
| 269 | 19.692308 | 76 | 0.732342 | false |
#if defined (STM32PLUS_F0_51) || defined (STM32PLUS_F0_30) || defined (STM32PLUS_F0_42)
/**
******************************************************************************
* @file stm32f0xx_exti.h
* @author MCD Application Team
* @version V1.5.0
* @date 05-December-2014
* @brief This file contains all the functions prototypes for the EXTI
* firmware library
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F0XX_EXTI_H
#define __STM32F0XX_EXTI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "fwlib/f0/cmsis/ST/STM32F0xx/Include/stm32f0xx.h"
/** @addtogroup STM32F0xx_StdPeriph_Driver
* @{
*/
/** @addtogroup EXTI
* @{
*/
/* Exported types ------------------------------------------------------------*/
/**
* @brief EXTI mode enumeration
*/
typedef enum
{
EXTI_Mode_Interrupt = 0x00,
EXTI_Mode_Event = 0x04
}EXTIMode_TypeDef;
#define IS_EXTI_MODE(MODE) (((MODE) == EXTI_Mode_Interrupt) || ((MODE) == EXTI_Mode_Event))
/**
* @brief EXTI Trigger enumeration
*/
typedef enum
{
EXTI_Trigger_Rising = 0x08,
EXTI_Trigger_Falling = 0x0C,
EXTI_Trigger_Rising_Falling = 0x10
}EXTITrigger_TypeDef;
#define IS_EXTI_TRIGGER(TRIGGER) (((TRIGGER) == EXTI_Trigger_Rising) || \
((TRIGGER) == EXTI_Trigger_Falling) || \
((TRIGGER) == EXTI_Trigger_Rising_Falling))
/**
* @brief EXTI Init Structure definition
*/
typedef struct
{
uint32_t EXTI_Line; /*!< Specifies the EXTI lines to be enabled or disabled.
This parameter can be any combination of @ref EXTI_Lines */
EXTIMode_TypeDef EXTI_Mode; /*!< Specifies the mode for the EXTI lines.
This parameter can be a value of @ref EXTIMode_TypeDef */
EXTITrigger_TypeDef EXTI_Trigger; /*!< Specifies the trigger signal active edge for the EXTI lines.
This parameter can be a value of @ref EXTIMode_TypeDef */
FunctionalState EXTI_LineCmd; /*!< Specifies the new state of the selected EXTI lines.
This parameter can be set either to ENABLE or DISABLE */
}EXTI_InitTypeDef;
/* Exported constants --------------------------------------------------------*/
/** @defgroup EXTI_Exported_Constants
* @{
*/
/** @defgroup EXTI_Lines
* @{
*/
#define EXTI_Line0 ((uint32_t)0x00000001) /*!< External interrupt line 0 */
#define EXTI_Line1 ((uint32_t)0x00000002) /*!< External interrupt line 1 */
#define EXTI_Line2 ((uint32_t)0x00000004) /*!< External interrupt line 2 */
#define EXTI_Line3 ((uint32_t)0x00000008) /*!< External interrupt line 3 */
#define EXTI_Line4 ((uint32_t)0x00000010) /*!< External interrupt line 4 */
#define EXTI_Line5 ((uint32_t)0x00000020) /*!< External interrupt line 5 */
#define EXTI_Line6 ((uint32_t)0x00000040) /*!< External interrupt line 6 */
#define EXTI_Line7 ((uint32_t)0x00000080) /*!< External interrupt line 7 */
#define EXTI_Line8 ((uint32_t)0x00000100) /*!< External interrupt line 8 */
#define EXTI_Line9 ((uint32_t)0x00000200) /*!< External interrupt line 9 */
#define EXTI_Line10 ((uint32_t)0x00000400) /*!< External interrupt line 10 */
#define EXTI_Line11 ((uint32_t)0x00000800) /*!< External interrupt line 11 */
#define EXTI_Line12 ((uint32_t)0x00001000) /*!< External interrupt line 12 */
#define EXTI_Line13 ((uint32_t)0x00002000) /*!< External interrupt line 13 */
#define EXTI_Line14 ((uint32_t)0x00004000) /*!< External interrupt line 14 */
#define EXTI_Line15 ((uint32_t)0x00008000) /*!< External interrupt line 15 */
#define EXTI_Line16 ((uint32_t)0x00010000) /*!< External interrupt line 16
Connected to the PVD Output,
not applicable for STM32F030 devices */
#define EXTI_Line17 ((uint32_t)0x00020000) /*!< Internal interrupt line 17
Connected to the RTC Alarm
event */
#define EXTI_Line18 ((uint32_t)0x00040000) /*!< Internal interrupt line 18
Connected to the USB
event, only applicable for
STM32F072 devices */
#define EXTI_Line19 ((uint32_t)0x00080000) /*!< Internal interrupt line 19
Connected to the RTC Tamper
and Time Stamp events */
#define EXTI_Line20 ((uint32_t)0x00100000) /*!< Internal interrupt line 20
Connected to the RTC wakeup
event, only applicable for
STM32F072 devices */
#define EXTI_Line21 ((uint32_t)0x00200000) /*!< Internal interrupt line 21
Connected to the Comparator 1
event, only applicable for STM32F051
ans STM32F072 devices */
#define EXTI_Line22 ((uint32_t)0x00400000) /*!< Internal interrupt line 22
Connected to the Comparator 2
event, only applicable for STM32F051
and STM32F072 devices */
#define EXTI_Line23 ((uint32_t)0x00800000) /*!< Internal interrupt line 23
Connected to the I2C1 wakeup
event, not applicable for STM32F030 devices */
#define EXTI_Line25 ((uint32_t)0x02000000) /*!< Internal interrupt line 25
Connected to the USART1 wakeup
event, not applicable for STM32F030 devices */
#define EXTI_Line26 ((uint32_t)0x04000000) /*!< Internal interrupt line 26
Connected to the USART2 wakeup
event, applicable only for
STM32F072 devices */
#define EXTI_Line27 ((uint32_t)0x08000000) /*!< Internal interrupt line 27
Connected to the CEC wakeup
event, applicable only for STM32F051
and STM32F072 devices */
#define EXTI_Line31 ((uint32_t)0x80000000) /*!< Internal interrupt line 31
Connected to the VDD USB monitor
event, applicable only for
STM32F072 devices */
#define IS_EXTI_LINE(LINE) ((((LINE) & (uint32_t)0x71000000) == 0x00) && ((LINE) != (uint16_t)0x00))
#define IS_GET_EXTI_LINE(LINE) (((LINE) == EXTI_Line0) || ((LINE) == EXTI_Line1) || \
((LINE) == EXTI_Line2) || ((LINE) == EXTI_Line3) || \
((LINE) == EXTI_Line4) || ((LINE) == EXTI_Line5) || \
((LINE) == EXTI_Line6) || ((LINE) == EXTI_Line7) || \
((LINE) == EXTI_Line8) || ((LINE) == EXTI_Line9) || \
((LINE) == EXTI_Line10) || ((LINE) == EXTI_Line11) || \
((LINE) == EXTI_Line12) || ((LINE) == EXTI_Line13) || \
((LINE) == EXTI_Line14) || ((LINE) == EXTI_Line15) || \
((LINE) == EXTI_Line16) || ((LINE) == EXTI_Line17) || \
((LINE) == EXTI_Line18) || ((LINE) == EXTI_Line19) || \
((LINE) == EXTI_Line20) || ((LINE) == EXTI_Line21) || \
((LINE) == EXTI_Line22) || ((LINE) == EXTI_Line23) || \
((LINE) == EXTI_Line25) || ((LINE) == EXTI_Line26) || \
((LINE) == EXTI_Line27) || ((LINE) == EXTI_Line31))
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
/* Function used to set the EXTI configuration to the default reset state *****/
void EXTI_DeInit(void);
/* Initialization and Configuration functions *********************************/
void EXTI_Init(EXTI_InitTypeDef* EXTI_InitStruct);
void EXTI_StructInit(EXTI_InitTypeDef* EXTI_InitStruct);
void EXTI_GenerateSWInterrupt(uint32_t EXTI_Line);
/* Interrupts and flags management functions **********************************/
FlagStatus EXTI_GetFlagStatus(uint32_t EXTI_Line);
void EXTI_ClearFlag(uint32_t EXTI_Line);
ITStatus EXTI_GetITStatus(uint32_t EXTI_Line);
void EXTI_ClearITPendingBit(uint32_t EXTI_Line);
#ifdef __cplusplus
}
#endif
#endif /* __STM32F0XX_EXTI_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
#endif
|
punkkeks/stm32plus
|
lib/fwlib/f0/stdperiph/inc/stm32f0xx_exti.h
|
C
|
bsd-3-clause
| 10,622 | 47.724771 | 101 | 0.482489 | false |
package org.motechproject.http.agent.service;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.http.agent.components.SynchronousCall;
import org.motechproject.http.agent.listener.HttpClientEventListener;
import org.motechproject.event.MotechEvent;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
public class SynchronousCallTest {
private SynchronousCall synchronousCall;
@Mock
private HttpClientEventListener mockHttpClientEventListener;
@Test
public void shouldInvokeHttpClientEventListenerDirectly() {
initMocks(this);
synchronousCall = new SynchronousCall(mockHttpClientEventListener);
MotechEvent motechEvent = new MotechEvent("subject");
synchronousCall.send(motechEvent);
verify(mockHttpClientEventListener).handle(motechEvent);
}
}
|
bruceMacLeod/motech-server-pillreminder-0.18
|
utils/http-agent/http-agent/src/test/java/org/motechproject/http/agent/service/SynchronousCallTest.java
|
Java
|
bsd-3-clause
| 883 | 32.961538 | 75 | 0.790487 | false |
<?php
namespace Application\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
// A feedback form model
class ContactForm extends Form
{
// Constructor.
public function __construct()
{
// Define form name
parent::__construct('contact-form');
// Set POST method for this form
$this->setAttribute('method', 'post');
// (Optionally) set action for this form
$this->setAttribute('action', '/contactus');
$this->addElements();
$this->addInputFilter();
}
protected function addElements()
{
// Add "email" field
$this->add(array(
'type' => 'text',
'name' => 'email',
'attributes' => array(
'id' => 'email',
),
'options' => array(
'label' => 'Your E-mail',
),
));
// Add "subject" field
$this->add(array(
'type' => 'text',
'name' => 'subject',
'attributes' => array(
'id' => 'subject'
),
'options' => array(
'label' => 'Subject',
),
));
// Add "body" field
$this->add(array(
'type' => 'textarea',
'name' => 'body',
'attributes' => array(
'id' => 'body'
),
'options' => array(
'label' => 'Message',
),
));
$this->add(array(
'type' => 'radio',
'name' => 'payment',
'options' => array(
//'label' => 'Payment',
'value_options' => array(
'pay' => 'Paypal',
'credit' => 'Credit Card',
),
'Separator' => ' ',
),
));
// Add the CSRF field
$this->add(array(
'type' => 'csrf',
'name' => 'csrf',
'options' => array(
'csrf_options' => array(
'timeout' => 600
)
),
));
$this->add(array(
'type' => 'captcha',
'name' => 'captcha',
'attributes' => array(
),
'options' => array(
'label' => 'Human check',
'captcha' => array(
'class' => 'Image',
'imgDir' => 'public/img/captcha',
'suffix' => '.png',
'imgUrl' => '/img/captcha/',
'imgAlt' => 'CAPTCHA Image',
'font' => './public/fonts/ThorneShaded.ttf',
'fsize' => 24,
'width' => 350,
'height' => 100,
'expiration' => 600,
'dotNoiseLevel' => 40,
'lineNoiseLevel' => 3
),
),
));
// Add the submit button
$this->add(array(
'type' => 'submit',
'name' => 'submit',
'attributes' => array(
'value' => 'Submit',
'id' => 'submitbutton',
),
));
}
private function addInputFilter()
{
$inputFilter = new InputFilter();
$this->setInputFilter($inputFilter);
$inputFilter->add(array(
'name' => 'email',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'allow' => \Zend\Validator\Hostname::ALLOW_DNS,
'useMxCheck' => false,
),
),
),
)
);
$inputFilter->add(array(
'name' => 'subject',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
array('name' => 'StripTags'),
array('name' => 'StripNewLines'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => 1,
'max' => 128
),
),
),
)
);
$inputFilter->add(array(
'name' => 'body',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => 1,
'max' => 4096
),
),
),
)
);
}
}
|
SjayTheGift/IntergratedProject-2
|
module/Application/src/Application/Form/ContactForm.php
|
PHP
|
bsd-3-clause
| 5,623 | 28.080214 | 81 | 0.30642 | false |
/*
Copyright (c) 2012-2015, The Saffire Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Saffire Group the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __VM_THREAD_H__
#define __VM_THREAD_H__
#include <saffire/vm/stackframe.h>
#include <saffire/objects/objects.h>
/**
* All data relevant to a single thread
*/
typedef struct _thread {
t_vm_stackframe *frame; // Current frame
t_exception_object *exception; // Current thrown exception
t_vm_stackframe *exception_frame; // Snapshot of the frame on when the exception was thrown
char *locale; // Current global locale
} t_thread;
t_thread *current_thread;
t_thread *thread_new(void);
void thread_free(t_thread *);
t_thread *thread_get_current(void);
t_vm_stackframe *thread_get_current_frame(void);
t_vm_stackframe *thread_get_exception_frame(void);
void thread_set_current_frame(t_vm_stackframe *frame);
void thread_create_exception(t_exception_object *exception, int code, const char *message);
void thread_create_exception_printf(t_exception_object *exception, int code, const char *format, ...);
void thread_clear_exception(void);
void thread_set_exception(t_exception_object *exception);
t_exception_object *thread_get_exception(void);
int thread_exception_thrown(void);
t_exception_object *thread_save_exception(void);
void thread_restore_exception(t_exception_object *exception);
void thread_dump_exception(t_exception_object *exception);
#endif
|
steazzalini/saffire
|
include/saffire/vm/thread.h
|
C
|
bsd-3-clause
| 2,996 | 44.393939 | 106 | 0.724967 | false |
//
// ComboSequenceComposer.java
// xal
//
// Created by Tom Pelaia on 9/25/08.
// Copyright 2008 Oak Ridge National Lab. All rights reserved.
//
package xal.extension.application.smf;
import xal.extension.bricks.WindowReference;
import xal.smf.*;
import xal.tools.ResourceManager;
import java.net.URL;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
/** Displays a dialog box which allows the user to compose a combo sequence by selecting the end sequences. */
class ComboSequenceComposer {
/** accelerator */
final private Accelerator ACCELERATOR;
/** sequence at the head of the combo */
private AcceleratorSeq _startSequence;
/** sequence at the end of the combo */
private AcceleratorSeq _endSequence;
/** indicates whether the user has confirmed the combo */
private boolean _confirmed;
/** Constructor */
private ComboSequenceComposer( final Accelerator accelerator ) {
ACCELERATOR = accelerator;
_confirmed = false;
}
/** determine whether the user has confirmed the combo sequence */
private boolean isConfirmed() {
return _confirmed;
}
/** set whether the current combo is confirmed */
private void setConfirmed( final boolean confirmed ) {
_confirmed = confirmed;
}
/** get the accelerator */
private Accelerator getAccelerator() {
return ACCELERATOR;
}
/** set the start sequence */
private void setStartSequence( final AcceleratorSeq sequence ) {
_startSequence = sequence;
}
/** set the end sequence */
private void setEndSequence( final AcceleratorSeq sequence ) {
_endSequence = sequence;
}
/** determine whether a combo sequence is possible between the start and end sequences */
private boolean isValidCombo() {
if ( _startSequence != null && _endSequence != null && _startSequence != _endSequence ) {
return generateCombo( "validate" ) != null;
}
else {
return false;
}
}
/** generate a combo sequence using the given name and the sequences between the start and end sequences */
private AcceleratorSeqCombo generateCombo( final String name ) {
final String comboID = name != null ? name : suggestedComboName();
return _startSequence != null && _endSequence != null ? AcceleratorSeqCombo.getInstanceForRange( comboID, _startSequence, _endSequence ) : null;
}
/** generate a suggested name based on the start and end sequence */
private String suggestedComboName() {
final StringBuffer buffer = new StringBuffer();
if ( _startSequence != null ) buffer.append( _startSequence.getId() );
buffer.append( ":" );
if ( _endSequence != null ) buffer.append( _endSequence.getId() );
return buffer.toString();
}
/**
* Display a dialog for selecting the start and end sequences to form a combo sequence joining them.
* @param accelerator pass the Accelerator object here from main routine
* @param owner the window that owns the sequence selector
*/
@SuppressWarnings( "unchecked" ) // need to cast from untyped JList
static public AcceleratorSeqCombo composeComboSequence( final Accelerator accelerator, final JFrame owner ) {
final ComboSequenceComposer composer = new ComboSequenceComposer( accelerator );
final List<AcceleratorSeq> sequences = accelerator.getSequences();
final URL uiURL = ResourceManager.getResourceURL( ComboSequenceComposer.class, "ui.bricks" );
final WindowReference windowReference = new WindowReference( uiURL, "ComboSequenceComposer", owner, "Combo Sequence Composer" );
final JDialog dialog = (JDialog)windowReference.getWindow();
final JTextField comboNameField = (JTextField)windowReference.getView( "Combo Name Field" );
final JButton cancelButton = (JButton)windowReference.getView( "CancelButton" );
cancelButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
dialog.setVisible( false );
}
});
final JButton okayButton = (JButton)windowReference.getView( "OkayButton" );
okayButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
composer.setConfirmed( true );
dialog.setVisible( false );
}
});
final Vector<String> sequenceNames = new Vector<String>();
for ( final AcceleratorSeq sequence : sequences ) {
sequenceNames.add( sequence.getId() );
}
final JList<String> startSequenceList = (JList<String>)windowReference.getView( "Start Sequence List" );
startSequenceList.setListData( sequenceNames );
startSequenceList.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( final ListSelectionEvent event ) {
if ( !event.getValueIsAdjusting() ) {
final Object selection = startSequenceList.getSelectedValue();
final AcceleratorSeq sequence = selection != null ? accelerator.getSequence( selection.toString() ) : null;
composer.setStartSequence( sequence );
comboNameField.setText( composer.suggestedComboName() );
okayButton.setEnabled( composer.isValidCombo() );
}
}
});
final JList<String> endSequenceList = (JList<String>)windowReference.getView( "End Sequence List" );
endSequenceList.setListData( sequenceNames );
endSequenceList.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( final ListSelectionEvent event ) {
if ( !event.getValueIsAdjusting() ) {
final Object selection = endSequenceList.getSelectedValue();
final AcceleratorSeq sequence = selection != null ? accelerator.getSequence( selection.toString() ) : null;
composer.setEndSequence( sequence );
comboNameField.setText( composer.suggestedComboName() );
okayButton.setEnabled( composer.isValidCombo() );
}
}
});
dialog.setLocationRelativeTo( owner );
dialog.setVisible( true );
return composer.isConfirmed() ? composer.generateCombo( comboNameField.getText() ) : null;
}
}
|
openxal/openxal
|
extensions/application/src/xal/extension/application/smf/ComboSequenceComposer.java
|
Java
|
bsd-3-clause
| 5,982 | 33.37931 | 146 | 0.722166 | false |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/download/download_manager_service.h"
#include "base/android/jni_string.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/android/download_controller_android.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/download_item.h"
#include "jni/DownloadManagerService_jni.h"
#include "ui/base/l10n/l10n_util.h"
using base::android::JavaParamRef;
using base::android::ConvertJavaStringToUTF8;
using base::android::ConvertUTF8ToJavaString;
namespace {
// The retry interval when resuming/canceling a download. This is needed because
// when the browser process is launched, we have to wait until the download
// history get loaded before a download can be resumed/cancelled. However,
// we don't want to retry after a long period of time as the same download Id
// can be reused later.
const int kRetryIntervalInMilliseconds = 3000;
}
// static
bool DownloadManagerService::RegisterDownloadManagerService(JNIEnv* env) {
return RegisterNativesImpl(env);
}
static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& jobj) {
Profile* profile = ProfileManager::GetActiveUserProfile();
content::DownloadManager* manager =
content::BrowserContext::GetDownloadManager(profile);
DownloadManagerService* service =
new DownloadManagerService(env, jobj, manager);
return reinterpret_cast<intptr_t>(service);
}
DownloadManagerService::DownloadManagerService(
JNIEnv* env,
jobject obj,
content::DownloadManager* manager)
: java_ref_(env, obj), manager_(manager) {
content::DownloadControllerAndroid::Get()->SetDefaultDownloadFileName(
l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME));
manager_->AddObserver(this);
}
DownloadManagerService::~DownloadManagerService() {
if (manager_)
manager_->RemoveObserver(this);
}
void DownloadManagerService::ResumeDownload(JNIEnv* env,
jobject obj,
uint32_t download_id,
jstring fileName) {
ResumeDownloadInternal(download_id, ConvertJavaStringToUTF8(env, fileName),
true);
}
void DownloadManagerService::CancelDownload(JNIEnv* env,
jobject obj,
uint32_t download_id) {
CancelDownloadInternal(download_id, true);
}
void DownloadManagerService::PauseDownload(JNIEnv* env,
jobject obj,
uint32_t download_id) {
content::DownloadItem* item = manager_->GetDownload(download_id);
if (item)
item->Pause();
}
void DownloadManagerService::ManagerGoingDown(
content::DownloadManager* manager) {
manager_ = nullptr;
}
void DownloadManagerService::ResumeDownloadItem(content::DownloadItem* item,
const std::string& fileName) {
if (!item->CanResume()) {
OnResumptionFailed(item->GetId(), fileName);
return;
}
item->AddObserver(content::DownloadControllerAndroid::Get());
item->Resume();
if (!resume_callback_for_testing_.is_null())
resume_callback_for_testing_.Run(true);
}
void DownloadManagerService::ResumeDownloadInternal(uint32_t download_id,
const std::string& fileName,
bool retry) {
if (!manager_) {
OnResumptionFailed(download_id, fileName);
return;
}
content::DownloadItem* item = manager_->GetDownload(download_id);
if (item) {
ResumeDownloadItem(item, fileName);
return;
}
if (!retry) {
OnResumptionFailed(download_id, fileName);
return;
}
// Post a delayed task to wait for the download history to load the download
// item. If the download item is not loaded when the delayed task runs, show
// an download failed notification. Alternatively, we can have the
// DownloadManager inform us when a download item is created. However, there
// is no guarantee when the download item will be created, since the newly
// created item might not be loaded from download history. So user might wait
// indefinitely to see the failed notification. See http://crbug.com/577893.
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&DownloadManagerService::ResumeDownloadInternal,
base::Unretained(this), download_id, fileName, false),
base::TimeDelta::FromMilliseconds(kRetryIntervalInMilliseconds));
}
void DownloadManagerService::CancelDownloadInternal(uint32_t download_id,
bool retry) {
if (!manager_)
return;
content::DownloadItem* item = manager_->GetDownload(download_id);
if (item) {
item->Cancel(true);
return;
}
if (retry) {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE, base::Bind(&DownloadManagerService::CancelDownloadInternal,
base::Unretained(this), download_id, false),
base::TimeDelta::FromMilliseconds(kRetryIntervalInMilliseconds));
}
}
void DownloadManagerService::OnResumptionFailed(uint32_t download_id,
const std::string& fileName) {
if (!java_ref_.is_null()) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_DownloadManagerService_onResumptionFailed(
env, java_ref_.obj(), download_id,
ConvertUTF8ToJavaString(env, fileName).obj());
}
if (!resume_callback_for_testing_.is_null())
resume_callback_for_testing_.Run(false);
}
|
ds-hwang/chromium-crosswalk
|
chrome/browser/android/download/download_manager_service.cc
|
C++
|
bsd-3-clause
| 5,982 | 37.346154 | 80 | 0.667001 | false |
package org.broadinstitute.hellbender.utils.codecs.gencode;
/**
* A Gencode GTF Feature representing a CDS.
*
* A GTF Feature represents one row of a GTF File.
* The specification of a GTF file is defined here:
* http://mblab.wustl.edu/GTF22.html
*
* Created by jonn on 7/25/17.
*/
final public class GencodeGtfCDSFeature extends GencodeGtfFeature {
private GencodeGtfCDSFeature(final String[] gtfFields) {
super(gtfFields);
}
public static GencodeGtfFeature create(final String[] gtfFields) {
return new GencodeGtfCDSFeature(gtfFields);
}
private GencodeGtfCDSFeature(final GencodeGtfFeatureBaseData baseData) {
super(baseData);
}
public static GencodeGtfFeature create(final GencodeGtfFeatureBaseData baseData) {
return new GencodeGtfCDSFeature(baseData);
}
}
|
magicDGS/gatk
|
src/main/java/org/broadinstitute/hellbender/utils/codecs/gencode/GencodeGtfCDSFeature.java
|
Java
|
bsd-3-clause
| 839 | 27.931034 | 86 | 0.727056 | false |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/bind_fwd.hpp" header
// -- DO NOT modify by hand!
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace mpl {
template<
typename F
>
struct bind0;
template<
typename F, typename T1
>
struct bind1;
template<
typename F, typename T1, typename T2
>
struct bind2;
template<
typename F, typename T1, typename T2, typename T3
>
struct bind3;
template<
typename F, typename T1, typename T2, typename T3, typename T4
>
struct bind4;
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct bind5;
}}
|
verma/PDAL
|
boost/boost/mpl/aux_/preprocessed/msvc70/bind_fwd.hpp
|
C++
|
bsd-3-clause
| 878 | 18.086957 | 89 | 0.679954 | false |
#
# MITK specific cross plattform install macro
#
# Usage: MITK_INSTALL_TARGETS(target1 [target2] ....)
#
macro(MITK_INSTALL_TARGETS)
MACRO_PARSE_ARGUMENTS(_install "TARGETS;EXECUTABLES;PLUGINS;LIBRARY_DIRS" "GLOB_PLUGINS" ${ARGN})
list(APPEND _install_TARGETS ${_install_DEFAULT_ARGS})
# TODO: how to supply the correct intermediate directory??
# CMAKE_CFG_INTDIR is not expanded to actual values inside the install(CODE "...") macro ...
set(intermediate_dir .)
if(WIN32 AND NOT MINGW)
set(intermediate_dir Release)
endif()
if(QT_LIBRARY_DIR MATCHES "^(/lib/|/lib32/|/lib64/|/usr/lib/|/usr/lib32/|/usr/lib64/|/usr/X11R6/)")
set(_qt_is_system_qt 1)
endif()
foreach(_target ${_install_EXECUTABLES})
get_target_property(_is_bundle ${_target} MACOSX_BUNDLE)
set(_qt_plugins_install_dirs "")
set(_qt_conf_install_dirs "")
set(_target_locations "")
if(APPLE)
if(_is_bundle)
set(_target_locations ${_target}.app)
set(${_target_locations}_qt_plugins_install_dir ${_target}.app/Contents/MacOS)
set(_bundle_dest_dir ${_target}.app/Contents/MacOS)
set(_qt_plugins_for_current_bundle ${_target}.app/Contents/MacOS)
set(_qt_conf_install_dirs ${_target}.app/Contents/Resources)
install(TARGETS ${_target} BUNDLE DESTINATION . )
else()
if(NOT MACOSX_BUNDLE_NAMES)
set(_qt_conf_install_dirs bin)
set(_target_locations bin/${_target})
set(${_target_locations}_qt_plugins_install_dir bin)
install(TARGETS ${_target} RUNTIME DESTINATION bin)
else()
foreach(bundle_name ${MACOSX_BUNDLE_NAMES})
list(APPEND _qt_conf_install_dirs ${bundle_name}.app/Contents/Resources)
set(_current_target_location ${bundle_name}.app/Contents/MacOS/${_target})
list(APPEND _target_locations ${_current_target_location})
set(${_current_target_location}_qt_plugins_install_dir ${bundle_name}.app/Contents/MacOS)
message( " set(${_current_target_location}_qt_plugins_install_dir ${bundle_name}.app/Contents/MacOS) ")
install(TARGETS ${_target} RUNTIME DESTINATION ${bundle_name}.app/Contents/MacOS/)
endforeach()
endif()
endif()
else()
set(_target_locations bin/${_target}${CMAKE_EXECUTABLE_SUFFIX})
set(${_target_locations}_qt_plugins_install_dir bin)
set(_qt_conf_install_dirs bin)
install(TARGETS ${_target} RUNTIME DESTINATION bin)
endif()
foreach(_target_location ${_target_locations})
if(NOT _qt_is_system_qt)
if(QT_PLUGINS_DIR)
if(WIN32)
install(DIRECTORY "${QT_PLUGINS_DIR}"
DESTINATION ${${_target_location}_qt_plugins_install_dir}
CONFIGURATIONS Release
FILES_MATCHING REGEX "[^4d]4?${CMAKE_SHARED_LIBRARY_SUFFIX}"
)
install(DIRECTORY "${QT_PLUGINS_DIR}"
DESTINATION ${${_target_location}_qt_plugins_install_dir}
CONFIGURATIONS Debug
FILES_MATCHING REGEX "d4?${CMAKE_SHARED_LIBRARY_SUFFIX}"
)
else(WIN32)
# install everything, see bug 7143
install(DIRECTORY "${QT_PLUGINS_DIR}"
DESTINATION ${${_target_location}_qt_plugins_install_dir}
FILES_MATCHING REGEX "${CMAKE_SHARED_LIBRARY_SUFFIX}"
)
endif(WIN32)
endif()
endif()
_fixup_target()
endforeach()
if(NOT _qt_is_system_qt)
#--------------------------------------------------------------------------------
# install a qt.conf file
# this inserts some cmake code into the install script to write the file
set(_qt_conf_plugin_install_prefix .)
if(APPLE)
set(_qt_conf_plugin_install_prefix ./MacOS)
endif()
foreach(_qt_conf_install_dir ${_qt_conf_install_dirs})
install(CODE "file(WRITE \"\${CMAKE_INSTALL_PREFIX}/${_qt_conf_install_dir}/qt.conf\" \"
[Paths]
Prefix=${_qt_conf_plugin_install_prefix}
\")")
endforeach()
endif()
endforeach()
endmacro()
|
rfloca/MITK
|
CMake/mitkMacroInstallTargets.cmake
|
CMake
|
bsd-3-clause
| 4,200 | 36.168142 | 116 | 0.596667 | false |
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __GRPC_INTERNAL_TRANSPORT_CHTTP2_FRAME_H__
#define __GRPC_INTERNAL_TRANSPORT_CHTTP2_FRAME_H__
#include <grpc/support/port_platform.h>
#include <grpc/support/slice.h>
/* Common definitions for frame handling in the chttp2 transport */
typedef enum {
GRPC_CHTTP2_PARSE_OK,
GRPC_CHTTP2_STREAM_ERROR,
GRPC_CHTTP2_CONNECTION_ERROR
} grpc_chttp2_parse_error;
typedef struct {
gpr_uint8 end_of_stream;
gpr_uint8 need_flush_reads;
gpr_uint8 metadata_boundary;
gpr_uint8 ack_settings;
gpr_uint8 send_ping_ack;
gpr_uint8 process_ping_reply;
gpr_uint8 goaway;
gpr_uint32 window_update;
gpr_uint32 goaway_last_stream_index;
gpr_uint32 goaway_error;
gpr_slice goaway_text;
} grpc_chttp2_parse_state;
#define GRPC_CHTTP2_FRAME_DATA 0
#define GRPC_CHTTP2_FRAME_HEADER 1
#define GRPC_CHTTP2_FRAME_CONTINUATION 9
#define GRPC_CHTTP2_FRAME_RST_STREAM 3
#define GRPC_CHTTP2_FRAME_SETTINGS 4
#define GRPC_CHTTP2_FRAME_PING 6
#define GRPC_CHTTP2_FRAME_GOAWAY 7
#define GRPC_CHTTP2_FRAME_WINDOW_UPDATE 8
#define GRPC_CHTTP2_MAX_PAYLOAD_LENGTH ((1 << 14) - 1)
#define GRPC_CHTTP2_DATA_FLAG_END_STREAM 1
#define GRPC_CHTTP2_FLAG_ACK 1
#define GRPC_CHTTP2_DATA_FLAG_END_HEADERS 4
#define GRPC_CHTTP2_DATA_FLAG_PADDED 8
#define GRPC_CHTTP2_FLAG_HAS_PRIORITY 0x20
#endif /* __GRPC_INTERNAL_TRANSPORT_CHTTP2_FRAME_H__ */
|
nathanielmanistaatgoogle/grpc
|
src/core/transport/chttp2/frame.h
|
C
|
bsd-3-clause
| 2,908 | 35.35 | 73 | 0.759629 | false |
# Tera Committer
为什么你需要成为tera的committer?因为你一旦成为了tera的committer,就意味着你的代码将有机会运行在一个实际的大规模生产环境中。同时,你的代码也能得到足够的应用场景验证,对实践大规模分布式编程,非常有帮助。因此期待你的加入!:-)
# 如何成为Tera Committer
作为一个tera的commiter,首要条件是需要对tera代码有足够的熟悉度。因此,除了熟读代码之外,要将tera真正run起来,这样能加深系统的理解。一旦发现问题,可以通过提issue和pull request,获得问题反馈和解决(当然,我们更欢迎自己解决问题的同学)。
提交issue时,如果是提交bug,需要描述复现方法、具体日志记录等;如果是新功能,则需要描述思路、附带设计文档,方便其他人review你的想法。
提交pull request时,需要按照一定的[规则](../en/contributor.md)填写commit log。
当你给tera开发了一到两个核心功能之后,就表明你对tera有了一定的把控能力,此时我们会将你列入Tera Committer的候选列表,经过内部讨论通过,就能正式成为tera的committer!:-)
# 如何进行Code Review
对他人的代码进行Code Review时,需要本着认真负责的原则,并按一定规则进行:
1、每个pr惯例是需要得到两个LGTM,然后由最后一个LGTM的人执行merge;
2、merge pr时,提pr的人,不能merge自己的pr;
3、code review时,避免两个都是新的commiter,完成LGTM就自行merge代码;
4、push代码时,禁止rebase,否则难以看出代码diff;
5、merge代码时,需要将commit log进行合并,每个pr保证只有一个commint log。
ps:每个commiter都应自觉遵守上述规则。
|
BaiduPS/tera
|
doc/cn/to_be_a_committer.md
|
Markdown
|
bsd-3-clause
| 1,816 | 36.043478 | 137 | 0.857981 | false |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/popup_message.h"
#include "ash/wm/window_animations.h"
#include "grit/ash_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/bubble/bubble_delegate.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
const int kMessageTopBottomMargin = 10;
const int kMessageLeftRightMargin = 10;
const int kMessageMinHeight = 29 - 2 * kMessageTopBottomMargin;
const SkColor kMessageTextColor = SkColorSetRGB(0x22, 0x22, 0x22);
// The maximum width of the Message bubble. Borrowed the value from
// ash/message/message_controller.cc
const int kMessageMaxWidth = 250;
// The offset for the Message bubble - making sure that the bubble is flush
// with the shelf. The offset includes the arrow size in pixels as well as
// the activation bar and other spacing elements.
const int kArrowOffsetLeftRight = 11;
const int kArrowOffsetTopBottom = 7;
// The number of pixels between the icon and the text.
const int kHorizontalPopupPaddingBetweenItems = 10;
// The number of pixels between the text items.
const int kVerticalPopupPaddingBetweenItems = 10;
} // namespace
// The implementation of Message of the launcher.
class PopupMessage::MessageBubble : public views::BubbleDelegateView {
public:
MessageBubble(const base::string16& caption,
const base::string16& message,
IconType message_type,
views::View* anchor,
views::BubbleBorder::Arrow arrow_orientation,
const gfx::Size& size_override,
int arrow_offset);
void Close();
private:
// views::View overrides:
gfx::Size GetPreferredSize() const override;
// Each component (width/height) can force a size override for that component
// if not 0.
gfx::Size size_override_;
DISALLOW_COPY_AND_ASSIGN(MessageBubble);
};
PopupMessage::MessageBubble::MessageBubble(const base::string16& caption,
const base::string16& message,
IconType message_type,
views::View* anchor,
views::BubbleBorder::Arrow arrow,
const gfx::Size& size_override,
int arrow_offset)
: views::BubbleDelegateView(anchor, arrow),
size_override_(size_override) {
gfx::Insets insets = gfx::Insets(kArrowOffsetTopBottom,
kArrowOffsetLeftRight,
kArrowOffsetTopBottom,
kArrowOffsetLeftRight);
// An anchor can have an asymmetrical border for spacing reasons. Adjust the
// anchor location for this.
if (anchor->border())
insets += anchor->border()->GetInsets();
set_anchor_view_insets(insets);
set_close_on_esc(false);
set_close_on_deactivate(false);
set_can_activate(false);
set_accept_events(false);
set_margins(gfx::Insets(kMessageTopBottomMargin, kMessageLeftRightMargin,
kMessageTopBottomMargin, kMessageLeftRightMargin));
set_shadow(views::BubbleBorder::SMALL_SHADOW);
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
kHorizontalPopupPaddingBetweenItems));
// Here is the layout:
// arrow_offset (if not 0)
// |-------------|
// | ^
// +-------------------------------------------------+
// -| |-
// icon | [!] Caption in bold which can be multi line | caption_label
// -| |-
// | Message text which can be multi line | message_label
// | as well. |
// | |-
// +-------------------------------------------------+
// |------------details container--------------|
// Note that the icon, caption and message are optional.
// Add the icon to the first column (if there is one).
if (message_type != ICON_NONE) {
views::ImageView* icon = new views::ImageView();
icon->SetImage(
bundle.GetImageNamed(IDR_AURA_WARNING_ICON).ToImageSkia());
icon->SetVerticalAlignment(views::ImageView::LEADING);
AddChildView(icon);
}
// Create a container for the text items and use it as second column.
views::View* details = new views::View();
AddChildView(details);
details->SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kVertical, 0, 0, kVerticalPopupPaddingBetweenItems));
// The caption label.
if (!caption.empty()) {
views::Label* caption_label = new views::Label(caption);
caption_label->SetMultiLine(true);
caption_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
caption_label->SetFontList(
bundle.GetFontList(ui::ResourceBundle::BoldFont));
caption_label->SetEnabledColor(kMessageTextColor);
details->AddChildView(caption_label);
}
// The message label.
if (!message.empty()) {
views::Label* message_label = new views::Label(message);
message_label->SetMultiLine(true);
message_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
message_label->SetEnabledColor(kMessageTextColor);
details->AddChildView(message_label);
}
views::BubbleDelegateView::CreateBubble(this);
// Change the arrow offset if needed.
if (arrow_offset) {
// With the creation of the bubble, the bubble got already placed (and
// possibly re-oriented to fit on the screen). Since it is not possible to
// set the arrow offset before the creation, we need to set the offset,
// and the orientation variables again and force a re-placement.
GetBubbleFrameView()->bubble_border()->set_arrow_offset(arrow_offset);
GetBubbleFrameView()->bubble_border()->set_arrow(arrow);
SetAlignment(views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR);
}
}
void PopupMessage::MessageBubble::Close() {
if (GetWidget())
GetWidget()->Close();
}
gfx::Size PopupMessage::MessageBubble::GetPreferredSize() const {
gfx::Size pref_size = views::BubbleDelegateView::GetPreferredSize();
// Override the size with either the provided size or adjust it to not
// violate our minimum / maximum sizes.
if (size_override_.height())
pref_size.set_height(size_override_.height());
else if (pref_size.height() < kMessageMinHeight)
pref_size.set_height(kMessageMinHeight);
if (size_override_.width())
pref_size.set_width(size_override_.width());
else if (pref_size.width() > kMessageMaxWidth)
pref_size.set_width(kMessageMaxWidth);
return pref_size;
}
PopupMessage::PopupMessage(const base::string16& caption,
const base::string16& message,
IconType message_type,
views::View* anchor,
views::BubbleBorder::Arrow arrow,
const gfx::Size& size_override,
int arrow_offset)
: view_(NULL) {
view_ = new MessageBubble(
caption, message, message_type, anchor, arrow, size_override,
arrow_offset);
widget_ = view_->GetWidget();
gfx::NativeView native_view = widget_->GetNativeView();
wm::SetWindowVisibilityAnimationType(
native_view, wm::WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL);
wm::SetWindowVisibilityAnimationTransition(
native_view, wm::ANIMATE_HIDE);
view_->GetWidget()->Show();
}
PopupMessage::~PopupMessage() {
CancelHidingAnimation();
Close();
}
void PopupMessage::Close() {
if (view_) {
view_->Close();
view_ = NULL;
widget_ = NULL;
}
}
void PopupMessage::CancelHidingAnimation() {
if (!widget_ || !widget_->GetNativeView())
return;
gfx::NativeView native_view = widget_->GetNativeView();
wm::SetWindowVisibilityAnimationTransition(
native_view, wm::ANIMATE_NONE);
}
} // namespace ash
|
sgraham/nope
|
ash/popup_message.cc
|
C++
|
bsd-3-clause
| 8,476 | 36.504425 | 79 | 0.627183 | false |
/**
* \file delta_test.cpp
* \brief Unit-tests for the discrete delta functions.
* \copyright Copyright (c) 2016-2018, Barba group. All rights reserved.
* \license BSD 3-Clause License.
*/
#include <algorithm>
#include <random>
#include <vector>
#include <petsc.h>
#include "gtest/gtest.h"
#include "petibm/delta.h"
using namespace petibm::delta;
// check value is zero outside region of influence
TEST(deltaRomaEtAlTest, zeroOutside)
{
const PetscReal h = 1.0;
EXPECT_EQ(0.0, Roma_et_al_1999(1.5, h));
EXPECT_EQ(0.0, Roma_et_al_1999(2.0, h));
}
// check maximum value at 0
TEST(deltaRomaEtAlTest, maximumValue)
{
const PetscReal h = 1.0;
EXPECT_EQ(2.0 / 3.0, Roma_et_al_1999(0.0, h));
}
// check delta function is monotonically decreasing
TEST(deltaRomaEtAlTest, decreasingInfluence)
{
const PetscReal h = 1.0;
// create a sorted vector of random reals between 0.0 and 1.5
std::vector<PetscReal> vals(10);
std::default_random_engine engine;
std::uniform_real_distribution<PetscReal> distrib(0.0, 1.5);
std::generate(vals.begin(), vals.end(), [&]() { return distrib(engine); });
std::sort(vals.begin(), vals.end());
// assert decreasing influence as the distance increases
for (unsigned int i = 0; i < vals.size() - 1; i++)
ASSERT_GT(Roma_et_al_1999(vals[i], h), Roma_et_al_1999(vals[i + 1], h));
}
// Run all tests
int main(int argc, char **argv)
{
PetscErrorCode ierr, status;
::testing::InitGoogleTest(&argc, argv);
ierr = PetscInitialize(&argc, &argv, nullptr, nullptr); CHKERRQ(ierr);
status = RUN_ALL_TESTS();
ierr = PetscFinalize(); CHKERRQ(ierr);
return status;
} // main
|
mesnardo/PetIBM
|
tests/misc/delta_test.cpp
|
C++
|
bsd-3-clause
| 1,685 | 26.622951 | 80 | 0.664688 | false |
//===-- ClangFormatFuzzer.cpp - Fuzz the Clang format tool ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements a function that runs Clang format on a single
/// input. This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "clang/Format/Format.h"
extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
// FIXME: fuzz more things: different styles, different style features.
std::string s((const char *)data, size);
auto Style = getGoogleStyle(clang::format::FormatStyle::LK_Cpp);
Style.ColumnLimit = 60;
auto Replaces = reformat(Style, s, clang::tooling::Range(0, s.size()));
auto Result = applyAllReplacements(s, Replaces);
// Output must be checked, as otherwise we crash.
if (!Result) {}
return 0;
}
|
youtube/cobalt
|
third_party/llvm-project/clang/tools/clang-format/fuzzer/ClangFormatFuzzer.cpp
|
C++
|
bsd-3-clause
| 1,100 | 36.931034 | 80 | 0.577273 | false |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/fetch/FetchManager.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8ThrowException.h"
#include "core/dom/DOMArrayBuffer.h"
#include "core/dom/Document.h"
#include "core/fetch/FetchUtils.h"
#include "core/fileapi/Blob.h"
#include "core/frame/Frame.h"
#include "core/frame/SubresourceIntegrity.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/ThreadableLoader.h"
#include "core/loader/ThreadableLoaderClient.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
#include "modules/fetch/Body.h"
#include "modules/fetch/BodyStreamBuffer.h"
#include "modules/fetch/CompositeDataConsumerHandle.h"
#include "modules/fetch/DataConsumerHandleUtil.h"
#include "modules/fetch/FetchFormDataConsumerHandle.h"
#include "modules/fetch/FetchRequestData.h"
#include "modules/fetch/Response.h"
#include "modules/fetch/ResponseInit.h"
#include "platform/HTTPNames.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceResponse.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/WebURLRequest.h"
#include "wtf/HashSet.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
namespace blink {
namespace {
bool IsRedirectStatusCode(int statusCode)
{
return (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307 || statusCode == 308);
}
} // namespace
class FetchManager::Loader final : public GarbageCollectedFinalized<FetchManager::Loader>, public ThreadableLoaderClient {
USING_PRE_FINALIZER(FetchManager::Loader, dispose);
public:
static Loader* create(ExecutionContext* executionContext, FetchManager* fetchManager, ScriptPromiseResolver* resolver, FetchRequestData* request, bool isIsolatedWorld)
{
return new Loader(executionContext, fetchManager, resolver, request, isIsolatedWorld);
}
~Loader() override;
DECLARE_VIRTUAL_TRACE();
void didReceiveResponse(unsigned long, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>) override;
void didFinishLoading(unsigned long, double) override;
void didFail(const ResourceError&) override;
void didFailAccessControlCheck(const ResourceError&) override;
void didFailRedirectCheck() override;
void start();
void dispose();
class SRIVerifier final : public GarbageCollectedFinalized<SRIVerifier>, public WebDataConsumerHandle::Client {
public:
// Promptly clear m_handle and m_reader.
EAGERLY_FINALIZE();
// SRIVerifier takes ownership of |handle| and |response|.
// |updater| must be garbage collected. The other arguments
// all must have the lifetime of the give loader.
SRIVerifier(PassOwnPtr<WebDataConsumerHandle> handle, CompositeDataConsumerHandle::Updater* updater, Response* response, FetchManager::Loader* loader, String integrityMetadata, const KURL& url)
: m_handle(std::move(handle))
, m_updater(updater)
, m_response(response)
, m_loader(loader)
, m_integrityMetadata(integrityMetadata)
, m_url(url)
, m_finished(false)
{
m_reader = m_handle->obtainReader(this);
}
void didGetReadable() override
{
ASSERT(m_reader);
ASSERT(m_loader);
ASSERT(m_response);
WebDataConsumerHandle::Result r = WebDataConsumerHandle::Ok;
while (r == WebDataConsumerHandle::Ok) {
const void* buffer;
size_t size;
r = m_reader->beginRead(&buffer, WebDataConsumerHandle::FlagNone, &size);
if (r == WebDataConsumerHandle::Ok) {
m_buffer.append(static_cast<const char*>(buffer), size);
m_reader->endRead(size);
}
}
if (r == WebDataConsumerHandle::ShouldWait)
return;
String errorMessage = "Unknown error occurred while trying to verify integrity.";
m_finished = true;
if (r == WebDataConsumerHandle::Done) {
if (SubresourceIntegrity::CheckSubresourceIntegrity(m_integrityMetadata, m_buffer.data(), m_buffer.size(), m_url, *m_loader->document(), errorMessage)) {
m_updater->update(FetchFormDataConsumerHandle::create(m_buffer.data(), m_buffer.size()));
m_loader->m_resolver->resolve(m_response);
m_loader->m_resolver.clear();
// FetchManager::Loader::didFinishLoading() can
// be called before didGetReadable() is called
// when the data is ready. In that case,
// didFinishLoading() doesn't clean up and call
// notifyFinished(), so it is necessary to
// explicitly finish the loader here.
if (m_loader->m_didFinishLoading)
m_loader->loadSucceeded();
return;
}
}
m_updater->update(createUnexpectedErrorDataConsumerHandle());
m_loader->performNetworkError(errorMessage);
}
bool isFinished() const { return m_finished; }
DEFINE_INLINE_TRACE()
{
visitor->trace(m_updater);
visitor->trace(m_response);
visitor->trace(m_loader);
}
private:
OwnPtr<WebDataConsumerHandle> m_handle;
Member<CompositeDataConsumerHandle::Updater> m_updater;
Member<Response> m_response;
Member<FetchManager::Loader> m_loader;
String m_integrityMetadata;
KURL m_url;
OwnPtr<WebDataConsumerHandle::Reader> m_reader;
Vector<char> m_buffer;
bool m_finished;
};
private:
Loader(ExecutionContext*, FetchManager*, ScriptPromiseResolver*, FetchRequestData*, bool isIsolatedWorld);
void performBasicFetch();
void performNetworkError(const String& message);
void performHTTPFetch(bool corsFlag, bool corsPreflightFlag);
void performDataFetch();
void failed(const String& message);
void notifyFinished();
Document* document() const;
void loadSucceeded();
Member<FetchManager> m_fetchManager;
Member<ScriptPromiseResolver> m_resolver;
Member<FetchRequestData> m_request;
OwnPtr<ThreadableLoader> m_loader;
bool m_failed;
bool m_finished;
int m_responseHttpStatusCode;
Member<SRIVerifier> m_integrityVerifier;
bool m_didFinishLoading;
bool m_isIsolatedWorld;
Member<ExecutionContext> m_executionContext;
};
FetchManager::Loader::Loader(ExecutionContext* executionContext, FetchManager* fetchManager, ScriptPromiseResolver* resolver, FetchRequestData* request, bool isIsolatedWorld)
: m_fetchManager(fetchManager)
, m_resolver(resolver)
, m_request(request)
, m_failed(false)
, m_finished(false)
, m_responseHttpStatusCode(0)
, m_integrityVerifier(nullptr)
, m_didFinishLoading(false)
, m_isIsolatedWorld(isIsolatedWorld)
, m_executionContext(executionContext)
{
ThreadState::current()->registerPreFinalizer(this);
}
FetchManager::Loader::~Loader()
{
ASSERT(!m_loader);
}
DEFINE_TRACE(FetchManager::Loader)
{
visitor->trace(m_fetchManager);
visitor->trace(m_resolver);
visitor->trace(m_request);
visitor->trace(m_integrityVerifier);
visitor->trace(m_executionContext);
}
void FetchManager::Loader::didReceiveResponse(unsigned long, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
{
ASSERT(handle);
if (response.url().protocolIs("blob") && response.httpStatusCode() == 404) {
// "If |blob| is null, return a network error."
// https://fetch.spec.whatwg.org/#concept-basic-fetch
performNetworkError("Blob not found.");
return;
}
if (response.url().protocolIs("blob") && response.httpStatusCode() == 405) {
performNetworkError("Only 'GET' method is allowed for blob URLs.");
return;
}
m_responseHttpStatusCode = response.httpStatusCode();
FetchRequestData::Tainting tainting = m_request->responseTainting();
if (response.url().protocolIsData()) {
if (m_request->url() == response.url()) {
// A direct request to data.
tainting = FetchRequestData::BasicTainting;
} else {
// A redirect to data: scheme occured.
// Redirects to data URLs are rejected by the spec because
// same-origin data-URL flag is unset, except for no-cors mode.
// TODO(hiroshige): currently redirects to data URLs in no-cors
// mode is also rejected by Chromium side.
switch (m_request->mode()) {
case WebURLRequest::FetchRequestModeNoCORS:
tainting = FetchRequestData::OpaqueTainting;
break;
case WebURLRequest::FetchRequestModeSameOrigin:
case WebURLRequest::FetchRequestModeCORS:
case WebURLRequest::FetchRequestModeCORSWithForcedPreflight:
case WebURLRequest::FetchRequestModeNavigate:
performNetworkError("Fetch API cannot load " + m_request->url().getString() + ". Redirects to data: URL are allowed only when mode is \"no-cors\".");
return;
}
}
} else if (!SecurityOrigin::create(response.url())->isSameSchemeHostPort(m_request->origin().get())) {
// Recompute the tainting if the request was redirected to a different
// origin.
switch (m_request->mode()) {
case WebURLRequest::FetchRequestModeSameOrigin:
ASSERT_NOT_REACHED();
break;
case WebURLRequest::FetchRequestModeNoCORS:
tainting = FetchRequestData::OpaqueTainting;
break;
case WebURLRequest::FetchRequestModeCORS:
case WebURLRequest::FetchRequestModeCORSWithForcedPreflight:
tainting = FetchRequestData::CORSTainting;
break;
case WebURLRequest::FetchRequestModeNavigate:
RELEASE_NOTREACHED();
break;
}
}
if (response.wasFetchedViaServiceWorker()) {
switch (response.serviceWorkerResponseType()) {
case WebServiceWorkerResponseTypeBasic:
case WebServiceWorkerResponseTypeDefault:
tainting = FetchRequestData::BasicTainting;
break;
case WebServiceWorkerResponseTypeCORS:
tainting = FetchRequestData::CORSTainting;
break;
case WebServiceWorkerResponseTypeOpaque:
tainting = FetchRequestData::OpaqueTainting;
break;
case WebServiceWorkerResponseTypeOpaqueRedirect:
// ServiceWorker can't respond to the request from fetch() with an
// opaque redirect response.
case WebServiceWorkerResponseTypeError:
// When ServiceWorker respond to the request from fetch() with an
// error response, FetchManager::Loader::didFail() must be called
// instead.
RELEASE_NOTREACHED();
break;
}
}
ScriptState* scriptState = m_resolver->getScriptState();
FetchResponseData* responseData = nullptr;
CompositeDataConsumerHandle::Updater* updater = nullptr;
if (m_request->integrity().isEmpty())
responseData = FetchResponseData::createWithBuffer(new BodyStreamBuffer(scriptState, createFetchDataConsumerHandleFromWebHandle(std::move(handle))));
else
responseData = FetchResponseData::createWithBuffer(new BodyStreamBuffer(scriptState, createFetchDataConsumerHandleFromWebHandle(CompositeDataConsumerHandle::create(createWaitingDataConsumerHandle(), &updater))));
responseData->setStatus(response.httpStatusCode());
responseData->setStatusMessage(response.httpStatusText());
for (auto& it : response.httpHeaderFields())
responseData->headerList()->append(it.key, it.value);
responseData->setURL(response.url());
responseData->setMIMEType(response.mimeType());
responseData->setResponseTime(response.responseTime());
FetchResponseData* taintedResponse = nullptr;
if (IsRedirectStatusCode(m_responseHttpStatusCode)) {
Vector<String> locations;
responseData->headerList()->getAll(HTTPNames::Location, locations);
if (locations.size() > 1) {
performNetworkError("Multiple Location header.");
return;
}
if (locations.size() == 1) {
KURL locationURL(m_request->url(), locations[0]);
if (!locationURL.isValid()) {
performNetworkError("Invalid Location header.");
return;
}
ASSERT(m_request->redirect() == WebURLRequest::FetchRedirectModeManual);
taintedResponse = responseData->createOpaqueRedirectFilteredResponse();
}
// When the location header doesn't exist, we don't treat the response
// as a redirect response, and execute tainting.
}
if (!taintedResponse) {
switch (tainting) {
case FetchRequestData::BasicTainting:
taintedResponse = responseData->createBasicFilteredResponse();
break;
case FetchRequestData::CORSTainting:
taintedResponse = responseData->createCORSFilteredResponse();
break;
case FetchRequestData::OpaqueTainting:
taintedResponse = responseData->createOpaqueFilteredResponse();
break;
}
}
Response* r = Response::create(m_resolver->getExecutionContext(), taintedResponse);
if (response.url().protocolIsData()) {
// An "Access-Control-Allow-Origin" header is added for data: URLs
// but no headers except for "Content-Type" should exist,
// according to the spec:
// https://fetch.spec.whatwg.org/#concept-basic-fetch
// "... return a response whose header list consist of a single header
// whose name is `Content-Type` and value is the MIME type and
// parameters returned from obtaining a resource"
r->headers()->headerList()->remove(HTTPNames::Access_Control_Allow_Origin);
}
r->headers()->setGuard(Headers::ImmutableGuard);
if (m_request->integrity().isEmpty()) {
m_resolver->resolve(r);
m_resolver.clear();
} else {
ASSERT(!m_integrityVerifier);
m_integrityVerifier = new SRIVerifier(std::move(handle), updater, r, this, m_request->integrity(), response.url());
}
}
void FetchManager::Loader::didFinishLoading(unsigned long, double)
{
m_didFinishLoading = true;
// If there is an integrity verifier, and it has not already finished, it
// will take care of finishing the load or performing a network error when
// verification is complete.
if (m_integrityVerifier && !m_integrityVerifier->isFinished())
return;
loadSucceeded();
}
void FetchManager::Loader::didFail(const ResourceError& error)
{
if (error.isCancellation() || error.isTimeout() || error.domain() != errorDomainBlinkInternal)
failed(String());
else
failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription());
}
void FetchManager::Loader::didFailAccessControlCheck(const ResourceError& error)
{
if (error.isCancellation() || error.isTimeout() || error.domain() != errorDomainBlinkInternal)
failed(String());
else
failed("Fetch API cannot load " + error.failingURL() + ". " + error.localizedDescription());
}
void FetchManager::Loader::didFailRedirectCheck()
{
failed("Fetch API cannot load " + m_request->url().getString() + ". Redirect failed.");
}
Document* FetchManager::Loader::document() const
{
if (m_executionContext->isDocument()) {
return toDocument(m_executionContext);
}
return nullptr;
}
void FetchManager::Loader::loadSucceeded()
{
ASSERT(!m_failed);
m_finished = true;
if (document() && document()->frame() && document()->frame()->page()
&& m_responseHttpStatusCode >= 200 && m_responseHttpStatusCode < 300) {
document()->frame()->page()->chromeClient().ajaxSucceeded(document()->frame());
}
InspectorInstrumentation::didFinishFetch(m_executionContext, this, m_request->method(), m_request->url().getString());
notifyFinished();
}
void FetchManager::Loader::start()
{
// "1. If |request|'s url contains a Known HSTS Host, modify it per the
// requirements of the 'URI [sic] Loading and Port Mapping' chapter of HTTP
// Strict Transport Security."
// FIXME: Implement this.
// "2. If |request|'s referrer is not none, set |request|'s referrer to the
// result of invoking determine |request|'s referrer."
// We set the referrer using workerGlobalScope's URL in
// WorkerThreadableLoader.
// "3. If |request|'s synchronous flag is unset and fetch is not invoked
// recursively, run the remaining steps asynchronously."
// We don't support synchronous flag.
// "4. Let response be the value corresponding to the first matching
// statement:"
// "- should fetching |request| be blocked as mixed content returns blocked"
// We do mixed content checking in ResourceFetcher.
// "- should fetching |request| be blocked as content security returns
// blocked"
if (!ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) && !m_executionContext->contentSecurityPolicy()->allowConnectToSource(m_request->url())) {
// "A network error."
performNetworkError("Refused to connect to '" + m_request->url().elidedString() + "' because it violates the document's Content Security Policy.");
return;
}
// "- |request|'s url's origin is |request|'s origin and the |CORS flag| is
// unset"
// "- |request|'s url's scheme is 'data' and |request|'s same-origin data
// URL flag is set"
// "- |request|'s url's scheme is 'about'"
// Note we don't support to call this method with |CORS flag|
// "- |request|'s mode is |navigate|".
if ((SecurityOrigin::create(m_request->url())->isSameSchemeHostPortAndSuborigin(m_request->origin().get()))
|| (m_request->url().protocolIsData() && m_request->sameOriginDataURLFlag())
|| (m_request->url().protocolIsAbout())
|| (m_request->mode() == WebURLRequest::FetchRequestModeNavigate)) {
// "The result of performing a basic fetch using request."
performBasicFetch();
return;
}
// "- |request|'s mode is |same-origin|"
if (m_request->mode() == WebURLRequest::FetchRequestModeSameOrigin) {
// "A network error."
performNetworkError("Fetch API cannot load " + m_request->url().getString() + ". Request mode is \"same-origin\" but the URL\'s origin is not same as the request origin " + m_request->origin()->toString() + ".");
return;
}
// "- |request|'s mode is |no CORS|"
if (m_request->mode() == WebURLRequest::FetchRequestModeNoCORS) {
// "Set |request|'s response tainting to |opaque|."
m_request->setResponseTainting(FetchRequestData::OpaqueTainting);
// "The result of performing a basic fetch using |request|."
performBasicFetch();
return;
}
// "- |request|'s url's scheme is not one of 'http' and 'https'"
// This may include other HTTP-like schemes if the embedder has added them
// to SchemeRegistry::registerURLSchemeAsSupportingFetchAPI.
if (!SchemeRegistry::shouldTreatURLSchemeAsSupportingFetchAPI(m_request->url().protocol())) {
// "A network error."
performNetworkError("Fetch API cannot load " + m_request->url().getString() + ". URL scheme must be \"http\" or \"https\" for CORS request.");
return;
}
// "- |request|'s mode is |CORS-with-forced-preflight|.
// "- |request|'s unsafe request flag is set and either |request|'s method
// is not a simple method or a header in |request|'s header list is not a
// simple header"
if (m_request->mode() == WebURLRequest::FetchRequestModeCORSWithForcedPreflight
|| (m_request->unsafeRequestFlag()
&& (!FetchUtils::isSimpleMethod(m_request->method())
|| m_request->headerList()->containsNonSimpleHeader()))) {
// "Set |request|'s response tainting to |CORS|."
m_request->setResponseTainting(FetchRequestData::CORSTainting);
// "The result of performing an HTTP fetch using |request| with the
// |CORS flag| and |CORS preflight flag| set."
performHTTPFetch(true, true);
return;
}
// "- Otherwise
// Set |request|'s response tainting to |CORS|."
m_request->setResponseTainting(FetchRequestData::CORSTainting);
// "The result of performing an HTTP fetch using |request| with the
// |CORS flag| set."
performHTTPFetch(true, false);
}
void FetchManager::Loader::dispose()
{
// Prevent notification
m_fetchManager = nullptr;
if (m_loader) {
m_loader->cancel();
m_loader.clear();
}
m_executionContext = nullptr;
}
void FetchManager::Loader::performBasicFetch()
{
// "To perform a basic fetch using |request|, switch on |request|'s url's
// scheme, and run the associated steps:"
if (SchemeRegistry::shouldTreatURLSchemeAsSupportingFetchAPI(m_request->url().protocol())) {
// "Return the result of performing an HTTP fetch using |request|."
performHTTPFetch(false, false);
} else if (m_request->url().protocolIsData()) {
performDataFetch();
} else if (m_request->url().protocolIs("blob")) {
performHTTPFetch(false, false);
} else {
// FIXME: implement other protocols.
performNetworkError("Fetch API cannot load " + m_request->url().getString() + ". URL scheme \"" + m_request->url().protocol() + "\" is not supported.");
}
}
void FetchManager::Loader::performNetworkError(const String& message)
{
failed(message);
}
void FetchManager::Loader::performHTTPFetch(bool corsFlag, bool corsPreflightFlag)
{
ASSERT(SchemeRegistry::shouldTreatURLSchemeAsSupportingFetchAPI(m_request->url().protocol()) || (m_request->url().protocolIs("blob") && !corsFlag && !corsPreflightFlag));
// CORS preflight fetch procedure is implemented inside DocumentThreadableLoader.
// "1. Let |HTTPRequest| be a copy of |request|, except that |HTTPRequest|'s
// body is a tee of |request|'s body."
// We use ResourceRequest class for HTTPRequest.
// FIXME: Support body.
ResourceRequest request(m_request->url());
request.setRequestContext(m_request->context());
request.setHTTPMethod(m_request->method());
request.setFetchRequestMode(m_request->mode());
request.setFetchCredentialsMode(m_request->credentials());
const Vector<OwnPtr<FetchHeaderList::Header>>& list = m_request->headerList()->list();
for (size_t i = 0; i < list.size(); ++i) {
request.addHTTPHeaderField(AtomicString(list[i]->first), AtomicString(list[i]->second));
}
if (m_request->method() != HTTPNames::GET && m_request->method() != HTTPNames::HEAD) {
if (m_request->buffer())
request.setHTTPBody(m_request->buffer()->drainAsFormData());
if (m_request->attachedCredential())
request.setAttachedCredential(m_request->attachedCredential());
}
request.setFetchRedirectMode(m_request->redirect());
request.setUseStreamOnResponse(true);
request.setExternalRequestStateFromRequestorAddressSpace(m_executionContext->securityContext().addressSpace());
// "2. Append `Referer`/empty byte sequence, if |HTTPRequest|'s |referrer|
// is none, and `Referer`/|HTTPRequest|'s referrer, serialized and utf-8
// encoded, otherwise, to HTTPRequest's header list.
//
// The following code also invokes "determine request's referrer" which is
// written in "Main fetch" operation.
const ReferrerPolicy referrerPolicy = m_request->getReferrerPolicy() == ReferrerPolicyDefault ? m_executionContext->getReferrerPolicy() : m_request->getReferrerPolicy();
const String referrerString = m_request->referrerString() == FetchRequestData::clientReferrerString() ? m_executionContext->outgoingReferrer() : m_request->referrerString();
// Note that generateReferrer generates |no-referrer| from |no-referrer|
// referrer string (i.e. String()).
request.setHTTPReferrer(SecurityPolicy::generateReferrer(referrerPolicy, m_request->url(), referrerString));
request.setSkipServiceWorker(m_isIsolatedWorld);
// "3. Append `Host`, ..."
// FIXME: Implement this when the spec is fixed.
// "4.If |HTTPRequest|'s force Origin header flag is set, append `Origin`/
// |HTTPRequest|'s origin, serialized and utf-8 encoded, to |HTTPRequest|'s
// header list."
// We set Origin header in updateRequestForAccessControl() called from
// DocumentThreadableLoader::makeCrossOriginAccessRequest
// "5. Let |credentials flag| be set if either |HTTPRequest|'s credentials
// mode is |include|, or |HTTPRequest|'s credentials mode is |same-origin|
// and the |CORS flag| is unset, and unset otherwise.
ResourceLoaderOptions resourceLoaderOptions;
resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
if (m_request->credentials() == WebURLRequest::FetchCredentialsModeInclude
|| m_request->credentials() == WebURLRequest::FetchCredentialsModePassword
|| (m_request->credentials() == WebURLRequest::FetchCredentialsModeSameOrigin && !corsFlag)) {
resourceLoaderOptions.allowCredentials = AllowStoredCredentials;
}
if (m_request->credentials() == WebURLRequest::FetchCredentialsModeInclude
|| m_request->credentials() == WebURLRequest::FetchCredentialsModePassword) {
resourceLoaderOptions.credentialsRequested = ClientRequestedCredentials;
}
resourceLoaderOptions.securityOrigin = m_request->origin().get();
ThreadableLoaderOptions threadableLoaderOptions;
threadableLoaderOptions.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceContentSecurityPolicy;
if (corsPreflightFlag)
threadableLoaderOptions.preflightPolicy = ForcePreflight;
switch (m_request->mode()) {
case WebURLRequest::FetchRequestModeSameOrigin:
threadableLoaderOptions.crossOriginRequestPolicy = DenyCrossOriginRequests;
break;
case WebURLRequest::FetchRequestModeNoCORS:
threadableLoaderOptions.crossOriginRequestPolicy = AllowCrossOriginRequests;
break;
case WebURLRequest::FetchRequestModeCORS:
case WebURLRequest::FetchRequestModeCORSWithForcedPreflight:
threadableLoaderOptions.crossOriginRequestPolicy = UseAccessControl;
break;
case WebURLRequest::FetchRequestModeNavigate:
// Using DenyCrossOriginRequests here to reduce the security risk.
// "navigate" request is only available in ServiceWorker.
threadableLoaderOptions.crossOriginRequestPolicy = DenyCrossOriginRequests;
break;
}
InspectorInstrumentation::willStartFetch(m_executionContext, this);
m_loader = ThreadableLoader::create(*m_executionContext, this, threadableLoaderOptions, resourceLoaderOptions);
m_loader->start(request);
}
// performDataFetch() is almost the same as performHTTPFetch(), except for:
// - We set AllowCrossOriginRequests to allow requests to data: URLs in
// 'same-origin' mode.
// - We reject non-GET method.
void FetchManager::Loader::performDataFetch()
{
ASSERT(m_request->url().protocolIsData());
// Spec: https://fetch.spec.whatwg.org/#concept-basic-fetch
// If |request|'s method is `GET` .... Otherwise, return a network error.
if (m_request->method() != HTTPNames::GET) {
performNetworkError("Only 'GET' method is allowed for data URLs in Fetch API.");
return;
}
ResourceRequest request(m_request->url());
request.setRequestContext(m_request->context());
request.setUseStreamOnResponse(true);
request.setHTTPMethod(m_request->method());
request.setFetchRedirectMode(WebURLRequest::FetchRedirectModeError);
// We intentionally skip 'setExternalRequestStateFromRequestorAddressSpace', as 'data:' can never be external.
ResourceLoaderOptions resourceLoaderOptions;
resourceLoaderOptions.dataBufferingPolicy = DoNotBufferData;
resourceLoaderOptions.securityOrigin = m_request->origin().get();
ThreadableLoaderOptions threadableLoaderOptions;
threadableLoaderOptions.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(m_executionContext) ? DoNotEnforceContentSecurityPolicy : EnforceContentSecurityPolicy;
threadableLoaderOptions.crossOriginRequestPolicy = AllowCrossOriginRequests;
InspectorInstrumentation::willStartFetch(m_executionContext, this);
m_loader = ThreadableLoader::create(*m_executionContext, this, threadableLoaderOptions, resourceLoaderOptions);
m_loader->start(request);
}
void FetchManager::Loader::failed(const String& message)
{
if (m_failed || m_finished)
return;
m_failed = true;
if (!message.isEmpty())
m_executionContext->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
if (m_resolver) {
if (!m_resolver->getExecutionContext() || m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
ScriptState* state = m_resolver->getScriptState();
ScriptState::Scope scope(state);
m_resolver->reject(V8ThrowException::createTypeError(state->isolate(), "Failed to fetch"));
}
InspectorInstrumentation::didFailFetch(m_executionContext, this);
notifyFinished();
}
void FetchManager::Loader::notifyFinished()
{
if (m_fetchManager)
m_fetchManager->onLoaderFinished(this);
}
FetchManager* FetchManager::create(ExecutionContext* executionContext)
{
return new FetchManager(executionContext);
}
FetchManager::FetchManager(ExecutionContext* executionContext)
: ContextLifecycleObserver(executionContext)
, m_isStopped(false)
{
}
ScriptPromise FetchManager::fetch(ScriptState* scriptState, FetchRequestData* request)
{
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
request->setContext(WebURLRequest::RequestContextFetch);
Loader* loader = Loader::create(getExecutionContext(), this, resolver, request, scriptState->world().isIsolatedWorld());
m_loaders.add(loader);
loader->start();
return promise;
}
void FetchManager::contextDestroyed()
{
ASSERT(!m_isStopped);
m_isStopped = true;
for (auto& loader : m_loaders)
loader->dispose();
}
void FetchManager::onLoaderFinished(Loader* loader)
{
m_loaders.remove(loader);
loader->dispose();
}
DEFINE_TRACE(FetchManager)
{
visitor->trace(m_loaders);
ContextLifecycleObserver::trace(visitor);
}
} // namespace blink
|
axinging/chromium-crosswalk
|
third_party/WebKit/Source/modules/fetch/FetchManager.cpp
|
C++
|
bsd-3-clause
| 31,645 | 41.533602 | 220 | 0.681087 | false |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.plugins.inapppurchase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import androidx.annotation.NonNull;
import com.android.billingclient.api.AccountIdentifiers;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.Purchase.PurchasesResult;
import com.android.billingclient.api.PurchaseHistoryRecord;
import com.android.billingclient.api.SkuDetails;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
public class TranslatorTest {
private static final String SKU_DETAIL_EXAMPLE_JSON =
"{\"productId\":\"example\",\"type\":\"inapp\",\"price\":\"$0.99\",\"price_amount_micros\":990000,\"price_currency_code\":\"USD\",\"title\":\"Example title\",\"description\":\"Example description.\",\"original_price\":\"$0.99\",\"original_price_micros\":990000}";
private static final String PURCHASE_EXAMPLE_JSON =
"{\"orderId\":\"foo\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\", \"obfuscatedAccountId\":\"Account101\", \"obfuscatedProfileId\": \"Profile105\"}";
@Before
public void setup() {
Locale locale = new Locale("en", "us");
Locale.setDefault(locale);
}
@Test
public void fromSkuDetail() throws JSONException {
final SkuDetails expected = new SkuDetails(SKU_DETAIL_EXAMPLE_JSON);
Map<String, Object> serialized = Translator.fromSkuDetail(expected);
assertSerialized(expected, serialized);
}
@Test
public void fromSkuDetailsList() throws JSONException {
final String SKU_DETAIL_EXAMPLE_2_JSON =
"{\"productId\":\"example2\",\"type\":\"inapp\",\"price\":\"$0.99\",\"price_amount_micros\":990000,\"price_currency_code\":\"USD\",\"title\":\"Example title\",\"description\":\"Example description.\",\"original_price\":\"$0.99\",\"original_price_micros\":990000}";
final List<SkuDetails> expected =
Arrays.asList(
new SkuDetails(SKU_DETAIL_EXAMPLE_JSON), new SkuDetails(SKU_DETAIL_EXAMPLE_2_JSON));
final List<HashMap<String, Object>> serialized = Translator.fromSkuDetailsList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromSkuDetailsList_null() {
assertEquals(Collections.emptyList(), Translator.fromSkuDetailsList(null));
}
@Test
public void fromPurchase() throws JSONException {
final Purchase expected = new Purchase(PURCHASE_EXAMPLE_JSON, "signature");
assertSerialized(expected, Translator.fromPurchase(expected));
}
@Test
public void fromPurchaseWithoutAccountIds() throws JSONException {
final Purchase expected =
new PurchaseWithoutAccountIdentifiers(PURCHASE_EXAMPLE_JSON, "signature");
Map<String, Object> serialized = Translator.fromPurchase(expected);
assertNotNull(serialized.get("orderId"));
assertNull(serialized.get("obfuscatedProfileId"));
assertNull(serialized.get("obfuscatedAccountId"));
}
@Test
public void fromPurchaseHistoryRecord() throws JSONException {
final PurchaseHistoryRecord expected =
new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, "signature");
assertSerialized(expected, Translator.fromPurchaseHistoryRecord(expected));
}
@Test
public void fromPurchasesHistoryRecordList() throws JSONException {
final String purchase2Json =
"{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}";
final String signature = "signature";
final List<PurchaseHistoryRecord> expected =
Arrays.asList(
new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, signature),
new PurchaseHistoryRecord(purchase2Json, signature));
final List<HashMap<String, Object>> serialized =
Translator.fromPurchaseHistoryRecordList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromPurchasesHistoryRecordList_null() {
assertEquals(Collections.emptyList(), Translator.fromPurchaseHistoryRecordList(null));
}
@Test
public void fromPurchasesList() throws JSONException {
final String purchase2Json =
"{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}";
final String signature = "signature";
final List<Purchase> expected =
Arrays.asList(
new Purchase(PURCHASE_EXAMPLE_JSON, signature), new Purchase(purchase2Json, signature));
final List<HashMap<String, Object>> serialized = Translator.fromPurchasesList(expected);
assertEquals(expected.size(), serialized.size());
assertSerialized(expected.get(0), serialized.get(0));
assertSerialized(expected.get(1), serialized.get(1));
}
@Test
public void fromPurchasesList_null() {
assertEquals(Collections.emptyList(), Translator.fromPurchasesList(null));
}
@Test
public void fromPurchasesResult() throws JSONException {
PurchasesResult result = mock(PurchasesResult.class);
final String purchase2Json =
"{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}";
final String signature = "signature";
final List<Purchase> expectedPurchases =
Arrays.asList(
new Purchase(PURCHASE_EXAMPLE_JSON, signature), new Purchase(purchase2Json, signature));
when(result.getPurchasesList()).thenReturn(expectedPurchases);
when(result.getResponseCode()).thenReturn(BillingClient.BillingResponseCode.OK);
BillingResult newBillingResult =
BillingResult.newBuilder()
.setDebugMessage("dummy debug message")
.setResponseCode(BillingClient.BillingResponseCode.OK)
.build();
when(result.getBillingResult()).thenReturn(newBillingResult);
final HashMap<String, Object> serialized = Translator.fromPurchasesResult(result);
assertEquals(BillingClient.BillingResponseCode.OK, serialized.get("responseCode"));
List<Map<String, Object>> serializedPurchases =
(List<Map<String, Object>>) serialized.get("purchasesList");
assertEquals(expectedPurchases.size(), serializedPurchases.size());
assertSerialized(expectedPurchases.get(0), serializedPurchases.get(0));
assertSerialized(expectedPurchases.get(1), serializedPurchases.get(1));
Map<String, Object> billingResultMap = (Map<String, Object>) serialized.get("billingResult");
assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode());
assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage());
}
@Test
public void fromBillingResult() throws JSONException {
BillingResult newBillingResult =
BillingResult.newBuilder()
.setDebugMessage("dummy debug message")
.setResponseCode(BillingClient.BillingResponseCode.OK)
.build();
Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult);
assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode());
assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage());
}
@Test
public void fromBillingResult_debugMessageNull() throws JSONException {
BillingResult newBillingResult =
BillingResult.newBuilder().setResponseCode(BillingClient.BillingResponseCode.OK).build();
Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult);
assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode());
assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage());
}
@Test
public void currencyCodeFromSymbol() {
assertEquals("$", Translator.currencySymbolFromCode("USD"));
try {
Translator.currencySymbolFromCode("EUROPACOIN");
fail("Translator should throw an exception");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
private void assertSerialized(SkuDetails expected, Map<String, Object> serialized) {
assertEquals(expected.getDescription(), serialized.get("description"));
assertEquals(expected.getFreeTrialPeriod(), serialized.get("freeTrialPeriod"));
assertEquals(expected.getIntroductoryPrice(), serialized.get("introductoryPrice"));
assertEquals(
expected.getIntroductoryPriceAmountMicros(),
serialized.get("introductoryPriceAmountMicros"));
assertEquals(expected.getIntroductoryPriceCycles(), serialized.get("introductoryPriceCycles"));
assertEquals(expected.getIntroductoryPricePeriod(), serialized.get("introductoryPricePeriod"));
assertEquals(expected.getPrice(), serialized.get("price"));
assertEquals(expected.getPriceAmountMicros(), serialized.get("priceAmountMicros"));
assertEquals(expected.getPriceCurrencyCode(), serialized.get("priceCurrencyCode"));
assertEquals("$", serialized.get("priceCurrencySymbol"));
assertEquals(expected.getSku(), serialized.get("sku"));
assertEquals(expected.getSubscriptionPeriod(), serialized.get("subscriptionPeriod"));
assertEquals(expected.getTitle(), serialized.get("title"));
assertEquals(expected.getType(), serialized.get("type"));
assertEquals(expected.getOriginalPrice(), serialized.get("originalPrice"));
assertEquals(
expected.getOriginalPriceAmountMicros(), serialized.get("originalPriceAmountMicros"));
}
private void assertSerialized(Purchase expected, Map<String, Object> serialized) {
assertEquals(expected.getOrderId(), serialized.get("orderId"));
assertEquals(expected.getPackageName(), serialized.get("packageName"));
assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime"));
assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken"));
assertEquals(expected.getSignature(), serialized.get("signature"));
assertEquals(expected.getOriginalJson(), serialized.get("originalJson"));
assertEquals(expected.getSku(), serialized.get("sku"));
assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload"));
assertEquals(expected.isAcknowledged(), serialized.get("isAcknowledged"));
assertEquals(expected.getPurchaseState(), serialized.get("purchaseState"));
assertNotNull(expected.getAccountIdentifiers().getObfuscatedAccountId());
assertEquals(
expected.getAccountIdentifiers().getObfuscatedAccountId(),
serialized.get("obfuscatedAccountId"));
assertNotNull(expected.getAccountIdentifiers().getObfuscatedProfileId());
assertEquals(
expected.getAccountIdentifiers().getObfuscatedProfileId(),
serialized.get("obfuscatedProfileId"));
}
private void assertSerialized(PurchaseHistoryRecord expected, Map<String, Object> serialized) {
assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime"));
assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken"));
assertEquals(expected.getSignature(), serialized.get("signature"));
assertEquals(expected.getOriginalJson(), serialized.get("originalJson"));
assertEquals(expected.getSku(), serialized.get("sku"));
assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload"));
}
}
class PurchaseWithoutAccountIdentifiers extends Purchase {
public PurchaseWithoutAccountIdentifiers(@NonNull String s, @NonNull String s1)
throws JSONException {
super(s, s1);
}
@Override
public AccountIdentifiers getAccountIdentifiers() {
return null;
}
}
|
tvolkert/plugins
|
packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/TranslatorTest.java
|
Java
|
bsd-3-clause
| 12,828 | 46.687732 | 303 | 0.738385 | false |
"""Dict provider async mode tests."""
from dependency_injector import containers, providers
from pytest import mark
@mark.asyncio
async def test_provide():
async def create_resource(param: str):
return param
class Container(containers.DeclarativeContainer):
resources = providers.Dict(
foo=providers.Resource(create_resource, "foo"),
bar=providers.Resource(create_resource, "bar")
)
container = Container()
resources = await container.resources()
assert resources["foo"] == "foo"
assert resources["bar"] == "bar"
|
ets-labs/python-dependency-injector
|
tests/unit/providers/async/test_dict_py36.py
|
Python
|
bsd-3-clause
| 592 | 24.73913 | 59 | 0.668919 | false |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
# External imports
# Bokeh imports
# Module under test
import bokeh.command.subcommands as sc
#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
def test_all():
assert hasattr(sc, 'all')
assert type(sc.all) is list
def test_all_types():
from bokeh.command.subcommand import Subcommand
assert all(issubclass(x, Subcommand) for x in sc.all)
def test_all_count():
from os.path import dirname
from os import listdir
files = listdir(dirname(sc.__file__))
pyfiles = [x for x in files if x.endswith(".py")]
# the -2 accounts for __init__.py and file_output.py
assert len(sc.all) == len(pyfiles) - 2
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
|
mindriot101/bokeh
|
bokeh/command/subcommands/tests/test_subcommands_package.py
|
Python
|
bsd-3-clause
| 2,262 | 33.272727 | 82 | 0.307692 | false |
<!-- %BD_HTML%/SearchResult.htm -->
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<TITLE>úåöàú àéðèøðè - Takanot File</TITLE>
</HEAD>
<style>
<!--
TR.A_Table {font-color:#3e6ea6; background-color: #f7f9fb; font-size:11;font-family: Arial,}
TR.B_Table {font-color:#3e6ea6; background-color: #ecf1f6; font-size:11;font-family: Arial,}
TR.C {font-color:#1e4a7a; background-color: #A9CAEF;font-weight:bold; font-size:11;font-family: Arial,}
TR.clear { font-color:#1e4a7a; background-color: #FFFFFF;}
H5 { font-family:Arial, Helvetica, sans-serif; font-size: 14px;}
H3 { font-family:Arial, Helvetica, sans-serif; font-size: 16px;}
TD.A_Row { font-family: Arial, Helvetica, sans-serif; font-weight:bold; font-style: normal; color: #093300; font-size: 10px}
.defaultFont { color:#1f4a7b;font-family: Arial, Helvetica, sans-serif; font-size: 12px}
-->
</style>
<BODY dir=rtl class="defaultFont">
<CENTER>
<IMG src="/budget/Images/title1.jpg" align=bottom alt="ú÷öéá äîãéðä">
<TABLE align="center" border=0 cellspacing=0 cellpadding=0>
<TR align="center">
<TD><H3>úåöàú çéôåù ìùðú 2000</H3></TD>
</TR>
<TR align="center">
<!--<TD><H3>ðúåðé áéöåò ðëåðéí ìñåó çåãù 02/2005</H3></TD>-->
<TD><H3>ðúåðé áéöåò ëôé ùðøùîå áñôøé äðäìú äçùáåðåú ùì äîùøãéí - 02/2005<br></H3></TD>
</TR>
</TR align="center">
<TD><H3>àéï àçéãåú áéï äñòéôéí ìâáé îåòã òãëåï äðúåðéí</H3></TD>
</TR>
</TABLE>
<H5>äñëåîéí äéðí ùì çå÷ äú÷öéá äî÷åøé åáàìôé ù÷ìéí <BR>
</H5>
</CENTER>
<table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee">
<TR class="C" align="center">
<TD valign=top width=50>ñòéó</TD>
<TD valign=top align="right" width=120>ùí ñòéó</TD>
<TD valign=top width=65>äåöàä ðèå</TD>
<TD valign=top width=65>äåöàä îåúðéú áäëðñä</TD>
<TD valign=top width=65>ñä"ë äåöàä</TD>
<TD valign=top width=65>äøùàä ìäúçééá</TD>
<TD valign=top width=65>ùéà ë"à</TD>
<TD valign=top width=40>ñä"ë ðåöì</TD>
<TD valign=top width=40>àçåæ ðåöì</TD>
</TR>
</TABLE>
<table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee">
<TR class="B_Table" align="center">
<TD valign=top width=50> 03</TD>
<TD valign=top align="right" width=120> çáøé îîùìä</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 11,112</TD>
<TD valign=top width=40> 66.51</TD>
</TR>
<TR class="A_Table" align="center">
<TD valign=top width=50> 0301</TD>
<TD valign=top align="right" width=120> çáøé äîîùìä</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 11,112</TD>
<TD valign=top width=40> 66.51</TD>
</TR>
<TR class="B_Table" align="center">
<TD valign=top width=50> 030101</TD>
<TD valign=top align="right" width=120> çáøé äîîùìä</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 16,708</TD>
<TD valign=top width=65> 0</TD>
<TD valign=top width=65> 0.0</TD>
<TD valign=top width=40> 11,112</TD>
<TD valign=top width=40> 66.51</TD>
</TR>
</TABLE>
</CENTER>
<BR>
<CENTER>
<table border="0" cellspacing="1" cellpadding="3" bgcolor="#8fbcee" dir="rtl">
<TR class="C" align="center">
<TD class="A_Row" valign=top width=80>ñéëåí ãå"ç</TD>
<TD class="A_Row" valign=top width=60>äåöàä ðèå</TD>
<TD class="A_Row" valign=top width=60>äåöàä îåúðéú áäëðñä</TD>
<TD class="A_Row" valign=top width=60>ñä"ë äåöàä</TD>
<TD class="A_Row" valign=top width=60>äøùàä ìäúçééá</TD>
<TD class="A_Row" valign=top width=60>ùéà ë"à</TD>
<TD class="A_Row" valign=top width=50>ñä"ë ðåöì</TD>
<TD class="A_Row" valign=top width=50>àçåæ ðåöì</TD>
</TR>
<TR class="clear" align="center">
<TD class="A_Row" valign=top width=80> ú÷öéá î÷åøé</TD>
<TD class="A_Row" valign=top width=60> 16,708</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 16,708</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=50> </TD>
<TD class="A_Row" valign=top width=50> </TD>
</TR>
<!--<TR class="clear" align="center">
<TD class="A_Row" valign=top width=80> ú÷öéá òì ùéðåééå</TD>
<TD class="A_Row" valign=top width=60> 16,708</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 16,708</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=60> 0</TD>
<TD class="A_Row" valign=top width=50> 11,112</TD>
<TD class="A_Row" valign=top width=50> 66.51</TD>
</TR>-->
</TABLE>
<CENTER>
<TABLE WIDTH="100" >
<TR>
<TD align="center" nowrap>
<IMG SRC="/budget/Images/semel.gif" HEIGHT=37 WIDTH=30 border = "0"><BR>
<FONT SIZE=-2>
<A HREF="http://www.mof.gov.il/rights.htm">
ëì äæëåéåú
©
.ùîåøåú,2005,îãéðú éùøàì<BR></A>
ðùîç ì÷áì àú äòøåúéëí åäöòåúéëí ìëúåáú:
</FONT>
<FONT SIZE=-2 dir=ltr>
<A HREF="mailto:[email protected]">[email protected]</A><BR>
</FONT>
</TD>
</TR>
</TABLE>
</CENTER>
</CENTER>
</BODY>
</HTML>
|
daonb/obudget
|
data/queries/results/result-2000-03.html
|
HTML
|
bsd-3-clause
| 6,507 | 39.980645 | 129 | 0.561549 | false |
var Backbone = require('backbone');
var CommandButtonView = require('./CommandButtonView');
module.exports = CommandButtonView.extend({
initialize(o, config) {
CommandButtonView.prototype.initialize.apply(this, arguments);
},
getInput() {
var m = this.model;
if(!this.input){
var cmd = m.get('command');
var input = '<select data-edit="' + cmd +'">';
var opts = m.get('options');
var label = m.get('title') || m.get('command');
input += '<option>' + label + '</option>';
for(var i = 0, len = opts.length; i < len; i++){
var opt = opts[i];
var value = opt.value;
var name = opt.name || value;
input += '<option value="' + value + '">' + name + '</option>';
}
input += '</select>';
this.input = $(input);
}
return this.input;
},
getInputCont() {
var input = this.getInput();
var pfx = this.ppfx;
var cont = $('<div class="'+pfx+'field '+pfx+'select"><div class="'+pfx+'sel-arrow"><div class="'+pfx+'d-s-arrow"></div></div></div>');
return cont.append(input);
},
render(...args) {
CommandButtonView.prototype.render.apply(this, args);
this.$el.html(this.getInputCont());
return this;
}
});
|
devierol/heroku-gjs
|
src/rich_text_editor/view/CommandButtonSelectView.js
|
JavaScript
|
bsd-3-clause
| 1,242 | 28.571429 | 139 | 0.561997 | false |
# get_version.cmake
# Determine project version by using Git or a local .version file
set(__detect_version 0)
find_package(Git)
set(ERROR_FLAG "0")
if (GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
# Working off a git repo, using git versioning
# Check if HEAD is pointing to a tag
execute_process (
COMMAND "${GIT_EXECUTABLE}" describe --always --tag
WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
OUTPUT_VARIABLE PROJECT_VERSION
RESULT_VARIABLE GIT_DESCRIBE_RESULT
ERROR_VARIABLE GIT_DESCRIBE_ERROR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if (GIT_DESCRIBE_RESULT EQUAL 0)
# If the sources have been changed locally, add -dirty to the version.
execute_process (
COMMAND "${GIT_EXECUTABLE}" diff --quiet
WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
RESULT_VARIABLE res
)
if (res EQUAL 1)
set(PROJECT_VERSION "${PROJECT_VERSION}-dirty")
endif ()
# Strip a leading v off of the version as proceeding code expects just the version numbering.
string(REGEX REPLACE "^v" "" PROJECT_VERSION ${PROJECT_VERSION})
# Read version string
string(REGEX REPLACE "^(0|[1-9][0-9]*)[.](0|[1-9][0-9]*)[.](0|[1-9][0-9]*)(-[.0-9A-Za-z-]+)?([+][.0-9A-Za-z-]+)?$"
"\\1;\\2;\\3" PROJECT_VERSION_LIST ${PROJECT_VERSION})
list(LENGTH PROJECT_VERSION_LIST len)
if (len EQUAL 3)
list(GET PROJECT_VERSION_LIST 0 PROJECT_VERSION_MAJOR)
list(GET PROJECT_VERSION_LIST 1 PROJECT_VERSION_MINOR)
list(GET PROJECT_VERSION_LIST 2 PROJECT_VERSION_PATCH)
set(__detect_version 1)
set(__version_str "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}")
# Compare git-Version with version read from .version file in source folder
if (EXISTS "${PROJECT_SOURCE_DIR}/.version")
# Local .version file found, read version string...
file(READ "${PROJECT_SOURCE_DIR}/.version" __version_file)
# ...the version does not match with git-version string
if (NOT __version_str STREQUAL __version_file)
message(STATUS "Rewrite ${PROJECT_SOURCE_DIR}/.version with ${__version_str}!")
endif ()
else (NOT EXISTS "${PROJECT_SOURCE_DIR}/.version")
# No local .version file found: Create a new one...
file(WRITE "${PROJECT_SOURCE_DIR}/.version" ${__version_str})
endif ()
message(STATUS "stlink version: ${PROJECT_VERSION}")
message(STATUS "Major ${PROJECT_VERSION_MAJOR} Minor ${PROJECT_VERSION_MINOR} Patch ${PROJECT_VERSION_PATCH}")
else (len EQUAL 3)
message(STATUS "Failed to extract version parts from \"${PROJECT_VERSION}\"")
set(ERROR_FLAG "1")
endif (len EQUAL 3)
else (GIT_DESCRIBE_RESULT EQUAL 0)
message(WARNING "git describe failed: ${GIT_DESCRIBE_ERROR}")
set(ERROR_FLAG "1")
endif(GIT_DESCRIBE_RESULT EQUAL 0)
endif ()
##
# Failure to read version via git
# Possible cases:
# -> git is not found or
# -> /.git does not exist or
# -> GIT_DESCRIBE failed or
# -> version string is of invalid format
##
if (NOT GIT_FOUND OR NOT EXISTS "${PROJECT_SOURCE_DIR}/.git" OR ERROR_FLAG EQUAL 1)
message(STATUS "Git and/or repository not found.") # e.g. when building from source package
message(STATUS "Try to detect version from \"${PROJECT_SOURCE_DIR}/.version\" file instead...")
if (EXISTS ${PROJECT_SOURCE_DIR}/.version)
file(STRINGS .version PROJECT_VERSION)
# Read version string
string(REGEX REPLACE "^(0|[1-9][0-9]*)[.](0|[1-9][0-9]*)[.](0|[1-9][0-9]*)(-[.0-9A-Za-z-]+)?([+][.0-9A-Za-z-]+)?$"
"\\1;\\2;\\3" PROJECT_VERSION_LIST ${PROJECT_VERSION})
list(LENGTH PROJECT_VERSION_LIST len)
if (len EQUAL 3)
list(GET PROJECT_VERSION_LIST 0 PROJECT_VERSION_MAJOR)
list(GET PROJECT_VERSION_LIST 1 PROJECT_VERSION_MINOR)
list(GET PROJECT_VERSION_LIST 2 PROJECT_VERSION_PATCH)
set(__detect_version 1)
else ()
message(STATUS "Fail to extract version parts from \"${PROJECT_VERSION}\"")
endif ()
else (EXISTS ${PROJECT_SOURCE_DIR}/.version)
message(STATUS "File \"${PROJECT_SOURCE_DIR}/.version\" does not exist.")
message(FATAL_ERROR "Unable to determine project version")
endif ()
endif ()
|
simonjwright/stlink
|
cmake/modules/get_version.cmake
|
CMake
|
bsd-3-clause
| 4,662 | 41.770642 | 122 | 0.59438 | false |
/**
* OpenAL cross platform audio library
* Copyright (C) 1999-2007 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include "alMain.h"
#include "alu.h"
#include "alError.h"
#include "alBuffer.h"
#include "alThunk.h"
static ALenum LoadData(ALbuffer *ALBuf, ALuint freq, ALenum NewFormat, ALsizei frames, enum UserFmtChannels chans, enum UserFmtType type, const ALvoid *data, ALboolean storesrc);
static void ConvertData(ALvoid *dst, enum UserFmtType dstType, const ALvoid *src, enum UserFmtType srcType, ALsizei numchans, ALsizei len);
static ALboolean IsValidType(ALenum type);
static ALboolean IsValidChannels(ALenum channels);
static ALboolean DecomposeUserFormat(ALenum format, enum UserFmtChannels *chans, enum UserFmtType *type);
static ALboolean DecomposeFormat(ALenum format, enum FmtChannels *chans, enum FmtType *type);
/*
* Global Variables
*/
/* IMA ADPCM Stepsize table */
static const int IMAStep_size[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19,
21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55,
60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157,
173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442,
11487,12635,13899,15289,16818,18500,20350,22358,24633,27086,29794,
32767
};
/* IMA4 ADPCM Codeword decode table */
static const int IMA4Codeword[16] = {
1, 3, 5, 7, 9, 11, 13, 15,
-1,-3,-5,-7,-9,-11,-13,-15,
};
/* IMA4 ADPCM Step index adjust decode table */
static const int IMA4Index_adjust[16] = {
-1,-1,-1,-1, 2, 4, 6, 8,
-1,-1,-1,-1, 2, 4, 6, 8
};
/* A quick'n'dirty lookup table to decode a muLaw-encoded byte sample into a
* signed 16-bit sample */
static const ALshort muLawDecompressionTable[256] = {
-32124,-31100,-30076,-29052,-28028,-27004,-25980,-24956,
-23932,-22908,-21884,-20860,-19836,-18812,-17788,-16764,
-15996,-15484,-14972,-14460,-13948,-13436,-12924,-12412,
-11900,-11388,-10876,-10364, -9852, -9340, -8828, -8316,
-7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140,
-5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092,
-3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004,
-2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980,
-1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436,
-1372, -1308, -1244, -1180, -1116, -1052, -988, -924,
-876, -844, -812, -780, -748, -716, -684, -652,
-620, -588, -556, -524, -492, -460, -428, -396,
-372, -356, -340, -324, -308, -292, -276, -260,
-244, -228, -212, -196, -180, -164, -148, -132,
-120, -112, -104, -96, -88, -80, -72, -64,
-56, -48, -40, -32, -24, -16, -8, 0,
32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956,
23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764,
15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412,
11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316,
7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140,
5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092,
3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004,
2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980,
1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436,
1372, 1308, 1244, 1180, 1116, 1052, 988, 924,
876, 844, 812, 780, 748, 716, 684, 652,
620, 588, 556, 524, 492, 460, 428, 396,
372, 356, 340, 324, 308, 292, 276, 260,
244, 228, 212, 196, 180, 164, 148, 132,
120, 112, 104, 96, 88, 80, 72, 64,
56, 48, 40, 32, 24, 16, 8, 0
};
/* Values used when encoding a muLaw sample */
static const int muLawBias = 0x84;
static const int muLawClip = 32635;
static const char muLawCompressTable[256] = {
0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
};
/* A quick'n'dirty lookup table to decode an aLaw-encoded byte sample into a
* signed 16-bit sample */
static const ALshort aLawDecompressionTable[256] = {
-5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
-7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
-2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
-3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
-22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
-30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
-11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
-15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
-344, -328, -376, -360, -280, -264, -312, -296,
-472, -456, -504, -488, -408, -392, -440, -424,
-88, -72, -120, -104, -24, -8, -56, -40,
-216, -200, -248, -232, -152, -136, -184, -168,
-1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
-1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
-688, -656, -752, -720, -560, -528, -624, -592,
-944, -912, -1008, -976, -816, -784, -880, -848,
5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736,
7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784,
2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368,
3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392,
22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472,
15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
344, 328, 376, 360, 280, 264, 312, 296,
472, 456, 504, 488, 408, 392, 440, 424,
88, 72, 120, 104, 24, 8, 56, 40,
216, 200, 248, 232, 152, 136, 184, 168,
1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184,
1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696,
688, 656, 752, 720, 560, 528, 624, 592,
944, 912, 1008, 976, 816, 784, 880, 848
};
/* Values used when encoding an aLaw sample */
static const int aLawClip = 32635;
static const char aLawCompressTable[128] = {
1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
};
AL_API ALvoid AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers)
{
ALCcontext *Context;
ALsizei cur = 0;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
ALenum err;
CHECK_VALUE(Context, n >= 0);
for(cur = 0;cur < n;cur++)
{
ALbuffer *buffer = calloc(1, sizeof(ALbuffer));
if(!buffer)
{
alDeleteBuffers(cur, buffers);
al_throwerr(Context, AL_OUT_OF_MEMORY);
}
RWLockInit(&buffer->lock);
err = NewThunkEntry(&buffer->id);
if(err == AL_NO_ERROR)
err = InsertUIntMapEntry(&device->BufferMap, buffer->id, buffer);
if(err != AL_NO_ERROR)
{
FreeThunkEntry(buffer->id);
memset(buffer, 0, sizeof(ALbuffer));
free(buffer);
alDeleteBuffers(cur, buffers);
al_throwerr(Context, err);
}
buffers[cur] = buffer->id;
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers)
{
ALCcontext *Context;
ALbuffer *ALBuf;
ALsizei i;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
CHECK_VALUE(Context, n >= 0);
for(i = 0;i < n;i++)
{
if(!buffers[i])
continue;
/* Check for valid Buffer ID */
if((ALBuf=LookupBuffer(device, buffers[i])) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
if(ALBuf->ref != 0)
al_throwerr(Context, AL_INVALID_OPERATION);
}
for(i = 0;i < n;i++)
{
if((ALBuf=RemoveBuffer(device, buffers[i])) == NULL)
continue;
FreeThunkEntry(ALBuf->id);
free(ALBuf->data);
memset(ALBuf, 0, sizeof(*ALBuf));
free(ALBuf);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer)
{
ALCcontext *Context;
ALboolean result;
Context = GetContextRef();
if(!Context) return AL_FALSE;
result = ((!buffer || LookupBuffer(Context->Device, buffer)) ?
AL_TRUE : AL_FALSE);
ALCcontext_DecRef(Context);
return result;
}
AL_API ALvoid AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
{
enum UserFmtChannels SrcChannels;
enum UserFmtType SrcType;
ALCcontext *Context;
ALuint FrameSize;
ALenum NewFormat;
ALbuffer *ALBuf;
ALenum err;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, size >= 0 && freq >= 0);
if(DecomposeUserFormat(format, &SrcChannels, &SrcType) == AL_FALSE)
al_throwerr(Context, AL_INVALID_ENUM);
switch(SrcType)
{
case UserFmtByte:
case UserFmtUByte:
case UserFmtShort:
case UserFmtUShort:
case UserFmtFloat:
FrameSize = FrameSizeFromUserFmt(SrcChannels, SrcType);
CHECK_VALUE(Context, (size%FrameSize) == 0);
err = LoadData(ALBuf, freq, format, size/FrameSize,
SrcChannels, SrcType, data, AL_TRUE);
if(err != AL_NO_ERROR)
al_throwerr(Context, err);
break;
case UserFmtInt:
case UserFmtUInt:
case UserFmtByte3:
case UserFmtUByte3:
case UserFmtDouble:
FrameSize = FrameSizeFromUserFmt(SrcChannels, SrcType);
CHECK_VALUE(Context, (size%FrameSize) == 0);
NewFormat = AL_FORMAT_MONO_FLOAT32;
switch(SrcChannels)
{
case UserFmtMono: NewFormat = AL_FORMAT_MONO_FLOAT32; break;
case UserFmtStereo: NewFormat = AL_FORMAT_STEREO_FLOAT32; break;
case UserFmtRear: NewFormat = AL_FORMAT_REAR32; break;
case UserFmtQuad: NewFormat = AL_FORMAT_QUAD32; break;
case UserFmtX51: NewFormat = AL_FORMAT_51CHN32; break;
case UserFmtX61: NewFormat = AL_FORMAT_61CHN32; break;
case UserFmtX71: NewFormat = AL_FORMAT_71CHN32; break;
}
err = LoadData(ALBuf, freq, NewFormat, size/FrameSize,
SrcChannels, SrcType, data, AL_TRUE);
if(err != AL_NO_ERROR)
al_throwerr(Context, err);
break;
case UserFmtMulaw:
case UserFmtAlaw:
FrameSize = FrameSizeFromUserFmt(SrcChannels, SrcType);
CHECK_VALUE(Context, (size%FrameSize) == 0);
NewFormat = AL_FORMAT_MONO16;
switch(SrcChannels)
{
case UserFmtMono: NewFormat = AL_FORMAT_MONO16; break;
case UserFmtStereo: NewFormat = AL_FORMAT_STEREO16; break;
case UserFmtRear: NewFormat = AL_FORMAT_REAR16; break;
case UserFmtQuad: NewFormat = AL_FORMAT_QUAD16; break;
case UserFmtX51: NewFormat = AL_FORMAT_51CHN16; break;
case UserFmtX61: NewFormat = AL_FORMAT_61CHN16; break;
case UserFmtX71: NewFormat = AL_FORMAT_71CHN16; break;
}
err = LoadData(ALBuf, freq, NewFormat, size/FrameSize,
SrcChannels, SrcType, data, AL_TRUE);
if(err != AL_NO_ERROR)
al_throwerr(Context, err);
break;
case UserFmtIMA4:
/* Here is where things vary:
* nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
* Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
*/
FrameSize = ChannelsFromUserFmt(SrcChannels) * 36;
CHECK_VALUE(Context, (size%FrameSize) == 0);
NewFormat = AL_FORMAT_MONO16;
switch(SrcChannels)
{
case UserFmtMono: NewFormat = AL_FORMAT_MONO16; break;
case UserFmtStereo: NewFormat = AL_FORMAT_STEREO16; break;
case UserFmtRear: NewFormat = AL_FORMAT_REAR16; break;
case UserFmtQuad: NewFormat = AL_FORMAT_QUAD16; break;
case UserFmtX51: NewFormat = AL_FORMAT_51CHN16; break;
case UserFmtX61: NewFormat = AL_FORMAT_61CHN16; break;
case UserFmtX71: NewFormat = AL_FORMAT_71CHN16; break;
}
err = LoadData(ALBuf, freq, NewFormat, size/FrameSize*65,
SrcChannels, SrcType, data, AL_TRUE);
if(err != AL_NO_ERROR)
al_throwerr(Context, err);
break;
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length)
{
enum UserFmtChannels SrcChannels;
enum UserFmtType SrcType;
ALCcontext *Context;
ALbuffer *ALBuf;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
ALuint original_align;
ALuint Channels;
ALuint Bytes;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, length >= 0 && offset >= 0);
if(DecomposeUserFormat(format, &SrcChannels, &SrcType) == AL_FALSE)
al_throwerr(Context, AL_INVALID_ENUM);
WriteLock(&ALBuf->lock);
original_align = ((ALBuf->OriginalType == UserFmtIMA4) ?
(ChannelsFromUserFmt(ALBuf->OriginalChannels)*36) :
FrameSizeFromUserFmt(ALBuf->OriginalChannels,
ALBuf->OriginalType));
if(SrcChannels != ALBuf->OriginalChannels || SrcType != ALBuf->OriginalType)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_ENUM);
}
if(offset > ALBuf->OriginalSize || length > ALBuf->OriginalSize-offset ||
(offset%original_align) != 0 || (length%original_align) != 0)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_VALUE);
}
Channels = ChannelsFromFmt(ALBuf->FmtChannels);
Bytes = BytesFromFmt(ALBuf->FmtType);
/* offset -> byte offset, length -> sample count */
if(SrcType == UserFmtIMA4)
{
offset = offset/36*65 * Bytes;
length = length/original_align * 65;
}
else
{
ALuint OldBytes = BytesFromUserFmt(SrcType);
offset = offset/OldBytes * Bytes;
length = length/OldBytes/Channels;
}
ConvertData((char*)ALBuf->data+offset, (enum UserFmtType)ALBuf->FmtType,
data, SrcType, Channels, length);
WriteUnlock(&ALBuf->lock);
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint buffer,
ALuint samplerate, ALenum internalformat, ALsizei samples,
ALenum channels, ALenum type, const ALvoid *data)
{
ALCcontext *Context;
ALbuffer *ALBuf;
ALenum err;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, samples >= 0 && samplerate != 0);
if(IsValidType(type) == AL_FALSE || IsValidChannels(channels) == AL_FALSE)
al_throwerr(Context, AL_INVALID_ENUM);
err = LoadData(ALBuf, samplerate, internalformat, samples,
channels, type, data, AL_FALSE);
if(err != AL_NO_ERROR)
al_throwerr(Context, err);
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint buffer,
ALsizei offset, ALsizei samples,
ALenum channels, ALenum type, const ALvoid *data)
{
ALCcontext *Context;
ALbuffer *ALBuf;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
ALuint FrameSize;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, samples >= 0 && offset >= 0);
if(IsValidType(type) == AL_FALSE)
al_throwerr(Context, AL_INVALID_ENUM);
WriteLock(&ALBuf->lock);
FrameSize = FrameSizeFromFmt(ALBuf->FmtChannels, ALBuf->FmtType);
if(channels != (ALenum)ALBuf->FmtChannels)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_ENUM);
}
else if(offset > ALBuf->SampleLen || samples > ALBuf->SampleLen-offset)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context,AL_INVALID_VALUE);
}
/* offset -> byte offset */
offset *= FrameSize;
ConvertData((char*)ALBuf->data+offset, (enum UserFmtType)ALBuf->FmtType,
data, type, ChannelsFromFmt(ALBuf->FmtChannels), samples);
WriteUnlock(&ALBuf->lock);
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint buffer,
ALsizei offset, ALsizei samples,
ALenum channels, ALenum type, ALvoid *data)
{
ALCcontext *Context;
ALbuffer *ALBuf;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
ALuint FrameSize;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, samples >= 0 && offset >= 0);
if(IsValidType(type) == AL_FALSE)
al_throwerr(Context, AL_INVALID_ENUM);
ReadLock(&ALBuf->lock);
FrameSize = FrameSizeFromFmt(ALBuf->FmtChannels, ALBuf->FmtType);
if(channels != (ALenum)ALBuf->FmtChannels)
{
ReadUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_ENUM);
}
if(offset > ALBuf->SampleLen || samples > ALBuf->SampleLen-offset)
{
ReadUnlock(&ALBuf->lock);
al_throwerr(Context,AL_INVALID_VALUE);
}
if(type == UserFmtIMA4 && (samples%65) != 0)
{
ReadUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_VALUE);
}
/* offset -> byte offset */
offset *= FrameSize;
ConvertData(data, type,
(char*)ALBuf->data+offset, (enum UserFmtType)ALBuf->FmtType,
ChannelsFromFmt(ALBuf->FmtChannels), samples);
ReadUnlock(&ALBuf->lock);
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum format)
{
enum FmtChannels DstChannels;
enum FmtType DstType;
ALCcontext *Context;
ALboolean ret;
Context = GetContextRef();
if(!Context) return AL_FALSE;
ret = DecomposeFormat(format, &DstChannels, &DstType);
ALCcontext_DecRef(Context);
return ret;
}
AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat value)
{
ALCcontext *Context;
(void)value;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3)
{
ALCcontext *Context;
(void)value1;
(void)value2;
(void)value3;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values)
{
ALCcontext *Context;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, values);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value)
{
ALCcontext *Context;
(void)value;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param, ALint value1, ALint value2, ALint value3)
{
ALCcontext *Context;
(void)value1;
(void)value2;
(void)value3;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values)
{
ALCcontext *Context;
ALbuffer *ALBuf;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, values);
switch(param)
{
case AL_LOOP_POINTS_SOFT:
WriteLock(&ALBuf->lock);
if(ALBuf->ref != 0)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_OPERATION);
}
if(values[0] >= values[1] || values[0] < 0 ||
values[1] > ALBuf->SampleLen)
{
WriteUnlock(&ALBuf->lock);
al_throwerr(Context, AL_INVALID_VALUE);
}
ALBuf->LoopStart = values[0];
ALBuf->LoopEnd = values[1];
WriteUnlock(&ALBuf->lock);
break;
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value)
{
ALCcontext *Context;
ALbuffer *Buffer;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((Buffer=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, value);
switch(param)
{
case AL_SEC_LENGTH_SOFT:
ReadLock(&Buffer->lock);
if(Buffer->SampleLen != 0)
*value = Buffer->SampleLen / (ALfloat)Buffer->Frequency;
else
*value = 0.0f;
ReadUnlock(&Buffer->lock);
break;
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
{
ALCcontext *Context;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, value1 && value2 && value3);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values)
{
ALCcontext *Context;
switch(param)
{
case AL_SEC_LENGTH_SOFT:
alGetBufferf(buffer, param, values);
return;
}
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, values);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API ALvoid AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value)
{
ALCcontext *Context;
ALbuffer *Buffer;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((Buffer=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, value);
switch(param)
{
case AL_FREQUENCY:
*value = Buffer->Frequency;
break;
case AL_BITS:
*value = BytesFromFmt(Buffer->FmtType) * 8;
break;
case AL_CHANNELS:
*value = ChannelsFromFmt(Buffer->FmtChannels);
break;
case AL_SIZE:
ReadLock(&Buffer->lock);
*value = Buffer->SampleLen * FrameSizeFromFmt(Buffer->FmtChannels,
Buffer->FmtType);
ReadUnlock(&Buffer->lock);
break;
case AL_INTERNAL_FORMAT_SOFT:
*value = Buffer->Format;
break;
case AL_BYTE_LENGTH_SOFT:
*value = Buffer->OriginalSize;
break;
case AL_SAMPLE_LENGTH_SOFT:
*value = Buffer->SampleLen;
break;
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3)
{
ALCcontext *Context;
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if(LookupBuffer(device, buffer) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, value1 && value2 && value3);
switch(param)
{
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values)
{
ALCcontext *Context;
ALbuffer *ALBuf;
switch(param)
{
case AL_FREQUENCY:
case AL_BITS:
case AL_CHANNELS:
case AL_SIZE:
case AL_INTERNAL_FORMAT_SOFT:
case AL_BYTE_LENGTH_SOFT:
case AL_SAMPLE_LENGTH_SOFT:
alGetBufferi(buffer, param, values);
return;
}
Context = GetContextRef();
if(!Context) return;
al_try
{
ALCdevice *device = Context->Device;
if((ALBuf=LookupBuffer(device, buffer)) == NULL)
al_throwerr(Context, AL_INVALID_NAME);
CHECK_VALUE(Context, values);
switch(param)
{
case AL_LOOP_POINTS_SOFT:
ReadLock(&ALBuf->lock);
values[0] = ALBuf->LoopStart;
values[1] = ALBuf->LoopEnd;
ReadUnlock(&ALBuf->lock);
break;
default:
al_throwerr(Context, AL_INVALID_ENUM);
}
}
al_endtry;
ALCcontext_DecRef(Context);
}
typedef ALubyte ALmulaw;
typedef ALubyte ALalaw;
typedef ALubyte ALima4;
typedef struct {
ALbyte b[3];
} ALbyte3;
extern ALbyte ALbyte3_size_is_not_3[(sizeof(ALbyte3)==sizeof(ALbyte[3]))?1:-1];
typedef struct {
ALubyte b[3];
} ALubyte3;
extern ALbyte ALubyte3_size_is_not_3[(sizeof(ALubyte3)==sizeof(ALubyte[3]))?1:-1];
static inline ALshort DecodeMuLaw(ALmulaw val)
{ return muLawDecompressionTable[val]; }
static ALmulaw EncodeMuLaw(ALshort val)
{
ALint mant, exp, sign;
sign = (val>>8) & 0x80;
if(sign)
{
/* -32768 doesn't properly negate on a short; it results in itself.
* So clamp to -32767 */
val = maxi(val, -32767);
val = -val;
}
val = mini(val, muLawClip);
val += muLawBias;
exp = muLawCompressTable[(val>>7) & 0xff];
mant = (val >> (exp+3)) & 0x0f;
return ~(sign | (exp<<4) | mant);
}
static inline ALshort DecodeALaw(ALalaw val)
{ return aLawDecompressionTable[val]; }
static ALalaw EncodeALaw(ALshort val)
{
ALint mant, exp, sign;
sign = ((~val) >> 8) & 0x80;
if(!sign)
{
val = maxi(val, -32767);
val = -val;
}
val = mini(val, aLawClip);
if(val >= 256)
{
exp = aLawCompressTable[(val>>8) & 0x7f];
mant = (val >> (exp+3)) & 0x0f;
}
else
{
exp = 0;
mant = val >> 4;
}
return ((exp<<4) | mant) ^ (sign^0x55);
}
static void DecodeIMA4Block(ALshort *dst, const ALima4 *src, ALint numchans)
{
ALint sample[MAX_INPUT_CHANNELS], index[MAX_INPUT_CHANNELS];
ALuint code[MAX_INPUT_CHANNELS];
ALsizei j,k,c;
for(c = 0;c < numchans;c++)
{
sample[c] = *(src++);
sample[c] |= *(src++) << 8;
sample[c] = (sample[c]^0x8000) - 32768;
index[c] = *(src++);
index[c] |= *(src++) << 8;
index[c] = (index[c]^0x8000) - 32768;
index[c] = clampi(index[c], 0, 88);
dst[c] = sample[c];
}
j = 1;
while(j < 65)
{
for(c = 0;c < numchans;c++)
{
code[c] = *(src++);
code[c] |= *(src++) << 8;
code[c] |= *(src++) << 16;
code[c] |= *(src++) << 24;
}
for(k = 0;k < 8;k++,j++)
{
for(c = 0;c < numchans;c++)
{
int nibble = code[c]&0xf;
code[c] >>= 4;
sample[c] += IMA4Codeword[nibble] * IMAStep_size[index[c]] / 8;
sample[c] = clampi(sample[c], -32768, 32767);
index[c] += IMA4Index_adjust[nibble];
index[c] = clampi(index[c], 0, 88);
dst[j*numchans + c] = sample[c];
}
}
}
}
static void EncodeIMA4Block(ALima4 *dst, const ALshort *src, ALint *sample, ALint *index, ALint numchans)
{
ALsizei j,k,c;
for(c = 0;c < numchans;c++)
{
int diff = src[c] - sample[c];
int step = IMAStep_size[index[c]];
int nibble;
nibble = 0;
if(diff < 0)
{
nibble = 0x8;
diff = -diff;
}
diff = mini(step*2, diff);
nibble |= (diff*8/step - 1) / 2;
sample[c] += IMA4Codeword[nibble] * step / 8;
sample[c] = clampi(sample[c], -32768, 32767);
index[c] += IMA4Index_adjust[nibble];
index[c] = clampi(index[c], 0, 88);
*(dst++) = sample[c] & 0xff;
*(dst++) = (sample[c]>>8) & 0xff;
*(dst++) = index[c] & 0xff;
*(dst++) = (index[c]>>8) & 0xff;
}
j = 1;
while(j < 65)
{
for(c = 0;c < numchans;c++)
{
for(k = 0;k < 8;k++)
{
int diff = src[(j+k)*numchans + c] - sample[c];
int step = IMAStep_size[index[c]];
int nibble;
nibble = 0;
if(diff < 0)
{
nibble = 0x8;
diff = -diff;
}
diff = mini(step*2, diff);
nibble |= (diff*8/step - 1) / 2;
sample[c] += IMA4Codeword[nibble] * step / 8;
sample[c] = clampi(sample[c], -32768, 32767);
index[c] += IMA4Index_adjust[nibble];
index[c] = clampi(index[c], 0, 88);
if(!(k&1)) *dst = nibble;
else *(dst++) |= nibble<<4;
}
}
j += 8;
}
}
static inline ALint DecodeByte3(ALbyte3 val)
{
if(IS_LITTLE_ENDIAN)
return (val.b[2]<<16) | (((ALubyte)val.b[1])<<8) | ((ALubyte)val.b[0]);
return (val.b[0]<<16) | (((ALubyte)val.b[1])<<8) | ((ALubyte)val.b[2]);
}
static inline ALbyte3 EncodeByte3(ALint val)
{
if(IS_LITTLE_ENDIAN)
{
ALbyte3 ret = {{ val, val>>8, val>>16 }};
return ret;
}
else
{
ALbyte3 ret = {{ val>>16, val>>8, val }};
return ret;
}
}
static inline ALint DecodeUByte3(ALubyte3 val)
{
if(IS_LITTLE_ENDIAN)
return (val.b[2]<<16) | (val.b[1]<<8) | (val.b[0]);
return (val.b[0]<<16) | (val.b[1]<<8) | val.b[2];
}
static inline ALubyte3 EncodeUByte3(ALint val)
{
if(IS_LITTLE_ENDIAN)
{
ALubyte3 ret = {{ val, val>>8, val>>16 }};
return ret;
}
else
{
ALubyte3 ret = {{ val>>16, val>>8, val }};
return ret;
}
}
static inline ALbyte Conv_ALbyte_ALbyte(ALbyte val)
{ return val; }
static inline ALbyte Conv_ALbyte_ALubyte(ALubyte val)
{ return val-128; }
static inline ALbyte Conv_ALbyte_ALshort(ALshort val)
{ return val>>8; }
static inline ALbyte Conv_ALbyte_ALushort(ALushort val)
{ return (val>>8)-128; }
static inline ALbyte Conv_ALbyte_ALint(ALint val)
{ return val>>24; }
static inline ALbyte Conv_ALbyte_ALuint(ALuint val)
{ return (val>>24)-128; }
static inline ALbyte Conv_ALbyte_ALfloat(ALfloat val)
{
if(val > 1.0f) return 127;
if(val < -1.0f) return -128;
return (ALint)(val * 127.0f);
}
static inline ALbyte Conv_ALbyte_ALdouble(ALdouble val)
{
if(val > 1.0) return 127;
if(val < -1.0) return -128;
return (ALint)(val * 127.0);
}
static inline ALbyte Conv_ALbyte_ALmulaw(ALmulaw val)
{ return Conv_ALbyte_ALshort(DecodeMuLaw(val)); }
static inline ALbyte Conv_ALbyte_ALalaw(ALalaw val)
{ return Conv_ALbyte_ALshort(DecodeALaw(val)); }
static inline ALbyte Conv_ALbyte_ALbyte3(ALbyte3 val)
{ return DecodeByte3(val)>>16; }
static inline ALbyte Conv_ALbyte_ALubyte3(ALubyte3 val)
{ return (DecodeUByte3(val)>>16)-128; }
static inline ALubyte Conv_ALubyte_ALbyte(ALbyte val)
{ return val+128; }
static inline ALubyte Conv_ALubyte_ALubyte(ALubyte val)
{ return val; }
static inline ALubyte Conv_ALubyte_ALshort(ALshort val)
{ return (val>>8)+128; }
static inline ALubyte Conv_ALubyte_ALushort(ALushort val)
{ return val>>8; }
static inline ALubyte Conv_ALubyte_ALint(ALint val)
{ return (val>>24)+128; }
static inline ALubyte Conv_ALubyte_ALuint(ALuint val)
{ return val>>24; }
static inline ALubyte Conv_ALubyte_ALfloat(ALfloat val)
{
if(val > 1.0f) return 255;
if(val < -1.0f) return 0;
return (ALint)(val * 127.0f) + 128;
}
static inline ALubyte Conv_ALubyte_ALdouble(ALdouble val)
{
if(val > 1.0) return 255;
if(val < -1.0) return 0;
return (ALint)(val * 127.0) + 128;
}
static inline ALubyte Conv_ALubyte_ALmulaw(ALmulaw val)
{ return Conv_ALubyte_ALshort(DecodeMuLaw(val)); }
static inline ALubyte Conv_ALubyte_ALalaw(ALalaw val)
{ return Conv_ALubyte_ALshort(DecodeALaw(val)); }
static inline ALubyte Conv_ALubyte_ALbyte3(ALbyte3 val)
{ return (DecodeByte3(val)>>16)+128; }
static inline ALubyte Conv_ALubyte_ALubyte3(ALubyte3 val)
{ return DecodeUByte3(val)>>16; }
static inline ALshort Conv_ALshort_ALbyte(ALbyte val)
{ return val<<8; }
static inline ALshort Conv_ALshort_ALubyte(ALubyte val)
{ return (val-128)<<8; }
static inline ALshort Conv_ALshort_ALshort(ALshort val)
{ return val; }
static inline ALshort Conv_ALshort_ALushort(ALushort val)
{ return val-32768; }
static inline ALshort Conv_ALshort_ALint(ALint val)
{ return val>>16; }
static inline ALshort Conv_ALshort_ALuint(ALuint val)
{ return (val>>16)-32768; }
static inline ALshort Conv_ALshort_ALfloat(ALfloat val)
{
if(val > 1.0f) return 32767;
if(val < -1.0f) return -32768;
return (ALint)(val * 32767.0f);
}
static inline ALshort Conv_ALshort_ALdouble(ALdouble val)
{
if(val > 1.0) return 32767;
if(val < -1.0) return -32768;
return (ALint)(val * 32767.0);
}
static inline ALshort Conv_ALshort_ALmulaw(ALmulaw val)
{ return Conv_ALshort_ALshort(DecodeMuLaw(val)); }
static inline ALshort Conv_ALshort_ALalaw(ALalaw val)
{ return Conv_ALshort_ALshort(DecodeALaw(val)); }
static inline ALshort Conv_ALshort_ALbyte3(ALbyte3 val)
{ return DecodeByte3(val)>>8; }
static inline ALshort Conv_ALshort_ALubyte3(ALubyte3 val)
{ return (DecodeUByte3(val)>>8)-32768; }
static inline ALushort Conv_ALushort_ALbyte(ALbyte val)
{ return (val+128)<<8; }
static inline ALushort Conv_ALushort_ALubyte(ALubyte val)
{ return val<<8; }
static inline ALushort Conv_ALushort_ALshort(ALshort val)
{ return val+32768; }
static inline ALushort Conv_ALushort_ALushort(ALushort val)
{ return val; }
static inline ALushort Conv_ALushort_ALint(ALint val)
{ return (val>>16)+32768; }
static inline ALushort Conv_ALushort_ALuint(ALuint val)
{ return val>>16; }
static inline ALushort Conv_ALushort_ALfloat(ALfloat val)
{
if(val > 1.0f) return 65535;
if(val < -1.0f) return 0;
return (ALint)(val * 32767.0f) + 32768;
}
static inline ALushort Conv_ALushort_ALdouble(ALdouble val)
{
if(val > 1.0) return 65535;
if(val < -1.0) return 0;
return (ALint)(val * 32767.0) + 32768;
}
static inline ALushort Conv_ALushort_ALmulaw(ALmulaw val)
{ return Conv_ALushort_ALshort(DecodeMuLaw(val)); }
static inline ALushort Conv_ALushort_ALalaw(ALalaw val)
{ return Conv_ALushort_ALshort(DecodeALaw(val)); }
static inline ALushort Conv_ALushort_ALbyte3(ALbyte3 val)
{ return (DecodeByte3(val)>>8)+32768; }
static inline ALushort Conv_ALushort_ALubyte3(ALubyte3 val)
{ return DecodeUByte3(val)>>8; }
static inline ALint Conv_ALint_ALbyte(ALbyte val)
{ return val<<24; }
static inline ALint Conv_ALint_ALubyte(ALubyte val)
{ return (val-128)<<24; }
static inline ALint Conv_ALint_ALshort(ALshort val)
{ return val<<16; }
static inline ALint Conv_ALint_ALushort(ALushort val)
{ return (val-32768)<<16; }
static inline ALint Conv_ALint_ALint(ALint val)
{ return val; }
static inline ALint Conv_ALint_ALuint(ALuint val)
{ return val-2147483648u; }
static inline ALint Conv_ALint_ALfloat(ALfloat val)
{
if(val > 1.0f) return 2147483647;
if(val < -1.0f) return -2147483647-1;
return (ALint)(val*16777215.0f) << 7;
}
static inline ALint Conv_ALint_ALdouble(ALdouble val)
{
if(val > 1.0) return 2147483647;
if(val < -1.0) return -2147483647-1;
return (ALint)(val * 2147483647.0);
}
static inline ALint Conv_ALint_ALmulaw(ALmulaw val)
{ return Conv_ALint_ALshort(DecodeMuLaw(val)); }
static inline ALint Conv_ALint_ALalaw(ALalaw val)
{ return Conv_ALint_ALshort(DecodeALaw(val)); }
static inline ALint Conv_ALint_ALbyte3(ALbyte3 val)
{ return DecodeByte3(val)<<8; }
static inline ALint Conv_ALint_ALubyte3(ALubyte3 val)
{ return (DecodeUByte3(val)-8388608)<<8; }
static inline ALuint Conv_ALuint_ALbyte(ALbyte val)
{ return (val+128)<<24; }
static inline ALuint Conv_ALuint_ALubyte(ALubyte val)
{ return val<<24; }
static inline ALuint Conv_ALuint_ALshort(ALshort val)
{ return (val+32768)<<16; }
static inline ALuint Conv_ALuint_ALushort(ALushort val)
{ return val<<16; }
static inline ALuint Conv_ALuint_ALint(ALint val)
{ return val+2147483648u; }
static inline ALuint Conv_ALuint_ALuint(ALuint val)
{ return val; }
static inline ALuint Conv_ALuint_ALfloat(ALfloat val)
{
if(val > 1.0f) return 4294967295u;
if(val < -1.0f) return 0;
return ((ALint)(val*16777215.0f)<<7) + 2147483648u;
}
static inline ALuint Conv_ALuint_ALdouble(ALdouble val)
{
if(val > 1.0) return 4294967295u;
if(val < -1.0) return 0;
return (ALint)(val * 2147483647.0) + 2147483648u;
}
static inline ALuint Conv_ALuint_ALmulaw(ALmulaw val)
{ return Conv_ALuint_ALshort(DecodeMuLaw(val)); }
static inline ALuint Conv_ALuint_ALalaw(ALalaw val)
{ return Conv_ALuint_ALshort(DecodeALaw(val)); }
static inline ALuint Conv_ALuint_ALbyte3(ALbyte3 val)
{ return (DecodeByte3(val)+8388608)<<8; }
static inline ALuint Conv_ALuint_ALubyte3(ALubyte3 val)
{ return DecodeUByte3(val)<<8; }
static inline ALfloat Conv_ALfloat_ALbyte(ALbyte val)
{ return val * (1.0f/127.0f); }
static inline ALfloat Conv_ALfloat_ALubyte(ALubyte val)
{ return (val-128) * (1.0f/127.0f); }
static inline ALfloat Conv_ALfloat_ALshort(ALshort val)
{ return val * (1.0f/32767.0f); }
static inline ALfloat Conv_ALfloat_ALushort(ALushort val)
{ return (val-32768) * (1.0f/32767.0f); }
static inline ALfloat Conv_ALfloat_ALint(ALint val)
{ return (ALfloat)(val * (1.0/2147483647.0)); }
static inline ALfloat Conv_ALfloat_ALuint(ALuint val)
{ return (ALfloat)((ALint)(val-2147483648u) * (1.0/2147483647.0)); }
static inline ALfloat Conv_ALfloat_ALfloat(ALfloat val)
{ return (val==val) ? val : 0.0f; }
static inline ALfloat Conv_ALfloat_ALdouble(ALdouble val)
{ return (val==val) ? (ALfloat)val : 0.0f; }
static inline ALfloat Conv_ALfloat_ALmulaw(ALmulaw val)
{ return Conv_ALfloat_ALshort(DecodeMuLaw(val)); }
static inline ALfloat Conv_ALfloat_ALalaw(ALalaw val)
{ return Conv_ALfloat_ALshort(DecodeALaw(val)); }
static inline ALfloat Conv_ALfloat_ALbyte3(ALbyte3 val)
{ return (ALfloat)(DecodeByte3(val) * (1.0/8388607.0)); }
static inline ALfloat Conv_ALfloat_ALubyte3(ALubyte3 val)
{ return (ALfloat)((DecodeUByte3(val)-8388608) * (1.0/8388607.0)); }
static inline ALdouble Conv_ALdouble_ALbyte(ALbyte val)
{ return val * (1.0/127.0); }
static inline ALdouble Conv_ALdouble_ALubyte(ALubyte val)
{ return (val-128) * (1.0/127.0); }
static inline ALdouble Conv_ALdouble_ALshort(ALshort val)
{ return val * (1.0/32767.0); }
static inline ALdouble Conv_ALdouble_ALushort(ALushort val)
{ return (val-32768) * (1.0/32767.0); }
static inline ALdouble Conv_ALdouble_ALint(ALint val)
{ return val * (1.0/2147483647.0); }
static inline ALdouble Conv_ALdouble_ALuint(ALuint val)
{ return (ALint)(val-2147483648u) * (1.0/2147483647.0); }
static inline ALdouble Conv_ALdouble_ALfloat(ALfloat val)
{ return (val==val) ? val : 0.0f; }
static inline ALdouble Conv_ALdouble_ALdouble(ALdouble val)
{ return (val==val) ? val : 0.0; }
static inline ALdouble Conv_ALdouble_ALmulaw(ALmulaw val)
{ return Conv_ALdouble_ALshort(DecodeMuLaw(val)); }
static inline ALdouble Conv_ALdouble_ALalaw(ALalaw val)
{ return Conv_ALdouble_ALshort(DecodeALaw(val)); }
static inline ALdouble Conv_ALdouble_ALbyte3(ALbyte3 val)
{ return DecodeByte3(val) * (1.0/8388607.0); }
static inline ALdouble Conv_ALdouble_ALubyte3(ALubyte3 val)
{ return (DecodeUByte3(val)-8388608) * (1.0/8388607.0); }
#define DECL_TEMPLATE(T) \
static inline ALmulaw Conv_ALmulaw_##T(T val) \
{ return EncodeMuLaw(Conv_ALshort_##T(val)); }
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
static inline ALmulaw Conv_ALmulaw_ALmulaw(ALmulaw val)
{ return val; }
DECL_TEMPLATE(ALalaw)
DECL_TEMPLATE(ALbyte3)
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static inline ALalaw Conv_ALalaw_##T(T val) \
{ return EncodeALaw(Conv_ALshort_##T(val)); }
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
static inline ALalaw Conv_ALalaw_ALalaw(ALalaw val)
{ return val; }
DECL_TEMPLATE(ALbyte3)
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static inline ALbyte3 Conv_ALbyte3_##T(T val) \
{ return EncodeByte3(Conv_ALint_##T(val)>>8); }
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
DECL_TEMPLATE(ALalaw)
static inline ALbyte3 Conv_ALbyte3_ALbyte3(ALbyte3 val)
{ return val; }
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static inline ALubyte3 Conv_ALubyte3_##T(T val) \
{ return EncodeUByte3(Conv_ALuint_##T(val)>>8); }
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
DECL_TEMPLATE(ALalaw)
DECL_TEMPLATE(ALbyte3)
static inline ALubyte3 Conv_ALubyte3_ALubyte3(ALubyte3 val)
{ return val; }
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T1, T2) \
static void Convert_##T1##_##T2(T1 *dst, const T2 *src, ALuint numchans, \
ALuint len) \
{ \
ALuint i, j; \
for(i = 0;i < len;i++) \
{ \
for(j = 0;j < numchans;j++) \
*(dst++) = Conv_##T1##_##T2(*(src++)); \
} \
}
DECL_TEMPLATE(ALbyte, ALbyte)
DECL_TEMPLATE(ALbyte, ALubyte)
DECL_TEMPLATE(ALbyte, ALshort)
DECL_TEMPLATE(ALbyte, ALushort)
DECL_TEMPLATE(ALbyte, ALint)
DECL_TEMPLATE(ALbyte, ALuint)
DECL_TEMPLATE(ALbyte, ALfloat)
DECL_TEMPLATE(ALbyte, ALdouble)
DECL_TEMPLATE(ALbyte, ALmulaw)
DECL_TEMPLATE(ALbyte, ALalaw)
DECL_TEMPLATE(ALbyte, ALbyte3)
DECL_TEMPLATE(ALbyte, ALubyte3)
DECL_TEMPLATE(ALubyte, ALbyte)
DECL_TEMPLATE(ALubyte, ALubyte)
DECL_TEMPLATE(ALubyte, ALshort)
DECL_TEMPLATE(ALubyte, ALushort)
DECL_TEMPLATE(ALubyte, ALint)
DECL_TEMPLATE(ALubyte, ALuint)
DECL_TEMPLATE(ALubyte, ALfloat)
DECL_TEMPLATE(ALubyte, ALdouble)
DECL_TEMPLATE(ALubyte, ALmulaw)
DECL_TEMPLATE(ALubyte, ALalaw)
DECL_TEMPLATE(ALubyte, ALbyte3)
DECL_TEMPLATE(ALubyte, ALubyte3)
DECL_TEMPLATE(ALshort, ALbyte)
DECL_TEMPLATE(ALshort, ALubyte)
DECL_TEMPLATE(ALshort, ALshort)
DECL_TEMPLATE(ALshort, ALushort)
DECL_TEMPLATE(ALshort, ALint)
DECL_TEMPLATE(ALshort, ALuint)
DECL_TEMPLATE(ALshort, ALfloat)
DECL_TEMPLATE(ALshort, ALdouble)
DECL_TEMPLATE(ALshort, ALmulaw)
DECL_TEMPLATE(ALshort, ALalaw)
DECL_TEMPLATE(ALshort, ALbyte3)
DECL_TEMPLATE(ALshort, ALubyte3)
DECL_TEMPLATE(ALushort, ALbyte)
DECL_TEMPLATE(ALushort, ALubyte)
DECL_TEMPLATE(ALushort, ALshort)
DECL_TEMPLATE(ALushort, ALushort)
DECL_TEMPLATE(ALushort, ALint)
DECL_TEMPLATE(ALushort, ALuint)
DECL_TEMPLATE(ALushort, ALfloat)
DECL_TEMPLATE(ALushort, ALdouble)
DECL_TEMPLATE(ALushort, ALmulaw)
DECL_TEMPLATE(ALushort, ALalaw)
DECL_TEMPLATE(ALushort, ALbyte3)
DECL_TEMPLATE(ALushort, ALubyte3)
DECL_TEMPLATE(ALint, ALbyte)
DECL_TEMPLATE(ALint, ALubyte)
DECL_TEMPLATE(ALint, ALshort)
DECL_TEMPLATE(ALint, ALushort)
DECL_TEMPLATE(ALint, ALint)
DECL_TEMPLATE(ALint, ALuint)
DECL_TEMPLATE(ALint, ALfloat)
DECL_TEMPLATE(ALint, ALdouble)
DECL_TEMPLATE(ALint, ALmulaw)
DECL_TEMPLATE(ALint, ALalaw)
DECL_TEMPLATE(ALint, ALbyte3)
DECL_TEMPLATE(ALint, ALubyte3)
DECL_TEMPLATE(ALuint, ALbyte)
DECL_TEMPLATE(ALuint, ALubyte)
DECL_TEMPLATE(ALuint, ALshort)
DECL_TEMPLATE(ALuint, ALushort)
DECL_TEMPLATE(ALuint, ALint)
DECL_TEMPLATE(ALuint, ALuint)
DECL_TEMPLATE(ALuint, ALfloat)
DECL_TEMPLATE(ALuint, ALdouble)
DECL_TEMPLATE(ALuint, ALmulaw)
DECL_TEMPLATE(ALuint, ALalaw)
DECL_TEMPLATE(ALuint, ALbyte3)
DECL_TEMPLATE(ALuint, ALubyte3)
DECL_TEMPLATE(ALfloat, ALbyte)
DECL_TEMPLATE(ALfloat, ALubyte)
DECL_TEMPLATE(ALfloat, ALshort)
DECL_TEMPLATE(ALfloat, ALushort)
DECL_TEMPLATE(ALfloat, ALint)
DECL_TEMPLATE(ALfloat, ALuint)
DECL_TEMPLATE(ALfloat, ALfloat)
DECL_TEMPLATE(ALfloat, ALdouble)
DECL_TEMPLATE(ALfloat, ALmulaw)
DECL_TEMPLATE(ALfloat, ALalaw)
DECL_TEMPLATE(ALfloat, ALbyte3)
DECL_TEMPLATE(ALfloat, ALubyte3)
DECL_TEMPLATE(ALdouble, ALbyte)
DECL_TEMPLATE(ALdouble, ALubyte)
DECL_TEMPLATE(ALdouble, ALshort)
DECL_TEMPLATE(ALdouble, ALushort)
DECL_TEMPLATE(ALdouble, ALint)
DECL_TEMPLATE(ALdouble, ALuint)
DECL_TEMPLATE(ALdouble, ALfloat)
DECL_TEMPLATE(ALdouble, ALdouble)
DECL_TEMPLATE(ALdouble, ALmulaw)
DECL_TEMPLATE(ALdouble, ALalaw)
DECL_TEMPLATE(ALdouble, ALbyte3)
DECL_TEMPLATE(ALdouble, ALubyte3)
DECL_TEMPLATE(ALmulaw, ALbyte)
DECL_TEMPLATE(ALmulaw, ALubyte)
DECL_TEMPLATE(ALmulaw, ALshort)
DECL_TEMPLATE(ALmulaw, ALushort)
DECL_TEMPLATE(ALmulaw, ALint)
DECL_TEMPLATE(ALmulaw, ALuint)
DECL_TEMPLATE(ALmulaw, ALfloat)
DECL_TEMPLATE(ALmulaw, ALdouble)
DECL_TEMPLATE(ALmulaw, ALmulaw)
DECL_TEMPLATE(ALmulaw, ALalaw)
DECL_TEMPLATE(ALmulaw, ALbyte3)
DECL_TEMPLATE(ALmulaw, ALubyte3)
DECL_TEMPLATE(ALalaw, ALbyte)
DECL_TEMPLATE(ALalaw, ALubyte)
DECL_TEMPLATE(ALalaw, ALshort)
DECL_TEMPLATE(ALalaw, ALushort)
DECL_TEMPLATE(ALalaw, ALint)
DECL_TEMPLATE(ALalaw, ALuint)
DECL_TEMPLATE(ALalaw, ALfloat)
DECL_TEMPLATE(ALalaw, ALdouble)
DECL_TEMPLATE(ALalaw, ALmulaw)
DECL_TEMPLATE(ALalaw, ALalaw)
DECL_TEMPLATE(ALalaw, ALbyte3)
DECL_TEMPLATE(ALalaw, ALubyte3)
DECL_TEMPLATE(ALbyte3, ALbyte)
DECL_TEMPLATE(ALbyte3, ALubyte)
DECL_TEMPLATE(ALbyte3, ALshort)
DECL_TEMPLATE(ALbyte3, ALushort)
DECL_TEMPLATE(ALbyte3, ALint)
DECL_TEMPLATE(ALbyte3, ALuint)
DECL_TEMPLATE(ALbyte3, ALfloat)
DECL_TEMPLATE(ALbyte3, ALdouble)
DECL_TEMPLATE(ALbyte3, ALmulaw)
DECL_TEMPLATE(ALbyte3, ALalaw)
DECL_TEMPLATE(ALbyte3, ALbyte3)
DECL_TEMPLATE(ALbyte3, ALubyte3)
DECL_TEMPLATE(ALubyte3, ALbyte)
DECL_TEMPLATE(ALubyte3, ALubyte)
DECL_TEMPLATE(ALubyte3, ALshort)
DECL_TEMPLATE(ALubyte3, ALushort)
DECL_TEMPLATE(ALubyte3, ALint)
DECL_TEMPLATE(ALubyte3, ALuint)
DECL_TEMPLATE(ALubyte3, ALfloat)
DECL_TEMPLATE(ALubyte3, ALdouble)
DECL_TEMPLATE(ALubyte3, ALmulaw)
DECL_TEMPLATE(ALubyte3, ALalaw)
DECL_TEMPLATE(ALubyte3, ALbyte3)
DECL_TEMPLATE(ALubyte3, ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static void Convert_##T##_ALima4(T *dst, const ALima4 *src, ALuint numchans, \
ALuint len) \
{ \
ALshort tmp[65*MAX_INPUT_CHANNELS]; /* Max samples an IMA4 frame can be */\
ALuint i, j, k; \
\
i = 0; \
while(i < len) \
{ \
DecodeIMA4Block(tmp, src, numchans); \
src += 36*numchans; \
\
for(j = 0;j < 65 && i < len;j++,i++) \
{ \
for(k = 0;k < numchans;k++) \
*(dst++) = Conv_##T##_ALshort(tmp[j*numchans + k]); \
} \
} \
}
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
DECL_TEMPLATE(ALalaw)
DECL_TEMPLATE(ALbyte3)
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static void Convert_ALima4_##T(ALima4 *dst, const T *src, ALuint numchans, \
ALuint len) \
{ \
ALshort tmp[65*MAX_INPUT_CHANNELS]; /* Max samples an IMA4 frame can be */\
ALint sample[MaxChannels] = {0,0,0,0,0,0,0,0}; \
ALint index[MaxChannels] = {0,0,0,0,0,0,0,0}; \
ALuint i, j; \
\
for(i = 0;i < len;i += 65) \
{ \
for(j = 0;j < 65*numchans;j++) \
tmp[j] = Conv_ALshort_##T(*(src++)); \
EncodeIMA4Block(dst, tmp, sample, index, numchans); \
dst += 36*numchans; \
} \
}
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
DECL_TEMPLATE(ALalaw)
static void Convert_ALima4_ALima4(ALima4 *dst, const ALima4 *src,
ALuint numchans, ALuint numblocks)
{ memcpy(dst, src, numblocks*36*numchans); }
DECL_TEMPLATE(ALbyte3)
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
#define DECL_TEMPLATE(T) \
static void Convert_##T(T *dst, const ALvoid *src, enum UserFmtType srcType, \
ALsizei numchans, ALsizei len) \
{ \
switch(srcType) \
{ \
case UserFmtByte: \
Convert_##T##_ALbyte(dst, src, numchans, len); \
break; \
case UserFmtUByte: \
Convert_##T##_ALubyte(dst, src, numchans, len); \
break; \
case UserFmtShort: \
Convert_##T##_ALshort(dst, src, numchans, len); \
break; \
case UserFmtUShort: \
Convert_##T##_ALushort(dst, src, numchans, len); \
break; \
case UserFmtInt: \
Convert_##T##_ALint(dst, src, numchans, len); \
break; \
case UserFmtUInt: \
Convert_##T##_ALuint(dst, src, numchans, len); \
break; \
case UserFmtFloat: \
Convert_##T##_ALfloat(dst, src, numchans, len); \
break; \
case UserFmtDouble: \
Convert_##T##_ALdouble(dst, src, numchans, len); \
break; \
case UserFmtMulaw: \
Convert_##T##_ALmulaw(dst, src, numchans, len); \
break; \
case UserFmtAlaw: \
Convert_##T##_ALalaw(dst, src, numchans, len); \
break; \
case UserFmtIMA4: \
Convert_##T##_ALima4(dst, src, numchans, len); \
break; \
case UserFmtByte3: \
Convert_##T##_ALbyte3(dst, src, numchans, len); \
break; \
case UserFmtUByte3: \
Convert_##T##_ALubyte3(dst, src, numchans, len); \
break; \
} \
}
DECL_TEMPLATE(ALbyte)
DECL_TEMPLATE(ALubyte)
DECL_TEMPLATE(ALshort)
DECL_TEMPLATE(ALushort)
DECL_TEMPLATE(ALint)
DECL_TEMPLATE(ALuint)
DECL_TEMPLATE(ALfloat)
DECL_TEMPLATE(ALdouble)
DECL_TEMPLATE(ALmulaw)
DECL_TEMPLATE(ALalaw)
DECL_TEMPLATE(ALima4)
DECL_TEMPLATE(ALbyte3)
DECL_TEMPLATE(ALubyte3)
#undef DECL_TEMPLATE
static void ConvertData(ALvoid *dst, enum UserFmtType dstType, const ALvoid *src, enum UserFmtType srcType, ALsizei numchans, ALsizei len)
{
switch(dstType)
{
case UserFmtByte:
Convert_ALbyte(dst, src, srcType, numchans, len);
break;
case UserFmtUByte:
Convert_ALubyte(dst, src, srcType, numchans, len);
break;
case UserFmtShort:
Convert_ALshort(dst, src, srcType, numchans, len);
break;
case UserFmtUShort:
Convert_ALushort(dst, src, srcType, numchans, len);
break;
case UserFmtInt:
Convert_ALint(dst, src, srcType, numchans, len);
break;
case UserFmtUInt:
Convert_ALuint(dst, src, srcType, numchans, len);
break;
case UserFmtFloat:
Convert_ALfloat(dst, src, srcType, numchans, len);
break;
case UserFmtDouble:
Convert_ALdouble(dst, src, srcType, numchans, len);
break;
case UserFmtMulaw:
Convert_ALmulaw(dst, src, srcType, numchans, len);
break;
case UserFmtAlaw:
Convert_ALalaw(dst, src, srcType, numchans, len);
break;
case UserFmtIMA4:
Convert_ALima4(dst, src, srcType, numchans, len);
break;
case UserFmtByte3:
Convert_ALbyte3(dst, src, srcType, numchans, len);
break;
case UserFmtUByte3:
Convert_ALubyte3(dst, src, srcType, numchans, len);
break;
}
}
/*
* LoadData
*
* Loads the specified data into the buffer, using the specified formats.
* Currently, the new format must have the same channel configuration as the
* original format.
*/
static ALenum LoadData(ALbuffer *ALBuf, ALuint freq, ALenum NewFormat, ALsizei frames, enum UserFmtChannels SrcChannels, enum UserFmtType SrcType, const ALvoid *data, ALboolean storesrc)
{
ALuint NewChannels, NewBytes;
enum FmtChannels DstChannels;
enum FmtType DstType;
ALuint64 newsize;
ALvoid *temp;
if(DecomposeFormat(NewFormat, &DstChannels, &DstType) == AL_FALSE ||
(long)SrcChannels != (long)DstChannels)
return AL_INVALID_ENUM;
NewChannels = ChannelsFromFmt(DstChannels);
NewBytes = BytesFromFmt(DstType);
newsize = frames;
newsize *= NewBytes;
newsize *= NewChannels;
if(newsize > INT_MAX)
return AL_OUT_OF_MEMORY;
WriteLock(&ALBuf->lock);
if(ALBuf->ref != 0)
{
WriteUnlock(&ALBuf->lock);
return AL_INVALID_OPERATION;
}
temp = realloc(ALBuf->data, (size_t)newsize);
if(!temp && newsize)
{
WriteUnlock(&ALBuf->lock);
return AL_OUT_OF_MEMORY;
}
ALBuf->data = temp;
if(data != NULL)
ConvertData(ALBuf->data, (enum UserFmtType)DstType, data, SrcType, NewChannels, frames);
if(storesrc)
{
ALBuf->OriginalChannels = SrcChannels;
ALBuf->OriginalType = SrcType;
if(SrcType == UserFmtIMA4)
ALBuf->OriginalSize = frames / 65 * 36 * ChannelsFromUserFmt(SrcChannels);
else
ALBuf->OriginalSize = frames * FrameSizeFromUserFmt(SrcChannels, SrcType);
}
else
{
ALBuf->OriginalChannels = (enum UserFmtChannels)DstChannels;
ALBuf->OriginalType = (enum UserFmtType)DstType;
ALBuf->OriginalSize = frames * NewBytes * NewChannels;
}
ALBuf->Frequency = freq;
ALBuf->FmtChannels = DstChannels;
ALBuf->FmtType = DstType;
ALBuf->Format = NewFormat;
ALBuf->SampleLen = frames;
ALBuf->LoopStart = 0;
ALBuf->LoopEnd = ALBuf->SampleLen;
WriteUnlock(&ALBuf->lock);
return AL_NO_ERROR;
}
ALuint BytesFromUserFmt(enum UserFmtType type)
{
switch(type)
{
case UserFmtByte: return sizeof(ALbyte);
case UserFmtUByte: return sizeof(ALubyte);
case UserFmtShort: return sizeof(ALshort);
case UserFmtUShort: return sizeof(ALushort);
case UserFmtInt: return sizeof(ALint);
case UserFmtUInt: return sizeof(ALuint);
case UserFmtFloat: return sizeof(ALfloat);
case UserFmtDouble: return sizeof(ALdouble);
case UserFmtByte3: return sizeof(ALbyte3);
case UserFmtUByte3: return sizeof(ALubyte3);
case UserFmtMulaw: return sizeof(ALubyte);
case UserFmtAlaw: return sizeof(ALubyte);
case UserFmtIMA4: break; /* not handled here */
}
return 0;
}
ALuint ChannelsFromUserFmt(enum UserFmtChannels chans)
{
switch(chans)
{
case UserFmtMono: return 1;
case UserFmtStereo: return 2;
case UserFmtRear: return 2;
case UserFmtQuad: return 4;
case UserFmtX51: return 6;
case UserFmtX61: return 7;
case UserFmtX71: return 8;
}
return 0;
}
static ALboolean DecomposeUserFormat(ALenum format, enum UserFmtChannels *chans,
enum UserFmtType *type)
{
static const struct {
ALenum format;
enum UserFmtChannels channels;
enum UserFmtType type;
} list[] = {
{ AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte },
{ AL_FORMAT_MONO16, UserFmtMono, UserFmtShort },
{ AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat },
{ AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble },
{ AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 },
{ AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw },
{ AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw },
{ AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte },
{ AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort },
{ AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat },
{ AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble },
{ AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 },
{ AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw },
{ AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw },
{ AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte },
{ AL_FORMAT_REAR16, UserFmtRear, UserFmtShort },
{ AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat },
{ AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw },
{ AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte },
{ AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort },
{ AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte },
{ AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort },
{ AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat },
{ AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw },
{ AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte },
{ AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort },
{ AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat },
{ AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw },
{ AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte },
{ AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort },
{ AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat },
{ AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw },
{ AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte },
{ AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort },
{ AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat },
{ AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw },
};
ALuint i;
for(i = 0;i < COUNTOF(list);i++)
{
if(list[i].format == format)
{
*chans = list[i].channels;
*type = list[i].type;
return AL_TRUE;
}
}
return AL_FALSE;
}
ALuint BytesFromFmt(enum FmtType type)
{
switch(type)
{
case FmtByte: return sizeof(ALbyte);
case FmtShort: return sizeof(ALshort);
case FmtFloat: return sizeof(ALfloat);
}
return 0;
}
ALuint ChannelsFromFmt(enum FmtChannels chans)
{
switch(chans)
{
case FmtMono: return 1;
case FmtStereo: return 2;
case FmtRear: return 2;
case FmtQuad: return 4;
case FmtX51: return 6;
case FmtX61: return 7;
case FmtX71: return 8;
}
return 0;
}
static ALboolean DecomposeFormat(ALenum format, enum FmtChannels *chans, enum FmtType *type)
{
static const struct {
ALenum format;
enum FmtChannels channels;
enum FmtType type;
} list[] = {
{ AL_MONO8_SOFT, FmtMono, FmtByte },
{ AL_MONO16_SOFT, FmtMono, FmtShort },
{ AL_MONO32F_SOFT, FmtMono, FmtFloat },
{ AL_STEREO8_SOFT, FmtStereo, FmtByte },
{ AL_STEREO16_SOFT, FmtStereo, FmtShort },
{ AL_STEREO32F_SOFT, FmtStereo, FmtFloat },
{ AL_REAR8_SOFT, FmtRear, FmtByte },
{ AL_REAR16_SOFT, FmtRear, FmtShort },
{ AL_REAR32F_SOFT, FmtRear, FmtFloat },
{ AL_FORMAT_QUAD8_LOKI, FmtQuad, FmtByte },
{ AL_FORMAT_QUAD16_LOKI, FmtQuad, FmtShort },
{ AL_QUAD8_SOFT, FmtQuad, FmtByte },
{ AL_QUAD16_SOFT, FmtQuad, FmtShort },
{ AL_QUAD32F_SOFT, FmtQuad, FmtFloat },
{ AL_5POINT1_8_SOFT, FmtX51, FmtByte },
{ AL_5POINT1_16_SOFT, FmtX51, FmtShort },
{ AL_5POINT1_32F_SOFT, FmtX51, FmtFloat },
{ AL_6POINT1_8_SOFT, FmtX61, FmtByte },
{ AL_6POINT1_16_SOFT, FmtX61, FmtShort },
{ AL_6POINT1_32F_SOFT, FmtX61, FmtFloat },
{ AL_7POINT1_8_SOFT, FmtX71, FmtByte },
{ AL_7POINT1_16_SOFT, FmtX71, FmtShort },
{ AL_7POINT1_32F_SOFT, FmtX71, FmtFloat },
};
ALuint i;
for(i = 0;i < COUNTOF(list);i++)
{
if(list[i].format == format)
{
*chans = list[i].channels;
*type = list[i].type;
return AL_TRUE;
}
}
return AL_FALSE;
}
static ALboolean IsValidType(ALenum type)
{
switch(type)
{
case AL_BYTE_SOFT:
case AL_UNSIGNED_BYTE_SOFT:
case AL_SHORT_SOFT:
case AL_UNSIGNED_SHORT_SOFT:
case AL_INT_SOFT:
case AL_UNSIGNED_INT_SOFT:
case AL_FLOAT_SOFT:
case AL_DOUBLE_SOFT:
case AL_BYTE3_SOFT:
case AL_UNSIGNED_BYTE3_SOFT:
return AL_TRUE;
}
return AL_FALSE;
}
static ALboolean IsValidChannels(ALenum channels)
{
switch(channels)
{
case AL_MONO_SOFT:
case AL_STEREO_SOFT:
case AL_REAR_SOFT:
case AL_QUAD_SOFT:
case AL_5POINT1_SOFT:
case AL_6POINT1_SOFT:
case AL_7POINT1_SOFT:
return AL_TRUE;
}
return AL_FALSE;
}
/*
* ReleaseALBuffers()
*
* INTERNAL: Called to destroy any buffers that still exist on the device
*/
ALvoid ReleaseALBuffers(ALCdevice *device)
{
ALsizei i;
for(i = 0;i < device->BufferMap.size;i++)
{
ALbuffer *temp = device->BufferMap.array[i].value;
device->BufferMap.array[i].value = NULL;
free(temp->data);
FreeThunkEntry(temp->id);
memset(temp, 0, sizeof(ALbuffer));
free(temp);
}
}
|
DKGL/DKGL
|
DK/lib/OpenAL/OpenAL32/alBuffer.c
|
C
|
bsd-3-clause
| 72,195 | 31.20116 | 186 | 0.569181 | false |
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferScene/Plane.h"
#include "IECoreScene/MeshPrimitive.h"
using namespace Gaffer;
using namespace GafferScene;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Plane );
size_t Plane::g_firstPlugIndex = 0;
Plane::Plane( const std::string &name )
: ObjectSource( name, "plane" )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new V2fPlug( "dimensions", Plug::In, V2f( 1.0f ), V2f( 0.0f ) ) );
addChild( new V2iPlug( "divisions", Plug::In, V2i( 1 ), V2i( 1 ) ) );
}
Plane::~Plane()
{
}
Gaffer::V2fPlug *Plane::dimensionsPlug()
{
return getChild<V2fPlug>( g_firstPlugIndex );
}
const Gaffer::V2fPlug *Plane::dimensionsPlug() const
{
return getChild<V2fPlug>( g_firstPlugIndex );
}
Gaffer::V2iPlug *Plane::divisionsPlug()
{
return getChild<V2iPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::V2iPlug *Plane::divisionsPlug() const
{
return getChild<V2iPlug>( g_firstPlugIndex + 1 );
}
void Plane::affects( const Plug *input, AffectedPlugsContainer &outputs ) const
{
ObjectSource::affects( input, outputs );
if ( input->parent<V2fPlug>() == dimensionsPlug() || input->parent<V2iPlug>() == divisionsPlug() )
{
outputs.push_back( sourcePlug() );
}
}
void Plane::hashSource( const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
dimensionsPlug()->hash( h );
divisionsPlug()->hash( h );
}
IECore::ConstObjectPtr Plane::computeSource( const Context *context ) const
{
V2f dimensions = dimensionsPlug()->getValue();
return MeshPrimitive::createPlane( Box2f( -dimensions / 2.0f, dimensions / 2.0f ), divisionsPlug()->getValue() );
}
|
lucienfostier/gaffer
|
src/GafferScene/Plane.cpp
|
C++
|
bsd-3-clause
| 3,536 | 33 | 114 | 0.688914 | false |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed 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.
==============================================================================*/
#ifndef TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_TOKENIZER_JNI_LIB_H_
#define TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_TOKENIZER_JNI_LIB_H_
#include <jni.h>
#include <string>
#include "tensorflow_lite_support/cc/text/tokenizers/tokenizer.h"
#include "tensorflow_lite_support/cc/utils/jni_utils.h"
namespace tflite {
namespace support {
jobjectArray nativeTokenize(JNIEnv* env, jlong handle, jstring jtext);
jintArray nativeConvertTokensToIds(JNIEnv* env,
jlong handle,
jobjectArray jtokens);
} // namespace support
} // namespace tflite
#endif // TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_TOKENIZER_JNI_LIB_H_
|
scheib/chromium
|
third_party/tflite_support/src/tensorflow_lite_support/cc/text/tokenizers/tokenizer_jni_lib.h
|
C
|
bsd-3-clause
| 1,365 | 35.891892 | 80 | 0.700366 | false |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="null" lang="null">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>CSVRendererTest xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />
</head>
<body>
<pre>
<a name="1" href="#1">1</a> <em>/**</em>
<a name="2" href="#2">2</a> <em> * BSD-style license; for more info see <a href="http://pmd.sourceforge.net/license.html" target="alexandria_uri">http://pmd.sourceforge.net/license.html</a></em>
<a name="3" href="#3">3</a> <em> */</em>
<a name="4" href="#4">4</a> <strong>package</strong> test.net.sourceforge.pmd.renderers;
<a name="5" href="#5">5</a>
<a name="6" href="#6">6</a> <strong>import</strong> net.sourceforge.pmd.PMD;
<a name="7" href="#7">7</a> <strong>import</strong> net.sourceforge.pmd.Report.ProcessingError;
<a name="8" href="#8">8</a> <strong>import</strong> net.sourceforge.pmd.renderers.AbstractRenderer;
<a name="9" href="#9">9</a> <strong>import</strong> net.sourceforge.pmd.renderers.CSVRenderer;
<a name="10" href="#10">10</a>
<a name="11" href="#11">11</a> <strong>public</strong> <strong>class</strong> <a href="../../../../../test/net/sourceforge/pmd/renderers/CSVRendererTest.html">CSVRendererTest</a> <strong>extends</strong> <a href="../../../../../test/net/sourceforge/pmd/renderers/AbstractRendererTst.html">AbstractRendererTst</a> {
<a name="12" href="#12">12</a>
<a name="13" href="#13">13</a> <strong>public</strong> AbstractRenderer getRenderer() {
<a name="14" href="#14">14</a> <strong>return</strong> <strong>new</strong> CSVRenderer();
<a name="15" href="#15">15</a> }
<a name="16" href="#16">16</a>
<a name="17" href="#17">17</a> <strong>public</strong> String getExpected() {
<a name="18" href="#18">18</a> <strong>return</strong> <span class="string">"\"Problem\",\"Package\",\"File\",\"Priority\",\"Line\",\"Description\",\"Rule set\",\"Rule\""</span> + PMD.EOL
<a name="19" href="#19">19</a> + <span class="string">"\"1\",\"\",\"n/a\",\"5\",\"1\",\"msg\",\"RuleSet\",\"Foo\""</span> + PMD.EOL;
<a name="20" href="#20">20</a> }
<a name="21" href="#21">21</a>
<a name="22" href="#22">22</a> <strong>public</strong> String getExpectedEmpty() {
<a name="23" href="#23">23</a> <strong>return</strong> <span class="string">"\"Problem\",\"Package\",\"File\",\"Priority\",\"Line\",\"Description\",\"Rule set\",\"Rule\""</span> + PMD.EOL;
<a name="24" href="#24">24</a> }
<a name="25" href="#25">25</a>
<a name="26" href="#26">26</a> <strong>public</strong> String getExpectedMultiple() {
<a name="27" href="#27">27</a> <strong>return</strong> <span class="string">"\"Problem\",\"Package\",\"File\",\"Priority\",\"Line\",\"Description\",\"Rule set\",\"Rule\""</span> + PMD.EOL
<a name="28" href="#28">28</a> + <span class="string">"\"1\",\"\",\"n/a\",\"5\",\"1\",\"msg\",\"RuleSet\",\"Foo\""</span> + PMD.EOL
<a name="29" href="#29">29</a> + <span class="string">"\"2\",\"\",\"n/a\",\"5\",\"1\",\"msg\",\"RuleSet\",\"Foo\""</span> + PMD.EOL;
<a name="30" href="#30">30</a> }
<a name="31" href="#31">31</a>
<a name="32" href="#32">32</a> <strong>public</strong> String getExpectedError(ProcessingError error) {
<a name="33" href="#33">33</a> <strong>return</strong> <span class="string">"\"Problem\",\"Package\",\"File\",\"Priority\",\"Line\",\"Description\",\"Rule set\",\"Rule\""</span> + PMD.EOL;
<a name="34" href="#34">34</a> }
<a name="35" href="#35">35</a>
<a name="36" href="#36">36</a> <strong>public</strong> <strong>static</strong> junit.framework.Test suite() {
<a name="37" href="#37">37</a> <strong>return</strong> <strong>new</strong> junit.framework.JUnit4TestAdapter(CSVRendererTest.<strong>class</strong>);
<a name="38" href="#38">38</a> }
<a name="39" href="#39">39</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
pscadiz/pmd-4.2.6-gds
|
docs/xref-test/test/net/sourceforge/pmd/renderers/CSVRendererTest.html
|
HTML
|
bsd-3-clause
| 4,762 | 90.576923 | 315 | 0.616758 | false |
# encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require 'gooddata'
describe GoodData::Subscription, :constraint => 'slow' do
before(:all) do
@client = ConnectionHelper.create_default_connection
@channel = GoodData::ChannelConfiguration.create(client: @client)
subscriptions = GoodData::Subscription.all(project: ProjectHelper::PROJECT_ID, client: @client)
subscriptions.each(&:delete)
end
after(:all) do
@channel && @channel.delete
@client && @client.disconnect
end
it 'should be able to create a subscription' do
begin
subscription = GoodData::Subscription.create(client: @client, project: ProjectHelper::PROJECT_ID, channels: @channel, message: 'hello world', process: ProcessHelper::PROCESS_ID, project_events: GoodData::Subscription::PROCESS_SUCCESS_EVENT)
expect(subscription.title).to eq ConnectionHelper::DEFAULT_USERNAME
expect(subscription.channels).to eq [@channel.uri]
expect(subscription.message).to eq 'hello world'
expect(subscription.process).to eq ProcessHelper::PROCESS_ID
expect(subscription.project_events).to eq [GoodData::Subscription::PROCESS_SUCCESS_EVENT]
ensure
subscription && subscription.delete
end
end
it 'should be able to edit a subscription' do
begin
subscription = GoodData::Subscription.create(client: @client, project: ProjectHelper::PROJECT_ID, channels: @channel, process: ProcessHelper::PROCESS_ID, project_events: GoodData::Subscription::PROCESS_SUCCESS_EVENT)
expect(subscription.title).to eq ConnectionHelper::DEFAULT_USERNAME
subscription.title = 'My title'
subscription.save
expect(GoodData::Subscription[subscription.subscription_id, project: ProjectHelper::PROJECT_ID, client: @client].title).to eq 'My title'
ensure
subscription && subscription.delete
end
end
it 'should be able to list all subscriptions' do
begin
expect(GoodData::Subscription.all(project: ProjectHelper::PROJECT_ID, client: @client)).to eq []
subscription = GoodData::Subscription.create(client: @client, project: ProjectHelper::PROJECT_ID, channels: @channel, process: ProcessHelper::PROCESS_ID, project_events: GoodData::Subscription::PROCESS_SUCCESS_EVENT)
expect(GoodData::Subscription.all(project: ProjectHelper::PROJECT_ID, client: @client)).to eq [subscription]
ensure
subscription && subscription.delete
end
end
it 'should be able to delete a subscription' do
subscription = GoodData::Subscription.create(client: @client, project: ProjectHelper::PROJECT_ID, channels: @channel, process: ProcessHelper::PROCESS_ID, project_events: GoodData::Subscription::PROCESS_SUCCESS_EVENT)
subscription.delete
end
end
|
Seikitsu/gooddata-ruby
|
spec/integration/subscription_spec.rb
|
Ruby
|
bsd-3-clause
| 2,902 | 45.063492 | 246 | 0.741558 | false |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/tabbed_pane/native_tabbed_pane_win.h"
#include <vssym32.h>
#include "base/logging.h"
#include "base/stl_util.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/win/hwnd_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font.h"
#include "ui/native_theme/native_theme_win.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane.h"
#include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
namespace views {
// A background object that paints the tab panel background which may be
// rendered by the system visual styles system.
class TabBackground : public Background {
public:
explicit TabBackground() {
// TMT_FILLCOLORHINT returns a color value that supposedly
// approximates the texture drawn by PaintTabPanelBackground.
SkColor tab_page_color =
ui::NativeThemeWin::instance()->GetThemeColorWithDefault(
ui::NativeThemeWin::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT,
COLOR_3DFACE);
SetNativeControlColor(tab_page_color);
}
virtual ~TabBackground() {}
virtual void Paint(gfx::Canvas* canvas, View* view) const {
gfx::Rect r(0, 0, view->width(), view->height());
ui::NativeTheme::ExtraParams extra;
ui::NativeTheme::instance()->Paint(
canvas->sk_canvas(), ui::NativeTheme::kTabPanelBackground,
ui::NativeTheme::kNormal, r, extra);
}
private:
DISALLOW_COPY_AND_ASSIGN(TabBackground);
};
// Custom layout manager that takes care of sizing and displaying the tab pages.
class TabLayout : public LayoutManager {
public:
TabLayout() {}
// Switches to the tab page identified by the given index.
void SwitchToPage(View* host, View* page) {
for (int i = 0; i < host->child_count(); ++i) {
View* child = host->child_at(i);
// The child might not have been laid out yet.
if (child == page)
child->SetBoundsRect(host->GetContentsBounds());
child->SetVisible(child == page);
}
FocusManager* focus_manager = page->GetFocusManager();
DCHECK(focus_manager);
const View* focused_view = focus_manager->GetFocusedView();
if (focused_view && host->Contains(focused_view) &&
!page->Contains(focused_view))
focus_manager->SetFocusedView(page);
}
private:
// LayoutManager overrides:
virtual void Layout(View* host) {
gfx::Rect bounds(host->GetContentsBounds());
for (int i = 0; i < host->child_count(); ++i) {
View* child = host->child_at(i);
// We only layout visible children, since it may be expensive.
if (child->visible() && child->bounds() != bounds)
child->SetBoundsRect(bounds);
}
}
virtual gfx::Size GetPreferredSize(View* host) {
// First, query the preferred sizes to determine a good width.
int width = 0;
for (int i = 0; i < host->child_count(); ++i) {
View* page = host->child_at(i);
width = std::max(width, page->GetPreferredSize().width());
}
// After we know the width, decide on the height.
return gfx::Size(width, GetPreferredHeightForWidth(host, width));
}
virtual int GetPreferredHeightForWidth(View* host, int width) {
int height = 0;
for (int i = 0; i < host->child_count(); ++i) {
View* page = host->child_at(i);
height = std::max(height, page->GetHeightForWidth(width));
}
return height;
}
DISALLOW_COPY_AND_ASSIGN(TabLayout);
};
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, public:
NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane)
: NativeControlWin(),
tabbed_pane_(tabbed_pane),
tab_layout_manager_(NULL),
content_window_(NULL),
selected_index_(-1) {
// Associates the actual HWND with the tabbed-pane so the tabbed-pane is
// the one considered as having the focus (not the wrapper) when the HWND is
// focused directly (with a click for example).
set_focus_view(tabbed_pane);
}
NativeTabbedPaneWin::~NativeTabbedPaneWin() {
// We own the tab views, let's delete them.
STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end());
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation:
void NativeTabbedPaneWin::AddTab(const string16& title, View* contents) {
AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true);
}
void NativeTabbedPaneWin::AddTabAtIndex(int index,
const string16& title,
View* contents,
bool select_if_first_tab) {
DCHECK(index <= static_cast<int>(tab_views_.size()));
contents->set_owned_by_client();
contents->SetVisible(false);
tab_views_.insert(tab_views_.begin() + index, contents);
tab_titles_.insert(tab_titles_.begin() + index, title);
if (!contents->background())
contents->set_background(new TabBackground);
if (tab_views_.size() == 1 && select_if_first_tab)
selected_index_ = 0;
// Add native tab only if the native control is alreay created.
if (content_window_) {
AddNativeTab(index, title);
// The newly added tab may have made the contents window smaller.
ResizeContents();
View* content_root = content_window_->GetRootView();
content_root->AddChildView(contents);
// Switch to the newly added tab if requested;
if (tab_views_.size() == 1 && select_if_first_tab)
tab_layout_manager_->SwitchToPage(content_root, contents);
}
}
void NativeTabbedPaneWin::AddNativeTab(int index, const string16& title) {
TCITEM tcitem;
tcitem.mask = TCIF_TEXT;
// If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is
// rendered properly on the tabs.
if (base::i18n::IsRTL()) {
tcitem.mask |= TCIF_RTLREADING;
}
tcitem.pszText = const_cast<wchar_t*>(title.c_str());
int result = TabCtrl_InsertItem(native_view(), index, &tcitem);
DCHECK(result != -1);
}
View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) {
int tab_count = static_cast<int>(tab_views_.size());
DCHECK(index >= 0 && index < tab_count);
if (index < (tab_count - 1)) {
// Select the next tab.
SelectTabAt(index + 1);
} else {
// We are the last tab, select the previous one.
if (index > 0) {
SelectTabAt(index - 1);
} else if (content_window_) {
// That was the last tab. Remove the contents.
content_window_->GetRootView()->RemoveAllChildViews(false);
}
}
TabCtrl_DeleteItem(native_view(), index);
// The removed tab may have made the contents window bigger.
if (content_window_)
ResizeContents();
std::vector<View*>::iterator iter = tab_views_.begin() + index;
View* removed_tab = *iter;
if (content_window_)
content_window_->GetRootView()->RemoveChildView(removed_tab);
tab_views_.erase(iter);
tab_titles_.erase(tab_titles_.begin() + index);
return removed_tab;
}
void NativeTabbedPaneWin::SelectTabAt(int index) {
DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size())));
if (native_view())
TabCtrl_SetCurSel(native_view(), index);
DoSelectTabAt(index, true);
}
int NativeTabbedPaneWin::GetTabCount() {
return TabCtrl_GetItemCount(native_view());
}
int NativeTabbedPaneWin::GetSelectedTabIndex() {
return TabCtrl_GetCurSel(native_view());
}
View* NativeTabbedPaneWin::GetSelectedTab() {
if (selected_index_ < 0)
return NULL;
return tab_views_[selected_index_];
}
View* NativeTabbedPaneWin::GetView() {
return this;
}
void NativeTabbedPaneWin::SetFocus() {
// Focus the associated HWND.
OnFocus();
}
gfx::Size NativeTabbedPaneWin::GetPreferredSize() {
if (!native_view())
return gfx::Size();
gfx::Rect contentSize(content_window_->GetRootView()->GetPreferredSize());
RECT paneSize = { 0, 0, contentSize.width(), contentSize.height() };
TabCtrl_AdjustRect(native_view(), TRUE, &paneSize);
return gfx::Size(paneSize.right - paneSize.left,
paneSize.bottom - paneSize.top);
}
gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const {
return native_view();
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, NativeControlWin override:
void NativeTabbedPaneWin::CreateNativeControl() {
// Create the tab control.
//
// Note that we don't follow the common convention for NativeControl
// subclasses and we don't pass the value returned from
// NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is
// why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when
// we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If
// we do that, then the HWND we create for |content_window_| below will
// inherit the WS_EX_LAYOUTRTL property and this will result in the contents
// being flipped, which is not what we want (because we handle mirroring in
// views without the use of Windows' support for mirroring). Therefore,
// we initially create our HWND without WS_EX_LAYOUTRTL and we explicitly set
// this property our child is created. This way, on RTL locales, our tabs
// will be nicely rendered from right to left (by virtue of Windows doing the
// right thing with the TabbedPane HWND) and each tab contents will use an
// RTL layout correctly (by virtue of the mirroring infrastructure in views
// doing the right thing with each View we put in the tab).
DWORD style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_CLIPCHILDREN;
HWND tab_control = ::CreateWindowEx(0,
WC_TABCONTROL,
L"",
style,
0, 0, width(), height(),
GetWidget()->GetNativeView(), NULL, NULL,
NULL);
ui::CheckWindowCreated(tab_control);
HFONT font = ResourceBundle::GetSharedInstance().
GetFont(ResourceBundle::BaseFont).GetNativeFont();
SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE);
// Create the view container which is a child of the TabControl.
content_window_ = new Widget;
Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
params.parent = tab_control;
content_window_->Init(params);
// Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above
// for why we waited until |content_window_| is created before we set this
// property for the tabbed pane's HWND).
if (base::i18n::IsRTL())
l10n_util::HWNDSetRTLLayout(tab_control);
View* root_view = content_window_->GetRootView();
tab_layout_manager_ = new TabLayout();
root_view->SetLayoutManager(tab_layout_manager_);
DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT);
SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color),
GetBValue(sys_color));
root_view->set_background(Background::CreateSolidBackground(color));
content_window_->SetFocusTraversableParentView(this);
NativeControlCreated(tab_control);
// Add tabs that are already added if any.
if (!tab_views_.empty()) {
InitializeTabs();
if (selected_index_ >= 0)
DoSelectTabAt(selected_index_, false);
}
ResizeContents();
}
bool NativeTabbedPaneWin::ProcessMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
if (message == WM_NOTIFY &&
reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) {
int selected_tab = TabCtrl_GetCurSel(native_view());
DCHECK(selected_tab != -1);
DoSelectTabAt(selected_tab, true);
return TRUE;
}
return NativeControlWin::ProcessMessage(message, w_param, l_param, result);
}
////////////////////////////////////////////////////////////////////////////////
// View override:
void NativeTabbedPaneWin::Layout() {
NativeControlWin::Layout();
ResizeContents();
}
FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() {
return content_window_;
}
void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add,
View *parent,
View *child) {
NativeControlWin::ViewHierarchyChanged(is_add, parent, child);
if (is_add && (child == this) && content_window_) {
// We have been added to a view hierarchy, update the FocusTraversable
// parent.
content_window_->SetFocusTraversableParent(
GetWidget()->GetFocusTraversable());
}
}
////////////////////////////////////////////////////////////////////////////////
// NativeTabbedPaneWin, private:
void NativeTabbedPaneWin::InitializeTabs() {
for (size_t i = 0; i < tab_titles_.size(); ++i)
AddNativeTab(i, tab_titles_[i]);
View* content_root = content_window_->GetRootView();
for (std::vector<View*>::iterator tab(tab_views_.begin());
tab != tab_views_.end(); ++tab)
content_root->AddChildView(*tab);
}
void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) {
selected_index_ = index;
if (content_window_) {
View* content_root = content_window_->GetRootView();
tab_layout_manager_->SwitchToPage(content_root, tab_views_[index]);
}
if (invoke_listener && tabbed_pane_->listener())
tabbed_pane_->listener()->TabSelectedAt(index);
}
void NativeTabbedPaneWin::ResizeContents() {
RECT content_bounds;
if (!GetClientRect(native_view(), &content_bounds))
return;
TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds);
content_window_->SetBounds(gfx::Rect(content_bounds));
}
} // namespace views
|
nacl-webkit/chrome_deps
|
ui/views/controls/tabbed_pane/native_tabbed_pane_win.cc
|
C++
|
bsd-3-clause
| 14,094 | 34.41206 | 80 | 0.644884 | false |
#ifndef BOOST_SIMD_INCLUDE_FUNCTIONS_IS_TRUE_HPP_INCLUDED
#define BOOST_SIMD_INCLUDE_FUNCTIONS_IS_TRUE_HPP_INCLUDED
#include <boost/simd/predicates/include/functions/is_true.hpp>
#endif
|
hainm/pythran
|
third_party/boost/simd/include/functions/is_true.hpp
|
C++
|
bsd-3-clause
| 188 | 30.333333 | 62 | 0.808511 | false |
<?php
function my_udf_md5($foo)
{
return md5($foo);
}
require_once(dirname(__FILE__) . '/new_db.inc');
define('TIMENOW', time());
echo "Creating Table\n";
var_dump($db->exec('CREATE TABLE test (time INTEGER, id STRING)'));
echo "INSERT into table\n";
var_dump($db->exec("INSERT INTO test (time, id) VALUES (" . TIMENOW . ", 'a')"));
var_dump($db->exec("INSERT INTO test (time, id) VALUES (" . TIMENOW . ", 'b')"));
echo "CREATING UDF\n";
var_dump($db->createFunction('my_udf_md5', 'my_udf_md5'));
echo "SELECTING results\n";
$results = $db->query("SELECT my_udf_md5(id) FROM test ORDER BY id ASC");
while ($result = $results->fetchArray(SQLITE3_NUM))
{
var_dump($result);
}
$results->finalize();
echo "Closing database\n";
var_dump($db->close());
echo "Done\n";
?>
|
JSchwehn/php
|
testdata/fuzzdir/corpus/ext_sqlite3_tests_sqlite3_08_udf.php
|
PHP
|
bsd-3-clause
| 774 | 23.1875 | 81 | 0.639535 | false |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/webstore_install_helper.h"
#include <string>
#include "base/bind.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h"
#include "chrome/common/chrome_utility_messages.h"
#include "chrome/common/extensions/chrome_utility_extensions_messages.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/utility_process_host.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
using content::UtilityProcessHost;
namespace {
const char kImageDecodeError[] = "Image decode failed";
} // namespace
namespace extensions {
WebstoreInstallHelper::WebstoreInstallHelper(
Delegate* delegate,
const std::string& id,
const std::string& manifest,
const GURL& icon_url,
net::URLRequestContextGetter* context_getter)
: delegate_(delegate),
id_(id),
manifest_(manifest),
icon_url_(icon_url),
context_getter_(context_getter),
icon_decode_complete_(false),
manifest_parse_complete_(false),
parse_error_(Delegate::UNKNOWN_ERROR) {
}
WebstoreInstallHelper::~WebstoreInstallHelper() {}
void WebstoreInstallHelper::Start() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (icon_url_.is_empty()) {
icon_decode_complete_ = true;
} else {
// No existing |icon_fetcher_| to avoid unbalanced AddRef().
CHECK(!icon_fetcher_.get());
AddRef(); // Balanced in OnFetchComplete().
icon_fetcher_.reset(new chrome::BitmapFetcher(icon_url_, this));
icon_fetcher_->Start(
context_getter_, std::string(),
net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES);
}
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&WebstoreInstallHelper::StartWorkOnIOThread, this));
}
void WebstoreInstallHelper::StartWorkOnIOThread() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
utility_host_ = UtilityProcessHost::Create(
this, base::ThreadTaskRunnerHandle::Get().get())->AsWeakPtr();
utility_host_->SetName(l10n_util::GetStringUTF16(
IDS_UTILITY_PROCESS_JSON_PARSER_NAME));
utility_host_->StartBatchMode();
utility_host_->Send(new ChromeUtilityMsg_ParseJSON(manifest_));
}
bool WebstoreInstallHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(WebstoreInstallHelper, message)
IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Succeeded,
OnJSONParseSucceeded)
IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ParseJSON_Failed,
OnJSONParseFailed)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void WebstoreInstallHelper::OnFetchComplete(const GURL& url,
const SkBitmap* image) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// OnFetchComplete should only be called as icon_fetcher_ delegate to avoid
// unbalanced Release().
CHECK(icon_fetcher_.get());
if (image)
icon_ = *image;
icon_decode_complete_ = true;
if (icon_.empty()) {
error_ = kImageDecodeError;
parse_error_ = Delegate::ICON_ERROR;
}
icon_fetcher_.reset();
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&WebstoreInstallHelper::ReportResultsIfComplete, this));
Release(); // Balanced in Start().
}
void WebstoreInstallHelper::OnJSONParseSucceeded(
const base::ListValue& wrapper) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
manifest_parse_complete_ = true;
const base::Value* value = NULL;
CHECK(wrapper.Get(0, &value));
if (value->IsType(base::Value::TYPE_DICTIONARY)) {
parsed_manifest_.reset(
static_cast<const base::DictionaryValue*>(value)->DeepCopy());
} else {
parse_error_ = Delegate::MANIFEST_ERROR;
}
ReportResultsIfComplete();
}
void WebstoreInstallHelper::OnJSONParseFailed(
const std::string& error_message) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
manifest_parse_complete_ = true;
error_ = error_message;
parse_error_ = Delegate::MANIFEST_ERROR;
ReportResultsIfComplete();
}
void WebstoreInstallHelper::ReportResultsIfComplete() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (!icon_decode_complete_ || !manifest_parse_complete_)
return;
// The utility_host_ will take care of deleting itself after this call.
if (utility_host_.get()) {
utility_host_->EndBatchMode();
utility_host_.reset();
}
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WebstoreInstallHelper::ReportResultFromUIThread, this));
}
void WebstoreInstallHelper::ReportResultFromUIThread() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (error_.empty() && parsed_manifest_)
delegate_->OnWebstoreParseSuccess(id_, icon_, parsed_manifest_.release());
else
delegate_->OnWebstoreParseFailure(id_, parse_error_, error_);
}
} // namespace extensions
|
guorendong/iridium-browser-ubuntu
|
chrome/browser/extensions/webstore_install_helper.cc
|
C++
|
bsd-3-clause
| 5,428 | 31.309524 | 78 | 0.705601 | false |