code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
flock.synth({ synthDef: { ugen: "flock.ugen.sin", freq: { ugen: "flock.ugen.value", rate: "audio", value: 400, add: { ugen: "flock.ugen.sin", freq: { ugen: "flock.ugen.mouse.cursor", mul: 124, add: 62, }, mul: { ugen: "flock.ugen.mouse.cursor", mul: 100, add: 100, options: { axis: "y" } } } }, mul: 0.3 } });
mrtunes/Flocking
demos/playground/demos/fm.js
JavaScript
mit
668
/** * Implementation of built-in Selenide commands. * You can override and add any commands. */ package com.codeborne.selenide.commands;
codeborne/selenide
src/main/java/com/codeborne/selenide/commands/package-info.java
Java
mit
140
## Related projects ### Material-UI Specific Projects - [formsy-material-ui](https://github.com/mbrookes/formsy-material-ui) A Formsy compatibility wrapper for Material-UI form components. - [react-materialui-notifications](https://github.com/puranjayjain/react-materialui-notifications) Spec compliant notifications for react and material ui users. - [material-ui-chip-input](https://github.com/TeamWertarbyte/material-ui-chip-input) An input field for chips as seen in the [Material design guidelines](https://material.google.com/components/chips.html#chips-behavior). - [material-ui-superselectfield](https://github.com/Sharlaan/material-ui-superselectfield) A flexible dropdown component for Material-UI. - [react-payment](https://github.com/lorensr/react-payment) Components for credit card and bank account forms. - [material-auto-rotating-carousel](https://github.com/TeamWertarbyte/material-auto-rotating-carousel) A responsive [auto-rotating carousel](https://material.google.com/growth-communications/onboarding.html#onboarding-top-user-benefits) to display your app's benefits. - [material-ui-rails](https://github.com/towonzhou/material-ui-rails) Material-UI for Rails. - [material-ui-rating](https://github.com/TeamWertarbyte/material-ui-rating) A star rating component. - [storybook-addon-material-ui](https://github.com/sm-react/storybook-addon-material-ui) Addon for storybook. - [crema](https://bitbucket.org/pinturic/crema/) CReMa: Cordova React Material-UI. - [babel-plugin-direct-import](https://github.com/umidbekkarimov/babel-plugin-direct-import) Babel plugin to cherry pick imports of es6 modules. - [material-ui-scrollable-tabs](https://github.com/STORIS/material-ui-scrollable-tabs) Extension of Material-UI `Tabs` component implementing [scrollable](https://material.io/guidelines/components/tabs.html#tabs-types-of-tabs) behavior. - [Electrode](http://www.electrode.io/docs/build_with_material_ui.html) A platform for building universal React/Node.js applications. - [material-ui-slider-label](https://github.com/tariqwest/material-ui-slider-label) This component augments the Material UI Slider component with a value label / info bubble. ### Complementary Projects - [react-swipeable-views](https://github.com/oliviertassinari/react-swipeable-views) A React component for swipeable views. Plays well with the `Tabs` component. - [UniversalRelayBoilerplate](https://github.com/codefoundries/UniversalRelayBoilerplate) Boilerplate + examples for React Native (iOS, Android), React (isomorphic, Material-UI), Relay, GraphQL, JWT, Node.js, Apache Cassandra. - [react-dnd](http://gaearon.github.io/react-dnd/examples-sortable-simple.html) Drag and Drop for React. - [redux-form](http://redux-form.com/6.1.1/examples/material-ui/) Manage your form state in Redux.
igorbt/material-ui
docs/src/app/components/pages/discover-more/related-projects.md
Markdown
mit
2,792
<!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_51) on Wed Apr 09 11:30:51 EDT 2014 --> <title>RotationOrder (Javadocs: peasycam)</title> <meta name="date" content="2014-04-09"> <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="RotationOrder (Javadocs: peasycam)"; } //--> </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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../peasy/org/apache/commons/math/geometry/Rotation.html" title="class in peasy.org.apache.commons.math.geometry"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?peasy/org/apache/commons/math/geometry/RotationOrder.html" target="_top">Frames</a></li> <li><a href="RotationOrder.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">peasy.org.apache.commons.math.geometry</div> <h2 title="Class RotationOrder" class="title">Class RotationOrder</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>peasy.org.apache.commons.math.geometry.RotationOrder</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">RotationOrder</span> extends java.lang.Object</pre> <div class="block">This class is a utility representing a rotation order specification for Cardan or Euler angles specification. This class cannot be instanciated by the user. He can only use one of the twelve predefined supported orders as an argument to either the <a href="../../../../../../peasy/org/apache/commons/math/geometry/Rotation.html#Rotation(peasy.org.apache.commons.math.geometry.RotationOrder, double, double, double)"><code>Rotation.Rotation(RotationOrder,double,double,double)</code></a> constructor or the <a href="../../../../../../peasy/org/apache/commons/math/geometry/Rotation.html#getAngles(peasy.org.apache.commons.math.geometry.RotationOrder)"><code>Rotation.getAngles(peasy.org.apache.commons.math.geometry.RotationOrder)</code></a> method.</div> <dl><dt><span class="strong">Since:</span></dt> <dd>1.2</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#XYX">XYX</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#XYZ">XYZ</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#XZX">XZX</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#XZY">XZY</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#YXY">YXY</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#YXZ">YXZ</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#YZX">YZX</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#YZY">YZY</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#ZXY">ZXY</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#ZXZ">ZXZ</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#ZYX">ZYX</a></strong></code> <div class="block">Set of Cardan angles.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#ZYZ">ZYZ</a></strong></code> <div class="block">Set of Euler angles.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#getA1()">getA1</a></strong>()</code> <div class="block">Get the axis of the first rotation.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#getA2()">getA2</a></strong>()</code> <div class="block">Get the axis of the second rotation.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#getA3()">getA3</a></strong>()</code> <div class="block">Get the axis of the second rotation.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html#toString()">toString</a></strong>()</code> <div class="block">Get a string representation of the instance.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="XYZ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XYZ</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> XYZ</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around X, then around Y, then around Z</div> </li> </ul> <a name="XZY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XZY</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> XZY</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around X, then around Z, then around Y</div> </li> </ul> <a name="YXZ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>YXZ</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> YXZ</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around Y, then around X, then around Z</div> </li> </ul> <a name="YZX"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>YZX</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> YZX</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around Y, then around Z, then around X</div> </li> </ul> <a name="ZXY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ZXY</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> ZXY</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around Z, then around X, then around Y</div> </li> </ul> <a name="ZYX"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ZYX</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> ZYX</pre> <div class="block">Set of Cardan angles. this ordered set of rotations is around Z, then around Y, then around X</div> </li> </ul> <a name="XYX"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XYX</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> XYX</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around X, then around Y, then around X</div> </li> </ul> <a name="XZX"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>XZX</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> XZX</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around X, then around Z, then around X</div> </li> </ul> <a name="YXY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>YXY</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> YXY</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around Y, then around X, then around Y</div> </li> </ul> <a name="YZY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>YZY</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> YZY</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around Y, then around Z, then around Y</div> </li> </ul> <a name="ZXZ"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ZXZ</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> ZXZ</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around Z, then around X, then around Z</div> </li> </ul> <a name="ZYZ"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ZYZ</h4> <pre>public static final&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/RotationOrder.html" title="class in peasy.org.apache.commons.math.geometry">RotationOrder</a> ZYZ</pre> <div class="block">Set of Euler angles. this ordered set of rotations is around Z, then around Y, then around Z</div> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">Get a string representation of the instance.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>a string representation of the instance (in fact, its name)</dd></dl> </li> </ul> <a name="getA1()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getA1</h4> <pre>public&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a>&nbsp;getA1()</pre> <div class="block">Get the axis of the first rotation.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>axis of the first rotation</dd></dl> </li> </ul> <a name="getA2()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getA2</h4> <pre>public&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a>&nbsp;getA2()</pre> <div class="block">Get the axis of the second rotation.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>axis of the second rotation</dd></dl> </li> </ul> <a name="getA3()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getA3</h4> <pre>public&nbsp;<a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry">Vector3D</a>&nbsp;getA3()</pre> <div class="block">Get the axis of the second rotation.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>axis of the second rotation</dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../peasy/org/apache/commons/math/geometry/Rotation.html" title="class in peasy.org.apache.commons.math.geometry"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../peasy/org/apache/commons/math/geometry/Vector3D.html" title="class in peasy.org.apache.commons.math.geometry"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?peasy/org/apache/commons/math/geometry/RotationOrder.html" target="_top">Frames</a></li> <li><a href="RotationOrder.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>processing library peasycam by Jonathan Feinberg. (c) 2013</small></p> </body> </html>
murix/beaglebonequadcopter
quad-processing/libraries/peasycam/reference/peasy/org/apache/commons/math/geometry/RotationOrder.html
HTML
mit
22,315
# simplr-smoothscroll ## [DEMO](http://simov.github.io/simplr-smoothscroll/examples) ## Requirements [jquery-mousewheel](https://github.com/jquery/jquery-mousewheel) ## Usage ```js $(function () { $.srSmoothscroll({ // defaults step: 55, speed: 400, ease: 'swing', target: $('body'), container: $(window) }) }) ``` ## Enable scrolling for specific widgets See this [example](http://simov.github.io/simplr-smoothscroll/examples/example-02.html) ```html <div id="container1"> <div id="widget1"> <p>lorem ipsum</p> </div> </div> <div id="container2"> <div id="widget2"> <p>lorem ipsum</p> </div> </div> ``` ```css #container1 { width: 500px; height: 300px; overflow: auto; } #container2 { width: 500px; height: 300px; overflow: auto; } ``` ```js $(function () { $.srSmoothscroll({ target: $('#widget1'), container: $('#container1') }) $.srSmoothscroll({ target: $('#widget2'), container: $('#container2') }) }) ``` ## Browser and os detection Browsers that support *smooth* scrolling natively may be excluded. ```js $(function () { var platform = navigator.platform.toLowerCase(); if (platform.indexOf('win') == 0 || platform.indexOf('linux') == 0) { if ($.browser.webkit) { $.srSmoothscroll(); } } }); ``` This will enable *simplr-smoothscroll* only for webkit browsers on windows and linux.
simov/simplr-smoothscroll
README.md
Markdown
mit
1,398
// THIS FILE IS AUTO-GENERATED package service import ( "github.com/brutella/hc/characteristic" ) const TypeCarbonMonoxideSensor = "7F" type CarbonMonoxideSensor struct { *Service CarbonMonoxideDetected *characteristic.CarbonMonoxideDetected } func NewCarbonMonoxideSensor() *CarbonMonoxideSensor { svc := CarbonMonoxideSensor{} svc.Service = New(TypeCarbonMonoxideSensor) svc.CarbonMonoxideDetected = characteristic.NewCarbonMonoxideDetected() svc.AddCharacteristic(svc.CarbonMonoxideDetected.Characteristic) return &svc }
edc1591/gohome
vendor/github.com/brutella/hc/service/carbon_monoxide_sensor.go
GO
mit
539
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 23 13:23:20 2018 @author: BallBlueMeercat """ from distutils.core import setup from Cython.Build import cythonize setup(ext_modules = cythonize('firstderivs_cython.pyx'))
lefthandedroo/Cosmo-models
zprev versions/Models_py_backup/setup.py
Python
mit
243
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Dfm { using System.Collections.Generic; public abstract class DfmFencesBlockPathQueryOption : IDfmFencesBlockPathQueryOption { public string HighlightLines { get; set; } public int? DedentLength { get; set; } public string ErrorMessage { get; protected set; } public abstract bool ValidateAndPrepare(string[] lines, DfmFencesToken token); public abstract IEnumerable<string> GetQueryLines(string[] lines); public bool ValidateHighlightLinesAndDedentLength(int totalLines) { var warningMessages = new List<string>(); bool result = true; if (!string.IsNullOrEmpty(HighlightLines)) { var ranges = HighlightLines.Split(','); int? startLine, endLine; int tempStartLine, tempEndLine; foreach (var range in ranges) { var match = DfmFencesRule._dfmFencesRangeQueryStringRegex.Match(range); if (match.Success) { // consider region as `{startlinenumber}-{endlinenumber}`, in which {endlinenumber} is optional startLine = int.TryParse(match.Groups["start"].Value, out tempStartLine) ? tempStartLine : (int?)null; endLine = int.TryParse(match.Groups["start"].Value, out tempEndLine) ? tempEndLine : (int?)null; } else { // consider region as a sigine line number if (int.TryParse(range, out tempStartLine)) { startLine = tempStartLine; endLine = startLine; } else { warningMessages.Add($"Illegal range `{range}` in query parameter `highlight`."); result = false; continue; } } if (!CheckLineRange(totalLines, startLine, endLine)) { warningMessages.Add(ErrorMessage + " in query parameter `highlight`."); result = false; } } } if (DedentLength != null && DedentLength < 0) { warningMessages.Add($"Dedent length {DedentLength} should be positive. Auto-dedent will be applied."); DedentLength = null; result = false; } ErrorMessage = string.Join(" ", warningMessages); return result; } protected bool CheckLineRange(int totalLines, int? startLine, int? endLine) { if (startLine == null && endLine == null) { ErrorMessage = "Neither start line nor end line is specified correctly"; return false; } if (startLine <= 0 || endLine <= 0) { ErrorMessage = "Start/End line should be larger than zero"; return false; } if (startLine > endLine) { ErrorMessage = $"Start line {startLine} shouldn't be larger than end line {endLine}"; return false; } if (startLine > totalLines) { ErrorMessage = $"Start line {startLine} execeeds total lines {totalLines}"; return false; } return true; } } }
LordZoltan/docfx
src/Microsoft.DocAsCode.Dfm/DfmFencesBlockPathQueryOptions/DfmFencesBlockPathQueryOption.cs
C#
mit
3,847
--- title: Молитвы святых date: 11/02/2019 --- **Свидетельство**: Откр. 8:1–4 «Помните — ни одна смиренная, искренняя молитва веры не остается без внимания; каждую молитву слышат. Псалмопевец молил: „Господи! к Тебе взываю: поспеши ко мне, внемли голосу моления моего, когда взываю к Тебе. Да направится молитва моя, как фимиам, пред лицо Твое, воздеяние рук моих как жертва вечерняя. Положи, Господи, охрану устам моим, и огради двери уст моих“ (Пс. 140:1–3). Мы можем быть уверены в том, что обращенная к Богу смиренная молитва покаяния драгоценна в Его очах. Ни одна из них не забыта. Нам обещано: „Просите, и дано будет вам; ищите, и найдете; стучите, и отворят вам, ибо всякий просящий получает, и ищущий находит, и стучащему отворят. Какой из вас отец, _когда_ сын попросит у него хлеба, подаст ему камень? или, _когда попросит_ рыбы, подаст ему змею вместо рыбы? Или, если попросит яйца, подаст ему скорпиона? Итак, если вы, будучи злы, умеете даяния благие давать детям вашим, тем более Отец Небесный даст Духа Святого просящим у Него“ (Лк. 11:9–13). Это приглашение звучит для всех. Спаситель пытается объяснить нам эту истину с помощью простой притчи. Разве отец даст камень своему сыну, если тот просит у него хлеба? Если он просит рыбу, разве ему дадут змею? Если сын попросит яйца, кто даст ему скорпиона? Это просто невозможно. Показывая, насколько отличаются друг от друга земное и небесное, Христос добавляет: „Итак, если вы, будучи злы, умеете даяния благие давать детям вашим, тем более Отец Небесный даст Духа Святого просящим у Него“»29. «Простые молитвы, вдохновленные Святым Духом, восходят через приоткрытые врата и открывают дверь, о которой Христос сказал: „Я отворил… и никто не может затворить“. Эти молитвы, соединенные с фимиамом совершенства Христа, как приятное благоухание восходят к Отцу, и ответ непременно придет»30. «Если вы найдете слова и время для молитвы, то будьте уверены, что Бог найдет время и слова, чтобы ответить вам»31. **Дискуссия** `1. Что, согласно этим отрывкам, символизирует собой в Библии фимиам?` `2. Какие обетования Божьи о молитве вы помните?` `3. Что мы должны делать, для того чтобы получить ответ на свои молитвы? (Подсказка: это очень просто!)` _Майкл Ли, Остин, Техас, США_
PrJared/sabbath-school-lessons
src/ru/2019-01-ay/07/03.md
Markdown
mit
4,035
<!DOCTYPE html> <html> <head> <title>FormBuilder Demo</title> <meta charset="utf-8" /> <!-- REQUIRED: jquery, dust-linkedin --> <script src="js/libs.min.js"></script> <script src="js/formbuilder.min.js"></script> <link href="css/formbuilder.css" media="screen" rel="stylesheet" /> <!-- Demo-only styles --> <style type="text/css"> a, body { font-family: "Tahoma", "Verdana", sans-serif; font-size: 12px; } </style> <script> // On document ready $(function(){ // IF you're loaded existing form data, it's up to you // how you want to load the JSON. In this example, // we pull it using ajax - all that form builder requires // is that you inject the JSON when calling `formbuilder` $.getJSON( 'fake-form-db-vals.json', function(resp){ // Create an instance of form builder var myForm = new Formbuilder({ // Provide a dom element the form will be built to // jQuery or simpleDOM elements required targets: $('.formbuilder'), // A callback allowing you to handle saving the form save: function(formData){ console.log(formData); }, // we loaded existing JSON, so we have a form_id. If you're // creating a new form, this may be left out form_id: resp.form_id, // we loaded existing JSON, so we pass it in here. If you're // creating a new form, this may be left out startingModel: resp.model }); }); }); </script> </head> <body> <h1>Form Builder Demo</h1> <p><a href="form.html">View sample rendered html</a>.</p> <div class="formbuilder"></div> </body> </html>
abhikalotra/Symfony-Move-Plus
testmove/test2/dist/index.html
HTML
mit
1,640
// // NUIViewRenderer.h // NUIDemo // // Created by Tom Benner on 11/24/12. // Copyright (c) 2012 Tom Benner. All rights reserved. // #import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> #import "NUISettings.h" @interface NUIViewRenderer : NSObject + (void)render:(UIView*)view withClass:(NSString*)className; + (void)renderBorderAndCorner:(UIView*)view withClass:(NSString*)className; + (void)renderShadow:(UIView*)view withClass:(NSString*)className; + (void)renderSize:(UIView*)view withClass:(NSString*)className; + (BOOL)hasShadowProperties:(UIView*)view withClass:(NSString*)className; @end
tutoru/nui
NUI/Core/Renderers/NUIViewRenderer.h
C
mit
621
import cn from 'classnames' import Image from 'next/image' import Link from 'next/link' export default function CoverImage({ title, url, slug }) { const image = ( <Image width={2000} height={1000} alt={`Cover Image for ${title}`} src={url} className={cn('shadow-small', { 'hover:shadow-medium transition-shadow duration-200': slug, })} /> ) return ( <div className="sm:mx-0"> {slug ? ( <Link href={slug}> <a aria-label={title}>{image}</a> </Link> ) : ( image )} </div> ) }
azukaru/next.js
examples/cms-storyblok/components/cover-image.js
JavaScript
mit
594
{ "ALLOWED_FILE_TYPE": "Only following files are allowed : ", "AUTHORIZATION_REQUIRED": "No estás autorizado para usar el administrador de archivos.", "DIRECTORY_ALREADY_EXISTS": "La carpeta '%s' ya existe.", "DIRECTORY_NOT_EXIST": "La carpeta %s no existe.", "DISALLOWED_FILE_TYPE": "Following files are not allowed : ", "ERROR_RENAMING_DIRECTORY": "Error al intentar renombrar la carpeta %s a %s.", "ERROR_RENAMING_FILE": "Error al intentar renombrar el archivo %s a %s.", "FILE_ALREADY_EXISTS": "El archivo '%s' ya existe.", "FILE_DOES_NOT_EXIST": "El archivo %s no existe.", "INVALID_ACTION": "Acción inválida.", "INVALID_DIRECTORY_OR_FILE": "Carpeta o archivo invalido.", "INVALID_FILE_TYPE": "File upload is not allowed.", "INVALID_FILE_UPLOAD": "Transferencia de archivo inválida.", "INVALID_VAR": "Variable %s inválida.", "LANGUAGE_FILE_NOT_FOUND": "Archivo de idioma no encontrado.", "MODE_ERROR": "Error de modo.", "UNABLE_TO_CREATE_DIRECTORY": "No se ha podido crear la carpeta %s.", "UNABLE_TO_OPEN_DIRECTORY": "No se ha podido abrir la carpeta %s.", "UPLOAD_FILES_SMALLER_THAN": "Por favor, sube solo imágenes con tamaño inferior a %s.", "UPLOAD_IMAGES_ONLY": "Por favor, sube solo imágenes, no se admiten otro tipo de archivos.", "UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG": "Por favor, sube solo imágenes de tipo JPEG, GIF o PNG.", "browse": "Browse...", "bytes": " bytes", "cancel": "Cancelar", "confirmation_delete": "¿Estás seguro de eliminar este archivo?", "could_not_retrieve_folder": "No se ha podido recuperar el contenido de la carpeta.", "create_folder": "Crear carpeta", "created": "Creado", "current_folder": "Carpeta actual: ", "default_foldername": "Mi carpeta", "del": "Eliminar", "dimensions": "Dimensiones", "download": "Descargar", "fck_select_integration": "La función 'Seleccionar' solo se puede utilizar desde FCKEditor.", "file_size_limit": "The file size limit is : ", "file_too_big": "The file is too big.", "gb": "gb", "grid_view": "Cambiar a vista de cuadrícula.", "kb": "kb", "list_view": "Cambiar a vista de lista.", "loading_data": "Transferring data ...", "mb": "mb", "modified": "Modificado", "move": "Move to ...", "name": "Nombre", "new_filename": "Introduce un nuevo nombre para el archivo", "new_folder": "Nueva carpeta", "no": "No", "no_foldername": "No se ha indicado un nombre para la carpeta.", "parentfolder": "Directorio padre", "prompt_foldername": "Introduce el nombre de la nueva carpeta", "rename": "Renombrar", "search": "Search", "search_reset": "Reset", "select": "Seleccionar", "select_from_left": "Selecciona un elemento de la izquierda.", "size": "tamaño", "successful_added_file": "Nuevo archivo añadido.", "successful_added_folder": "Nueva carpeta creada.", "successful_delete": "Eliminación completada.", "successful_moved": "Move successful.", "successful_rename": "Renombrado con éxito.", "upload": "Subir", "yes": "Sí" }
zogs/reservem
src/Zogs/UtilsBundle/Resources/public/ckeditor_filemanager/scripts/languages/es.js
JavaScript
mit
3,219
--- title: Tesalónica Y Berea date: 28/08/2018 --- Cuando Pablo y Silas fueron liberados de la cárcel, los misioneros partieron de Filipos (Hech. 16:35-40). De Filipos, Pablo y sus compañeros fueron directamente a Tesalónica, la capital de Macedonia. `Lee Hechos 17:1 al 9. ¿Cómo reaccionaron los judíos de Tesalónica ante la exitosa predicación de Pablo entre los gentiles?` Una vez más vemos que Pablo buscó la sinagoga para compartir el evangelio. Muchos griegos devotos y no pocas mujeres prominentes fueron persuadidos por el mensaje de Pablo. El hecho de que estos conversos “se juntar[a]n con Pablo y con Silas” (Hech. 17:4) parece indicar que formaron un grupo aparte y que no se reunían en la sinagoga, sino probablemente en la casa de Jasón. Motivados por los celos, sus oponentes iniciaron una revuelta. Su intención era llevar a Pablo y a Silas (no se menciona a Timoteo) ante la asamblea de la ciudad y acusarlos. Como no pudieron encontrar a los misioneros, el propio Jasón y otros nuevos creyentes fueron arrastrados hasta las autoridades locales bajo la acusación de albergar a agitadores políticos. `Lee Hechos 17:10 al 15. ¿Cuál fue la respuesta de los judíos bereanos en comparación con los de Tesalónica?` El término eugenēs (Hech. 17:11) originalmente significaba “bien nacido” o “de noble nacimiento”, pero llegó a denotar, en términos más generales, una actitud “imparcial”, que probablemente sea el caso aquí. Los judíos de Berea son elogiados no solo porque estuvieron de acuerdo con Pablo y Silas sino también por su disposición a examinar las Escrituras por sí mismos y a diario para ver si lo que los misioneros estaban diciendo era correcto. Una respuesta meramente emocional al evangelio, sin la necesaria convicción intelectual, tiende a ser superficial y de corta duración. No obstante, al poco tiempo la persecución interrumpió el ministerio productivo de Pablo en Berea, obligándolo a avanzar más al sur, hacia Atenas. `¿Cuándo fue la última vez que examinaste diligentemente las Escrituras para averiguar “si estas cosas [cualesquiera que sean] eran así”?` --- #### Comentarios Elena G.W Pablo y Silas trabajaron en la sinagoga de los judíos en Tesalónica con algún éxito; pero los judíos incrédulos estaban muy desconectados, y causaron disturbios, y provocaron un gran tumulto en contra de ellos. Estos devotos apóstoles se vieron obligados a dejar Tesalónica, bajo la protección de la noche e irse a Berea, donde se los recibió con alegría. Elogiaron a los Bereanos de este modo: “Estos eran más nobles que los que estaban en Tesalónica, pues recibieron la palabra con toda solicitud, escudriñando cada día las Escrituras para ver si estas cosas eran así. Así que creyeron muchos de ellos” [Hechos 17:11-12] (_Testimonios para la iglesia_, t. 2, p. 613). La mente de los bereanos no estaba estrechada por el prejuicio. Estaban dispuestos a investigar la verdad de la doctrina presentada por los apóstoles. Estudiaban la Biblia, no por curiosidad, sino para aprender lo que se había escrito concerniente al Mesías prometido. Investigaban diariamente los relatos inspirados; y al comparar escritura con escritura, los ángeles celestiales estaban junto a ellos, iluminando sus mentes e impresionando sus corazones (_Los hechos de los apóstoles_, p. 188). Los ángeles del cielo no descendieron a la escuela de los profetas ni cantaron sus himnos en el templo o las sinagogas, sino que salieron al encuentro de seres humanos que eran lo suficientemente humildes como para recibir el mensaje. Cantaron las alegres nuevas del Salvador en las llanuras de Belén, mientras los grandes hombres, los dirigentes y los honorables quedaban en tinieblas, porque estaban perfectamente satisfechos con su situación y no sentían necesidad de una piedad mayor a la que tenían…  Los grandes hombres, y los que profesan ser sumamente buenos, pueden llevar a cabo obras terribles impulsados por su fanatismo y por lo exaltado del cargo que ocupan, y vanagloriarse al mismo tiempo de que están sirviendo a Dios. No conviene confiar en ellos. Usted y yo necesitamos a toda costa la verdad bíblica. Como los nobles bereanos, tenemos que escudriñar cada día las Escrituras con ferviente oración, para conocer la verdad, y entonces obedecerla a toda costa sin hacer caso de la opinión de los hombres grandes o buenos (_Cada día con Dios_, p. 317). Han ocurrido apostasías y el Señor ha permitido que asuntos de esa naturaleza se desarrollasen en el pasado a fin de mostrar con cuánta facilidad sus hijos serán descarriados cuando dependan de las palabras de los hombres en vez de investigar por sí mismos las Escrituras, como hicieron los nobles bereanos… La rebelión y la apostasía están en el aire mismo que respiramos. Seremos afectados por ellas a menos que vinculemos mediante la fe nuestras almas desvalidas con Cristo. Si los hombres son descarriados ahora con tanta facilidad, ¿cómo resistirán cuando Satanás personifique a Cristo y realice milagros?… ¿Qué impedirá que el pueblo de Dios preste obediencia a los falsos cristos? “No vayáis” [Lucas ١٧:٢٣]… Todos nuestros ministros deben dar un testimonio decidido en todas nuestras iglesias. Dios ha permitido que ocurran apostasías a fin de mostrar cuán poco se puede confiar en el hombre. Siempre debemos acudir a Dios, porque su palabra no es sí y no, sino sí y amen (_Mensajes selectos_, t. 2, pp. 454-456).
PrJared/sabbath-school-lessons
src/es/2018-03/09/04.md
Markdown
mit
5,538
using Microsoft.Extensions.Logging; using Moq; using NBitcoin; using Stratis.Bitcoin.AsyncWork; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Features.BlockStore; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Signals; using Stratis.Bitcoin.Tests.Common; using Stratis.Bitcoin.Utilities; using Stratis.Features.FederatedPeg.Interfaces; using Stratis.Features.FederatedPeg.TargetChain; using Stratis.Features.FederatedPeg.Wallet; using Xunit; namespace Stratis.Features.FederatedPeg.Tests.Wallet { public sealed class FederationWalletManagerTests { private readonly Network network; private readonly BitcoinAddress federationMultiSigAddress; public FederationWalletManagerTests() { this.network = new StratisMain(); var base58 = new Key().PubKey.GetAddress(this.network).ToString(); this.federationMultiSigAddress = BitcoinAddress.Create(base58, this.network); } /// <summary> /// In a federation wallet multisig scenario, transactions will be constantly added to /// the wallet until all the federation members has signed the transaction. In this case, /// transactions and their spending details are constantly updated until the fully signed transaction /// is confirmed in a block. /// /// It is entirely possible that during this process a partially signed transaction added to the wallet /// that spends another transaction is quickly superceded by a more signed partial transaction, also spending said transaction. /// In this case, the previously, less signed transaction should be removed from the wallet as it is no longer applicable. /// </summary> [Fact] public void RemoveTransactions_When_OverwritingSpendDetails() { FederationWalletManager federationWalletManager = CreateFederationWalletManager(); // Create the initial transaction and add it to the wallet. Transaction transactionA = this.network.CreateTransaction(); transactionA.AddOutput(new TxOut(Money.Coins(10), this.federationMultiSigAddress)); federationWalletManager.ProcessTransaction(transactionA); // Verify that transaction A is present and unspent. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionA.GetHash(), 0, out TransactionData addedTx_A); Assert.NotNull(addedTx_A); Assert.Null(addedTx_A.SpendingDetails); // Create a spending transaction that spends transaction A Transaction transactionB = this.network.CreateTransaction(); transactionB.Time = transactionA.Time + 1; transactionB.AddInput(transactionA, 0); transactionB.AddOutput(new TxOut(Money.Coins(5), this.federationMultiSigAddress)); federationWalletManager.ProcessTransaction(transactionB); // Verify that transaction B is present and unspent. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionB.GetHash(), 0, out TransactionData addedTx_B); Assert.NotNull(addedTx_B); Assert.Null(addedTx_B.SpendingDetails); // Verify that transaction B now spends transaction A. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionA.GetHash(), 0, out addedTx_A); Assert.NotNull(addedTx_A); Assert.NotNull(addedTx_A.SpendingDetails); Assert.Equal(addedTx_A.SpendingDetails.TransactionId, transactionB.GetHash()); // Create another spending transaction that also spends transaction A Transaction transactionC = this.network.CreateTransaction(); transactionC.Time = transactionB.Time + 1; transactionC.AddInput(transactionA, 0); transactionC.AddOutput(new TxOut(Money.Coins(5), this.federationMultiSigAddress)); federationWalletManager.ProcessTransaction(transactionC); // Verify that transaction C is present and unspent. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionC.GetHash(), 0, out TransactionData addedTx_C); Assert.NotNull(addedTx_C); Assert.Null(addedTx_C.SpendingDetails); // Verify that transaction C now spends transaction A. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionA.GetHash(), 0, out addedTx_A); Assert.NotNull(addedTx_A); Assert.NotNull(addedTx_A.SpendingDetails); Assert.Equal(addedTx_A.SpendingDetails.TransactionId, transactionC.GetHash()); // Verify that transaction B was now removed. federationWalletManager.Wallet.MultiSigAddress.Transactions.TryGetTransaction(transactionB.GetHash(), 0, out addedTx_B); Assert.Null(addedTx_B); } private FederationWalletManager CreateFederationWalletManager() { var logger = new Mock<ILogger>(); var loggerFactory = new Mock<ILoggerFactory>(); loggerFactory.Setup(lf => lf.CreateLogger(It.IsAny<string>())).Returns(logger.Object); var nodeLifetime = new NodeLifetime(); var signals = new Mock<ISignals>(); var asyncProvider = new AsyncProvider(loggerFactory.Object, signals.Object, nodeLifetime); var dataFolder = new DataFolder(TestBase.CreateTestDir(this)); var chainIndexer = new ChainIndexer(this.network); var federatedPegSettings = new Mock<IFederatedPegSettings>(); federatedPegSettings.Setup(f => f.MultiSigAddress).Returns(this.federationMultiSigAddress); // Create the wallet manager. var federationWalletManager = new FederationWalletManager( loggerFactory.Object, this.network, chainIndexer, dataFolder, new Mock<IWalletFeePolicy>().Object, asyncProvider, nodeLifetime, new Mock<IDateTimeProvider>().Object, federatedPegSettings.Object, new Mock<IWithdrawalExtractor>().Object, new Mock<IBlockRepository>().Object); federationWalletManager.Start(); return federationWalletManager; } } }
fassadlr/StratisBitcoinFullNode
src/Stratis.Features.FederatedPeg.Tests/Wallet/FederationWalletManagerTests.cs
C#
mit
6,558
#include <lib.h> #define stat _stat #include <sys/stat.h> #include <string.h> PUBLIC int stat(name, buffer) _CONST char *name; struct stat *buffer; { message m; m.m1_i1 = strlen(name) + 1; m.m1_p1 = (char *) name; m.m1_p2 = (char *) buffer; return(_syscall(FS, STAT, &m)); }
ducis/operating-system-labs
src.clean/lib/libc/posix/_stat.c
C
mit
303
export default function promiseMiddleware() { return next => action => { const { promise, type, ...rest } = action; if (!promise) return next(action); const SUCCESS = type + '_SUCCESS'; const REQUEST = type + '_REQUEST'; const FAILURE = type + '_FAILURE'; next({ ...rest, type: REQUEST }); return promise .then(req => { next({ ...rest, req, type: SUCCESS }); return true; }) .catch(error => { next({ ...rest, error, type: FAILURE }); console.log(error); return false; }); }; }
caljrimmer/financial-redux-app
src/common/api/promiseMiddleware.js
JavaScript
mit
581
--- title: Pulp 2.10.0 Generally Available author: Sean Myers tags: - release - rpm - docker categories: - Releases --- Pulp 2.10.0 is now generally available, and can be downloaded from the Pulp 2.10 stable repositories: <https://repos.fedorapeople.org/repos/pulp/pulp/stable/2.10/> New features for Pulp 2.10 include the new rsync distributor, new high-availability features for resource managers, as well as some improvements to RPM publishing and package validation. Several bugs were also fixed; all the details can be found later in this announcement. More information about these new features can be found in the release notes: - <http://docs.pulpproject.org/en/2.10/testing/user-guide/release-notes/2.10.x.html> - <http://docs.pulpproject.org/en/2.10/testing/plugins/pulp_rpm/user-guide/release-notes/2.10.x.html> - <http://docs.pulpproject.org/en/2.10/testing/plugins/pulp_docker/user-guide/release-notes/2.1.x.html> Try out the new features, and let us know how they work for you! These two issues were listed as blockers for release candidate 1, and fixed in release candidate 2. Upgrade testing to 2.10.0 from earlier versions of pulp is complete and has verified that these issues do not affect 2.10.0: - [2234](https://pulp.plan.io/issues/2234) Upgrading to pulp 2.9 causes sync of repos with SRPM's with a filelist field to fail. - [2236](https://pulp.plan.io/issues/2236) Upgrading hto pulp 2.9 causes sync of repos with DRPM' with a "relativepath" field to fail. No other blocking issues have been identified, which clears 2.10.0 to become generally available a little earlier than I indicated in my previous announcement for this release. ## Upgrading The 2.10 stable repositories are included in the pulp repo files: https://repos.fedorapeople.org/repos/pulp/pulp/fedora-pulp.repo for fedora 23 & 24 https://repos.fedorapeople.org/repos/pulp/pulp/rhel-pulp.repo for RHEL 6 & 7 After enabling the pulp-stable or pulp-2-stable repository, you'll want to follow the standard upgrade path, with migrations, to get to 2.10.0: ```sh $ sudo systemctl stop httpd pulp_workers pulp_resource_manager pulp_celerybeat $ sudo yum upgrade $ sudo -u apache pulp-manage-db $ sudo systemctl start httpd pulp_workers pulp_resource_manager pulp_celerybeat ``` ## New Features Here are the specific stories done for 2.10.0: ### Docker Support - 1887 As a user, I can use the rsync predistributor with docker web distributor - 1291 As a user, I can sync feeds that require username/password authentication ### Pulp - 1990 Rsync distributor - 1963 As a user, I can use rsync distributor to publish iso repositories - 1759 As a user, I can use rsync distributor to publish RPM repositores - 898 As a user I can run multiple pulp_resource_managers concurrently with all of them actively participating ### RPM Support - 1991 As a user, uploaded units which don't pass the signature check are not imported - 1982 As a user, I can force a full sync - 1878 Support for choosing the checksum type in updateinfo - 1156 As a user, I can have an "signature" attribute stored for RPMs, SRPMs, and DRPMs View this list in [redmine](http://bit.ly/2axDGKA). ## Issues Addressed Here are the bug fixes specific to 2.10.0: ### Pulp - 2082 Cannot add importer to the repository - 1948 Upgrading RPMs on EL6 sometimes fails during pre script - 2187 rsync as predistributor logic is wrong - 2202 predistributor logic in platform does not account for force_full and updated distributor configs - 2030 importer config is not validated during the update - 2039 Not full importer config is validated in the update call - 2118 Reduce runtime of file path migration - 1606 API call to install consumers raises 500 if body contains wrong data type - 2106 Pin to flake8 2.6.2 ### RPM Support - 2188 Make GPG signature checking is called "filtering" - 2042 updateinfo.xml is missing checksums - 2199 The RPM rsync distributor breaks when SELinux is enabled - 2115 The 'skip_fast_forward' in RPM rsync config should be renamed to 'force_full' All bug fixes from Pulp 2.9.2 and earlier are included in Pulp 2.10, as well as the fixes for the two blockers mentioned above. View this list in [redmine](http://bit.ly/2awB1h4). ## Fedora Support Fedora 22 has reached its end-of-life. As a result Pulp 2.10 is being built for (and tested on) Fedoras 23 and 24.
dkliban/pulpproject.org
_posts/2016-09-15-pulp-2-10-0-generally-available.md
Markdown
mit
4,367
<?php namespace Algolia\Core; class TemplateHelper { private $templates_dir; private $algolia_registry; public function __construct() { $this->templates_dir = plugin_dir_path(__DIR__).'templates/'; $this->algolia_registry = Registry::getInstance(); } public function available_templates() { $templates = array(); foreach (scandir($this->templates_dir) as $dir) { if ($dir[0] != '.') { $template = new \stdClass(); $configs = array(); if (file_exists($this->templates_dir.$dir.'/config.php')) $configs = include $this->templates_dir.$dir.'/config.php'; $template->dir = $dir; $template->name = isset($configs['name']) ? $configs['name'] : $dir; $template->screenshot = isset($configs['screenshot']) ? $configs['screenshot'] : 'screenshot.png'; if (file_exists($this->templates_dir.$dir.'/'.$template->screenshot)) $template->screenshot = plugin_dir_url(__FILE__).'../templates/'.$dir.'/'.$template->screenshot; else $template->screenshot = null; $template->screenshot_autocomplete = isset($configs['screenshot-autocomplete']) ? $configs['screenshot-autocomplete'] : 'screenshot-autocomplete.png'; if (file_exists($this->templates_dir.$dir.'/'.$template->screenshot_autocomplete)) $template->screenshot_autocomplete = plugin_dir_url(__FILE__).'../templates/'.$dir.'/'.$template->screenshot_autocomplete; else $template->screenshot_autocomplete = null; $template->description = isset($configs['description']) ? $configs['description'] : ''; $template->facet_types = isset($configs['facet_types']) ? $configs['facet_types'] : array(); $templates[] = $template; } } return $templates; } public function get_current_template() { foreach ($this->available_templates() as $template) if ($template->dir == $this->algolia_registry->template) return $template; } }
2947721120/algoliasearch-wordpress
core/TemplateHelper.php
PHP
mit
2,282
using System; using Tasker.Models.Contracts; namespace Tasker.Models { public class Task : ITask { private int id; private string description; public Task(string description) { this.Description = description; } public int Id { get { return this.id; } set { if (value < 0) { throw new ArgumentException(); } this.id = value; } } public string Description { get { return this.description; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentNullException(); } this.description = value; } } } }
shopOFF/TelerikAcademyCourses
Unit-Testing/Unit-Testing/Topics/02. Test-Driven Development/demos/Tasker/Tasker/Models/Task.cs
C#
mit
971
--- layout: post title: "iOS开发|Xcode插件整理" subtitle: "" author: "Jack" date: 2014-04-22 tag: [iOS, Xcode] header-img: "img/post-img/post-bg-ios.jpg" --- ## Package Manager —— `Alcatraz` 1. Install, paste this into your terminal: `curl -fsSL https://raw.githubusercontent.com/supermarin/Alcatraz/deploy/Scripts/install.sh | sh` 2. Uninstall, delete the plugin: `rm -rf ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin` 3. Remove all cached data: `rm -rf ~/Library/Application\ Support/Alcatraz` ## Plugin List - `KSImageNamed` Xcode plug-in that provides autocomplete for imageNamed: calls. > https://github.com/ksuther/KSImageNamed-Xcode - `FuzzyAutocomplete` A Xcode 5+ plugin that adds more flexible autocompletion rather than just prefix-matching. > https://github.com/FuzzyAutocomplete/FuzzyAutocompletePlugin - `VVDocumenter` Xcode plug-in which helps you write documentation comment easier, for both Objective-C and Swift. > https://github.com/onevcat/VVDocumenter-Xcode - `SCXcodeSwitchExpander` Xcode plugin that enables switch cases autocompletion. > https://github.com/stefanceriu/SCXcodeSwitchExpander - `ColorSense` Plugin for Xcode to make working with colors more visual. > https://github.com/omz/ColorSense-for-Xcode - `XToDo` Xcode plugin to collect and list the `TODO`,`FIXME`,`???`,`!!!!` > https://github.com/trawor/XToDo - `deriveddata-exterminator` A magic button in Xcode to exterminate the current project's DerivedData directories. > https://github.com/kattrali/deriveddata-exterminator - `ClangFormat` Xcode plug-in to to use clang-format from in Xcode and consistently format your code with Clang. > https://github.com/travisjeffery/ClangFormat-Xcode
mushank/Notes
_posts/2014-04-22-iOS开发|Xcode插件整理.md
Markdown
mit
1,815
DROP TABLE IF EXISTS Orders; DROP TABLE IF EXISTS Customers; CREATE TABLE Customers ( customerid CHAR(5) NOT NULL PRIMARY KEY, city VARCHAR(10) NOT NULL ); INSERT INTO Customers(customerid, city) VALUES('FISSA', 'Madrid'); INSERT INTO Customers(customerid, city) VALUES('FRNDO', 'Madrid'); INSERT INTO Customers(customerid, city) VALUES('KRLOS', 'Madrid'); INSERT INTO Customers(customerid, city) VALUES('MRPHS', 'Zion'); CREATE TABLE Orders ( orderid INT NOT NULL PRIMARY KEY, customerid CHAR(5) NULL REFERENCES Customers(customerid) ); INSERT INTO Orders(orderid, customerid) VALUES(1, 'FRNDO'); INSERT INTO Orders(orderid, customerid) VALUES(2, 'FRNDO'); INSERT INTO Orders(orderid, customerid) VALUES(3, 'KRLOS'); INSERT INTO Orders(orderid, customerid) VALUES(4, 'KRLOS'); INSERT INTO Orders(orderid, customerid) VALUES(5, 'KRLOS'); INSERT INTO Orders(orderid, customerid) VALUES(6, 'MRPHS'); INSERT INTO Orders(orderid, customerid) VALUES(7, NULL);
kanghj/alasql
test/test198-1.sql
SQL
mit
994
# RecordsManagementExtensions.GetManualRecordDeclarationInAllLocations Method Get the value of the records management is allowed in all places setting **Namespace:** [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md) **Assembly:** OfficeDevPnP.Core.dll ## Syntax ```C# public static bool GetManualRecordDeclarationInAllLocations(this Site site) ``` ### Parameters #### site &emsp;&emsp;Type: Microsoft.SharePoint.Client.Site &emsp;&emsp;Site collection to operate on ### Return Value Type: bool True if records management is allowed in all places, false otherwise ## See also - [RecordsManagementExtensions](Microsoft.SharePoint.Client.RecordsManagementExtensions.md) - [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md)
erwinvanhunen/PnP-Guidance
sitescore/Microsoft.SharePoint.Client.RecordsManagementExtensions.63e928bb.md
Markdown
mit
773
import { Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'sourceFilter' }) export class sourceFilter implements PipeTransform { public regexp: RegExp; public inputsource : string; transform(value: any, args: any[]): any { if(!args[0]){ alert(args[0]); return value; }else{ this.inputsource = args.toString(); this.regexp= new RegExp(this.inputsource); return value.filter(item=>{if(this.regexp.test(item.toLowerCase())){return true;}else{return false;}}); } } }
ksivaganesh99/Busroutes
public/app/shared/sourcefilter.pipe.ts
TypeScript
mit
573
module Saml class Artifact include ::XmlMapper TYPE_CODE = "\000\004" ENDPOINT_INDEX = "\000\000" tag "Artifact" namespace 'samlp' content :artifact, String def initialize(artifact = nil, endpoint_index = ENDPOINT_INDEX) if artifact @artifact = artifact else source_id = ::Digest::SHA1.digest(Saml.current_provider.entity_id.to_s) message_handle = ::SecureRandom.random_bytes(20) @type_code = TYPE_CODE @endpoint_index = endpoint_index.is_a?(Numeric) ? [endpoint_index].pack("n") : endpoint_index @artifact = Saml::Encoding.encode_64 [@type_code, @endpoint_index, source_id, message_handle].join end end def type_code decoded_value[0, 2] end def endpoint_index decoded_value[2, 2] end def source_id decoded_value[4, 20] end def message_handle decoded_value[24, 20] end def to_s artifact end private def decoded_value ::Base64.decode64(artifact) end end end
JanDintel/libsaml
lib/saml/artifact.rb
Ruby
mit
1,081
// These properties are special and can open client libraries to security // issues var ignoreProperties = ['__proto__', 'constructor', 'prototype']; /** * Returns the value of object `o` at the given `path`. * * ####Example: * * var obj = { * comments: [ * { title: 'exciting!', _doc: { title: 'great!' }} * , { title: 'number dos' } * ] * } * * mpath.get('comments.0.title', o) // 'exciting!' * mpath.get('comments.0.title', o, '_doc') // 'great!' * mpath.get('comments.title', o) // ['exciting!', 'number dos'] * * // summary * mpath.get(path, o) * mpath.get(path, o, special) * mpath.get(path, o, map) * mpath.get(path, o, special, map) * * @param {String} path * @param {Object} o * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. */ exports.get = function (path, o, special, map) { var lookup; if ('function' == typeof special) { if (special.length < 2) { map = special; special = undefined; } else { lookup = special; special = undefined; } } map || (map = K); var parts = 'string' == typeof path ? path.split('.') : path if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var obj = o , part; for (var i = 0; i < parts.length; ++i) { part = parts[i]; if (Array.isArray(obj) && !/^\d+$/.test(part)) { // reading a property from the array items var paths = parts.slice(i); // Need to `concat()` to avoid `map()` calling a constructor of an array // subclass return [].concat(obj).map(function (item) { return item ? exports.get(paths, item, special || lookup, map) : map(undefined); }); } if (lookup) { obj = lookup(obj, part); } else { var _from = special && obj[special] ? obj[special] : obj; obj = _from instanceof Map ? _from.get(part) : _from[part]; } if (!obj) return map(obj); } return map(obj); }; /** * Returns true if `in` returns true for every piece of the path * * @param {String} path * @param {Object} o */ exports.has = function (path, o) { var parts = typeof path === 'string' ? path.split('.') : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { return false; } cur = cur[parts[i]]; } return true; }; /** * Deletes the last piece of `path` * * @param {String} path * @param {Object} o */ exports.unset = function (path, o) { var parts = typeof path === 'string' ? path.split('.') : path; if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } var len = parts.length; var cur = o; for (var i = 0; i < len; ++i) { if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { return false; } // Disallow any updates to __proto__ or special properties. if (ignoreProperties.indexOf(parts[i]) !== -1) { return false; } if (i === len - 1) { delete cur[parts[i]]; return true; } cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; } return true; }; /** * Sets the `val` at the given `path` of object `o`. * * @param {String} path * @param {Anything} val * @param {Object} o * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. */ exports.set = function (path, val, o, special, map, _copying) { var lookup; if ('function' == typeof special) { if (special.length < 2) { map = special; special = undefined; } else { lookup = special; special = undefined; } } map || (map = K); var parts = 'string' == typeof path ? path.split('.') : path if (!Array.isArray(parts)) { throw new TypeError('Invalid `path`. Must be either string or array'); } if (null == o) return; for (var i = 0; i < parts.length; ++i) { // Silently ignore any updates to `__proto__`, these are potentially // dangerous if using mpath with unsanitized data. if (ignoreProperties.indexOf(parts[i]) !== -1) { return; } } // the existance of $ in a path tells us if the user desires // the copying of an array instead of setting each value of // the array to the one by one to matching positions of the // current array. Unless the user explicitly opted out by passing // false, see Automattic/mongoose#6273 var copy = _copying || (/\$/.test(path) && _copying !== false) , obj = o , part for (var i = 0, len = parts.length - 1; i < len; ++i) { part = parts[i]; if ('$' == part) { if (i == len - 1) { break; } else { continue; } } if (Array.isArray(obj) && !/^\d+$/.test(part)) { var paths = parts.slice(i); if (!copy && Array.isArray(val)) { for (var j = 0; j < obj.length && j < val.length; ++j) { // assignment of single values of array exports.set(paths, val[j], obj[j], special || lookup, map, copy); } } else { for (var j = 0; j < obj.length; ++j) { // assignment of entire value exports.set(paths, val, obj[j], special || lookup, map, copy); } } return; } if (lookup) { obj = lookup(obj, part); } else { var _to = special && obj[special] ? obj[special] : obj; obj = _to instanceof Map ? _to.get(part) : _to[part]; } if (!obj) return; } // process the last property of the path part = parts[len]; // use the special property if exists if (special && obj[special]) { obj = obj[special]; } // set the value on the last branch if (Array.isArray(obj) && !/^\d+$/.test(part)) { if (!copy && Array.isArray(val)) { _setArray(obj, val, part, lookup, special, map); } else { for (var j = 0; j < obj.length; ++j) { item = obj[j]; if (item) { if (lookup) { lookup(item, part, map(val)); } else { if (item[special]) item = item[special]; item[part] = map(val); } } } } } else { if (lookup) { lookup(obj, part, map(val)); } else if (obj instanceof Map) { obj.set(part, map(val)); } else { obj[part] = map(val); } } } /*! * Recursively set nested arrays */ function _setArray(obj, val, part, lookup, special, map) { for (var item, j = 0; j < obj.length && j < val.length; ++j) { item = obj[j]; if (Array.isArray(item) && Array.isArray(val[j])) { _setArray(item, val[j], part, lookup, special, map); } else if (item) { if (lookup) { lookup(item, part, map(val[j])); } else { if (item[special]) item = item[special]; item[part] = map(val[j]); } } } } /*! * Returns the value passed to it. */ function K (v) { return v; }
RemziDalyan/leonids
node_modules/mpath/lib/index.js
JavaScript
mit
7,689
#include "stdafx.h" #include "CppUnitTest.h" #include "../src/polynomial.hpp" #include <vector> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace test { TEST_CLASS(test_polynomial) { public: TEST_METHOD(naive_evaluate_case1) { auto sample = std::vector < int > { 1 }; //y = 1 auto x = 2; auto expect = 1; auto actual = clrs::ch02::naive_evaluate(sample, x); Assert::AreEqual(actual, expect); } TEST_METHOD(naive_evaluate_case2) { auto sample = std::vector < int > { 1, 2 }; // y = 1 + 2x auto x = 2; auto expect = 5; auto actual = clrs::ch02::naive_evaluate(sample, x); Assert::AreEqual(actual, expect); } TEST_METHOD(naive_evaluate_case3) { auto sample = std::vector < int > { 5, 2, 0, 7}; // y = 5 + 2x + 0x^2 + 7x^3 auto x = 2; // = 5 + 4 + 0 + 56 = 65 auto expect = 65; auto actual = clrs::ch02::naive_evaluate(sample, x); Assert::AreEqual(expect, actual); } TEST_METHOD(horner_evaluate_case1) { auto sample = std::vector < int > { 1 }; //y = 1 auto x = 2; auto expect = 1; auto actual = clrs::ch02::horner_evaluate(sample, x); Assert::AreEqual(actual, expect); } TEST_METHOD(horner_evaluate_case2) { auto sample = std::vector < int > { 1, 2 }; // y = 1 + 2x auto x = 2; auto expect = 5; auto actual = clrs::ch02::horner_evaluate(sample, x); Assert::AreEqual(actual, expect); } TEST_METHOD(horner_evaluate_case3) { auto sample = std::vector < int > { 5, 2, 0, 7}; // y = 5 + 2x + 0x^2 + 7x^3 auto x = 2; // = 5 + 4 + 0 + 56 = 65 auto expect = 65; auto actual = clrs::ch02::horner_evaluate(sample, x); Assert::AreEqual(expect, actual); } }; }
opensourceDA/CLRS
ch02/test/test_polynomial.cpp
C++
mit
1,755
#!/bin/bash set -u -e -o pipefail declare -A payloadLimits payloadLimits["hello_world__closure", "uncompressed", "bundle"]=106000 payloadLimits["hello_world__closure", "gzip7", "bundle"]=35000 payloadLimits["hello_world__closure", "gzip9", "bundle"]=35000 payloadLimits["cli-hello-world", "uncompressed", "inline"]=1500 payloadLimits["cli-hello-world", "uncompressed", "main"]=175000 payloadLimits["cli-hello-world", "uncompressed", "polyfills"]=64000 payloadLimits["cli-hello-world", "gzip7", "inline"]=900 payloadLimits["cli-hello-world", "gzip7", "main"]=48000 payloadLimits["cli-hello-world", "gzip7", "polyfills"]=22000 payloadLimits["cli-hello-world", "gzip9", "inline"]=900 payloadLimits["cli-hello-world", "gzip9", "main"]=48000 payloadLimits["cli-hello-world", "gzip9", "polyfills"]=22000
smartm0use/angular
integration/_payload-limits.sh
Shell
mit
802
using System; using System.Xml.Serialization; namespace SevenDigital.Api.Schema.Packages { public class Streaming { [XmlElement("releaseDate")] public DateTime ReleaseDate { get; set; } } }
gregsochanik/SevenDigital.Api.Schema
src/Schema/Packages/Streaming.cs
C#
mit
197
## Trimethyl test application We use this application to test features and UI behaviours. This is not a demonstration app. ### Usage ``` trimethyl install ti build -p ios --shadow ```
trimethyl/trimethyl
test-application/README.md
Markdown
mit
187
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // 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 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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. // using NUnit.Framework; using System; using System.Data; using GHTUtils; using GHTUtils.Base; namespace tests.system_data_dll.System_Data { [TestFixture] public class InRowChangingEventException_Generate : GHTBase { [Test] public void Main() { InRowChangingEventException_Generate tc = new InRowChangingEventException_Generate(); Exception exp = null; try { tc.BeginTest("InRowChangingEventException"); tc.run(); } catch(Exception ex) { exp = ex; } finally { tc.EndTest(exp); } } //Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { Exception exp = null; DataTable dt = GHTUtils.DataProvider.CreateParentDataTable(); dt.RowChanging += new DataRowChangeEventHandler ( Row_Changing ); dt.Rows[0][1] = "NewValue"; //this event must be raised in order to test the exception try { BeginCase("RowChanging - Event raised"); Compare(_EventTriggered ,true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} } private bool _EventTriggered = false; private void Row_Changing( object sender, DataRowChangeEventArgs e ) { Exception exp = null; Exception tmpEx = null; try { BeginCase("InRowChangingEventException - EndEdit"); try { e.Row.EndEdit(); //can't invoke EndEdit while in ChangingEvent } catch (InRowChangingEventException ex) { tmpEx = ex; } base.Compare(tmpEx.GetType(),typeof(InRowChangingEventException)); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} _EventTriggered = true; } } }
jjenki11/blaze-chem-rendering
qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/System.Data/Test/System.Data.Tests.Mainsoft/System.Data/InRowChangingEventException/InRowChangingEventException_Generate.cs
C#
mit
3,213
require 'spec_helper' describe "posts" do let(:forum) { FactoryGirl.create(:forum) } let(:user) { FactoryGirl.create(:user) } let(:topic) { FactoryGirl.create(:topic, :forum => forum, :user => user) } context "not signed in users" do it "cannot begin to post a reply" do visit new_topic_post_path(topic) flash_alert!("You must sign in first.") end it "cannot delete posts" do first_post = topic.posts[0] delete topic_post_path(topic, first_post), :id => first_post.id.to_s response.should redirect_to(sign_in_path) flash.alert.should == "You must sign in first." end end context "signed in users" do before do sign_in(user) visit forum_topic_path(forum, topic) end context "replying" do before do within(selector_for(:first_post)) do click_link("Reply") end end context "to an unlocked topic" do it "can post a reply" do fill_in "Text", :with => "Witty and insightful commentary." click_button "Post Reply" flash_notice!("Your reply has been posted.") assert_seen("In reply to #{topic.posts.first.user.login}", :within => :second_post) click_link "Welcome to Forem!" end end context "to a locked topic" do it "cannot post a reply" do topic.lock_topic! fill_in "Text", :with => "Witty and insightful commentary." click_button "Post Reply" flash_alert!("You cannot reply to a locked topic.") end end it "cannot post a reply to a topic with blank text" do click_button "Post Reply" flash_alert!("Your reply could not be posted.") end it "does not hold over failed post flash to next request" do click_button "Post Reply" flash_alert!("Your reply could not be posted.") visit root_path page.should_not have_content("Your reply could not be posted.") end end context "deleting posts in topics" do before do sign_in(user) end context "topic contains two posts" do before do topic.posts << FactoryGirl.create(:post, :user => FactoryGirl.create(:user, :login => 'other_forem_user', :email => "maryanne@boblaw.com")) end it "shows correct 'started by' and 'last post' information" do visit forum_path(forum) within(".topic .started-by") do page.should have_content("forem_user") end within(".topic .latest-post") do page.should have_content("other_forem_user") end end it "can delete their own post" do visit forum_topic_path(forum, topic) within(selector_for(:first_post)) do click_link("Delete") end flash_notice!("Your post has been deleted.") end it "cannot delete posts by others" do visit forum_topic_path(forum, topic) other_post = topic.posts[1] #sends delete request with the current rack-test logged-in session & follows the redirect Capybara.current_session.driver.submit :delete, topic_post_path(topic, other_post), {} flash_alert!("You cannot delete a post you do not own.") ::Forem::Post.should exist(other_post.id) end end context "topic contains one post" do before do visit forum_topic_path(forum, topic) end it "topic is deleted if only post" do Forem::Topic.count.should == 1 within(selector_for(:first_post)) do click_link("Delete") end Forem::Topic.count.should == 0 flash_notice!("Only post in topic deleted. Topic also deleted.") end end end end end
dmitry-ilyashevich/forem
spec/requests/posts_spec.rb
Ruby
mit
3,857
(function() { var def, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; def = require('./utils').def; Object["new"] = function(a) { var o; o = {}; a.step(2, function(k, v) { return o[k] = v; }); return o; }; def(Object, { concat: function(m) { var k, o, v; o = {}; for (k in this) { v = this[k]; o[k] = v; } return o.merge(m || {}); } }); def(Object, { destroy: function(key) { var res; if (this.hasKey(key)) { res = this[key]; delete this[key]; return res; } return null; } }); def(Object, { each: function(f) { var k, v; if (f != null) { for (k in this) { v = this[k]; f(k, v); } } return this; } }); def(Object, { empty: function() { return this.keys().empty(); } }); def(Object, { first: function() { if (this.empty()) { return null; } else { return this.flatten().group(2).first(); } } }); def(Object, { flatten: function() { var a, k, v; a = []; for (k in this) { v = this[k]; a = a.concat([k, v]); } return a; } }); def(Object, { has: function(value) { return __indexOf.call(this.values(), value) >= 0; } }); def(Object, { hasKey: function(key) { return this[key] != null; } }); def(Object, { keys: function() { var k, _results; _results = []; for (k in this) { _results.push(k); } return _results; } }); def(Object, { length: function() { return this.keys().length; } }); def(Object, { last: function() { if (this.empty()) { return null; } else { return this.flatten().group(2).last(); } } }); def(Object, { map: function(f) { var k, v; return Object["new"](((function() { var _results; _results = []; for (k in this) { v = this[k]; _results.push(f(k, v)); } return _results; }).call(this)).flatten()); } }); def(Object, { merge: function(o) { var k, v; for (k in o) { v = o[k]; this[k] = v; } return this; } }); def(Object, { reject: function(f) { var k, o, v; o = {}; for (k in this) { v = this[k]; if (!(typeof f === "function" ? f(k, v) : void 0)) { o[k] = v; } } return o; } }); def(Object, { select: function(f) { var k, o, v; o = {}; for (k in this) { v = this[k]; if (typeof f === "function" ? f(k, v) : void 0) { o[k] = v; } } return o; } }); def(Object, { size: function() { return this.length(); } }); def(Object, { sort: function(f) { var k, o, _i, _len, _ref; if ((f == null) || typeof f !== 'function') { f = function(a, b) { if (a > b) { return 1; } else if (b < a) { return -1; } else { return 0; } }; } o = {}; _ref = this.keys().sort(f); for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; o[k] = this[k]; } return o; } }); def(Object, { sortedKeys: function() { return this.keys().sort(); } }); def(Object, { sortedValues: function() { var k, _i, _len, _ref, _results; _ref = this.sortedKeys(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; _results.push(this[k]); } return _results; } }); def(Object, { tap: function(block) { block.call(this, this); return this; } }); def(Object, { type: function() { return Object.prototype.toString.call(this).toLowerCase().replace(/\[object (\w+)\]/, "$1"); } }); def(Object, { update: Object.prototype.merge }); def(Object, { values: function() { var k, _i, _len, _ref, _results; _ref = this.keys(); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; _results.push(this[k]); } return _results; } }); def(Object, { quacksLike: function(type) { var definition, k, v, _ref; if (type.__definition__ != null) { definition = type.__definition__; if (typeof definition === "function") { return definition(this); } for (k in definition) { v = definition[k]; switch (typeof v) { case "function": if (!v(this[k])) { return false; } break; default: if (!(v === "*" || ((_ref = this[k]) != null ? _ref.type() : void 0) === v)) { return false; } } } return true; } else { return false; } } }); }).call(this);
Montana-Studio/StarterDailyMediakit
node_modules/neat/lib/core/types/object.js
JavaScript
mit
5,319
# Cloud Foundry buildpack: Meteorite This buildpack is derived from [heroku-buildpack-meteorite](https://github.com/oortcloud/heroku-buildpack-meteorite) by [sweetleon](https://github.com/sweetleon). This buildpack enables you to easily deploy meteor apps to Cloud Foundry using [meteorite](https://github.com/cloudfoundry-community/cloudfoundry-buildpack-meteorite). It's easy to use different branches of meteor and any smart package you can lay your hands on. ## Usage Create a CF app and bind it to a MongoDB service. Then run the following command in your terminal: ``` cf push [APP_NAME] -b https://github.com/cloudfoundry-community/cloudfoundry-buildpack-meteorite.git ``` ## NOTES You can specify meteor settings by setting the `METEOR_SETTINGS` environment variable: ``` cf set-env [APP_NAME] METEOR_SETTINGS '{"herp":"derp"}' ``` You need to have a service for MongoDB available and bound to the app. Alternatively, you can set `MONGO_URL` to point to your MongoDB outside of Cloud Foundry with the command: ``` cf set-env [APP_NAME] MONGO_URL mongodb://[SERVER]:[PORT]/[DB] # substitute your configuration values ``` ## Websockets To enable websockets on run.pivotal.io, you will need to use SSL over port 4443, e.g., `https://[APP_NAME].cfapps.io:4443/`
cloudfoundry-community/cloudfoundry-buildpack-meteorite
README.md
Markdown
mit
1,278
--- title: Motståndet börjar date: 20/10/2019 --- `Läs Esra 4:1–5. Varför vägrade Israels rest att ta emot andra folks hjälp i tempelbygget?` Till det yttre verkade erbjudandet som en vänlig gest från grannar, så varför avvisa hjälpen? I en bemärkelse finns svaret i själva texten. ”Fiender” kom för att erbjuda dem hjälp. _Fiender?_ Redan det antyder starkt varför israeliterna agerade som de gjorde. Varför kallades dessa människor för ”fiender”? 2 Kung. 17:24–41 förklarar att de var ditförda från andra nationer till Samarien och trakterna runt omkring efter att befolkningen i Nordriket Israel fördes bort. Kungen av Assyrien sände till dem präster som skulle lära dem hur landets, Israels, Gud skulle tillbes. Men religionen som det resulterade i innefattade också kanaaneiska gudar. Därför var den israelitiska resten rädd att denna religion skulle införlivas i deras tempeltjänst. Därför var det bästa och smartaste de kunde göra att tacka nej. Till att börja med måste vi också komma ihåg varför allt detta hände. Det var deras förfäders ständiga kompromisser med de hedniska religionerna runt omkring dem som ledde till templets förstörelse och deras exil. När de på nytt byggde templet var det utan tvekan det sista de ville göra att bli för nära allierade med folken runt omkring dem. `Vad finns det mer i dessa texter som visar varför denna vägran var det rätta att göra? Se Esra 4:4, 5. Tänk hur lätt de kunde ha rationaliserat mottagandet av denna hjälp. Vad säger 2 Kor. 6:14 till oss i detta sammanhang?`
imasaru/sabbath-school-lessons
src/sv/2019-04/04/02.md
Markdown
mit
1,599
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {{#each collections.blog}} <url> <loc>{{../site.url}}/{{{this.path}}}</loc> <lastmod>{{formatDate this.date}}</lastmod> </url> {{/each}} <url> <loc>{{site.url}}/</loc> <lastmod>{{formatDate "now"}}</lastmod> </url> <url> <loc>{{site.url}}/blog/</loc> <lastmod>{{formatDate "now"}}</lastmod> </url> </urlset>
evocode/metalsmith-base
layouts/sitemap.html
HTML
mit
448
// This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Controls\0.18.8\Graphics\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Controls.Circle.h> #include <Fuse.Controls.Graphics.ShapeVisual-1.h> #include <Fuse.Scripting.INameScope.h> namespace g{namespace Fuse{namespace Controls{namespace Graphics{struct CircleVisual;}}}} namespace g{namespace Fuse{namespace Drawing{struct Brush;}}} namespace g{namespace Fuse{namespace Drawing{struct Stroke;}}} namespace g{namespace Fuse{struct DrawContext;}} namespace g{namespace Fuse{struct HitTestContext;}} namespace g{ namespace Fuse{ namespace Controls{ namespace Graphics{ // public sealed class CircleVisual :740 // { ::g::Fuse::Controls::Graphics::ShapeVisual_type* CircleVisual_typeof(); void CircleVisual__ctor_4_fn(CircleVisual* __this); void CircleVisual__get_Circle_fn(CircleVisual* __this, ::g::Fuse::Controls::Circle** __retval); void CircleVisual__DrawFill_fn(CircleVisual* __this, ::g::Fuse::DrawContext* dc, ::g::Fuse::Drawing::Brush* fill); void CircleVisual__DrawStroke_fn(CircleVisual* __this, ::g::Fuse::DrawContext* dc, ::g::Fuse::Drawing::Stroke* stroke); void CircleVisual__New1_fn(CircleVisual** __retval); void CircleVisual__OnHitTest_fn(CircleVisual* __this, ::g::Fuse::HitTestContext* htc); struct CircleVisual : ::g::Fuse::Controls::Graphics::ShapeVisual { void ctor_4(); ::g::Fuse::Controls::Circle* Circle(); static CircleVisual* New1(); }; // } }}}} // ::g::Fuse::Controls::Graphics
blyk/BlackCode-Fuse
TestApp/.build/Simulator/Android/include/Fuse.Controls.Graphics.CircleVisual.h
C
mit
1,544
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import { Directive, ElementRef, Inject, InjectionToken, Input, OnDestroy, Optional, SkipSelf, } from '@angular/core'; import {Subject} from 'rxjs'; import {CDK_DRAG_PARENT} from '../drag-parent'; import {assertElementNode} from './assertions'; /** * Injection token that can be used to reference instances of `CdkDragHandle`. It serves as * alternative token to the actual `CdkDragHandle` class which could cause unnecessary * retention of the class and its directive metadata. */ export const CDK_DRAG_HANDLE = new InjectionToken<CdkDragHandle>('CdkDragHandle'); /** Handle that can be used to drag a CdkDrag instance. */ @Directive({ selector: '[cdkDragHandle]', host: { 'class': 'cdk-drag-handle' }, providers: [{provide: CDK_DRAG_HANDLE, useExisting: CdkDragHandle}], }) export class CdkDragHandle implements OnDestroy { /** Closest parent draggable instance. */ _parentDrag: {} | undefined; /** Emits when the state of the handle has changed. */ readonly _stateChanges = new Subject<CdkDragHandle>(); /** Whether starting to drag through this handle is disabled. */ @Input('cdkDragHandleDisabled') get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); this._stateChanges.next(this); } private _disabled = false; constructor( public element: ElementRef<HTMLElement>, @Inject(CDK_DRAG_PARENT) @Optional() @SkipSelf() parentDrag?: any) { if (typeof ngDevMode === 'undefined' || ngDevMode) { assertElementNode(element.nativeElement, 'cdkDragHandle'); } this._parentDrag = parentDrag; } ngOnDestroy() { this._stateChanges.complete(); } static ngAcceptInputType_disabled: BooleanInput; }
josephperrott/material2
src/cdk/drag-drop/directives/drag-handle.ts
TypeScript
mit
2,049
describe('CreateController', function() { beforeEach(module('mainModule')); var $scope, $controller, $httpBackend, $state; beforeEach(inject(function(_$controller_, _$httpBackend_, _$state_) { $httpBackend = _$httpBackend_; $state = _$state_; $scope = {}; $controller = _$controller_('CreateController', { $scope: $scope }); $httpBackend.whenGET('/header').respond(200); $httpBackend.whenGET('/filters').respond(200); $httpBackend.flush(); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('initial parameter of cleanNewCheck is custom object', function() { expect($scope.cleanNewCheck).toBeDefined(); }); it('function resetNewCheck should copy to object custom template', function() { $scope.cheque = {}; $scope.resetNewCheck(); expect($scope.cheque).toEqual($scope.cleanNewCheck); }); it('function addKit should return object with key "kit"', function() { expect($scope.addKit('example')).toEqual({'kit': 'example'}); }); it('should add note and diagnostic to cheque and send items to server', function() { $scope.cheque = {"id":1, "name":'Bob', "notes":[], diagnostics:[]}; $scope.note = {"text":'text'}; $scope.diagnostic = {"text":'text'}; $httpBackend.expectPOST('/cheques', {"id":1, "name":'Bob', "notes":[{"text":'text'}], diagnostics:[{"text":'text'}]}).respond(200); $scope.sendCheque(); $httpBackend.flush(); }); it('should create mdDialog for datepicker and take response', inject(function($mdDialog, $q, $rootScope) { angular.extend($scope, {$new: function() {} }); var deferred = $q.defer(); spyOn($mdDialog, 'show').and.returnValue(deferred.promise); $scope.introducedPicker(); $scope.guaranteePicker(); deferred.resolve('test'); $rootScope.$apply(); expect($scope.cheque.introducedFrom).toEqual('test'); expect($scope.cheque.guarantee).toEqual('test'); expect($mdDialog.show).toHaveBeenCalled(); })); });
Nandtel/GearService
src/test/client/unit/controllers/createControllerSpec.js
JavaScript
mit
2,215
/** ****************************************************************************** * @file stm32f4xx_hal_i2s_ex.c * @author MCD Application Team * @version V1.3.0 * @date 09-March-2015 * @brief I2S HAL module driver. * This file provides firmware functions to manage the following * functionalities of I2S extension peripheral: * + Extension features Functions * @verbatim ============================================================================== ##### I2S Extension features ##### ============================================================================== [..] (#) In I2S full duplex mode, each SPI peripheral is able to manage sending and receiving data simultaneously using two data lines. Each SPI peripheral has an extended block called I2Sxext (i.e I2S2ext for SPI2 and I2S3ext for SPI3). (#) The extension block is not a full SPI IP, it is used only as I2S slave to implement full duplex mode. The extension block uses the same clock sources as its master. (#) Both I2Sx and I2Sx_ext can be configured as transmitters or receivers. [..] (@) Only I2Sx can deliver SCK and WS to I2Sx_ext in full duplex mode, where I2Sx can be I2S2 or I2S3. ##### How to use this driver ##### =============================================================================== [..] Three operation modes are available within this driver : *** Polling mode IO operation *** ================================= [..] (+) Send and receive in the same time an amount of data in blocking mode using HAL_I2S_TransmitReceive() *** Interrupt mode IO operation *** =================================== [..] (+) Send and receive in the same time an amount of data in non blocking mode using HAL_I2S_TransmitReceive_IT() (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxCpltCallback (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxCpltCallback (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_I2S_ErrorCallback *** DMA mode IO operation *** ============================== [..] (+) Send and receive an amount of data in non blocking mode (DMA) using HAL_I2S_TransmitReceive_DMA() (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_TxCpltCallback (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can add his own code by customization of function pointer HAL_I2S_RxCpltCallback (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_I2S_ErrorCallback (+) Pause the DMA Transfer using HAL_I2S_DMAPause() (+) Resume the DMA Transfer using HAL_I2S_DMAResume() (+) Stop the DMA Transfer using HAL_I2S_DMAStop() @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * 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 STMicroelectronics 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup I2SEx I2SEx * @brief I2S HAL module driver * @{ */ #ifdef HAL_I2S_MODULE_ENABLED #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @addtogroup I2SEx_Private_Functions * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup I2SEx_Exported_Functions I2S Exported Functions * @{ */ /** @defgroup I2SEx_Group1 Extension features functions * @brief Extension features functions * @verbatim =============================================================================== ##### Extension features Functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the I2S data transfers. (#) There are two modes of transfer: (++) Blocking mode : The communication is performed in the polling mode. The status of all data processing is returned by the same function after finishing transfer. (++) No-Blocking mode : The communication is performed using Interrupts or DMA. These functions return the status of the transfer startup. The end of the data processing will be indicated through the dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when using DMA mode. (#) Blocking mode functions are : (++) HAL_I2S_TransmitReceive() (#) No-Blocking mode functions with Interrupt are : (++) HAL_I2S_TransmitReceive_IT() (#) No-Blocking mode functions with DMA are : (++) HAL_I2S_TransmitReceive_DMA() (#) A set of Transfer Complete Callbacks are provided in non Blocking mode: (++) HAL_I2S_TxCpltCallback() (++) HAL_I2S_RxCpltCallback() (++) HAL_I2S_ErrorCallback() @endverbatim * @{ */ /** * @brief Initializes the I2S according to the specified parameters * in the I2S_InitTypeDef and create the associated handle. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) { uint32_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1; uint32_t tmp = 0, i2sclk = 0; /* Check the I2S handle allocation */ if(hi2s == NULL) { return HAL_ERROR; } /* Check the I2S parameters */ assert_param(IS_I2S_MODE(hi2s->Init.Mode)); assert_param(IS_I2S_STANDARD(hi2s->Init.Standard)); assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat)); assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput)); assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq)); assert_param(IS_I2S_CPOL(hi2s->Init.CPOL)); assert_param(IS_I2S_CLOCKSOURCE(hi2s->Init.ClockSource)); if(hi2s->State == HAL_I2S_STATE_RESET) { /* Allocate lock resource and initialize it */ hi2s->Lock = HAL_UNLOCKED; /* Init the low level hardware : GPIO, CLOCK, CORTEX */ HAL_I2S_MspInit(hi2s); } hi2s->State = HAL_I2S_STATE_BUSY; /*----------------------- SPIx I2SCFGR & I2SPR Configuration ---------------*/ /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ hi2s->Instance->I2SCFGR &= ~(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \ SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \ SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD); hi2s->Instance->I2SPR = 0x0002; /* Get the I2SCFGR register value */ tmpreg = hi2s->Instance->I2SCFGR; /* If the default frequency value has to be written, reinitialize i2sdiv and i2sodd */ /* If the requested audio frequency is not the default, compute the prescaler */ if(hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT) { /* Check the frame length (For the Prescaler computing) *******************/ if(hi2s->Init.DataFormat != I2S_DATAFORMAT_16B) { /* Packet length is 32 bits */ packetlength = 2; } /* Get I2S source Clock frequency ****************************************/ i2sclk = I2S_GetInputClock(hi2s); /* Compute the Real divider depending on the MCLK output state, with a floating point */ if(hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE) { /* MCLK output is enabled */ tmp = (uint32_t)(((((i2sclk / 256) * 10) / hi2s->Init.AudioFreq)) + 5); } else { /* MCLK output is disabled */ tmp = (uint32_t)(((((i2sclk / (32 * packetlength)) *10 ) / hi2s->Init.AudioFreq)) + 5); } /* Remove the flatting point */ tmp = tmp / 10; /* Check the parity of the divider */ i2sodd = (uint32_t)(tmp & (uint32_t)1); /* Compute the i2sdiv prescaler */ i2sdiv = (uint32_t)((tmp - i2sodd) / 2); /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ i2sodd = (uint32_t) (i2sodd << 8); } /* Test if the divider is 1 or 0 or greater than 0xFF */ if((i2sdiv < 2) || (i2sdiv > 0xFF)) { /* Set the default values */ i2sdiv = 2; i2sodd = 0; } /* Write to SPIx I2SPR register the computed value */ hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput)); /* Configure the I2S with the I2S_InitStruct values */ tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL); #if defined(SPI_I2SCFGR_ASTRTEN) if (hi2s->Init.Standard == I2S_STANDARD_PCM_SHORT) { /* Write to SPIx I2SCFGR */ hi2s->Instance->I2SCFGR = tmpreg | SPI_I2SCFGR_ASTRTEN; } else { /* Write to SPIx I2SCFGR */ hi2s->Instance->I2SCFGR = tmpreg; } #else /* Write to SPIx I2SCFGR */ hi2s->Instance->I2SCFGR = tmpreg; #endif /* Configure the I2S extended if the full duplex mode is enabled */ assert_param(IS_I2S_FULLDUPLEX_MODE(hi2s->Init.FullDuplexMode)); if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) { /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ I2SxEXT(hi2s->Instance)->I2SCFGR &= ~(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \ SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \ SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD); I2SxEXT(hi2s->Instance)->I2SPR = 2; /* Get the I2SCFGR register value */ tmpreg = I2SxEXT(hi2s->Instance)->I2SCFGR; /* Get the mode to be configured for the extended I2S */ if((hi2s->Init.Mode == I2S_MODE_MASTER_TX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_TX)) { tmp = I2S_MODE_SLAVE_RX; } else { if((hi2s->Init.Mode == I2S_MODE_MASTER_RX) || (hi2s->Init.Mode == I2S_MODE_SLAVE_RX)) { tmp = I2S_MODE_SLAVE_TX; } } /* Configure the I2S Slave with the I2S Master parameter values */ tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | tmp | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL); /* Write to SPIx I2SCFGR */ I2SxEXT(hi2s->Instance)->I2SCFGR = tmpreg; } hi2s->ErrorCode = HAL_I2S_ERROR_NONE; hi2s->State= HAL_I2S_STATE_READY; return HAL_OK; } /** * @brief Full-Duplex Transmit/Receive data in blocking mode. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @param pTxData: a 16-bit pointer to the Transmit data buffer. * @param pRxData: a 16-bit pointer to the Receive data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S * configuration phase, the Size parameter means the number of 16-bit data length * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected * the Size parameter means the number of 16-bit data length. * @param Timeout: Timeout duration * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size, uint32_t Timeout) { uint32_t tickstart = 0; uint32_t tmp1 = 0, tmp2 = 0; if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) { return HAL_ERROR; } /* Check the I2S State */ if(hi2s->State == HAL_I2S_STATE_READY) { tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S configuration phase, the Size parameter means the number of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data frame is selected the Size parameter means the number of 16-bit data length. */ if((tmp1 == I2S_DATAFORMAT_24B)|| \ (tmp2 == I2S_DATAFORMAT_32B)) { hi2s->TxXferSize = Size*2; hi2s->TxXferCount = Size*2; hi2s->RxXferSize = Size*2; hi2s->RxXferCount = Size*2; } else { hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } /* Process Locked */ __HAL_LOCK(hi2s); /* Set the I2S State busy TX/RX */ hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { /* Check if the I2S is already enabled: The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization between Master and Slave. */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2Sext(receiver) before enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; /* Enable I2Sx peripheral */ __HAL_I2S_ENABLE(hi2s); } while(hi2s->TxXferCount > 0) { /* Wait until TXE flag is set */ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } hi2s->Instance->DR = (*pTxData++); /* Get tick */ tickstart = HAL_GetTick(); /* Wait until RXNE flag is set */ while((I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE) != SPI_SR_RXNE) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_TIMEOUT; } } } (*pRxData++) = I2SxEXT(hi2s->Instance)->DR; hi2s->TxXferCount--; hi2s->RxXferCount--; } } /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ else { /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral before the I2Sext*/ __HAL_I2S_ENABLE(hi2s); /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; } else { /* Check if Master Receiver mode is selected */ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) { /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read access to the SPI_SR register. */ __HAL_I2S_CLEAR_OVRFLAG(hi2s); } } while(hi2s->TxXferCount > 0) { /* Get tick */ tickstart = HAL_GetTick(); /* Wait until TXE flag is set */ while((I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE) != SPI_SR_TXE) { if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_TIMEOUT; } } } I2SxEXT(hi2s->Instance)->DR = (*pTxData++); /* Wait until RXNE flag is set */ if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK) { return HAL_TIMEOUT; } (*pRxData++) = hi2s->Instance->DR; hi2s->TxXferCount--; hi2s->RxXferCount--; } } /* Set the I2S State ready */ hi2s->State = HAL_I2S_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @param pTxData: a 16-bit pointer to the Transmit data buffer. * @param pRxData: a 16-bit pointer to the Receive data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S * configuration phase, the Size parameter means the number of 16-bit data length * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected * the Size parameter means the number of 16-bit data length. * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size) { uint32_t tmp1 = 0, tmp2 = 0; if(hi2s->State == HAL_I2S_STATE_READY) { if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) { return HAL_ERROR; } hi2s->pTxBuffPtr = pTxData; hi2s->pRxBuffPtr = pRxData; tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S configuration phase, the Size parameter means the number of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data frame is selected the Size parameter means the number of 16-bit data length. */ if((tmp1 == I2S_DATAFORMAT_24B)||\ (tmp2 == I2S_DATAFORMAT_32B)) { hi2s->TxXferSize = Size*2; hi2s->TxXferCount = Size*2; hi2s->RxXferSize = Size*2; hi2s->RxXferCount = Size*2; } else { hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } /* Process Locked */ __HAL_LOCK(hi2s); hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { /* Enable I2Sext RXNE and ERR interrupts */ I2SxEXT(hi2s->Instance)->CR2 |= (I2S_IT_RXNE | I2S_IT_ERR); /* Enable I2Sx TXE and ERR interrupts */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2Sext(receiver) before enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; /* Enable I2Sx peripheral */ __HAL_I2S_ENABLE(hi2s); } } /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ else { /* Enable I2Sext TXE and ERR interrupts */ I2SxEXT(hi2s->Instance)->CR2 |= (I2S_IT_TXE |I2S_IT_ERR); /* Enable I2Sext RXNE and ERR interrupts */ __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Check if the I2S_MODE_MASTER_RX is selected */ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) { /* Prepare the First Data before enabling the I2S */ if(hi2s->TxXferCount != 0) { /* Transmit First data */ I2SxEXT(hi2s->Instance)->DR = (*hi2s->pTxBuffPtr++); hi2s->TxXferCount--; if(hi2s->TxXferCount == 0) { /* Disable I2Sext TXE interrupt */ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_TXE; } } } /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; } } /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Full-Duplex Transmit/Receive data in non-blocking mode using DMA * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @param pTxData: a 16-bit pointer to the Transmit data buffer. * @param pRxData: a 16-bit pointer to the Receive data buffer. * @param Size: number of data sample to be sent: * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S * configuration phase, the Size parameter means the number of 16-bit data length * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected * the Size parameter means the number of 16-bit data length. * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization * between Master and Slave(example: audio streaming). * @retval HAL status */ HAL_StatusTypeDef HAL_I2SEx_TransmitReceive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pTxData, uint16_t *pRxData, uint16_t Size) { uint32_t *tmp; uint32_t tmp1 = 0, tmp2 = 0; if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) { return HAL_ERROR; } if(hi2s->State == HAL_I2S_STATE_READY) { hi2s->pTxBuffPtr = pTxData; hi2s->pRxBuffPtr = pRxData; tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); /* Check the Data format: When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S configuration phase, the Size parameter means the number of 16-bit data length in the transaction and when a 24-bit data frame or a 32-bit data frame is selected the Size parameter means the number of 16-bit data length. */ if((tmp1 == I2S_DATAFORMAT_24B)||\ (tmp2 == I2S_DATAFORMAT_32B)) { hi2s->TxXferSize = Size*2; hi2s->TxXferCount = Size*2; hi2s->RxXferSize = Size*2; hi2s->RxXferCount = Size*2; } else { hi2s->TxXferSize = Size; hi2s->TxXferCount = Size; hi2s->RxXferSize = Size; hi2s->RxXferCount = Size; } /* Process Locked */ __HAL_LOCK(hi2s); hi2s->State = HAL_I2S_STATE_BUSY_TX_RX; hi2s->ErrorCode = HAL_I2S_ERROR_NONE; /* Set the I2S Rx DMA Half transfer complete callback */ hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; /* Set the I2S Rx DMA transfer complete callback */ hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; /* Set the I2S Rx DMA error callback */ hi2s->hdmarx->XferErrorCallback = I2S_DMAError; /* Set the I2S Tx DMA Half transfer complete callback */ hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; /* Set the I2S Tx DMA transfer complete callback */ hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; /* Set the I2S Tx DMA error callback */ hi2s->hdmatx->XferErrorCallback = I2S_DMAError; tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { /* Enable the Rx DMA Stream */ tmp = (uint32_t*)&pRxData; HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&I2SxEXT(hi2s->Instance)->DR, *(uint32_t*)tmp, hi2s->RxXferSize); /* Enable Rx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_RXDMAEN; /* Enable the Tx DMA Stream */ tmp = (uint32_t*)&pTxData; HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize); /* Enable Tx DMA Request */ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2Sext(receiver) before enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; /* Enable I2S peripheral after the I2Sext */ __HAL_I2S_ENABLE(hi2s); } } else { /* Enable the Tx DMA Stream */ tmp = (uint32_t*)&pTxData; HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&I2SxEXT(hi2s->Instance)->DR, hi2s->TxXferSize); /* Enable Tx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_TXDMAEN; /* Enable the Rx DMA Stream */ tmp = (uint32_t*)&pRxData; HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize); /* Enable Rx DMA Request */ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; /* Check if the I2S is already enabled */ if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) { /* Enable I2S peripheral before the I2Sext */ __HAL_I2S_ENABLE(hi2s); /* Enable I2Sext(transmitter) after enabling I2Sx peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR |= SPI_I2SCFGR_I2SE; } else { /* Check if Master Receiver mode is selected */ if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) { /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read access to the SPI_SR register. */ __HAL_I2S_CLEAR_OVRFLAG(hi2s); } } } /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } else { return HAL_BUSY; } } /** * @brief Pauses the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); if(hi2s->State == HAL_I2S_STATE_BUSY_TX) { /* Disable the I2S DMA Tx request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); } else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) { /* Disable the I2S DMA Rx request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); } else if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) { if((hi2s->Init.Mode == I2S_MODE_SLAVE_TX)||(hi2s->Init.Mode == I2S_MODE_MASTER_TX)) { /* Disable the I2S DMA Tx request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); /* Disable the I2SEx Rx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); } else { /* Disable the I2S DMA Rx request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); /* Disable the I2SEx Tx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); } } /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } /** * @brief Resumes the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); if(hi2s->State == HAL_I2S_STATE_BUSY_TX) { /* Enable the I2S DMA Tx request */ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; } else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) { /* Enable the I2S DMA Rx request */ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; } else if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) { if((hi2s->Init.Mode == I2S_MODE_SLAVE_TX)||(hi2s->Init.Mode == I2S_MODE_MASTER_TX)) { /* Enable the I2S DMA Tx request */ hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; /* Disable the I2SEx Rx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_RXDMAEN; } else { /* Enable the I2S DMA Rx request */ hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; /* Enable the I2SEx Tx DMA Request */ I2SxEXT(hi2s->Instance)->CR2 |= SPI_CR2_TXDMAEN; } } /* If the I2S peripheral is still not enabled, enable it */ if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) == 0) { /* Enable I2S peripheral */ __HAL_I2S_ENABLE(hi2s); } /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } /** * @brief Resumes the audio stream playing from the Media. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status */ HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) { /* Process Locked */ __HAL_LOCK(hi2s); /* Disable the I2S Tx/Rx DMA requests */ hi2s->Instance->CR2 &= ~SPI_CR2_TXDMAEN; hi2s->Instance->CR2 &= ~SPI_CR2_RXDMAEN; if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) { /* Disable the I2S extended Tx/Rx DMA requests */ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); } /* Abort the I2S DMA Stream tx */ if(hi2s->hdmatx != NULL) { HAL_DMA_Abort(hi2s->hdmatx); } /* Abort the I2S DMA Stream rx */ if(hi2s->hdmarx != NULL) { HAL_DMA_Abort(hi2s->hdmarx); } /* Disable I2S peripheral */ __HAL_I2S_DISABLE(hi2s); if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) { /* Disable the I2Sext peripheral */ I2SxEXT(hi2s->Instance)->I2SCFGR &= ~SPI_I2SCFGR_I2SE; } hi2s->State = HAL_I2S_STATE_READY; /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } /** * @brief This function handles I2S interrupt request. * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval None */ void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) { uint32_t tmp1 = 0, tmp2 = 0; __IO uint32_t tmpreg1 = 0; if(hi2s->Init.FullDuplexMode != I2S_FULLDUPLEXMODE_ENABLE) { if(hi2s->State == HAL_I2S_STATE_BUSY_RX) { tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE); /* I2S in mode Receiver ------------------------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { I2S_Receive_IT(hi2s); } tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); /* I2S Overrun error interrupt occurred ---------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { __HAL_I2S_CLEAR_OVRFLAG(hi2s); hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; } } if(hi2s->State == HAL_I2S_STATE_BUSY_TX) { tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE); /* I2S in mode Tramitter -----------------------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { I2S_Transmit_IT(hi2s); } tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); /* I2S Underrun error interrupt occurred --------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { __HAL_I2S_CLEAR_UDRFLAG(hi2s); hi2s->ErrorCode |= HAL_I2S_ERROR_UDR; } } } else { tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE; tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_RXNE; /* I2Sext in mode Receiver ---------------------------------------------*/ if((tmp1 == SPI_SR_RXNE) && (tmp2 == I2S_IT_RXNE)) { tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX, the I2Sext RXNE interrupt will be generated to manage the full-duplex receive phase. */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { I2SEx_TransmitReceive_IT(hi2s); } } tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_OVR; tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_ERR; /* I2Sext Overrun error interrupt occurred ------------------------------*/ if((tmp1 == SPI_SR_OVR) && (tmp2 == I2S_IT_ERR)) { /* Clear I2Sext OVR Flag */ tmpreg1 = I2SxEXT(hi2s->Instance)->DR; tmpreg1 = I2SxEXT(hi2s->Instance)->SR; hi2s->ErrorCode |= HAL_I2SEX_ERROR_OVR; UNUSED(tmpreg1); } tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE); /* I2S in mode Tramitter -----------------------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* When the I2S mode is configured as I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX, the I2S TXE interrupt will be generated to manage the full-duplex transmit phase. */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { I2SEx_TransmitReceive_IT(hi2s); } } tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); /* I2S Underrun error interrupt occurred --------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { __HAL_I2S_CLEAR_UDRFLAG(hi2s); hi2s->ErrorCode |= HAL_I2S_ERROR_UDR; } } /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ else { tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE); /* I2S in mode Receiver ------------------------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX, the I2S RXNE interrupt will be generated to manage the full-duplex receive phase. */ if((tmp1 == I2S_MODE_MASTER_RX) || (tmp2 == I2S_MODE_SLAVE_RX)) { I2SEx_TransmitReceive_IT(hi2s); } } tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR); tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); /* I2S Overrun error interrupt occurred ---------------------------------*/ if((tmp1 != RESET) && (tmp2 != RESET)) { __HAL_I2S_CLEAR_OVRFLAG(hi2s); hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; } tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE; tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_TXE; /* I2Sext in mode Tramitter --------------------------------------------*/ if((tmp1 == SPI_SR_TXE) && (tmp2 == I2S_IT_TXE)) { tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* When the I2S mode is configured as I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX, the I2Sext TXE interrupt will be generated to manage the full-duplex transmit phase. */ if((tmp1 == I2S_MODE_MASTER_RX) || (tmp2 == I2S_MODE_SLAVE_RX)) { I2SEx_TransmitReceive_IT(hi2s); } } tmp1 = I2SxEXT(hi2s->Instance)->SR & SPI_SR_UDR; tmp2 = I2SxEXT(hi2s->Instance)->CR2 & I2S_IT_ERR; /* I2Sext Underrun error interrupt occurred -----------------------------*/ if((tmp1 == SPI_SR_UDR) && (tmp2 == I2S_IT_ERR)) { /* Clear I2Sext UDR Flag */ tmpreg1 = I2SxEXT(hi2s->Instance)->SR; hi2s->ErrorCode |= HAL_I2SEX_ERROR_UDR; UNUSED(tmpreg1); } } } /* Call the Error call Back in case of Errors */ if(hi2s->ErrorCode != HAL_I2S_ERROR_NONE) { /* Set the I2S state ready to be able to start again the process */ hi2s->State= HAL_I2S_STATE_READY; HAL_I2S_ErrorCallback(hi2s); } } /** * @} */ /** * @brief Full-Duplex Transmit/Receive data in non-blocking mode using Interrupt * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval HAL status */ HAL_StatusTypeDef I2SEx_TransmitReceive_IT(I2S_HandleTypeDef *hi2s) { uint32_t tmp1 = 0, tmp2 = 0; if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) { /* Process Locked */ __HAL_LOCK(hi2s); tmp1 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; tmp2 = hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG; /* Check if the I2S_MODE_MASTER_TX or I2S_MODE_SLAVE_TX Mode is selected */ if((tmp1 == I2S_MODE_MASTER_TX) || (tmp2 == I2S_MODE_SLAVE_TX)) { if(hi2s->TxXferCount != 0) { if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE) != RESET) { /* Transmit data */ hi2s->Instance->DR = (*hi2s->pTxBuffPtr++); hi2s->TxXferCount--; if(hi2s->TxXferCount == 0) { /* Disable TXE interrupt */ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_TXE); } } } if(hi2s->RxXferCount != 0) { if((I2SxEXT(hi2s->Instance)->SR & SPI_SR_RXNE) == SPI_SR_RXNE) { /* Receive data */ (*hi2s->pRxBuffPtr++) = I2SxEXT(hi2s->Instance)->DR; hi2s->RxXferCount--; if(hi2s->RxXferCount == 0) { /* Disable I2Sext RXNE interrupt */ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_RXNE; } } } } /* The I2S_MODE_MASTER_RX or I2S_MODE_SLAVE_RX Mode is selected */ else { if(hi2s->TxXferCount != 0) { if((I2SxEXT(hi2s->Instance)->SR & SPI_SR_TXE) == SPI_SR_TXE) { /* Transmit data */ I2SxEXT(hi2s->Instance)->DR = (*hi2s->pTxBuffPtr++); hi2s->TxXferCount--; if(hi2s->TxXferCount == 0) { /* Disable I2Sext TXE interrupt */ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_TXE; HAL_I2S_TxCpltCallback(hi2s); } } } if(hi2s->RxXferCount != 0) { if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE) != RESET) { /* Receive data */ (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR; hi2s->RxXferCount--; if(hi2s->RxXferCount == 0) { /* Disable RXNE interrupt */ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_RXNE); HAL_I2S_RxCpltCallback(hi2s); } } } } tmp1 = hi2s->RxXferCount; tmp2 = hi2s->TxXferCount; if((tmp1 == 0) && (tmp2 == 0)) { /* Disable I2Sx ERR interrupt */ __HAL_I2S_DISABLE_IT(hi2s, I2S_IT_ERR); /* Disable I2Sext ERR interrupt */ I2SxEXT(hi2s->Instance)->CR2 &= ~I2S_IT_ERR; hi2s->State = HAL_I2S_STATE_READY; } /* Process Unlocked */ __HAL_UNLOCK(hi2s); return HAL_OK; } else { return HAL_BUSY; } } #endif /* STM32F40xxx/ STM32F41xxx/ STM32F42xxx/ STM32F43xxx/ STM32F401xx/ STM32F411xx */ /** * @brief DMA I2S transmit process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) { I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0) { hi2s->TxXferCount = 0; /* Disable Tx DMA Request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) { /* Disable Rx DMA Request for the slave*/ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); } #endif /* STM32F40xxx/ STM32F41xxx/ STM32F42xxx/ STM32F43xxx/ STM32F401xx/ STM32F411xx */ if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) { if(hi2s->RxXferCount == 0) { hi2s->State = HAL_I2S_STATE_READY; } } else { hi2s->State = HAL_I2S_STATE_READY; } } HAL_I2S_TxCpltCallback(hi2s); } /** * @brief DMA I2S receive process complete callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) { I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0) { /* Disable Rx DMA Request */ hi2s->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE) if(hi2s->Init.FullDuplexMode == I2S_FULLDUPLEXMODE_ENABLE) { /* Disable Tx DMA Request for the slave*/ I2SxEXT(hi2s->Instance)->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); } #endif /* STM32F40xxx/ STM32F41xxx/ STM32F42xxx/ STM32F43xxx/ STM32F401xx/ STM32F411xx */ hi2s->RxXferCount = 0; if(hi2s->State == HAL_I2S_STATE_BUSY_TX_RX) { if(hi2s->TxXferCount == 0) { hi2s->State = HAL_I2S_STATE_READY; } } else { hi2s->State = HAL_I2S_STATE_READY; } } HAL_I2S_RxCpltCallback(hi2s); } /** * @brief Get I2S clock Input based on Source clock selection in RCC * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains * the configuration information for I2S module * @retval I2S Clock Input */ uint32_t I2S_GetInputClock(I2S_HandleTypeDef *hi2s) { /* This variable used to store the VCO Input (value in Hz) */ uint32_t vcoinput = 0; /* This variable used to store the VCO Output (value in Hz) */ uint32_t vcooutput = 0; /* This variable used to store the I2S_CK_x (value in Hz) */ uint32_t i2ssourceclock = 0; /* Configure SAI Clock based on SAI source clock selection */ #if defined(STM32F446xx) switch(hi2s->Init.ClockSource) { case I2S_CLOCK_EXTERNAL : { /* Set the I2S clock to the external clock value */ i2ssourceclock = EXTERNAL_CLOCK_VALUE; break; } case I2S_CLOCK_PLL : { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); } else { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); } /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6) & (RCC_PLLI2SCFGR_PLLI2SN >> 6))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ i2ssourceclock = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28) & (RCC_PLLI2SCFGR_PLLI2SR >> 28))); break; } case I2S_CLOCK_PLLR : { /* Configure the PLLI2S division factor */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); } else { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); } /* PLL_VCO Output = PLL_VCO Input * PLLN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6) & (RCC_PLLCFGR_PLLN >> 6))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ i2ssourceclock = (uint32_t)(vcooutput /(((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 28) & (RCC_PLLCFGR_PLLR >> 28))); break; } case I2S_CLOCK_PLLSRC : { /* Configure the PLLI2S division factor */ /* PLL_VCO Input = PLL_SOURCE/PLLM */ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ i2ssourceclock = (uint32_t)(HSE_VALUE); } else { /* Get the I2S source clock value */ i2ssourceclock = (uint32_t)(HSI_VALUE); } break; } default : { break; } } #endif /* STM32F446xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) ||\ defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F401xC) || defined(STM32F401xE) /* If an external I2S clock has to be used, the specific define should be set in the project configuration or in the stm32f4xx_conf.h file */ if(hi2s->Init.ClockSource == I2S_CLOCK_EXTERNAL) { /* Enable the External Clock selection */ __HAL_RCC_I2S_CONFIG(RCC_I2SCLKSOURCE_EXT); /* Set the I2S clock to the external clock value */ i2ssourceclock = EXTERNAL_CLOCK_VALUE; } else { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLM */ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); } else { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCC->PLLCFGR & RCC_PLLCFGR_PLLM)); } /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6) & (RCC_PLLI2SCFGR_PLLI2SN >> 6))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ i2ssourceclock = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28) & (RCC_PLLI2SCFGR_PLLI2SR >> 28))); } #endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx */ #if defined(STM32F411xE) /* If an external I2S clock has to be used, the specific define should be set in the project configuration or in the stm32f4xx_conf.h file */ if(hi2s->Init.ClockSource == I2S_CLOCK_EXTERNAL) { /* Enable the External Clock selection */ __HAL_RCC_I2S_CONFIG(RCC_I2SCLKSOURCE_EXT); /* Set the I2S clock to the external clock value */ i2ssourceclock = EXTERNAL_CLOCK_VALUE; } else { /* Configure the PLLI2S division factor */ /* PLLI2S_VCO Input = PLL_SOURCE/PLLI2SM */ if((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) == RCC_PLLSOURCE_HSE) { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSE_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); } else { /* Get the I2S source clock value */ vcoinput = (uint32_t)(HSI_VALUE / (uint32_t)(RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SM)); } /* PLLI2S_VCO Output = PLLI2S_VCO Input * PLLI2SN */ vcooutput = (uint32_t)(vcoinput * (((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SN) >> 6) & (RCC_PLLI2SCFGR_PLLI2SN >> 6))); /* I2S_CLK = PLLI2S_VCO Output/PLLI2SR */ i2ssourceclock = (uint32_t)(vcooutput /(((RCC->PLLI2SCFGR & RCC_PLLI2SCFGR_PLLI2SR) >> 28) & (RCC_PLLI2SCFGR_PLLI2SR >> 28))); } #endif /* STM32F411xE */ /* the return result is the value of SAI clock */ return i2ssourceclock; } /** * @} */ #endif /* HAL_I2S_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
BeyondCloud/uRock
Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c
C
mit
54,539
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2018_06_01.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.microsoft.azure.management.network.v2018_06_01.LocalNetworkGateway; import rx.Observable; import com.microsoft.azure.management.network.v2018_06_01.AddressSpace; import com.microsoft.azure.management.network.v2018_06_01.BgpSettings; class LocalNetworkGatewayImpl extends GroupableResourceCoreImpl<LocalNetworkGateway, LocalNetworkGatewayInner, LocalNetworkGatewayImpl, NetworkManager> implements LocalNetworkGateway, LocalNetworkGateway.Definition, LocalNetworkGateway.Update { LocalNetworkGatewayImpl(String name, LocalNetworkGatewayInner inner, NetworkManager manager) { super(name, inner, manager); } @Override public Observable<LocalNetworkGateway> createResourceAsync() { LocalNetworkGatewaysInner client = this.manager().inner().localNetworkGateways(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<LocalNetworkGateway> updateResourceAsync() { LocalNetworkGatewaysInner client = this.manager().inner().localNetworkGateways(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<LocalNetworkGatewayInner> getInnerAsync() { LocalNetworkGatewaysInner client = this.manager().inner().localNetworkGateways(); return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public BgpSettings bgpSettings() { return this.inner().bgpSettings(); } @Override public String etag() { return this.inner().etag(); } @Override public String gatewayIpAddress() { return this.inner().gatewayIpAddress(); } @Override public AddressSpace localNetworkAddressSpace() { return this.inner().localNetworkAddressSpace(); } @Override public String provisioningState() { return this.inner().provisioningState(); } @Override public String resourceGuid() { return this.inner().resourceGuid(); } @Override public LocalNetworkGatewayImpl withBgpSettings(BgpSettings bgpSettings) { this.inner().withBgpSettings(bgpSettings); return this; } @Override public LocalNetworkGatewayImpl withEtag(String etag) { this.inner().withEtag(etag); return this; } @Override public LocalNetworkGatewayImpl withGatewayIpAddress(String gatewayIpAddress) { this.inner().withGatewayIpAddress(gatewayIpAddress); return this; } @Override public LocalNetworkGatewayImpl withLocalNetworkAddressSpace(AddressSpace localNetworkAddressSpace) { this.inner().withLocalNetworkAddressSpace(localNetworkAddressSpace); return this; } @Override public LocalNetworkGatewayImpl withResourceGuid(String resourceGuid) { this.inner().withResourceGuid(resourceGuid); return this; } }
navalev/azure-sdk-for-java
sdk/network/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/LocalNetworkGatewayImpl.java
Java
mit
3,555
/**************************************************************** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * @author: Copyright (C) Tim Carver * ***************************************************************/ package org.emboss.jemboss.soap; import java.util.*; import org.emboss.jemboss.JembossParams; import javax.swing.JOptionPane; //AXIS import org.apache.axis.client.Call; import javax.xml.namespace.QName; import org.apache.axis.encoding.XMLType; /** * * Make a axis call to a private server, using the default service * */ public class PrivateRequest { /** results from calling the web service */ private Hashtable proganswer; /** * * @param mysettings jemboss properties * @param method method to call * @param args arguments * @throws JembossSoapException if authentication fails * */ public PrivateRequest(JembossParams mysettings, String method, Vector args) throws JembossSoapException { this(mysettings, mysettings.getPrivateSoapService(), method, args); } /** * * @param mysettings jemboss properties * @param service service to call * @param method method to call * @throws JembossSoapException If authentication fails * */ public PrivateRequest(JembossParams mysettings, String service, String method) throws JembossSoapException { this(mysettings, service, method, (Vector) null); } /** * * @param mysettings jemboss properties * @param service service to call * @param method method to call * @param args arguments * @throws JembossSoapException if authentication fails */ public PrivateRequest(JembossParams mysettings, String service, String method, Vector args) throws JembossSoapException { try { String endpoint = mysettings.getPublicSoapURL()+"/"+service; org.apache.axis.client.Service serv = new org.apache.axis.client.Service(); Call call = (Call) serv.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName(new QName(service, method)); call.setEncodingStyle(org.apache.axis.Constants.URI_SOAP12_ENC); int nargs = 0; Object params[] = null; if(args != null) { if(mysettings.getUseAuth()) nargs = args.size()+2; else nargs = args.size()+1; params = new Object[nargs]; Enumeration e = args.elements(); for(int i=0;i<args.size();i++) { Object obj = e.nextElement(); params[i] = obj; if(obj.getClass().equals(String.class)) { call.addParameter("Args"+i, XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); } else if(obj.getClass().equals(Vector.class)) { params[i] = obj; call.addParameter("Args"+i, XMLType.SOAP_VECTOR, javax.xml.rpc.ParameterMode.IN); } else if(obj.getClass().equals(Hashtable.class)) { params[i] = getVector((Hashtable)obj); call.addParameter("Args"+i, XMLType.SOAP_VECTOR, javax.xml.rpc.ParameterMode.IN); } else // byte[] { call.addParameter("ByteArray", XMLType.XSD_BASE64, javax.xml.rpc.ParameterMode.IN); params[i] = obj; } } } if(mysettings.getUseAuth() == true) { if(args == null) { nargs = 2; params = new Object[nargs]; } call.addParameter("Door", XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); params[nargs-2] = mysettings.getServiceUserName(); call.addParameter("Key", XMLType.XSD_BASE64, javax.xml.rpc.ParameterMode.IN); params[nargs-1] = mysettings.getServicePasswdByte(); } else //No authorization reqd, so use user name here { //to create own sand box on server if(nargs == 0) { nargs = 1; params = new Object[nargs]; } if(args == null) args = new Vector(); call.addParameter("Door", XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); params[nargs-1] = System.getProperty("user.name"); } call.setReturnType(org.apache.axis.Constants.SOAP_VECTOR); Vector vans = (Vector)call.invoke( params ); proganswer = new Hashtable(); // assumes it's even sized int n = vans.size(); for(int j=0;j<n;j+=2) { String s = (String)vans.get(j); if(s.equals("msg")) { String msg = (String)vans.get(j+1); if(msg.startsWith("Failed Authorisation")) throw new JembossSoapException("Authentication Failed"); else if(msg.indexOf("Error")!=-1 || msg.indexOf("error")!=-1 || msg.equals("NOT OK")) JOptionPane.showMessageDialog(null, msg, "alert", JOptionPane.ERROR_MESSAGE); } proganswer.put(s,vans.get(j+1)); } } catch (Exception e) { System.err.println("Exception in PrivateRequest "+ e.getMessage ()); throw new JembossSoapException(e.getMessage()); } } /** * * Change the contents of a hashtable to a vector * @return contents of the hash * */ private Vector getVector(Hashtable h) { Vector v = new Vector(); for(Enumeration e = h.keys() ; e.hasMoreElements() ;) { String s = (String)e.nextElement(); v.add(s); v.add(h.get(s)); } return v; } /** * * Gets an element out of the embreo result hash * @param val key to look up * @return the element, or an empty String if there is no * element that matches the key * */ public Object getVal(String val) { if (proganswer.containsKey(val)) return proganswer.get(val); else return ""; } /** * * Get the results returned by the server call * @return results * */ public Hashtable getHash() { return proganswer; } }
lauringlab/CodonShuffle
lib/EMBOSS-6.6.0/jemboss/org/emboss/jemboss/soap/PrivateRequest.java
Java
mit
7,138
// Generated by CoffeeScript 1.4.0 (function() { var $, Ajax, Base, Collection, Extend, Include, Model, Queue, Singleton, Spine, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice; Spine = this.Spine || require('spine'); $ = Spine.$; Model = Spine.Model; Queue = $({}); Ajax = { getURL: function(object) { return object && (typeof object.url === "function" ? object.url() : void 0) || object.url; }, enabled: true, disable: function(callback) { if (this.enabled) { this.enabled = false; try { return callback(); } catch (e) { throw e; } finally { this.enabled = true; } } else { return callback(); } }, queue: function(request) { if (request) { return Queue.queue(request); } else { return Queue.queue(); } }, clearQueue: function() { return this.queue([]); } }; Base = (function() { function Base() {} Base.prototype.defaults = { contentType: 'application/json', dataType: 'json', processData: false, headers: { 'X-Requested-With': 'XMLHttpRequest' } }; Base.prototype.queue = Ajax.queue; Base.prototype.ajax = function(params, defaults) { return $.ajax(this.ajaxSettings(params, defaults)); }; Base.prototype.ajaxQueue = function(params, defaults) { var deferred, jqXHR, promise, request, settings; jqXHR = null; deferred = $.Deferred(); promise = deferred.promise(); if (!Ajax.enabled) { return promise; } settings = this.ajaxSettings(params, defaults); request = function(next) { return jqXHR = $.ajax(settings).done(deferred.resolve).fail(deferred.reject).then(next, next); }; promise.abort = function(statusText) { var index; if (jqXHR) { return jqXHR.abort(statusText); } index = $.inArray(request, this.queue()); if (index > -1) { this.queue().splice(index, 1); } deferred.rejectWith(settings.context || settings, [promise, statusText, '']); return promise; }; this.queue(request); return promise; }; Base.prototype.ajaxSettings = function(params, defaults) { return $.extend({}, this.defaults, defaults, params); }; return Base; })(); Collection = (function(_super) { __extends(Collection, _super); function Collection(model) { this.model = model; this.failResponse = __bind(this.failResponse, this); this.recordsResponse = __bind(this.recordsResponse, this); } Collection.prototype.find = function(id, params) { var record; record = new this.model({ id: id }); return this.ajaxQueue(params, { type: 'GET', url: Ajax.getURL(record) }).done(this.recordsResponse).fail(this.failResponse); }; Collection.prototype.all = function(params) { return this.ajaxQueue(params, { type: 'GET', url: Ajax.getURL(this.model) }).done(this.recordsResponse).fail(this.failResponse); }; Collection.prototype.fetch = function(params, options) { var id, _this = this; if (params == null) { params = {}; } if (options == null) { options = {}; } if (id = params.id) { delete params.id; return this.find(id, params).done(function(record) { return _this.model.refresh(record, options); }); } else { return this.all(params).done(function(records) { return _this.model.refresh(records, options); }); } }; Collection.prototype.recordsResponse = function(data, status, xhr) { return this.model.trigger('ajaxSuccess', null, status, xhr); }; Collection.prototype.failResponse = function(xhr, statusText, error) { return this.model.trigger('ajaxError', null, xhr, statusText, error); }; return Collection; })(Base); Singleton = (function(_super) { __extends(Singleton, _super); function Singleton(record) { this.record = record; this.failResponse = __bind(this.failResponse, this); this.recordResponse = __bind(this.recordResponse, this); this.model = this.record.constructor; } Singleton.prototype.reload = function(params, options) { return this.ajaxQueue(params, { type: 'GET', url: Ajax.getURL(this.record) }).done(this.recordResponse(options)).fail(this.failResponse(options)); }; Singleton.prototype.create = function(params, options) { return this.ajaxQueue(params, { type: 'POST', data: JSON.stringify(this.record), url: Ajax.getURL(this.model) }).done(this.recordResponse(options)).fail(this.failResponse(options)); }; Singleton.prototype.update = function(params, options) { return this.ajaxQueue(params, { type: 'PUT', data: JSON.stringify(this.record), url: Ajax.getURL(this.record) }).done(this.recordResponse(options)).fail(this.failResponse(options)); }; Singleton.prototype.destroy = function(params, options) { return this.ajaxQueue(params, { type: 'DELETE', url: Ajax.getURL(this.record) }).done(this.recordResponse(options)).fail(this.failResponse(options)); }; Singleton.prototype.recordResponse = function(options) { var _this = this; if (options == null) { options = {}; } return function(data, status, xhr) { var _ref, _ref1; if (Spine.isBlank(data) || _this.record.destroyed) { data = false; } else { data = _this.model.fromJSON(data); } Ajax.disable(function() { if (data) { if (data.id && _this.record.id !== data.id) { _this.record.changeID(data.id); } return _this.record.updateAttributes(data.attributes()); } }); _this.record.trigger('ajaxSuccess', data, status, xhr); if ((_ref = options.success) != null) { _ref.apply(_this.record); } return (_ref1 = options.done) != null ? _ref1.apply(_this.record) : void 0; }; }; Singleton.prototype.failResponse = function(options) { var _this = this; if (options == null) { options = {}; } return function(xhr, statusText, error) { var _ref, _ref1; _this.record.trigger('ajaxError', xhr, statusText, error); if ((_ref = options.error) != null) { _ref.apply(_this.record); } return (_ref1 = options.fail) != null ? _ref1.apply(_this.record) : void 0; }; }; return Singleton; })(Base); Model.host = ''; Include = { ajax: function() { return new Singleton(this); }, url: function() { var args, url; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; url = Ajax.getURL(this.constructor); if (url.charAt(url.length - 1) !== '/') { url += '/'; } url += encodeURIComponent(this.id); args.unshift(url); return args.join('/'); } }; Extend = { ajax: function() { return new Collection(this); }, url: function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; args.unshift(this.className.toLowerCase() + 's'); args.unshift(Model.host); return args.join('/'); } }; Model.Ajax = { extended: function() { this.fetch(this.ajaxFetch); this.change(this.ajaxChange); this.extend(Extend); return this.include(Include); }, ajaxFetch: function() { var _ref; return (_ref = this.ajax()).fetch.apply(_ref, arguments); }, ajaxChange: function(record, type, options) { if (options == null) { options = {}; } if (options.ajax === false) { return; } return record.ajax()[type](options.ajax, options); } }; Model.Ajax.Methods = { extended: function() { this.extend(Extend); return this.include(Include); } }; Ajax.defaults = Base.prototype.defaults; Spine.Ajax = Ajax; if (typeof module !== "undefined" && module !== null) { module.exports = Ajax; } }).call(this);
Luphia/Elucia-storage-supplier
public/lib/spine/ajax.js
JavaScript
mit
8,846
<html><!-- Created using the cpp_pretty_printer from the dlib C++ library. See http://dlib.net for updates. --><head><title>dlib C++ Library - matrix_la_abstract.h</title></head><body bgcolor='white'><pre> <font color='#009900'>// Copyright (C) 2009 Davis E. King (davis@dlib.net) </font><font color='#009900'>// License: Boost Software License See LICENSE.txt for the full license. </font><font color='#0000FF'>#undef</font> DLIB_MATRIx_LA_FUNCTS_ABSTRACT_ <font color='#0000FF'>#ifdef</font> DLIB_MATRIx_LA_FUNCTS_ABSTRACT_ <font color='#0000FF'>#include</font> "<a style='text-decoration:none' href='matrix_abstract.h.html'>matrix_abstract.h</a>" <font color='#0000FF'>#include</font> <font color='#5555FF'>&lt;</font>complex<font color='#5555FF'>&gt;</font> <font color='#0000FF'>namespace</font> dlib <b>{</b> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// Global linear algebra functions </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::matrix_type <b><a name='inv'></a>inv</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m is a square matrix ensures - returns the inverse of m (Note that if m is singular or so close to being singular that there is a lot of numerical error then the returned matrix will be bogus. You can check by seeing if m*inv(m) is an identity matrix) !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix <b><a name='pinv'></a>pinv</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m, <font color='#0000FF'><u>double</u></font> tol <font color='#5555FF'>=</font> <font color='#979000'>0</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - tol &gt;= 0 ensures - returns the Moore-Penrose pseudoinverse of m. - The returned matrix has m.nc() rows and m.nr() columns. - if (tol == 0) then - singular values less than max(m.nr(),m.nc()) times the machine epsilon times the largest singular value are ignored. - else - singular values less than tol are ignored. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='svd'></a>svd</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> u, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> w, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> v <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - computes the singular value decomposition of m - m == #u*#w*trans(#v) - trans(#u)*#u == identity matrix - trans(#v)*#v == identity matrix - diag(#w) == the singular values of the matrix m in no particular order. All non-diagonal elements of #w are set to 0. - #u.nr() == m.nr() - #u.nc() == m.nc() - #w.nr() == m.nc() - #w.nc() == m.nc() - #v.nr() == m.nc() - #v.nc() == m.nc() - if DLIB_USE_LAPACK is #defined then the xGESVD routine from LAPACK is used to compute the SVD. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>long</u></font> <b><a name='svd2'></a>svd2</b> <font face='Lucida Console'>(</font> <font color='#0000FF'><u>bool</u></font> withu, <font color='#0000FF'><u>bool</u></font> withv, <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> u, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> w, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> v <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m.nr() &gt;= m.nc() ensures - computes the singular value decomposition of matrix m - m == subm(#u,get_rect(m))*diagm(#w)*trans(#v) - trans(#u)*#u == identity matrix - trans(#v)*#v == identity matrix - #w == the singular values of the matrix m in no particular order. - #u.nr() == m.nr() - #u.nc() == m.nr() - #w.nr() == m.nc() - #w.nc() == 1 - #v.nr() == m.nc() - #v.nc() == m.nc() - if (widthu == false) then - ignore the above regarding #u, it isn't computed and its output state is undefined. - if (widthv == false) then - ignore the above regarding #v, it isn't computed and its output state is undefined. - returns an error code of 0, if no errors and 'k' if we fail to converge at the 'kth' singular value. - if (DLIB_USE_LAPACK is #defined) then - if (withu == withv) then - the xGESDD routine from LAPACK is used to compute the SVD. - else - the xGESVD routine from LAPACK is used to compute the SVD. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'><u>void</u></font> <b><a name='svd3'></a>svd3</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> u, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> w, matrix<font color='#5555FF'>&lt;</font>matrix_exp::type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> v <font face='Lucida Console'>)</font>; <font color='#009900'>/*! ensures - computes the singular value decomposition of m - m == #u*diagm(#w)*trans(#v) - trans(#u)*#u == identity matrix - trans(#v)*#v == identity matrix - #w == the singular values of the matrix m in no particular order. - #u.nr() == m.nr() - #u.nc() == m.nc() - #w.nr() == m.nc() - #w.nc() == 1 - #v.nr() == m.nc() - #v.nc() == m.nc() - if DLIB_USE_LAPACK is #defined then the xGESVD routine from LAPACK is used to compute the SVD. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='svd_fast'></a>svd_fast</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> u, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> w, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> v, <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> l, <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> q <font color='#5555FF'>=</font> <font color='#979000'>1</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - l &gt; 0 - A.size() &gt; 0 (i.e. A can't be an empty matrix) ensures - computes the singular value decomposition of A. - Lets define some constants we use to document the behavior of svd_fast(): - Let m = A.nr() - Let n = A.nc() - Let k = min(l, min(m,n)) - Therefore, A represents an m by n matrix and svd_fast() is designed to find a rank-k representation of it. - if (the rank of A is &lt;= k) then - A == #u*diagm(#w)*trans(#v) - else - A is approximated by #u*diagm(#w)*trans(#v) (i.e. In this case A can't be represented with a rank-k matrix, so the matrix you get by trying to reconstruct A from the output of the SVD is not exactly the same.) - trans(#u)*#u == identity matrix - trans(#v)*#v == identity matrix - #w == the top k singular values of the matrix A (in no particular order). - #u.nr() == m - #u.nc() == k - #w.nr() == k - #w.nc() == 1 - #v.nr() == n - #v.nc() == k - This function implements the randomized subspace iteration defined in the algorithm 4.4 and 5.1 boxes of the paper: Finding Structure with Randomness: Probabilistic Algorithms for Constructing Approximate Matrix Decompositions by Halko et al. Therefore, it is very fast and suitable for use with very large matrices. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> sparse_vector_type, <font color='#0000FF'>typename</font> T <font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='svd_fast'></a>svd_fast</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> std::vector<font color='#5555FF'>&lt;</font>sparse_vector_type<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> u, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> w, matrix<font color='#5555FF'>&lt;</font>T<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> v, <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> l, <font color='#0000FF'><u>unsigned</u></font> <font color='#0000FF'><u>long</u></font> q <font color='#5555FF'>=</font> <font color='#979000'>1</font> <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A contains a set of sparse vectors. See dlib/svm/sparse_vector_abstract.h for a definition of what constitutes a sparse vector. - l &gt; 0 - max_index_plus_one(A) &gt; 0 (i.e. A can't be an empty matrix) ensures - computes the singular value decomposition of A. In this case, we interpret A as a matrix of A.size() rows, where each row is defined by a sparse vector. - Lets define some constants we use to document the behavior of svd_fast(): - Let m = A.size() - Let n = max_index_plus_one(A) - Let k = min(l, min(m,n)) - Therefore, A represents an m by n matrix and svd_fast() is designed to find a rank-k representation of it. - if (the rank of A is &lt;= k) then - A == #u*diagm(#w)*trans(#v) - else - A is approximated by #u*diagm(#w)*trans(#v) (i.e. In this case A can't be represented with a rank-k matrix, so the matrix you get by trying to reconstruct A from the output of the SVD is not exactly the same.) - trans(#u)*#u == identity matrix - trans(#v)*#v == identity matrix - #w == the top k singular values of the matrix A (in no particular order). - #u.nr() == m - #u.nc() == k - #w.nr() == k - #w.nc() == 1 - #v.nr() == n - #v.nc() == k - This function implements the randomized subspace iteration defined in the algorithm 4.4 and 5.1 boxes of the paper: Finding Structure with Randomness: Probabilistic Algorithms for Constructing Approximate Matrix Decompositions by Halko et al. Therefore, it is very fast and suitable for use with very large matrices. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> T, <font color='#0000FF'><u>long</u></font> NR, <font color='#0000FF'><u>long</u></font> NC, <font color='#0000FF'>typename</font> MM, <font color='#0000FF'>typename</font> L <font color='#5555FF'>&gt;</font> <font color='#0000FF'><u>void</u></font> <b><a name='orthogonalize'></a>orthogonalize</b> <font face='Lucida Console'>(</font> matrix<font color='#5555FF'>&lt;</font>T,NR,NC,MM,L<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m.nr() &gt;= m.nc() - m.size() &gt; 0 ensures - #m == an orthogonal matrix with the same dimensions as m. In particular, the columns of #m have the same span as the columns of m. - trans(#m)*#m == identity matrix - This function is just shorthand for computing the QR decomposition of m and then storing the Q factor into #m. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix <b><a name='real_eigenvalues'></a>real_eigenvalues</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m.nr() == m.nc() - matrix_exp::type == float or double ensures - returns a matrix E such that: - E.nr() == m.nr() - E.nc() == 1 - E contains the real part of all eigenvalues of the matrix m. (note that the eigenvalues are not sorted) !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::type <b><a name='det'></a>det</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m is a square matrix ensures - returns the determinant of m !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::type <b><a name='trace'></a>trace</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> m <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - m is a square matrix ensures - returns the trace of m (i.e. returns sum(diag(m))) !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::matrix_type <b><a name='chol'></a>chol</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A is a square matrix ensures - if (A has a Cholesky Decomposition) then - returns the decomposition of A. That is, returns a matrix L such that L*trans(L) == A. L will also be lower triangular. - else - returns a matrix with the same dimensions as A but it will have a bogus value. I.e. it won't be a decomposition. In this case the algorithm returns a partial decomposition. - You can tell when chol fails by looking at the lower right element of the returned matrix. If it is 0 then it means A does not have a cholesky decomposition. - If DLIB_USE_LAPACK is defined then the LAPACK routine xPOTRF is used to compute the cholesky decomposition. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::matrix_type <b><a name='inv_lower_triangular'></a>inv_lower_triangular</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A is a square matrix ensures - if (A is lower triangular) then - returns the inverse of A. - else - returns a matrix with the same dimensions as A but it will have a bogus value. I.e. it won't be an inverse. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>const</font> matrix_exp::matrix_type <b><a name='inv_upper_triangular'></a>inv_upper_triangular</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A is a square matrix ensures - if (A is upper triangular) then - returns the inverse of A. - else - returns a matrix with the same dimensions as A but it will have a bogus value. I.e. it won't be an inverse. !*/</font> <font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// Matrix decomposition classes </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font><font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> matrix_exp_type <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='lu_decomposition'></a>lu_decomposition</b> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON matrix_exp_type must be some kind of matrix expression as defined in the dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object) The matrix type must also contain float or double values. WHAT THIS OBJECT REPRESENTS This object represents something that can compute an LU decomposition of a real valued matrix. That is, for any matrix A it computes matrices L, U, and a pivot vector P such that rowm(A,P) == L*U. The LU decomposition with pivoting always exists, even if the matrix is singular, so the constructor will never fail. The primary use of the LU decomposition is in the solution of square systems of simultaneous linear equations. This will fail if is_singular() returns true (or if A is very nearly singular). If DLIB_USE_LAPACK is defined then the LAPACK routine xGETRF is used to compute the LU decomposition. !*/</font> <font color='#0000FF'>public</font>: <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> matrix_exp_type::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> matrix_exp_type::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::layout_type layout_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>type,<font color='#979000'>0</font>,<font color='#979000'>0</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> matrix_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>type,NR,<font color='#979000'>1</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> column_vector_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font><font color='#0000FF'><u>long</u></font>,NR,<font color='#979000'>1</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> pivot_column_vector_type; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <b><a name='lu_decomposition'></a>lu_decomposition</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&amp;</font>A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - EXP::type == lu_decomposition::type - A.size() &gt; 0 ensures - #nr() == A.nr() - #nc() == A.nc() - #is_square() == (A.nr() == A.nc()) - computes the LU factorization of the given A matrix. !*/</font> <font color='#0000FF'><u>bool</u></font> <b><a name='is_square'></a>is_square</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - if (the input A matrix was a square matrix) then - returns true - else - returns false !*/</font> <font color='#0000FF'><u>bool</u></font> <b><a name='is_singular'></a>is_singular</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - is_square() == true ensures - if (the input A matrix is singular) then - returns true - else - returns false !*/</font> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the number of rows in the input matrix !*/</font> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the number of columns in the input matrix !*/</font> <font color='#0000FF'>const</font> matrix_type <b><a name='get_l'></a>get_l</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the lower triangular L factor of the LU factorization. - L.nr() == nr() - L.nc() == min(nr(),nc()) !*/</font> <font color='#0000FF'>const</font> matrix_type <b><a name='get_u'></a>get_u</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the upper triangular U factor of the LU factorization. - U.nr() == min(nr(),nc()) - U.nc() == nc() !*/</font> <font color='#0000FF'>const</font> pivot_column_vector_type<font color='#5555FF'>&amp;</font> <b><a name='get_pivot'></a>get_pivot</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the pivot permutation vector. That is, if A is the input matrix then this function returns a vector P such that: - rowm(A,P) == get_l()*get_u() - P.nr() == A.nr() !*/</font> type <b><a name='det'></a>det</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - is_square() == true ensures - computes and returns the determinant of the input matrix using LU factors. !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_type <b><a name='solve'></a>solve</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&amp;</font>B <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - EXP::type == lu_decomposition::type - is_square() == true - B.nr() == nr() ensures - Let A denote the input matrix to this class's constructor. Then this function solves A*X == B for X and returns X. - Note that if A is singular (or very close to singular) then the X returned by this function won't fit A*X == B very well (if at all). !*/</font> <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> matrix_exp_type <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='cholesky_decomposition'></a>cholesky_decomposition</b> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON matrix_exp_type must be some kind of matrix expression as defined in the dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object) The matrix type must also contain float or double values. WHAT THIS OBJECT REPRESENTS This object represents something that can compute a cholesky decomposition of a real valued matrix. That is, for any symmetric, positive definite matrix A, it computes a lower triangular matrix L such that A == L*trans(L). If the matrix is not symmetric or positive definite, the function computes only a partial decomposition. This can be tested with the is_spd() flag. If DLIB_USE_LAPACK is defined then the LAPACK routine xPOTRF is used to compute the cholesky decomposition. !*/</font> <font color='#0000FF'>public</font>: <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> matrix_exp_type::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> matrix_exp_type::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::layout_type layout_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::matrix_type matrix_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>type,NR,<font color='#979000'>1</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> column_vector_type; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <b><a name='cholesky_decomposition'></a>cholesky_decomposition</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - EXP::type == cholesky_decomposition::type - A.size() &gt; 0 - A.nr() == A.nc() (i.e. A must be a square matrix) ensures - if (A is symmetric positive-definite) then - #is_spd() == true - Constructs a lower triangular matrix L, such that L*trans(L) == A. and #get_l() == L - else - #is_spd() == false !*/</font> <font color='#0000FF'><u>bool</u></font> <b><a name='is_spd'></a>is_spd</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - if (the input matrix was symmetric positive-definite) then - returns true - else - returns false !*/</font> <font color='#0000FF'>const</font> matrix_type<font color='#5555FF'>&amp;</font> <b><a name='get_l'></a>get_l</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the lower triangular factor, L, such that L*trans(L) == A (where A is the input matrix to this class's constructor) - Note that if A is not symmetric positive definite or positive semi-definite then the equation L*trans(L) == A won't hold. !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix <b><a name='solve'></a>solve</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> B <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - EXP::type == cholesky_decomposition::type - B.nr() == get_l().nr() (i.e. the number of rows in B must match the number of rows in the input matrix A) ensures - Let A denote the input matrix to this class's constructor. Then this function solves A*X = B for X and returns X. - Note that if is_spd() == false or A was really close to being non-SPD then the solver will fail to find an accurate solution. !*/</font> <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> matrix_exp_type <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='qr_decomposition'></a>qr_decomposition</b> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON matrix_exp_type must be some kind of matrix expression as defined in the dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object) The matrix type must also contain float or double values. WHAT THIS OBJECT REPRESENTS This object represents something that can compute a classical QR decomposition of an m-by-n real valued matrix A with m &gt;= n. The QR decomposition is an m-by-n orthogonal matrix Q and an n-by-n upper triangular matrix R so that A == Q*R. The QR decomposition always exists, even if the matrix does not have full rank, so the constructor will never fail. The primary use of the QR decomposition is in the least squares solution of non-square systems of simultaneous linear equations. This will fail if is_full_rank() returns false or A is very nearly not full rank. The Q and R factors can be retrieved via the get_q() and get_r() methods. Furthermore, a solve() method is provided to find the least squares solution of Ax=b using the QR factors. If DLIB_USE_LAPACK is #defined then the xGEQRF routine from LAPACK is used to compute the QR decomposition. !*/</font> <font color='#0000FF'>public</font>: <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> matrix_exp_type::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> matrix_exp_type::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::layout_type layout_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>type,<font color='#979000'>0</font>,<font color='#979000'>0</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> matrix_type; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <b><a name='qr_decomposition'></a>qr_decomposition</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - EXP::type == qr_decomposition::type - A.nr() &gt;= A.nc() - A.size() &gt; 0 ensures - #nr() == A.nr() - #nc() == A.nc() - computes the QR decomposition of the given A matrix. !*/</font> <font color='#0000FF'><u>bool</u></font> <b><a name='is_full_rank'></a>is_full_rank</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - if (the input A matrix had full rank) then - returns true - else - returns false !*/</font> <font color='#0000FF'><u>long</u></font> <b><a name='nr'></a>nr</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the number of rows in the input matrix !*/</font> <font color='#0000FF'><u>long</u></font> <b><a name='nc'></a>nc</b><font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the number of columns in the input matrix !*/</font> <font color='#0000FF'>const</font> matrix_type <b><a name='get_r'></a>get_r</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a matrix R such that: - R is the upper triangular factor, R, of the QR factorization - get_q()*R == input matrix A - R.nr() == nc() - R.nc() == nc() !*/</font> <font color='#0000FF'>const</font> matrix_type <b><a name='get_q'></a>get_q</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a matrix Q such that: - Q is the economy-sized orthogonal factor Q from the QR factorization. - trans(Q)*Q == identity matrix - Q*get_r() == input matrix A - Q.nr() == nr() - Q.nc() == nc() !*/</font> <font color='#0000FF'><u>void</u></font> <b><a name='get_q'></a>get_q</b> <font face='Lucida Console'>(</font> matrix_type<font color='#5555FF'>&amp;</font> Q <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - #Q == get_q() - This function exists to allow a user to get the Q matrix without the overhead of returning a matrix by value. !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <font color='#0000FF'>const</font> matrix_type <b><a name='solve'></a>solve</b> <font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> B <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! requires - EXP::type == qr_decomposition::type - B.nr() == nr() ensures - Let A denote the input matrix to this class's constructor. Then this function finds the least squares solution to the equation A*X = B and returns X. X has the following properties: - X is the matrix that minimizes the two norm of A*X-B. That is, it minimizes sum(squared(A*X - B)). - X.nr() == nc() - X.nc() == B.nc() - Note that this function will fail to output a good solution if is_full_rank() == false or the A matrix is close to not being full rank. !*/</font> <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font> <font color='#0000FF'>typename</font> matrix_exp_type <font color='#5555FF'>&gt;</font> <font color='#0000FF'>class</font> <b><a name='eigenvalue_decomposition'></a>eigenvalue_decomposition</b> <b>{</b> <font color='#009900'>/*! REQUIREMENTS ON matrix_exp_type must be some kind of matrix expression as defined in the dlib/matrix/matrix_abstract.h file. (e.g. a dlib::matrix object) The matrix type must also contain float or double values. WHAT THIS OBJECT REPRESENTS This object represents something that can compute an eigenvalue decomposition of a real valued matrix. So it gives you the set of eigenvalues and eigenvectors for a matrix. Let A denote the input matrix to this object's constructor. Then what this object does is it finds two matrices, D and V, such that - A*V == V*D Where V is a square matrix that contains all the eigenvectors of the A matrix (each column of V is an eigenvector) and D is a diagonal matrix containing the eigenvalues of A. It is important to note that if A is symmetric or non-symmetric you get somewhat different results. If A is a symmetric matrix (i.e. A == trans(A)) then: - All the eigenvalues and eigenvectors of A are real numbers. - Because of this there isn't really any point in using the part of this class's interface that returns complex matrices. All you need are the get_real_eigenvalues() and get_pseudo_v() functions. - V*trans(V) should be equal to the identity matrix. That is, all the eigenvectors in V should be orthonormal. - So A == V*D*trans(V) - If DLIB_USE_LAPACK is #defined then this object uses the xSYEVR LAPACK routine. On the other hand, if A is not symmetric then: - Some of the eigenvalues and eigenvectors might be complex numbers. - An eigenvalue is complex if and only if its corresponding eigenvector is complex. So you can check for this case by just checking get_imag_eigenvalues() to see if any values are non-zero. You don't have to check the V matrix as well. - V*trans(V) won't be equal to the identity matrix but it is usually invertible. So A == V*D*inv(V) is usually a valid statement but A == V*D*trans(V) won't be. - If DLIB_USE_LAPACK is #defined then this object uses the xGEEV LAPACK routine. !*/</font> <font color='#0000FF'>public</font>: <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NR <font color='#5555FF'>=</font> matrix_exp_type::NR; <font color='#0000FF'>const</font> <font color='#0000FF'>static</font> <font color='#0000FF'><u>long</u></font> NC <font color='#5555FF'>=</font> matrix_exp_type::NC; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::type type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::mem_manager_type mem_manager_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::layout_type layout_type; <font color='#0000FF'>typedef</font> <font color='#0000FF'>typename</font> matrix_exp_type::matrix_type matrix_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>type,NR,<font color='#979000'>1</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> column_vector_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>std::complex<font color='#5555FF'>&lt;</font>type<font color='#5555FF'>&gt;</font>,<font color='#979000'>0</font>,<font color='#979000'>0</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> complex_matrix_type; <font color='#0000FF'>typedef</font> matrix<font color='#5555FF'>&lt;</font>std::complex<font color='#5555FF'>&lt;</font>type<font color='#5555FF'>&gt;</font>,NR,<font color='#979000'>1</font>,mem_manager_type,layout_type<font color='#5555FF'>&gt;</font> complex_column_vector_type; <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <b><a name='eigenvalue_decomposition'></a>eigenvalue_decomposition</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_exp<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A.nr() == A.nc() - A.size() &gt; 0 - EXP::type == eigenvalue_decomposition::type ensures - #dim() == A.nr() - computes the eigenvalue decomposition of A. - #get_eigenvalues() == the eigenvalues of A - #get_v() == all the eigenvectors of A !*/</font> <font color='#0000FF'>template</font> <font color='#5555FF'>&lt;</font><font color='#0000FF'>typename</font> EXP<font color='#5555FF'>&gt;</font> <b><a name='eigenvalue_decomposition'></a>eigenvalue_decomposition</b><font face='Lucida Console'>(</font> <font color='#0000FF'>const</font> matrix_op<font color='#5555FF'>&lt;</font>op_make_symmetric<font color='#5555FF'>&lt;</font>EXP<font color='#5555FF'>&gt;</font> <font color='#5555FF'>&gt;</font><font color='#5555FF'>&amp;</font> A <font face='Lucida Console'>)</font>; <font color='#009900'>/*! requires - A.nr() == A.nc() - A.size() &gt; 0 - EXP::type == eigenvalue_decomposition::type ensures - #dim() == A.nr() - computes the eigenvalue decomposition of the symmetric matrix A. Does so using a method optimized for symmetric matrices. - #get_eigenvalues() == the eigenvalues of A - #get_v() == all the eigenvectors of A - moreover, since A is symmetric there won't be any imaginary eigenvalues. So we will have: - #get_imag_eigenvalues() == 0 - #get_real_eigenvalues() == the eigenvalues of A - #get_pseudo_v() == all the eigenvectors of A - diagm(#get_real_eigenvalues()) == #get_pseudo_d() Note that the symmetric matrix operator is created by the dlib::make_symmetric() function. This function simply reflects the lower triangular part of a square matrix into the upper triangular part to create a symmetric matrix. It can also be used to denote that a matrix is already symmetric using the C++ type system. !*/</font> <font color='#0000FF'><u>long</u></font> <b><a name='dim'></a>dim</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - dim() == the number of rows/columns in the input matrix A !*/</font> <font color='#0000FF'>const</font> complex_column_vector_type <b><a name='get_eigenvalues'></a>get_eigenvalues</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns diag(get_d()). That is, returns a vector that contains the eigenvalues of the input matrix. - the returned vector has dim() rows - the eigenvalues are not sorted in any particular way !*/</font> <font color='#0000FF'>const</font> column_vector_type<font color='#5555FF'>&amp;</font> <b><a name='get_real_eigenvalues'></a>get_real_eigenvalues</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the real parts of the eigenvalues. That is, returns real(get_eigenvalues()) - the returned vector has dim() rows - the eigenvalues are not sorted in any particular way !*/</font> <font color='#0000FF'>const</font> column_vector_type<font color='#5555FF'>&amp;</font> <b><a name='get_imag_eigenvalues'></a>get_imag_eigenvalues</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the imaginary parts of the eigenvalues. That is, returns imag(get_eigenvalues()) - the returned vector has dim() rows - the eigenvalues are not sorted in any particular way !*/</font> <font color='#0000FF'>const</font> complex_matrix_type <b><a name='get_v'></a>get_v</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns the eigenvector matrix V that is dim() rows by dim() columns - Each column in V is one of the eigenvectors of the input matrix !*/</font> <font color='#0000FF'>const</font> complex_matrix_type <b><a name='get_d'></a>get_d</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a matrix D such that: - D.nr() == dim() - D.nc() == dim() - diag(D) == get_eigenvalues() (i.e. the diagonal of D contains all the eigenvalues in the input matrix) - all off diagonal elements of D are set to 0 !*/</font> <font color='#0000FF'>const</font> matrix_type<font color='#5555FF'>&amp;</font> <b><a name='get_pseudo_v'></a>get_pseudo_v</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - returns a matrix that is dim() rows by dim() columns - Let A denote the input matrix given to this object's constructor. - if (A has any imaginary eigenvalues) then - returns the pseudo-eigenvector matrix V - The matrix V returned by this function is structured such that: - A*V == V*get_pseudo_d() - else - returns the eigenvector matrix V with A's eigenvectors as the columns of V - A*V == V*diagm(get_real_eigenvalues()) !*/</font> <font color='#0000FF'>const</font> matrix_type <b><a name='get_pseudo_d'></a>get_pseudo_d</b> <font face='Lucida Console'>(</font> <font face='Lucida Console'>)</font> <font color='#0000FF'>const</font>; <font color='#009900'>/*! ensures - The returned matrix is dim() rows by dim() columns - Computes and returns the block diagonal eigenvalue matrix. If the original matrix A is not symmetric, then the eigenvalue matrix D is block diagonal with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, a + i*b, in 2-by-2 blocks, (a, b; -b, a). That is, if the complex eigenvalues look like u + iv . . . . . . u - iv . . . . . . a + ib . . . . . . a - ib . . . . . . x . . . . . . y Then D looks like u v . . . . -v u . . . . . . a b . . . . -b a . . . . . . x . . . . . . y This keeps V (The V you get from get_pseudo_v()) a real matrix in both symmetric and non-symmetric cases, and A*V = V*D. - the eigenvalues are not sorted in any particular way !*/</font> <b>}</b>; <font color='#009900'>// ---------------------------------------------------------------------------------------- </font> <b>}</b> <font color='#0000FF'>#endif</font> <font color='#009900'>// DLIB_MATRIx_LA_FUNCTS_ABSTRACT_ </font> </pre></body></html>
eldilibra/mudsling
include/dlib-18.9/docs/dlib/matrix/matrix_la_abstract.h.html
HTML
mit
57,160
class SetImageGravityDefaultToWallpapers < ActiveRecord::Migration def up change_column_default(:wallpapers, :image_gravity, 'c') end def down change_column_default(:wallpapers, :image_gravity, nil) end end
wallgig/wallgig
db/migrate/20140126194412_set_image_gravity_default_to_wallpapers.rb
Ruby
mit
224
/* * Copyright 2007 Sun Microsystems, 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 Sun Microsystems 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. */ package org.jdesktop.animation.transitions; import java.util.*; import javax.swing.*; /** * The type of transition that this effect should be used for. * <p> * This enum class manages the cache of effects for the application. Users wishing to have specific * effects occur on particular components should cache those effects here. These effects will be * retrieved at transition time, based on which components are transitioning and which * transition type is needed. * * @author Chet Haase * @author Rogério Liesenfeld */ public enum TransitionType { /** * Applies to components that exist in both the start and end states of the transition. */ CHANGING, /** * Applies to components that do not exist in the start state, but exist in the end state. */ APPEARING, /** * Applies to components that do not exist in the end state, but exist in the start state. */ DISAPPEARING; private final Map<JComponent, Effect> cachedEffects = new HashMap<JComponent, Effect>(); /** * This method is used to cache a custom effect on a per-component basis for the application. * Note that these custom effects are application wide for the duration of the process, or until * a new or null effect is set for this component. Note also that custom effects are registered * according to the transition type. So a custom <code>TransitionType.CHANGING</code> effect for * a given component will have no bearing on the effect used in a transition where the component * either appears or disappers between the transition states. * * @param component The JComponent that this effect should be applied to. * @param effect The custom effect desired. A null argument effectively cancels any prior * custom value for this component and this transition type; it is equivalent to * calling {@link #removeEffect(javax.swing.JComponent)}. */ public void setEffect(JComponent component, Effect effect) { if (effect == null) { removeEffect(component); return; } cachedEffects.put(component, effect); } /** * This method is called during the setup phase for any transition. It queries this transition * type's cache for a custom effect associated with a given component. * * @param component The component we are querying on behalf of. * @return The custom effect associated with this component. A null return value indicates that * there is no custom effect associated with this component and transition type. */ public Effect getEffect(JComponent component) { return cachedEffects.get(component); } /** * Removes an effect for the specified component in the cache for this transition type, if an * effect exists. * * @param component The component associated with the effect that should be removed. */ public void removeEffect(JComponent component) { cachedEffects.remove(component); } /** * Clears all effects for this transition type. */ public void clearEffects() { cachedEffects.clear(); } /** * Clears the cache for each transition type of all custom effects currently set. */ public static void clearAllEffects() { for (TransitionType transitionType : values()) { transitionType.cachedEffects.clear(); } } }
theyelllowdart/jmockit
samples/AnimatedTransitions/src/org/jdesktop/animation/transitions/TransitionType.java
Java
mit
5,116
package com.aspose.cells.model; import com.aspose.cells.model.Link; import com.aspose.cells.model.CellArea; public class Hyperlink { private String Address = null; private CellArea Area = null; private String ScreenTip = null; private String TextToDisplay = null; private Link link = null; /** * getAddress * Gets String * @return Address */ public String getAddress() { return Address; } /** * setAddress * Sets String * @param Address String */ public void setAddress(String Address) { this.Address = Address; } /** * getArea * Gets CellArea * @return Area */ public CellArea getArea() { return Area; } /** * setArea * Sets CellArea * @param Area CellArea */ public void setArea(CellArea Area) { this.Area = Area; } /** * getScreenTip * Gets String * @return ScreenTip */ public String getScreenTip() { return ScreenTip; } /** * setScreenTip * Sets String * @param ScreenTip String */ public void setScreenTip(String ScreenTip) { this.ScreenTip = ScreenTip; } /** * getTextToDisplay * Gets String * @return TextToDisplay */ public String getTextToDisplay() { return TextToDisplay; } /** * setTextToDisplay * Sets String * @param TextToDisplay String */ public void setTextToDisplay(String TextToDisplay) { this.TextToDisplay = TextToDisplay; } /** * getLink * Gets Link * @return link */ public Link getLink() { return link; } /** * setLink * Sets Link * @param link Link */ public void setLink(Link link) { this.link = link; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Hyperlink {\n"); sb.append(" Address: ").append(Address).append("\n"); sb.append(" Area: ").append(Area).append("\n"); sb.append(" ScreenTip: ").append(ScreenTip).append("\n"); sb.append(" TextToDisplay: ").append(TextToDisplay).append("\n"); sb.append(" link: ").append(link).append("\n"); sb.append("}\n"); return sb.toString(); } }
asposecellscloud/Aspose.Cells_Cloud_SDK_For_Java
src/main/java/com/aspose/cells/model/Hyperlink.java
Java
mit
2,104
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Component\Core\OrderProcessing; use Doctrine\Common\Collections\ArrayCollection; use PhpSpec\ObjectBehavior; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Core\Model\OrderShippingStates; use Sylius\Component\Core\Model\Payment; use Sylius\Component\Core\Model\PaymentInterface; use Sylius\Component\Core\Model\ShipmentInterface; use Sylius\Component\Core\OrderProcessing\StateResolverInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ class StateResolverSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Sylius\Component\Core\OrderProcessing\StateResolver'); } function it_implements_Sylius_order_state_resolver_interface() { $this->shouldImplement(StateResolverInterface::class); } function it_marks_order_as_a_backorders_if_it_contains_backordered_units(OrderInterface $order) { $order->isBackorder()->shouldBeCalled()->willReturn(true); $order->setShippingState(OrderShippingStates::BACKORDER)->shouldBeCalled(); $this->resolveShippingState($order); } function it_marks_order_as_shipped_if_all_shipments_delivered( OrderInterface $order, ShipmentInterface $shipment1, ShipmentInterface $shipment2 ) { $order->isBackorder()->shouldBeCalled()->willReturn(false); $order->getShipments()->willReturn(array($shipment1, $shipment2)); $shipment1->getState()->willReturn(ShipmentInterface::STATE_SHIPPED); $shipment2->getState()->willReturn(ShipmentInterface::STATE_SHIPPED); $order->setShippingState(OrderShippingStates::SHIPPED)->shouldBeCalled(); $this->resolveShippingState($order); } function it_marks_order_as_partially_shipped_if_not_all_shipments_delivered( OrderInterface $order, ShipmentInterface $shipment1, ShipmentInterface $shipment2 ) { $order->isBackorder()->shouldBeCalled()->willReturn(false); $order->getShipments()->willReturn(array($shipment1, $shipment2)); $shipment1->getState()->willReturn(ShipmentInterface::STATE_SHIPPED); $shipment2->getState()->willReturn(ShipmentInterface::STATE_READY); $order->setShippingState(OrderShippingStates::PARTIALLY_SHIPPED)->shouldBeCalled(); $this->resolveShippingState($order); } function it_marks_order_as_returned_if_all_shipments_were_returned( OrderInterface $order, ShipmentInterface $shipment1, ShipmentInterface $shipment2 ) { $order->isBackorder()->shouldBeCalled()->willReturn(false); $order->getShipments()->willReturn(array($shipment1, $shipment2)); $shipment1->getState()->willReturn(ShipmentInterface::STATE_RETURNED); $shipment2->getState()->willReturn(ShipmentInterface::STATE_RETURNED); $order->setShippingState(OrderShippingStates::RETURNED)->shouldBeCalled(); $this->resolveShippingState($order); } function it_marks_order_as_completed_if_fully_paid( OrderInterface $order ) { $payment1 = new Payment(); $payment1->setAmount(10000); $payment1->setState(PaymentInterface::STATE_COMPLETED); $payments = new ArrayCollection(array($payment1)); $order->hasPayments()->willReturn(true); $order->getPayments()->willReturn($payments); $order->getTotal()->willReturn(10000); $order->setPaymentState(PaymentInterface::STATE_COMPLETED)->shouldBeCalled(); $this->resolvePaymentState($order); } function it_marks_order_as_completed_if_fully_paid_multiple_payments( OrderInterface $order ) { $payment1 = new Payment(); $payment1->setAmount(6000); $payment1->setState(PaymentInterface::STATE_COMPLETED); $payment2 = new Payment(); $payment2->setAmount(4000); $payment2->setState(PaymentInterface::STATE_COMPLETED); $payments = new ArrayCollection(array($payment1, $payment2)); $order->hasPayments()->willReturn(true); $order->getPayments()->willReturn($payments); $order->getTotal()->willReturn(10000); $order->setPaymentState(PaymentInterface::STATE_COMPLETED)->shouldBeCalled(); $this->resolvePaymentState($order); } function it_marks_order_as_processing_if_one_of_the_payment_is_processing(OrderInterface $order) { $payment1 = new Payment(); $payment1->setAmount(6000); $payment1->setState(PaymentInterface::STATE_PROCESSING); $payment2 = new Payment(); $payment2->setAmount(4000); $payment2->setState(PaymentInterface::STATE_NEW); $payments = new ArrayCollection(array($payment1, $payment2)); $order->hasPayments()->willReturn(true); $order->getPayments()->willReturn($payments); $order->getTotal()->willReturn(10000); $order->setPaymentState(PaymentInterface::STATE_PROCESSING)->shouldBeCalled(); $this->resolvePaymentState($order); } function it_marks_order_as_new_if_no_payment_is_in_process(OrderInterface $order) { $payment1 = new Payment(); $payment1->setAmount(6000); $payment1->setState(PaymentInterface::STATE_NEW); $payment2 = new Payment(); $payment2->setAmount(4000); $payment2->setState(PaymentInterface::STATE_NEW); $payments = new ArrayCollection(array($payment1, $payment2)); $order->hasPayments()->willReturn(true); $order->getPayments()->willReturn($payments); $order->getTotal()->willReturn(10000); $order->setPaymentState(PaymentInterface::STATE_NEW)->shouldBeCalled(); $this->resolvePaymentState($order); } }
pfwd/Sylius
src/Sylius/Component/Core/spec/OrderProcessing/StateResolverSpec.php
PHP
mit
5,990
module OWD class InventoryStatus < Document def _build opts = {} if opts[:filters] doc.tag!(self.owd_name) do opts[:filters].each do |filt| doc.FILTER filt end end else doc.tag!(self.owd_name) end end end end
rochers/owd
lib/owd/documents/inventory_status.rb
Ruby
mit
295
/* * * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import ColorMapMixin from '../../Mixins/ColorMapSeries.js'; var colorMapSeriesMixin = ColorMapMixin.colorMapSeriesMixin; import H from '../../Core/Globals.js'; var noop = H.noop; import LegendSymbol from '../../Core/Legend/LegendSymbol.js'; import MapChart from '../../Core/Chart/MapChart.js'; var maps = MapChart.maps, splitPath = MapChart.splitPath; import MapPoint from './MapPoint.js'; import palette from '../../Core/Color/Palette.js'; import Series from '../../Core/Series/Series.js'; import SeriesRegistry from '../../Core/Series/SeriesRegistry.js'; var // indirect dependency to keep product size low _a = SeriesRegistry.seriesTypes, ColumnSeries = _a.column, ScatterSeries = _a.scatter; import SVGRenderer from '../../Core/Renderer/SVG/SVGRenderer.js'; import U from '../../Core/Utilities.js'; var extend = U.extend, fireEvent = U.fireEvent, getNestedProperty = U.getNestedProperty, isArray = U.isArray, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat; /* * * * Class * * */ /** * @private * @class * @name Highcharts.seriesTypes.map * * @augments Highcharts.Series */ var MapSeries = /** @class */ (function (_super) { __extends(MapSeries, _super); function MapSeries() { /* * * * Static Properties * * */ var _this = _super !== null && _super.apply(this, arguments) || this; /* * * * Properties * * */ _this.baseTrans = void 0; _this.chart = void 0; _this.data = void 0; _this.group = void 0; _this.joinBy = void 0; _this.options = void 0; _this.points = void 0; _this.transformGroup = void 0; return _this; /* eslint-enable valid-jsdoc */ } /* * * * Functions * * */ /* eslint-disable valid-jsdoc */ /** * The initial animation for the map series. By default, animation is * disabled. Animation of map shapes is not at all supported in VML * browsers. * @private */ MapSeries.prototype.animate = function (init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); } } }; /** * Animate in the new series from the clicked point in the old series. * Depends on the drilldown.js module * @private */ MapSeries.prototype.animateDrilldown = function (init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; this.points.forEach(function (point) { if (point.graphic) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); } }); } }; /** * When drilling up, pull out the individual point graphics from the lower * series and animate them into the origin point in the upper series. * @private */ MapSeries.prototype.animateDrillupFrom = function (level) { ColumnSeries.prototype.animateDrillupFrom.call(this, level); }; /** * When drilling up, keep the upper series invisible until the lower series * has moved into place. * @private */ MapSeries.prototype.animateDrillupTo = function (init) { ColumnSeries.prototype.animateDrillupTo.call(this, init); }; /** * Allow a quick redraw by just translating the area group. Used for zooming * and panning in capable browsers. * @private */ MapSeries.prototype.doFullTranslate = function () { return (this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans); }; /** * Draw the data labels. Special for maps is the time that the data labels * are drawn (after points), and the clipping of the dataLabelsGroup. * @private */ MapSeries.prototype.drawMapDataLabels = function () { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } }; /** * Use the drawPoints method of column, that is able to handle simple * shapeArgs. Extend it by assigning the tooltip position. * @private */ MapSeries.prototype.drawPoints = function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans, transformGroup, startTranslateX, startTranslateY, startScaleX, startScaleY; // Set a group that handles transform during zooming and panning in // order to preserve clipping on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); series.transformGroup.survive = true; } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions. if (chart.hasRendered && !chart.styledMode) { series.points.forEach(function (point) { // Restore state color on update/redraw (#3529) if (point.shapeArgs) { point.shapeArgs.fill = series.pointAttribs(point, point.state).fill; } }); } // Draw them in transformGroup series.group = series.transformGroup; ColumnSeries.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names series.points.forEach(function (point) { if (point.graphic) { var className = ''; if (point.name) { className += 'highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase(); } if (point.properties && point.properties['hc-key']) { className += ' highcharts-key-' + point.properties['hc-key'].toLowerCase(); } if (className) { point.graphic.addClass(className); } // In styled mode, apply point colors by CSS if (chart.styledMode) { point.graphic.css(series.pointAttribs(point, point.selected && 'select' || void 0)); } } }); // Set the base for later scale-zooming. The originX and originY // properties are the axis values in the plot area's upper left // corner. this.baseTrans = { originX: (xAxis.min - xAxis.minPixelPadding / xAxis.transA), originY: (yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA)), transAX: xAxis.transA, transAY: yAxis.transA }; // Reset transformation in case we're doing a full translate // (#3789) this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 }); // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); // Handle rounding errors in normal view (#3789) if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) { scaleX = 1; scaleY = 1; translateX = Math.round(translateX); translateY = Math.round(translateY); } /* Animate or move to the new zoom level. In order to prevent flickering as the different transform components are set out of sync (#5991), we run a fake animator attribute and set scale and translation synchronously in the same step. A possible improvement to the API would be to handle this in the renderer or animation engine itself, to ensure that when we are animating multiple properties, we make sure that each step for each property is performed in the same step. Also, for symbols and for transform properties, it should induce a single updateTransform and symbolAttr call. */ transformGroup = this.transformGroup; if (chart.renderer.globalAnimation) { startTranslateX = transformGroup.attr('translateX'); startTranslateY = transformGroup.attr('translateY'); startScaleX = transformGroup.attr('scaleX'); startScaleY = transformGroup.attr('scaleY'); transformGroup .attr({ animator: 0 }) .animate({ animator: 1 }, { step: function (now, fx) { transformGroup.attr({ translateX: (startTranslateX + (translateX - startTranslateX) * fx.pos), translateY: (startTranslateY + (translateY - startTranslateY) * fx.pos), scaleX: (startScaleX + (scaleX - startScaleX) * fx.pos), scaleY: (startScaleY + (scaleY - startScaleY) * fx.pos) }); } }); // When dragging, animation is off. } else { transformGroup.attr({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } } /* Set the stroke-width directly on the group element so the children inherit it. We need to use setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be set. */ if (!chart.styledMode) { group.element.setAttribute('stroke-width', (pick(series.options[(series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth'], 1 // Styled mode ) / (scaleX || 1))); } this.drawMapDataLabels(); }; /** * Get the bounding box of all paths in the map combined. * @private */ MapSeries.prototype.getBox = function (paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box (paths || []).forEach(function (point) { if (point.path) { if (typeof point.path === 'string') { point.path = splitPath(point.path); // Legacy one-dimensional array } else if (point.path[0] === 'M') { point.path = SVGRenderer.prototype.pathToSegments(point.path); } var path = point.path || [], pointMaxX_1 = -MAX_VALUE, pointMinX_1 = MAX_VALUE, pointMaxY_1 = -MAX_VALUE, pointMinY_1 = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { path.forEach(function (seg) { var x = seg[seg.length - 2]; var y = seg[seg.length - 1]; if (typeof x === 'number' && typeof y === 'number') { pointMinX_1 = Math.min(pointMinX_1, x); pointMaxX_1 = Math.max(pointMaxX_1, x); pointMinY_1 = Math.min(pointMinY_1, y); pointMaxY_1 = Math.max(pointMaxY_1, y); } }); // Cache point bounding box for use to position data // labels, bubbles etc point._midX = (pointMinX_1 + (pointMaxX_1 - pointMinX_1) * pick(point.middleX, properties && properties['hc-middle-x'], 0.5)); point._midY = (pointMinY_1 + (pointMaxY_1 - pointMinY_1) * pick(point.middleY, properties && properties['hc-middle-y'], 0.5)); point._maxX = pointMaxX_1; point._minX = pointMinX_1; point._maxY = pointMaxY_1; point._minY = pointMinY_1; point.labelrank = pick(point.labelrank, (pointMaxX_1 - pointMinX_1) * (pointMaxY_1 - pointMinY_1)); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming // range to 5 times the size of the smallest element if (xAxis && typeof xAxis.options.minRange === 'undefined') { xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE); } if (yAxis && typeof yAxis.options.minRange === 'undefined') { yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE); } } }; MapSeries.prototype.getExtremes = function () { // Get the actual value extremes for colors var _a = Series.prototype.getExtremes .call(this, this.valueData), dataMin = _a.dataMin, dataMax = _a.dataMax; // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } if (isNumber(dataMin)) { this.valueMin = dataMin; } if (isNumber(dataMax)) { this.valueMax = dataMax; } // Extremes for the mock Y axis return { dataMin: this.minY, dataMax: this.maxY }; }; /** * Define hasData function for non-cartesian series. Returns true if the * series has points at all. * @private */ MapSeries.prototype.hasData = function () { return !!this.processedXData.length; // != 0 }; /** * Get presentational attributes. In the maps series this runs in both * styled and non-styled mode, because colors hold data when a colorAxis is * used. * @private */ MapSeries.prototype.pointAttribs = function (point, state) { var attr = point.series.chart.styledMode ? this.colorAttribs(point) : ColumnSeries.prototype.pointAttribs.call(this, point, state); // Set the stroke-width on the group element and let all point // graphics inherit. That way we don't have to iterate over all // points to update the stroke-width on zooming. attr['stroke-width'] = pick(point.options[(this.pointAttrToOptions && this.pointAttrToOptions['stroke-width']) || 'borderWidth'], 'inherit'); return attr; }; /** * Override render to throw in an async call in IE8. Otherwise it chokes on * the US counties demo. * @private */ MapSeries.prototype.render = function () { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function () { render.call(series); }); } else { render.call(series); } }; /** * Extend setData to join in mapData. If the allAreas option is true, all * areas from the mapData are used, and those that don't correspond to a * data value are given null values. * @private */ MapSeries.prototype.setData = function (data, redraw, animation, updatePoints) { var options = this.options, chartOptions = this.chart.options.chart, globalMapData = chartOptions && chartOptions.map, mapData = options.mapData, joinBy = this.joinBy, pointArrayMap = options.keys || this.pointArrayMap, dataUsed = [], mapMap = {}, mapPoint, mapTransforms = this.chart.mapTransforms, props, i; // Collect mapData from chart options if not defined on series if (!mapData && globalMapData) { mapData = typeof globalMapData === 'string' ? maps[globalMapData] : globalMapData; } // Pick up numeric values, add index // Convert Array point definitions to objects using pointArrayMap if (data) { data.forEach(function (val, i) { var ix = 0; if (isNumber(val)) { data[i] = { value: val }; } else if (isArray(val)) { data[i] = {}; // Automatically copy first item to hc-key if there is // an extra leading string if (!options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string') { data[i]['hc-key'] = val[0]; ++ix; } // Run through pointArrayMap and what's left of the // point data array in parallel, copying over the values for (var j = 0; j < pointArrayMap.length; ++j, ++ix) { if (pointArrayMap[j] && typeof val[ix] !== 'undefined') { if (pointArrayMap[j].indexOf('.') > 0) { MapPoint.prototype.setNestedProperty(data[i], val[ix], pointArrayMap[j]); } else { data[i][pointArrayMap[j]] = val[ix]; } } } } if (joinBy && joinBy[0] === '_i') { data[i]._i = i; } }); } this.getBox(data); // Pick up transform definitions for chart this.chart.mapTransforms = mapTransforms = chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms; // Cache cos/sin of transform rotation angle if (mapTransforms) { objectEach(mapTransforms, function (transform) { if (transform.rotation) { transform.cosAngle = Math.cos(transform.rotation); transform.sinAngle = Math.sin(transform.rotation); } }); } if (mapData) { if (mapData.type === 'FeatureCollection') { this.mapTitle = mapData.title; mapData = H.geojson(mapData, this.type, this); } this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } mapMap[mapPoint[joinBy[0]]] = mapPoint; } this.mapMap = mapMap; // Registered the point codes that actually hold data if (data && joinBy[1]) { var joinKey_1 = joinBy[1]; data.forEach(function (pointOptions) { var mapKey = getNestedProperty(joinKey_1, pointOptions); if (mapMap[mapKey]) { dataUsed.push(mapMap[mapKey]); } }); } if (options.allAreas) { this.getBox(mapData); data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { var joinKey_2 = joinBy[1]; data.forEach(function (pointOptions) { dataUsed.push(getNestedProperty(joinKey_2, pointOptions)); }); } // Add those map points that don't correspond to data, which // will be drawn as null points dataUsed = ('|' + dataUsed.map(function (point) { return point && point[joinBy[0]]; }).join('|') + '|'); // Faster than array.indexOf mapData.forEach(function (mapPoint) { if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) { data.push(merge(mapPoint, { value: null })); // #5050 - adding all areas causes the update // optimization of setData to kick in, even though // the point order has changed updatePoints = false; } }); } else { this.getBox(dataUsed); // Issue #4784 } } Series.prototype.setData.call(this, data, redraw, animation, updatePoints); }; /** * Extend setOptions by picking up the joinBy option and applying it to a * series property. * @private */ MapSeries.prototype.setOptions = function (itemOptions) { var options = Series.prototype.setOptions.call(this, itemOptions), joinBy = options.joinBy, joinByNull = joinBy === null; if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } return options; }; /** * Add the path option for data points. Find the max value for color * calculation. * @private */ MapSeries.prototype.translate = function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); series.data.forEach(function (point) { // Record the middle point (loosely based on centroid), // determined by the middleX and middleY options. if (isNumber(point._midX) && isNumber(point._midY)) { point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); } if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { d: series.translatePath(point.path) }; } }); fireEvent(series, 'afterTranslate'); }; /** * Translate the path, so it automatically fits into the plot area box. * @private */ MapSeries.prototype.translatePath = function (path) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, ret = []; // Preserve the original // Do the translation if (path) { path.forEach(function (seg) { if (seg[0] === 'M') { ret.push([ 'M', (seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding ]); } else if (seg[0] === 'L') { ret.push([ 'L', (seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding ]); } else if (seg[0] === 'C') { ret.push([ 'C', (seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding, (seg[3] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[4] - (yMin || 0)) * yTransA + yMinPixelPadding, (seg[5] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[6] - (yMin || 0)) * yTransA + yMinPixelPadding ]); } else if (seg[0] === 'Q') { ret.push([ 'Q', (seg[1] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[2] - (yMin || 0)) * yTransA + yMinPixelPadding, (seg[3] - (xMin || 0)) * xTransA + xMinPixelPadding, (seg[4] - (yMin || 0)) * yTransA + yMinPixelPadding ]); } else if (seg[0] === 'Z') { ret.push(['Z']); } }); } return ret; }; /** * The map series is used for basic choropleth maps, where each map area has * a color based on its value. * * @sample maps/demo/all-maps/ * Choropleth map * * @extends plotOptions.scatter * @excluding marker, cluster * @product highmaps * @optionparent plotOptions.map */ MapSeries.defaultOptions = merge(ScatterSeries.defaultOptions, { animation: false, dataLabels: { crop: false, formatter: function () { var numberFormatter = this.series.chart.numberFormatter; var value = this.point.value; return isNumber(value) ? numberFormatter(value, -1) : ''; }, inside: true, overflow: false, padding: 0, verticalAlign: 'middle' }, /** * @ignore-option * * @private */ marker: null, /** * The color to apply to null points. * * In styled mode, the null point fill is set in the * `.highcharts-null-point` class. * * @sample maps/demo/all-areas-as-null/ * Null color * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * * @private */ nullColor: palette.neutralColor3, /** * Whether to allow pointer interaction like tooltips and mouse events * on null points. * * @type {boolean} * @since 4.2.7 * @apioption plotOptions.map.nullInteraction * * @private */ stickyTracking: false, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, /** * @ignore-option * * @private */ turboThreshold: 0, /** * Whether all areas of the map defined in `mapData` should be rendered. * If `true`, areas which don't correspond to a data point, are rendered * as `null` points. If `false`, those areas are skipped. * * @sample maps/plotoptions/series-allareas-false/ * All areas set to false * * @type {boolean} * @default true * @product highmaps * @apioption plotOptions.series.allAreas * * @private */ allAreas: true, /** * The border color of the map areas. * * In styled mode, the border stroke is given in the `.highcharts-point` * class. * * @sample {highmaps} maps/plotoptions/series-border/ * Borders demo * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default #cccccc * @product highmaps * @apioption plotOptions.series.borderColor * * @private */ borderColor: palette.neutralColor20, /** * The border width of each map area. * * In styled mode, the border stroke width is given in the * `.highcharts-point` class. * * @sample maps/plotoptions/series-border/ * Borders demo * * @type {number} * @default 1 * @product highmaps * @apioption plotOptions.series.borderWidth * * @private */ borderWidth: 1, /** * @type {string} * @default value * @apioption plotOptions.map.colorKey */ /** * What property to join the `mapData` to the value data. For example, * if joinBy is "code", the mapData items with a specific code is merged * into the data with the same code. For maps loaded from GeoJSON, the * keys may be held in each point's `properties` object. * * The joinBy option can also be an array of two values, where the first * points to a key in the `mapData`, and the second points to another * key in the `data`. * * When joinBy is `null`, the map items are joined by their position in * the array, which performs much better in maps with many data points. * This is the recommended option if you are printing more than a * thousand data points and have a backend that can preprocess the data * into a parallel array of the mapData. * * @sample maps/plotoptions/series-border/ * Joined by "code" * @sample maps/demo/geojson/ * GeoJSON joined by an array * @sample maps/series/joinby-null/ * Simple data joined by null * * @type {string|Array<string>} * @default hc-key * @product highmaps * @apioption plotOptions.series.joinBy * * @private */ joinBy: 'hc-key', /** * Define the z index of the series. * * @type {number} * @product highmaps * @apioption plotOptions.series.zIndex */ /** * @apioption plotOptions.series.states * * @private */ states: { /** * @apioption plotOptions.series.states.hover */ hover: { /** @ignore-option */ halo: null, /** * The color of the shape in this state. * * @sample maps/plotoptions/series-states-hover/ * Hover options * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption plotOptions.series.states.hover.color */ /** * The border color of the point in this state. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption plotOptions.series.states.hover.borderColor */ /** * The border width of the point in this state * * @type {number} * @product highmaps * @apioption plotOptions.series.states.hover.borderWidth */ /** * The relative brightness of the point when hovered, relative * to the normal point color. * * @type {number} * @product highmaps * @default 0.2 * @apioption plotOptions.series.states.hover.brightness */ brightness: 0.2 }, /** * @apioption plotOptions.series.states.normal */ normal: { /** * @productdesc {highmaps} * The animation adds some latency in order to reduce the effect * of flickering when hovering in and out of for example an * uneven coastline. * * @sample {highmaps} maps/plotoptions/series-states-animation-false/ * No animation of fill color * * @apioption plotOptions.series.states.normal.animation */ animation: true }, /** * @apioption plotOptions.series.states.select */ select: { /** * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default ${palette.neutralColor20} * @product highmaps * @apioption plotOptions.series.states.select.color */ color: palette.neutralColor20 }, inactive: { opacity: 1 } } }); return MapSeries; }(ScatterSeries)); extend(MapSeries.prototype, { type: 'map', axisTypes: colorMapSeriesMixin.axisTypes, colorAttribs: colorMapSeriesMixin.colorAttribs, colorKey: colorMapSeriesMixin.colorKey, // When tooltip is not shared, this series (and derivatives) requires // direct touch/hover. KD-tree does not apply. directTouch: true, // We need the points' bounding boxes in order to draw the data labels, // so we skip it now and call it from drawPoints instead. drawDataLabels: noop, // No graph for the map series drawGraph: noop, drawLegendSymbol: LegendSymbol.drawRectangle, forceDL: true, getExtremesFromAll: true, getSymbol: colorMapSeriesMixin.getSymbol, parallelArrays: colorMapSeriesMixin.parallelArrays, pointArrayMap: colorMapSeriesMixin.pointArrayMap, pointClass: MapPoint, // X axis and Y axis must have same translation slope preserveAspectRatio: true, searchPoint: noop, trackerGroups: colorMapSeriesMixin.trackerGroups, // Get axis extremes from paths, not values useMapGeometry: true }); SeriesRegistry.registerSeriesType('map', MapSeries); /* * * * Default Export * * */ export default MapSeries; /* * * * API Options * * */ /** * A map data object containing a `path` definition and optionally additional * properties to join in the data as per the `joinBy` option. * * @sample maps/demo/category-map/ * Map data and joinBy * * @type {Array<Highcharts.SeriesMapDataOptions>|*} * @product highmaps * @apioption series.mapData */ /** * A `map` series. If the [type](#series.map.type) option is not specified, it * is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.map * @excluding dataParser, dataURL, marker * @product highmaps * @apioption series.map */ /** * An array of data points for the series. For the `map` series type, points can * be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `value` options. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond to * `[hc-key, value]`. Example: * ```js * data: [ * ['us-ny', 0], * ['us-mi', 5], * ['us-tx', 3], * ['us-ak', 5] * ] * ``` * * 3. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.map.turboThreshold), * this option is not available. * ```js * data: [{ * value: 6, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<number|Array<string,(number|null)>|null|*>} * @product highmaps * @apioption series.map.data */ /** * Individual color for the point. By default the color is either used * to denote the value, or pulled from the global `colors` array. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption series.map.data.color */ /** * Individual data label for each point. The options are the same as * the ones for [plotOptions.series.dataLabels]( * #plotOptions.series.dataLabels). * * @sample maps/series/data-datalabels/ * Disable data labels for individual areas * * @type {Highcharts.DataLabelsOptions} * @product highmaps * @apioption series.map.data.dataLabels */ /** * The `id` of a series in the [drilldown.series](#drilldown.series) * array to use for a drilldown for this point. * * @sample maps/demo/map-drilldown/ * Basic drilldown * * @type {string} * @product highmaps * @apioption series.map.data.drilldown */ /** * An id for the point. This can be used after render time to get a * pointer to the point object through `chart.get()`. * * @sample maps/series/data-id/ * Highlight a point by id * * @type {string} * @product highmaps * @apioption series.map.data.id */ /** * When data labels are laid out on a map, Highmaps runs a simplified * algorithm to detect collision. When two labels collide, the one with * the lowest rank is hidden. By default the rank is computed from the * area. * * @type {number} * @product highmaps * @apioption series.map.data.labelrank */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleX can be defined * there. * * @type {number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleX */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleY can be defined * there. * * @type {number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleY */ /** * The name of the point as shown in the legend, tooltip, dataLabel * etc. * * @sample maps/series/data-datalabels/ * Point names * * @type {string} * @product highmaps * @apioption series.map.data.name */ /** * For map and mapline series types, the SVG path for the shape. For * compatibily with old IE, not all SVG path definitions are supported, * but M, L and C operators are safe. * * To achieve a better separation between the structure and the data, * it is recommended to use `mapData` to define that paths instead * of defining them on the data points themselves. * * @sample maps/series/data-path/ * Paths defined in data * * @type {string} * @product highmaps * @apioption series.map.data.path */ /** * The numeric value of the data point. * * @type {number|null} * @product highmaps * @apioption series.map.data.value */ /** * Individual point events * * @extends plotOptions.series.point.events * @product highmaps * @apioption series.map.data.events */ ''; // adds doclets above to the transpiled file
cdnjs/cdnjs
ajax/libs/highcharts/9.2.2/es-modules/Series/Map/MapSeries.js
JavaScript
mit
43,828
import * as React from 'react'; import { assert } from 'chai'; function assertDOMNode(node) { // duck typing a DOM node assert.ok(node.nodeName); } /** * Utility method to make assertions about the ref on an element * @param {React.ReactElement} element - The element should have a component wrapped * in withStyles as the root * @param {function} mount - Should be returnvalue of createMount * @param {function} onRef - Callback, first arg is the ref. * Assert that the ref is a DOM node by default */ export default function testRef(element, mount, onRef = assertDOMNode) { const ref = React.createRef(); const wrapper = mount(React.createElement(React.Fragment, null, React.cloneElement(element, { ref }))); onRef(ref.current, wrapper); }
cdnjs/cdnjs
ajax/libs/material-ui/4.9.7/es/test-utils/testRef.js
JavaScript
mit
831
/* * Copyright (c) 2007 - 2008 by Damien Di Fede <ddf@compartmental.net> * * This program 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 program 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 program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package ddf.minim.javasound; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.SourceDataLine; import org.tritonus.share.sampled.AudioUtils; import javazoom.spi.mpeg.sampled.convert.DecodedMpegAudioInputStream; import ddf.minim.AudioMetaData; class JSMPEGAudioRecordingStream extends JSBaseAudioRecordingStream { private AudioMetaData meta; private AudioInputStream encAis; JSMPEGAudioRecordingStream(JSMinim sys, AudioMetaData mdata, AudioInputStream encStream, AudioInputStream decStream, SourceDataLine sdl, int bufferSize) { super(sys, decStream, sdl, bufferSize, mdata.length()); meta = mdata; encAis = encStream; } public AudioMetaData getMetaData() { return meta; } public int getMillisecondLength() { return meta.length(); } protected int skip(int millis) { system.debug("Skipping forward by " + millis + " milliseconds."); long toSkip = AudioUtils.millis2BytesFrameAligned(millis, format); byte[] skipBytes = new byte[(int)toSkip]; long totalSkipped = 0; try { // it's only able to read about 2 seconds at a time // so we've got to loop until we've skipped the requested amount while (totalSkipped < toSkip) { int read; synchronized ( ais ) { // we don't use skip here because it doesn't work with our decoder read = ais.read(skipBytes, 0, (int)(toSkip - totalSkipped)); } if (read == -1) { // EOF! break; } totalSkipped += read; } } catch (IOException e) { system.error("Unable to skip due to read error: " + e.getMessage()); } system.debug("Total actually skipped was " + totalSkipped + ", which is " + AudioUtils.bytes2Millis(totalSkipped, format) + " milliseconds."); return (int)totalSkipped; } protected void rewind() { // close and reload // because marking the thing such that you can play the // entire file without the mark being invalidated, // essentially means you are loading the file into memory // as it is played. which can mean out-of-memory for large files. synchronized ( ais ) { try { ais.close(); } catch (IOException e) { system.error("Couldn't close the stream for reloading: " + e.getMessage()); } AudioInputStream encIn = system.getAudioInputStream(meta.fileName()); ais = (DecodedMpegAudioInputStream)system.getAudioInputStream(format, encIn); } } }
drakh/enterin_wodies
processing_libraries/minim/src/ddf/minim/javasound/JSMPEGAudioRecordingStream.java
Java
cc0-1.0
3,294
<html> <body> <iframe class="mapa" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3660.768779427074!2d-45.07420856245732!3d-23.432718272002823!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cd522086951abb%3A0x90160a09e57afc85!2sCondom%C3%ADnio+Waldomiro+Ernica+-+R.+Dr.+Esteves+da+Silva%2C+147+-+Centro%2C+Ubatuba+-+SP%2C+11680-000!5e0!3m2!1spt-BR!2sbr!4v1438948062883" frameborder="1" style="border:0" allowfullscreen></iframe> </body> </html>
josealbertorodriguesjunior/epicentro
modules/contato/mapa.html
HTML
cc0-1.0
470
<!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.6.0_27) on Thu Jul 10 12:36:42 IST 2014 --> <title>com.franz.agraph.repository.config</title> <meta name="date" content="2014-07-10"> <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="com.franz.agraph.repository.config"; } //--> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></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 class="aboutLanguage"><em>Franz Inc, AllegroGraph</em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/franz/agraph/repository/package-summary.html">PREV PACKAGE</a></li> <li><a href="../../../../../com/franz/openrdf/rio/nquads/package-summary.html">NEXT PACKAGE</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/franz/agraph/repository/config/package-summary.html" target="_top">FRAMES</a></li> <li><a href="package-summary.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="Package" class="title">Package&nbsp;com.franz.agraph.repository.config</h1> <p class="subTitle"> <div class="block">Repository creation and configuration for AllegroGraph.</div> </p> <p>See:&nbsp;<a href="#package_description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../com/franz/agraph/repository/config/AGRepositoryConfig.html" title="class in com.franz.agraph.repository.config">AGRepositoryConfig</a></td> <td class="colLast"> <div class="block">Configuration for an AllegroGraph Repository.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../com/franz/agraph/repository/config/AGRepositoryFactory.html" title="class in com.franz.agraph.repository.config">AGRepositoryFactory</a></td> <td class="colLast"> <div class="block">A <code>RepositoryFactory</code> that creates <a href="../../../../../com/franz/agraph/repository/AGRepository.html" title="class in com.franz.agraph.repository"><code>AGRepository</code></a>s based on RDF configuration data.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../com/franz/agraph/repository/config/AGRepositorySchema.html" title="class in com.franz.agraph.repository.config">AGRepositorySchema</a></td> <td class="colLast"> <div class="block">Defines constants for the AGRepository schema which is used by <a href="../../../../../com/franz/agraph/repository/config/AGRepositoryFactory.html" title="class in com.franz.agraph.repository.config"><code>AGRepositoryFactory</code></a>s to initialize <a href="../../../../../com/franz/agraph/repository/AGRepository.html" title="class in com.franz.agraph.repository"><code>AGRepository</code></a>s.</div> </td> </tr> </tbody> </table> </li> </ul> <a name="package_description"> <!-- --> </a> <h2 title="Package com.franz.agraph.repository.config Description">Package com.franz.agraph.repository.config Description</h2> <div class="block"><p>Repository creation and configuration for AllegroGraph. </p></div> <dl><dt><span class="strong">Since:</span></dt> <dd>v4.5.1</dd> <dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/franz/agraph/repository/config/AGRepositoryFactory.html" title="class in com.franz.agraph.repository.config"><code>AGRepositoryFactory</code></a>, <a href="../../../../../com/franz/agraph/repository/config/AGRepositoryConfig.html" title="class in com.franz.agraph.repository.config"><code>AGRepositoryConfig</code></a>, <a href="../../../../../com/franz/agraph/repository/config/AGRepositorySchema.html" title="class in com.franz.agraph.repository.config"><code>AGRepositorySchema</code></a></dd></dl> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></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 class="aboutLanguage"><em>Copyright &copy; 2008-2012 Franz Inc.</em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/franz/agraph/repository/package-summary.html">PREV PACKAGE</a></li> <li><a href="../../../../../com/franz/openrdf/rio/nquads/package-summary.html">NEXT PACKAGE</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/franz/agraph/repository/config/package-summary.html" target="_top">FRAMES</a></li> <li><a href="package-summary.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>
mohanever4u/ag-java-client
target/test-ws/acjproject/javadoc/com/franz/agraph/repository/config/package-summary.html
HTML
epl-1.0
7,237
<!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_25) on Thu Sep 12 10:52:55 BST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>com.hp.hpl.jena.sparql.expr.aggregate (Apache Jena ARQ)</title> <meta name="date" content="2013-09-12"> <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="com.hp.hpl.jena.sparql.expr.aggregate (Apache Jena ARQ)"; } //--> </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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/nodevalue/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hp/hpl/jena/sparql/expr/aggregate/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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="Package" class="title">Package&nbsp;com.hp.hpl.jena.sparql.expr.aggregate</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation"> <caption><span>Interface Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Interface</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/Accumulator.html" title="interface in com.hp.hpl.jena.sparql.expr.aggregate">Accumulator</a></td> <td class="colLast"> <div class="block">An Accumulator is the processor for each section of a group, so there is one Accumulator for each group key.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/Aggregator.html" title="interface in com.hp.hpl.jena.sparql.expr.aggregate">Aggregator</a></td> <td class="colLast"> <div class="block">An Aggregator is the processor for the whole result stream.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggAvg.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggAvg</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggAvgDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggAvgDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggCount.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggCount</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggCountDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggCountDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggCountVar.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggCountVar</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggCountVarDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggCountVarDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggGroupConcat.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggGroupConcat</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggGroupConcatDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggGroupConcatDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggMax.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggMax</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggMaxDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggMaxDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggMin.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggMin</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggMinDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggMinDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggNull.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggNull</a></td> <td class="colLast"> <div class="block">The null aggregate (which can't be written in SPARQL) calculates nothering but does help remember the group key</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggregatorBase.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggregatorBase</a></td> <td class="colLast"> <div class="block">Aggregate that does everything except the per-group aggregation that is needed for each operation</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggregatorFactory.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggregatorFactory</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggSample.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggSample</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggSampleDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggSampleDistinct</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggSum.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggSum</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/aggregate/AggSumDistinct.html" title="class in com.hp.hpl.jena.sparql.expr.aggregate">AggSumDistinct</a></td> <td class="colLast">&nbsp;</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 class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/package-summary.html">Prev Package</a></li> <li><a href="../../../../../../../com/hp/hpl/jena/sparql/expr/nodevalue/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?com/hp/hpl/jena/sparql/expr/aggregate/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.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 ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
vuk/Clojure-Movies
resources/apache-jena/javadoc-arq/com/hp/hpl/jena/sparql/expr/aggregate/package-summary.html
HTML
epl-1.0
10,861
/***************************************************************************** * Copyright (c) 2011 CEA LIST. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * CEA LIST - Initial API and implementation * *****************************************************************************/ package org.eclipse.papyrus.sysml.diagram.blockdefinition; import org.eclipse.papyrus.infra.gmfdiag.common.GmfEditorFactory; import org.eclipse.papyrus.sysml.diagram.blockdefinition.provider.ElementTypes; public class BlockDefinitionDiagramEditorFactory extends GmfEditorFactory { public BlockDefinitionDiagramEditorFactory() { super(BlockDefinitionDiagramForMultiEditor.class, ElementTypes.DIAGRAM_ID); } }
bmaggi/Papyrus-SysML11
plugins/diagram/org.eclipse.papyrus.sysml.diagram.blockdefinition/src-gen/org/eclipse/papyrus/sysml/diagram/blockdefinition/BlockDefinitionDiagramEditorFactory.java
Java
epl-1.0
928
/******************************************************************************* * Copyright (c) 2015 Bosch Software Innovations GmbH and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * The Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Bosch Software Innovations GmbH - Please refer to git log *******************************************************************************/ package org.eclipse.vorto.remoterepository.service; import org.eclipse.vorto.remoterepository.builder.IModelQueryBuilder; import org.eclipse.vorto.remoterepository.dao.IModelDAO; import org.eclipse.vorto.remoterepository.model.ModelAuthor; import org.eclipse.vorto.remoterepository.model.ModelContent; import org.eclipse.vorto.remoterepository.model.ModelId; import org.eclipse.vorto.remoterepository.model.ModelView; import org.eclipse.vorto.remoterepository.service.governance.IGovernanceService; import org.eclipse.vorto.remoterepository.service.indexing.IIndexService; import org.eclipse.vorto.remoterepository.service.search.IModelQuery; import org.eclipse.vorto.remoterepository.service.search.IModelQueryFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class DefaultModelRepoService implements IModelRepoService { @Autowired private IModelDAO modelDao; @Autowired private IIndexService indexService; @Autowired private IModelQueryBuilder modelQueryBuilder; @Autowired private IModelQueryFactory modelQueryFactory; @Autowired private IGovernanceService gService; @Override public IModelQuery newQuery() { return modelQueryFactory.newModelQuery(); } @Override public IModelQuery newQueryFromExpression(String expression) { return modelQueryBuilder.buildFromExpression(newQuery(), expression); } @Override public ModelContent getModelContent(ModelId modelId) { return modelDao.getModelById(modelId); } @Override public ModelView saveModel(ModelContent modelContent) { gService.start(modelContent, new ModelAuthor()); ModelView mv = modelDao.saveModel(modelContent); indexService.indexModel(mv); return mv; } }
erlemantos/eclipse-vorto
repo/remoterepository/src/main/java/org/eclipse/vorto/remoterepository/service/DefaultModelRepoService.java
Java
epl-1.0
2,490
/******************************************************************************* * Copyright (c) 2012 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dialogs; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; public class DataSetBindingSelectorPage extends WizardPage { private DataSetBindingSelector selector; public DataSetBindingSelectorPage( ) { super( Messages.getString( "DataSetBindingSelectorPage.Title" ) ); //$NON-NLS-1$ this.setTitle( Messages.getString( "DataSetBindingSelectorPage.Title" ) ); //$NON-NLS-1$ this.setMessage( Messages.getString( "DataSetBindingSelectorPage.Label.SelectBindingColumns" ) ); //$NON-NLS-1$ } public void createControl( Composite parent ) { Composite pageComp = new Composite( parent, SWT.NONE ); GridLayout pageCompLayout = new GridLayout( ); pageCompLayout.marginWidth = 0; pageCompLayout.marginHeight = 0; pageComp.setLayout( pageCompLayout ); pageComp.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL | GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL ) ); UIUtil.bindHelp( pageComp, IHelpContextIds.SELECT_DATASET_BINDING_COLUMN ); pageComp.layout( ); selector = new DataSetBindingSelector( UIUtil.getDefaultShell( ), Messages.getString( "DataSetBindingSelectorPage.Title" ) ); //$NON-NLS-1$ Control control = selector.createDialogArea( pageComp ); control.setLayoutData( new GridData( GridData.FILL_BOTH ) ); setControl( pageComp ); } public boolean isPageComplete( ) { return true; } public Object getResult( ) { if ( selector != null ) return selector.getResult( ); return null; } public void performFinish( ) { selector.okPressed( ); } @Override public void setVisible( boolean visible ) { super.setVisible( visible ); if ( visible ) { getControl( ).forceFocus( ); } } }
sguan-actuate/birt
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dialogs/DataSetBindingSelectorPage.java
Java
epl-1.0
2,767
/* * Copyright (c) 2013 Big Switch Networks, Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * 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.sdnplatform.netvirt.manager.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFType; import org.openflow.util.HexString; import org.sdnplatform.addressspace.BetterEntityClass; import org.sdnplatform.core.ListenerContext; import org.sdnplatform.core.IControllerService; import org.sdnplatform.core.IHAListener; import org.sdnplatform.core.IInfoProvider; import org.sdnplatform.core.IOFMessageListener; import org.sdnplatform.core.IOFSwitch; import org.sdnplatform.core.IOFSwitchListener; import org.sdnplatform.core.IControllerService.Role; import org.sdnplatform.core.annotations.LogMessageCategory; import org.sdnplatform.core.annotations.LogMessageDoc; import org.sdnplatform.core.annotations.LogMessageDocs; import org.sdnplatform.core.module.ModuleContext; import org.sdnplatform.core.module.ModuleException; import org.sdnplatform.core.module.IModule; import org.sdnplatform.core.module.IPlatformService; import org.sdnplatform.core.util.ListenerDispatcher; import org.sdnplatform.core.util.SingletonTask; import org.sdnplatform.devicegroup.DeviceGroupMatcher; import org.sdnplatform.devicegroup.IDeviceGroupMatcher; import org.sdnplatform.devicegroup.MembershipRule; import org.sdnplatform.devicemanager.IDevice; import org.sdnplatform.devicemanager.IDeviceListener; import org.sdnplatform.devicemanager.IDeviceService; import org.sdnplatform.devicemanager.IEntityClass; import org.sdnplatform.devicemanager.SwitchPort; import org.sdnplatform.flowcache.FCQueryObj; import org.sdnplatform.flowcache.FlowCacheQueryResp; import org.sdnplatform.flowcache.IFlowCacheService; import org.sdnplatform.flowcache.IFlowQueryHandler; import org.sdnplatform.flowcache.IFlowReconcileListener; import org.sdnplatform.flowcache.IFlowReconcileService; import org.sdnplatform.flowcache.OFMatchReconcile; import org.sdnplatform.flowcache.PendingSwRespKey; import org.sdnplatform.flowcache.PendingSwitchResp; import org.sdnplatform.flowcache.IFlowCacheService.FCQueryEvType; import org.sdnplatform.forwarding.IRewriteService; import org.sdnplatform.netvirt.core.VNS; import org.sdnplatform.netvirt.core.VNSInterface; import org.sdnplatform.netvirt.core.VNS.ARPMode; import org.sdnplatform.netvirt.core.VNS.BroadcastMode; import org.sdnplatform.netvirt.core.VNS.DHCPMode; import org.sdnplatform.netvirt.manager.IVNSInterfaceClassifier; import org.sdnplatform.netvirt.manager.INetVirtListener; import org.sdnplatform.netvirt.manager.INetVirtManagerService; import org.sdnplatform.netvirt.virtualrouting.IVirtualRoutingService; import org.sdnplatform.netvirt.web.NetVirtWebRoutable; import org.sdnplatform.packet.Ethernet; import org.sdnplatform.packet.IPv4; import org.sdnplatform.restserver.IRestApiService; import org.sdnplatform.storage.IResultSet; import org.sdnplatform.storage.IStorageSourceListener; import org.sdnplatform.storage.IStorageSourceService; import org.sdnplatform.storage.StorageException; import org.sdnplatform.tagmanager.ITagListener; import org.sdnplatform.tagmanager.ITagManagerService; import org.sdnplatform.tagmanager.Tag; import org.sdnplatform.threadpool.IThreadPoolService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The NetVirt manager component is responsible for maintaining a mapping * between devices on the network and the NetVirts and NetVirt interfaces to * which they belong. NetVirt manager does not make any forwarding decision: * its responsibility is limited to NetVirt ID updates. * @author readams */ @LogMessageCategory("Network Virtualization") public class NetVirtManagerImpl implements IModule, IOFMessageListener, INetVirtManagerService, IStorageSourceListener, ITagListener, IFlowReconcileListener, IFlowQueryHandler, IOFSwitchListener, IInfoProvider, IHAListener { protected static Logger logger = LoggerFactory.getLogger(NetVirtManagerImpl.class); // ******************************* // Constants for accessing storage // ******************************* // Table names public static final String VNS_TABLE_NAME = "controller_vns"; public static final String VNS_INTERFACE_RULE_TABLE_NAME = "controller_vnsinterfacerule"; public static final String SWITCH_INTERFACE_CONFIG_TABLE_NAME = "controller_switchinterfaceconfig"; // Column names public static final String ID_COLUMN_NAME = "id"; public static final String ACTIVE_COLUMN_NAME = "active"; public static final String PRIORITY_COLUMN_NAME = "priority"; public static final String ORIGIN_COLUMN_NAME = "origin"; public static final String ADDRESS_SPACE_COLUMN_NAME = "vns_address_space_id"; public static final String DHCP_CONFIG_MODE_COLUMN_NAME = "dhcp_mode"; public static final String DHCP_IP_COLUMN_NAME = "dhcp_ip"; public static final String ARP_CONFIG_MODE_COLUMN_NAME = "arp_mode"; public static final String BROADCAST_CONFIG_MODE_COLUMN_NAME = "broadcast"; public static final String VNS_COLUMN_NAME = "vns_id"; public static final String DESCRIPTION_COLUMN_NAME = "description"; public static final String MULTIPLE_ALLOWED_COLUMN_NAME = "allow_multiple"; public static final String VLAN_TAG_ON_EGRESS_COLUMN_NAME = "vlan_tag_on_egress"; public static final String MAC_COLUMN_NAME = "mac"; public static final String IP_SUBNET_COLUMN_NAME = "ip_subnet"; public static final String SWITCH_COLUMN_NAME = "switch"; public static final String PORTS_COLUMN_NAME = "ports"; public static final String VLANS_COLUMN_NAME = "vlans"; public static final String TAGS_COLUMN_NAME = "tags"; public static final String SWITCH_BROADCAST_IFACE_COLUMN_NAME = "broadcast"; public static final String SWITCH_IFACE_NAME = "if_name"; public static final String SWITCH_DPID = "switch_id"; // Time constants protected static final int INTERFACE_AGE_TIME = 1000 * 60 * 60; // 1 hour protected static final int INTERFACE_CLEANUP_INTERVAL = 12; // hours protected static final int LAST_SEEN_UPDATE_INTERVAL = 1000 * 60 * 5; // 5 minutes protected static final int UPDATE_TASK_BATCH_DELAY_MS = 750; // ******************** // Service Dependencies // ******************** protected IControllerService controllerProvider; protected IDeviceService deviceManager; protected IStorageSourceService storageSource; protected ITagManagerService tagManager; protected IVirtualRoutingService virtualRouting; protected IRestApiService restApi; protected IFlowCacheService betterFlowCacheMgr; protected IFlowReconcileService flowReconcileMgr; protected IThreadPoolService threadPool; protected IRewriteService rewriteService; protected DeviceListenerImpl deviceListener; // ***************** // NetVirt configuration // ***************** /** * This is the switch dpid, iface name tuple of all configured * broadcast interfaces */ public class SwitchInterface { String dpid; String ifaceName; public String getDpid() { return dpid; } public String getIfaceName() { return ifaceName; } } /** * This class represents the configuration of NetVirt manager that is * created / updated / read from storage (NetVirt table and NetVirt interface * table). We use "double buffering" to increase performance. We have one * instance of ConfigState that contains the currently running config * and one that we use to build the configuration while reading from * storage. * @author gregor * */ public static class ConfigState { public ConfigState() { interfaceRuleMap = new HashMap<String, MembershipRule<VNS>>(); vnsMap = new ConcurrentHashMap<String, VNS>(); switchInterfaceRuleMap = new ConcurrentHashMap<Long, List<MembershipRule<VNS>>>(); interfaceMap = new ConcurrentHashMap<String, VNSInterface>(); deviceGroupMatchers = new HashMap<String, IDeviceGroupMatcher<VNS>>(); deviceInterfaceMap = new ConcurrentHashMap<Long, List<VNSInterface>>(); } public void clear() { interfaceRuleMap.clear(); vnsMap.clear(); switchInterfaceRuleMap.clear(); interfaceMap.clear(); deviceGroupMatchers.clear(); deviceInterfaceMap.clear(); } /** * This is the cache for mapping a device to its list of interfaces */ protected Map<Long, List<VNSInterface>> deviceInterfaceMap; /** * This is the set of VNS that exist in the system, mapping * ID to VNS object */ public ConcurrentHashMap<String, VNS> vnsMap; /** * This is the set of VNS interface rules that exist in the * system, mapping ID to VNS interface rule object */ public Map<String,MembershipRule<VNS>> interfaceRuleMap; /** * This is the set of VNS interface rules that exist in the * system, mapping a switch DPID to a VNS interface rule object */ public Map<Long, List<MembershipRule<VNS>>> switchInterfaceRuleMap; /** * This is the set of VNS interfaces that exist in the * system, mapping ID to VNS interface object */ public Map<String,VNSInterface> interfaceMap; /** * Matches devices to interfaces using the interface rules */ public HashMap<String, IDeviceGroupMatcher<VNS>> deviceGroupMatchers; } /** * The currently active config */ protected ConfigState curConfigState; /** * The config currently being read / created from storage */ protected ConfigState newConfigState; /** * This is the set of switch port tuples to which all broadcast * messages will be sent. */ protected List<SwitchInterface> confBroadcastIfaces; /** * This is the set of switch port tuples to which all broadcast * messages will be sent. */ protected List<SwitchPort> broadcastSwitchPorts; protected static final String CLASSIFIER = "Classifier"; private ListenerDispatcher<String,IVNSInterfaceClassifier> vnsInterfaceClassifiers; private IDeviceGroupMatcher<VNS> getDeviceGroupMatcher(IDevice device) { if (device.getEntityClass() == null) return null; String name = device.getEntityClass().getName(); return curConfigState.deviceGroupMatchers.get(name); } /** The number of times flow query resp handler method was called. */ protected int flowQueryRespHandlerCallCount; /** The last fc query resp. */ protected FlowCacheQueryResp lastFCQueryResp; /** * Data structure for pending switch query responses */ protected ConcurrentHashMap<PendingSwRespKey, PendingSwitchResp>pendSwRespMap; public FlowCacheQueryResp getLastFCQueryResp() { return lastFCQueryResp; } public int getFlowQueryRespHandlerCallCount() { return flowQueryRespHandlerCallCount; } public List<SwitchInterface> getConfBroadcastIfaces() { return confBroadcastIfaces; } // ***************** // NetVirt manager state // ***************** /** * Lock for reading from storage into newConfigState */ protected Object newConfigLock; /** * Lock on NetVirt configuration state. * readLock needs to be held while accessing curConfigState * writeLock needs to be held while switching curConfigState and * newConfigState * */ protected ReentrantReadWriteLock configLock; /** * Asynchronous task for responding to NetVirt configuration changes * notifications. */ SingletonTask configUpdateTask; // List of INetVirtListeners protected List<INetVirtListener> netVirtListeners; /* A config property. If this is set to true, we will enable special * treatment for VNS with a non-empty, non-null origin field. If such a * VNS is added/modified/deleted we will /only/ reconcile flows from * this NetVirt and not from all other NetVirt with the same or lower priority. * The assumption / contract is that such NetVirt have non-overlapping * membership rules */ private boolean nonNullOriginSimpleReconcile; public NetVirtManagerImpl() { } /* package private. Only to be used by test code */ void setNonNullOriginSimpleReconcile(boolean nonNullOriginSimpleReconcile) { this.nonNullOriginSimpleReconcile = nonNullOriginSimpleReconcile; } // ****************** // IPlatformService // ****************** @Override public Collection<Class<? extends IPlatformService>> getModuleServices() { Collection<Class<? extends IPlatformService>> l = new ArrayList<Class<? extends IPlatformService>>(); l.add(INetVirtManagerService.class); return l; } @Override public Map<Class<? extends IPlatformService>, IPlatformService> getServiceImpls() { Map<Class<? extends IPlatformService>, IPlatformService> m = new HashMap<Class<? extends IPlatformService>, IPlatformService>(); // We are the class that implements the service m.put(INetVirtManagerService.class, this); return m; } @Override public Collection<Class<? extends IPlatformService>> getModuleDependencies() { Collection<Class<? extends IPlatformService>> l = new ArrayList<Class<? extends IPlatformService>>(); l.add(IControllerService.class); l.add(IDeviceService.class); l.add(IStorageSourceService.class); l.add(ITagManagerService.class); l.add(IRestApiService.class); l.add(IVirtualRoutingService.class); l.add(IFlowCacheService.class); l.add(IFlowReconcileService.class); l.add(IThreadPoolService.class); l.add(IRewriteService.class); return l; } @Override public void init(ModuleContext context) throws ModuleException { Map<String, String> configOptions = context.getConfigParams(this); String option = configOptions.get("nonnulloriginsimplereconcile"); if (option != null && option.equalsIgnoreCase("false")) { nonNullOriginSimpleReconcile = false; logger.info("Disabled special treatmeant of non-null origin for " + "flow reconcile"); } else { nonNullOriginSimpleReconcile = true; logger.info("Enabled special treatmeant of non-null origin for " + "flow reconcile"); } controllerProvider = context.getServiceImpl(IControllerService.class); deviceManager = context.getServiceImpl(IDeviceService.class); storageSource = context.getServiceImpl(IStorageSourceService.class); tagManager = context.getServiceImpl(ITagManagerService.class); restApi = context.getServiceImpl(IRestApiService.class); virtualRouting = context.getServiceImpl(IVirtualRoutingService.class); betterFlowCacheMgr = context.getServiceImpl(IFlowCacheService.class); flowReconcileMgr = context.getServiceImpl(IFlowReconcileService.class); threadPool = context.getServiceImpl(IThreadPoolService.class); rewriteService = context.getServiceImpl(IRewriteService.class); // Init internal data structures flowQueryRespHandlerCallCount = 0; configLock = new ReentrantReadWriteLock(); newConfigLock = new Object(); curConfigState = new ConfigState(); broadcastSwitchPorts = new ArrayList<SwitchPort>(); confBroadcastIfaces = new ArrayList<SwitchInterface>(); configLock = new ReentrantReadWriteLock(); vnsInterfaceClassifiers = new ListenerDispatcher<String, IVNSInterfaceClassifier>(); netVirtListeners = new ArrayList<INetVirtListener>(); deviceListener = new DeviceListenerImpl(); } @Override public void startUp(ModuleContext context) { restApi.addRestletRoutable(new NetVirtWebRoutable()); ScheduledExecutorService ses = threadPool.getScheduledExecutor(); configUpdateTask = new SingletonTask(ses, new Runnable() { @Override public void run() { readVNSConfigFromStorage(); } }); storageSource.createTable(VNS_TABLE_NAME, null); storageSource.setTablePrimaryKeyName(VNS_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(VNS_INTERFACE_RULE_TABLE_NAME, null); storageSource.setTablePrimaryKeyName(VNS_INTERFACE_RULE_TABLE_NAME, ID_COLUMN_NAME); storageSource.createTable(SWITCH_INTERFACE_CONFIG_TABLE_NAME, null); storageSource.setTablePrimaryKeyName(SWITCH_INTERFACE_CONFIG_TABLE_NAME, ID_COLUMN_NAME); storageSource.addListener(VNS_TABLE_NAME, this); storageSource.addListener(VNS_INTERFACE_RULE_TABLE_NAME, this); storageSource.addListener(SWITCH_INTERFACE_CONFIG_TABLE_NAME, this); controllerProvider.addOFMessageListener(OFType.PACKET_IN, this); controllerProvider.addOFMessageListener(OFType.STATS_REPLY, this); controllerProvider.addOFSwitchListener(this); controllerProvider.addHAListener(this); controllerProvider.addInfoProvider("summary", this); flowReconcileMgr.addFlowReconcileListener(this); tagManager.addListener(this); deviceManager.addListener(this.deviceListener); readVNSConfigFromStorage(); readSwitchInterfaceConfig(); } @Override public void addNetVirtListener(INetVirtListener listener) { if (listener != null) netVirtListeners.add(listener); } @Override public void removeNetVirtListener(INetVirtListener listener) { if (listener != null) netVirtListeners.remove(listener); } protected List<INetVirtListener> getNetVirtListener() { return Collections.unmodifiableList(netVirtListeners); } @Override public void addVNSInterfaceClassifier(IVNSInterfaceClassifier classifier) { vnsInterfaceClassifiers.addListener(CLASSIFIER, classifier); } // ****************** // IOFMessageListener // ****************** @Override public IOFMessageListener.Command receive(IOFSwitch sw, OFMessage msg, ListenerContext cntx) { switch (msg.getType()) { case PACKET_IN: return this.processPacketInMessage(sw, (OFPacketIn) msg, cntx); default: break; } return Command.CONTINUE; } @Override public String getName() { return "netVirtmanager"; } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return name.equals("devicemanager"); } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { return false; } // *********** // INetVirtManager // *********** @Override public Iterator<VNS> getAllVNS() { configLock.readLock().lock(); try { return curConfigState.vnsMap.values().iterator(); } finally { configLock.readLock().unlock(); } } @Override public VNS getVNS(String name) { configLock.readLock().lock(); try { return curConfigState.vnsMap.get(name); } finally { configLock.readLock().unlock(); } } @Override @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Failed to assign a VNS to device {device} {exception}", explanation="Could not assign a VNS to the device.", recommendation=LogMessageDoc.GENERIC_ACTION) }) public List<VNSInterface> getInterfaces(IDevice d) { List<VNSInterface> ifaces = null; boolean cachemiss = false; configLock.readLock().lock(); try { // Always check with registered VNSInterfaceClassifiers and union the results. ifaces = classifyUnknownDevice(d); if (logger.isTraceEnabled()) { if (ifaces != null) { for (VNSInterface iface : ifaces) { logger.trace("Registered classifier results: {} matches interface {}", d.getMACAddressString(), iface.toString()); } } else { logger.trace("Registered classifier results: {} matches null interface", d.getMACAddressString()); } } // Check cached interfaces for the device List<VNSInterface> tmpIfaces = curConfigState .deviceInterfaceMap.get(d.getDeviceKey()); cachemiss = (tmpIfaces == null); if (cachemiss) { try { tmpIfaces = matchDevice(d); } catch (Exception e) { logger.error("Failed to assign a VNS to device {}: {}", d, e); } } // Merge the two sets of vnsInterfaces together. if (ifaces != null) { if (tmpIfaces != null && tmpIfaces.size() > 0) { ifaces.addAll(tmpIfaces); } } else { ifaces = tmpIfaces; } if (ifaces == null || ifaces.size() == 0) { // If there's no assignment, assign to the default interface on // the default VNS VNSInterface defIface = getIfaceFromName( new String[] {"default", d.getMACAddressString()}, null, d, null); tmpIfaces = new ArrayList<VNSInterface>(1); tmpIfaces.add(defIface); ifaces = tmpIfaces; } if (cachemiss && tmpIfaces != null) { // Cache result curConfigState.deviceInterfaceMap.put(d.getDeviceKey(), tmpIfaces); for (VNSInterface b : tmpIfaces) { b.getParentVNS().addDevice(d); } if (logger.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("VNS interface(s) assigned: "); sb.append(d.getEntityClass().getName()); sb.append("::"); sb.append(d.getMACAddressString() + " ["); for (VNSInterface b : tmpIfaces) { sb.append(b.getParentVNS().getName() + ":"); sb.append(b.getName() + ","); } sb.append("]"); logger.debug(sb.toString()); } } // Update timestamps on ifaces Date currentTime = new Date(); for (VNSInterface i : ifaces) { i.setLastSeen(currentTime); } } finally { configLock.readLock().unlock(); } if (logger.isTraceEnabled()) { logger.trace("All getInterface results for {} :", d.getMACAddressString()); for (VNSInterface iface : ifaces) { logger.trace("{} matches interface {}", d.getMACAddressString(), iface.toString()); } } return ifaces; } protected List<VNSInterface> classifyUnknownDevice(IDevice d) { if (d == null || d.getEntityClass() == null) return null; List<IVNSInterfaceClassifier> listeners = vnsInterfaceClassifiers.getOrderedListeners(); List<VNSInterface> vnsInterfaces = null; if (listeners != null) { vnsInterfaces = new ArrayList<VNSInterface>(); for (IVNSInterfaceClassifier listener : listeners) { List<VNSInterface> interfaces = listener.classifyDevice(d); if (interfaces != null && interfaces.size() > 0) { vnsInterfaces.addAll(interfaces); } } } if (vnsInterfaces == null || vnsInterfaces.size() == 0) { return null; } else { return vnsInterfaces; } } protected List<VNSInterface> classifyUnknownDevice(String addressSpace, Long deviceMac, Short deviceVlan, Integer deviceIpv4, SwitchPort switchPort) { List<IVNSInterfaceClassifier> listeners = vnsInterfaceClassifiers.getOrderedListeners(); List<VNSInterface> vnsInterfaces = null; if (listeners != null) { vnsInterfaces = new ArrayList<VNSInterface>(); for (IVNSInterfaceClassifier listener : listeners) { List<VNSInterface> interfaces = listener.classifyDevice(addressSpace, deviceMac, deviceVlan, deviceIpv4, switchPort); if (interfaces != null && interfaces.size() > 0) { vnsInterfaces.addAll(interfaces); } } } if (vnsInterfaces == null || vnsInterfaces.size() == 0) { return null; } else { return vnsInterfaces; } } @Override public VNSInterface getInterface(String name) { configLock.readLock().lock(); try { return curConfigState.interfaceMap.get(name); } finally { configLock.readLock().unlock(); } } @Override public Iterator<VNSInterface> getAllInterfaces() { configLock.readLock().lock(); try { return curConfigState.interfaceMap.values().iterator(); } finally { configLock.readLock().unlock(); } } @Override public List<SwitchPort> getBroadcastSwitchPorts() { return broadcastSwitchPorts; } // ******************* // IDeviceListener // ******************* class DeviceListenerImpl implements IDeviceListener { @Override public void deviceAdded(IDevice device) { // Don't care return; } @Override public void deviceRemoved(IDevice device) { clearCachedDeviceState(device.getDeviceKey()); } @Override public void deviceMoved(IDevice device) { // Remove cached device state if we have attachment point rules IDeviceGroupMatcher<VNS> deviceGroupMatcher = getDeviceGroupMatcher(device); if (deviceGroupMatcher == null) return; if (deviceGroupMatcher.hasSwitchPortRules() || deviceGroupMatcher.hasTagRules()) { clearCachedDeviceState(device.getDeviceKey()); } } @Override public void deviceIPV4AddrChanged(IDevice device) { // Remove cached device state if we have ip address rules IDeviceGroupMatcher<VNS> deviceGroupMatcher = getDeviceGroupMatcher(device); if (deviceGroupMatcher == null) return; if (deviceGroupMatcher.hasIpSubnetRules()) { clearCachedDeviceState(device.getDeviceKey()); } } @Override public void deviceVlanChanged(IDevice device) { clearCachedDeviceState(device.getDeviceKey()); } @Override public String getName() { return NetVirtManagerImpl.this.getName(); } @Override public boolean isCallbackOrderingPrereq(String type, String name) { return false; } @Override public boolean isCallbackOrderingPostreq(String type, String name) { return false; } } // *************** // IFlowReconcileListener // *************** @Override public Command reconcileFlows(ArrayList<OFMatchReconcile> ofmRcList) { for (OFMatchReconcile ofm : ofmRcList) { IFlowCacheService.fcStore.put(ofm.cntx, IFlowCacheService.FLOWCACHE_APP_INSTANCE_NAME, "netVirt"); if (logger.isTraceEnabled()) { logger.trace("Reconciling flow: match={}", ofm.ofmWithSwDpid.getOfMatch()); } annotateDeviceVNSInterfaces (ofm.cntx, ofm.ofmWithSwDpid.getOfMatch()); } return Command.CONTINUE; } // ***************** // IFlowQueryHandler // ***************** @Override public void flowQueryRespHandler(FlowCacheQueryResp flowResp) { flowQueryRespHandlerCallCount++; lastFCQueryResp = flowResp; if (logger.isTraceEnabled()) { logger.trace("Executing flowQueryRespHandler {} flowCnt={}", flowResp.toString(), lastFCQueryResp.qrFlowCacheObjList.size()); } flowReconcileMgr.flowQueryGenericHandler(flowResp); } // ********************** // IStorageSourceListener // ********************** @Override public void rowsModified(String tableName, Set<Object> rowKeys) { if (tableName.equals(SWITCH_INTERFACE_CONFIG_TABLE_NAME)) readSwitchInterfaceConfig(); else queueConfigUpdate(); } @Override public void rowsDeleted(String tableName, Set<Object> rowKeys) { if (tableName.equals(SWITCH_INTERFACE_CONFIG_TABLE_NAME)) readSwitchInterfaceConfig(); else queueConfigUpdate(); } // ********************** // ITagListener // ********************** @Override public void tagAdded(Tag tag) { // Noop } @Override public void tagDeleted(Tag tag) { // Noop } /* (non-Javadoc) * @see org.sdnplatform.tagmanager.ITagListener# * tagDevicesReMapped(java.util.Iterator) */ @Override public void tagDevicesReMapped(Iterator<? extends IDevice> devices) { if (logger.isTraceEnabled()) logger.trace("Devices got remapped to tags"); while (devices.hasNext()) { IDevice d = devices.next(); IDeviceGroupMatcher<VNS> deviceGroupMatcher = getDeviceGroupMatcher(d); if (deviceGroupMatcher == null) continue; if (!deviceGroupMatcher.hasTagRules()) { continue; } if (logger.isTraceEnabled()) { logger.trace("This device got remapped - {}", d.getMACAddressString()); } clearCachedDeviceState(d.getDeviceKey()); flowReconcileMgr.updateFlowForDestinationDevice(d, this, FCQueryEvType.DEVICE_PROPERTY_CHANGED); flowReconcileMgr.updateFlowForSourceDevice(d, this, FCQueryEvType.DEVICE_PROPERTY_CHANGED); } } // ************* // IInfoProvider // ************* @Override public Map<String, Object> getInfo(String type) { if (!"summary".equals(type)) return null; Map<String, Object> info = new HashMap<String, Object>(); configLock.readLock().lock(); try { info.put("# VNSes", curConfigState.vnsMap.size()); info.put("# VNS Interfaces", curConfigState.interfaceMap.size()); } finally { configLock.readLock().unlock(); } return info; } // *************** // Private methods // *************** /** * Queue a task to update the configuration state */ protected void queueConfigUpdate() { configUpdateTask.reschedule(UPDATE_TASK_BATCH_DELAY_MS, TimeUnit.MILLISECONDS); } @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="VNS {vns}: Invalid DHCP server IP {ip}, " + "reverting to {mode}", explanation="An invalid IP DHCP server IP is present in the " + "configuration for this VNS", recommendation="Correct the invalid DHCP server IP"), @LogMessageDoc(level="INFO", message="VNS {vns}: DHCP Manager mode {mode}, server {ip}", explanation="This displays the DHCP Manager mode " + "configuration for this VNS") }) private void setDhcpConfig(VNS b, String mode, String ip) { int dhcpIp = 0; try { if (ip != null) dhcpIp = IPv4.toIPv4Address(ip); } catch (IllegalArgumentException e) { mode = "flood-if-unknown"; dhcpIp = 0; ip = null; logger.error("VNS {}: Invalid DHCP server IP {}, reverting to {}", ip, mode); } b.setDhcpIp(dhcpIp); b.setDhcpManagerMode(DHCPMode.fromString(mode)); logger.info("VNS {}: DHCP Manager mode {}, server {}", new Object[] {b.getName(), b.getDhcpManagerMode(), ip == null ? "not specified" : ip}); } @LogMessageDoc(level="INFO", message="VNS {vns}: ARP Manager setting is: {mode}", explanation="This displays the ARP Manager mode " + "configuration for this VNS") private void setArpConfig(VNS b, String setting) { b.setArpManagerMode(ARPMode.fromString(setting)); logger.info("VNS {}: ARP Manager setting is: {}", b.getName(), b.getArpManagerMode()); } @LogMessageDoc(level="INFO", message="VNS {vns}: Broadcast setting is: {mode}", explanation="This displays the general broadcast packet " + "mode for this VNS.") private void setBroadcastConfig(VNS b, String setting) { b.setBroadcastMode(BroadcastMode.fromString(setting)); logger.info("VNS {}: Broadcast setting is: {}", b.getName(), b.getBroadcastMode()); } /** * Read the broadcast interfaces from switch config. * @throws StorageException */ protected void readSwitchInterfaceConfig() throws StorageException { IResultSet swIfaceConfigResultSet; // try multiple times as work-around for BSC-2928; // see Jira BSC-2928 comment 09/Dec/12 1:01 PM int trial = 0; while (true) { trial++; try { swIfaceConfigResultSet = storageSource.executeQuery(SWITCH_INTERFACE_CONFIG_TABLE_NAME, new String[]{SWITCH_DPID, SWITCH_IFACE_NAME, SWITCH_BROADCAST_IFACE_COLUMN_NAME}, null, null); break; } catch (StorageException e) { if (trial > 15) { throw e; } logger.warn("retry " + trial + ": readSwitchInterfaceConfig encountered StorageExcption " + e.getMessage()); try { Thread.sleep((trial < 6) ? 1000 : 2000); } catch (InterruptedException e2) { logger.warn("sleep interrupted"); } } } List<SwitchInterface> lsi = new ArrayList<SwitchInterface>(); while (swIfaceConfigResultSet.next()) { boolean broadcast = swIfaceConfigResultSet.getBoolean(SWITCH_BROADCAST_IFACE_COLUMN_NAME); if (broadcast) { SwitchInterface si = new SwitchInterface(); si.dpid = swIfaceConfigResultSet.getString(SWITCH_DPID); si.ifaceName = swIfaceConfigResultSet.getString(SWITCH_IFACE_NAME); lsi.add(si); } } confBroadcastIfaces = lsi; updateBroadcastSwitchPorts(); } /** * Updates the broadcast switch ports whenever a switch joins, leaves, or the * config for broadcast interfaces is changed. */ protected void updateBroadcastSwitchPorts() { List<SwitchPort> lspt = new ArrayList<SwitchPort>(); for(SwitchInterface si : confBroadcastIfaces) { Long dpid = HexString.toLong(si.dpid); IOFSwitch sw = controllerProvider.getSwitches().get(dpid); if (sw != null) { OFPhysicalPort p = sw.getPort(si.getIfaceName()); if (p!=null && sw.portEnabled(p)) lspt.add(new SwitchPort(dpid, p.getPortNumber())); } } broadcastSwitchPorts = lspt; } private void triggerFlowReconciliation (String vnsName) { /* NetVirt Manager triggers the flow reconciliation by submitting * flow query to the flow cache. The flows are actually reconciled * in virtual routing. */ FCQueryObj fcQueryObj = new FCQueryObj(this, vnsName, null, // null vlan null, // null srcDevice null, // null destDevice getName(), FCQueryEvType.APP_CONFIG_CHANGED, null); betterFlowCacheMgr.submitFlowCacheQuery(fcQueryObj); } /* * netVirtProcessAddressSpaceConfig * * Process address-space configuration in netVirt. */ private void netVirtProcessAddressSpaceConfig (VNS oldVNS, VNS vns, IResultSet netVirtResultSet, Set<VNS> vnsModifiedSet) { String oldAddressSpace; String newAddressSpace; if (oldVNS == null) { oldAddressSpace = "default"; } else { oldAddressSpace = oldVNS.getAddressSpaceName(); if (oldAddressSpace == null || oldAddressSpace.isEmpty()) { oldAddressSpace = "default"; } } newAddressSpace = netVirtResultSet.getString(ADDRESS_SPACE_COLUMN_NAME); if (newAddressSpace == null || newAddressSpace.isEmpty()) { newAddressSpace = "default"; } vns.setAddressSpaceName(newAddressSpace); if (!oldAddressSpace.equals(newAddressSpace)) { // we need to add the old and new VNS to the change set // so we can correctly determine which address-spaces are affected vnsModifiedSet.add(vns); if (oldVNS != null) vnsModifiedSet.add(oldVNS); } if (!newConfigState.deviceGroupMatchers.containsKey(newAddressSpace)) { newConfigState.deviceGroupMatchers.put(newAddressSpace, new DeviceGroupMatcher<VNS>(tagManager, controllerProvider)); } return; } /** * Read the VNS configuration information from storage, merging with the * existing configuration. */ @LogMessageDocs({ @LogMessageDoc(level="ERROR", message="Error loading VNS {vns} from storage, entry ignored. ", explanation="Could not read the entry for this NetVirt from " + "the system database", recommendation="This can happen transiently under certain " + "circumstances without causing problems. If the " + "problem persists, it may indicate" + " corruption in the system database."), @LogMessageDoc(level="ERROR", message="Error loading VNS {vns} rule {rule} from " + "storage, entry ignored.", explanation="Could not read the entry for this VNS rule from " + "the system database", recommendation="This can happen transiently under certain " + "circumstances without causing problems. If the " + "problem persists, it may indicate" + " corruption in the system database.") }) protected void readVNSConfigFromStorage() throws StorageException { IResultSet vnsResultSet; // try multiple times as work-around for BSC-2928 int trial = 0; while (true) { trial++; try { vnsResultSet = storageSource.executeQuery(VNS_TABLE_NAME, null, null, null); break; } catch (StorageException e) { if (trial > 15) { throw e; } logger.warn("retry " + trial + ": readNetVirtConfigFromStorage encountered StorageExcption " + e.getMessage()); try { Thread.sleep((trial < 6) ? 1000 : 2000); } catch (InterruptedException e2) { logger.warn("sleep interrupted"); } } } IResultSet vnsIRuleResultSet = storageSource.executeQuery(VNS_INTERFACE_RULE_TABLE_NAME, new String[]{ID_COLUMN_NAME, VNS_COLUMN_NAME, DESCRIPTION_COLUMN_NAME, VLAN_TAG_ON_EGRESS_COLUMN_NAME, MULTIPLE_ALLOWED_COLUMN_NAME, ACTIVE_COLUMN_NAME, PRIORITY_COLUMN_NAME, MAC_COLUMN_NAME, IP_SUBNET_COLUMN_NAME, SWITCH_COLUMN_NAME, PORTS_COLUMN_NAME, VLANS_COLUMN_NAME, TAGS_COLUMN_NAME}, null, null); // We will maintain a set of NetVirtes that were deleted and a set new NetVirtes // that were created so that we can reconcile flows in a subset of NetVirtes // We add NetVirt to this set if they have been modified in a way // that would affect flow reconciliation. We will often add the // old and new NetVirt to this set so we can identify the all // relevant address-spaces and the highest priority NetVirt that // changed. // For this reason this must be a list and not a set // because old and new NetVirt will be considered equal Set<VNS> deletedSet = Collections.newSetFromMap(new IdentityHashMap<VNS, Boolean>()); Set<VNS> modifiedSet = Collections.newSetFromMap(new IdentityHashMap<VNS, Boolean>()); synchronized(newConfigLock) { newConfigState = new ConfigState(); while (vnsResultSet.next()) { String id = vnsResultSet.getString(ID_COLUMN_NAME); VNS oldvns = curConfigState.vnsMap.get(id); VNS vns = new VNS(id); if (oldvns == null) { // New VNS was created modifiedSet.add(vns); } try { // FIXME: We don't track changes to the ORIGIN column vns.setOrigin(vnsResultSet.getString(ORIGIN_COLUMN_NAME)); vns.setActive(vnsResultSet.getBoolean(ACTIVE_COLUMN_NAME)); if (oldvns != null && oldvns.isActive() != vns.isActive()) { if (oldvns.isActive()) modifiedSet.add(oldvns); else modifiedSet.add(vns); } vns.setPriority(vnsResultSet.getInt(PRIORITY_COLUMN_NAME)); if (oldvns != null && oldvns.getPriority() != vns.getPriority()) { // need to flag both VNS' as modified since we need // later identify the highest priority one to // reconcile modifiedSet.add(oldvns); modifiedSet.add(vns); } vns.setDescription( vnsResultSet.getString(DESCRIPTION_COLUMN_NAME)); netVirtProcessAddressSpaceConfig(oldvns, vns, vnsResultSet, modifiedSet); setArpConfig(vns, vnsResultSet.getString(ARP_CONFIG_MODE_COLUMN_NAME)); setDhcpConfig(vns, vnsResultSet.getString(DHCP_CONFIG_MODE_COLUMN_NAME), vnsResultSet.getString(DHCP_IP_COLUMN_NAME)); setBroadcastConfig(vns, vnsResultSet.getString(BROADCAST_CONFIG_MODE_COLUMN_NAME)); } catch (Exception e) { logger.warn("Error loading VNS " + id + " from storage, entry ignored. " + e); continue; } vns.setMarked(true); newConfigState.vnsMap.put(vns.getName(), vns); if (logger.isTraceEnabled()) { logger.trace("VNS {}: Configuration complete ", vns.getName()); } } // clear out state related to VNS that no longer exist for (VNS oldvns: curConfigState.vnsMap.values()) { if (! newConfigState.vnsMap.containsKey(oldvns.getName())) deletedSet.add(oldvns); } // Read interface rules from result set while (vnsIRuleResultSet.next()) { String id = vnsIRuleResultSet.getString(ID_COLUMN_NAME); String vnsid = vnsIRuleResultSet.getString(VNS_COLUMN_NAME); VNS vns = newConfigState.vnsMap.get(vnsid); MembershipRule<VNS> oldIRule = curConfigState.interfaceRuleMap.get(id); MembershipRule<VNS> irule; if (vns != null) { if (oldIRule == null) { modifiedSet.add(vns); } irule = new MembershipRule<VNS>(id, vns); try { /* For each of the possible VNS Interface rule match * options, we compare the match field with the old * value, and if the new value is differnet then we * add the netVirt to netVirtWithRuleChangeSet */ irule.setDescription(vnsIRuleResultSet.getString(DESCRIPTION_COLUMN_NAME)); irule.setActive(vnsIRuleResultSet.getBoolean(ACTIVE_COLUMN_NAME)); irule.setMultipleAllowed(vnsIRuleResultSet.getBoolean(MULTIPLE_ALLOWED_COLUMN_NAME)); irule.setVlanTagOnEgress(vnsIRuleResultSet.getBoolean(VLAN_TAG_ON_EGRESS_COLUMN_NAME)); irule.setPriority(vnsIRuleResultSet.getInt(PRIORITY_COLUMN_NAME)); irule.setMac(vnsIRuleResultSet.getString(MAC_COLUMN_NAME)); irule.setIpSubnet(vnsIRuleResultSet.getString(IP_SUBNET_COLUMN_NAME)); irule.setSwitchId(vnsIRuleResultSet.getString(SWITCH_COLUMN_NAME)); irule.setPorts(vnsIRuleResultSet.getString(PORTS_COLUMN_NAME)); irule.setVlans(vnsIRuleResultSet.getString(VLANS_COLUMN_NAME)); irule.setTags(vnsIRuleResultSet.getString(TAGS_COLUMN_NAME)); if (oldIRule != null && !oldIRule.matchingFieldsEquals(irule)) { // rules have changed modifiedSet.add(oldIRule.getParentDeviceGroup()); modifiedSet.add(irule.getParentDeviceGroup()); } } catch (Exception e) { logger.warn("Error loading VNS " + vnsid + " rule " + id + " from storage, entry ignored. " + e); continue; } irule.setMarked(true); newConfigState.interfaceRuleMap.put(irule.getName(), irule); createVNSInterfaces(irule); // Setup lookup data structures String addrSpaceName = vns.getAddressSpaceName(); IDeviceGroupMatcher<VNS> deviceGroupMatcher = newConfigState.deviceGroupMatchers.get(addrSpaceName); if (deviceGroupMatcher != null) { // deviceGroupMatcher should never be null deviceGroupMatcher.addRuleIfActive(irule); } if (logger.isTraceEnabled()) { logger.trace("Configured VNS Interface Rule {} ", irule); } } } // Flag NetVirt with deleted rules for (MembershipRule<VNS> oldIRule: curConfigState.interfaceRuleMap.values()) { if (! newConfigState.interfaceRuleMap .containsKey(oldIRule.getName())) { modifiedSet.add(oldIRule.getParentDeviceGroup()); } } // Get VNS that must be sent to flow reconciliation Set<String> vnsFlowQuerySet = getVNSFlowReconciliation(modifiedSet, deletedSet); // Swap config states configLock.writeLock().lock(); try { curConfigState = newConfigState; newConfigState = null; } finally { configLock.writeLock().unlock(); } for (String netVirtName : vnsFlowQuerySet) { triggerFlowReconciliation(netVirtName); } if (!vnsFlowQuerySet.isEmpty()) { // FIXME: temporary work-around to be able to reconcile // flow from VirtualRoutingService triggerFlowReconciliation( IVirtualRoutingService.VRS_FLOWCACHE_NAME); // Notify all netVirtListeners on changed netVirtes for (INetVirtListener listener : netVirtListeners) { listener.netVirtChanged(vnsFlowQuerySet); if (logger.isTraceEnabled()) { logger.trace("Notify listener {} of changed VNSes {}", listener.getClass().getName(), vnsFlowQuerySet); } } } } // end synchronized } protected Set<String> getVNSFlowReconciliation (Set<VNS> vnsModifiedSet, Set<VNS> vnsDeletedSet) { /* Reconcile flows for the VNStes that were deleted and check if any * flow would be moved to a new vns that was created with higher * priority. * <p> * * DELETED VNS * =========== * For the flows in VNSes that were deleted either those flows need to * be deleted or they need to be moved to some other NetVirt if the devices * were member of multiple vns. If the flow need to be moved to some * other NetVirt then the flow-mods in the switches need not be touched buy * the flow-cache should be updated so that these flows are moved to * other application instance name. Here we need to submit flow query * for all the VNSes that were deleted. * <p> * ADDED VNS * ========= * For the new vns that were created we need to check if any flow * from a lower priority NetVirt need to be migrated to a newly created * vns. To accomplish this we need to submit flow query for all the * existing vns that are in lower priority than the highest-priority * vns that was created. * * We will use the logic stated above to create a set of vns for which * flow queries need to be submitted for reconciliation. * * QUICK HACK * ========== * see nonNullOriginSimpleReconcile's comment * */ HashSet<String> vnsFlowQuerySet = new HashSet<String>(); if (vnsDeletedSet.isEmpty() && vnsModifiedSet.isEmpty()) return Collections.emptySet(); /* * TODO: we can do this a lot more efficently: * a) only query for NetVirt' that are in the affected address-spaces * (instead of quering all NetVirt' with a priority lower than max) * b) rely on the NetVirt ordering (which includes NetVirt name to break a * tie) instead of using just the priority. */ /* Find the NetVirt with highest priority in netVirtModifiedSet */ int maxPriority = -Integer.MIN_VALUE; for (VNS netVirtIdx : vnsModifiedSet) { vnsFlowQuerySet.add(netVirtIdx.getName()); if (nonNullOriginSimpleReconcile && netVirtIdx.getOrigin() != null && !netVirtIdx.getOrigin().isEmpty() ) { continue; } if (netVirtIdx.getPriority() > maxPriority) { maxPriority = netVirtIdx.getPriority(); } } /* Get all NetVirtes with priority less than or equal to * highestPriorityNetVirtAddedAndRuleChanged */ for (String vnsNameIdx : newConfigState.vnsMap.keySet() ) { VNS vnsCur = newConfigState.vnsMap.get(vnsNameIdx); if (vnsCur.getPriority() <= maxPriority) { vnsFlowQuerySet.add(vnsNameIdx); } } /* Now add all the NetVirtes that were deleted as we need to reconcile * flows in those NetVirtes */ for (VNS vnsIdx : vnsDeletedSet) { vnsFlowQuerySet.add(vnsIdx.getName()); } /* Now submit flow query to get the flows in each of these NetVirtes */ if (logger.isTraceEnabled()) { logger.trace("Set of NetVirtes to query for flow reconciliation: {}", vnsFlowQuerySet); } // We want to always add default NetVirt to reconcile set given that it // will match everything that was otherwise unmatched vnsFlowQuerySet.add("default|default"); return vnsFlowQuerySet; } /** * Pre-create NetVirt interface based on the rule */ private void createVNSInterfaces(MembershipRule<VNS> vnsIRule) { String ifname = vnsIRule.getFixedInterfaceName(); VNS vns = vnsIRule.getParentDeviceGroup(); VNSInterface iface = newConfigState.interfaceMap.get(vns.getName() + "|" + ifname); if (iface == null) { iface = new VNSInterface(ifname, vns, vnsIRule, null); newConfigState.interfaceMap.put(vns.getName() + "|" + ifname, iface); } /** * Update the switchInterfaceRuleMap to include vnsirule if * it has any switch-specific sub-interface to be created. */ if (vnsIRule.getSwitchId() == null) return; long switchDPID = HexString.toLong(vnsIRule.getSwitchId()); List<MembershipRule<VNS>> memList; memList = newConfigState.switchInterfaceRuleMap.get(switchDPID); if (memList == null) { memList = new ArrayList<MembershipRule<VNS>>(); newConfigState.switchInterfaceRuleMap.put(switchDPID, memList); } memList.add(vnsIRule); /** * If the switch with switchDPID is already connected, then * create the sub-interface rule immediately. */ IOFSwitch sw = controllerProvider.getSwitches().get(switchDPID); if (sw == null) return; createVNSSubInterfaces(newConfigState, sw, vnsIRule); } /** * When a switch connects to the controller, this method will create * NetVirt sub-interfaces for any switch/switch-port specific configurations. * This method is called from addedSwitch() and therefore must operate * on curConfigState * @param switchDPID */ private void createVNSSubInterfacesForSwitch(long switchDPID) { /* * We can perform this operation while only holding the read lock * since we won't be swapping configState pointers. * TODO: verify that this is indeed the case */ configLock.readLock().lock(); try { List<MembershipRule<VNS>> memList; memList = curConfigState.switchInterfaceRuleMap.get(switchDPID); if (memList == null) return; IOFSwitch sw = controllerProvider.getSwitches().get(switchDPID); if (sw == null) return; for(MembershipRule<VNS> irule: memList) createVNSSubInterfaces(curConfigState, sw, irule); } finally { configLock.readLock().unlock(); } } /** * Pre-create NetVirt sub-interfaces based on rule (if applicable) * Only switch-port rules are relevant in the current implementation */ private void createVNSSubInterfaces(ConfigState configState, IOFSwitch sw, MembershipRule<VNS> irule) { String ifname = irule.getFixedInterfaceName(); VNS vns = irule.getParentDeviceGroup(); VNSInterface iface = configState.interfaceMap.get(vns.getName() + "|" + ifname); if (iface == null) { logger.debug("Fixed interface not created for {}", irule); return; } List<String> subifnames = irule.getFixedSubInterfaceNames(sw); if (subifnames == null) return; for (String name : subifnames) { VNSInterface subiface = configState.interfaceMap.get(vns.getName() + "|" + name); if (subiface == null) { subiface = new VNSInterface(name, vns, irule, iface); configState.interfaceMap.put(vns.getName() + "|" + name, subiface); } } } /** * Annotate the message context for a packet in the NetVirt interfaces associated * with the source and destination addresses for the flow. * * @param sw the switch for the packet-in * @param pi the packet-in message * @param cntx * @return @ref */ private Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, ListenerContext cntx) { IFlowCacheService.fcStore.put(cntx, IFlowCacheService.FLOWCACHE_APP_INSTANCE_NAME, "netVirt"); return annotateDeviceVNSInterfaces (cntx, null); } /** * Annotate NetVirt interfaces for src and dst devices * @param cntx * @return */ @LogMessageDoc(level="WARN", message="Source device {device}'s entity class is not " + " a BetterEntityClass", explanation="This message indicates a misconfiguration of the " + "packet processing pipeline.", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG) private Command annotateDeviceVNSInterfaces (ListenerContext cntx, OFMatch match) { IDevice src = IDeviceService.fcStore. get(cntx, IDeviceService.CONTEXT_SRC_DEVICE); IDevice dst = IDeviceService.fcStore. get(cntx, IDeviceService.CONTEXT_DST_DEVICE); if (logger.isTraceEnabled()) { logger.trace("srcDevice: {}, dstDevice: {}", src, dst); } // Retrieve interfaces for source and destination List<VNSInterface> srcIfaces = null; IEntityClass srcEc = null; if (src != null) { srcEc = src.getEntityClass(); if (srcEc instanceof BetterEntityClass) { BetterEntityClass addrSpace = (BetterEntityClass)srcEc; if (addrSpace.getVlan() != null) { rewriteService.setTransportVlan(addrSpace.getVlan(), cntx); } } else { logger.warn("Source device {}'s entity class is not " + " a BetterEntityClass", src); } srcIfaces = getInterfaces(src); if (srcIfaces != null && srcIfaces.size() > 0) { if (logger.isTraceEnabled()) { logger.trace("srcIface: {}", srcIfaces.get(0)); } bcStore.put(cntx, INetVirtManagerService.CONTEXT_SRC_IFACES, srcIfaces); } } List<VNSInterface> dstIfaces = null; if (dst != null) { dstIfaces = getInterfaces(dst); } else { // shortcut out of having to do work before calling registered classifiers // if no classifiers have registered if (srcEc != null && vnsInterfaceClassifiers.getOrderedListeners() != null) { dstIfaces = tryClassifyingUnknownDevice(cntx, match, srcEc); } } if (dstIfaces != null && dstIfaces.size() > 0) { if (logger.isTraceEnabled()) { logger.trace("dstIface: {}", dstIfaces.get(0)); } bcStore.put(cntx, INetVirtManagerService.CONTEXT_DST_IFACES, dstIfaces); } return Command.CONTINUE; } /** * Even without a device, this method will try to get the relevant information * from the packet, in order to classify the unknown device's NetVirtInterfaces * using registered INetVirtIntefaceClassifiers (like SINetVirtInterfaceClassifier) */ private List<VNSInterface> tryClassifyingUnknownDevice(ListenerContext cntx, OFMatch match, IEntityClass srcEc) { Integer ipAddress = null; Short vlan = null; long dstMac = 0; Ethernet eth = IControllerService.bcStore. get(cntx,IControllerService.CONTEXT_PI_PAYLOAD); if (eth != null) { // If packetIn is an unicast IPV4 packet, get destination ipaddress. if (eth.getPayload() instanceof IPv4 && !eth.isBroadcast() && !eth.isMulticast()) { IPv4 ipv4 = (IPv4) eth.getPayload(); ipAddress = ipv4.getDestinationAddress(); } vlan = eth.getVlanID(); dstMac = eth.getDestinationMAC().toLong(); } else if (match != null) { ipAddress = match.getNetworkDestination(); vlan = match.getDataLayerVirtualLan(); dstMac = Ethernet.toLong(match.getDataLayerDestination()); } /** * There are two options on when to query registered NetVirtInterfaceClassifiers: * 1. If the device doesn't match any NetVirtInterface, * Check the registered NetVirtInterfaceClassifiers for device * classification. This is what is required for ServiceInsertion feature and, * hence, the implementation. * 2. Always check with registered NetVirtInterfaceClassifiers and union the results. * * Option 2 is more flexible, but no use case yet. */ return classifyUnknownDevice(srcEc.getName(), dstMac, vlan, ipAddress, null); } /** * Match a device against the interface rules and return the list of interfaces. * Must be called with a config read lock held. * * @param d * @return */ protected List<VNSInterface> matchDevice(IDevice d) throws Exception { IDeviceGroupMatcher<VNS> deviceGroupMatcher = getDeviceGroupMatcher(d); if (deviceGroupMatcher == null) return null; List<MembershipRule<VNS>> matches = deviceGroupMatcher.matchDevice(d); if (matches == null) return null; ArrayList<VNSInterface> deviceInterfaces = new ArrayList<VNSInterface>(); for (MembershipRule<VNS> netVirtIRule: matches) { deviceInterfaces.add(getIfaceFromMatchingRule(netVirtIRule, d)); } return deviceInterfaces; } /** * createDefaultNetVirt * Create default NetVirt under the entity's address-space. * for tenant default */ protected VNS createDefaultNetVirt (IEntityClass entityClass) { /* * Use 'default' by default. */ String netVirtName = "default|default"; String addressSpaceName = "default"; /* * If this device is in non-default address-space, name the netVirt * accordingly. */ if (entityClass != null && !entityClass.getName().isEmpty() && !entityClass.getName().equals("default")) { addressSpaceName = entityClass.getName(); netVirtName = "default|" + addressSpaceName + "-default"; } /* * Create a new NetVirt and set its address-space. */ VNS netVirt = new VNS(netVirtName); netVirt.setActive(true); netVirt.setAddressSpaceName(addressSpaceName); VNS oldNetVirt = curConfigState.vnsMap.putIfAbsent(netVirt.getName(), netVirt); if (oldNetVirt != null) return oldNetVirt; else return netVirt; } /** * Get an interface from an interface name, creating it if needed * @param iname the components of the interface name * @param netVirt the netVirt for the interface (may be null, in which case * use the default NetVirt) * @param rule the NetVirt rule for the interface (may be null) * @return */ @Override public VNSInterface getIfaceFromName(String[] iname, VNS netVirt, IDevice device, MembershipRule<VNS> rule) { String[] names = new String[iname.length]; StringBuffer sb = new StringBuffer(); for (int i = 0; i < iname.length; i++) { if (i > 0) sb.append("/"); sb.append(iname[i]); names[i] = sb.toString(); } // use default NetVirt, creating if needed, if NetVirt is null if (netVirt == null) { IEntityClass entityClass = null; if (device != null) { entityClass = device.getEntityClass(); } netVirt = createDefaultNetVirt(entityClass); } VNSInterface iface = curConfigState.interfaceMap.get(netVirt.getName() + "|" + names[names.length-1]); if (iface == null) { // Allocate new interface boolean created = false; for (String name : names) { VNSInterface last = iface; iface = curConfigState.interfaceMap.get(netVirt.getName() + "|" + name); if (iface == null) { iface = new VNSInterface(name, netVirt, rule, last); curConfigState.interfaceMap.put(netVirt.getName() + "|" + name, iface); if (created) { // catching missed pre-creation logger.debug( "Parent interface not pre-created {}", last); } created = true; } } } return iface; } /** * Get the NetVirt interface for a matching rule and its device * @param rule the rule * @param d the device * @return the interface */ protected VNSInterface getIfaceFromMatchingRule(MembershipRule<VNS> rule, IDevice d) { String[] iname = rule.getInterfaceNameForDevice(d, controllerProvider); return getIfaceFromName(iname, rule.getParentDeviceGroup(), d, rule); } @Override public void clearCachedDeviceState(long deviceKey) { if (logger.isDebugEnabled()) { logger.debug("Clearing cached NetVirt interface mapping for {}", deviceKey); } configLock.writeLock().lock(); try { List<VNSInterface> ifaces = curConfigState.deviceInterfaceMap.get(deviceKey); if (ifaces == null) return; for (VNSInterface iface : ifaces) { iface.getParentVNS().removeDevice(deviceKey); curConfigState.interfaceMap.remove(iface.getParentVNS().getName() + "|" + iface.getName()); } curConfigState.deviceInterfaceMap.remove(deviceKey); } finally { configLock.writeLock().unlock(); } } // *************** // IOFSwitchListener // *************** @Override public void addedSwitch(IOFSwitch sw) { configLock.writeLock().lock(); try { createVNSSubInterfacesForSwitch(sw.getId()); } finally { configLock.writeLock().unlock(); } updateBroadcastSwitchPorts(); } @Override public void removedSwitch(IOFSwitch sw) { updateBroadcastSwitchPorts(); } @Override public void switchPortChanged(Long switchId) { // no-op } @Override public void controllerNodeIPsChanged( Map<String, String> curControllerNodeIPs, Map<String, String> addedControllerNodeIPs, Map<String, String> removedControllerNodeIPs) { // ignore } // *************** // IHARoleListener // *************** @Override public void roleChanged(Role oldRole, Role newRole) { switch(newRole) { case MASTER: if (oldRole == Role.SLAVE) { reloadConfigState(); } break; case SLAVE: logger.debug("Clearing config state due to HA " + "role change to SLAVE"); clearConfigState(); clearCachedState(); break; default: break; } } /** * Clears all the internal config state. */ protected void clearConfigState() { configLock.writeLock().lock(); try { curConfigState.clear(); confBroadcastIfaces.clear(); broadcastSwitchPorts.clear(); } finally { configLock.writeLock().unlock(); } } protected void clearCachedState() { flowQueryRespHandlerCallCount = 0; lastFCQueryResp = null; } /** * Reloads the internal config state. */ protected void reloadConfigState() { readVNSConfigFromStorage(); readSwitchInterfaceConfig(); } }
mandeepdhami/netvirt-ctrl
sdnplatform/src/main/java/org/sdnplatform/netvirt/manager/internal/NetVirtManagerImpl.java
Java
epl-1.0
73,762
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.api.elements.structures; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.core.PropertyStructure; import org.eclipse.birt.report.model.util.ModelUtil; /** * Base class for highlight and map rules in the style. Choices for the operand * are defined in <code>DesignChoiceConstants</code>. * * @see DesignChoiceConstants */ public abstract class StyleRule extends PropertyStructure { /** * Name of the comparison operator member. */ public static final String OPERATOR_MEMBER = "operator"; //$NON-NLS-1$ /** * Name of the property that gives the expression for the first operator * operand. */ public static final String VALUE1_MEMBER = "value1"; //$NON-NLS-1$ /** * Name of the property that gives the expression for the second operator * operand. */ public static final String VALUE2_MEMBER = "value2"; //$NON-NLS-1$ /** * The expression for this rule. */ public static final String TEST_EXPR_MEMBER = "testExpr"; //$NON-NLS-1$ /** * Status that determines whether this structure is used in design time or * not */ public static final String IS_DESIGN_TIME_MEMBER = "isDesignTime"; //$NON-NLS-1$ /** * The comparison operator. Default value is <code>MAP_OPERATOR_EQ</code> */ protected String operator = null; /** * Expression for the first operand. */ protected List value1 = null; /** * Expression for the second operand. */ protected Expression value2 = null; /** * the test expression for this highlight rule. */ protected Expression testExpression = null; /** * */ protected Boolean isDesignTime = null; /** * Default constructor. */ public StyleRule( ) { } /** * Constructs the style rule with an operator and its operands. * * @param op * the choice name for the operand * @param v1 * expression for the first operand * @param v2 * expression for the second operand * @param testExpr * the expression to check */ public StyleRule( String op, String v1, String v2, String testExpr ) { operator = op; value1 = new ArrayList( ); value1.add( new Expression( v1, null ) ); value2 = new Expression( v2, null ); testExpression = new Expression( testExpr, null ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.core.PropertyStructure#getIntrinsicProperty * (java.lang.String) */ protected Object getIntrinsicProperty( String propName ) { if ( OPERATOR_MEMBER.equals( propName ) ) return operator; else if ( VALUE1_MEMBER.equals( propName ) ) return value1; else if ( VALUE2_MEMBER.equals( propName ) ) return value2; else if ( TEST_EXPR_MEMBER.equals( propName ) ) return testExpression; else if ( IS_DESIGN_TIME_MEMBER.equals( propName ) ) return isDesignTime; return super.getIntrinsicProperty( propName ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.core.PropertyStructure#setIntrinsicProperty * (java.lang.String, java.lang.Object) */ protected void setIntrinsicProperty( String propName, Object value ) { if ( OPERATOR_MEMBER.equals( propName ) ) operator = (String) value; else if ( VALUE1_MEMBER.equals( propName ) ) { if ( value == null ) { value1 = null; return; } if ( value instanceof List ) { value1 = (List<String>) value; } else { value1 = new ArrayList( ); value1.add( value ); } } else if ( VALUE2_MEMBER.equals( propName ) ) value2 = (Expression) value; else if ( TEST_EXPR_MEMBER.equals( propName ) ) testExpression = (Expression) value; else if ( IS_DESIGN_TIME_MEMBER.equals( propName ) ) isDesignTime = (Boolean) value; else super.setIntrinsicProperty( propName, value ); } /** * Returns the operator. The possible values are defined in * {@link org.eclipse.birt.report.model.api.elements.DesignChoiceConstants}, * and they are: * <ul> * <li>MAP_OPERATOR_EQ * <li>MAP_OPERATOR_NE * <li>MAP_OPERATOR_LT * <li>MAP_OPERATOR_LE * <li>MAP_OPERATOR_GE * <li>MAP_OPERATOR_GT * <li>MAP_OPERATOR_BETWEEN * <li>MAP_OPERATOR_NOT_BETWEEN * <li>MAP_OPERATOR_NULL * <li>MAP_OPERATOR_NOT_NULL * <li>MAP_OPERATOR_TRUE * <li>MAP_OPERATOR_FALSE * <li>MAP_OPERATOR_LIKE * <li>MAP_OPERATOR_ANY * </ul> * * @return the operator */ public String getOperator( ) { return (String) getProperty( null, OPERATOR_MEMBER ); } /** * Sets the operator. The allowed values are defined in * {@link org.eclipse.birt.report.model.api.elements.DesignChoiceConstants}, * and they are: * <ul> * <li>MAP_OPERATOR_EQ * <li>MAP_OPERATOR_NE * <li>MAP_OPERATOR_LT * <li>MAP_OPERATOR_LE * <li>MAP_OPERATOR_GE * <li>MAP_OPERATOR_GT * <li>MAP_OPERATOR_BETWEEN * <li>MAP_OPERATOR_NOT_BETWEEN * <li>MAP_OPERATOR_NULL * <li>MAP_OPERATOR_NOT_NULL * <li>MAP_OPERATOR_TRUE * <li>MAP_OPERATOR_FALSE * <li>MAP_OPERATOR_LIKE * <li>MAP_OPERATOR_ANY * </ul> * * @param operator * the operator to set */ public void setOperator( String operator ) { setProperty( OPERATOR_MEMBER, operator ); } /** * Returns the expression for the first operand. * * @return the first operand expression */ public String getValue1( ) { List valueList = getValue1List( ); if ( valueList == null || valueList.isEmpty( ) ) return null; return (String) valueList.get( 0 ); } /** * Gets the value1 expression list. For most map operator, there is only one * expression in the returned list. However, map operator 'in' may contain * more than one expression. * * @return the value1 expression list. * * @deprecated {@link #getValue1ExpressionList()} */ public List getValue1List( ) { List<Expression> valueList = (List<Expression>) getProperty( null, VALUE1_MEMBER ); if ( valueList == null || valueList.isEmpty( ) ) return Collections.EMPTY_LIST; return Collections.unmodifiableList( ModelUtil .getExpressionCompatibleList( valueList ) ); } /** * Gets the value1 expression list. For most map operator, there is only one * expression in the returned list. However, map operator 'in' may contain * more than one expression. * * @return the value1 expression list. Each item is <code>Expression</code> * object. */ public List getValue1ExpressionList( ) { List<Expression> valueList = (List<Expression>) getProperty( null, VALUE1_MEMBER ); if ( valueList == null || valueList.isEmpty( ) ) return Collections.EMPTY_LIST; return Collections.unmodifiableList( valueList ); } /** * Set expression for the first operand. * * @param value * the first operand expression. */ public void setValue1( String value ) { if ( value == null ) { setProperty( VALUE1_MEMBER, null ); return; } List valueList = new ArrayList( ); valueList.add( value ); setProperty( VALUE1_MEMBER, valueList ); } /** * Sets the value 1 expression. * * @param value1List * the value 1 expression list to set */ public void setValue1( List value1List ) { setProperty( VALUE1_MEMBER, value1List ); } /** * Returns the expression for the second operand. * * @return the second operand expression */ public String getValue2( ) { return getStringProperty( null, VALUE2_MEMBER ); } /** * Set expression for the second operand. * * @param value * the second operand expression. */ public void setValue2( String value ) { setProperty( VALUE2_MEMBER, value ); } /** * sets the test expression for the rule. * * @param expression * the expression value * */ public void setTestExpression( String expression ) { setProperty( TEST_EXPR_MEMBER, expression ); } /** * gets the test expression value of this rule. * * @return the expression */ public String getTestExpression( ) { return testExpression == null ? null : testExpression .getStringExpression( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.model.core.Structure#isDesignTime() */ public boolean isDesignTime( ) { Boolean isDesignTime = (Boolean) getProperty( null, IS_DESIGN_TIME_MEMBER ); if ( isDesignTime == null ) return true; return isDesignTime.booleanValue( ); } /** * Sets the design time status for this structure. * * @param isDesignTime */ public void setDesignTime( boolean isDesignTime ) { setProperty( IS_DESIGN_TIME_MEMBER, Boolean.valueOf( isDesignTime ) ); } }
sguan-actuate/birt
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/api/elements/structures/StyleRule.java
Java
epl-1.0
9,305
/******************************************************************************* * Copyright (c) 2017 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.archive.reader.channelarchiver.file; import java.io.File; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import org.csstudio.apputil.text.RegExHelper; import org.csstudio.archive.reader.ArchiveInfo; import org.csstudio.archive.reader.ArchiveReader; import org.csstudio.archive.reader.UnknownChannelException; import org.csstudio.archive.reader.ValueIterator; /** ArchiveReader for Channel Archiver index & data files. * @author Amanda Carpenter */ public class ArchiveFileReader implements ArchiveReader { public static final Logger logger = Logger.getLogger(ArchiveFileReader.class.getName()); private final String index_name; private final ArchiveFileIndexReader indexReader; /** Construct an ArchiveFileReader. * @param index Path to Channel Archiver index file * @throws IOException */ public ArchiveFileReader(final String index) throws IOException { index_name = index; indexReader = new ArchiveFileIndexReader(new File(index)); } @Override public String getServerName() { return "Channel Archiver"; } @Override public String getURL() { return ArchiveFileReaderFactory.PREFIX + index_name; } @Override public String getDescription() { return "Data File"; } @Override public int getVersion() { return 0; } @Override public ArchiveInfo[] getArchiveInfos() { return new ArchiveInfo[] { new ArchiveInfo(getServerName(), getDescription(), 0)}; } @Override public String[] getNamesByPattern(final int key, final String glob_pattern) throws Exception { return getNamesByRegExp(key, RegExHelper.fullRegexFromGlob(glob_pattern)); } @Override public String[] getNamesByRegExp(final int key, final String reg_exp) throws Exception { final Pattern pattern = Pattern.compile(reg_exp, Pattern.CASE_INSENSITIVE); final List<String> result = new ArrayList<>(); for (String name : indexReader.getChannelNames()) if (pattern.matcher(name).matches()) result.add(name); return result.toArray(new String [result.size()]); } @Override public ValueIterator getRawValues(int key, String name, Instant start, Instant end) throws UnknownChannelException, Exception { final List<DataFileEntry> entries = indexReader.getEntries(name, start, end); return new ArchiveFileSampleReader(start, end, entries); } @Override public ValueIterator getOptimizedValues(int key, String name, Instant start, Instant end, int count) throws UnknownChannelException, Exception { // Not implemented, falling back to raw values return getRawValues(key, name, start, end); } @Override public void cancel() { //no-op } @Override public void close() { try { indexReader.close(); } catch (Exception ex) { logger.log(Level.WARNING, "Cannot close index", ex); } } }
ControlSystemStudio/cs-studio
applications/archive/archive-plugins/org.csstudio.archive.reader.channelarchiver/src/org/csstudio/archive/reader/channelarchiver/file/ArchiveFileReader.java
Java
epl-1.0
3,756
<div class="tableWrapper"> <div class="table dataTable reqHistory"> <div class="thdiv"> <div class="tddiv rh-col1"></div> <div class="tddiv rh-col2">{{ 'YANGUI_HISTORY_METHOD' | translate }}</div> <div class="tddiv rh-col3">{{ 'YANGUI_HISTORY_PATH' | translate }}</div> <div class="tddiv rh-col4">{{ 'YANGUI_HISTORY_STATUS' | translate }}</div> <div class="tddiv rh-col5"></div> <div class="tddiv rh-col6"></div> <div class="tddiv actions rh-col7">{{ 'YANGUI_HISTORY_ACTION' | translate }}</div> </div> <div class="scroll"> <div ng-repeat="req in requestList.list track by $index" class="trdiv"> <div ng-controller="reqInHistoryCtrl" ng-init="init(requestList)"> <div class="tddiv rh-col1"><button class="yangButton iconDanger" tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ 'YANGUI_API_NOT_AVAILABLE' | translate }}" ng-hide="req.availability"></button></div> <div class="tddiv rh-col2"><span>{{ req.method }}</span></div> <div class="tddiv rh-col3"><span>{{ req.path }}</span></div> <div class="tddiv rh-col4"><span>{{ req.status }}</span></div> <div class="tddiv rh-col5"> <div tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ req.sentData ? '' : 'YANGUI_HISTORY_NO_SEND_DATA_TT' | translate }}"> <button class="btn btn-primary ng-scope btn-slim {{!req.sentData ? 'disabled' : ''}}" ng-click='showShistoryData()'> {{ 'YANGUI_HISTORY_SEND_DATA' | translate }} </button> </div> </div> <div class="tddiv rh-col6"> <div tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ req.receivedData ? '' : 'YANGUI_HISTORY_NO_REC_DATA_TT' | translate }}"> <button class="btn btn-primary ng-scope btn-slim {{!req.receivedData ? 'disabled' : ''}}" ng-click='showRhistoryData()'> {{ 'YANGUI_HISTORY_REC_DATA' | translate }} </button> </div> </div> <div class="tddiv rh-col7"> <div class="requestActions"> <div class="inlineBlock" tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ req.availability ? 'YANGUI_RUN' : 'YANGUI_API_NA_ERROR_TT' | translate }}"> <button ng-disabled="!req.availability" class="yangButton iconNext {{ req.availability ? '' : 'disabled' }}" ng-click="executeRequest()"></button> </div> <div class="inlineBlock historyRequestBox" tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ 'YANGUI_ADD_TO_COLLECTION' | translate }}"> <div class="yangButton iconPlus inlineBlock" ng-click='showCollBox(req)'></div> </div> <div class="inlineBlock" tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ req.availability ? (req.receivedData || req.sentData) ? 'YANGUI_FILL_DATA_TT' : 'YANGUI_REC_SENT_DATA_ERROR_TT' : 'YANGUI_API_NA_ERROR_TT' | translate }}"> <button class="yangButton iconFillData {{ req.availability && (req.receivedData || req.sentData) ? '' : 'disabled' }}" ng-disabled="!req.availability || !(req.receivedData || req.sentData)" ng-click="fillRequest()"></button> </div> <button class="yangButton iconClose" ng-click="deleteRequestItem(req, 'requestList')" tooltip-placement="{{ $index ? 'top' : 'bottom' }}" tooltip="{{ 'YANGUI_DELETE' | translate }}"></button> </div> </div> <div ng-show="showData" class="trdiv pre-div" ng-include src="currentPath + 'parts/history-dataview-part.tpl.html'"></div> </div> </div> </div> </div> <button class="btn btn-primary ng-scope btn-slim" ng-click='clearHistoryData("requestList")'> {{ 'YANGUI_CLEAR_HISTORY' | translate }} </button> </div>
stshtina/ODL
modules/yangui-resources/src/main/resources/yangui/views/parts/history-tab.tpl.html
HTML
epl-1.0
4,530
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.metadata; import java.util.regex.Pattern; import org.eclipse.birt.report.model.api.elements.structures.HideRule; import org.eclipse.birt.report.model.api.metadata.IPropertyDefn; import org.eclipse.birt.report.model.api.metadata.IStructureDefn; import org.eclipse.birt.report.model.api.metadata.PropertyValueException; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.birt.report.model.core.DesignElement; import org.eclipse.birt.report.model.core.Module; import org.eclipse.birt.report.model.elements.interfaces.IStyleModel; import org.eclipse.birt.report.model.util.StyleUtil; /** * String property type. * <p> * All string values are valid. However, if the caller provides a type other * than a string, the value is converted to a string using default conversion * rules. * */ public class StringPropertyType extends TextualPropertyType { /** * Display name key. */ private static final String DISPLAY_NAME_KEY = "Property.string"; //$NON-NLS-1$ private static final String HIDE_RULE_FORMAT_PATTERN = "[$_a-zA-Z][\\.$_a-zA-Z0-9]*"; //$NON-NLS-1$ private static final Pattern hideRuleFormatPattern = Pattern.compile( HIDE_RULE_FORMAT_PATTERN, Pattern.CASE_INSENSITIVE ); /** * Constructor. */ public StringPropertyType( ) { super( DISPLAY_NAME_KEY ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.metadata.PropertyType#validateValue(org * .eclipse.birt.report.model.core.Module, * org.eclipse.birt.report.model.core.DesignElement, * org.eclipse.birt.report.model.metadata.PropertyDefn, java.lang.Object) */ public Object validateValue( Module module, DesignElement element, PropertyDefn defn, Object value ) throws PropertyValueException { if ( value == null ) return null; String stringValue = trimString( value.toString( ), defn .getTrimOption( ) ); if ( IStyleModel.FONT_FAMILY_PROP.equals( defn.getName( ) ) ) { return StyleUtil.handleFontFamily( defn, stringValue ); } if ( HideRule.FORMAT_MEMBER.equals( defn.getName( ) ) ) { IStructureDefn hideRuleStruct = MetaDataDictionary.getInstance( ) .getStructure( HideRule.STRUCTURE_NAME ); IPropertyDefn formatProperty = null; if ( hideRuleStruct != null ) formatProperty = hideRuleStruct .getMember( HideRule.FORMAT_MEMBER ); if ( defn == formatProperty ) { return validateHideRuleFormat( stringValue ); } } return stringValue; } /** * * @param value * @return * @throws PropertyValueException */ private Object validateHideRuleFormat( String value ) throws PropertyValueException { if ( StringUtil.isBlank( value ) ) { return value; } if ( !hideRuleFormatPattern.matcher( value ).matches( ) ) throw new PropertyValueException( value, PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE, getTypeCode( ) ); return value; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.design.metadata.PropertyType#getTypeCode() */ public int getTypeCode( ) { return STRING_TYPE; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.model.design.metadata.PropertyType#getXmlName() */ public String getName( ) { return STRING_TYPE_NAME; } /** * Converts the string property value to a double, this method will always * return 0. */ public double toDouble( Module module, Object value ) { // Strings cannot be converted to doubles because the conversion // rules are locale-dependent. return 0; } /** * Converts the string property value to an integer. * * @return integer value of the string representation, return <code>0</code> * if <code>value</code> is null. */ public int toInteger( Module module, Object value ) { if ( value == null ) return 0; try { return Integer.decode( (String) value ).intValue( ); } catch ( NumberFormatException e ) { return 0; } } }
sguan-actuate/birt
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/metadata/StringPropertyType.java
Java
epl-1.0
4,515
/******************************************************************************* * Copyright (c) 2006 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.tests.script.component; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.script.api.attribute.ILabel; import org.eclipse.birt.chart.script.api.scale.ICategoryScale; import org.eclipse.birt.chart.script.api.scale.ILinearScale; import org.eclipse.birt.chart.script.api.scale.ITimeScale; import org.eclipse.birt.chart.tests.script.BaseChartTestCase; /** * */ public class AxisTest extends BaseChartTestCase { public void testVisible( ) { assertTrue( getChartWithAxes( ).getCategoryAxis( ).isVisible( ) ); assertTrue( getChartWithAxes( ).getValueAxes( )[0].isVisible( ) ); assertFalse( getChartWithAxes( ).getValueAxes( )[2].isVisible( ) ); getChartWithAxes( ).getValueAxes( )[2].setVisible( true ); assertTrue( getChartWithAxes( ).getValueAxes( )[2].isVisible( ) ); } public void testTitle( ) { assertEquals( getChartWithAxes( ).getCategoryAxis( ) .getTitle( ) .getCaption( ) .getValue( ), "X-Axis Title" ); assertEquals( getChartWithAxes( ).getValueAxes( )[0].getTitle( ) .getCaption( ) .getValue( ), "Y-Axis Title" ); assertFalse( getChartWithAxes( ).getValueAxes( )[1].getTitle( ) .isVisible( ) ); ILabel title = getChartWithAxes( ).getValueAxes( )[2].getTitle( ); title.setVisible( true ); String text = "Y Axis 3"; title.getCaption( ).setValue( text ); assertTrue( title.isVisible( ) ); assertEquals( title.getCaption( ).getValue( ), text ); } public void testGetScale( ) { assertTrue( getChartWithAxes( ).getCategoryAxis( ).getScale( ) instanceof ICategoryScale ); assertTrue( getChartWithAxes( ).getValueAxes( )[0].getScale( ) instanceof ITimeScale ); assertTrue( getChartWithAxes( ).getValueAxes( )[1].getScale( ) instanceof ILinearScale ); } public void testGetMarkerLines( ) { assertEquals( getChartWithAxes( ).getCategoryAxis( ).getMarkerLines( ).length, 0 ); assertEquals( getChartWithAxes( ).getValueAxes( )[0].getMarkerLines( ).length, 0 ); assertEquals( getChartWithAxes( ).getValueAxes( )[1].getMarkerLines( ).length, 1 ); assertEquals( getChartWithAxes( ).getValueAxes( )[2].getMarkerLines( ).length, 0 ); } public void testGetMarkerRanges( ) { assertEquals( getChartWithAxes( ).getCategoryAxis( ).getMarkerRanges( ).length, 1 ); assertEquals( getChartWithAxes( ).getValueAxes( )[0].getMarkerRanges( ).length, 0 ); assertEquals( getChartWithAxes( ).getValueAxes( )[1].getMarkerRanges( ).length, 0 ); assertEquals( getChartWithAxes( ).getValueAxes( )[2].getMarkerRanges( ).length, 0 ); } public void testType( ) { assertEquals( getChartWithAxes( ).getCategoryAxis( ).getType( ), AxisType.DATE_TIME_LITERAL.getName( ) ); assertEquals( getChartWithAxes( ).getValueAxes( )[0].getType( ), AxisType.DATE_TIME_LITERAL.getName( ) ); assertEquals( getChartWithAxes( ).getValueAxes( )[1].getType( ), AxisType.LINEAR_LITERAL.getName( ) ); assertEquals( getChartWithAxes( ).getValueAxes( )[2].getType( ), AxisType.LINEAR_LITERAL.getName( ) ); getChartWithAxes( ).getCategoryAxis( ) .setType( AxisType.TEXT_LITERAL.getName( ) ); assertEquals( "Test setting axis type", getChartWithAxes( ).getCategoryAxis( ).getType( ), AxisType.TEXT_LITERAL.getName( ) ); getChartWithAxes( ).getCategoryAxis( ).setType( "" ); assertEquals( "Test invalid axis type", getChartWithAxes( ).getCategoryAxis( ).getType( ), AxisType.LINEAR_LITERAL.getName( ) ); } }
sguan-actuate/birt
chart/org.eclipse.birt.chart.tests/src/org/eclipse/birt/chart/tests/script/component/AxisTest.java
Java
epl-1.0
4,036
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="pt-br" xml:lang="pt-br"> <!-- 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. --> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta name="copyright" content="(C) Copyright 2005" /> <meta name="DC.rights.owner" content="(C) Copyright 2005" /> <meta content="public" name="security" /> <meta content="index,follow" name="Robots" /> <meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <meta content="concept" name="DC.Type" /> <meta name="DC.Title" content="Sintaxe SQL adicional" /> <meta scheme="URI" name="DC.Relation" content="rrefjdbc34565.html" /> <meta scheme="URI" name="DC.Relation" content="rrefjdbc27433.html" /> <meta scheme="URI" name="DC.Relation" content="rrefjdbc37352.html" /> <meta scheme="URI" name="DC.Relation" content="rrefjdbc10889.html" /> <meta content="XHTML" name="DC.Format" /> <meta content="crefjavgcasyn" name="DC.Identifier" /> <meta content="pt-br" name="DC.Language" /> <link href="commonltr.css" type="text/css" rel="stylesheet" /> <title>Sintaxe SQL adicional</title> </head> <body id="crefjavgcasyn"><a name="crefjavgcasyn"><!-- --></a> <h1 class="topictitle1">Sintaxe SQL adicional</h1> <div> <div class="p">O <span>Derby</span> também suporta a seguinte sintaxe do padrão SQL para obter uma referência à conexão corrente em um procedimento ou método JDBC do lado do servidor: <pre><strong>jdbc:default:connection</strong></pre> </div> </div> <div> <div class="familylinks"> <div class="parentlink"><strong>Tópico pai:</strong> <a href="rrefjdbc34565.html" title="">java.sql.DriverManager.getConnection</a></div> </div> <div class="relref"><strong>Referências relacionadas</strong><br /> <div><a href="rrefjdbc27433.html" title="">Sintaxe da URL de conexão com banco de dados Derby</a></div> <div><a href="rrefjdbc37352.html" title="">Sintaxe da URL de conexão com banco de dados para aplicativos com bancos de dados incorporados</a></div> <div><a href="rrefjdbc10889.html" title="">Atributos da URL de conexão com o banco de dados Derby</a></div> </div> </div> </body> </html>
acshea/edgware
bundle.apache.derby/db-derby-10.8.3.0-bin/docs/html/pt_BR/ref/crefjavgcasyn.html
HTML
epl-1.0
3,229
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-us" xml:lang="en-us"> <!-- 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. --> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta name="copyright" content="(C) Copyright 2005" /> <meta name="DC.rights.owner" content="(C) Copyright 2005" /> <meta content="public" name="security" /> <meta content="index,follow" name="Robots" /> <meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <meta content="concept" name="DC.Type" /> <meta name="DC.Title" content="Creating, dropping, and backing up databases" /> <meta name="abstract" content="You create new databases and access existing ones by specifying attributes to the Derby connection URL." /> <meta name="description" content="You create new databases and access existing ones by specifying attributes to the Derby connection URL." /> <meta content="Databases, dropping, Dropping databases, Backing up databases, backing up" name="DC.subject" /> <meta content="Databases, dropping, Dropping databases, Backing up databases, backing up" name="keywords" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp845973.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp18166.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp84026.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp25820.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp846110.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp30653.html" /> <meta scheme="URI" name="DC.Relation" content="rdevdvlp22102.html" /> <meta scheme="URI" name="DC.Relation" content="cdevadvjdbc41138.html" /> <meta scheme="URI" name="DC.Relation" content="cdevcsecuree.html" /> <meta scheme="URI" name="DC.Relation" content="cdevdvlp21955.html" /> <meta content="XHTML" name="DC.Format" /> <meta content="cdevdvlp42173" name="DC.Identifier" /> <meta content="en-us" name="DC.Language" /> <link href="commonltr.css" type="text/css" rel="stylesheet" /> <title>Creating, dropping, and backing up databases</title> </head> <body id="cdevdvlp42173"><a name="cdevdvlp42173"><!-- --></a> <h1 class="topictitle1">Creating, dropping, and backing up databases</h1> <div><p>You create new databases and access existing ones by specifying attributes to the <span>Derby</span> connection URL.</p> <p>If you use an in-memory database, you can use a connection URL attribute to drop it. For a file system database, however, there is no drop attribute. To drop a database on the file system, delete the database directory with operating system commands. The database must not be booted when you remove a database. You can get a list of booted databases with <em>getPropertyInfo</em>.</p> <p>To back up a database, you can use the online backup utility. For information on this utility, see the <cite><span><em>Derby Server and Administration Guide</em></span></cite>.</p> <p>You can also use <em>roll-forward recovery</em> to recover a damaged database. <span>Derby</span> accomplishes roll-forward recovery by using a full backup copy of the database, archived logs, and active logs from the most recent time before a failure. For more information on roll-forward recovery see the <cite><span><em>Derby Server and Administration Guide</em></span></cite>.</p> </div> <div> <div class="familylinks"> <div class="parentlink"><strong>Parent topic:</strong> <a href="cdevdvlp21955.html" title="A Derby database contains dictionary objects such as tables, columns, indexes, and jar files. A Derby database can also store its own configuration information.">A Derby database</a></div> </div> <div class="relconcepts"><strong>Related concepts</strong><br /> <div><a href="cdevdvlp845973.html" title="An application can shut down a single database within a Derby system and leave the rest of the system running.">Single database shutdown</a></div> <div><a href="cdevdvlp18166.html" title="A Derby database (unless it is an in-memory database) provides persistent storage and recovery. Derby ensures that all committed transactions are durable, even if the system fails, through the use of a database transaction log.">Storage and recovery</a></div> <div><a href="cdevdvlp84026.html" title="You can put a database's log on a separate device when you create it.">Log on separate device</a></div> <div><a href="cdevdvlp25820.html" title="Derby tables and indexes, known as conglomerates, consist of two or more pages.">Database pages</a></div> <div><a href="cdevdvlp846110.html" title="You can set many Derby properties as database-level properties. When set in this way, they are stored in the database and &quot;travel&quot; with the database unless overridden by a system property.">Database-wide properties</a></div> <div><a href="cdevdvlp30653.html" title="Derby databases have a few limitations.">Derby database limitations</a></div> <div><a href="cdevadvjdbc41138.html" title="JDBC's java.sql.Driver.getPropertyInfo method allows a generic GUI tool to determine the properties for which it should prompt a user in order to get enough information to connect to a database. Depending on the values the user has supplied so far, additional values might become necessary. It might be necessary to iterate though several calls to getPropertyInfo.">Offering connection choices to the user</a></div> <div><a href="cdevcsecuree.html" title="Derby can be deployed in a number of ways and in a number of different environments. The security needs of the Derby system are also diverse.">Derby and security</a></div> </div> <div class="relref"><strong>Related reference</strong><br /> <div><a href="rdevdvlp22102.html" title="The examples in this section use the syntax of the connection URL for use in an embedded environment.">Database connection examples</a></div> </div> </div> </body> </html>
acshea/edgware
bundle.apache.derby/db-derby-10.8.3.0-bin/docs/html/devguide/cdevdvlp42173.html
HTML
epl-1.0
6,966
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.layout; public interface IBlockStackingLayoutManager extends IStackingLayoutManager { }
sguan-actuate/birt
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/IBlockStackingLayoutManager.java
Java
epl-1.0
642
/** * Copyright (c) 2010-2017 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.homematic.internal.communicator.parser; import java.io.IOException; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.openhab.binding.homematic.internal.communicator.client.UnknownParameterSetException; import org.openhab.binding.homematic.internal.communicator.client.UnknownRpcFailureException; import org.openhab.binding.homematic.internal.communicator.message.RpcRequest; /** * Parses the response from a RPC call, throws exception if fault response. * * @author Gerhard Riegler - Initial contribution */ public class RpcResponseParser extends CommonRpcParser<Object[], Object[]> { private RpcRequest response; public RpcResponseParser(RpcRequest request) { this.response = request; } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Object[] parse(Object[] message) throws IOException { if (message != null && message.length > 0) { Object responseData = message[0]; if (responseData instanceof Map) { Map<String, Object> map = (Map<String, Object>) responseData; if (map.containsKey("faultCode")) { Number faultCode = toNumber(map.get("faultCode")); String faultString = toString(map.get("faultString")); String faultMessage = String.format("%s %s (sending %s)", faultCode, faultString, response); if (faultCode.intValue() == -1 && StringUtils.equals("Failure", faultString)) { throw new UnknownRpcFailureException(faultMessage); } else if (faultCode.intValue() == -3 && StringUtils.equals("Unknown paramset", faultString)) { throw new UnknownParameterSetException(faultMessage); } throw new IOException(faultMessage); } } return message; } throw new IOException("Unknown Result: " + message); } }
peuter/openhab2
addons/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/RpcResponseParser.java
Java
epl-1.0
2,368
package p; class A{ A(){ this(5); } A(int u){ super(); } void f(){ int i= 0; } }
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test16_in.java
Java
epl-1.0
92
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-us" xml:lang="en-us"> <!-- 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. --> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <meta name="copyright" content="(C) Copyright 2005" /> <meta name="DC.rights.owner" content="(C) Copyright 2005" /> <meta content="public" name="security" /> <meta content="index,follow" name="Robots" /> <meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' /> <meta content="concept" name="DC.Type" /> <meta name="DC.Title" content="Using ij" /> <meta name="abstract" content="ij is Derby's interactive JDBC scripting tool. It is a simple utility for running scripts or interactive queries against a Derby database." /> <meta name="description" content="ij is Derby's interactive JDBC scripting tool. It is a simple utility for running scripts or interactive queries against a Derby database." /> <meta scheme="URI" name="DC.Relation" content="ttoolsij11815.html" /> <meta scheme="URI" name="DC.Relation" content="ttoolsijcreatedatabase.html" /> <meta scheme="URI" name="DC.Relation" content="ttoolsij30600.html" /> <meta scheme="URI" name="DC.Relation" content="ctoolsij32837.html" /> <meta content="XHTML" name="DC.Format" /> <meta content="ctoolsij34525" name="DC.Identifier" /> <meta content="en-us" name="DC.Language" /> <link href="commonltr.css" type="text/css" rel="stylesheet" /> <title>Using ij</title> </head> <body id="ctoolsij34525"><a name="ctoolsij34525"><!-- --></a> <h1 class="topictitle1">Using ij</h1> <div><p>ij is <span>Derby</span>'s interactive JDBC scripting tool. It is a simple utility for running scripts or interactive queries against a <span>Derby</span> database.</p> <p>ij is a Java application, which you start from a command window such as an MS-DOS Command Window or the UNIX shell. ij provides several non-SQL commands for ease in accessing a variety of JDBC features for testing.</p> </div> <div> <ul class="ullinks"> <li class="ulchildlink"><strong><a href="ttoolsij11815.html">Starting ij</a></strong><br /> </li> <li class="ulchildlink"><strong><a href="ttoolsijcreatedatabase.html">Creating a database using ij</a></strong><br /> </li> <li class="ulchildlink"><strong><a href="ttoolsij30600.html">Starting ij using properties</a></strong><br /> </li> <li class="ulchildlink"><strong><a href="ctoolsij32837.html">Getting started with ij</a></strong><br /> </li> </ul> </div> </body> </html>
acshea/edgware
bundle.apache.derby/db-derby-10.8.3.0-bin/docs/html/tools/ctoolsij34525.html
HTML
epl-1.0
3,565
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.executor.css; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.birt.report.engine.util.FileUtil; import org.eclipse.birt.report.model.api.IResourceLocator; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.w3c.dom.Element; import org.w3c.dom.Node; //TODO: review, we should remove the CssParser from this class. //TODO: review, in HTML, we need support a RESOURCE tag like VALUE-OF which create a URL. /** * Converts the deprecated element according to the HTML 4.0 specification and * parses the style attribute of the HTML element. * */ public class HTMLProcessor { /** the logger */ private static Logger logger = Logger.getLogger( HTMLProcessor.class .getName( ) ); /** the possible values for property SIZE of HTML element FONT */ private static String[] FONT_SIZE = new String[]{"7.5pt", //$NON-NLS-1$ "7.5pt", "7.5pt", //$NON-NLS-1$ //$NON-NLS-2$ "7.5pt", "7.5pt", //$NON-NLS-1$//$NON-NLS-2$ "7.5pt", "10pt", //$NON-NLS-1$ //$NON-NLS-2$ "7.5pt", "7.5pt", //$NON-NLS-1$ //$NON-NLS-2$ "10pt", "12pt", //$NON-NLS-1$ //$NON-NLS-2$ "13.8pt", "18pt", //$NON-NLS-1$//$NON-NLS-2$ "23pt", "36pt"}; //$NON-NLS-1$//$NON-NLS-2$ private static final Pattern IN_BRACKET_PATTERN = Pattern.compile( "\\(.*?\\)" ); private static final Pattern STYLE_PAIR_PATTERN = Pattern.compile( "[ ]*([^:]*)[ ]*:[ ]*([^;]*)[ ]*[;]*" ); private static final String BRACKETED_REPLACEMENT = "___BRACKETED___"; // private static String[] FONT_SIZE = new String[]{"xx-small", "x-small", // //$NON-NLS-1$ //$NON-NLS-2$ // "small", "medium", //$NON-NLS-1$ //$NON-NLS-2$ // "large", "x-large", //$NON-NLS-1$//$NON-NLS-2$ // "xx-large", "xxx-large"}; //$NON-NLS-1$//$NON-NLS-2$ protected ReportDesignHandle design; protected String rootPath; private Map appContext; /** * Constructor * * @param context * the execution context */ public HTMLProcessor( ReportDesignHandle design, Map context ) { this.design = design; this.rootPath = null; // Takes the zero-length string as parameter just for keeping to the // interface of constructor this.appContext = context; } public HTMLProcessor( String rootPath ) { this.design = null; this.rootPath = rootPath; // Takes the zero-length string as parameter just for keeping to the // interface of constructor } /** * Parses the style attribute of the element node and converts the * deprecated element node in HTML 4.0, and calls it on its children element * nodes recursively * * @param ele * the element node in the DOM tree * @param text * the text content object */ public void execute( Element ele, HashMap styles ) { HashMap cssStyle = new HashMap( ); if ( ele.hasAttribute( "style" ) ) //$NON-NLS-1$ { String inlineStyle = ele.getAttribute( "style" ); //$NON-NLS-1$ if ( null != inlineStyle && !"".equals( inlineStyle ) ) //$NON-NLS-1$ { ArrayList<String> bracketed = new ArrayList<String>( ); //replace all bracketed content to avoid : and ; in the bracket. Matcher matcher = IN_BRACKET_PATTERN.matcher( inlineStyle ); while ( matcher.find( ) ) { bracketed.add( matcher.group( 0 ) ); } inlineStyle = matcher.replaceAll( BRACKETED_REPLACEMENT ); int replacementIndex=0; matcher = STYLE_PAIR_PATTERN.matcher( inlineStyle ); while ( matcher.find( ) ) { String name = matcher.group( 1 ); String value = matcher.group( 2 ); if ( name != null && name.length( ) > 0 && value != null && value.length( ) > 0 ) { while ( value.contains( BRACKETED_REPLACEMENT ) ) { value = value.replace( BRACKETED_REPLACEMENT, bracketed.get( replacementIndex++ ) ); } cssStyle.put( name, value.trim() ); } } ele.removeAttribute( "style" ); //$NON-NLS-1$ // If the background image is a local resource, then get its // global // URI. String src = (String) cssStyle.get( "background-image" ); //$NON-NLS-1$ if ( src != null ) { // The resource is surrounded with "url(" and ")", or "\"", // or // "\'". Removes them. if ( src.startsWith( "url(" ) && src.length( ) > 5 ) //$NON-NLS-1$ { src = src.substring( 4, src.length( ) - 1 ); } else if ( ( src.startsWith( "\"" ) || src.startsWith( "\'" ) ) //$NON-NLS-1$ //$NON-NLS-2$ && src.length( ) > 2 ) { src = src.substring( 1, src.length( ) - 1 ); } if ( design != null ) { URL url = design.findResource( src, IResourceLocator.IMAGE, appContext ); if ( url != null ) { src = url.toExternalForm( ); } } if ( rootPath != null ) { // Checks if the resource is local if ( FileUtil.isLocalResource( src ) ) { src = FileUtil.getAbsolutePath( rootPath, src ); } } if ( src != null ) { // Puts the modified URI of the resource cssStyle.put( "background-image", src ); //$NON-NLS-1$ } else { // If the resource does not exist, then removes this // item. cssStyle.remove( "background-image" ); //$NON-NLS-1$ } } } // FOR HTML 4.0 COMPATIBILITY if ( "b".equals( ele.getTagName( ) ) ) //$NON-NLS-1$ { addToStyle( cssStyle, "font-weight", "bold" ); //$NON-NLS-1$//$NON-NLS-2$ // Re-points to the element node in the tree ele = replaceElement( ele, "span" ); //$NON-NLS-1$ } else if ( "center".equals( ele.getTagName( ) ) ) //$NON-NLS-1$ { addToStyle( cssStyle, "text-align", "center" ); //$NON-NLS-1$ //$NON-NLS-2$ ele = replaceElement( ele, "div" ); //$NON-NLS-1$ } else if ( "font".equals( ele.getTagName( ) ) ) //$NON-NLS-1$ { addToStyle( cssStyle, "color", ele.getAttribute( "color" ) ); //$NON-NLS-1$ //$NON-NLS-2$ addToStyle( cssStyle, "font-family", ele.getAttribute( "face" ) ); //$NON-NLS-1$ //$NON-NLS-2$ if ( ele.hasAttribute( "size" ) ) //$NON-NLS-1$ { try { int size = Integer .parseInt( ele.getAttribute( "size" ) ); //$NON-NLS-1$ addToStyle( cssStyle, "font-size", FONT_SIZE[size + 7] ); //$NON-NLS-1$ } catch ( Exception e ) { logger .log( Level.SEVERE, "There is a invalid value for property SIZE of element FONT in the HTML." ); //$NON-NLS-1$ } } // Removes these attributes to avoid for being copied again. ele.removeAttribute( "color" ); //$NON-NLS-1$ ele.removeAttribute( "face" ); //$NON-NLS-1$ ele.removeAttribute( "size" ); //$NON-NLS-1$ ele = replaceElement( ele, "span" ); //$NON-NLS-1$ } else if ( "i".equals( ele.getTagName( ) ) ) //$NON-NLS-1$ { addToStyle( cssStyle, "font-style", "italic" ); //$NON-NLS-1$ //$NON-NLS-2$ ele = replaceElement( ele, "span" ); //$NON-NLS-1$ } else if ( "u".equals( ele.getTagName( ) ) ) //$NON-NLS-1$ { String decoration = (String) cssStyle.get( "text-decoration" ); //$NON-NLS-1$ // The property "text-decoration" is made of more than one // token. if ( decoration != null && decoration.indexOf( "underline" ) == -1 //$NON-NLS-1$ && decoration.indexOf( "none" ) == -1 //$NON-NLS-1$ && decoration.indexOf( "inherit" ) == -1 ) //$NON-NLS-1$ { decoration = decoration + " underline"; //$NON-NLS-1$ } else if ( decoration == null ) { decoration = "underline"; //$NON-NLS-1$ } cssStyle.put( "text-decoration", decoration ); //$NON-NLS-1$ ele = replaceElement( ele, "span" ); //$NON-NLS-1$ } else if ( "img".equals( ele.getTagName( ) ) ) { String src = ele.getAttribute( "src" ); //$NON-NLS-1$ if ( src != null ) { // The resource is surrounded with "url(" and ")", or "\"", // or // "\'". Removes them. if ( ( src.startsWith( "\"" ) || src.startsWith( "\'" ) ) //$NON-NLS-1$ //$NON-NLS-2$ && src.length( ) > 2 ) { src = src.substring( 1, src.length( ) - 1 ); } if ( design != null ) { URL url = design.findResource( src, IResourceLocator.IMAGE, appContext ); if ( url != null ) { src = url.toExternalForm( ); } } if ( rootPath != null ) { // Checks if the resource is local if ( FileUtil.isLocalResource( src ) ) { src = FileUtil.getAbsolutePath( rootPath, src ); } } if ( src != null ) { // Puts the modified URI of the resource ele.removeAttribute( "src" ); //$NON-NLS-1$ ele.setAttribute( "src", src ); } } } styles.put( ele, cssStyle ); } // Walks on its children nodes recursively for ( int i = 0; i < ele.getChildNodes( ).getLength( ); i++ ) { Node child = ele.getChildNodes( ).item( i ); if ( child.getNodeType( ) == Node.ELEMENT_NODE ) { execute( (Element) child, styles ); } } } /** * Replaces the previous element with the new tag name in the same position * and return it * * @param oldEle * the replaced element * @param tag * the tag name of the new HTML element * @return the new HTML element */ private Element replaceElement( Element oldEle, String tag ) { Element newEle = oldEle.getOwnerDocument( ).createElement( tag ); // Copies the attributes for ( int i = 0; i < oldEle.getAttributes( ).getLength( ); i++ ) { String attrName = oldEle.getAttributes( ).item( i ).getNodeName( ); newEle.setAttribute( attrName, oldEle.getAttribute( attrName ) ); } // Copies the children nodes // Note: After the child node is moved to another parent node, then // relationship between it and its sibling is removed. So here calls // <code>Node.getFirstChild()</code>again and again till it is null. for ( Node child = oldEle.getFirstChild( ); child != null; child = oldEle .getFirstChild( ) ) { newEle.appendChild( child ); } oldEle.getParentNode( ).replaceChild( newEle, oldEle ); return newEle; } /** * Adds the attribute name and value to the style if attribute value is not * null and a zero-length string and the added attribute is not in the * style. * * @param style * the style attribute for HTML element * @param attrName * the added attribute name * @param attrValue * the added attribute value */ private void addToStyle( HashMap style, String attrName, String attrValue ) { if ( attrValue == null || attrValue.trim( ).length( ) == 0 ) { return; } if ( style.get( attrName ) == null ) { style.put( attrName, attrValue ); } } }
sguan-actuate/birt
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/executor/css/HTMLProcessor.java
Java
epl-1.0
11,427
/******************************************************************************* * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.api.script.instance; import java.util.Map; /** * */ public interface IDrillThroughInstance { /** * @return the report name. */ String getReportName( ); /** * Set the report name. * @param reportName */ void setReportName( String reportName ); /** * @return a set of name/value pairs for running the report in the * drillthrough link. */ Map getParameterBindings( ); /** * Set a set of name/value pairs for running the report in the * drillthrough link. */ void setParameterBindings( Map parameterBindings ); /** * @return a set of name/value pairs for searching the report in the * drillthrough link. */ Map getSearchCriteria( ); /** * Set a set of name/value pairs for searching the report in the * drillthrough link. */ void setSearchCriteria( Map searchCriteria ); /** * @return the format of output report. * */ String getFormat( ); /** * Set the format of output report. * */ void setFormat( String format ); /** * @return the bookmark type. * True, the bookmark is a bookmark. * False, the bookmark is a toc. */ boolean isBookmark(); /** * Set the bookmark to the drillThrough . * @param bookmark */ void setBookmark( String bookmark ); /** * @return the bookmark string if the bookmark type is Bookmark. * NULL if the bookmark type is TOC. */ String getBookmark( ); /** * Set the TOC of this drillThrough. * @param toc */ void setTOC( String toc ); /** * @return the bookmark string if the bookmark type is TOC. * NULL if the bookmark type is Bookmark. */ String getTOC( ); /** * @return the targetWindow string. */ String getTargetWindow( ); /** * Set the targetWindow string. */ void setTargetWindow( String target ); /** * Sets target report file type for a drill-through action. */ void setTargetFileType( String targetFileType ); /** * @return the type of the target report file. */ String getTargetFileType( ); }
sguan-actuate/birt
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/script/instance/IDrillThroughInstance.java
Java
epl-1.0
2,637
/* ********************************************************************** ** ** Copyright notice ** ** ** ** (c) 2005-2009 RSSOwl Development Team ** ** http://www.rssowl.org/ ** ** ** ** All rights reserved ** ** ** ** This program and the accompanying materials are made available under ** ** the terms of the Eclipse Public License v1.0 which accompanies this ** ** distribution, and is available at: ** ** http://www.rssowl.org/legal/epl-v10.html ** ** ** ** A copy is found in the file epl-v10.html and important notices to the ** ** license from the team is found in the textfile LICENSE.txt distributed ** ** in this package. ** ** ** ** This copyright notice MUST APPEAR in all copies of the file! ** ** ** ** Contributors: ** ** RSSOwl Development Team - initial API and implementation ** ** ** ** ********************************************************************** */ package org.rssowl.core.internal.persist; import org.rssowl.core.util.ArrayUtils; import java.util.Arrays; /** * Subclass of {@link LongArrayList} that sorts its elements. */ public final class SortedLongArrayList extends LongArrayList { /** * Provided for deserialization. */ protected SortedLongArrayList() { super(); } public SortedLongArrayList(int initialCapacity) { super(initialCapacity); } /* * @see org.rssowl.core.internal.persist.LongArrayList#indexOf(long) */ @Override public int indexOf(long element) { return ArrayUtils.binarySearch(fElements, element, fSize); } /* * @see org.rssowl.core.internal.persist.LongArrayList#add(long) */ @Override public void add(long element) { fElements = ArrayUtils.ensureCapacity(fElements, fSize + 1); int insertionPoint = indexOf(element); if (insertionPoint < 0) insertionPoint = (-insertionPoint) - 1; System.arraycopy(fElements, insertionPoint, fElements, insertionPoint + 1, fSize - insertionPoint); fElements[insertionPoint] = element; ++fSize; } /* * @see org.rssowl.core.internal.persist.LongArrayList#setAll(long[]) */ @Override public void setAll(long[] elements) { super.setAll(elements); Arrays.sort(fElements, 0, fSize); } }
rssowl/RSSOwl
org.rssowl.core/src/org/rssowl/core/internal/persist/SortedLongArrayList.java
Java
epl-1.0
3,146
/** * Copyright (c) 2010-2017 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.loxone.internal.core; import java.io.IOException; import org.openhab.binding.loxone.internal.core.LxJsonApp3.LxJsonControl; /** * A timed switch type of control on Loxone Miniserver. * <p> * According to Loxone API documentation, a switch control is: * <ul> * <li>a virtual input of switch type * <li>a push button function block * </ul> * * @author Stephan Brunner * */ public class LxControlTimedSwitch extends LxControl { /** * A name by which Miniserver refers to timed switch controls */ private static final String TYPE_NAME = "timedswitch"; /** * deactivationDelay - countdown until the output is deactivated. * 0 = the output is turned off * -1 = the output is permanently on * otherwise it will count down from deactivationDelayTotal */ private static final String STATE_DEACTIVATION_DELAY = "deactivationdelay"; /** * Command string used to set timed switch to ON without deactivation delay */ private static final String CMD_ON = "On"; /** * Command string used to set timed switch to ON with deactivation delay */ private static final String CMD_PULSE = "pulse"; /** * Command string used to set timed switch to OFF */ private static final String CMD_OFF = "Off"; /** * Create timed switch control object. * * @param client * communication client used to send commands to the Miniserver * @param uuid * switch's UUID * @param json * JSON describing the control as received from the Miniserver * @param room * room to which switch belongs * @param category * category to which switch belongs */ LxControlTimedSwitch(LxWsClient client, LxUuid uuid, LxJsonControl json, LxContainer room, LxCategory category) { super(client, uuid, json, room, category); } /** * Check if control accepts provided type name from the Miniserver * * @param type * name of the type received from Miniserver * @return * true if this control is suitable for this type */ public static boolean accepts(String type) { return type.equalsIgnoreCase(TYPE_NAME); } /** * Set timed switch to ON without deactivation delay. * <p> * Sends a command to operate the timed switch. * * @throws IOException * when something went wrong with communication */ public void on() throws IOException { socketClient.sendAction(uuid, CMD_ON); } /** * Set timed switch to ON with deactivation delay. * <p> * Sends a command to operate the timed switch. * * @throws IOException * when something went wrong with communication */ public void pulse() throws IOException { socketClient.sendAction(uuid, CMD_PULSE); } /** * Set timed switch to OFF. * <p> * Sends a command to operate the timed switch. * * @throws IOException * when something went wrong with communication */ public void off() throws IOException { socketClient.sendAction(uuid, CMD_OFF); } /** * Get current value of the timed switch'es state. * * @return * 0 - switch off, 1 - switch on */ public Double getState() { /** * 0 = the output is turned off * -1 = the output is permanently on * otherwise it will count down from deactivationDelayTotal **/ LxControlState state = getState(STATE_DEACTIVATION_DELAY); if (state != null && state.getValue() != null) { if (state.getValue() == -1 || state.getValue() > 0) { // mapping return 1d; } else if (state.getValue() == 0) { return 0d; } } return null; } /** * * @return deactivation delay in seconds * Loxone also returns floating point values for the delay e.g. 9.99 seconds */ public Double getDeactivationDelay() { LxControlState state = getState(STATE_DEACTIVATION_DELAY); if (state != null) { return state.getValue(); } return null; } }
beowulfe/openhab2
addons/binding/org.openhab.binding.loxone/src/main/java/org/openhab/binding/loxone/internal/core/LxControlTimedSwitch.java
Java
epl-1.0
4,682
/******************************************************************************* * Copyright (c) 2016 IBH SYSTEMS GmbH and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBH SYSTEMS GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.packagedrone.repo.trigger.common.unique; import org.eclipse.packagedrone.repo.channel.AddingContext; import org.eclipse.packagedrone.repo.trigger.Processor; import org.eclipse.packagedrone.repo.trigger.ProcessorFactory; import org.eclipse.packagedrone.web.LinkTarget; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UniqueArtifactProcessorFactory implements ProcessorFactory { static final Class<?>[] SUPPORTED_CONTEXTS = new Class<?>[] { AddingContext.class }; private final static Logger logger = LoggerFactory.getLogger ( UniqueArtifactProcessorFactory.class ); public static final String ID = "unique.artifact"; @Override public Class<?>[] getSupportedContexts () { return SUPPORTED_CONTEXTS; } @Override public Processor create ( final String configuration ) { return new UniqueArtifactProcessor ( UniqueArtifactConfiguration.fromJson ( configuration ) ); } @Override public String getLabel () { return "Unique artifacts"; } @Override public String getDescription () { return "Ensure the uniqueness of artifacts."; } @Override public String getConfigurationUrl () { try { return LinkTarget.createFromController ( UniqueArtifactConfigurationController.class, "configure" ).getUrl (); } catch ( final Exception e ) { logger.warn ( "Failed to generate configuration url", e ); return null; } } }
ibh-systems/packagedrone
bundles/org.eclipse.packagedrone.repo.trigger.common/src/org/eclipse/packagedrone/repo/trigger/common/unique/UniqueArtifactProcessorFactory.java
Java
epl-1.0
2,095
/* * Copyright (C) 2009-2011, Pino Toscano <pino@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "poppler-document.h" #include "poppler-embedded-file.h" #include "poppler-page.h" #include "poppler-toc.h" #include "poppler-document-private.h" #include "poppler-embedded-file-private.h" #include "poppler-private.h" #include "poppler-toc-private.h" #include "Catalog.h" #include "ErrorCodes.h" #include "GlobalParams.h" #include "Outline.h" #include <algorithm> #include <iterator> #include <memory> using namespace poppler; unsigned int poppler::initer::count = 0U; initer::initer() { if (!count) { globalParams = new GlobalParams(); setErrorFunction(detail::error_function); } count++; } initer::~initer() { if (count > 0) { --count; if (!count) { delete globalParams; globalParams = 0; } } } document_private::document_private(GooString *file_path, const std::string &owner_password, const std::string &user_password) : initer() , doc(0) , raw_doc_data(0) , raw_doc_data_length(0) , is_locked(false) { GooString goo_owner_password(owner_password.c_str()); GooString goo_user_password(user_password.c_str()); doc = new PDFDoc(file_path, &goo_owner_password, &goo_user_password); } document_private::document_private(byte_array *file_data, const std::string &owner_password, const std::string &user_password) : initer() , doc(0) , raw_doc_data(0) , raw_doc_data_length(0) , is_locked(false) { Object obj; obj.initNull(); file_data->swap(doc_data); MemStream *memstr = new MemStream(&doc_data[0], 0, doc_data.size(), &obj); GooString goo_owner_password(owner_password.c_str()); GooString goo_user_password(user_password.c_str()); doc = new PDFDoc(memstr, &goo_owner_password, &goo_user_password); } document_private::document_private(const char *file_data, int file_data_length, const std::string &owner_password, const std::string &user_password) : initer() , doc(0) , raw_doc_data(file_data) , raw_doc_data_length(file_data_length) , is_locked(false) { Object obj; obj.initNull(); MemStream *memstr = new MemStream(const_cast<char *>(raw_doc_data), 0, raw_doc_data_length, &obj); GooString goo_owner_password(owner_password.c_str()); GooString goo_user_password(user_password.c_str()); doc = new PDFDoc(memstr, &goo_owner_password, &goo_user_password); } document_private::~document_private() { delete_all(embedded_files); delete doc; } document* document_private::check_document(document_private *doc, byte_array *file_data) { if (doc->doc->isOk() || doc->doc->getErrorCode() == errEncrypted) { if (doc->doc->getErrorCode() == errEncrypted) { doc->is_locked = true; } return new document(*doc); } else { // put back the document data where it was before if (file_data) { file_data->swap(doc->doc_data); } delete doc; } return 0; } /** \class poppler::document poppler-document.h "poppler/cpp/poppler-document.h" Represents a PDF %document. */ /** \enum poppler::document::page_mode_enum The various page modes available in a PDF %document. */ /** \var poppler::document::page_mode_enum poppler::document::use_none The %document specifies no particular page mode. */ /** \var poppler::document::page_mode_enum poppler::document::use_outlines The %document specifies its TOC (table of contents) should be open. */ /** \var poppler::document::page_mode_enum poppler::document::use_thumbs The %document specifies that should be open a view of the thumbnails of its pages. */ /** \var poppler::document::page_mode_enum poppler::document::fullscreen The %document specifies it wants to be open in a fullscreen mode. */ /** \var poppler::document::page_mode_enum poppler::document::use_oc The %document specifies that should be open a view of its Optional Content (also known as layers). */ /** \var poppler::document::page_mode_enum poppler::document::use_attach The %document specifies that should be open a view of its %document-level attachments. */ document::document(document_private &dd) : d(&dd) { } document::~document() { delete d; } /** \returns whether the current %document is locked */ bool document::is_locked() const { return d->is_locked; } /** Unlocks the current doocument, if locked. \returns the new locking status of the document */ bool document::unlock(const std::string &owner_password, const std::string &user_password) { if (d->is_locked) { document_private *newdoc = 0; if (d->doc_data.size() > 0) { newdoc = new document_private(&d->doc_data, owner_password, user_password); } else if (d->raw_doc_data) { newdoc = new document_private(d->raw_doc_data, d->raw_doc_data_length, owner_password, user_password); } else { newdoc = new document_private(new GooString(d->doc->getFileName()), owner_password, user_password); } if (!newdoc->doc->isOk()) { d->doc_data.swap(newdoc->doc_data); delete newdoc; } else { delete d; d = newdoc; d->is_locked = false; } } return d->is_locked; } /** \returns the eventual page mode specified by the current PDF %document */ document::page_mode_enum document::page_mode() const { switch (d->doc->getCatalog()->getPageMode()) { case Catalog::pageModeNone: return use_none; case Catalog::pageModeOutlines: return use_outlines; case Catalog::pageModeThumbs: return use_thumbs; case Catalog::pageModeFullScreen: return fullscreen; case Catalog::pageModeOC: return use_oc; case Catalog::pageModeAttach: return use_attach; default: return use_none; } } /** \returns the eventual page layout specified by the current PDF %document */ document::page_layout_enum document::page_layout() const { switch (d->doc->getCatalog()->getPageLayout()) { case Catalog::pageLayoutNone: return no_layout; case Catalog::pageLayoutSinglePage: return single_page; case Catalog::pageLayoutOneColumn: return one_column; case Catalog::pageLayoutTwoColumnLeft: return two_column_left; case Catalog::pageLayoutTwoColumnRight: return two_column_right; case Catalog::pageLayoutTwoPageLeft: return two_page_left; case Catalog::pageLayoutTwoPageRight: return two_page_right; default: return no_layout; } } /** Gets the version of the current PDF %document. Example: \code poppler::document *doc = ...; // for example, if the document is PDF 1.6: int major = 0, minor = 0; doc->get_pdf_version(&major, &minor); // major == 1 // minor == 6 \endcode \param major if not NULL, will be set to the "major" number of the version \param minor if not NULL, will be set to the "minor" number of the version */ void document::get_pdf_version(int *major, int *minor) const { if (major) { *major = d->doc->getPDFMajorVersion(); } if (minor) { *minor = d->doc->getPDFMinorVersion(); } } /** \returns all the information keys available in the %document \see info_key, info_date */ std::vector<std::string> document::info_keys() const { if (d->is_locked) { return std::vector<std::string>(); } Object info; if (!d->doc->getDocInfo(&info)->isDict()) { info.free(); return std::vector<std::string>(); } Dict *info_dict = info.getDict(); std::vector<std::string> keys(info_dict->getLength()); for (int i = 0; i < info_dict->getLength(); ++i) { keys[i] = std::string(info_dict->getKey(i)); } info.free(); return keys; } /** Gets the value of the specified \p key of the document information. \returns the value for the \p key, or an empty string if not available \see info_keys, info_date */ ustring document::info_key(const std::string &key) const { if (d->is_locked) { return ustring(); } Object info; if (!d->doc->getDocInfo(&info)->isDict()) { info.free(); return ustring(); } Dict *info_dict = info.getDict(); Object obj; ustring result; if (info_dict->lookup(PSTR(key.c_str()), &obj)->isString()) { result = detail::unicode_GooString_to_ustring(obj.getString()); } obj.free(); info.free(); return result; } /** Gets the time_t value value of the specified \p key of the document information. \returns the time_t value for the \p key \see info_keys, info_date */ time_type document::info_date(const std::string &key) const { if (d->is_locked) { return time_type(-1); } Object info; if (!d->doc->getDocInfo(&info)->isDict()) { info.free(); return time_type(-1); } Dict *info_dict = info.getDict(); Object obj; time_type result = time_type(-1); if (info_dict->lookup(PSTR(key.c_str()), &obj)->isString()) { result = detail::convert_date(obj.getString()->getCString()); } obj.free(); info.free(); return result; } /** \returns whether the document is encrypted */ bool document::is_encrypted() const { return d->doc->isEncrypted(); } /** \returns whether the document is linearized */ bool document::is_linearized() const { return d->doc->isLinearized(); } /** Check for available "document permission". \returns whether the specified permission is allowed */ bool document::has_permission(permission_enum which) const { switch (which) { case perm_print: return d->doc->okToPrint(); case perm_change: return d->doc->okToChange(); case perm_copy: return d->doc->okToCopy(); case perm_add_notes: return d->doc->okToAddNotes(); case perm_fill_forms: return d->doc->okToFillForm(); case perm_accessibility: return d->doc->okToAccessibility(); case perm_assemble: return d->doc->okToAssemble(); case perm_print_high_resolution: return d->doc->okToPrintHighRes(); } return true; } /** Reads the %document metadata string. \return the %document metadata string */ ustring document::metadata() const { std::auto_ptr<GooString> md(d->doc->getCatalog()->readMetadata()); if (md.get()) { return detail::unicode_GooString_to_ustring(md.get()); } return ustring(); } /** Gets the IDs of the current PDF %document, if available. \param permanent_id if not NULL, will be set to the permanent ID of the %document \param update_id if not NULL, will be set to the update ID of the %document \returns whether the document has the IDs \since 0.16 */ bool document::get_pdf_id(std::string *permanent_id, std::string *update_id) const { GooString goo_permanent_id; GooString goo_update_id; if (!d->doc->getID(permanent_id ? &goo_permanent_id : 0, update_id ? &goo_update_id : 0)) { return false; } if (permanent_id) { *permanent_id = goo_permanent_id.getCString(); } if (update_id) { *update_id = goo_update_id.getCString(); } return true; } /** Document page count. \returns the number of pages of the document */ int document::pages() const { return d->doc->getNumPages(); } /** Document page by label reading. This creates a new page representing the %document %page whose label is the specified \p label. If there is no page with that \p label, NULL is returned. \returns a new page object or NULL */ page* document::create_page(const ustring &label) const { std::auto_ptr<GooString> goolabel(detail::ustring_to_unicode_GooString(label)); int index = 0; if (!d->doc->getCatalog()->labelToIndex(goolabel.get(), &index)) { return 0; } return create_page(index); } /** Document page by index reading. This creates a new page representing the \p index -th %page of the %document. \note the page indexes are in the range [0, pages()[. \returns a new page object or NULL */ page* document::create_page(int index) const { return index >= 0 && index < d->doc->getNumPages() ? new page(d, index) : 0; } /** Reads all the font information of the %document. \note this can be slow for big documents; prefer the use of a font_iterator to read incrementally page by page \see create_font_iterator */ std::vector<font_info> document::fonts() const { std::vector<font_info> result; font_iterator it(0, d); while (it.has_next()) { const std::vector<font_info> l = it.next(); std::copy(l.begin(), l.end(), std::back_inserter(result)); } return result; } /** Creates a new font iterator. This creates a new font iterator for reading the font information of the %document page by page, starting at the specified \p start_page (0 if not specified). \returns a new font iterator */ font_iterator* document::create_font_iterator(int start_page) const { return new font_iterator(start_page, d); } /** Reads the TOC (table of contents) of the %document. \returns a new toc object if a TOC is available, NULL otherwise */ toc* document::create_toc() const { return toc_private::load_from_outline(d->doc->getOutline()); } /** Reads whether the current document has %document-level embedded files (attachments). This is a very fast way to know whether there are embedded files (also known as "attachments") at the %document-level. Note this does not take into account files embedded in other ways (e.g. to annotations). \returns whether the document has embedded files */ bool document::has_embedded_files() const { return d->doc->getCatalog()->numEmbeddedFiles() > 0; } /** Reads all the %document-level embedded files of the %document. \returns the %document-level embedded files */ std::vector<embedded_file *> document::embedded_files() const { if (d->is_locked) { return std::vector<embedded_file *>(); } if (d->embedded_files.empty() && d->doc->getCatalog()->numEmbeddedFiles() > 0) { const int num = d->doc->getCatalog()->numEmbeddedFiles(); d->embedded_files.resize(num); for (int i = 0; i < num; ++i) { FileSpec *fs = d->doc->getCatalog()->embeddedFile(i); d->embedded_files[i] = embedded_file_private::create(fs); } } return d->embedded_files; } /** Tries to load a PDF %document from the specified file. \param file_name the file to open \returns a new document if the load succeeded (even if the document is locked), NULL otherwise */ document* document::load_from_file(const std::string &file_name, const std::string &owner_password, const std::string &user_password) { document_private *doc = new document_private( new GooString(file_name.c_str()), owner_password, user_password); return document_private::check_document(doc, 0); } /** Tries to load a PDF %document from the specified data. \note if the loading succeeds, the document takes ownership of the \p file_data (swap()ing it) \param file_data the data representing a document to open \returns a new document if the load succeeded (even if the document is locked), NULL otherwise */ document* document::load_from_data(byte_array *file_data, const std::string &owner_password, const std::string &user_password) { if (!file_data || file_data->size() < 10) { return 0; } document_private *doc = new document_private( file_data, owner_password, user_password); return document_private::check_document(doc, file_data); } /** Tries to load a PDF %document from the specified data buffer. \note the buffer must remain valid for the whole lifetime of the returned document \param file_data the data buffer representing a document to open \param file_data_length the length of the data buffer \returns a new document if the load succeeded (even if the document is locked), NULL otherwise \since 0.16 */ document* document::load_from_raw_data(const char *file_data, int file_data_length, const std::string &owner_password, const std::string &user_password) { if (!file_data || file_data_length < 10) { return 0; } document_private *doc = new document_private( file_data, file_data_length, owner_password, user_password); return document_private::check_document(doc, 0); }
kenjiuno/ThumbGensPack
src/poppler/cpp/poppler-document.cpp
C++
gpl-2.0
17,947
/* * Copyright (C) 2010-2011 Corentin Chary <corentin.chary@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <QtCore/QCoreApplication> #include <QtCore/QFileInfo> #include <QtCore/QDir> #include "seriesaction.h" #include "settings.h" Settings::Settings(QObject *parent) : QSettings(QSettings::IniFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName(), parent) { } Settings::~Settings() { } Settings * Settings::instance() { if (!instance_) { instance_ = new Settings(); if (instance_->value("version").isNull()) { QList < SeriesAction * > actions; SeriesAction *action = new SeriesAction(); action = new SeriesAction(); action->setText(tr("Buy on Amazon")); action->setShowUrl(QString("http://www.amazon.com/s/?tag=httpxfiksaifn-21&url=search-alias%3Ddvd&field-keywords=%S")); action->setSeasonUrl(QString("http://www.amazon.com/s/?tag=httpxfiksaifn-21&url=search-alias%3Ddvd&field-keywords=%S season %n")); action->setIconPath(":/res/amazon.png"); actions << action; SeriesAction::addToSettings(actions); qDeleteAll(actions); } instance_->setValue("version", QCoreApplication::applicationVersion()); instance_->sync(); } return instance_; } QString Settings::path() { Settings *conf = instance(); return QFileInfo(conf->fileName()).dir().canonicalPath(); } Settings *Settings::instance_ = NULL;
jepaan/serieswatcher
common/settings.cpp
C++
gpl-2.0
2,161
/* Mainly the interface between cpplib and the C front ends. Copyright (C) 1987-2013 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC 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 General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "input.h" #include "c-common.h" #include "flags.h" #include "timevar.h" #include "cpplib.h" #include "c-pragma.h" #include "intl.h" #include "splay-tree.h" #include "debug.h" #include "target.h" /* We may keep statistics about how long which files took to compile. */ static int header_time, body_time; static splay_tree file_info_tree; int pending_lang_change; /* If we need to switch languages - C++ only */ int c_header_level; /* depth in C headers - C++ only */ static tree interpret_integer (const cpp_token *, unsigned int, enum overflow_type *); static tree interpret_float (const cpp_token *, unsigned int, const char *, enum overflow_type *); static tree interpret_fixed (const cpp_token *, unsigned int); static enum integer_type_kind narrowest_unsigned_type (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT, unsigned int); static enum integer_type_kind narrowest_signed_type (unsigned HOST_WIDE_INT, unsigned HOST_WIDE_INT, unsigned int); static enum cpp_ttype lex_string (const cpp_token *, tree *, bool, bool); static tree lex_charconst (const cpp_token *); static void update_header_times (const char *); static int dump_one_header (splay_tree_node, void *); static void cb_line_change (cpp_reader *, const cpp_token *, int); static void cb_ident (cpp_reader *, unsigned int, const cpp_string *); static void cb_def_pragma (cpp_reader *, unsigned int); static void cb_define (cpp_reader *, unsigned int, cpp_hashnode *); static void cb_undef (cpp_reader *, unsigned int, cpp_hashnode *); void init_c_lex (void) { struct cpp_callbacks *cb; struct c_fileinfo *toplevel; /* The get_fileinfo data structure must be initialized before cpp_read_main_file is called. */ toplevel = get_fileinfo ("<top level>"); if (flag_detailed_statistics) { header_time = 0; body_time = get_run_time (); toplevel->time = body_time; } cb = cpp_get_callbacks (parse_in); cb->line_change = cb_line_change; cb->ident = cb_ident; cb->def_pragma = cb_def_pragma; cb->valid_pch = c_common_valid_pch; cb->read_pch = c_common_read_pch; /* Set the debug callbacks if we can use them. */ if ((debug_info_level == DINFO_LEVEL_VERBOSE && (write_symbols == DWARF2_DEBUG || write_symbols == VMS_AND_DWARF2_DEBUG)) || flag_dump_go_spec != NULL) { cb->define = cb_define; cb->undef = cb_undef; } } struct c_fileinfo * get_fileinfo (const char *name) { splay_tree_node n; struct c_fileinfo *fi; if (!file_info_tree) file_info_tree = splay_tree_new ((splay_tree_compare_fn) strcmp, 0, (splay_tree_delete_value_fn) free); n = splay_tree_lookup (file_info_tree, (splay_tree_key) name); if (n) return (struct c_fileinfo *) n->value; fi = XNEW (struct c_fileinfo); fi->time = 0; fi->interface_only = 0; fi->interface_unknown = 1; splay_tree_insert (file_info_tree, (splay_tree_key) name, (splay_tree_value) fi); return fi; } static void update_header_times (const char *name) { /* Changing files again. This means currently collected time is charged against header time, and body time starts back at 0. */ if (flag_detailed_statistics) { int this_time = get_run_time (); struct c_fileinfo *file = get_fileinfo (name); header_time += this_time - body_time; file->time += this_time - body_time; body_time = this_time; } } static int dump_one_header (splay_tree_node n, void * ARG_UNUSED (dummy)) { print_time ((const char *) n->key, ((struct c_fileinfo *) n->value)->time); return 0; } void dump_time_statistics (void) { struct c_fileinfo *file = get_fileinfo (input_filename); int this_time = get_run_time (); file->time += this_time - body_time; fprintf (stderr, "\n******\n"); print_time ("header files (total)", header_time); print_time ("main file (total)", this_time - body_time); fprintf (stderr, "ratio = %g : 1\n", (double) header_time / (double) (this_time - body_time)); fprintf (stderr, "\n******\n"); splay_tree_foreach (file_info_tree, dump_one_header, 0); } static void cb_ident (cpp_reader * ARG_UNUSED (pfile), unsigned int ARG_UNUSED (line), const cpp_string * ARG_UNUSED (str)) { if (!flag_no_ident) { /* Convert escapes in the string. */ cpp_string cstr = { 0, 0 }; if (cpp_interpret_string (pfile, str, 1, &cstr, CPP_STRING)) { targetm.asm_out.output_ident ((const char *) cstr.text); free (CONST_CAST (unsigned char *, cstr.text)); } } } /* Called at the start of every non-empty line. TOKEN is the first lexed token on the line. Used for diagnostic line numbers. */ static void cb_line_change (cpp_reader * ARG_UNUSED (pfile), const cpp_token *token, int parsing_args) { if (token->type != CPP_EOF && !parsing_args) input_location = token->src_loc; } void fe_file_change (const struct line_map *new_map) { if (new_map == NULL) return; if (new_map->reason == LC_ENTER) { /* Don't stack the main buffer on the input stack; we already did in compile_file. */ if (!MAIN_FILE_P (new_map)) { unsigned int included_at = LAST_SOURCE_LINE_LOCATION (new_map - 1); int line = 0; if (included_at > BUILTINS_LOCATION) line = SOURCE_LINE (new_map - 1, included_at); input_location = new_map->start_location; (*debug_hooks->start_source_file) (line, LINEMAP_FILE (new_map)); #ifndef NO_IMPLICIT_EXTERN_C if (c_header_level) ++c_header_level; else if (LINEMAP_SYSP (new_map) == 2) { c_header_level = 1; ++pending_lang_change; } #endif } } else if (new_map->reason == LC_LEAVE) { #ifndef NO_IMPLICIT_EXTERN_C if (c_header_level && --c_header_level == 0) { if (LINEMAP_SYSP (new_map) == 2) warning (0, "badly nested C headers from preprocessor"); --pending_lang_change; } #endif input_location = new_map->start_location; (*debug_hooks->end_source_file) (LINEMAP_LINE (new_map)); } update_header_times (LINEMAP_FILE (new_map)); input_location = new_map->start_location; } static void cb_def_pragma (cpp_reader *pfile, source_location loc) { /* Issue a warning message if we have been asked to do so. Ignore unknown pragmas in system headers unless an explicit -Wunknown-pragmas has been given. */ if (warn_unknown_pragmas > in_system_header) { const unsigned char *space, *name; const cpp_token *s; location_t fe_loc = loc; space = name = (const unsigned char *) ""; s = cpp_get_token (pfile); if (s->type != CPP_EOF) { space = cpp_token_as_text (pfile, s); s = cpp_get_token (pfile); if (s->type == CPP_NAME) name = cpp_token_as_text (pfile, s); } warning_at (fe_loc, OPT_Wunknown_pragmas, "ignoring #pragma %s %s", space, name); } } /* #define callback for DWARF and DWARF2 debug info. */ static void cb_define (cpp_reader *pfile, source_location loc, cpp_hashnode *node) { const struct line_map *map = linemap_lookup (line_table, loc); (*debug_hooks->define) (SOURCE_LINE (map, loc), (const char *) cpp_macro_definition (pfile, node)); } /* #undef callback for DWARF and DWARF2 debug info. */ static void cb_undef (cpp_reader * ARG_UNUSED (pfile), source_location loc, cpp_hashnode *node) { const struct line_map *map = linemap_lookup (line_table, loc); (*debug_hooks->undef) (SOURCE_LINE (map, loc), (const char *) NODE_NAME (node)); } /* Read a token and return its type. Fill *VALUE with its value, if applicable. Fill *CPP_FLAGS with the token's flags, if it is non-NULL. */ enum cpp_ttype c_lex_with_flags (tree *value, location_t *loc, unsigned char *cpp_flags, int lex_flags) { static bool no_more_pch; const cpp_token *tok; enum cpp_ttype type; unsigned char add_flags = 0; enum overflow_type overflow = OT_NONE; timevar_push (TV_CPP); retry: tok = cpp_get_token_with_location (parse_in, loc); type = tok->type; retry_after_at: switch (type) { case CPP_PADDING: goto retry; case CPP_NAME: *value = HT_IDENT_TO_GCC_IDENT (HT_NODE (tok->val.node.node)); break; case CPP_NUMBER: { const char *suffix = NULL; unsigned int flags = cpp_classify_number (parse_in, tok, &suffix, *loc); switch (flags & CPP_N_CATEGORY) { case CPP_N_INVALID: /* cpplib has issued an error. */ *value = error_mark_node; break; case CPP_N_INTEGER: /* C++ uses '0' to mark virtual functions as pure. Set PURE_ZERO to pass this information to the C++ parser. */ if (tok->val.str.len == 1 && *tok->val.str.text == '0') add_flags = PURE_ZERO; *value = interpret_integer (tok, flags, &overflow); break; case CPP_N_FLOATING: *value = interpret_float (tok, flags, suffix, &overflow); break; default: gcc_unreachable (); } if (flags & CPP_N_USERDEF) { char *str; tree literal; tree suffix_id = get_identifier (suffix); int len = tok->val.str.len - strlen (suffix); /* If this is going to be used as a C string to pass to a raw literal operator, we need to add a trailing NUL. */ tree num_string = build_string (len + 1, (const char *) tok->val.str.text); TREE_TYPE (num_string) = char_array_type_node; num_string = fix_string_type (num_string); str = CONST_CAST (char *, TREE_STRING_POINTER (num_string)); str[len] = '\0'; literal = build_userdef_literal (suffix_id, *value, overflow, num_string); *value = literal; } } break; case CPP_ATSIGN: /* An @ may give the next token special significance in Objective-C. */ if (c_dialect_objc ()) { location_t atloc = *loc; location_t newloc; retry_at: tok = cpp_get_token_with_location (parse_in, &newloc); type = tok->type; switch (type) { case CPP_PADDING: goto retry_at; case CPP_STRING: case CPP_WSTRING: case CPP_STRING16: case CPP_STRING32: case CPP_UTF8STRING: type = lex_string (tok, value, true, true); break; case CPP_NAME: *value = HT_IDENT_TO_GCC_IDENT (HT_NODE (tok->val.node.node)); if (OBJC_IS_AT_KEYWORD (C_RID_CODE (*value)) || OBJC_IS_CXX_KEYWORD (C_RID_CODE (*value))) { type = CPP_AT_NAME; /* Note the complication: if we found an OBJC_CXX keyword, for example, 'class', we will be returning a token of type CPP_AT_NAME and rid code RID_CLASS (not RID_AT_CLASS). The language parser needs to convert that to RID_AT_CLASS. */ break; } /* FALLTHROUGH */ default: /* ... or not. */ error_at (atloc, "stray %<@%> in program"); *loc = newloc; goto retry_after_at; } break; } /* FALLTHROUGH */ case CPP_HASH: case CPP_PASTE: { unsigned char name[8]; *cpp_spell_token (parse_in, tok, name, true) = 0; error_at (*loc, "stray %qs in program", name); } goto retry; case CPP_OTHER: { cppchar_t c = tok->val.str.text[0]; if (c == '"' || c == '\'') error ("missing terminating %c character", (int) c); else if (ISGRAPH (c)) error ("stray %qc in program", (int) c); else error ("stray %<\\%o%> in program", (int) c); } goto retry; case CPP_CHAR_USERDEF: case CPP_WCHAR_USERDEF: case CPP_CHAR16_USERDEF: case CPP_CHAR32_USERDEF: { tree literal; cpp_token temp_tok = *tok; const char *suffix = cpp_get_userdef_suffix (tok); temp_tok.val.str.len -= strlen (suffix); temp_tok.type = cpp_userdef_char_remove_type (type); literal = build_userdef_literal (get_identifier (suffix), lex_charconst (&temp_tok), OT_NONE, NULL_TREE); *value = literal; } break; case CPP_CHAR: case CPP_WCHAR: case CPP_CHAR16: case CPP_CHAR32: *value = lex_charconst (tok); break; case CPP_STRING_USERDEF: case CPP_WSTRING_USERDEF: case CPP_STRING16_USERDEF: case CPP_STRING32_USERDEF: case CPP_UTF8STRING_USERDEF: { tree literal, string; const char *suffix = cpp_get_userdef_suffix (tok); string = build_string (tok->val.str.len - strlen (suffix), (const char *) tok->val.str.text); literal = build_userdef_literal (get_identifier (suffix), string, OT_NONE, NULL_TREE); *value = literal; } break; case CPP_STRING: case CPP_WSTRING: case CPP_STRING16: case CPP_STRING32: case CPP_UTF8STRING: if ((lex_flags & C_LEX_STRING_NO_JOIN) == 0) { type = lex_string (tok, value, false, (lex_flags & C_LEX_STRING_NO_TRANSLATE) == 0); break; } *value = build_string (tok->val.str.len, (const char *) tok->val.str.text); break; case CPP_PRAGMA: *value = build_int_cst (integer_type_node, tok->val.pragma); break; /* These tokens should not be visible outside cpplib. */ case CPP_HEADER_NAME: case CPP_MACRO_ARG: gcc_unreachable (); /* CPP_COMMENT will appear when compiling with -C and should be ignored. */ case CPP_COMMENT: goto retry; default: *value = NULL_TREE; break; } if (cpp_flags) *cpp_flags = tok->flags | add_flags; if (!no_more_pch) { no_more_pch = true; c_common_no_more_pch (); } timevar_pop (TV_CPP); return type; } /* Returns the narrowest C-visible unsigned type, starting with the minimum specified by FLAGS, that can fit HIGH:LOW, or itk_none if there isn't one. */ static enum integer_type_kind narrowest_unsigned_type (unsigned HOST_WIDE_INT low, unsigned HOST_WIDE_INT high, unsigned int flags) { int itk; if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) itk = itk_unsigned_int; else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) itk = itk_unsigned_long; else itk = itk_unsigned_long_long; for (; itk < itk_none; itk += 2 /* skip unsigned types */) { tree upper; if (integer_types[itk] == NULL_TREE) continue; upper = TYPE_MAX_VALUE (integer_types[itk]); if ((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (upper) > high || ((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (upper) == high && TREE_INT_CST_LOW (upper) >= low)) return (enum integer_type_kind) itk; } return itk_none; } /* Ditto, but narrowest signed type. */ static enum integer_type_kind narrowest_signed_type (unsigned HOST_WIDE_INT low, unsigned HOST_WIDE_INT high, unsigned int flags) { int itk; if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) itk = itk_int; else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) itk = itk_long; else itk = itk_long_long; for (; itk < itk_none; itk += 2 /* skip signed types */) { tree upper; if (integer_types[itk] == NULL_TREE) continue; upper = TYPE_MAX_VALUE (integer_types[itk]); if ((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (upper) > high || ((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (upper) == high && TREE_INT_CST_LOW (upper) >= low)) return (enum integer_type_kind) itk; } return itk_none; } /* Interpret TOKEN, an integer with FLAGS as classified by cpplib. */ static tree interpret_integer (const cpp_token *token, unsigned int flags, enum overflow_type *overflow) { tree value, type; enum integer_type_kind itk; cpp_num integer; *overflow = OT_NONE; integer = cpp_interpret_integer (parse_in, token, flags); if (integer.overflow) *overflow = OT_OVERFLOW; /* The type of a constant with a U suffix is straightforward. */ if (flags & CPP_N_UNSIGNED) itk = narrowest_unsigned_type (integer.low, integer.high, flags); else { /* The type of a potentially-signed integer constant varies depending on the base it's in, the standard in use, and the length suffixes. */ enum integer_type_kind itk_u = narrowest_unsigned_type (integer.low, integer.high, flags); enum integer_type_kind itk_s = narrowest_signed_type (integer.low, integer.high, flags); /* In both C89 and C99, octal and hex constants may be signed or unsigned, whichever fits tighter. We do not warn about this choice differing from the traditional choice, as the constant is probably a bit pattern and either way will work. */ if ((flags & CPP_N_RADIX) != CPP_N_DECIMAL) itk = MIN (itk_u, itk_s); else { /* In C99, decimal constants are always signed. In C89, decimal constants that don't fit in long have undefined behavior; we try to make them unsigned long. In GCC's extended C89, that last is true of decimal constants that don't fit in long long, too. */ itk = itk_s; if (itk_s > itk_u && itk_s > itk_long) { if (!flag_isoc99) { if (itk_u < itk_unsigned_long) itk_u = itk_unsigned_long; itk = itk_u; warning (0, "this decimal constant is unsigned only in ISO C90"); } else warning (OPT_Wtraditional, "this decimal constant would be unsigned in ISO C90"); } } } if (itk == itk_none) /* cpplib has already issued a warning for overflow. */ type = ((flags & CPP_N_UNSIGNED) ? widest_unsigned_literal_type_node : widest_integer_literal_type_node); else { type = integer_types[itk]; if (itk > itk_unsigned_long && (flags & CPP_N_WIDTH) != CPP_N_LARGE) emit_diagnostic ((c_dialect_cxx () ? cxx_dialect == cxx98 : !flag_isoc99) ? DK_PEDWARN : DK_WARNING, input_location, OPT_Wlong_long, (flags & CPP_N_UNSIGNED) ? "integer constant is too large for %<unsigned long%> type" : "integer constant is too large for %<long%> type"); } value = build_int_cst_wide (type, integer.low, integer.high); /* Convert imaginary to a complex type. */ if (flags & CPP_N_IMAGINARY) value = build_complex (NULL_TREE, build_int_cst (type, 0), value); return value; } /* Interpret TOKEN, a floating point number with FLAGS as classified by cpplib. For C++0X SUFFIX may contain a user-defined literal suffix. */ static tree interpret_float (const cpp_token *token, unsigned int flags, const char *suffix, enum overflow_type *overflow) { tree type; tree const_type; tree value; REAL_VALUE_TYPE real; REAL_VALUE_TYPE real_trunc; char *copy; size_t copylen; *overflow = OT_NONE; /* Default (no suffix) depends on whether the FLOAT_CONST_DECIMAL64 pragma has been used and is either double or _Decimal64. Types that are not allowed with decimal float default to double. */ if (flags & CPP_N_DEFAULT) { flags ^= CPP_N_DEFAULT; flags |= CPP_N_MEDIUM; if (((flags & CPP_N_HEX) == 0) && ((flags & CPP_N_IMAGINARY) == 0)) { warning (OPT_Wunsuffixed_float_constants, "unsuffixed float constant"); if (float_const_decimal64_p ()) flags |= CPP_N_DFLOAT; } } /* Decode _Fract and _Accum. */ if (flags & CPP_N_FRACT || flags & CPP_N_ACCUM) return interpret_fixed (token, flags); /* Decode type based on width and properties. */ if (flags & CPP_N_DFLOAT) if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) type = dfloat128_type_node; else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) type = dfloat32_type_node; else type = dfloat64_type_node; else if (flags & CPP_N_WIDTH_MD) { char suffix; enum machine_mode mode; if ((flags & CPP_N_WIDTH_MD) == CPP_N_MD_W) suffix = 'w'; else suffix = 'q'; mode = targetm.c.mode_for_suffix (suffix); if (mode == VOIDmode) { error ("unsupported non-standard suffix on floating constant"); return error_mark_node; } else pedwarn (input_location, OPT_Wpedantic, "non-standard suffix on floating constant"); type = c_common_type_for_mode (mode, 0); gcc_assert (type); } else if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) type = long_double_type_node; else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL || flag_single_precision_constant) type = float_type_node; else type = double_type_node; const_type = excess_precision_type (type); if (!const_type) const_type = type; /* Copy the constant to a nul-terminated buffer. If the constant has any suffixes, cut them off; REAL_VALUE_ATOF/ REAL_VALUE_HTOF can't handle them. */ copylen = token->val.str.len; if (flags & CPP_N_USERDEF) copylen -= strlen (suffix); else if (flags & CPP_N_DFLOAT) copylen -= 2; else { if ((flags & CPP_N_WIDTH) != CPP_N_MEDIUM) /* Must be an F or L or machine defined suffix. */ copylen--; if (flags & CPP_N_IMAGINARY) /* I or J suffix. */ copylen--; } copy = (char *) alloca (copylen + 1); if (cxx_dialect > cxx11) { size_t maxlen = 0; for (size_t i = 0; i < copylen; ++i) if (token->val.str.text[i] != '\'') copy[maxlen++] = token->val.str.text[i]; copy[maxlen] = '\0'; } else { memcpy (copy, token->val.str.text, copylen); copy[copylen] = '\0'; } real_from_string3 (&real, copy, TYPE_MODE (const_type)); if (const_type != type) /* Diagnosing if the result of converting the value with excess precision to the semantic type would overflow (with associated double rounding) is more appropriate than diagnosing if the result of converting the string directly to the semantic type would overflow. */ real_convert (&real_trunc, TYPE_MODE (type), &real); /* Both C and C++ require a diagnostic for a floating constant outside the range of representable values of its type. Since we have __builtin_inf* to produce an infinity, this is now a mandatory pedwarn if the target does not support infinities. */ if (REAL_VALUE_ISINF (real) || (const_type != type && REAL_VALUE_ISINF (real_trunc))) { *overflow = OT_OVERFLOW; if (!(flags & CPP_N_USERDEF)) { if (!MODE_HAS_INFINITIES (TYPE_MODE (type))) pedwarn (input_location, 0, "floating constant exceeds range of %qT", type); else warning (OPT_Woverflow, "floating constant exceeds range of %qT", type); } } /* We also give a warning if the value underflows. */ else if (REAL_VALUES_EQUAL (real, dconst0) || (const_type != type && REAL_VALUES_EQUAL (real_trunc, dconst0))) { REAL_VALUE_TYPE realvoidmode; int oflow = real_from_string (&realvoidmode, copy); *overflow = (oflow == 0 ? OT_NONE : (oflow < 0 ? OT_UNDERFLOW : OT_OVERFLOW)); if (!(flags & CPP_N_USERDEF)) { if (oflow < 0 || !REAL_VALUES_EQUAL (realvoidmode, dconst0)) warning (OPT_Woverflow, "floating constant truncated to zero"); } } /* Create a node with determined type and value. */ value = build_real (const_type, real); if (flags & CPP_N_IMAGINARY) { value = build_complex (NULL_TREE, convert (const_type, integer_zero_node), value); if (type != const_type) { const_type = TREE_TYPE (value); type = build_complex_type (type); } } if (type != const_type) value = build1 (EXCESS_PRECISION_EXPR, type, value); return value; } /* Interpret TOKEN, a fixed-point number with FLAGS as classified by cpplib. */ static tree interpret_fixed (const cpp_token *token, unsigned int flags) { tree type; tree value; FIXED_VALUE_TYPE fixed; char *copy; size_t copylen; copylen = token->val.str.len; if (flags & CPP_N_FRACT) /* _Fract. */ { if (flags & CPP_N_UNSIGNED) /* Unsigned _Fract. */ { if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) { type = unsigned_long_long_fract_type_node; copylen -= 4; } else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) { type = unsigned_long_fract_type_node; copylen -= 3; } else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) { type = unsigned_short_fract_type_node; copylen -= 3; } else { type = unsigned_fract_type_node; copylen -= 2; } } else /* Signed _Fract. */ { if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) { type = long_long_fract_type_node; copylen -= 3; } else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) { type = long_fract_type_node; copylen -= 2; } else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) { type = short_fract_type_node; copylen -= 2; } else { type = fract_type_node; copylen --; } } } else /* _Accum. */ { if (flags & CPP_N_UNSIGNED) /* Unsigned _Accum. */ { if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) { type = unsigned_long_long_accum_type_node; copylen -= 4; } else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) { type = unsigned_long_accum_type_node; copylen -= 3; } else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) { type = unsigned_short_accum_type_node; copylen -= 3; } else { type = unsigned_accum_type_node; copylen -= 2; } } else /* Signed _Accum. */ { if ((flags & CPP_N_WIDTH) == CPP_N_LARGE) { type = long_long_accum_type_node; copylen -= 3; } else if ((flags & CPP_N_WIDTH) == CPP_N_MEDIUM) { type = long_accum_type_node; copylen -= 2; } else if ((flags & CPP_N_WIDTH) == CPP_N_SMALL) { type = short_accum_type_node; copylen -= 2; } else { type = accum_type_node; copylen --; } } } copy = (char *) alloca (copylen + 1); memcpy (copy, token->val.str.text, copylen); copy[copylen] = '\0'; fixed_from_string (&fixed, copy, TYPE_MODE (type)); /* Create a node with determined type and value. */ value = build_fixed (type, fixed); return value; } /* Convert a series of STRING, WSTRING, STRING16, STRING32 and/or UTF8STRING tokens into a tree, performing string constant concatenation. TOK is the first of these. VALP is the location to write the string into. OBJC_STRING indicates whether an '@' token preceded the incoming token (in that case, the strings can either be ObjC strings, preceded by a single '@', or normal strings, not preceded by '@'. The result will be a CPP_OBJC_STRING). Returns the CPP token type of the result (CPP_STRING, CPP_WSTRING, CPP_STRING32, CPP_STRING16, CPP_UTF8STRING, or CPP_OBJC_STRING). This is unfortunately more work than it should be. If any of the strings in the series has an L prefix, the result is a wide string (6.4.5p4). Whether or not the result is a wide string affects the meaning of octal and hexadecimal escapes (6.4.4.4p6,9). But escape sequences do not continue across the boundary between two strings in a series (6.4.5p7), so we must not lose the boundaries. Therefore cpp_interpret_string takes a vector of cpp_string structures, which we must arrange to provide. */ static enum cpp_ttype lex_string (const cpp_token *tok, tree *valp, bool objc_string, bool translate) { tree value; size_t concats = 0; struct obstack str_ob; cpp_string istr; enum cpp_ttype type = tok->type; /* Try to avoid the overhead of creating and destroying an obstack for the common case of just one string. */ cpp_string str = tok->val.str; cpp_string *strs = &str; /* objc_at_sign_was_seen is only used when doing Objective-C string concatenation. It is 'true' if we have seen an '@' before the current string, and 'false' if not. We must see exactly one or zero '@' before each string. */ bool objc_at_sign_was_seen = false; retry: tok = cpp_get_token (parse_in); switch (tok->type) { case CPP_PADDING: goto retry; case CPP_ATSIGN: if (objc_string) { if (objc_at_sign_was_seen) error ("repeated %<@%> before Objective-C string"); objc_at_sign_was_seen = true; goto retry; } /* FALLTHROUGH */ default: break; case CPP_WSTRING: case CPP_STRING16: case CPP_STRING32: case CPP_UTF8STRING: if (type != tok->type) { if (type == CPP_STRING) type = tok->type; else error ("unsupported non-standard concatenation of string literals"); } case CPP_STRING: if (!concats) { gcc_obstack_init (&str_ob); obstack_grow (&str_ob, &str, sizeof (cpp_string)); } concats++; obstack_grow (&str_ob, &tok->val.str, sizeof (cpp_string)); if (objc_string) objc_at_sign_was_seen = false; goto retry; } /* It is an error if we saw a '@' with no following string. */ if (objc_at_sign_was_seen) error ("stray %<@%> in program"); /* We have read one more token than we want. */ _cpp_backup_tokens (parse_in, 1); if (concats) strs = XOBFINISH (&str_ob, cpp_string *); if (concats && !objc_string && !in_system_header) warning (OPT_Wtraditional, "traditional C rejects string constant concatenation"); if ((translate ? cpp_interpret_string : cpp_interpret_string_notranslate) (parse_in, strs, concats + 1, &istr, type)) { value = build_string (istr.len, (const char *) istr.text); free (CONST_CAST (unsigned char *, istr.text)); } else { /* Callers cannot generally handle error_mark_node in this context, so return the empty string instead. cpp_interpret_string has issued an error. */ switch (type) { default: case CPP_STRING: case CPP_UTF8STRING: value = build_string (1, ""); break; case CPP_STRING16: value = build_string (TYPE_PRECISION (char16_type_node) / TYPE_PRECISION (char_type_node), "\0"); /* char16_t is 16 bits */ break; case CPP_STRING32: value = build_string (TYPE_PRECISION (char32_type_node) / TYPE_PRECISION (char_type_node), "\0\0\0"); /* char32_t is 32 bits */ break; case CPP_WSTRING: value = build_string (TYPE_PRECISION (wchar_type_node) / TYPE_PRECISION (char_type_node), "\0\0\0"); /* widest supported wchar_t is 32 bits */ break; } } switch (type) { default: case CPP_STRING: case CPP_UTF8STRING: TREE_TYPE (value) = char_array_type_node; break; case CPP_STRING16: TREE_TYPE (value) = char16_array_type_node; break; case CPP_STRING32: TREE_TYPE (value) = char32_array_type_node; break; case CPP_WSTRING: TREE_TYPE (value) = wchar_array_type_node; } *valp = fix_string_type (value); if (concats) obstack_free (&str_ob, 0); return objc_string ? CPP_OBJC_STRING : type; } /* Converts a (possibly wide) character constant token into a tree. */ static tree lex_charconst (const cpp_token *token) { cppchar_t result; tree type, value; unsigned int chars_seen; int unsignedp = 0; result = cpp_interpret_charconst (parse_in, token, &chars_seen, &unsignedp); if (token->type == CPP_WCHAR) type = wchar_type_node; else if (token->type == CPP_CHAR32) type = char32_type_node; else if (token->type == CPP_CHAR16) type = char16_type_node; /* In C, a character constant has type 'int'. In C++ 'char', but multi-char charconsts have type 'int'. */ else if (!c_dialect_cxx () || chars_seen > 1) type = integer_type_node; else type = char_type_node; /* Cast to cppchar_signed_t to get correct sign-extension of RESULT before possibly widening to HOST_WIDE_INT for build_int_cst. */ if (unsignedp || (cppchar_signed_t) result >= 0) value = build_int_cst_wide (type, result, 0); else value = build_int_cst_wide (type, (cppchar_signed_t) result, -1); return value; }
Hellybean/SaberMod_ROM_Toolchain
gcc/c-family/c-lex.c
C
gpl-2.0
32,615
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2014 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using System.Collections.Generic; /// <summary> /// This script should be attached to each camera that's used to draw the objects with /// UI components on them. This may mean only one camera (main camera or your UI camera), /// or multiple cameras if you happen to have multiple viewports. Failing to attach this /// script simply means that objects drawn by this camera won't receive UI notifications: /// /// * OnHover (isOver) is sent when the mouse hovers over a collider or moves away. /// * OnPress (isDown) is sent when a mouse button gets pressed on the collider. /// * OnSelect (selected) is sent when a mouse button is released on the same object as it was pressed on. /// * OnClick () is sent with the same conditions as OnSelect, with the added check to see if the mouse has not moved much. /// UICamera.currentTouchID tells you which button was clicked. /// * OnDoubleClick () is sent when the click happens twice within a fourth of a second. /// UICamera.currentTouchID tells you which button was clicked. /// /// * OnDragStart () is sent to a game object under the touch just before the OnDrag() notifications begin. /// * OnDrag (delta) is sent to an object that's being dragged. /// * OnDragOver (draggedObject) is sent to a game object when another object is dragged over its area. /// * OnDragOut (draggedObject) is sent to a game object when another object is dragged out of its area. /// * OnDragEnd () is sent to a dragged object when the drag event finishes. /// /// * OnTooltip (show) is sent when the mouse hovers over a collider for some time without moving. /// * OnScroll (float delta) is sent out when the mouse scroll wheel is moved. /// * OnKey (KeyCode key) is sent when keyboard or controller input is used. /// </summary> [ExecuteInEditMode] [AddComponentMenu("NGUI/UI/NGUI Event System (UICamera)")] [RequireComponent(typeof(Camera))] public class UICamera : MonoBehaviour { public enum ControlScheme { Mouse, Touch, Controller, } /// <summary> /// Whether the touch event will be sending out the OnClick notification at the end. /// </summary> public enum ClickNotification { None, Always, BasedOnDelta, } /// <summary> /// Ambiguous mouse, touch, or controller event. /// </summary> public class MouseOrTouch { public Vector2 pos; // Current position of the mouse or touch event public Vector2 lastPos; // Previous position of the mouse or touch event public Vector2 delta; // Delta since last update public Vector2 totalDelta; // Delta since the event started being tracked public Camera pressedCam; // Camera that the OnPress(true) was fired with public GameObject last; // Last object under the touch or mouse public GameObject current; // Current game object under the touch or mouse public GameObject pressed; // Last game object to receive OnPress public GameObject dragged; // Game object that's being dragged public float clickTime = 0f; // The last time a click event was sent out public ClickNotification clickNotification = ClickNotification.Always; public bool touchBegan = true; public bool pressStarted = false; public bool dragStarted = false; } /// <summary> /// Camera type controls how raycasts are handled by the UICamera. /// </summary> public enum EventType { World, // Perform a Physics.Raycast and sort by distance to the point that was hit. UI, // Perform a Physics.Raycast and sort by widget depth. #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 Unity2D, // Perform a Physics2D.OverlapPoint #endif } /// <summary> /// List of all active cameras in the scene. /// </summary> static public BetterList<UICamera> list = new BetterList<UICamera>(); public delegate void OnScreenResize (); /// <summary> /// Delegate triggered when the screen size changes for any reason. /// Subscribe to it if you don't want to compare Screen.width and Screen.height each frame. /// </summary> static public OnScreenResize onScreenResize; /// <summary> /// Event type -- use "UI" for your user interfaces, and "World" for your game camera. /// This setting changes how raycasts are handled. Raycasts have to be more complicated for UI cameras. /// </summary> public EventType eventType = EventType.UI; /// <summary> /// Which layers will receive events. /// </summary> public LayerMask eventReceiverMask = -1; /// <summary> /// If 'true', currently hovered object will be shown in the top left corner. /// </summary> public bool debug = false; /// <summary> /// Whether the mouse input is used. /// </summary> public bool useMouse = true; /// <summary> /// Whether the touch-based input is used. /// </summary> public bool useTouch = true; /// <summary> /// Whether multi-touch is allowed. /// </summary> public bool allowMultiTouch = true; /// <summary> /// Whether the keyboard events will be processed. /// </summary> public bool useKeyboard = true; /// <summary> /// Whether the joystick and controller events will be processed. /// </summary> public bool useController = true; [System.Obsolete("Use new OnDragStart / OnDragOver / OnDragOut / OnDragEnd events instead")] public bool stickyPress { get { return true; } } /// <summary> /// Whether the tooltip will disappear as soon as the mouse moves (false) or only if the mouse moves outside of the widget's area (true). /// </summary> public bool stickyTooltip = true; /// <summary> /// How long of a delay to expect before showing the tooltip. /// </summary> public float tooltipDelay = 1f; /// <summary> /// How much the mouse has to be moved after pressing a button before it starts to send out drag events. /// </summary> public float mouseDragThreshold = 4f; /// <summary> /// How far the mouse is allowed to move in pixels before it's no longer considered for click events, if the click notification is based on delta. /// </summary> public float mouseClickThreshold = 10f; /// <summary> /// How much the mouse has to be moved after pressing a button before it starts to send out drag events. /// </summary> public float touchDragThreshold = 40f; /// <summary> /// How far the touch is allowed to move in pixels before it's no longer considered for click events, if the click notification is based on delta. /// </summary> public float touchClickThreshold = 40f; /// <summary> /// Raycast range distance. By default it's as far as the camera can see. /// </summary> public float rangeDistance = -1f; /// <summary> /// Name of the axis used for scrolling. /// </summary> public string scrollAxisName = "Mouse ScrollWheel"; /// <summary> /// Name of the axis used to send up and down key events. /// </summary> public string verticalAxisName = "Vertical"; /// <summary> /// Name of the axis used to send left and right key events. /// </summary> public string horizontalAxisName = "Horizontal"; /// <summary> /// Various keys used by the camera. /// </summary> public KeyCode submitKey0 = KeyCode.Return; public KeyCode submitKey1 = KeyCode.JoystickButton0; public KeyCode cancelKey0 = KeyCode.Escape; public KeyCode cancelKey1 = KeyCode.JoystickButton1; public delegate void OnCustomInput (); /// <summary> /// Custom input processing logic, if desired. For example: WP7 touches. /// Use UICamera.current to get the current camera. /// </summary> static public OnCustomInput onCustomInput; /// <summary> /// Whether tooltips will be shown or not. /// </summary> static public bool showTooltips = true; /// <summary> /// Position of the last touch (or mouse) event. /// </summary> static public Vector2 lastTouchPosition = Vector2.zero; /// <summary> /// Last raycast hit prior to sending out the event. This is useful if you want detailed information /// about what was actually hit in your OnClick, OnHover, and other event functions. /// </summary> static public RaycastHit lastHit; /// <summary> /// UICamera that sent out the event. /// </summary> static public UICamera current = null; /// <summary> /// Last camera active prior to sending out the event. This will always be the camera that actually sent out the event. /// </summary> static public Camera currentCamera = null; /// <summary> /// Current control scheme. Set automatically when events arrive. /// </summary> static public ControlScheme currentScheme = ControlScheme.Mouse; /// <summary> /// ID of the touch or mouse operation prior to sending out the event. Mouse ID is '-1' for left, '-2' for right mouse button, '-3' for middle. /// </summary> static public int currentTouchID = -1; /// <summary> /// Key that triggered the event, if any. /// </summary> static public KeyCode currentKey = KeyCode.None; /// <summary> /// Ray projected into the screen underneath the current touch. /// </summary> static public Ray currentRay { get { return (currentCamera != null && currentTouch != null) ? currentCamera.ScreenPointToRay(currentTouch.pos) : new Ray(); } } /// <summary> /// Current touch, set before any event function gets called. /// </summary> static public MouseOrTouch currentTouch = null; /// <summary> /// Whether an input field currently has focus. /// </summary> static public bool inputHasFocus = false; /// <summary> /// If set, this game object will receive all events regardless of whether they were handled or not. /// </summary> static public GameObject genericEventHandler; /// <summary> /// If events don't get handled, they will be forwarded to this game object. /// </summary> static public GameObject fallThrough; // Selected widget (for input) static GameObject mCurrentSelection = null; static GameObject mNextSelection = null; static ControlScheme mNextScheme = ControlScheme.Controller; // Mouse events static MouseOrTouch[] mMouse = new MouseOrTouch[] { new MouseOrTouch(), new MouseOrTouch(), new MouseOrTouch() }; // The last object to receive OnHover static GameObject mHover; // Joystick/controller/keyboard event static public MouseOrTouch controller = new MouseOrTouch(); // Used to ensure that joystick-based controls don't trigger that often static float mNextEvent = 0f; // List of currently active touches static Dictionary<int, MouseOrTouch> mTouches = new Dictionary<int, MouseOrTouch>(); // Used to detect screen dimension changes static int mWidth = 0; static int mHeight = 0; // Tooltip widget (mouse only) GameObject mTooltip = null; // Mouse input is turned off on iOS Camera mCam = null; float mTooltipTime = 0f; float mNextRaycast = 0f; /// <summary> /// Helper function that determines if this script should be handling the events. /// </summary> bool handlesEvents { get { return eventHandler == this; } } /// <summary> /// Caching is always preferable for performance. /// </summary> public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } } /// <summary> /// Set to 'true' just before OnDrag-related events are sent. No longer needed, but kept for backwards compatibility. /// </summary> static public bool isDragging = false; /// <summary> /// The object hit by the last Raycast that was the result of a mouse or touch event. /// </summary> static public GameObject hoveredObject; /// <summary> /// Option to manually set the selected game object. /// </summary> static public GameObject selectedObject { get { return mCurrentSelection; } set { SetSelection(value, UICamera.currentScheme); } } /// <summary> /// Change the selection. /// </summary> static protected void SetSelection (GameObject go, ControlScheme scheme) { if (mNextSelection != null) { mNextSelection = go; } else if (mCurrentSelection != go) { if (mCurrentSelection != null) { UICamera uicam = FindCameraForLayer(mCurrentSelection.layer); if (uicam != null) { current = uicam; currentCamera = uicam.mCam; UICamera.currentScheme = scheme; Notify(mCurrentSelection, "OnSelect", false); current = null; } } mCurrentSelection = null; mNextSelection = go; mNextScheme = scheme; if (UICamera.list.size > 0) { UICamera cam = (mNextSelection != null) ? FindCameraForLayer(mNextSelection.layer) : UICamera.list[0]; if (cam != null) cam.StartCoroutine(cam.ChangeSelection()); } } } /// <summary> /// Selection change is delayed on purpose. This way selection changes during event processing won't cause /// the newly selected widget to continue processing when it is it's turn. Example: pressing 'tab' on one /// button selects the next button, and then it also processes its 'tab' in turn, selecting the next one. /// </summary> System.Collections.IEnumerator ChangeSelection () { yield return new WaitForEndOfFrame(); mCurrentSelection = mNextSelection; mNextSelection = null; if (mCurrentSelection != null) { current = this; currentCamera = mCam; UICamera.currentScheme = mNextScheme; Notify(mCurrentSelection, "OnSelect", true); current = null; } } /// <summary> /// Number of active touches from all sources. /// </summary> static public int touchCount { get { int count = 0; foreach (KeyValuePair<int, MouseOrTouch> touch in mTouches) if (touch.Value.pressed != null) ++count; for (int i = 0; i < mMouse.Length; ++i) if (mMouse[i].pressed != null) ++count; if (controller.pressed != null) ++count; return count; } } /// <summary> /// Number of active drag events from all sources. /// </summary> static public int dragCount { get { int count = 0; foreach (KeyValuePair<int, MouseOrTouch> touch in mTouches) if (touch.Value.dragged != null) ++count; for (int i = 0; i < mMouse.Length; ++i) if (mMouse[i].dragged != null) ++count; if (controller.dragged != null) ++count; return count; } } /// <summary> /// Convenience function that returns the main HUD camera. /// </summary> static public Camera mainCamera { get { UICamera mouse = eventHandler; return (mouse != null) ? mouse.cachedCamera : null; } } /// <summary> /// Event handler for all types of events. /// </summary> static public UICamera eventHandler { get { for (int i = 0; i < list.size; ++i) { // Invalid or inactive entry -- keep going UICamera cam = list.buffer[i]; if (cam == null || !cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue; return cam; } return null; } } /// <summary> /// Static comparison function used for sorting. /// </summary> static int CompareFunc (UICamera a, UICamera b) { if (a.cachedCamera.depth < b.cachedCamera.depth) return 1; if (a.cachedCamera.depth > b.cachedCamera.depth) return -1; return 0; } struct DepthEntry { public int depth; public RaycastHit hit; } static DepthEntry mHit = new DepthEntry(); static BetterList<DepthEntry> mHits = new BetterList<DepthEntry>(); static RaycastHit mEmpty = new RaycastHit(); /// <summary> /// Returns the object under the specified position. /// </summary> static public bool Raycast (Vector3 inPos, out RaycastHit hit) { for (int i = 0; i < list.size; ++i) { UICamera cam = list.buffer[i]; // Skip inactive scripts if (!cam.enabled || !NGUITools.GetActive(cam.gameObject)) continue; // Convert to view space currentCamera = cam.cachedCamera; Vector3 pos = currentCamera.ScreenToViewportPoint(inPos); if (float.IsNaN(pos.x) || float.IsNaN(pos.y)) continue; // If it's outside the camera's viewport, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue; // Cast a ray into the screen Ray ray = currentCamera.ScreenPointToRay(inPos); // Raycast into the screen int mask = currentCamera.cullingMask & (int)cam.eventReceiverMask; float dist = (cam.rangeDistance > 0f) ? cam.rangeDistance : currentCamera.farClipPlane - currentCamera.nearClipPlane; if (cam.eventType == EventType.World) { if (Physics.Raycast(ray, out hit, dist, mask)) { hoveredObject = hit.collider.gameObject; return true; } continue; } else if (cam.eventType == EventType.UI) { RaycastHit[] hits = Physics.RaycastAll(ray, dist, mask); if (hits.Length > 1) { for (int b = 0; b < hits.Length; ++b) { GameObject go = hits[b].collider.gameObject; UIWidget w = go.GetComponent<UIWidget>(); if (w != null) { if (!w.isVisible) continue; if (w.hitCheck != null && !w.hitCheck(hits[b].point)) continue; } else { UIRect rect = NGUITools.FindInParents<UIRect>(go); if (rect != null && rect.finalAlpha < 0.001f) continue; } mHit.depth = NGUITools.CalculateRaycastDepth(go); if (mHit.depth != int.MaxValue) { mHit.hit = hits[b]; mHits.Add(mHit); } } mHits.Sort(delegate(DepthEntry r1, DepthEntry r2) { return r2.depth.CompareTo(r1.depth); }); for (int b = 0; b < mHits.size; ++b) { #if UNITY_FLASH if (IsVisible(mHits.buffer[b])) #else if (IsVisible(ref mHits.buffer[b])) #endif { hit = mHits[b].hit; hoveredObject = hit.collider.gameObject; mHits.Clear(); return true; } } mHits.Clear(); } else if (hits.Length == 1) { Collider c = hits[0].collider; UIWidget w = c.GetComponent<UIWidget>(); if (w != null) { if (!w.isVisible) continue; if (w.hitCheck != null && !w.hitCheck(hits[0].point)) continue; } else { UIRect rect = NGUITools.FindInParents<UIRect>(c.gameObject); if (rect != null && rect.finalAlpha < 0.001f) continue; } if (IsVisible(ref hits[0])) { hit = hits[0]; hoveredObject = hit.collider.gameObject; return true; } } continue; } #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 else if (cam.eventType == EventType.Unity2D) { if (m2DPlane.Raycast(ray, out dist)) { Collider2D c2d = Physics2D.OverlapPoint(ray.GetPoint(dist), mask); if (c2d) { hit = lastHit; hit.point = pos; hoveredObject = c2d.gameObject; return true; } } continue; } #endif } hit = mEmpty; return false; } #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 static Plane m2DPlane = new Plane(Vector3.back, 0f); #endif /// <summary> /// Helper function to check if the specified hit is visible by the panel. /// </summary> static bool IsVisible (ref RaycastHit hit) { UIPanel panel = NGUITools.FindInParents<UIPanel>(hit.collider.gameObject); if (panel == null || panel.IsVisible(hit.point)) { return true; } return false; } /// <summary> /// Helper function to check if the specified hit is visible by the panel. /// </summary> #if UNITY_FLASH static bool IsVisible (DepthEntry de) #else static bool IsVisible (ref DepthEntry de) #endif { UIPanel panel = NGUITools.FindInParents<UIPanel>(de.hit.collider.gameObject); return (panel == null || panel.IsVisible(de.hit.point)); } /// <summary> /// Whether the specified object should be highlighted. /// </summary> static public bool IsHighlighted (GameObject go) { if (UICamera.currentScheme == UICamera.ControlScheme.Mouse) return (UICamera.hoveredObject == go); if (UICamera.currentScheme == UICamera.ControlScheme.Controller) return (UICamera.selectedObject == go); return false; } /// <summary> /// Find the camera responsible for handling events on objects of the specified layer. /// </summary> static public UICamera FindCameraForLayer (int layer) { int layerMask = 1 << layer; for (int i = 0; i < list.size; ++i) { UICamera cam = list.buffer[i]; Camera uc = cam.cachedCamera; if ((uc != null) && (uc.cullingMask & layerMask) != 0) return cam; } return null; } /// <summary> /// Using the keyboard will result in 1 or -1, depending on whether up or down keys have been pressed. /// </summary> static int GetDirection (KeyCode up, KeyCode down) { if (Input.GetKeyDown(up)) return 1; if (Input.GetKeyDown(down)) return -1; return 0; } /// <summary> /// Using the keyboard will result in 1 or -1, depending on whether up or down keys have been pressed. /// </summary> static int GetDirection (KeyCode up0, KeyCode up1, KeyCode down0, KeyCode down1) { if (Input.GetKeyDown(up0) || Input.GetKeyDown(up1)) return 1; if (Input.GetKeyDown(down0) || Input.GetKeyDown(down1)) return -1; return 0; } /// <summary> /// Using the joystick to move the UI results in 1 or -1 if the threshold has been passed, mimicking up/down keys. /// </summary> static int GetDirection (string axis) { float time = RealTime.time; if (mNextEvent < time && !string.IsNullOrEmpty(axis)) { float val = Input.GetAxis(axis); if (val > 0.75f) { mNextEvent = time + 0.25f; return 1; } if (val < -0.75f) { mNextEvent = time + 0.25f; return -1; } } return 0; } /// <summary> /// Generic notification function. Used in place of SendMessage to shorten the code and allow for more than one receiver. /// </summary> static public void Notify (GameObject go, string funcName, object obj) { if (go != null) { go.SendMessage(funcName, obj, SendMessageOptions.DontRequireReceiver); if (genericEventHandler != null && genericEventHandler != go) { genericEventHandler.SendMessage(funcName, obj, SendMessageOptions.DontRequireReceiver); } } } /// <summary> /// Get the details of the specified mouse button. /// </summary> static public MouseOrTouch GetMouse (int button) { return mMouse[button]; } /// <summary> /// Get or create a touch event. /// </summary> static public MouseOrTouch GetTouch (int id) { MouseOrTouch touch = null; if (id < 0) return GetMouse(-id - 1); if (!mTouches.TryGetValue(id, out touch)) { touch = new MouseOrTouch(); touch.touchBegan = true; mTouches.Add(id, touch); } return touch; } /// <summary> /// Remove a touch event from the list. /// </summary> static public void RemoveTouch (int id) { mTouches.Remove(id); } /// <summary> /// Add this camera to the list. /// </summary> void Awake () { mWidth = Screen.width; mHeight = Screen.height; if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 || Application.platform == RuntimePlatform.WP8Player #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || Application.platform == RuntimePlatform.BB10Player #else || Application.platform == RuntimePlatform.BlackBerryPlayer #endif #endif ) { useMouse = false; useTouch = true; if (Application.platform == RuntimePlatform.IPhonePlayer) { useKeyboard = false; useController = false; } } else if (Application.platform == RuntimePlatform.PS3 || Application.platform == RuntimePlatform.XBOX360) { useMouse = false; useTouch = false; useKeyboard = false; useController = true; } // Save the starting mouse position mMouse[0].pos.x = Input.mousePosition.x; mMouse[0].pos.y = Input.mousePosition.y; for (int i = 1; i < 3; ++i) { mMouse[i].pos = mMouse[0].pos; mMouse[i].lastPos = mMouse[0].pos; } lastTouchPosition = mMouse[0].pos; } /// <summary> /// Sort the list when enabled. /// </summary> void OnEnable () { list.Add(this); list.Sort(CompareFunc); } /// <summary> /// Remove this camera from the list. /// </summary> void OnDisable () { list.Remove(this); } #if !UNITY_3_5 && !UNITY_4_0 /// <summary> /// We don't want the camera to send out any kind of mouse events. /// </summary> void Start () { if (eventType != EventType.World && cachedCamera.transparencySortMode != TransparencySortMode.Orthographic) cachedCamera.transparencySortMode = TransparencySortMode.Orthographic; if (Application.isPlaying) cachedCamera.eventMask = 0; if (handlesEvents) NGUIDebug.debugRaycast = debug; } #else void Start () { if (handlesEvents) NGUIDebug.debugRaycast = debug; } #endif #if UNITY_EDITOR void OnValidate () { Start(); } #endif /// <summary> /// Check the input and send out appropriate events. /// </summary> void Update () { // Only the first UI layer should be processing events if (!Application.isPlaying || !handlesEvents) return; current = this; int w = Screen.width; int h = Screen.height; if (w != mWidth || h != mHeight) { mWidth = w; mHeight = h; if (onScreenResize != null) onScreenResize(); } // Process touch events first if (useTouch) ProcessTouches (); else if (useMouse) ProcessMouse(); // Custom input processing if (onCustomInput != null) onCustomInput(); // Clear the selection on the cancel key, but only if mouse input is allowed if (useMouse && mCurrentSelection != null) { if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey0; selectedObject = null; } else if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)) { currentScheme = ControlScheme.Controller; currentKey = cancelKey1; selectedObject = null; } } // If nothing is selected, input focus is lost if (mCurrentSelection == null) inputHasFocus = false; // Update the keyboard and joystick events if (mCurrentSelection != null) ProcessOthers(); // If it's time to show a tooltip, inform the object we're hovering over if (useMouse && mHover != null) { float scroll = !string.IsNullOrEmpty(scrollAxisName) ? Input.GetAxis(scrollAxisName) : 0f; if (scroll != 0f) Notify(mHover, "OnScroll", scroll); if (showTooltips && mTooltipTime != 0f && (mTooltipTime < RealTime.time || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))) { mTooltip = mHover; ShowTooltip(true); } } current = null; } /// <summary> /// Update mouse input. /// </summary> public void ProcessMouse () { // Update the position and delta lastTouchPosition = Input.mousePosition; mMouse[0].delta = lastTouchPosition - mMouse[0].pos; mMouse[0].pos = lastTouchPosition; bool posChanged = mMouse[0].delta.sqrMagnitude > 0.001f; // Propagate the updates to the other mouse buttons for (int i = 1; i < 3; ++i) { mMouse[i].pos = mMouse[0].pos; mMouse[i].delta = mMouse[0].delta; } // Is any button currently pressed? bool isPressed = false; bool justPressed = false; for (int i = 0; i < 3; ++i) { if (Input.GetMouseButtonDown(i)) { currentScheme = ControlScheme.Mouse; justPressed = true; isPressed = true; } else if (Input.GetMouseButton(i)) { currentScheme = ControlScheme.Mouse; isPressed = true; } } // No need to perform raycasts every frame if (isPressed || posChanged || mNextRaycast < RealTime.time) { mNextRaycast = RealTime.time + 0.02f; if (!Raycast(Input.mousePosition, out lastHit)) hoveredObject = fallThrough; if (hoveredObject == null) hoveredObject = genericEventHandler; for (int i = 0; i < 3; ++i) mMouse[i].current = hoveredObject; } bool highlightChanged = (mMouse[0].last != mMouse[0].current); if (highlightChanged) currentScheme = ControlScheme.Mouse; if (isPressed) { // A button was pressed -- cancel the tooltip mTooltipTime = 0f; } else if (posChanged && (!stickyTooltip || highlightChanged)) { if (mTooltipTime != 0f) { // Delay the tooltip mTooltipTime = RealTime.time + tooltipDelay; } else if (mTooltip != null) { // Hide the tooltip ShowTooltip(false); } } // The button was released over a different object -- remove the highlight from the previous if ((justPressed || !isPressed) && mHover != null && highlightChanged) { currentScheme = ControlScheme.Mouse; if (mTooltip != null) ShowTooltip(false); Notify(mHover, "OnHover", false); mHover = null; } // Process all 3 mouse buttons as individual touches for (int i = 0; i < 3; ++i) { bool pressed = Input.GetMouseButtonDown(i); bool unpressed = Input.GetMouseButtonUp(i); if (pressed || unpressed) currentScheme = ControlScheme.Mouse; currentTouch = mMouse[i]; currentTouchID = -1 - i; currentKey = KeyCode.Mouse0 + i; // We don't want to update the last camera while there is a touch happening if (pressed) currentTouch.pressedCam = currentCamera; else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam; // Process the mouse events ProcessTouch(pressed, unpressed); currentKey = KeyCode.None; } currentTouch = null; // If nothing is pressed and there is an object under the touch, highlight it if (!isPressed && highlightChanged) { currentScheme = ControlScheme.Mouse; mTooltipTime = RealTime.time + tooltipDelay; mHover = mMouse[0].current; Notify(mHover, "OnHover", true); } // Update the last value mMouse[0].last = mMouse[0].current; for (int i = 1; i < 3; ++i) mMouse[i].last = mMouse[0].last; } /// <summary> /// Update touch-based events. /// </summary> public void ProcessTouches () { currentScheme = ControlScheme.Touch; for (int i = 0; i < Input.touchCount; ++i) { Touch touch = Input.GetTouch(i); currentTouchID = allowMultiTouch ? touch.fingerId : 1; currentTouch = GetTouch(currentTouchID); bool pressed = (touch.phase == TouchPhase.Began) || currentTouch.touchBegan; bool unpressed = (touch.phase == TouchPhase.Canceled) || (touch.phase == TouchPhase.Ended); currentTouch.touchBegan = false; // Although input.deltaPosition can be used, calculating it manually is safer (just in case) currentTouch.delta = pressed ? Vector2.zero : touch.position - currentTouch.pos; currentTouch.pos = touch.position; // Raycast into the screen if (!Raycast(currentTouch.pos, out lastHit)) hoveredObject = fallThrough; if (hoveredObject == null) hoveredObject = genericEventHandler; currentTouch.last = currentTouch.current; currentTouch.current = hoveredObject; lastTouchPosition = currentTouch.pos; // We don't want to update the last camera while there is a touch happening if (pressed) currentTouch.pressedCam = currentCamera; else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam; // Double-tap support if (touch.tapCount > 1) currentTouch.clickTime = RealTime.time; // Process the events from this touch ProcessTouch(pressed, unpressed); // If the touch has ended, remove it from the list if (unpressed) RemoveTouch(currentTouchID); currentTouch.last = null; currentTouch = null; // Don't consider other touches if (!allowMultiTouch) break; } if (Input.touchCount == 0) { if (useMouse) ProcessMouse(); #if UNITY_EDITOR else ProcessFakeTouches(); #endif } } /// <summary> /// Process fake touch events where the mouse acts as a touch device. /// Useful for testing mobile functionality in the editor. /// </summary> void ProcessFakeTouches () { bool pressed = Input.GetMouseButtonDown(0); bool unpressed = Input.GetMouseButtonUp(0); bool held = Input.GetMouseButton(0); if (pressed || unpressed || held) { currentTouchID = 1; currentTouch = mMouse[0]; currentTouch.touchBegan = pressed; Vector2 pos = Input.mousePosition; currentTouch.delta = pressed ? Vector2.zero : pos - currentTouch.pos; currentTouch.pos = pos; // Raycast into the screen if (!Raycast(currentTouch.pos, out lastHit)) hoveredObject = fallThrough; if (hoveredObject == null) hoveredObject = genericEventHandler; currentTouch.last = currentTouch.current; currentTouch.current = hoveredObject; lastTouchPosition = currentTouch.pos; // We don't want to update the last camera while there is a touch happening if (pressed) currentTouch.pressedCam = currentCamera; else if (currentTouch.pressed != null) currentCamera = currentTouch.pressedCam; // Process the events from this touch ProcessTouch(pressed, unpressed); // If the touch has ended, remove it from the list if (unpressed) RemoveTouch(currentTouchID); currentTouch.last = null; currentTouch = null; } } /// <summary> /// Process keyboard and joystick events. /// </summary> public void ProcessOthers () { currentTouchID = -100; currentTouch = controller; // If this is an input field, ignore WASD and Space key presses inputHasFocus = (mCurrentSelection != null && mCurrentSelection.GetComponent<UIInput>() != null); bool submitKeyDown = false; bool submitKeyUp = false; if (submitKey0 != KeyCode.None && Input.GetKeyDown(submitKey0)) { currentKey = submitKey0; submitKeyDown = true; } if (submitKey1 != KeyCode.None && Input.GetKeyDown(submitKey1)) { currentKey = submitKey1; submitKeyDown = true; } if (submitKey0 != KeyCode.None && Input.GetKeyUp(submitKey0)) { currentKey = submitKey0; submitKeyUp = true; } if (submitKey1 != KeyCode.None && Input.GetKeyUp(submitKey1)) { currentKey = submitKey1; submitKeyUp = true; } if (submitKeyDown || submitKeyUp) { currentScheme = ControlScheme.Controller; currentTouch.last = currentTouch.current; currentTouch.current = mCurrentSelection; ProcessTouch(submitKeyDown, submitKeyUp); currentTouch.last = null; } int vertical = 0; int horizontal = 0; if (useKeyboard) { if (inputHasFocus) { vertical += GetDirection(KeyCode.UpArrow, KeyCode.DownArrow); horizontal += GetDirection(KeyCode.RightArrow, KeyCode.LeftArrow); } else { vertical += GetDirection(KeyCode.W, KeyCode.UpArrow, KeyCode.S, KeyCode.DownArrow); horizontal += GetDirection(KeyCode.D, KeyCode.RightArrow, KeyCode.A, KeyCode.LeftArrow); } } if (useController) { if (!string.IsNullOrEmpty(verticalAxisName)) vertical += GetDirection(verticalAxisName); if (!string.IsNullOrEmpty(horizontalAxisName)) horizontal += GetDirection(horizontalAxisName); } // Send out key notifications if (vertical != 0) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", vertical > 0 ? KeyCode.UpArrow : KeyCode.DownArrow); } if (horizontal != 0) { currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", horizontal > 0 ? KeyCode.RightArrow : KeyCode.LeftArrow); } if (useKeyboard && Input.GetKeyDown(KeyCode.Tab)) { currentKey = KeyCode.Tab; currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.Tab); } // Send out the cancel key notification if (cancelKey0 != KeyCode.None && Input.GetKeyDown(cancelKey0)) { currentKey = cancelKey0; currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.Escape); } if (cancelKey1 != KeyCode.None && Input.GetKeyDown(cancelKey1)) { currentKey = cancelKey1; currentScheme = ControlScheme.Controller; Notify(mCurrentSelection, "OnKey", KeyCode.Escape); } currentTouch = null; currentKey = KeyCode.None; } /// <summary> /// Process the events of the specified touch. /// </summary> public void ProcessTouch (bool pressed, bool unpressed) { // Whether we're using the mouse bool isMouse = (currentScheme == ControlScheme.Mouse); float drag = isMouse ? mouseDragThreshold : touchDragThreshold; float click = isMouse ? mouseClickThreshold : touchClickThreshold; // Send out the press message if (pressed) { if (mTooltip != null) ShowTooltip(false); currentTouch.pressStarted = true; Notify(currentTouch.pressed, "OnPress", false); currentTouch.pressed = currentTouch.current; currentTouch.dragged = currentTouch.current; currentTouch.clickNotification = ClickNotification.BasedOnDelta; currentTouch.totalDelta = Vector2.zero; currentTouch.dragStarted = false; Notify(currentTouch.pressed, "OnPress", true); // Clear the selection if (currentTouch.pressed != mCurrentSelection) { if (mTooltip != null) ShowTooltip(false); currentScheme = ControlScheme.Touch; selectedObject = null; } } else if (currentTouch.pressed != null && (currentTouch.delta.magnitude != 0f || currentTouch.current != currentTouch.last)) { // Keep track of the total movement currentTouch.totalDelta += currentTouch.delta; float mag = currentTouch.totalDelta.magnitude; bool justStarted = false; // If the drag process hasn't started yet but we've already moved off the object, start it immediately if (!currentTouch.dragStarted && currentTouch.last != currentTouch.current) { currentTouch.dragStarted = true; currentTouch.delta = currentTouch.totalDelta; // OnDragOver is sent for consistency, so that OnDragOut is always preceded by OnDragOver isDragging = true; Notify(currentTouch.dragged, "OnDragStart", null); Notify(currentTouch.last, "OnDragOver", currentTouch.dragged); isDragging = false; } else if (!currentTouch.dragStarted && drag < mag) { // If the drag event has not yet started, see if we've dragged the touch far enough to start it justStarted = true; currentTouch.dragStarted = true; currentTouch.delta = currentTouch.totalDelta; } // If we're dragging the touch, send out drag events if (currentTouch.dragStarted) { if (mTooltip != null) ShowTooltip(false); isDragging = true; bool isDisabled = (currentTouch.clickNotification == ClickNotification.None); if (justStarted) { Notify(currentTouch.dragged, "OnDragStart", null); Notify(currentTouch.current, "OnDragOver", currentTouch.dragged); } else if (currentTouch.last != currentTouch.current) { Notify(currentTouch.last, "OnDragOut", currentTouch.dragged); Notify(currentTouch.current, "OnDragOver", currentTouch.dragged); } Notify(currentTouch.dragged, "OnDrag", currentTouch.delta); currentTouch.last = currentTouch.current; isDragging = false; if (isDisabled) { // If the notification status has already been disabled, keep it as such currentTouch.clickNotification = ClickNotification.None; } else if (currentTouch.clickNotification == ClickNotification.BasedOnDelta && click < mag) { // We've dragged far enough to cancel the click currentTouch.clickNotification = ClickNotification.None; } } } // Send out the unpress message if (unpressed) { currentTouch.pressStarted = false; if (mTooltip != null) ShowTooltip(false); if (currentTouch.pressed != null) { // If there was a drag event in progress, make sure OnDragOut gets sent if (currentTouch.dragStarted) { Notify(currentTouch.last, "OnDragOut", currentTouch.dragged); Notify(currentTouch.dragged, "OnDragEnd", null); } // Send the notification of a touch ending Notify(currentTouch.pressed, "OnPress", false); // Send a hover message to the object if (isMouse) Notify(currentTouch.current, "OnHover", true); mHover = currentTouch.current; // If the button/touch was released on the same object, consider it a click and select it if (currentTouch.dragged == currentTouch.current || (currentScheme != ControlScheme.Controller && currentTouch.clickNotification != ClickNotification.None && currentTouch.totalDelta.magnitude < drag)) { if (currentTouch.pressed != mCurrentSelection) { mNextSelection = null; mCurrentSelection = currentTouch.pressed; Notify(currentTouch.pressed, "OnSelect", true); } else { mNextSelection = null; mCurrentSelection = currentTouch.pressed; } // If the touch should consider clicks, send out an OnClick notification if (currentTouch.clickNotification != ClickNotification.None) { float time = RealTime.time; Notify(currentTouch.pressed, "OnClick", null); if (currentTouch.clickTime + 0.35f > time) { Notify(currentTouch.pressed, "OnDoubleClick", null); } currentTouch.clickTime = time; } } else if (currentTouch.dragStarted) // The button/touch was released on a different object { // Send a drop notification (for drag & drop) Notify(currentTouch.current, "OnDrop", currentTouch.dragged); } } currentTouch.dragStarted = false; currentTouch.pressed = null; currentTouch.dragged = null; } } /// <summary> /// Show or hide the tooltip. /// </summary> public void ShowTooltip (bool val) { mTooltipTime = 0f; Notify(mTooltip, "OnTooltip", val); if (!val) mTooltip = null; } #if !UNITY_EDITOR /// <summary> /// Clear all active press states when the application gets paused. /// </summary> void OnApplicationPause () { if (useTouch) { BetterList<int> ids = new BetterList<int>(); foreach (KeyValuePair<int, MouseOrTouch> pair in mTouches) { if (pair.Value != null && pair.Value.pressed) { currentTouch = pair.Value; currentTouchID = pair.Key; currentScheme = ControlScheme.Touch; currentTouch.clickNotification = ClickNotification.None; ProcessTouch(false, true); ids.Add(currentTouchID); currentTouch = null; } } for (int i = 0; i < ids.size; ++i) RemoveTouch(ids[i]); } if (useMouse) { for (int i = 0; i < 3; ++i) { if (mMouse[i].pressed) { currentTouch = mMouse[i]; currentTouchID = -1 - i; currentKey = KeyCode.Mouse0 + i; currentScheme = ControlScheme.Mouse; currentTouch.clickNotification = ClickNotification.None; ProcessTouch(false, true); currentTouch = null; } } } if (useController) { if (controller.pressed) { currentTouch = controller; currentTouchID = -100; currentScheme = ControlScheme.Controller; currentTouch.last = currentTouch.current; currentTouch.current = mCurrentSelection; currentTouch.clickNotification = ClickNotification.None; ProcessTouch(false, true); currentTouch.last = null; currentTouch = null; } } } #endif }
code-minion/artofwar
artofwar/Assets/Scripts/Frameworks/NGUI/Scripts/UI/UICamera.cs
C#
gpl-2.0
42,582
/* * This file is part of the coreboot project. * * Copyright (C) 2010 Advanced Micro Devices, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef RS780_CHIP_H #define RS780_CHIP_H /* Member variables are defined in devicetree.cb. */ struct southbridge_amd_rs780_config { u8 gppsb_configuration; /* The configuration of General Purpose Port, A/B/C/D/E. */ u8 gpp_configuration; /* The configuration of General Purpose Port, C/D. */ u16 port_enable; /* Which port is enabled? GFX(2,3), GPP(4,5,6,7) */ u8 gfx_dev2_dev3; /* for GFX Core initialization REFCLK_SEL */ u8 gfx_dual_slot; /* Is it dual graphics slots */ u8 gfx_lane_reversal; /* Single/Dual slot lan reversal */ u8 gfx_tmds; /* whether support TMDS? */ u8 gfx_compliance; /* whether support compliance? */ u8 gfx_reconfiguration; /* Dynamic Link Width Control */ u8 gfx_link_width; /* Desired width of lane 2 */ u8 gfx_pcie_config; /* GFX PCIE Modes */ u8 gfx_ddi_config; /* GFX DDI Modes */ }; #endif /* RS780_CHIP_H */
tidatida/coreboot
src/southbridge/amd/rs780/chip.h
C
gpl-2.0
1,643
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * implementing now * */ class Mage_Adminhtml_Block_Api_Tab_Roleinfo extends Mage_Adminhtml_Block_Widget_Form { public function __construct() { parent::__construct(); } public function _beforeToHtml() { $this->_initForm(); return parent::_beforeToHtml(); } protected function _initForm() { $roleId = $this->getRequest()->getParam('rid'); $form = new Varien_Data_Form(); $fieldset = $form->addFieldset('base_fieldset', array('legend'=>Mage::helper('adminhtml')->__('Role Information'))); $fieldset->addField('role_name', 'text', array( 'name' => 'rolename', 'label' => Mage::helper('adminhtml')->__('Role Name'), 'id' => 'role_name', 'class' => 'required-entry', 'required' => true, ) ); $fieldset->addField('current_password', 'obscure', array( 'name' => 'current_password', 'label' => Mage::helper('adminhtml')->__('Current Admin Password'), 'title' => Mage::helper('adminhtml')->__('Current Admin Password'), 'required' => true ) ); $fieldset->addField('role_id', 'hidden', array( 'name' => 'role_id', 'id' => 'role_id', ) ); $fieldset->addField('in_role_user', 'hidden', array( 'name' => 'in_role_user', 'id' => 'in_role_userz', ) ); $fieldset->addField('in_role_user_old', 'hidden', array('name' => 'in_role_user_old')); $form->setValues($this->getRole()->getData()); $this->setForm($form); } }
miguelangelramirez/magento.dev
app/code/core/Mage/Adminhtml/Block/Api/Tab/Roleinfo.php
PHP
gpl-2.0
2,765
/* $Id: sdp_neg.c 369517 2012-07-01 17:28:57Z file $ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <pjmedia/sdp_neg.h> #include <pjmedia/sdp.h> #include <pjmedia/errno.h> #include <pj/assert.h> #include <pj/pool.h> #include <pj/string.h> #include <pj/ctype.h> #include <pj/array.h> /** * This structure describes SDP media negotiator. */ struct pjmedia_sdp_neg { pjmedia_sdp_neg_state state; /**< Negotiator state. */ pj_bool_t prefer_remote_codec_order; pj_bool_t has_remote_answer; pj_bool_t answer_was_remote; pjmedia_sdp_session *initial_sdp, /**< Initial local SDP */ *active_local_sdp, /**< Currently active local SDP. */ *active_remote_sdp, /**< Currently active remote's. */ *neg_local_sdp, /**< Temporary local SDP. */ *neg_remote_sdp; /**< Temporary remote SDP. */ }; static const char *state_str[] = { "STATE_NULL", "STATE_LOCAL_OFFER", "STATE_REMOTE_OFFER", "STATE_WAIT_NEGO", "STATE_DONE", }; /* Definition of customized SDP format negotiation callback */ struct fmt_match_cb_t { pj_str_t fmt_name; pjmedia_sdp_neg_fmt_match_cb cb; }; /* Number of registered customized SDP format negotiation callbacks */ static unsigned fmt_match_cb_cnt; /* The registered customized SDP format negotiation callbacks */ static struct fmt_match_cb_t fmt_match_cb[PJMEDIA_SDP_NEG_MAX_CUSTOM_FMT_NEG_CB]; /* Redefining a very long identifier name, just for convenience */ #define ALLOW_MODIFY_ANSWER PJMEDIA_SDP_NEG_FMT_MATCH_ALLOW_MODIFY_ANSWER static pj_status_t custom_fmt_match( pj_pool_t *pool, const pj_str_t *fmt_name, pjmedia_sdp_media *offer, unsigned o_fmt_idx, pjmedia_sdp_media *answer, unsigned a_fmt_idx, unsigned option); /* * Get string representation of negotiator state. */ PJ_DEF(const char*) pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_state state) { if (state >=0 && state < (pjmedia_sdp_neg_state)PJ_ARRAY_SIZE(state_str)) return state_str[state]; return "<?UNKNOWN?>"; } /* * Create with local offer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_local_offer( pj_pool_t *pool, const pjmedia_sdp_session *local, pjmedia_sdp_neg **p_neg) { pjmedia_sdp_neg *neg; pj_status_t status; /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && local && p_neg, PJ_EINVAL); *p_neg = NULL; /* Validate local offer. */ PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(local))==PJ_SUCCESS, status); /* Create and initialize negotiator. */ neg = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_neg); PJ_ASSERT_RETURN(neg != NULL, PJ_ENOMEM); neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; neg->prefer_remote_codec_order = PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER; neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); *p_neg = neg; return PJ_SUCCESS; } /* * Create with remote offer and initial local offer/answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_create_w_remote_offer(pj_pool_t *pool, const pjmedia_sdp_session *initial, const pjmedia_sdp_session *remote, pjmedia_sdp_neg **p_neg) { pjmedia_sdp_neg *neg; pj_status_t status; /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && remote && p_neg, PJ_EINVAL); *p_neg = NULL; /* Validate remote offer and initial answer */ status = pjmedia_sdp_validate(remote); if (status != PJ_SUCCESS) return status; /* Create and initialize negotiator. */ neg = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_neg); PJ_ASSERT_RETURN(neg != NULL, PJ_ENOMEM); neg->prefer_remote_codec_order = PJMEDIA_SDP_NEG_PREFER_REMOTE_CODEC_ORDER; neg->neg_remote_sdp = pjmedia_sdp_session_clone(pool, remote); if (initial) { PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(initial))==PJ_SUCCESS, status); neg->initial_sdp = pjmedia_sdp_session_clone(pool, initial); neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, initial); neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; } else { neg->state = PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER; } *p_neg = neg; return PJ_SUCCESS; } /* * Set codec order preference. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_prefer_remote_codec_order( pjmedia_sdp_neg *neg, pj_bool_t prefer_remote) { PJ_ASSERT_RETURN(neg, PJ_EINVAL); neg->prefer_remote_codec_order = prefer_remote; return PJ_SUCCESS; } /* * Get SDP negotiator state. */ PJ_DEF(pjmedia_sdp_neg_state) pjmedia_sdp_neg_get_state( pjmedia_sdp_neg *neg ) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(neg != NULL, PJMEDIA_SDP_NEG_STATE_NULL); return neg->state; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_active_local( pjmedia_sdp_neg *neg, const pjmedia_sdp_session **local) { PJ_ASSERT_RETURN(neg && local, PJ_EINVAL); PJ_ASSERT_RETURN(neg->active_local_sdp, PJMEDIA_SDPNEG_ENOACTIVE); *local = neg->active_local_sdp; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_active_remote( pjmedia_sdp_neg *neg, const pjmedia_sdp_session **remote) { PJ_ASSERT_RETURN(neg && remote, PJ_EINVAL); PJ_ASSERT_RETURN(neg->active_remote_sdp, PJMEDIA_SDPNEG_ENOACTIVE); *remote = neg->active_remote_sdp; return PJ_SUCCESS; } PJ_DEF(pj_bool_t) pjmedia_sdp_neg_was_answer_remote(pjmedia_sdp_neg *neg) { PJ_ASSERT_RETURN(neg, PJ_FALSE); return neg->answer_was_remote; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_remote( pjmedia_sdp_neg *neg, const pjmedia_sdp_session **remote) { PJ_ASSERT_RETURN(neg && remote, PJ_EINVAL); PJ_ASSERT_RETURN(neg->neg_remote_sdp, PJMEDIA_SDPNEG_ENONEG); *remote = neg->neg_remote_sdp; return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_get_neg_local( pjmedia_sdp_neg *neg, const pjmedia_sdp_session **local) { PJ_ASSERT_RETURN(neg && local, PJ_EINVAL); PJ_ASSERT_RETURN(neg->neg_local_sdp, PJMEDIA_SDPNEG_ENONEG); *local = neg->neg_local_sdp; return PJ_SUCCESS; } static pjmedia_sdp_media *sdp_media_clone_deactivate( pj_pool_t *pool, const pjmedia_sdp_media *rem_med, const pjmedia_sdp_media *local_med, const pjmedia_sdp_session *local_sess) { pjmedia_sdp_media *res; res = pjmedia_sdp_media_clone_deactivate(pool, rem_med); if (!res) return NULL; if (!res->conn && (!local_sess || !local_sess->conn)) { if (local_med && local_med->conn) res->conn = pjmedia_sdp_conn_clone(pool, local_med->conn); else { res->conn = PJ_POOL_ZALLOC_T(pool, pjmedia_sdp_conn); res->conn->net_type = pj_str("IN"); res->conn->addr_type = pj_str("IP4"); res->conn->addr = pj_str("127.0.0.1"); } } return res; } /* * Modify local SDP and wait for remote answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer( pj_pool_t *pool, pjmedia_sdp_neg *neg, const pjmedia_sdp_session *local) { pjmedia_sdp_session *new_offer; pjmedia_sdp_session *old_offer; char media_used[PJMEDIA_MAX_SDP_MEDIA]; unsigned oi; /* old offer media index */ pj_status_t status; /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL); /* Can only do this in STATE_DONE. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, PJMEDIA_SDPNEG_EINSTATE); /* Validate the new offer */ status = pjmedia_sdp_validate(local); if (status != PJ_SUCCESS) return status; /* Change state to STATE_LOCAL_OFFER */ neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; /* Init vars */ pj_bzero(media_used, sizeof(media_used)); old_offer = neg->active_local_sdp; new_offer = pjmedia_sdp_session_clone(pool, local); /* RFC 3264 Section 8: When issuing an offer that modifies the session, * the "o=" line of the new SDP MUST be identical to that in the * previous SDP, except that the version in the origin field MUST * increment by one from the previous SDP. */ pj_strdup(pool, &new_offer->origin.user, &old_offer->origin.user); new_offer->origin.id = old_offer->origin.id; new_offer->origin.version = old_offer->origin.version + 1; pj_strdup(pool, &new_offer->origin.net_type, &old_offer->origin.net_type); pj_strdup(pool, &new_offer->origin.addr_type,&old_offer->origin.addr_type); pj_strdup(pool, &new_offer->origin.addr, &old_offer->origin.addr); /* Generating the new offer, in the case media lines doesn't match the * active SDP (e.g. current/active SDP's have m=audio and m=video lines, * and the new offer only has m=audio line), the negotiator will fix * the new offer by reordering and adding the missing media line with * port number set to zero. */ for (oi = 0; oi < old_offer->media_count; ++oi) { pjmedia_sdp_media *om; pjmedia_sdp_media *nm; unsigned ni; /* new offer media index */ pj_bool_t found = PJ_FALSE; om = old_offer->media[oi]; for (ni = oi; ni < new_offer->media_count; ++ni) { nm = new_offer->media[ni]; if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) { if (ni != oi) { /* The same media found but the position unmatched to the * old offer, so let's put this media in the right place, * and keep the order of the rest. */ pj_array_insert(new_offer->media, /* array */ sizeof(new_offer->media[0]), /* elmt size*/ ni, /* count */ oi, /* pos */ &nm); /* new elmt */ } found = PJ_TRUE; break; } } if (!found) { pjmedia_sdp_media *m; m = sdp_media_clone_deactivate(pool, om, om, local); pj_array_insert(new_offer->media, sizeof(new_offer->media[0]), new_offer->media_count++, oi, &m); } } /* New_offer fixed */ neg->initial_sdp = new_offer; neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, new_offer); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_send_local_offer( pj_pool_t *pool, pjmedia_sdp_neg *neg, const pjmedia_sdp_session **offer) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(neg && offer, PJ_EINVAL); *offer = NULL; /* Can only do this in STATE_DONE or STATE_LOCAL_OFFER. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE || neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, PJMEDIA_SDPNEG_EINSTATE); if (neg->state == PJMEDIA_SDP_NEG_STATE_DONE) { /* If in STATE_DONE, set the active SDP as the offer. */ PJ_ASSERT_RETURN(neg->active_local_sdp, PJMEDIA_SDPNEG_ENOACTIVE); neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER; neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, neg->active_local_sdp); *offer = neg->active_local_sdp; } else { /* We assume that we're in STATE_LOCAL_OFFER. * In this case set the neg_local_sdp as the offer. */ *offer = neg->neg_local_sdp; } return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_answer( pj_pool_t *pool, pjmedia_sdp_neg *neg, const pjmedia_sdp_session *remote) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && remote, PJ_EINVAL); /* Can only do this in STATE_LOCAL_OFFER. * If we haven't provided local offer, then rx_remote_offer() should * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER, PJMEDIA_SDPNEG_EINSTATE); /* We're ready to negotiate. */ neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; neg->has_remote_answer = PJ_TRUE; neg->neg_remote_sdp = pjmedia_sdp_session_clone(pool, remote); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_remote_offer( pj_pool_t *pool, pjmedia_sdp_neg *neg, const pjmedia_sdp_session *remote) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && remote, PJ_EINVAL); /* Can only do this in STATE_DONE. * If we already provide local offer, then rx_remote_answer() should * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, PJMEDIA_SDPNEG_EINSTATE); /* State now is STATE_REMOTE_OFFER. */ neg->state = PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER; neg->neg_remote_sdp = pjmedia_sdp_session_clone(pool, remote); return PJ_SUCCESS; } PJ_DEF(pj_status_t) pjmedia_sdp_neg_set_local_answer( pj_pool_t *pool, pjmedia_sdp_neg *neg, const pjmedia_sdp_session *local) { /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL); /* Can only do this in STATE_REMOTE_OFFER. * If we already provide local offer, then rx_remote_answer() should * be called instead of this function. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER, PJMEDIA_SDPNEG_EINSTATE); /* State now is STATE_WAIT_NEGO. */ neg->state = PJMEDIA_SDP_NEG_STATE_WAIT_NEGO; if (local) { neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local); if (neg->initial_sdp) { /* I don't think there is anything in RFC 3264 that mandates * answerer to place the same origin (and increment version) * in the answer, but probably it won't hurt either. * Note that the version will be incremented in * pjmedia_sdp_neg_negotiate() */ neg->neg_local_sdp->origin.id = neg->initial_sdp->origin.id; } else { neg->initial_sdp = pjmedia_sdp_session_clone(pool, local); } } else { PJ_ASSERT_RETURN(neg->initial_sdp, PJMEDIA_SDPNEG_ENOINITIAL); neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, neg->initial_sdp); } return PJ_SUCCESS; } PJ_DEF(pj_bool_t) pjmedia_sdp_neg_has_local_answer(pjmedia_sdp_neg *neg) { pj_assert(neg && neg->state==PJMEDIA_SDP_NEG_STATE_WAIT_NEGO); return !neg->has_remote_answer; } /* Swap string. */ static void str_swap(pj_str_t *str1, pj_str_t *str2) { pj_str_t tmp = *str1; *str1 = *str2; *str2 = tmp; } static void remove_all_media_directions(pjmedia_sdp_media *m) { pjmedia_sdp_media_remove_all_attr(m, "inactive"); pjmedia_sdp_media_remove_all_attr(m, "sendrecv"); pjmedia_sdp_media_remove_all_attr(m, "sendonly"); pjmedia_sdp_media_remove_all_attr(m, "recvonly"); } /* Update media direction based on peer's media direction */ static void update_media_direction(pj_pool_t *pool, const pjmedia_sdp_media *remote, pjmedia_sdp_media *local) { pjmedia_dir old_dir = PJMEDIA_DIR_ENCODING_DECODING, new_dir; /* Get the media direction of local SDP */ if (pjmedia_sdp_media_find_attr2(local, "sendonly", NULL)) old_dir = PJMEDIA_DIR_ENCODING; else if (pjmedia_sdp_media_find_attr2(local, "recvonly", NULL)) old_dir = PJMEDIA_DIR_DECODING; else if (pjmedia_sdp_media_find_attr2(local, "inactive", NULL)) old_dir = PJMEDIA_DIR_NONE; new_dir = old_dir; /* Adjust local media direction based on remote media direction */ if (pjmedia_sdp_media_find_attr2(remote, "inactive", NULL) != NULL) { /* If remote has "a=inactive", then local is inactive too */ new_dir = PJMEDIA_DIR_NONE; } else if(pjmedia_sdp_media_find_attr2(remote, "sendonly", NULL) != NULL) { /* If remote has "a=sendonly", then set local to "recvonly" if * it is currently "sendrecv". Otherwise if local is NOT "recvonly", * then set local direction to "inactive". */ switch (old_dir) { case PJMEDIA_DIR_ENCODING_DECODING: new_dir = PJMEDIA_DIR_DECODING; break; case PJMEDIA_DIR_DECODING: /* No change */ break; default: new_dir = PJMEDIA_DIR_NONE; break; } } else if(pjmedia_sdp_media_find_attr2(remote, "recvonly", NULL) != NULL) { /* If remote has "a=recvonly", then set local to "sendonly" if * it is currently "sendrecv". Otherwise if local is NOT "sendonly", * then set local direction to "inactive" */ switch (old_dir) { case PJMEDIA_DIR_ENCODING_DECODING: new_dir = PJMEDIA_DIR_ENCODING; break; case PJMEDIA_DIR_ENCODING: /* No change */ break; default: new_dir = PJMEDIA_DIR_NONE; break; } } else { /* Remote indicates "sendrecv" capability. No change to local * direction */ } if (new_dir != old_dir) { pjmedia_sdp_attr *a = NULL; remove_all_media_directions(local); switch (new_dir) { case PJMEDIA_DIR_NONE: a = pjmedia_sdp_attr_create(pool, "inactive", NULL); break; case PJMEDIA_DIR_ENCODING: a = pjmedia_sdp_attr_create(pool, "sendonly", NULL); break; case PJMEDIA_DIR_DECODING: a = pjmedia_sdp_attr_create(pool, "recvonly", NULL); break; default: /* sendrecv */ break; } if (a) { pjmedia_sdp_media_add_attr(local, a); } } } /* Update single local media description to after receiving answer * from remote. */ static pj_status_t process_m_answer( pj_pool_t *pool, pjmedia_sdp_media *offer, pjmedia_sdp_media *answer, pj_bool_t allow_asym) { unsigned i; /* Check that the media type match our offer. */ if (pj_strcmp(&answer->desc.media, &offer->desc.media)!=0) { /* The media type in the answer is different than the offer! */ return PJMEDIA_SDPNEG_EINVANSMEDIA; } /* Check that transport in the answer match our offer. */ /* At this point, transport type must be compatible, * the transport instance will do more validation later. */ if (pjmedia_sdp_transport_cmp(&answer->desc.transport, &offer->desc.transport) != PJ_SUCCESS) { return PJMEDIA_SDPNEG_EINVANSTP; } /* Check if remote has rejected our offer */ if (answer->desc.port == 0) { /* Remote has rejected our offer. * Deactivate our media too. */ pjmedia_sdp_media_deactivate(pool, offer); /* Don't need to proceed */ return PJ_SUCCESS; } /* Ticket #1148: check if remote answer does not set port to zero when * offered with port zero. Let's just tolerate it. */ if (offer->desc.port == 0) { /* Don't need to proceed */ return PJ_SUCCESS; } /* Process direction attributes */ update_media_direction(pool, answer, offer); /* If asymetric media is allowed, then just check that remote answer has * codecs that are within the offer. * * Otherwise if asymetric media is not allowed, then we will choose only * one codec in our initial offer to match the answer. */ if (allow_asym) { for (i=0; i<answer->desc.fmt_count; ++i) { unsigned j; pj_str_t *rem_fmt = &answer->desc.fmt[i]; for (j=0; j<offer->desc.fmt_count; ++j) { if (pj_strcmp(rem_fmt, &answer->desc.fmt[j])==0) break; } if (j != offer->desc.fmt_count) { /* Found at least one common codec. */ break; } } if (i == answer->desc.fmt_count) { /* No common codec in the answer! */ return PJMEDIA_SDPNEG_EANSNOMEDIA; } PJ_TODO(CHECK_SDP_NEGOTIATION_WHEN_ASYMETRIC_MEDIA_IS_ALLOWED); } else { /* Offer format priority based on answer format index/priority */ unsigned offer_fmt_prior[PJMEDIA_MAX_SDP_FMT]; /* Remove all format in the offer that has no matching answer */ for (i=0; i<offer->desc.fmt_count;) { unsigned pt; pj_uint32_t j; pj_str_t *fmt = &offer->desc.fmt[i]; /* Find matching answer */ pt = pj_strtoul(fmt); if (pt < 96) { for (j=0; j<answer->desc.fmt_count; ++j) { if (pj_strcmp(fmt, &answer->desc.fmt[j])==0) break; } } else { /* This is dynamic payload type. * For dynamic payload type, we must look the rtpmap and * compare the encoding name. */ const pjmedia_sdp_attr *a; pjmedia_sdp_rtpmap or_; /* Get the rtpmap for the payload type in the offer. */ a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); if (!a) { pj_assert(!"Bug! Offer should have been validated"); return PJ_EBUG; } pjmedia_sdp_attr_get_rtpmap(a, &or_); /* Find paylaod in answer SDP with matching * encoding name and clock rate. */ for (j=0; j<answer->desc.fmt_count; ++j) { a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &answer->desc.fmt[j]); if (a) { pjmedia_sdp_rtpmap ar; pjmedia_sdp_attr_get_rtpmap(a, &ar); /* See if encoding name, clock rate, and channel * count match */ if (!pj_stricmp(&or_.enc_name, &ar.enc_name) && or_.clock_rate == ar.clock_rate && (pj_stricmp(&or_.param, &ar.param)==0 || (ar.param.slen==1 && *ar.param.ptr=='1'))) { /* Call custom format matching callbacks */ if (custom_fmt_match(pool, &or_.enc_name, offer, i, answer, j, 0) == PJ_SUCCESS) { /* Match! */ break; } } } } } if (j == answer->desc.fmt_count) { /* This format has no matching answer. * Remove it from our offer. */ pjmedia_sdp_attr *a; /* Remove rtpmap associated with this format */ a = pjmedia_sdp_media_find_attr2(offer, "rtpmap", fmt); if (a) pjmedia_sdp_media_remove_attr(offer, a); /* Remove fmtp associated with this format */ a = pjmedia_sdp_media_find_attr2(offer, "fmtp", fmt); if (a) pjmedia_sdp_media_remove_attr(offer, a); /* Remove this format from offer's array */ pj_array_erase(offer->desc.fmt, sizeof(offer->desc.fmt[0]), offer->desc.fmt_count, i); --offer->desc.fmt_count; } else { offer_fmt_prior[i] = j; ++i; } } if (0 == offer->desc.fmt_count) { /* No common codec in the answer! */ return PJMEDIA_SDPNEG_EANSNOMEDIA; } /* Post process: * - Resort offer formats so the order match to the answer. * - Remove answer formats that unmatches to the offer. */ /* Resort offer formats */ for (i=0; i<offer->desc.fmt_count; ++i) { unsigned j; for (j=i+1; j<offer->desc.fmt_count; ++j) { if (offer_fmt_prior[i] > offer_fmt_prior[j]) { unsigned tmp = offer_fmt_prior[i]; offer_fmt_prior[i] = offer_fmt_prior[j]; offer_fmt_prior[j] = tmp; str_swap(&offer->desc.fmt[i], &offer->desc.fmt[j]); } } } /* Remove unmatched answer formats */ { unsigned del_cnt = 0; for (i=0; i<answer->desc.fmt_count;) { /* The offer is ordered now, also the offer_fmt_prior */ if (i >= offer->desc.fmt_count || offer_fmt_prior[i]-del_cnt != i) { pj_str_t *fmt = &answer->desc.fmt[i]; pjmedia_sdp_attr *a; /* Remove rtpmap associated with this format */ a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", fmt); if (a) pjmedia_sdp_media_remove_attr(answer, a); /* Remove fmtp associated with this format */ a = pjmedia_sdp_media_find_attr2(answer, "fmtp", fmt); if (a) pjmedia_sdp_media_remove_attr(answer, a); /* Remove this format from answer's array */ pj_array_erase(answer->desc.fmt, sizeof(answer->desc.fmt[0]), answer->desc.fmt_count, i); --answer->desc.fmt_count; ++del_cnt; } else { ++i; } } } } /* Looks okay */ return PJ_SUCCESS; } /* Update local media session (offer) to create active local session * after receiving remote answer. */ static pj_status_t process_answer(pj_pool_t *pool, pjmedia_sdp_session *offer, pjmedia_sdp_session *answer, pj_bool_t allow_asym, pjmedia_sdp_session **p_active) { unsigned omi = 0; /* Offer media index */ unsigned ami = 0; /* Answer media index */ pj_bool_t has_active = PJ_FALSE; pj_status_t status; /* Check arguments. */ PJ_ASSERT_RETURN(pool && offer && answer && p_active, PJ_EINVAL); /* Check that media count match between offer and answer */ // Ticket #527, different media count is allowed for more interoperability, // however, the media order must be same between offer and answer. // if (offer->media_count != answer->media_count) // return PJMEDIA_SDPNEG_EMISMEDIA; /* Now update each media line in the offer with the answer. */ for (; omi<offer->media_count; ++omi) { if (ami == answer->media_count) { /* The answer has less media than the offer */ pjmedia_sdp_media *am; /* Generate matching-but-disabled-media for the answer */ am = sdp_media_clone_deactivate(pool, offer->media[omi], offer->media[omi], offer); answer->media[answer->media_count++] = am; ++ami; /* Deactivate our media offer too */ pjmedia_sdp_media_deactivate(pool, offer->media[omi]); /* No answer media to be negotiated */ continue; } status = process_m_answer(pool, offer->media[omi], answer->media[ami], allow_asym); /* If media type is mismatched, just disable the media. */ if (status == PJMEDIA_SDPNEG_EINVANSMEDIA) { pjmedia_sdp_media_deactivate(pool, offer->media[omi]); continue; } /* No common format in the answer media. */ else if (status == PJMEDIA_SDPNEG_EANSNOMEDIA) { pjmedia_sdp_media_deactivate(pool, offer->media[omi]); pjmedia_sdp_media_deactivate(pool, answer->media[ami]); } /* Return the error code, for other errors. */ else if (status != PJ_SUCCESS) { return status; } if (offer->media[omi]->desc.port != 0) has_active = PJ_TRUE; ++ami; } *p_active = offer; return has_active ? PJ_SUCCESS : PJMEDIA_SDPNEG_ENOMEDIA; } /* Internal function to rewrite the format string in SDP attribute rtpmap * and fmtp. */ PJ_INLINE(void) rewrite_pt(pj_pool_t *pool, pj_str_t *attr_val, const pj_str_t *old_pt, const pj_str_t *new_pt) { int len_diff = new_pt->slen - old_pt->slen; /* Note that attribute value should be null-terminated. */ if (len_diff > 0) { pj_str_t new_val; new_val.ptr = (char*)pj_pool_alloc(pool, attr_val->slen+len_diff+1); new_val.slen = attr_val->slen + len_diff; pj_memcpy(new_val.ptr + len_diff, attr_val->ptr, attr_val->slen + 1); *attr_val = new_val; } else if (len_diff < 0) { attr_val->slen += len_diff; pj_memmove(attr_val->ptr, attr_val->ptr - len_diff, attr_val->slen + 1); } pj_memcpy(attr_val->ptr, new_pt->ptr, new_pt->slen); } /* Internal function to apply symmetric PT for the local answer. */ static void apply_answer_symmetric_pt(pj_pool_t *pool, pjmedia_sdp_media *answer, unsigned pt_cnt, const pj_str_t pt_offer[], const pj_str_t pt_answer[]) { pjmedia_sdp_attr *a_tmp[PJMEDIA_MAX_SDP_ATTR]; unsigned i, a_tmp_cnt = 0; /* Rewrite the payload types in the answer if different to * the ones in the offer. */ for (i = 0; i < pt_cnt; ++i) { pjmedia_sdp_attr *a; /* Skip if the PTs are the same already, e.g: static PT. */ if (pj_strcmp(&pt_answer[i], &pt_offer[i]) == 0) continue; /* Rewrite payload type in the answer to match to the offer */ pj_strdup(pool, &answer->desc.fmt[i], &pt_offer[i]); /* Also update payload type in rtpmap */ a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &pt_answer[i]); if (a) { rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); /* Temporarily remove the attribute in case the new payload * type is being used by another format in the media. */ pjmedia_sdp_media_remove_attr(answer, a); a_tmp[a_tmp_cnt++] = a; } /* Also update payload type in fmtp */ a = pjmedia_sdp_media_find_attr2(answer, "fmtp", &pt_answer[i]); if (a) { rewrite_pt(pool, &a->value, &pt_answer[i], &pt_offer[i]); /* Temporarily remove the attribute in case the new payload * type is being used by another format in the media. */ pjmedia_sdp_media_remove_attr(answer, a); a_tmp[a_tmp_cnt++] = a; } } /* Return back 'rtpmap' and 'fmtp' attributes */ for (i = 0; i < a_tmp_cnt; ++i) pjmedia_sdp_media_add_attr(answer, a_tmp[i]); } /* Try to match offer with answer. */ static pj_status_t match_offer(pj_pool_t *pool, pj_bool_t prefer_remote_codec_order, const pjmedia_sdp_media *offer, const pjmedia_sdp_media *preanswer, const pjmedia_sdp_session *preanswer_sdp, pjmedia_sdp_media **p_answer) { unsigned i; pj_bool_t master_has_codec = 0, master_has_telephone_event = 0, master_has_other = 0, found_matching_codec = 0, found_matching_telephone_event = 0, found_matching_other = 0; unsigned pt_answer_count = 0; pj_str_t pt_answer[PJMEDIA_MAX_SDP_FMT]; pj_str_t pt_offer[PJMEDIA_MAX_SDP_FMT]; pjmedia_sdp_media *answer; const pjmedia_sdp_media *master, *slave; /* If offer has zero port, just clone the offer */ if (offer->desc.port == 0) { answer = sdp_media_clone_deactivate(pool, offer, preanswer, preanswer_sdp); *p_answer = answer; return PJ_SUCCESS; } /* If the preanswer define zero port, this media is being rejected, * just clone the preanswer. */ if (preanswer->desc.port == 0) { answer = pjmedia_sdp_media_clone(pool, preanswer); *p_answer = answer; return PJ_SUCCESS; } /* Set master/slave negotiator based on prefer_remote_codec_order. */ if (prefer_remote_codec_order) { master = offer; slave = preanswer; } else { master = preanswer; slave = offer; } /* With the addition of telephone-event and dodgy MS RTC SDP, * the answer generation algorithm looks really shitty... */ for (i=0; i<master->desc.fmt_count; ++i) { unsigned j; if (pj_isdigit(*master->desc.fmt[i].ptr)) { /* This is normal/standard payload type, where it's identified * by payload number. */ unsigned pt; pt = pj_strtoul(&master->desc.fmt[i]); if (pt < 96) { /* For static payload type, it's enough to compare just * the payload number. */ master_has_codec = 1; /* We just need to select one codec. * Continue if we have selected matching codec for previous * payload. */ if (found_matching_codec) continue; /* Find matching codec in local descriptor. */ for (j=0; j<slave->desc.fmt_count; ++j) { unsigned p; p = pj_strtoul(&slave->desc.fmt[j]); if (p == pt && pj_isdigit(*slave->desc.fmt[j].ptr)) { found_matching_codec = 1; pt_offer[pt_answer_count] = slave->desc.fmt[j]; pt_answer[pt_answer_count++] = slave->desc.fmt[j]; break; } } } else { /* This is dynamic payload type. * For dynamic payload type, we must look the rtpmap and * compare the encoding name. */ const pjmedia_sdp_attr *a; pjmedia_sdp_rtpmap or_; pj_bool_t is_codec; /* Get the rtpmap for the payload type in the master. */ a = pjmedia_sdp_media_find_attr2(master, "rtpmap", &master->desc.fmt[i]); if (!a) { pj_assert(!"Bug! Offer should have been validated"); return PJMEDIA_SDP_EMISSINGRTPMAP; } pjmedia_sdp_attr_get_rtpmap(a, &or_); if (!pj_stricmp2(&or_.enc_name, "telephone-event")) { master_has_telephone_event = 1; if (found_matching_telephone_event) continue; is_codec = 0; } else { master_has_codec = 1; if (found_matching_codec) continue; is_codec = 1; } /* Find paylaod in our initial SDP with matching * encoding name and clock rate. */ for (j=0; j<slave->desc.fmt_count; ++j) { a = pjmedia_sdp_media_find_attr2(slave, "rtpmap", &slave->desc.fmt[j]); if (a) { pjmedia_sdp_rtpmap lr; pjmedia_sdp_attr_get_rtpmap(a, &lr); /* See if encoding name, clock rate, and * channel count match */ if (!pj_stricmp(&or_.enc_name, &lr.enc_name) && or_.clock_rate == lr.clock_rate && (pj_stricmp(&or_.param, &lr.param)==0 || (lr.param.slen==0 && or_.param.slen==1 && *or_.param.ptr=='1') || (or_.param.slen==0 && lr.param.slen==1 && *lr.param.ptr=='1'))) { /* Match! */ if (is_codec) { pjmedia_sdp_media *o, *a; unsigned o_fmt_idx, a_fmt_idx; o = (pjmedia_sdp_media*)offer; a = (pjmedia_sdp_media*)preanswer; o_fmt_idx = prefer_remote_codec_order? i:j; a_fmt_idx = prefer_remote_codec_order? j:i; /* Call custom format matching callbacks */ if (custom_fmt_match(pool, &or_.enc_name, o, o_fmt_idx, a, a_fmt_idx, ALLOW_MODIFY_ANSWER) != PJ_SUCCESS) { continue; } found_matching_codec = 1; } else { found_matching_telephone_event = 1; } pt_offer[pt_answer_count] = prefer_remote_codec_order? offer->desc.fmt[i]: offer->desc.fmt[j]; pt_answer[pt_answer_count++] = prefer_remote_codec_order? preanswer->desc.fmt[j]: preanswer->desc.fmt[i]; break; } } } } } else { /* This is a non-standard, brain damaged SDP where the payload * type is non-numeric. It exists e.g. in Microsoft RTC based * UA, to indicate instant messaging capability. * Example: * - m=x-ms-message 5060 sip null */ master_has_other = 1; if (found_matching_other) continue; for (j=0; j<slave->desc.fmt_count; ++j) { if (!pj_strcmp(&master->desc.fmt[i], &slave->desc.fmt[j])) { /* Match */ found_matching_other = 1; pt_offer[pt_answer_count] = prefer_remote_codec_order? offer->desc.fmt[i]: offer->desc.fmt[j]; pt_answer[pt_answer_count++] = prefer_remote_codec_order? preanswer->desc.fmt[j]: preanswer->desc.fmt[i]; break; } } } } /* See if all types of master can be matched. */ if (master_has_codec && !found_matching_codec) { return PJMEDIA_SDPNEG_NOANSCODEC; } /* If this comment is removed, negotiation will fail if remote has offered telephone-event and local is not configured with telephone-event if (offer_has_telephone_event && !found_matching_telephone_event) { return PJMEDIA_SDPNEG_NOANSTELEVENT; } */ if (master_has_other && !found_matching_other) { return PJMEDIA_SDPNEG_NOANSUNKNOWN; } /* Seems like everything is in order. * Build the answer by cloning from preanswer, but rearrange the payload * to suit the offer. */ answer = pjmedia_sdp_media_clone(pool, preanswer); for (i=0; i<pt_answer_count; ++i) { unsigned j; for (j=i; j<answer->desc.fmt_count; ++j) { if (!pj_strcmp(&answer->desc.fmt[j], &pt_answer[i])) break; } pj_assert(j != answer->desc.fmt_count); str_swap(&answer->desc.fmt[i], &answer->desc.fmt[j]); } /* Remove unwanted local formats. */ for (i=pt_answer_count; i<answer->desc.fmt_count; ++i) { pjmedia_sdp_attr *a; /* Remove rtpmap for this format */ a = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &answer->desc.fmt[i]); if (a) { pjmedia_sdp_media_remove_attr(answer, a); } /* Remove fmtp for this format */ a = pjmedia_sdp_media_find_attr2(answer, "fmtp", &answer->desc.fmt[i]); if (a) { pjmedia_sdp_media_remove_attr(answer, a); } } answer->desc.fmt_count = pt_answer_count; #if PJMEDIA_SDP_NEG_ANSWER_SYMMETRIC_PT apply_answer_symmetric_pt(pool, answer, pt_answer_count, pt_offer, pt_answer); #endif /* Update media direction. */ update_media_direction(pool, offer, answer); *p_answer = answer; return PJ_SUCCESS; } /* Create complete answer for remote's offer. */ static pj_status_t create_answer( pj_pool_t *pool, pj_bool_t prefer_remote_codec_order, const pjmedia_sdp_session *initial, const pjmedia_sdp_session *offer, pjmedia_sdp_session **p_answer) { pj_status_t status = PJMEDIA_SDPNEG_ENOMEDIA; pj_bool_t has_active = PJ_FALSE; pjmedia_sdp_session *answer; char media_used[PJMEDIA_MAX_SDP_MEDIA]; unsigned i; /* Validate remote offer. * This should have been validated before. */ PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(offer))==PJ_SUCCESS, status); /* Create initial answer by duplicating initial SDP, * but clear all media lines. The media lines will be filled up later. */ answer = pjmedia_sdp_session_clone(pool, initial); PJ_ASSERT_RETURN(answer != NULL, PJ_ENOMEM); answer->media_count = 0; pj_bzero(media_used, sizeof(media_used)); /* For each media line, create our answer based on our initial * capability. */ for (i=0; i<offer->media_count; ++i) { const pjmedia_sdp_media *om; /* offer */ const pjmedia_sdp_media *im; /* initial media */ pjmedia_sdp_media *am = NULL; /* answer/result */ unsigned j; om = offer->media[i]; /* Find media description in our initial capability that matches * the media type and transport type of offer's media, has * matching codec, and has not been used to answer other offer. */ for (im=NULL, j=0; j<initial->media_count; ++j) { im = initial->media[j]; if (pj_strcmp(&om->desc.media, &im->desc.media)==0 && pj_strcmp(&om->desc.transport, &im->desc.transport)==0 && media_used[j] == 0) { pj_status_t status2; /* See if it has matching codec. */ status2 = match_offer(pool, prefer_remote_codec_order, om, im, initial, &am); if (status2 == PJ_SUCCESS) { /* Mark media as used. */ media_used[j] = 1; break; } else { status = status2; } } } if (j==initial->media_count) { /* No matching media. * Reject the offer by setting the port to zero in the answer. */ /* For simplicity in the construction of the answer, we'll * just clone the media from the offer. Anyway receiver will * ignore anything in the media once it sees that the port * number is zero. */ am = sdp_media_clone_deactivate(pool, om, om, answer); } else { /* The answer is in am */ pj_assert(am != NULL); } /* Add the media answer */ answer->media[answer->media_count++] = am; /* Check if this media is active.*/ if (am->desc.port != 0) has_active = PJ_TRUE; } *p_answer = answer; return has_active ? PJ_SUCCESS : status; } /* Cancel offer */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_cancel_offer(pjmedia_sdp_neg *neg) { PJ_ASSERT_RETURN(neg, PJ_EINVAL); /* Must be in LOCAL_OFFER state. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER || neg->state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER, PJMEDIA_SDPNEG_EINSTATE); /* Reset state to done */ neg->state = PJMEDIA_SDP_NEG_STATE_DONE; /* Clear temporary SDP */ neg->neg_local_sdp = neg->neg_remote_sdp = NULL; neg->has_remote_answer = PJ_FALSE; return PJ_SUCCESS; } /* The best bit: SDP negotiation function! */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_negotiate( pj_pool_t *pool, pjmedia_sdp_neg *neg, pj_bool_t allow_asym) { pj_status_t status; /* Check arguments are valid. */ PJ_ASSERT_RETURN(pool && neg, PJ_EINVAL); /* Must be in STATE_WAIT_NEGO state. */ PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, PJMEDIA_SDPNEG_EINSTATE); /* Must have remote offer. */ PJ_ASSERT_RETURN(neg->neg_remote_sdp, PJ_EBUG); if (neg->has_remote_answer) { pjmedia_sdp_session *active; status = process_answer(pool, neg->neg_local_sdp, neg->neg_remote_sdp, allow_asym, &active); if (status == PJ_SUCCESS) { /* Only update active SDPs when negotiation is successfull */ neg->active_local_sdp = active; neg->active_remote_sdp = neg->neg_remote_sdp; } } else { pjmedia_sdp_session *answer = NULL; status = create_answer(pool, neg->prefer_remote_codec_order, neg->neg_local_sdp, neg->neg_remote_sdp, &answer); if (status == PJ_SUCCESS) { pj_uint32_t active_ver; if (neg->active_local_sdp) active_ver = neg->active_local_sdp->origin.version; else active_ver = neg->initial_sdp->origin.version; /* Only update active SDPs when negotiation is successfull */ neg->active_local_sdp = answer; neg->active_remote_sdp = neg->neg_remote_sdp; /* Increment SDP version */ neg->active_local_sdp->origin.version = ++active_ver; } } /* State is DONE regardless */ neg->state = PJMEDIA_SDP_NEG_STATE_DONE; /* Save state */ neg->answer_was_remote = neg->has_remote_answer; /* Clear temporary SDP */ neg->neg_local_sdp = neg->neg_remote_sdp = NULL; neg->has_remote_answer = PJ_FALSE; return status; } static pj_status_t custom_fmt_match(pj_pool_t *pool, const pj_str_t *fmt_name, pjmedia_sdp_media *offer, unsigned o_fmt_idx, pjmedia_sdp_media *answer, unsigned a_fmt_idx, unsigned option) { unsigned i; for (i = 0; i < fmt_match_cb_cnt; ++i) { if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) { pj_assert(fmt_match_cb[i].cb); return (*fmt_match_cb[i].cb)(pool, offer, o_fmt_idx, answer, a_fmt_idx, option); } } /* Not customized format matching found, should be matched */ return PJ_SUCCESS; } /* Register customized SDP format negotiation callback function. */ PJ_DECL(pj_status_t) pjmedia_sdp_neg_register_fmt_match_cb( const pj_str_t *fmt_name, pjmedia_sdp_neg_fmt_match_cb cb) { struct fmt_match_cb_t *f = NULL; unsigned i; PJ_ASSERT_RETURN(fmt_name, PJ_EINVAL); /* Check if the callback for the format name has been registered */ for (i = 0; i < fmt_match_cb_cnt; ++i) { if (pj_stricmp(fmt_name, &fmt_match_cb[i].fmt_name) == 0) break; } /* Unregistration */ if (cb == NULL) { if (i == fmt_match_cb_cnt) return PJ_ENOTFOUND; pj_array_erase(fmt_match_cb, sizeof(fmt_match_cb[0]), fmt_match_cb_cnt, i); fmt_match_cb_cnt--; return PJ_SUCCESS; } /* Registration */ if (i < fmt_match_cb_cnt) { /* The same format name has been registered before */ if (cb != fmt_match_cb[i].cb) return PJ_EEXISTS; else return PJ_SUCCESS; } if (fmt_match_cb_cnt >= PJ_ARRAY_SIZE(fmt_match_cb)) return PJ_ETOOMANY; f = &fmt_match_cb[fmt_match_cb_cnt++]; f->fmt_name = *fmt_name; f->cb = cb; return PJ_SUCCESS; } /* Match format in the SDP media offer and answer. */ PJ_DEF(pj_status_t) pjmedia_sdp_neg_fmt_match(pj_pool_t *pool, pjmedia_sdp_media *offer, unsigned o_fmt_idx, pjmedia_sdp_media *answer, unsigned a_fmt_idx, unsigned option) { const pjmedia_sdp_attr *attr; pjmedia_sdp_rtpmap o_rtpmap, a_rtpmap; unsigned o_pt; unsigned a_pt; o_pt = pj_strtoul(&offer->desc.fmt[o_fmt_idx]); a_pt = pj_strtoul(&answer->desc.fmt[a_fmt_idx]); if (o_pt < 96 || a_pt < 96) { if (o_pt == a_pt) return PJ_SUCCESS; else return PJMEDIA_SDP_EFORMATNOTEQUAL; } /* Get the format rtpmap from the offer. */ attr = pjmedia_sdp_media_find_attr2(offer, "rtpmap", &offer->desc.fmt[o_fmt_idx]); if (!attr) { pj_assert(!"Bug! Offer haven't been validated"); return PJ_EBUG; } pjmedia_sdp_attr_get_rtpmap(attr, &o_rtpmap); /* Get the format rtpmap from the answer. */ attr = pjmedia_sdp_media_find_attr2(answer, "rtpmap", &answer->desc.fmt[a_fmt_idx]); if (!attr) { pj_assert(!"Bug! Answer haven't been validated"); return PJ_EBUG; } pjmedia_sdp_attr_get_rtpmap(attr, &a_rtpmap); if (pj_stricmp(&o_rtpmap.enc_name, &a_rtpmap.enc_name) != 0 || o_rtpmap.clock_rate != a_rtpmap.clock_rate) { return PJMEDIA_SDP_EFORMATNOTEQUAL; } return custom_fmt_match(pool, &o_rtpmap.enc_name, offer, o_fmt_idx, answer, a_fmt_idx, option); }
fluentstream/asterisk-p2p
res/pjproject/pjmedia/src/pjmedia/sdp_neg.c
C
gpl-2.0
44,693
<div class="wrap shopp"> <?php if (!empty($updated)): ?><div id="message" class="updated fade"><p><?php echo $updated; ?></p></div><?php endif; ?> <div class="icon32"></div> <h2><?php _e('Payment Settings','Shopp'); ?></h2> <form action="<?php echo $this->url; ?>" id="payments" method="post"> <div> <?php wp_nonce_field('shopp-settings-payments'); ?> </div> <div class="tablenav"><div class=" actions"> <select name="id" id="payment-option-menu"> <option><?php _e('Add a payment system&hellip;','Shopp'); ?></option> <?php echo menuoptions($installed,false,true); ?> </select> <button type="submit" name="add-payment-option" id="add-payment-option" class="button-secondary hide-if-js" tabindex="9999"><?php _e('Add Payment Option','Shopp'); ?></button> </div> </div> <table class="widefat" cellspacing="0"> <thead> <tr><?php print_column_headers('shopp_page_shopp-settings-payments'); ?></tr> </thead> <tfoot> <tr><?php print_column_headers('shopp_page_shopp-settings-payments',false); ?></tr> </tfoot> <tbody id="payments-settings-table" class="list"> <?php if ($edit && !in_array($edit,$gateways)) { $template_data = array( '${cancel_href}' => $this->url, '${instance}' => $id ); $editor = str_replace(array_keys($template_data),$template_data,$editor); $editor = preg_replace('/\${\w+}/','',$editor); echo $editor; } if (count($gateways) == 0 && !$edit): ?> <tr id="no-payment-settings"><td colspan="6"><?php _e('No payment methods, yet.','Shopp'); ?></td></tr> <?php endif; $hidden = get_hidden_columns('shopp_page_shopp-settings-payments'); $event = false; $even = false; foreach ($gateways as $gateway): $id = false; if (false !== strpos($gateway,'-')) list($gateway,$id) = explode('-',$gateway); if (!isset($Gateways->active[$gateway])) continue; $Gateway = $Gateways->active[$gateway]; $payment = $Gateway->settings; if (false !== $id) { $payment = $Gateway->settings[$id]; $slug = join('-',array($gateway,$id)); } else $slug = $gateway; $cards = array(); if (isset($payment['cards'])) { foreach ((array)$payment['cards'] as $symbol) { $Paycard = Lookup::paycard($symbol); if ($Paycard) $cards[] = $Paycard->name; } } $editurl = add_query_arg(array('id'=>$slug),$this->url); $deleteurl = wp_nonce_url(add_query_arg(array('delete'=>$slug),$this->url),'shopp_delete_gateway'); $classes = array(); if (!$even) $classes[] = 'alternate'; $even = !$even; if ($edit && $edit == $slug && in_array($edit,$gateways)) { $event = strtolower($edit); $template_data = array( '${editing_class}' => "$event-editing", '${cancel_href}' => $this->url, '${instance}' => $id ); // Handle payment data value substitution for multi-instance payment systems foreach ($payment as $name => $value) $template_data['${'.$name.'}'] = $value; $editor = str_replace(array_keys($template_data),$template_data,$editor); $editor = preg_replace('/\${\w+}/','',$editor); echo $editor; if ( $edit == $slug ) continue; } $label = empty($payment['label'])?__('(no label)','Shopp'):$payment['label']; ?> <tr class="<?php echo join(' ',$classes); ?>" id="payment-setting-<?php echo sanitize_title_with_dashes($gateway); ?>"> <td class="name column-name"><a class="row-title" href="<?php echo $editurl; ?>" title="<?php _e('Edit','Shopp'); ?> &quot;<?php echo esc_attr($label); ?>&quot;" class="edit"><?php echo esc_html($label); ?></a> <div class="row-actions"> <span class='edit'><a href="<?php echo esc_url($editurl); ?>" title="<?php _e('Edit','Shopp'); ?> &quot;<?php echo esc_attr($label); ?>&quot;" class="edit"><?php _e('Edit','Shopp'); ?></a> | </span><span class='delete'><a href="<?php echo esc_url($deleteurl); ?>" title="<?php _e('Delete','Shopp'); ?> &quot;<?php echo esc_attr($label); ?>&quot;" class="delete"><?php _e('Delete','Shopp'); ?></a></span> </div> </td> <?php // @todo Add title hover labels for accessibility/instructions ?> <td class="processor column-processor"><?php echo esc_html($Gateway->name); ?></td> <td class="supported column-supported"><?php echo join(', ',$cards); ?></td> <td class="ssl column-ssl"> <div class="checkbox"><?php if ($Gateway->secure): ?><div class="checked">&nbsp;</div><?php else: ?>&nbsp;<?php endif; ?></div> </td> <td class="captures column-captures"> <div class="checkbox"><?php if ($Gateway->captures): ?><div class="checked">&nbsp;</div><?php else: ?>&nbsp;<?php endif; ?></div> </td> <td class="recurring column-recurring"> <div class="checkbox"><?php if ($Gateway->recurring): ?><div class="checked">&nbsp;</div><?php else: ?>&nbsp;<?php endif; ?></div> </td> <td class="refunds column-refunds"> <div class="checkbox"><?php if ($Gateway->refunds): ?><div class="checked">&nbsp;</div><?php else: ?>&nbsp;<?php endif; ?></div> </td> </tr> <?php endforeach; ?> </tbody> </table> </form> </div> <?php do_action('shopp_gateway_module_settings'); ?> <script type="text/javascript"> /* <![CDATA[ */ var gateways = <?php echo json_encode(array_map('sanitize_title_with_dashes',array_keys($installed))); ?>; <?php if ($event): ?>jQuery(document).ready(function($) { $(document).trigger('<?php echo $event; ?>Settings',[$('#payments-settings-table tr.<?php echo $event; ?>-editing')]); });<?php endif; ?> /* ]]> */ </script>
sharpmachine/vintzthepuppet.com
wp-content/plugins/shopp/core/ui/settings/payments.php
PHP
gpl-2.0
5,419
--- title: "mbuf_free()" decl_name: "mbuf_free" symbol_kind: "func" signature: | void mbuf_free(struct mbuf *); --- Free the space allocated for the mbuffer and resets the mbuf structure.
baosongliang/SelfUse
mongoose-master/docs/c-api/mbuf.h/mbuf_free.md
Markdown
gpl-2.0
193
/* * optionstree.h - Soft-coded options structure header * Copyright (C) 2006 Kevin Smith * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #ifndef OPTIONSTREE_H #define OPTIONSTREE_H #include "varianttree.h" /** * \class OptionsTree * \brief Dynamic hierachical options structure * OptionsTree allows the dynamic creation of options (of type QVariant) * and will save and load these to/from xml. */ class OptionsTree : public QObject { Q_OBJECT public: OptionsTree(QObject *parent = nullptr); ~OptionsTree(); QVariant getOption(const QString &name, const QVariant &defaultValue = QVariant::Invalid) const; inline QVariant getOption(const char *name, const QVariant &defaultValue = QVariant::Invalid) const { return getOption(QString(QString::fromLatin1(name)), defaultValue); } // Warning: when inserting Map/Hash be very careful with keys. They are going to become xml element names. // full set of supported types can be found in VariantTree::variantToElement() void setOption(const QString &name, const QVariant &value); bool isInternalNode(const QString &node) const; void setComment(const QString &name, const QString &comment); QString getComment(const QString &name) const; QStringList allOptionNames() const; QStringList getChildOptionNames(const QString & = QString(""), bool direct = false, bool internal_nodes = false) const; bool removeOption(const QString &name, bool internal_nodes = false); static bool isValidName(const QString &name); // Map helpers QString mapLookup(const QString &basename, const QVariant &key) const; QString mapPut(const QString &basename, const QVariant &key); void mapPut(const QString &basename, const QVariant &key, const QString &node, const QVariant &value); QVariant mapGet(const QString &basename, const QVariant &key, const QString &node) const; QVariant mapGet(const QString &basename, const QVariant &key, const QString &node, const QVariant &def) const; QVariantList mapKeyList(const QString &basename, bool sortedByNumbers = false) const; bool saveOptions(const QString &fileName, const QString &configName, const QString &configNS, const QString &configVersion, bool streamWriter = false) const; bool loadOptions(const QString &fileName, const QString &configName, const QString &configNS = "", const QString &configVersion = "", bool streamReader = false); bool loadOptions(const QDomElement &name, const QString &configName, const QString &configNS = "", const QString &configVersion = ""); static bool exists(QString fileName); signals: void optionChanged(const QString &option); void optionAboutToBeInserted(const QString &option); void optionInserted(const QString &option); void optionAboutToBeRemoved(const QString &option); void optionRemoved(const QString &option); private: VariantTree tree_; friend class OptionsTreeReader; friend class OptionsTreeWriter; }; #endif // OPTIONSTREE_H
drizt/psi
src/tools/optionstree/optionstree.h
C
gpl-2.0
3,825
/* * Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program 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 General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "GridNotifiers.h" #include "halls_of_origination.h" #include "InstanceScript.h" #include "Map.h" #include "ObjectAccessor.h" #include "Player.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" #include "SpellScript.h" enum Texts { SAY_AGGRO = 0, SAY_SHIELD = 1, EMOTE_SHIELD = 2, EMOTE_UNSHIELD = 3, SAY_KILL = 4, SAY_DEATH = 5 }; enum Events { EVENT_DIVINE_RECKONING = 1, EVENT_BURNING_LIGHT = 2, EVENT_SEAR = 3, }; enum Spells { SPELL_DIVINE_RECKONING = 75592, SPELL_BURNING_LIGHT = 75115, SPELL_REVERBERATING_HYMN = 75322, SPELL_SHIELD_OF_LIGHT = 74938, SPELL_ACTIVATE_BEACONS = 76599, SPELL_TELEPORT = 74969, SPELL_SHIELD_VISUAL_RIGHT = 83698, SPELL_BEAM_OF_LIGHT_RIGHT = 76573, SPELL_SHIELD_VISUAL_LEFT = 83697, SPELL_BEAM_OF_LIGHT_LEFT = 74930, SPELL_SEARING_LIGHT = 75194, }; enum Phases { PHASE_SHIELDED = 0, PHASE_FIRST_SHIELD = 1, // Ready to be shielded for the first time PHASE_SECOND_SHIELD = 2, // First shield already happened, ready to be shielded a second time PHASE_FINAL = 3 // Already shielded twice, ready to finish the encounter normally. }; enum Actions { ACTION_DISABLE_BEACON, }; class boss_temple_guardian_anhuur : public CreatureScript { public: boss_temple_guardian_anhuur() : CreatureScript("boss_temple_guardian_anhuur") { } struct boss_temple_guardian_anhuurAI : public BossAI { boss_temple_guardian_anhuurAI(Creature* creature) : BossAI(creature, DATA_TEMPLE_GUARDIAN_ANHUUR) { Initialize(); } void Initialize() { _phase = PHASE_FIRST_SHIELD; _oldPhase = PHASE_FIRST_SHIELD; _beacons = 0; } void CleanStalkers() { std::list<Creature*> stalkers; GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); for (std::list<Creature*>::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) { (*itr)->RemoveAurasDueToSpell(SPELL_BEAM_OF_LIGHT_RIGHT); (*itr)->RemoveAurasDueToSpell(SPELL_BEAM_OF_LIGHT_LEFT); } } void Reset() override { Initialize(); _Reset(); CleanStalkers(); me->RemoveAurasDueToSpell(SPELL_SHIELD_OF_LIGHT); events.ScheduleEvent(EVENT_DIVINE_RECKONING, urand(10000, 12000)); events.ScheduleEvent(EVENT_BURNING_LIGHT, 12000); } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if ((me->HealthBelowPctDamaged(66, damage) && _phase == PHASE_FIRST_SHIELD) || (me->HealthBelowPctDamaged(33, damage) && _phase == PHASE_SECOND_SHIELD)) { _beacons = 2; _phase++; // Increase the phase _oldPhase = _phase; _phase = PHASE_SHIELDED; me->InterruptNonMeleeSpells(true); me->AttackStop(); DoCast(me, SPELL_TELEPORT); DoCast(me, SPELL_SHIELD_OF_LIGHT); me->SetFlag(UNIT_FIELD_FLAGS, uint32(UNIT_FLAG_UNK_31)); DoCastAOE(SPELL_ACTIVATE_BEACONS); GameObject* door = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_ANHUUR_DOOR)); if (door) { std::list<Creature*> stalkers; GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); stalkers.remove_if(Trinity::HeightDifferenceCheck(door, 0.0f, false)); // Target only the bottom ones for (std::list<Creature*>::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) { if ((*itr)->GetPositionX() > door->GetPositionX()) { (*itr)->CastSpell((*itr), SPELL_SHIELD_VISUAL_LEFT, true); (*itr)->CastSpell((*itr), SPELL_BEAM_OF_LIGHT_LEFT, true); } else { (*itr)->CastSpell((*itr), SPELL_SHIELD_VISUAL_RIGHT, true); (*itr)->CastSpell((*itr), SPELL_BEAM_OF_LIGHT_RIGHT, true); } } } DoCast(me, SPELL_REVERBERATING_HYMN); Talk(EMOTE_SHIELD); Talk(SAY_SHIELD); } } void DoAction(int32 action) override { if (action == ACTION_DISABLE_BEACON) { --_beacons; if (!_beacons) { me->RemoveAurasDueToSpell(SPELL_SHIELD_OF_LIGHT); Talk(EMOTE_UNSHIELD); _phase = _oldPhase; } } } void EnterCombat(Unit* /*who*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_ENGAGE, me, 1); Talk(SAY_AGGRO); _EnterCombat(); } void JustDied(Unit* /*killer*/) override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); Talk(SAY_DEATH); _JustDied(); } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void JustReachedHome() override { instance->SendEncounterUnit(ENCOUNTER_FRAME_DISENGAGE, me); _JustReachedHome(); instance->SetBossState(DATA_TEMPLE_GUARDIAN_ANHUUR, FAIL); } void UpdateAI(uint32 diff) override { if (!UpdateVictim() || !CheckInRoom() || me->GetCurrentSpell(CURRENT_CHANNELED_SPELL) || _phase == PHASE_SHIELDED) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_DIVINE_RECKONING: DoCastVictim(SPELL_DIVINE_RECKONING); events.ScheduleEvent(EVENT_DIVINE_RECKONING, urand(10000, 12000)); break; case EVENT_BURNING_LIGHT: { Unit* unit = SelectTarget(SELECT_TARGET_RANDOM, 0, NonTankTargetSelector(me)); if (!unit) unit = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true); DoCast(unit, SPELL_BURNING_LIGHT); events.ScheduleEvent(EVENT_SEAR, 2000); events.ScheduleEvent(EVENT_BURNING_LIGHT, 12000); break; } case EVENT_SEAR: { Unit* target = me->FindNearestCreature(NPC_SEARING_LIGHT, 100.0f); if (!target) break; std::list<Creature*> stalkers; GetCreatureListWithEntryInGrid(stalkers, me, NPC_CAVE_IN_STALKER, 100.0f); stalkers.remove_if(Trinity::HeightDifferenceCheck(ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_ANHUUR_DOOR)), 5.0f, true)); if (stalkers.empty()) break; stalkers.sort(Trinity::ObjectDistanceOrderPred(target)); // Get the closest statue face (any of its eyes) Creature* eye1 = stalkers.front(); stalkers.remove(eye1); // Remove the eye. stalkers.sort(Trinity::ObjectDistanceOrderPred(eye1)); // Find the second eye. Creature* eye2 = stalkers.front(); eye1->CastSpell(eye1, SPELL_SEARING_LIGHT, true); eye2->CastSpell(eye2, SPELL_SEARING_LIGHT, true); break; } } } DoMeleeAttackIfReady(); } private: uint8 _phase; uint8 _oldPhase; uint8 _beacons; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfOriginationAI<boss_temple_guardian_anhuurAI>(creature); } }; class spell_anhuur_shield_of_light : public SpellScriptLoader { public: spell_anhuur_shield_of_light() : SpellScriptLoader("spell_anhuur_shield_of_light") { } class spell_anhuur_shield_of_light_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_shield_of_light_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { if (InstanceScript* const script = GetCaster()->GetInstanceScript()) { if (GameObject* go = ObjectAccessor::GetGameObject(*GetCaster(), script->GetGuidData(DATA_ANHUUR_DOOR))) { targets.remove_if(Trinity::HeightDifferenceCheck(go, 5.0f, false)); targets.remove(GetCaster()); targets.sort(Trinity::ObjectDistanceOrderPred(GetCaster())); targets.resize(2); } } } void Register() override { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_anhuur_shield_of_light_SpellScript::FilterTargets, EFFECT_1, TARGET_UNIT_SRC_AREA_ENTRY); } }; SpellScript* GetSpellScript() const override { return new spell_anhuur_shield_of_light_SpellScript(); } }; class spell_anhuur_disable_beacon_beams : public SpellScriptLoader { public: spell_anhuur_disable_beacon_beams() : SpellScriptLoader("spell_anhuur_disable_beacon_beams") { } class spell_anhuur_disable_beacon_beams_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_disable_beacon_beams_SpellScript); void HandleScript(SpellEffIndex /*effIndex*/) { GetHitUnit()->RemoveAurasDueToSpell(GetEffectValue()); } void Notify(SpellEffIndex /*index*/) { if (InstanceScript* const script = GetCaster()->GetInstanceScript()) if (Creature* anhuur = ObjectAccessor::GetCreature(*GetCaster(), script->GetGuidData(DATA_ANHUUR_GUID))) anhuur->AI()->DoAction(ACTION_DISABLE_BEACON); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_anhuur_disable_beacon_beams_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); OnEffectHit += SpellEffectFn(spell_anhuur_disable_beacon_beams_SpellScript::Notify, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_anhuur_disable_beacon_beams_SpellScript(); } }; class spell_anhuur_activate_beacons : public SpellScriptLoader { public: spell_anhuur_activate_beacons() : SpellScriptLoader("spell_anhuur_activate_beacons") { } class spell_anhuur_activate_beacons_SpellScript : public SpellScript { PrepareSpellScript(spell_anhuur_activate_beacons_SpellScript); void Activate(SpellEffIndex index) { PreventHitDefaultEffect(index); GetHitGObj()->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_anhuur_activate_beacons_SpellScript::Activate, EFFECT_0, SPELL_EFFECT_ACTIVATE_OBJECT); } }; SpellScript* GetSpellScript() const override { return new spell_anhuur_activate_beacons_SpellScript(); } }; class spell_anhuur_divine_reckoning : public SpellScriptLoader { public: spell_anhuur_divine_reckoning() : SpellScriptLoader("spell_anhuur_divine_reckoning") { } class spell_anhuur_divine_reckoning_AuraScript : public AuraScript { PrepareAuraScript(spell_anhuur_divine_reckoning_AuraScript); void OnPeriodic(AuraEffect const* aurEff) { if (Unit* caster = GetCaster()) { CustomSpellValues values; values.AddSpellMod(SPELLVALUE_BASE_POINT0, aurEff->GetAmount()); caster->CastCustomSpell(aurEff->GetSpellEffectInfo()->TriggerSpell, values, GetTarget()); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_anhuur_divine_reckoning_AuraScript::OnPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY); } }; AuraScript* GetAuraScript() const override { return new spell_anhuur_divine_reckoning_AuraScript(); } }; void AddSC_boss_temple_guardian_anhuur() { new boss_temple_guardian_anhuur(); new spell_anhuur_shield_of_light(); new spell_anhuur_disable_beacon_beams(); new spell_anhuur_activate_beacons(); new spell_anhuur_divine_reckoning(); }
jameyboor/TrinityCore
src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp
C++
gpl-2.0
14,547
/* rlwrap.h: includes, definitions, declarations */ /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License , or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. You may contact the author by: e-mail: hlub@knoware.nl */ #include "../config.h" #include <sys/types.h> #if HAVE_SYS_WAIT_H # include <sys/wait.h> #endif #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/resource.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <stdio.h> #include <ctype.h> #include <inttypes.h> /* stdint.h is not on AIX, inttypes.h is in ISO C 1999 */ #include <errno.h> #include <stdarg.h> /* #define __USE_XOPEN #define __USE_GNU */ #include <stdlib.h> #include <sched.h> #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # if HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #ifdef HAVE_GETOPT_H # include <getopt.h> #endif #ifdef HAVE_CURSES_H # include <curses.h> # ifdef HAVE_TERM_H # include <term.h> # else # ifdef HAVE_NCURSES_TERM_H /* cygwin? AIX? */ # include <ncurses/term.h> # endif # endif #else # ifdef HAVE_TERMCAP_H # include <termcap.h> # endif #endif #include <termios.h> #ifdef HAVE_REGEX_H # include <regex.h> #endif #if STDC_HEADERS # include <string.h> #else # ifndef HAVE_STRRCHR # define strrchr rindex # endif char *strchr(), *strrchr(); # ifndef HAVE_MEMMOVE # define memmove(d, s, n) bcopy ((s), (d), (n)) # endif #endif #ifdef HAVE_PTY_H /* glibc (even if BSD) */ # include <pty.h> #elif HAVE_LIBUTIL_H /* BSD, non-glibc */ # include <libutil.h> #elif HAVE_UTIL_H /* BSD, other varriants */ # include <util.h> #endif #define BUFFSIZE 512 #ifndef MAXPATHLEN #define MAXPATHLEN 512 #endif #ifdef HAVE_SNPRINTF /* don't rely on the compiler understanding variadic macros */ # define snprintf0(buf,bufsize,format) snprintf(buf,bufsize,format) # define snprintf1(buf,bufsize,format,arg1) snprintf(buf,bufsize,format,arg1) # define snprintf2(buf,bufsize,format,arg1,arg2) snprintf(buf,bufsize,format,arg1,arg2) # define snprintf3(buf,bufsize,format,arg1,arg2,arg3) snprintf(buf,bufsize,format,arg1,arg2,arg3) # define snprintf4(buf,bufsize,format,arg1,arg2,arg3,arg4) snprintf(buf,bufsize,format,arg1,arg2,arg3,arg4) # define snprintf5(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5) snprintf(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5) # define snprintf6(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5,arg6) snprintf(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5,arg6) #else # define snprintf0(buf,bufsize,format) sprintf(buf,format) # define snprintf1(buf,bufsize,format,arg1) sprintf(buf,format,arg1) # define snprintf2(buf,bufsize,format,arg1,arg2) sprintf(buf,format,arg1,arg2) # define snprintf3(buf,bufsize,format,arg1,arg2,arg3) sprintf(buf,format,arg1,arg2,arg3) # define snprintf4(buf,bufsize,format,arg1,arg2,arg3,arg4) sprintf(buf,format,arg1,arg2,arg3,arg4) # define snprintf5(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5) sprintf(buf,format,arg1,arg2,arg3,arg4,arg5) # define snprintf6(buf,bufsize,format,arg1,arg2,arg3,arg4,arg5,arg6) sprintf(buf,format,arg1,arg2,arg3,arg4,arg5,arg6) # define vsnprintf(buf,bufsize,format,ap) vsprintf(buf,format,ap) #endif #ifndef HAVE_STRNLEN # define strnlen(s,l) strlen(s) #endif #include <readline/readline.h> #include <readline/history.h> #ifndef HAVE_RL_VARIABLE_VALUE # define rl_variable_value(s) "off" #endif #ifndef HAVE_RL_READLINE_VERSION # define rl_readline_version 0xbaddef #endif #if defined(SPY_ON_READLINE) extern int _rl_eof_char; /* Spying on readline's private life .... */ extern int _rl_horizontal_scroll_mode; # if !defined(HOMEGROWN_REDISPLAY) # define MAYBE_MULTILINE 1 # endif #else # define _rl_eof_char 0; #endif #ifdef MAYBE_MULTILINE # define redisplay_multiple_lines (!_rl_horizontal_scroll_mode) #else # define redisplay_multiple_lines (strncmp(rl_variable_value("horizontal-scroll-mode"),"off",3) == 0) #endif /* in main.c: */ extern int master_pty_fd; extern int slave_pty_sensing_fd; extern FILE *debug_fp; extern char *program_name, *command_name; extern int always_readline; extern int complete_filenames; extern pid_t command_pid; extern char *rlwrap_command_line; extern char *command_line; extern char *extra_char_after_completion; extern int i_am_child; extern int nowarn; extern int debug; extern char *password_prompt_search_string; extern int one_shot_rlwrap; extern char *substitute_prompt; extern char *history_format; extern char *forget_regexp; extern char *multi_line_tmpfile_ext; extern char *prompt_regexp; extern int renice; extern int ignore_queued_input; extern int history_duplicate_avoidance_policy; extern int pass_on_sigINT_as_sigTERM; /* now follow the possible values for history_duplicate_avoidance_policy: */ #define KEEP_ALL_DOUBLES 0 #define ELIMINATE_SUCCESIVE_DOUBLES 1 #define ELIMINATE_ALL_DOUBLES 2 extern int one_shot_rlwrap; extern int ansi_colour_aware; extern int colour_the_prompt; extern int received_WINCH; extern int prompt_is_still_uncooked; extern int mirror_arguments; extern int impatient_prompt; extern int we_just_got_a_signal_or_EOF; extern int remember_for_completion; extern int commands_children_not_wrapped; extern int accepted_lines; extern char *filter_command; extern int polling; void cleanup_rlwrap_and_exit(int status); void put_in_output_queue(char *stuff); int output_queue_is_nonempty(void); void flush_output_queue(void); /* in readline.c: */ extern struct rl_state { /* struct to save readline state while we're processing output from slave command*/ char *input_buffer; /* current input buffer */ char *raw_prompt; /* current prompt */ char *cooked_prompt; /* ditto redefined by user, or with colour added */ int point; /* cursor position within input buffer */ int already_saved; /* flag set when saved, cleared when restored */ } saved_rl_state; void save_rl_state(void); void restore_rl_state(void); void init_readline(char *); void my_redisplay(void); void initialise_colour_codes(char *colour); void reprint_prompt(int coloured); char *colourise (const char *prompt); void move_cursor_to_start_of_prompt(int erase); #define ERASE 1 #define DONT_ERASE 0 int prompt_is_single_line(void); char *process_new_output(const char* buffer, struct rl_state* state); int cook_prompt_if_necessary (void); extern int within_line_edit, transparent; extern char *multiline_separator; extern char *pre_given; extern int leave_prompt_alone; /* in signals.c */ extern volatile int command_is_dead; extern int commands_exit_status; extern int filter_is_dead; extern int filters_exit_status; extern int sigterm_received; extern int deferred_adapt_commands_window_size; extern int signal_handlers_were_installed; extern int received_sigALRM; #ifndef RETSIGTYPE #define RETSIGTYPE void /* systems where RETSIGTYPE = int have died out, apparently */ #endif typedef RETSIGTYPE (*sighandler_type)(int); void mysignal(int sig, sighandler_type handler); void install_signal_handlers(void); void block_signals(int *sigs); void unblock_signals(int *sigs); void block_all_passed_on_signals(void); void block_all_signals(void); void unblock_all_signals(void); void ignore_sigchld(void); void suicide_by(int sig, int status); int adapt_tty_winsize(int from_fd, int to_fd); void myalarm(int msec); void handle_sigALRM(int signo); char *signal_name(int signal); /* in utils.c */ void yield(void); void zero_select_timeout(void); int my_pselect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *ptimeout_ts, const sigset_t *sigmask); struct termios *my_tcgetattr(int fd, char *which); int read_patiently(int fd, void *buffer, int count, char *whence); int write_patiently(int fd, const void *buffer, int count, const char *whither); void read_patiently2(int fd, void *buffer, int count, int uninterruptible_msec, const char *whence); void write_patiently2(int fd, const void *buffer, int count, int uninterruptible_msec, const char *whither); void mysetenv(const char *name, const char *value); void set_ulimit(int resource, long value); void usage(int status); int open_unique_tempfile(const char *suffix, char **tmpfile_name); void mirror_args_init(char **argv); void mirror_args(pid_t command_pid); /* flags to use for the error_flags argument to myerror */ #define FATAL 2 #define WARNING 0 #define USE_ERRNO 1 #define NOERRNO 0 void myerror(int error_flags, const char *message, ...); void *mymalloc(size_t size); void myfree(void *ptr); void mysetsid(void); void close_open_files_without_writing_buffers(void); size_t filesize(const char *filename); void open_logfile(const char *filename); void write_logfile(const char *str); void close_logfile(void); void timestamp(char *buf, int size); int killed_by(int status); void change_working_directory(void); void log_terminal_settings(struct termios *terminal_settings); void log_fd_info(int fd); void last_minute_checks(void); void mymicrosleep(int msec); void do_nothing(int unused); extern char slaves_working_directory[]; /* in string_utils.c */ char *mybasename(char *filename); char *mydirname(char *filename); void mystrlcpy(char *dst, const char *src, size_t size); void mystrlcat(char *dst, const char *src, size_t size); char *mystrstr(const char *haystack, const char *needle); char *mysavestring(const char *string); char *add3strings(const char *str1, const char *str2, const char *str3); #define add2strings(a,b) add3strings(a,b,"") char *mystrtok(const char *s, const char *delim); char **split_with(const char *string, const char *delim); char *unsplit_with(int n, char ** strings, const char *delim); char **split_on_single_char(const char *string, char c); int scan_metacharacters(const char* string, const char *metacharacters); char **list4 (char *el0, char *el1, char *el2, char *el3); void free_splitlist (char **list); char *append_and_free_old(char *str1, const char *str2); char *mangle_char_for_debug_log(char c, int quote_me); char *mangle_string_for_debug_log(const char *string, int maxlen); char *mangle_buffer_for_debug_log(const char *buffer, int length); char *mem2str(const char *mem, int size); char *search_and_replace(char *patt, char *repl, const char *string, int cursorpos, int *line, int *col); char *first_of(char **strings); char *as_string(int i); char *append_and_expand_history_format(char *line); void remove_padding_and_terminate(char *buf, int length); void unbackspace(char* buf); void test_unbackspace (const char *input, const char *expected_result); char *mark_invisible(const char *buf); char *copy_and_unbackspace(const char *original); int colourless_strlen(const char *str, char **pcopy_without_ignore_markers, int termwidth); int colourless_strlen_unmarked (const char *str, int termwidth); char *get_last_screenline(char *long_line, int termwidth); char *lowercase(const char *str); char *colour_name_to_ansi_code(const char *colour_name); int match_regexp(const char *string, const char *regexp, int case_insensitive); /* in pty.c: */ pid_t my_pty_fork(int *, const struct termios *, const struct winsize *); int slave_is_in_raw_mode(void); struct termios *get_pterm_slave(void); void mirror_slaves_echo_mode(void); void completely_mirror_slaves_terminal_settings(void); void completely_mirror_slaves_output_settings(void); void completely_mirror_slaves_special_characters(void); void write_EOF_to_master_pty(void); void write_EOL_to_master_pty(char *); int dont_wrap_command_waits(void); int skip_rlwrap(void); /* in ptytty.c: */ int ptytty_get_pty(int *fd_tty, const char **ttydev); int ptytty_get_tty(const char *ttydev); int ptytty_control_tty(int fd_tty, const char *ttydev); int ptytty_openpty(int *amaster, int *aslave, const char **name); /* in completion.rb: */ void init_completer(void); void feed_file_into_completion_list(const char *completions_file); void feed_line_into_completion_list(const char *line); void add_word_to_completions(const char *word); void remove_word_from_completions(const char *word); char *my_completion_function(char *prefix, int state); extern int completion_is_case_sensitive; /* in term.c: */ extern int redisplay; /* TRUE when user input should be readable (instead of *******) */ void init_terminal(void); void set_echo(int); void prepare_terminal(void); void cr(void); void backspace(int); void clear_line(void); void clear_the_screen(void); void curs_up(void); void curs_down(void); void curs_left(void); void test_terminal(void); int my_putchar(TPUTS_PUTC_ARGTYPE c); void my_putstr(const char *string); int cursor_hpos(int col); extern struct termios saved_terminal_settings; extern int terminal_settings_saved; extern struct winsize winsize; extern char *term_name; extern char *term_backspace, term_eof, term_stop, *term_cursor_hpos, *term_cursor_up, *term_cursor_down, *term_cursor_left, *term_rmcup, *term_rmkx; extern int newline_came_last; /* in filter.c */ #define TAG_INPUT 0 #define TAG_OUTPUT 1 #define TAG_HISTORY 2 #define TAG_COMPLETION 3 #define TAG_PROMPT 4 #define TAG_IGNORE 251 #define TAG_ADD_TO_COMPLETION_LIST 252 #define TAG_REMOVE_FROM_COMPLETION_LIST 253 #define TAG_OUTPUT_OUT_OF_BAND 254 #define TAG_ERROR 255 #define out_of_band(tag) (tag & 128) extern pid_t filter_pid; extern int filter_is_dead; void spawn_filter(const char *filter_command); void kill_filter(void); char *pass_through_filter(int tag, const char *buffer); char *filters_last_words(void); void filter_test(void); /* some handy macros */ #ifndef TRUE # define TRUE 1 #endif #ifndef FALSE # define FALSE 0 #endif #ifndef min # define min(a,b) ((a) < (b) ? (a) : (b)) #endif #ifndef max # define max(a,b) ((a) < (b) ? (b) : (a)) #endif #include "malloc_debug.h" /* malloc_debug.{c,h} not ready for prime time */ #define DEBUG_FILENAME "/tmp/rlwrap.debug" #define KA_BOOM {char *p = (char *) 1; *p = 'c';} /* dump core right here */ #define KA_SCRUNCH {volatile int x=1, y=0; x = x/y;} /* force a SIGFPE */ #define KA_SCREECH kill(getpid(),SIGTRAP); /* enter the debugger - use it to set (conditional) breakpoints from within C code: if (condition) KA_SCREECH; */ /* DPRINTF0 and its ilk doesn't produce any output except when DEBUG is #defined (via --enable-debug configure option) */ #ifdef DEBUG # define DEBUG_TERMIO 1 # define DEBUG_SIGNALS 2 # define DEBUG_READLINE 4 # define DEBUG_MEMORY_MANAGEMENT 8 /* used with malloc_debug.c */ # define DEBUG_FILTERING 16 # define DEBUG_COMPLETION 32 # define DEBUG_AD_HOC 64 /* only used during rlwrap development */ # define DEBUG_WITH_TIMESTAMPS 128 /* add timestamps to every line in debug log */ # define FORCE_HOMEGROWN_REDISPLAY 256 /* force use of my_homegrown_redisplay() */ # define DEBUG_LONG_STRINGS 512 /* log all strings completely, however long they are */ # define DEBUG_RACES 1024 /* introduce random delays */ # define DEBUG_RANDOM_FAIL 2048 /* fail tests randomly */ # define DEBUG_TEST_MAIN 4096 /* run test_main and exit */ # define DEBUG_MAX DEBUG_TEST_MAIN # define MANGLE_LENGTH ((debug_saved & DEBUG_LONG_STRINGS) ? 0 : 20) /* debug_saved is defined within DPRINTF macro */ # define DEBUG_DEFAULT (DEBUG_TERMIO | DEBUG_SIGNALS | DEBUG_READLINE) # define DEBUG_ALL (2*DEBUG_MAX-1) # ifndef __GNUC__ # define __FUNCTION__ "" # endif # define WHERE_AND_WHEN \ int debug_saved = debug; char file_line[100], when[100]; \ if(debug & DEBUG_WITH_TIMESTAMPS) timestamp(when, sizeof(when)); else *when='\0'; \ debug = 0; /* don't debug while evaluating the DPRINTF arguments */ \ snprintf2(file_line, sizeof(file_line),"%.15s:%d:",__FILE__,__LINE__); \ fprintf(debug_fp, "%-20s %s %-25.25s ", file_line, when, __FUNCTION__);\ # define NL_AND_FLUSH fputc('\n', debug_fp) ; fflush(debug_fp); debug = debug_saved; # define DPRINTF0(mask, format) \ if ((debug & mask) && debug_fp) {WHERE_AND_WHEN; fprintf(debug_fp, format); NL_AND_FLUSH; } # define DPRINTF1(mask, format,arg) \ if ((debug & mask) && debug_fp) {WHERE_AND_WHEN; fprintf(debug_fp, format, arg); NL_AND_FLUSH; } # define DPRINTF2(mask, format,arg1, arg2) \ if ((debug & mask) && debug_fp) {WHERE_AND_WHEN; fprintf(debug_fp, format, arg1, arg2); NL_AND_FLUSH; } # define DPRINTF3(mask, format,arg1, arg2, arg3) \ if ((debug & mask) && debug_fp) {WHERE_AND_WHEN; fprintf(debug_fp, format, arg1, arg2, arg3); NL_AND_FLUSH; } # define DPRINTF4(mask, format,arg1, arg2, arg3, arg4) \ if ((debug & mask) && debug_fp) {WHERE_AND_WHEN; fprintf(debug_fp, format, arg1, arg2, arg3,arg4); NL_AND_FLUSH; } # define ERRMSG(b) (b && (errno != 0) ? add3strings("(", strerror(errno), ")") : "" ) # define SHOWCURSOR(c) if (debug & DEBUG_READLINE) {my_putchar(c); mymicrosleep(1200); curs_left();} /* (may work incorrectly at last column!)*/ # define DEBUG_RANDOM_SLEEP if (debug & DEBUG_RACES) {int sleeptime=rand()&31; DPRINTF1(DEBUG_RACES,"sleeping for %d msecs", sleeptime); mymicrosleep(sleeptime);} #else # define HEAVEN_FORBID(exp) (exp) # define OH_PLEASE(exp) (exp) # define MANGLE_LENGTH 0 # define DPRINTF0(mask, format) # define DPRINTF1(mask, format,arg) # define DPRINTF2(mask, format,arg1, arg2) # define DPRINTF3(mask, format,arg1, arg2, arg3) # define DPRINTF4(mask, format,arg1, arg2, arg3, arg4) # define ERRMSG(b) # define SHOWCURSOR # define NDEBUG /* disable assertions */ # define DEBUG_RANDOM_SLEEP #endif #include <assert.h>
prtysh/rlwrap
src/rlwrap.h
C
gpl-2.0
19,164
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <boost/test/unit_test.hpp> #include "storage/Utils/Logger.h" #include "testsuite/helpers/TsCmp.h" using namespace storage; BOOST_AUTO_TEST_CASE(dependencies) { set_logger(get_stdout_logger()); TsCmpActiongraph cmp("test1"); BOOST_CHECK_MESSAGE(cmp.ok(), cmp); BOOST_CHECK_EQUAL(required_features(cmp.get_probed()), ""); BOOST_CHECK_EQUAL(suggested_features(cmp.get_probed()), ""); BOOST_CHECK_EQUAL(required_features(cmp.get_staging()), ""); BOOST_CHECK_EQUAL(suggested_features(cmp.get_staging()), "ext4"); BOOST_CHECK_EQUAL(features(cmp.get_actiongraph()), "ext4"); }
aschnell/libstorage-ng
testsuite/dependencies/test1.cc
C++
gpl-2.0
687
<?php /** * HUBzero CMS * * Copyright 2005-2015 HUBzero Foundation, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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 NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS 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. * * HUBzero is a registered trademark of Purdue University. * * @package hubzero-cms * @copyright Copyright 2005-2015 HUBzero Foundation, LLC. * @license http://opensource.org/licenses/MIT MIT */ // no direct access defined('_HZEXEC_') or die(); Toolbar::title(Lang::txt('COM_CACHE_CLEAR_CACHE'), 'clear'); Toolbar::custom('delete', 'delete.png', 'delete_f2.png', 'JTOOLBAR_DELETE', true); Toolbar::divider(); if (User::authorise('core.admin', 'com_cache')) { Toolbar::preferences('com_cache'); } Toolbar::divider(); Toolbar::help('clear'); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); ?> <form action="<?php echo Route::url('index.php?option=com_cache'); ?>" method="post" name="adminForm" id="adminForm"> <fieldset id="filter-bar"> <div class="filter-select"> <select name="filter_client_id" class="inputbox" onchange="this.form.submit()"> <?php foreach (\Components\Cache\Helpers\Helper::getClientOptions() as $option) : ?> <option value="<?php echo $option->value; ?>"<?php if ($option->value == $this->state->get('clientId')) { echo ' selected="selected"'; } ?>><?php echo $this->escape(ucfirst($option->text)); ?></option> <?php endforeach; ?> </select> </div> </fieldset> <table class="adminlist"> <thead> <tr> <th scope="col" class="priority-3"> <?php echo Lang::txt('COM_CACHE_NUM'); ?> </th> <th scope="col"> <input type="checkbox" name="checkall-toggle" value="" title="<?php echo Lang::txt('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" /> </th> <th scope="col" class="title nowrap"> <?php echo Html::grid('sort', 'COM_CACHE_GROUP', 'group', $listDirn, $listOrder); ?> </th> <th scope="col" class="center nowrap priority-2"> <?php echo Html::grid('sort', 'COM_CACHE_NUMBER_OF_FILES', 'count', $listDirn, $listOrder); ?> </th> <th scope="col" class="center"> <?php echo Html::grid('sort', 'COM_CACHE_SIZE', 'size', $listDirn, $listOrder); ?> </th> </tr> </thead> <tfoot> <tr> <td colspan="5"> <?php echo $this->pagination->render(); ?> </td> </tr> </tfoot> <tbody> <?php $i = 0; foreach ($this->data as $folder => $item): ?> <tr class="row<?php echo $i % 2; ?>"> <td class="priority-3"> <?php echo $this->pagination->getRowOffset($i); ?> </td> <td> <input type="checkbox" id="cb<?php echo $i; ?>" name="cid[]" value="<?php echo $item->group; ?>" onclick="Joomla.isChecked(this.checked);" /> </td> <td> <strong><?php echo $item->group; ?></strong> </td> <td class="center priority-2"> <?php echo $item->count; ?> </td> <td class="center"> <?php echo \Hubzero\Utility\Number::formatBytes($item->size * 1024); ?> </td> </tr> <?php $i++; endforeach; ?> </tbody> </table> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="client" value="<?php echo $this->client->id; ?>" /> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" /> <?php echo Html::input('token'); ?> </form>
drewthoennes/hubzero-cms
core/components/com_cache/admin/views/cleanser/tmpl/cache.php
PHP
gpl-2.0
4,457
<?php include_once 'qode-instagram-widget.php';
hslincoln/reflex
wp-content/plugins/qode-instagram-widget/widgets/load.php
PHP
gpl-2.0
50
#include "gnc-csv-model.h" #include <glib/gi18n.h> #include <goffice/goffice-features.h> #if (GO_VERSION_EPOCH == 0) && (GO_VERSION_MAJOR == 7) && (GO_VERSION_MINOR == 8) /* For libgoffice-0.7.8, disable its internal inclusion of <regutf8.h> so to avoid clashing symbol definitions with <regex.h> */ # define GO_REGUTF8_H #endif #include <goffice/utils/go-glib-extras.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <regex.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include <math.h> #include <time.h> #ifndef HAVE_LOCALTIME_R #include "localtime_r.h" #endif static QofLogModule log_module = GNC_MOD_IMPORT; const int num_date_formats = 5; const gchar* date_format_user[] = {N_("y-m-d"), N_("d-m-y"), N_("m-d-y"), N_("d-m"), N_("m-d") }; /* This array contains all of the different strings for different column types. */ gchar* gnc_csv_column_type_strs[GNC_CSV_NUM_COL_TYPES] = {N_("None"), N_("Date"), N_("Description"), N_("Balance"), N_("Deposit"), N_("Withdrawal"), N_("Num") }; /** A set of sensible defaults for parsing CSV files. * @return StfParseOptions_t* for parsing a file with comma separators */ static StfParseOptions_t* default_parse_options(void) { StfParseOptions_t* options = stf_parse_options_new(); stf_parse_options_set_type(options, PARSE_TYPE_CSV); stf_parse_options_csv_set_separators(options, ",", NULL); return options; } /** Parses a string into a date, given a format. The format must * include the year. This function should only be called by * parse_date. * @param date_str The string containing a date being parsed * @param format An index specifying a format in date_format_user * @return The parsed value of date_str on success or -1 on failure */ static time_t parse_date_with_year(const char* date_str, int format) { time_t rawtime; /* The integer time */ struct tm retvalue, test_retvalue; /* The time in a broken-down structure */ int i, j, mem_length, orig_year = -1, orig_month = -1, orig_day = -1; /* Buffer for containing individual parts (e.g. year, month, day) of a date */ char date_segment[5]; /* The compiled regular expression */ regex_t preg = {0}; /* An array containing indices specifying the matched substrings in date_str */ regmatch_t pmatch[4] = { {0}, {0}, {0}, {0} }; /* The regular expression for parsing dates */ const char* regex = "^ *([0-9]+) *[-/.'] *([0-9]+) *[-/.'] *([0-9]+).*$|^ *([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]).*$"; /* We get our matches using the regular expression. */ regcomp(&preg, regex, REG_EXTENDED); regexec(&preg, date_str, 4, pmatch, 0); regfree(&preg); /* If there wasn't a match, there was an error. */ if (pmatch[0].rm_eo == 0) return -1; /* If this is a string without separators ... */ if (pmatch[1].rm_so == -1) { /* ... we will fill in the indices based on the user's selection. */ int k = 0; /* k traverses date_str by keeping track of where separators "should" be. */ j = 1; /* j traverses pmatch. */ for (i = 0; date_format_user[format][i]; i++) { char segment_type = date_format_user[format][i]; /* Only do something if this is a meaningful character */ if (segment_type == 'y' || segment_type == 'm' || segment_type == 'd') { pmatch[j].rm_so = k; switch (segment_type) { case 'm': case 'd': k += 2; break; case 'y': k += 4; break; } pmatch[j].rm_eo = k; j++; } } } /* Put some sane values in retvalue by using the current time for * the non-year-month-day parts of the date. */ time(&rawtime); localtime_r(&rawtime, &retvalue); /* j traverses pmatch (index 0 contains the entire string, so we * start at index 1 for the first meaningful match). */ j = 1; /* Go through the date format and interpret the matches in order of * the sections in the date format. */ for (i = 0; date_format_user[format][i]; i++) { char segment_type = date_format_user[format][i]; /* Only do something if this is a meaningful character */ if (segment_type == 'y' || segment_type == 'm' || segment_type == 'd') { /* Copy the matching substring into date_segment so that we can * convert it into an integer. */ mem_length = pmatch[j].rm_eo - pmatch[j].rm_so; memcpy(date_segment, date_str + pmatch[j].rm_so, mem_length); date_segment[mem_length] = '\0'; /* Set the appropriate member of retvalue. Save the original * values so that we can check if the change when we use mktime * below. */ switch (segment_type) { case 'y': retvalue.tm_year = atoi(date_segment); /* Handle two-digit years. */ if (retvalue.tm_year < 100) { /* We allow two-digit years in the range 1969 - 2068. */ if (retvalue.tm_year < 69) retvalue.tm_year += 100; } else retvalue.tm_year -= 1900; orig_year = retvalue.tm_year; break; case 'm': orig_month = retvalue.tm_mon = atoi(date_segment) - 1; break; case 'd': orig_day = retvalue.tm_mday = atoi(date_segment); break; } j++; } } /* Convert back to an integer. If mktime leaves retvalue unchanged, * everything is okay; otherwise, an error has occurred. */ /* We have to use a "test" date value to account for changes in * daylight savings time, which can cause a date change with mktime * near midnight, causing the code to incorrectly think a date is * incorrect. */ test_retvalue = retvalue; mktime(&test_retvalue); retvalue.tm_isdst = test_retvalue.tm_isdst; rawtime = mktime(&retvalue); if (retvalue.tm_mday == orig_day && retvalue.tm_mon == orig_month && retvalue.tm_year == orig_year) { return rawtime; } else { return -1; } } /** Parses a string into a date, given a format. The format cannot * include the year. This function should only be called by * parse_date. * @param date_str The string containing a date being parsed * @param format An index specifying a format in date_format_user * @return The parsed value of date_str on success or -1 on failure */ static time_t parse_date_without_year(const char* date_str, int format) { time_t rawtime; /* The integer time */ struct tm retvalue, test_retvalue; /* The time in a broken-down structure */ int i, j, mem_length, orig_year = -1, orig_month = -1, orig_day = -1; /* Buffer for containing individual parts (e.g. year, month, day) of a date */ gchar* date_segment; /* The compiled regular expression */ regex_t preg = {0}; /* An array containing indices specifying the matched substrings in date_str */ regmatch_t pmatch[3] = { {0}, {0}, {0} }; /* The regular expression for parsing dates */ const char* regex = "^ *([0-9]+) *[-/.'] *([0-9]+).*$"; /* We get our matches using the regular expression. */ regcomp(&preg, regex, REG_EXTENDED); regexec(&preg, date_str, 3, pmatch, 0); regfree(&preg); /* If there wasn't a match, there was an error. */ if (pmatch[0].rm_eo == 0) return -1; /* Put some sane values in retvalue by using the current time for * the non-year-month-day parts of the date. */ time(&rawtime); localtime_r(&rawtime, &retvalue); orig_year = retvalue.tm_year; /* j traverses pmatch (index 0 contains the entire string, so we * start at index 1 for the first meaningful match). */ j = 1; /* Go through the date format and interpret the matches in order of * the sections in the date format. */ for (i = 0; date_format_user[format][i]; i++) { char segment_type = date_format_user[format][i]; /* Only do something if this is a meaningful character */ if (segment_type == 'm' || segment_type == 'd') { /* Copy the matching substring into date_segment so that we can * convert it into an integer. */ mem_length = pmatch[j].rm_eo - pmatch[j].rm_so; date_segment = g_new(gchar, mem_length); memcpy(date_segment, date_str + pmatch[j].rm_so, mem_length); date_segment[mem_length] = '\0'; /* Set the appropriate member of retvalue. Save the original * values so that we can check if the change when we use mktime * below. */ switch (segment_type) { case 'm': orig_month = retvalue.tm_mon = atoi(date_segment) - 1; break; case 'd': orig_day = retvalue.tm_mday = atoi(date_segment); break; } g_free(date_segment); j++; } } /* Convert back to an integer. If mktime leaves retvalue unchanged, * everything is okay; otherwise, an error has occurred. */ /* We have to use a "test" date value to account for changes in * daylight savings time, which can cause a date change with mktime * near midnight, causing the code to incorrectly think a date is * incorrect. */ test_retvalue = retvalue; mktime(&test_retvalue); retvalue.tm_isdst = test_retvalue.tm_isdst; rawtime = mktime(&retvalue); if (retvalue.tm_mday == orig_day && retvalue.tm_mon == orig_month && retvalue.tm_year == orig_year) { return rawtime; } else { return -1; } } /** Parses a string into a date, given a format. This function * requires only knowing the order in which the year, month and day * appear. For example, 01-02-2003 will be parsed the same way as * 01/02/2003. * @param date_str The string containing a date being parsed * @param format An index specifying a format in date_format_user * @return The parsed value of date_str on success or -1 on failure */ static time_t parse_date(const char* date_str, int format) { if (strchr(date_format_user[format], 'y')) return parse_date_with_year(date_str, format); else return parse_date_without_year(date_str, format); } /** Constructor for GncCsvParseData. * @return Pointer to a new GncCSvParseData */ GncCsvParseData* gnc_csv_new_parse_data(void) { GncCsvParseData* parse_data = g_new(GncCsvParseData, 1); parse_data->encoding = "UTF-8"; /* All of the data pointers are initially NULL. This is so that, if * gnc_csv_parse_data_free is called before all of the data is * initialized, only the data that needs to be freed is freed. */ parse_data->raw_str.begin = parse_data->raw_str.end = parse_data->file_str.begin = parse_data->file_str.end = NULL; parse_data->orig_lines = NULL; parse_data->orig_row_lengths = NULL; parse_data->column_types = NULL; parse_data->error_lines = parse_data->transactions = NULL; parse_data->options = default_parse_options(); parse_data->date_format = -1; parse_data->chunk = g_string_chunk_new(100 * 1024); return parse_data; } /** Destructor for GncCsvParseData. * @param parse_data Parse data whose memory will be freed */ void gnc_csv_parse_data_free(GncCsvParseData* parse_data) { /* All non-NULL pointers have been initialized and must be freed. */ if (parse_data->raw_mapping != NULL) g_mapped_file_free(parse_data->raw_mapping); if (parse_data->file_str.begin != NULL) g_free(parse_data->file_str.begin); if (parse_data->orig_lines != NULL) stf_parse_general_free(parse_data->orig_lines); if (parse_data->orig_row_lengths != NULL) g_array_free(parse_data->orig_row_lengths, FALSE); if (parse_data->options != NULL) stf_parse_options_free(parse_data->options); if (parse_data->column_types != NULL) g_array_free(parse_data->column_types, TRUE); if (parse_data->error_lines != NULL) g_list_free(parse_data->error_lines); if (parse_data->transactions != NULL) { GList* transactions = parse_data->transactions; /* We have to free the GncCsvTransLine's that are at each node in * the list before freeing the entire list. */ do { g_free(transactions->data); transactions = g_list_next(transactions); } while (transactions != NULL); g_list_free(parse_data->transactions); } g_free(parse_data->chunk); g_free(parse_data); } /** Converts raw file data using a new encoding. This function must be * called after gnc_csv_load_file only if gnc_csv_load_file guessed * the wrong encoding. * @param parse_data Data that is being parsed * @param encoding Encoding that data should be translated using * @param error Will point to an error on failure * @return 0 on success, 1 on failure */ int gnc_csv_convert_encoding(GncCsvParseData* parse_data, const char* encoding, GError** error) { gsize bytes_read, bytes_written; /* If parse_data->file_str has already been initialized it must be * freed first. (This should always be the case, since * gnc_csv_load_file should always be called before this * function.) */ if (parse_data->file_str.begin != NULL) g_free(parse_data->file_str.begin); /* Do the actual translation to UTF-8. */ parse_data->file_str.begin = g_convert(parse_data->raw_str.begin, parse_data->raw_str.end - parse_data->raw_str.begin, "UTF-8", encoding, &bytes_read, &bytes_written, error); /* Handle errors that occur. */ if (parse_data->file_str.begin == NULL) return 1; /* On success, save the ending pointer of the translated data and * the encoding type and return 0. */ parse_data->file_str.end = parse_data->file_str.begin + bytes_written; parse_data->encoding = (gchar*)encoding; return 0; } /** Loads a file into a GncCsvParseData. This is the first function * that must be called after createing a new GncCsvParseData. If this * fails because the file couldn't be opened, no more functions can be * called on the parse data until this succeeds (or until it fails * because of an encoding guess error). If it fails because the * encoding could not be guessed, gnc_csv_convert_encoding must be * called until it succeeds. * @param parse_data Data that is being parsed * @param filename Name of the file that should be opened * @param error Will contain an error if there is a failure * @return 0 on success, 1 on failure */ int gnc_csv_load_file(GncCsvParseData* parse_data, const char* filename, GError** error) { const char* guess_enc; /* Get the raw data first and handle an error if one occurs. */ parse_data->raw_mapping = g_mapped_file_new(filename, FALSE, error); if (parse_data->raw_mapping == NULL) { /* TODO Handle file opening errors more specifically, * e.g. inexistent file versus no read permission. */ parse_data->raw_str.begin = NULL; g_set_error(error, 0, GNC_CSV_FILE_OPEN_ERR, "%s", _("File opening failed.")); return 1; } /* Copy the mapping's contents into parse-data->raw_str. */ parse_data->raw_str.begin = g_mapped_file_get_contents(parse_data->raw_mapping); parse_data->raw_str.end = parse_data->raw_str.begin + g_mapped_file_get_length(parse_data->raw_mapping); /* Make a guess at the encoding of the data. */ guess_enc = go_guess_encoding((const char*)(parse_data->raw_str.begin), (size_t)(parse_data->raw_str.end - parse_data->raw_str.begin), "UTF-8", NULL); if (guess_enc == NULL) { g_set_error(error, 0, GNC_CSV_ENCODING_ERR, "%s", _("Unknown encoding.")); return 1; } /* Convert using the guessed encoding into parse_data->file_str and * handle any errors that occur. */ gnc_csv_convert_encoding(parse_data, guess_enc, error); if (parse_data->file_str.begin == NULL) { g_set_error(error, 0, GNC_CSV_ENCODING_ERR, "%s", _("Unknown encoding.")); return 1; } else return 0; } /** Parses a file into cells. This requires having an encoding that * works (see gnc_csv_convert_encoding). parse_data->options should be * set according to how the user wants before calling this * function. (Note: this function must be called with guessColTypes as * TRUE before it is ever called with it as FALSE.) (Note: if * guessColTypes is TRUE, all the column types will be GNC_CSV_NONE * right now.) * @param parse_data Data that is being parsed * @param guessColTypes TRUE to guess what the types of columns are based on the cell contents * @param error Will contain an error if there is a failure * @return 0 on success, 1 on failure */ int gnc_csv_parse(GncCsvParseData* parse_data, gboolean guessColTypes, GError** error) { /* max_cols is the number of columns in the row with the most columns. */ int i, max_cols = 0; if (parse_data->orig_lines != NULL) { stf_parse_general_free(parse_data->orig_lines); } /* If everything is fine ... */ if (parse_data->file_str.begin != NULL) { /* Do the actual parsing. */ parse_data->orig_lines = stf_parse_general(parse_data->options, parse_data->chunk, parse_data->file_str.begin, parse_data->file_str.end); } /* If we couldn't get the encoding right, we just want an empty array. */ else { parse_data->orig_lines = g_ptr_array_new(); } /* Record the original row lengths of parse_data->orig_lines. */ if (parse_data->orig_row_lengths != NULL) g_array_free(parse_data->orig_row_lengths, FALSE); parse_data->orig_row_lengths = g_array_sized_new(FALSE, FALSE, sizeof(int), parse_data->orig_lines->len); g_array_set_size(parse_data->orig_row_lengths, parse_data->orig_lines->len); parse_data->orig_max_row = 0; for (i = 0; i < parse_data->orig_lines->len; i++) { int length = ((GPtrArray*)parse_data->orig_lines->pdata[i])->len; parse_data->orig_row_lengths->data[i] = length; if (length > parse_data->orig_max_row) parse_data->orig_max_row = length; } /* If it failed, generate an error. */ if (parse_data->orig_lines == NULL) { g_set_error(error, 0, 0, "Parsing failed."); return 1; } /* Now that we have data, let's set max_cols. */ for (i = 0; i < parse_data->orig_lines->len; i++) { if (max_cols < ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len) max_cols = ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len; } if (guessColTypes) { /* Free parse_data->column_types if it's already been created. */ if (parse_data->column_types != NULL) g_array_free(parse_data->column_types, TRUE); /* Create parse_data->column_types and fill it with guesses based * on the contents of each column. */ parse_data->column_types = g_array_sized_new(FALSE, FALSE, sizeof(int), max_cols); g_array_set_size(parse_data->column_types, max_cols); /* TODO Make it actually guess. */ for (i = 0; i < parse_data->column_types->len; i++) { parse_data->column_types->data[i] = GNC_CSV_NONE; } } else { /* If we don't need to guess column types, we will simply set any * new columns that are created that didn't exist before to "None" * since we don't want gibberish to appear. Note: * parse_data->column_types should have already been * initialized, so we don't check for it being NULL. */ int i = parse_data->column_types->len; g_array_set_size(parse_data->column_types, max_cols); for (; i < parse_data->column_types->len; i++) { parse_data->column_types->data[i] = GNC_CSV_NONE; } } return 0; } /** A struct containing TransProperties that all describe a single transaction. */ typedef struct { int date_format; /**< The format for parsing dates */ Account* account; /**< The account the transaction belongs to */ GList* properties; /**< List of TransProperties */ } TransPropertyList; /** A struct encapsulating a property of a transaction. */ typedef struct { int type; /**< A value from the GncCsvColumnType enum except * GNC_CSV_NONE and GNC_CSV_NUM_COL_TYPES */ void* value; /**< Pointer to the data that will be used to configure a transaction */ TransPropertyList* list; /**< The list the property belongs to */ } TransProperty; /** Constructor for TransProperty. * @param type The type of the new property (see TransProperty.type for possible values) */ static TransProperty* trans_property_new(int type, TransPropertyList* list) { TransProperty* prop = g_new(TransProperty, 1); prop->type = type; prop->list = list; prop->value = NULL; return prop; } /** Destructor for TransProperty. * @param prop The property to be freed */ static void trans_property_free(TransProperty* prop) { switch (prop->type) { /* The types for "Date" and "Balance" (time_t and gnc_numeric, * respectively) are typically not pointed to, we have to free * them, unlike types like char* ("Description"). */ case GNC_CSV_DATE: case GNC_CSV_BALANCE: case GNC_CSV_DEPOSIT: case GNC_CSV_WITHDRAWAL: if (prop->value != NULL) g_free(prop->value); break; } g_free(prop); } /** Sets the value of the property by parsing str. Note: this should * only be called once on an instance of TransProperty, as calling it * more than once can cause memory leaks. * @param prop The property being set * @param str The string to be parsed * @return TRUE on success, FALSE on failure */ static gboolean trans_property_set(TransProperty* prop, char* str) { char *endptr, *possible_currency_symbol, *str_dupe; double value; switch (prop->type) { case GNC_CSV_DATE: prop->value = g_new(time_t, 1); *((time_t*)(prop->value)) = parse_date(str, prop->list->date_format); return *((time_t*)(prop->value)) != -1; case GNC_CSV_DESCRIPTION: case GNC_CSV_NUM: prop->value = g_strdup(str); return TRUE; case GNC_CSV_BALANCE: case GNC_CSV_DEPOSIT: case GNC_CSV_WITHDRAWAL: str_dupe = g_strdup(str); /* First, we make a copy so we can't mess up real data. */ /* Go through str_dupe looking for currency symbols. */ for (possible_currency_symbol = str_dupe; *possible_currency_symbol; possible_currency_symbol = g_utf8_next_char(possible_currency_symbol)) { if (g_unichar_type(g_utf8_get_char(possible_currency_symbol)) == G_UNICODE_CURRENCY_SYMBOL) { /* If we find a currency symbol, save the position just ahead * of the currency symbol (next_symbol), and find the null * terminator of the string (last_symbol). */ char *next_symbol = g_utf8_next_char(possible_currency_symbol), *last_symbol = next_symbol; while (*last_symbol) last_symbol = g_utf8_next_char(last_symbol); /* Move all of the string (including the null byte, which is * why we have +1 in the size parameter) following the * currency symbol back one character, thereby overwriting the * currency symbol. */ memmove(possible_currency_symbol, next_symbol, last_symbol - next_symbol + 1); break; } } /* Translate the string (now clean of currency symbols) into a number. */ value = strtod(str_dupe, &endptr); /* If this isn't a valid numeric string, this is an error. */ if (endptr != str_dupe + strlen(str_dupe)) { g_free(str_dupe); return FALSE; } g_free(str_dupe); /* Change abs to fabs, to fix bug 586805 */ if (fabs(value) > 0.00001) { prop->value = g_new(gnc_numeric, 1); *((gnc_numeric*)(prop->value)) = double_to_gnc_numeric(value, xaccAccountGetCommoditySCU(prop->list->account), GNC_HOW_RND_ROUND_HALF_UP); } return TRUE; } return FALSE; /* We should never actually get here. */ } /** Constructor for TransPropertyList. * @param account The account with which transactions should be built * @param date_format An index from date_format_user for how date properties should be parsed * @return A pointer to a new TransPropertyList */ static TransPropertyList* trans_property_list_new(Account* account, int date_format) { TransPropertyList* list = g_new(TransPropertyList, 1); list->account = account; list->date_format = date_format; list->properties = NULL; return list; } /** Destructor for TransPropertyList. * @param list The list to be freed */ static void trans_property_list_free(TransPropertyList* list) { /* Free all of the properties in this list before freeeing the list itself. */ GList* properties_begin = list->properties; while (list->properties != NULL) { trans_property_free((TransProperty*)(list->properties->data)); list->properties = g_list_next(list->properties); } g_list_free(properties_begin); g_free(list); } /** Adds a property to the list it's linked with. * (The TransPropertyList is not passed as a parameter because the property is * associated with a list when it's constructed.) * @param property The property to be added to its list */ static void trans_property_list_add(TransProperty* property) { property->list->properties = g_list_append(property->list->properties, property); } /** Adds a split to a transaction. * @param trans The transaction to add a split to * @param account The account used for the split * @param book The book where the split should be stored * @param amount The amount of the split */ static void trans_add_split(Transaction* trans, Account* account, QofBook* book, gnc_numeric amount) { Split* split = xaccMallocSplit(book); xaccSplitSetAccount(split, account); xaccSplitSetParent(split, trans); xaccSplitSetAmount(split, amount); xaccSplitSetValue(split, amount); xaccSplitSetAction(split, "Deposit"); } /** Tests a TransPropertyList for having enough essential properties. * Essential properties are "Date" and one of the following: "Balance", "Deposit", or * "Withdrawal". * @param list The list we are checking * @param error Contains an error message on failure * @return TRUE if there are enough essentials; FALSE otherwise */ static gboolean trans_property_list_verify_essentials(TransPropertyList* list, gchar** error) { int i; /* possible_errors lists the ways in which a list can fail this test. */ enum PossibleErrorTypes {NO_DATE, NO_AMOUNT, NUM_OF_POSSIBLE_ERRORS}; gchar* possible_errors[NUM_OF_POSSIBLE_ERRORS] = { N_("No date column."), N_("No balance, deposit, or withdrawal column.") }; int possible_error_lengths[NUM_OF_POSSIBLE_ERRORS] = {0}; GList *properties_begin = list->properties, *errors_list = NULL; /* Go through each of the properties and erase possible errors. */ while (list->properties) { switch (((TransProperty*)(list->properties->data))->type) { case GNC_CSV_DATE: possible_errors[NO_DATE] = NULL; break; case GNC_CSV_BALANCE: case GNC_CSV_DEPOSIT: case GNC_CSV_WITHDRAWAL: possible_errors[NO_AMOUNT] = NULL; break; } list->properties = g_list_next(list->properties); } list->properties = properties_begin; /* Accumulate a list of the actual errors. */ for (i = 0; i < NUM_OF_POSSIBLE_ERRORS; i++) { if (possible_errors[i] != NULL) { errors_list = g_list_append(errors_list, GINT_TO_POINTER(i)); /* Since we added an error, we want to also store its length for * when we construct the full error string. */ possible_error_lengths[i] = strlen(_(possible_errors[i])); } } /* If there are no errors, we can quit now. */ if (errors_list == NULL) return TRUE; else { /* full_error_size is the full length of the error message. */ int full_error_size = 0, string_length = 0; GList* errors_list_begin = errors_list; gchar *error_message, *error_message_begin; /* Find the value for full_error_size. */ while (errors_list) { /* We add an extra 1 to account for spaces in between messages. */ full_error_size += possible_error_lengths[GPOINTER_TO_INT(errors_list->data)] + 1; errors_list = g_list_next(errors_list); } errors_list = errors_list_begin; /* Append the error messages one after another. */ error_message = error_message_begin = g_new(gchar, full_error_size); while (errors_list) { i = GPOINTER_TO_INT(errors_list->data); string_length = possible_error_lengths[i]; /* Copy the error message and put a space after it. */ strncpy(error_message, _(possible_errors[i]), string_length); error_message += string_length; *error_message = ' '; error_message++; errors_list = g_list_next(errors_list); } *error_message = '\0'; /* Replace the last space with the null byte. */ g_list_free(errors_list_begin); *error = error_message_begin; return FALSE; } } /** Create a Transaction from a TransPropertyList. * @param list The list of properties * @param error Contains an error on failure * @return On success, a GncCsvTransLine; on failure, the trans pointer is NULL */ static GncCsvTransLine* trans_property_list_to_trans(TransPropertyList* list, gchar** error) { GncCsvTransLine* trans_line = g_new(GncCsvTransLine, 1); GList* properties_begin = list->properties; QofBook* book = gnc_account_get_book(list->account); gnc_commodity* currency = xaccAccountGetCommodity(list->account); gnc_numeric amount = double_to_gnc_numeric(0.0, xaccAccountGetCommoditySCU(list->account), GNC_HOW_RND_ROUND_HALF_UP); /* This flag is set to TRUE if we can use the "Deposit" or "Withdrawal" column. */ gboolean amount_set = FALSE; /* The balance is 0 by default. */ trans_line->balance_set = FALSE; trans_line->balance = amount; /* We make the line_no -1 just to mark that it hasn't been set. We * may get rid of line_no soon anyway, so it's not particularly * important. */ trans_line->line_no = -1; /* Make sure this is a transaction with all the columns we need. */ if (!trans_property_list_verify_essentials(list, error)) { g_free(trans_line); return NULL; } trans_line->trans = xaccMallocTransaction(book); xaccTransBeginEdit(trans_line->trans); xaccTransSetCurrency(trans_line->trans, currency); /* Go through each of the properties and edit the transaction accordingly. */ list->properties = properties_begin; while (list->properties != NULL) { TransProperty* prop = (TransProperty*)(list->properties->data); switch (prop->type) { case GNC_CSV_DATE: xaccTransSetDatePostedSecs(trans_line->trans, *((time_t*)(prop->value))); break; case GNC_CSV_DESCRIPTION: xaccTransSetDescription(trans_line->trans, (char*)(prop->value)); break; case GNC_CSV_NUM: xaccTransSetNum(trans_line->trans, (char*)(prop->value)); break; case GNC_CSV_DEPOSIT: /* Add deposits to the existing amount. */ if (prop->value != NULL) { amount = gnc_numeric_add(*((gnc_numeric*)(prop->value)), amount, xaccAccountGetCommoditySCU(list->account), GNC_HOW_RND_ROUND_HALF_UP); amount_set = TRUE; /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */ trans_line->balance_set = FALSE; } break; case GNC_CSV_WITHDRAWAL: /* Withdrawals are just negative deposits. */ if (prop->value != NULL) { amount = gnc_numeric_add(gnc_numeric_neg(*((gnc_numeric*)(prop->value))), amount, xaccAccountGetCommoditySCU(list->account), GNC_HOW_RND_ROUND_HALF_UP); amount_set = TRUE; /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */ trans_line->balance_set = FALSE; } break; case GNC_CSV_BALANCE: /* The balance gets stored in a separate field in trans_line. */ /* We will use the "Deposit" and "Withdrawal" columns in preference to "Balance". */ if (!amount_set && prop->value != NULL) { /* This gets put into the actual transaction at the end of gnc_csv_parse_to_trans. */ trans_line->balance = *((gnc_numeric*)(prop->value)); trans_line->balance_set = TRUE; } break; } list->properties = g_list_next(list->properties); } /* Add a split with the cumulative amount value. */ trans_add_split(trans_line->trans, list->account, book, amount); return trans_line; } /** Creates a list of transactions from parsed data. Transactions that * could be created from rows are placed in parse_data->transactions; * rows that fail are placed in parse_data->error_lines. (Note: there * is no way for this function to "fail," i.e. it only returns 0, so * it may be changed to a void function in the future.) * @param parse_data Data that is being parsed * @param account Account with which transactions are created * @param redo_errors TRUE to convert only error data, FALSE for all data * @return 0 on success, 1 on failure */ int gnc_csv_parse_to_trans(GncCsvParseData* parse_data, Account* account, gboolean redo_errors) { gboolean hasBalanceColumn; int i, j, max_cols = 0; GArray* column_types = parse_data->column_types; GList *error_lines = NULL, *begin_error_lines = NULL; /* last_transaction points to the last element in * parse_data->transactions, or NULL if it's empty. */ GList* last_transaction = NULL; /* Free parse_data->error_lines and parse_data->transactions if they * already exist. */ if (redo_errors) /* If we're redoing errors, we save freeing until the end. */ { begin_error_lines = error_lines = parse_data->error_lines; } else { if (parse_data->error_lines != NULL) { g_list_free(parse_data->error_lines); } if (parse_data->transactions != NULL) { g_list_free(parse_data->transactions); } } parse_data->error_lines = NULL; if (redo_errors) /* If we're looking only at error data ... */ { if (parse_data->transactions == NULL) { last_transaction = NULL; } else { /* Move last_transaction to the end. */ last_transaction = parse_data->transactions; while (g_list_next(last_transaction) != NULL) { last_transaction = g_list_next(last_transaction); } } /* ... we use only the lines in error_lines. */ if (error_lines == NULL) i = parse_data->orig_lines->len; /* Don't go into the for loop. */ else i = GPOINTER_TO_INT(error_lines->data); } else /* Otherwise, we look at all the data. */ { /* The following while-loop effectively behaves like the following for-loop: * for(i = 0; i < parse_data->orig_lines->len; i++). */ i = 0; last_transaction = NULL; } while (i < parse_data->orig_lines->len) { GPtrArray* line = parse_data->orig_lines->pdata[i]; /* This flag is TRUE if there are any errors in this row. */ gboolean errors = FALSE; gchar* error_message = NULL; TransPropertyList* list = trans_property_list_new(account, parse_data->date_format); GncCsvTransLine* trans_line = NULL; for (j = 0; j < line->len; j++) { /* We do nothing in "None" columns. */ if (column_types->data[j] != GNC_CSV_NONE) { /* Affect the transaction appropriately. */ TransProperty* property = trans_property_new(column_types->data[j], list); gboolean succeeded = trans_property_set(property, line->pdata[j]); /* TODO Maybe move error handling to within TransPropertyList functions? */ if (succeeded) { trans_property_list_add(property); } else { errors = TRUE; error_message = g_strdup_printf(_("%s column could not be understood."), _(gnc_csv_column_type_strs[property->type])); trans_property_free(property); break; } } } /* If we had success, add the transaction to parse_data->transaction. */ if (!errors) { trans_line = trans_property_list_to_trans(list, &error_message); errors = trans_line == NULL; } trans_property_list_free(list); /* If there were errors, add this line to parse_data->error_lines. */ if (errors) { parse_data->error_lines = g_list_append(parse_data->error_lines, GINT_TO_POINTER(i)); /* If there's already an error message, we need to replace it. */ if (line->len > (int)(parse_data->orig_row_lengths->data[i])) { g_free(line->pdata[line->len - 1]); line->pdata[line->len - 1] = error_message; } else { /* Put the error message at the end of the line. */ g_ptr_array_add(line, error_message); } } else { /* If all went well, add this transaction to the list. */ trans_line->line_no = i; /* We keep the transactions sorted by date. We start at the end * of the list and go backward, simply because the file itself * is probably also sorted by date (but we need to handle the * exception anyway). */ /* If we can just put it at the end, do so and increment last_transaction. */ if (last_transaction == NULL || xaccTransGetDate(((GncCsvTransLine*)(last_transaction->data))->trans) <= xaccTransGetDate(trans_line->trans)) { parse_data->transactions = g_list_append(parse_data->transactions, trans_line); /* If this is the first transaction, we need to get last_transaction on track. */ if (last_transaction == NULL) last_transaction = parse_data->transactions; else /* Otherwise, we can just continue. */ last_transaction = g_list_next(last_transaction); } /* Otherwise, search backward for the correct spot. */ else { GList* insertion_spot = last_transaction; while (insertion_spot != NULL && xaccTransGetDate(((GncCsvTransLine*)(insertion_spot->data))->trans) > xaccTransGetDate(trans_line->trans)) { insertion_spot = g_list_previous(insertion_spot); } /* Move insertion_spot one location forward since we have to * use the g_list_insert_before function. */ if (insertion_spot == NULL) /* We need to handle the case of inserting at the beginning of the list. */ insertion_spot = parse_data->transactions; else insertion_spot = g_list_next(insertion_spot); parse_data->transactions = g_list_insert_before(parse_data->transactions, insertion_spot, trans_line); } } /* Increment to the next row. */ if (redo_errors) { /* Move to the next error line in the list. */ error_lines = g_list_next(error_lines); if (error_lines == NULL) i = parse_data->orig_lines->len; /* Don't continue the for loop. */ else i = GPOINTER_TO_INT(error_lines->data); } else { i++; } } /* If we have a balance column, set the appropriate amounts on the transactions. */ hasBalanceColumn = FALSE; for (i = 0; i < parse_data->column_types->len; i++) { if (parse_data->column_types->data[i] == GNC_CSV_BALANCE) { hasBalanceColumn = TRUE; break; } } if (hasBalanceColumn) { GList* transactions = parse_data->transactions; /* balance_offset is how much the balance currently in the account * differs from what it will be after the transactions are * imported. This will be sum of all the previous transactions for * any given transaction. */ gnc_numeric balance_offset = double_to_gnc_numeric(0.0, xaccAccountGetCommoditySCU(account), GNC_HOW_RND_ROUND_HALF_UP); while (transactions != NULL) { GncCsvTransLine* trans_line = (GncCsvTransLine*)transactions->data; if (trans_line->balance_set) { time_t date = xaccTransGetDate(trans_line->trans); /* Find what the balance should be by adding the offset to the actual balance. */ gnc_numeric existing_balance = gnc_numeric_add(balance_offset, xaccAccountGetBalanceAsOfDate(account, date), xaccAccountGetCommoditySCU(account), GNC_HOW_RND_ROUND_HALF_UP); /* The amount of the transaction is the difference between the new and existing balance. */ gnc_numeric amount = gnc_numeric_sub(trans_line->balance, existing_balance, xaccAccountGetCommoditySCU(account), GNC_HOW_RND_ROUND_HALF_UP); SplitList* splits = xaccTransGetSplitList(trans_line->trans); while (splits) { SplitList* next_splits = g_list_next(splits); xaccSplitDestroy((Split*)splits->data); splits = next_splits; } trans_add_split(trans_line->trans, account, gnc_account_get_book(account), amount); /* This new transaction needs to be added to the balance offset. */ balance_offset = gnc_numeric_add(balance_offset, amount, xaccAccountGetCommoditySCU(account), GNC_HOW_RND_ROUND_HALF_UP); } transactions = g_list_next(transactions); } } if (redo_errors) /* Now that we're at the end, we do the freeing. */ { g_list_free(begin_error_lines); } /* We need to resize parse_data->column_types since errors may have added columns. */ for (i = 0; i < parse_data->orig_lines->len; i++) { if (max_cols < ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len) max_cols = ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len; } i = parse_data->column_types->len; parse_data->column_types = g_array_set_size(parse_data->column_types, max_cols); for (; i < max_cols; i++) { parse_data->column_types->data[i] = GNC_CSV_NONE; } return 0; }
hypatia/gnucash
src/import-export/csv/gnc-csv-model.c
C
gpl-2.0
45,804
/* * Copyright (c) 2002, Intel Corporation. All rights reserved. * Created by: julie.n.fleischer REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. Test that the function: struct tm *gmtime(const time_t *); is declared. */ #include <time.h> typedef struct tm *(*gmtime_test) (const time_t *); static int dummyfcn(void) { gmtime_test dummyvar; dummyvar = gmtime; return 0; }
linux-test-project/ltp
testcases/open_posix_testsuite/conformance/definitions/time_h/20-1-buildonly.c
C
gpl-2.0
538
## Unit 4 - Database Normalization For this batch of videos we're going to take a closer look at the CDDB and FreeDB formats and see how they compare to the kind of data structures that we'll be studying most this semester, relational databases. This will also be the first time that you need to submit your assignment via GitHub - don't worry, there are instructions below on how to do that! **GitHub** See the GitHub video below on how to update your fork of the class with this week's content and then submit your assignment. Note that, although I use a text file in the example, you can put any file you want in a directory tracked by git and it will sync up to the server. This week you'll be turning in a .txt text file and a .png graphic. **Videos** - The FreeDB File Format: <https://vimeo.com/139494412> - 1NF Database Normalization: <https://vimeo.com/74420806> - 2NF Database Normalization: <https://vimeo.com/74423053> - 3NF Database Normalization: <https://vimeo.com/74424001> - Updating Your Syllabus Fork: <https://vimeo.com/234756098> - Resolving Git Conflicts in DSC: <https://vimeo.com/234755868> - Submitting Assignments on GitHub: <https://vimeo.com/234756048> - Using Gliffy: <https://vimeo.com/139494414> *Note 1: Since the Gliffy video was made Gliffy was changed to require a login. Just create a free account; once you're in, the software works the same way it does in the video.* *Note 2: In the 2NF video, I create a one to one relationship between artists and discs. That's because I'm just creating a model based on the FreeDB file right now, and yes, it should be a many to many relationship in an actual relational database schema for this type of data.* *Note 3: Apologies that the fork update video is a bit choppy; GitHub doesn't like what I'm trying to do by simulating multiple user accounts. Just let me know if you run into any trouble in Slack. It just goes to show though: despite being incredibly useful, git can also be a real pain point in any development workflow!* **Reading** This is not required, but may be helpful: <http://www.phpbuilder.com/columns/barry20000731.php3> Note that you don't need to worry about 4NF and 5NF right now. **Assignment** I want you to come up with a new exhibition site for audio tracks. There are a lot of music sites out there, but do they show off audio in the most effective way? Does the most effective way change based on the context of the content? For example, you probably want a different set of data and metadata when you're working with oral histories than, say, Beatles records. In a text file, propose an interesting audio data set (it may exist in reality or only in your imagination) and identify what you want to show off about it in a digital exhibition space. The space may be network-based or sited. Using FreeDB/CDDB as your baseline, describe a set of fields that extend that baseline to capture whatever you need to run your more contextually-aware exhibition. Then, go to Gliffy and create a database diagram that shows your new schema. Export it as a (yourname).png, put it in the 004 directory along with your text file, and sync back to your GitHub fork so that I'll be able to see them on GitHub.com. This assignment is due on Tuesday the 26th at 11:59PM.
shelleylightburn/dig540
004/README.md
Markdown
gpl-2.0
3,273
/* * linux/mm/page_alloc.c * * Manages the free list, the system allocates free pages here. * Note that kmalloc() lives in slab.c * * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds * Swap reorganised 29.12.95, Stephen Tweedie * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 * Reshaped it to be a zoned allocator, Ingo Molnar, Red Hat, 1999 * Discontiguous memory support, Kanoj Sarcar, SGI, Nov 1999 * Zone balancing, Kanoj Sarcar, SGI, Jan 2000 * Per cpu hot/cold page lists, bulk allocation, Martin J. Bligh, Sept 2002 * (lots of bits borrowed from Ingo Molnar & Andrew Morton) */ #include <linux/stddef.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/interrupt.h> #include <linux/pagemap.h> #include <linux/jiffies.h> #include <linux/bootmem.h> #include <linux/compiler.h> #include <linux/kernel.h> #include <linux/kmemcheck.h> #include <linux/module.h> #include <linux/suspend.h> #include <linux/pagevec.h> #include <linux/blkdev.h> #include <linux/slab.h> #include <linux/oom.h> #include <linux/notifier.h> #include <linux/topology.h> #include <linux/sysctl.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/memory_hotplug.h> #include <linux/nodemask.h> #include <linux/vmalloc.h> #include <linux/mempolicy.h> #include <linux/stop_machine.h> #include <linux/sort.h> #include <linux/pfn.h> #include <linux/backing-dev.h> #include <linux/fault-inject.h> #include <linux/page-isolation.h> #include <linux/page_cgroup.h> #include <linux/debugobjects.h> #include <linux/kmemleak.h> #include <linux/memory.h> #include <linux/compaction.h> #include <trace/events/kmem.h> #include <linux/ftrace_event.h> #include <asm/tlbflush.h> #include <asm/div64.h> #include "internal.h" #ifdef CONFIG_USE_PERCPU_NUMA_NODE_ID DEFINE_PER_CPU(int, numa_node); EXPORT_PER_CPU_SYMBOL(numa_node); #endif #ifdef CONFIG_HAVE_MEMORYLESS_NODES /* * N.B., Do NOT reference the '_numa_mem_' per cpu variable directly. * It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined. * Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem() * defined in <linux/topology.h>. */ DEFINE_PER_CPU(int, _numa_mem_); /* Kernel "local memory" node */ EXPORT_PER_CPU_SYMBOL(_numa_mem_); #endif /* * Array of node states. */ nodemask_t node_states[NR_NODE_STATES] __read_mostly = { [N_POSSIBLE] = NODE_MASK_ALL, [N_ONLINE] = { { [0] = 1UL } }, #ifndef CONFIG_NUMA [N_NORMAL_MEMORY] = { { [0] = 1UL } }, #ifdef CONFIG_HIGHMEM [N_HIGH_MEMORY] = { { [0] = 1UL } }, #endif [N_CPU] = { { [0] = 1UL } }, #endif /* NUMA */ }; EXPORT_SYMBOL(node_states); unsigned long totalram_pages __read_mostly; unsigned long totalreserve_pages __read_mostly; int percpu_pagelist_fraction; gfp_t gfp_allowed_mask __read_mostly = GFP_BOOT_MASK; #ifdef CONFIG_PM_SLEEP /* * The following functions are used by the suspend/hibernate code to temporarily * change gfp_allowed_mask in order to avoid using I/O during memory allocations * while devices are suspended. To avoid races with the suspend/hibernate code, * they should always be called with pm_mutex held (gfp_allowed_mask also should * only be modified with pm_mutex held, unless the suspend/hibernate code is * guaranteed not to run in parallel with that modification). */ static gfp_t saved_gfp_mask; void pm_restore_gfp_mask(void) { WARN_ON(!mutex_is_locked(&pm_mutex)); if (saved_gfp_mask) { gfp_allowed_mask = saved_gfp_mask; saved_gfp_mask = 0; } } void pm_restrict_gfp_mask(void) { WARN_ON(!mutex_is_locked(&pm_mutex)); WARN_ON(saved_gfp_mask); saved_gfp_mask = gfp_allowed_mask; gfp_allowed_mask &= ~GFP_IOFS; } #endif /* CONFIG_PM_SLEEP */ #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE int pageblock_order __read_mostly; #endif static void __free_pages_ok(struct page *page, unsigned int order); /* * results with 256, 32 in the lowmem_reserve sysctl: * 1G machine -> (16M dma, 800M-16M normal, 1G-800M high) * 1G machine -> (16M dma, 784M normal, 224M high) * NORMAL allocation will leave 784M/256 of ram reserved in the ZONE_DMA * HIGHMEM allocation will leave 224M/32 of ram reserved in ZONE_NORMAL * HIGHMEM allocation will (224M+784M)/256 of ram reserved in ZONE_DMA * * TBD: should special case ZONE_DMA32 machines here - in those we normally * don't need any ZONE_NORMAL reservation */ int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1] = { #ifdef CONFIG_ZONE_DMA 256, #endif #ifdef CONFIG_ZONE_DMA32 256, #endif #ifdef CONFIG_HIGHMEM 32, #endif 32, }; EXPORT_SYMBOL(totalram_pages); static char * const zone_names[MAX_NR_ZONES] = { #ifdef CONFIG_ZONE_DMA "DMA", #endif #ifdef CONFIG_ZONE_DMA32 "DMA32", #endif "Normal", #ifdef CONFIG_HIGHMEM "HighMem", #endif "Movable", }; int min_free_kbytes = 1024; int min_free_order_shift = 1; static unsigned long __meminitdata nr_kernel_pages; static unsigned long __meminitdata nr_all_pages; static unsigned long __meminitdata dma_reserve; #ifdef CONFIG_ARCH_POPULATES_NODE_MAP /* * MAX_ACTIVE_REGIONS determines the maximum number of distinct * ranges of memory (RAM) that may be registered with add_active_range(). * Ranges passed to add_active_range() will be merged if possible * so the number of times add_active_range() can be called is * related to the number of nodes and the number of holes */ #ifdef CONFIG_MAX_ACTIVE_REGIONS /* Allow an architecture to set MAX_ACTIVE_REGIONS to save memory */ #define MAX_ACTIVE_REGIONS CONFIG_MAX_ACTIVE_REGIONS #else #if MAX_NUMNODES >= 32 /* If there can be many nodes, allow up to 50 holes per node */ #define MAX_ACTIVE_REGIONS (MAX_NUMNODES*50) #else /* By default, allow up to 256 distinct regions */ #define MAX_ACTIVE_REGIONS 256 #endif #endif static struct node_active_region __meminitdata early_node_map[MAX_ACTIVE_REGIONS]; static int __meminitdata nr_nodemap_entries; static unsigned long __meminitdata arch_zone_lowest_possible_pfn[MAX_NR_ZONES]; static unsigned long __meminitdata arch_zone_highest_possible_pfn[MAX_NR_ZONES]; static unsigned long __initdata required_kernelcore; static unsigned long __initdata required_movablecore; static unsigned long __meminitdata zone_movable_pfn[MAX_NUMNODES]; /* movable_zone is the "real" zone pages in ZONE_MOVABLE are taken from */ int movable_zone; EXPORT_SYMBOL(movable_zone); #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */ #if MAX_NUMNODES > 1 int nr_node_ids __read_mostly = MAX_NUMNODES; int nr_online_nodes __read_mostly = 1; EXPORT_SYMBOL(nr_node_ids); EXPORT_SYMBOL(nr_online_nodes); #endif int page_group_by_mobility_disabled __read_mostly; static void set_pageblock_migratetype(struct page *page, int migratetype) { if (unlikely(page_group_by_mobility_disabled)) migratetype = MIGRATE_UNMOVABLE; set_pageblock_flags_group(page, (unsigned long)migratetype, PB_migrate, PB_migrate_end); } bool oom_killer_disabled __read_mostly; #ifdef CONFIG_DEBUG_VM static int page_outside_zone_boundaries(struct zone *zone, struct page *page) { int ret = 0; unsigned seq; unsigned long pfn = page_to_pfn(page); do { seq = zone_span_seqbegin(zone); if (pfn >= zone->zone_start_pfn + zone->spanned_pages) ret = 1; else if (pfn < zone->zone_start_pfn) ret = 1; } while (zone_span_seqretry(zone, seq)); return ret; } static int page_is_consistent(struct zone *zone, struct page *page) { if (!pfn_valid_within(page_to_pfn(page))) return 0; if (zone != page_zone(page)) return 0; return 1; } /* * Temporary debugging check for pages not lying within a given zone. */ static int bad_range(struct zone *zone, struct page *page) { if (page_outside_zone_boundaries(zone, page)) return 1; if (!page_is_consistent(zone, page)) return 1; return 0; } #else static inline int bad_range(struct zone *zone, struct page *page) { return 0; } #endif static void bad_page(struct page *page) { static unsigned long resume; static unsigned long nr_shown; static unsigned long nr_unshown; /* Don't complain about poisoned pages */ if (PageHWPoison(page)) { __ClearPageBuddy(page); return; } /* * Allow a burst of 60 reports, then keep quiet for that minute; * or allow a steady drip of one report per second. */ if (nr_shown == 60) { if (time_before(jiffies, resume)) { nr_unshown++; goto out; } if (nr_unshown) { printk(KERN_ALERT "BUG: Bad page state: %lu messages suppressed\n", nr_unshown); nr_unshown = 0; } nr_shown = 0; } if (nr_shown++ == 0) resume = jiffies + 60 * HZ; printk(KERN_ALERT "BUG: Bad page state in process %s pfn:%05lx\n", current->comm, page_to_pfn(page)); dump_page(page); dump_stack(); out: /* Leave bad fields for debug, except PageBuddy could make trouble */ __ClearPageBuddy(page); add_taint(TAINT_BAD_PAGE); } /* * Higher-order pages are called "compound pages". They are structured thusly: * * The first PAGE_SIZE page is called the "head page". * * The remaining PAGE_SIZE pages are called "tail pages". * * All pages have PG_compound set. All pages have their ->private pointing at * the head page (even the head page has this). * * The first tail page's ->lru.next holds the address of the compound page's * put_page() function. Its ->lru.prev holds the order of allocation. * This usage means that zero-order pages may not be compound. */ static void free_compound_page(struct page *page) { __free_pages_ok(page, compound_order(page)); } void prep_compound_page(struct page *page, unsigned long order) { int i; int nr_pages = 1 << order; set_compound_page_dtor(page, free_compound_page); set_compound_order(page, order); __SetPageHead(page); for (i = 1; i < nr_pages; i++) { struct page *p = page + i; __SetPageTail(p); p->first_page = page; } } static int destroy_compound_page(struct page *page, unsigned long order) { int i; int nr_pages = 1 << order; int bad = 0; if (unlikely(compound_order(page) != order) || unlikely(!PageHead(page))) { bad_page(page); bad++; } __ClearPageHead(page); for (i = 1; i < nr_pages; i++) { struct page *p = page + i; if (unlikely(!PageTail(p) || (p->first_page != page))) { bad_page(page); bad++; } __ClearPageTail(p); } return bad; } static inline void prep_zero_page(struct page *page, int order, gfp_t gfp_flags) { int i; /* * clear_highpage() will use KM_USER0, so it's a bug to use __GFP_ZERO * and __GFP_HIGHMEM from hard or soft interrupt context. */ VM_BUG_ON((gfp_flags & __GFP_HIGHMEM) && in_interrupt()); for (i = 0; i < (1 << order); i++) clear_highpage(page + i); } static inline void set_page_order(struct page *page, int order) { set_page_private(page, order); __SetPageBuddy(page); } static inline void rmv_page_order(struct page *page) { __ClearPageBuddy(page); set_page_private(page, 0); } /* * Locate the struct page for both the matching buddy in our * pair (buddy1) and the combined O(n+1) page they form (page). * * 1) Any buddy B1 will have an order O twin B2 which satisfies * the following equation: * B2 = B1 ^ (1 << O) * For example, if the starting buddy (buddy2) is #8 its order * 1 buddy is #10: * B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10 * * 2) Any buddy B will have an order O+1 parent P which * satisfies the following equation: * P = B & ~(1 << O) * * Assumption: *_mem_map is contiguous at least up to MAX_ORDER */ static inline unsigned long __find_buddy_index(unsigned long page_idx, unsigned int order) { return page_idx ^ (1 << order); } /* * This function checks whether a page is free && is the buddy * we can do coalesce a page and its buddy if * (a) the buddy is not in a hole && * (b) the buddy is in the buddy system && * (c) a page and its buddy have the same order && * (d) a page and its buddy are in the same zone. * * For recording whether a page is in the buddy system, we use PG_buddy. * Setting, clearing, and testing PG_buddy is serialized by zone->lock. * * For recording page's order, we use page_private(page). */ static inline int page_is_buddy(struct page *page, struct page *buddy, int order) { if (!pfn_valid_within(page_to_pfn(buddy))) return 0; if (page_zone_id(page) != page_zone_id(buddy)) return 0; if (PageBuddy(buddy) && page_order(buddy) == order) { VM_BUG_ON(page_count(buddy) != 0); return 1; } return 0; } /* * Freeing function for a buddy system allocator. * * The concept of a buddy system is to maintain direct-mapped table * (containing bit values) for memory blocks of various "orders". * The bottom level table contains the map for the smallest allocatable * units of memory (here, pages), and each level above it describes * pairs of units from the levels below, hence, "buddies". * At a high level, all that happens here is marking the table entry * at the bottom level available, and propagating the changes upward * as necessary, plus some accounting needed to play nicely with other * parts of the VM system. * At each level, we keep a list of pages, which are heads of continuous * free pages of length of (1 << order) and marked with PG_buddy. Page's * order is recorded in page_private(page) field. * So when we are allocating or freeing one, we can derive the state of the * other. That is, if we allocate a small block, and both were * free, the remainder of the region must be split into blocks. * If a block is freed, and its buddy is also free, then this * triggers coalescing into a block of larger size. * * -- wli */ static inline void __free_one_page(struct page *page, struct zone *zone, unsigned int order, int migratetype) { unsigned long page_idx; unsigned long combined_idx; unsigned long uninitialized_var(buddy_idx); struct page *buddy; if (unlikely(PageCompound(page))) if (unlikely(destroy_compound_page(page, order))) return; VM_BUG_ON(migratetype == -1); page_idx = page_to_pfn(page) & ((1 << MAX_ORDER) - 1); VM_BUG_ON(page_idx & ((1 << order) - 1)); VM_BUG_ON(bad_range(zone, page)); while (order < MAX_ORDER-1) { buddy_idx = __find_buddy_index(page_idx, order); buddy = page + (buddy_idx - page_idx); if (!page_is_buddy(page, buddy, order)) break; /* Our buddy is free, merge with it and move up one order. */ list_del(&buddy->lru); zone->free_area[order].nr_free--; rmv_page_order(buddy); combined_idx = buddy_idx & page_idx; page = page + (combined_idx - page_idx); page_idx = combined_idx; order++; } set_page_order(page, order); /* * If this is not the largest possible page, check if the buddy * of the next-highest order is free. If it is, it's possible * that pages are being freed that will coalesce soon. In case, * that is happening, add the free page to the tail of the list * so it's less likely to be used soon and more likely to be merged * as a higher order page */ if ((order < MAX_ORDER-2) && pfn_valid_within(page_to_pfn(buddy))) { struct page *higher_page, *higher_buddy; combined_idx = buddy_idx & page_idx; higher_page = page + (combined_idx - page_idx); buddy_idx = __find_buddy_index(combined_idx, order + 1); higher_buddy = page + (buddy_idx - combined_idx); if (page_is_buddy(higher_page, higher_buddy, order + 1)) { list_add_tail(&page->lru, &zone->free_area[order].free_list[migratetype]); goto out; } } list_add(&page->lru, &zone->free_area[order].free_list[migratetype]); out: zone->free_area[order].nr_free++; } /* * free_page_mlock() -- clean up attempts to free and mlocked() page. * Page should not be on lru, so no need to fix that up. * free_pages_check() will verify... */ static inline void free_page_mlock(struct page *page) { __dec_zone_page_state(page, NR_MLOCK); __count_vm_event(UNEVICTABLE_MLOCKFREED); } static inline int free_pages_check(struct page *page) { if (unlikely(page_mapcount(page) | (page->mapping != NULL) | (atomic_read(&page->_count) != 0) | (page->flags & PAGE_FLAGS_CHECK_AT_FREE))) { bad_page(page); return 1; } if (page->flags & PAGE_FLAGS_CHECK_AT_PREP) page->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; return 0; } /* * Frees a number of pages from the PCP lists * Assumes all pages on list are in same zone, and of same order. * count is the number of pages to free. * * If the zone was previously in an "all pages pinned" state then look to * see if this freeing clears that state. * * And clear the zone's pages_scanned counter, to hold off the "all pages are * pinned" detection logic. */ static void free_pcppages_bulk(struct zone *zone, int count, struct per_cpu_pages *pcp) { int migratetype = 0; int batch_free = 0; int to_free = count; spin_lock(&zone->lock); zone->all_unreclaimable = 0; zone->pages_scanned = 0; while (to_free) { struct page *page; struct list_head *list; /* * Remove pages from lists in a round-robin fashion. A * batch_free count is maintained that is incremented when an * empty list is encountered. This is so more pages are freed * off fuller lists instead of spinning excessively around empty * lists */ do { batch_free++; if (++migratetype == MIGRATE_PCPTYPES) migratetype = 0; list = &pcp->lists[migratetype]; } while (list_empty(list)); do { page = list_entry(list->prev, struct page, lru); /* must delete as __free_one_page list manipulates */ list_del(&page->lru); /* MIGRATE_MOVABLE list may include MIGRATE_RESERVEs */ __free_one_page(page, zone, 0, page_private(page)); trace_mm_page_pcpu_drain(page, 0, page_private(page)); } while (--to_free && --batch_free && !list_empty(list)); } __mod_zone_page_state(zone, NR_FREE_PAGES, count); spin_unlock(&zone->lock); } static void free_one_page(struct zone *zone, struct page *page, int order, int migratetype) { spin_lock(&zone->lock); zone->all_unreclaimable = 0; zone->pages_scanned = 0; __free_one_page(page, zone, order, migratetype); __mod_zone_page_state(zone, NR_FREE_PAGES, 1 << order); spin_unlock(&zone->lock); } static bool free_pages_prepare(struct page *page, unsigned int order) { int i; int bad = 0; trace_mm_page_free_direct(page, order); kmemcheck_free_shadow(page, order); for (i = 0; i < (1 << order); i++) { struct page *pg = page + i; if (PageAnon(pg)) pg->mapping = NULL; bad += free_pages_check(pg); } if (bad) return false; if (!PageHighMem(page)) { debug_check_no_locks_freed(page_address(page),PAGE_SIZE<<order); debug_check_no_obj_freed(page_address(page), PAGE_SIZE << order); } arch_free_page(page, order); kernel_map_pages(page, 1 << order, 0); return true; } static void __free_pages_ok(struct page *page, unsigned int order) { unsigned long flags; int wasMlocked = __TestClearPageMlocked(page); if (!free_pages_prepare(page, order)) return; local_irq_save(flags); if (unlikely(wasMlocked)) free_page_mlock(page); __count_vm_events(PGFREE, 1 << order); free_one_page(page_zone(page), page, order, get_pageblock_migratetype(page)); local_irq_restore(flags); } /* * permit the bootmem allocator to evade page validation on high-order frees */ void __meminit __free_pages_bootmem(struct page *page, unsigned int order) { if (order == 0) { __ClearPageReserved(page); set_page_count(page, 0); set_page_refcounted(page); __free_page(page); } else { int loop; prefetchw(page); for (loop = 0; loop < BITS_PER_LONG; loop++) { struct page *p = &page[loop]; if (loop + 1 < BITS_PER_LONG) prefetchw(p + 1); __ClearPageReserved(p); set_page_count(p, 0); } set_page_refcounted(page); __free_pages(page, order); } } /* * The order of subdivision here is critical for the IO subsystem. * Please do not alter this order without good reasons and regression * testing. Specifically, as large blocks of memory are subdivided, * the order in which smaller blocks are delivered depends on the order * they're subdivided in this function. This is the primary factor * influencing the order in which pages are delivered to the IO * subsystem according to empirical testing, and this is also justified * by considering the behavior of a buddy system containing a single * large block of memory acted on by a series of small allocations. * This behavior is a critical factor in sglist merging's success. * * -- wli */ static inline void expand(struct zone *zone, struct page *page, int low, int high, struct free_area *area, int migratetype) { unsigned long size = 1 << high; while (high > low) { area--; high--; size >>= 1; VM_BUG_ON(bad_range(zone, &page[size])); list_add(&page[size].lru, &area->free_list[migratetype]); area->nr_free++; set_page_order(&page[size], high); } } /* * This page is about to be returned from the page allocator */ static inline int check_new_page(struct page *page) { if (unlikely(page_mapcount(page) | (page->mapping != NULL) | (atomic_read(&page->_count) != 0) | (page->flags & PAGE_FLAGS_CHECK_AT_PREP))) { bad_page(page); return 1; } return 0; } static int prep_new_page(struct page *page, int order, gfp_t gfp_flags) { int i; for (i = 0; i < (1 << order); i++) { struct page *p = page + i; if (unlikely(check_new_page(p))) return 1; } set_page_private(page, 0); set_page_refcounted(page); arch_alloc_page(page, order); kernel_map_pages(page, 1 << order, 1); if (gfp_flags & __GFP_ZERO) prep_zero_page(page, order, gfp_flags); if (order && (gfp_flags & __GFP_COMP)) prep_compound_page(page, order); return 0; } /* * Go through the free lists for the given migratetype and remove * the smallest available page from the freelists */ static inline struct page *__rmqueue_smallest(struct zone *zone, unsigned int order, int migratetype) { unsigned int current_order; struct free_area * area; struct page *page; /* Find a page of the appropriate size in the preferred list */ for (current_order = order; current_order < MAX_ORDER; ++current_order) { area = &(zone->free_area[current_order]); if (list_empty(&area->free_list[migratetype])) continue; page = list_entry(area->free_list[migratetype].next, struct page, lru); list_del(&page->lru); rmv_page_order(page); area->nr_free--; expand(zone, page, order, current_order, area, migratetype); return page; } return NULL; } /* * This array describes the order lists are fallen back to when * the free lists for the desirable migrate type are depleted */ static int fallbacks[MIGRATE_TYPES][MIGRATE_TYPES-1] = { [MIGRATE_UNMOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE }, [MIGRATE_RECLAIMABLE] = { MIGRATE_UNMOVABLE, MIGRATE_MOVABLE, MIGRATE_RESERVE }, [MIGRATE_MOVABLE] = { MIGRATE_RECLAIMABLE, MIGRATE_UNMOVABLE, MIGRATE_RESERVE }, [MIGRATE_RESERVE] = { MIGRATE_RESERVE, MIGRATE_RESERVE, MIGRATE_RESERVE }, /* Never used */ }; /* * Move the free pages in a range to the free lists of the requested type. * Note that start_page and end_pages are not aligned on a pageblock * boundary. If alignment is required, use move_freepages_block() */ static int move_freepages(struct zone *zone, struct page *start_page, struct page *end_page, int migratetype) { struct page *page; unsigned long order; int pages_moved = 0; #ifndef CONFIG_HOLES_IN_ZONE /* * page_zone is not safe to call in this context when * CONFIG_HOLES_IN_ZONE is set. This bug check is probably redundant * anyway as we check zone boundaries in move_freepages_block(). * Remove at a later date when no bug reports exist related to * grouping pages by mobility */ BUG_ON(page_zone(start_page) != page_zone(end_page)); #endif for (page = start_page; page <= end_page;) { /* Make sure we are not inadvertently changing nodes */ VM_BUG_ON(page_to_nid(page) != zone_to_nid(zone)); if (!pfn_valid_within(page_to_pfn(page))) { page++; continue; } if (!PageBuddy(page)) { page++; continue; } order = page_order(page); list_del(&page->lru); list_add(&page->lru, &zone->free_area[order].free_list[migratetype]); page += 1 << order; pages_moved += 1 << order; } return pages_moved; } static int move_freepages_block(struct zone *zone, struct page *page, int migratetype) { unsigned long start_pfn, end_pfn; struct page *start_page, *end_page; start_pfn = page_to_pfn(page); start_pfn = start_pfn & ~(pageblock_nr_pages-1); start_page = pfn_to_page(start_pfn); end_page = start_page + pageblock_nr_pages - 1; end_pfn = start_pfn + pageblock_nr_pages - 1; /* Do not cross zone boundaries */ if (start_pfn < zone->zone_start_pfn) start_page = page; if (end_pfn >= zone->zone_start_pfn + zone->spanned_pages) return 0; return move_freepages(zone, start_page, end_page, migratetype); } static void change_pageblock_range(struct page *pageblock_page, int start_order, int migratetype) { int nr_pageblocks = 1 << (start_order - pageblock_order); while (nr_pageblocks--) { set_pageblock_migratetype(pageblock_page, migratetype); pageblock_page += pageblock_nr_pages; } } /* Remove an element from the buddy allocator from the fallback list */ static inline struct page * __rmqueue_fallback(struct zone *zone, int order, int start_migratetype) { struct free_area * area; int current_order; struct page *page; int migratetype, i; /* Find the largest possible block of pages in the other list */ for (current_order = MAX_ORDER-1; current_order >= order; --current_order) { for (i = 0; i < MIGRATE_TYPES - 1; i++) { migratetype = fallbacks[start_migratetype][i]; /* MIGRATE_RESERVE handled later if necessary */ if (migratetype == MIGRATE_RESERVE) continue; area = &(zone->free_area[current_order]); if (list_empty(&area->free_list[migratetype])) continue; page = list_entry(area->free_list[migratetype].next, struct page, lru); area->nr_free--; /* * If breaking a large block of pages, move all free * pages to the preferred allocation list. If falling * back for a reclaimable kernel allocation, be more * agressive about taking ownership of free pages */ if (unlikely(current_order >= (pageblock_order >> 1)) || start_migratetype == MIGRATE_RECLAIMABLE || page_group_by_mobility_disabled) { unsigned long pages; pages = move_freepages_block(zone, page, start_migratetype); /* Claim the whole block if over half of it is free */ if (pages >= (1 << (pageblock_order-1)) || page_group_by_mobility_disabled) set_pageblock_migratetype(page, start_migratetype); migratetype = start_migratetype; } /* Remove the page from the freelists */ list_del(&page->lru); rmv_page_order(page); /* Take ownership for orders >= pageblock_order */ if (current_order >= pageblock_order) change_pageblock_range(page, current_order, start_migratetype); expand(zone, page, order, current_order, area, migratetype); trace_mm_page_alloc_extfrag(page, order, current_order, start_migratetype, migratetype); return page; } } return NULL; } /* * Do the hard work of removing an element from the buddy allocator. * Call me with the zone->lock already held. */ static struct page *__rmqueue(struct zone *zone, unsigned int order, int migratetype) { struct page *page; retry_reserve: page = __rmqueue_smallest(zone, order, migratetype); if (unlikely(!page) && migratetype != MIGRATE_RESERVE) { page = __rmqueue_fallback(zone, order, migratetype); /* * Use MIGRATE_RESERVE rather than fail an allocation. goto * is used because __rmqueue_smallest is an inline function * and we want just one call site */ if (!page) { migratetype = MIGRATE_RESERVE; goto retry_reserve; } } trace_mm_page_alloc_zone_locked(page, order, migratetype); return page; } /* * Obtain a specified number of elements from the buddy allocator, all under * a single hold of the lock, for efficiency. Add them to the supplied list. * Returns the number of new pages which were placed at *list. */ static int rmqueue_bulk(struct zone *zone, unsigned int order, unsigned long count, struct list_head *list, int migratetype, int cold) { int i; spin_lock(&zone->lock); for (i = 0; i < count; ++i) { struct page *page = __rmqueue(zone, order, migratetype); if (unlikely(page == NULL)) break; /* * Split buddy pages returned by expand() are received here * in physical page order. The page is added to the callers and * list and the list head then moves forward. From the callers * perspective, the linked list is ordered by page number in * some conditions. This is useful for IO devices that can * merge IO requests if the physical pages are ordered * properly. */ if (likely(cold == 0)) list_add(&page->lru, list); else list_add_tail(&page->lru, list); set_page_private(page, migratetype); list = &page->lru; } __mod_zone_page_state(zone, NR_FREE_PAGES, -(i << order)); spin_unlock(&zone->lock); return i; } #ifdef CONFIG_NUMA /* * Called from the vmstat counter updater to drain pagesets of this * currently executing processor on remote nodes after they have * expired. * * Note that this function must be called with the thread pinned to * a single processor. */ void drain_zone_pages(struct zone *zone, struct per_cpu_pages *pcp) { unsigned long flags; int to_drain; local_irq_save(flags); if (pcp->count >= pcp->batch) to_drain = pcp->batch; else to_drain = pcp->count; free_pcppages_bulk(zone, to_drain, pcp); pcp->count -= to_drain; local_irq_restore(flags); } #endif /* * Drain pages of the indicated processor. * * The processor must either be the current processor and the * thread pinned to the current processor or a processor that * is not online. */ static void drain_pages(unsigned int cpu) { unsigned long flags; struct zone *zone; for_each_populated_zone(zone) { struct per_cpu_pageset *pset; struct per_cpu_pages *pcp; local_irq_save(flags); pset = per_cpu_ptr(zone->pageset, cpu); pcp = &pset->pcp; free_pcppages_bulk(zone, pcp->count, pcp); pcp->count = 0; local_irq_restore(flags); } } /* * Spill all of this CPU's per-cpu pages back into the buddy allocator. */ void drain_local_pages(void *arg) { drain_pages(smp_processor_id()); } /* * Spill all the per-cpu pages from all CPUs back into the buddy allocator */ void drain_all_pages(void) { on_each_cpu(drain_local_pages, NULL, 1); } #ifdef CONFIG_HIBERNATION void mark_free_pages(struct zone *zone) { unsigned long pfn, max_zone_pfn; unsigned long flags; int order, t; struct list_head *curr; if (!zone->spanned_pages) return; spin_lock_irqsave(&zone->lock, flags); max_zone_pfn = zone->zone_start_pfn + zone->spanned_pages; for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) if (pfn_valid(pfn)) { struct page *page = pfn_to_page(pfn); if (!swsusp_page_is_forbidden(page)) swsusp_unset_page_free(page); } for_each_migratetype_order(order, t) { list_for_each(curr, &zone->free_area[order].free_list[t]) { unsigned long i; pfn = page_to_pfn(list_entry(curr, struct page, lru)); for (i = 0; i < (1UL << order); i++) swsusp_set_page_free(pfn_to_page(pfn + i)); } } spin_unlock_irqrestore(&zone->lock, flags); } #endif /* CONFIG_PM */ /* * Free a 0-order page * cold == 1 ? free a cold page : free a hot page */ void free_hot_cold_page(struct page *page, int cold) { struct zone *zone = page_zone(page); struct per_cpu_pages *pcp; unsigned long flags; int migratetype; int wasMlocked = __TestClearPageMlocked(page); if (!free_pages_prepare(page, 0)) return; migratetype = get_pageblock_migratetype(page); set_page_private(page, migratetype); local_irq_save(flags); if (unlikely(wasMlocked)) free_page_mlock(page); __count_vm_event(PGFREE); /* * We only track unmovable, reclaimable and movable on pcp lists. * Free ISOLATE pages back to the allocator because they are being * offlined but treat RESERVE as movable pages so we can get those * areas back if necessary. Otherwise, we may have to free * excessively into the page allocator */ if (migratetype >= MIGRATE_PCPTYPES) { if (unlikely(migratetype == MIGRATE_ISOLATE)) { free_one_page(zone, page, 0, migratetype); goto out; } migratetype = MIGRATE_MOVABLE; } pcp = &this_cpu_ptr(zone->pageset)->pcp; if (cold) list_add_tail(&page->lru, &pcp->lists[migratetype]); else list_add(&page->lru, &pcp->lists[migratetype]); pcp->count++; if (pcp->count >= pcp->high) { free_pcppages_bulk(zone, pcp->batch, pcp); pcp->count -= pcp->batch; } out: local_irq_restore(flags); } /* * split_page takes a non-compound higher-order page, and splits it into * n (1<<order) sub-pages: page[0..n] * Each sub-page must be freed individually. * * Note: this is probably too low level an operation for use in drivers. * Please consult with lkml before using this in your driver. */ void split_page(struct page *page, unsigned int order) { int i; VM_BUG_ON(PageCompound(page)); VM_BUG_ON(!page_count(page)); #ifdef CONFIG_KMEMCHECK /* * Split shadow pages too, because free(page[0]) would * otherwise free the whole shadow. */ if (kmemcheck_page_is_tracked(page)) split_page(virt_to_page(page[0].shadow), order); #endif for (i = 1; i < (1 << order); i++) set_page_refcounted(page + i); } /* * Similar to split_page except the page is already free. As this is only * being used for migration, the migratetype of the block also changes. * As this is called with interrupts disabled, the caller is responsible * for calling arch_alloc_page() and kernel_map_page() after interrupts * are enabled. * * Note: this is probably too low level an operation for use in drivers. * Please consult with lkml before using this in your driver. */ int split_free_page(struct page *page) { unsigned int order; unsigned long watermark; struct zone *zone; BUG_ON(!PageBuddy(page)); zone = page_zone(page); order = page_order(page); /* Obey watermarks as if the page was being allocated */ watermark = low_wmark_pages(zone) + (1 << order); if (!zone_watermark_ok(zone, 0, watermark, 0, 0)) return 0; /* Remove page from free list */ list_del(&page->lru); zone->free_area[order].nr_free--; rmv_page_order(page); __mod_zone_page_state(zone, NR_FREE_PAGES, -(1UL << order)); /* Split into individual pages */ set_page_refcounted(page); split_page(page, order); if (order >= pageblock_order - 1) { struct page *endpage = page + (1 << order) - 1; for (; page < endpage; page += pageblock_nr_pages) set_pageblock_migratetype(page, MIGRATE_MOVABLE); } return 1 << order; } /* * Really, prep_compound_page() should be called from __rmqueue_bulk(). But * we cheat by calling it from here, in the order > 0 path. Saves a branch * or two. */ static inline struct page *buffered_rmqueue(struct zone *preferred_zone, struct zone *zone, int order, gfp_t gfp_flags, int migratetype) { unsigned long flags; struct page *page; int cold = !!(gfp_flags & __GFP_COLD); again: if (likely(order == 0)) { struct per_cpu_pages *pcp; struct list_head *list; local_irq_save(flags); pcp = &this_cpu_ptr(zone->pageset)->pcp; list = &pcp->lists[migratetype]; if (list_empty(list)) { pcp->count += rmqueue_bulk(zone, 0, pcp->batch, list, migratetype, cold); if (unlikely(list_empty(list))) goto failed; } if (cold) page = list_entry(list->prev, struct page, lru); else page = list_entry(list->next, struct page, lru); list_del(&page->lru); pcp->count--; } else { if (unlikely(gfp_flags & __GFP_NOFAIL)) { /* * __GFP_NOFAIL is not to be used in new code. * * All __GFP_NOFAIL callers should be fixed so that they * properly detect and handle allocation failures. * * We most definitely don't want callers attempting to * allocate greater than order-1 page units with * __GFP_NOFAIL. */ WARN_ON_ONCE(order > 1); } spin_lock_irqsave(&zone->lock, flags); page = __rmqueue(zone, order, migratetype); spin_unlock(&zone->lock); if (!page) goto failed; __mod_zone_page_state(zone, NR_FREE_PAGES, -(1 << order)); } __count_zone_vm_events(PGALLOC, zone, 1 << order); zone_statistics(preferred_zone, zone); local_irq_restore(flags); VM_BUG_ON(bad_range(zone, page)); if (prep_new_page(page, order, gfp_flags)) goto again; return page; failed: local_irq_restore(flags); return NULL; } /* The ALLOC_WMARK bits are used as an index to zone->watermark */ #define ALLOC_WMARK_MIN WMARK_MIN #define ALLOC_WMARK_LOW WMARK_LOW #define ALLOC_WMARK_HIGH WMARK_HIGH #define ALLOC_NO_WATERMARKS 0x04 /* don't check watermarks at all */ /* Mask to get the watermark bits */ #define ALLOC_WMARK_MASK (ALLOC_NO_WATERMARKS-1) #define ALLOC_HARDER 0x10 /* try to alloc harder */ #define ALLOC_HIGH 0x20 /* __GFP_HIGH set */ #define ALLOC_CPUSET 0x40 /* check for correct cpuset */ #ifdef CONFIG_FAIL_PAGE_ALLOC static struct fail_page_alloc_attr { struct fault_attr attr; u32 ignore_gfp_highmem; u32 ignore_gfp_wait; u32 min_order; #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS struct dentry *ignore_gfp_highmem_file; struct dentry *ignore_gfp_wait_file; struct dentry *min_order_file; #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */ } fail_page_alloc = { .attr = FAULT_ATTR_INITIALIZER, .ignore_gfp_wait = 1, .ignore_gfp_highmem = 1, .min_order = 1, }; static int __init setup_fail_page_alloc(char *str) { return setup_fault_attr(&fail_page_alloc.attr, str); } __setup("fail_page_alloc=", setup_fail_page_alloc); static int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) { if (order < fail_page_alloc.min_order) return 0; if (gfp_mask & __GFP_NOFAIL) return 0; if (fail_page_alloc.ignore_gfp_highmem && (gfp_mask & __GFP_HIGHMEM)) return 0; if (fail_page_alloc.ignore_gfp_wait && (gfp_mask & __GFP_WAIT)) return 0; return should_fail(&fail_page_alloc.attr, 1 << order); } #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS static int __init fail_page_alloc_debugfs(void) { mode_t mode = S_IFREG | S_IRUSR | S_IWUSR; struct dentry *dir; int err; err = init_fault_attr_dentries(&fail_page_alloc.attr, "fail_page_alloc"); if (err) return err; dir = fail_page_alloc.attr.dentries.dir; fail_page_alloc.ignore_gfp_wait_file = debugfs_create_bool("ignore-gfp-wait", mode, dir, &fail_page_alloc.ignore_gfp_wait); fail_page_alloc.ignore_gfp_highmem_file = debugfs_create_bool("ignore-gfp-highmem", mode, dir, &fail_page_alloc.ignore_gfp_highmem); fail_page_alloc.min_order_file = debugfs_create_u32("min-order", mode, dir, &fail_page_alloc.min_order); if (!fail_page_alloc.ignore_gfp_wait_file || !fail_page_alloc.ignore_gfp_highmem_file || !fail_page_alloc.min_order_file) { err = -ENOMEM; debugfs_remove(fail_page_alloc.ignore_gfp_wait_file); debugfs_remove(fail_page_alloc.ignore_gfp_highmem_file); debugfs_remove(fail_page_alloc.min_order_file); cleanup_fault_attr_dentries(&fail_page_alloc.attr); } return err; } late_initcall(fail_page_alloc_debugfs); #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */ #else /* CONFIG_FAIL_PAGE_ALLOC */ static inline int should_fail_alloc_page(gfp_t gfp_mask, unsigned int order) { return 0; } #endif /* CONFIG_FAIL_PAGE_ALLOC */ /* * Return true if free pages are above 'mark'. This takes into account the order * of the allocation. */ static bool __zone_watermark_ok(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags, long free_pages) { /* free_pages my go negative - that's OK */ long min = mark; int o; free_pages -= (1 << order) + 1; if (alloc_flags & ALLOC_HIGH) min -= min / 2; if (alloc_flags & ALLOC_HARDER) min -= min / 4; if (free_pages <= min + z->lowmem_reserve[classzone_idx]) return false; for (o = 0; o < order; o++) { /* At the next order, this order's pages become unavailable */ free_pages -= z->free_area[o].nr_free << o; /* Require fewer higher order pages to be free */ min >>= min_free_order_shift; if (free_pages <= min) return false; } return true; } bool zone_watermark_ok(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags) { return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags, zone_page_state(z, NR_FREE_PAGES)); } bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark, int classzone_idx, int alloc_flags) { long free_pages = zone_page_state(z, NR_FREE_PAGES); if (z->percpu_drift_mark && free_pages < z->percpu_drift_mark) free_pages = zone_page_state_snapshot(z, NR_FREE_PAGES); return __zone_watermark_ok(z, order, mark, classzone_idx, alloc_flags, free_pages); } #ifdef CONFIG_NUMA /* * zlc_setup - Setup for "zonelist cache". Uses cached zone data to * skip over zones that are not allowed by the cpuset, or that have * been recently (in last second) found to be nearly full. See further * comments in mmzone.h. Reduces cache footprint of zonelist scans * that have to skip over a lot of full or unallowed zones. * * If the zonelist cache is present in the passed in zonelist, then * returns a pointer to the allowed node mask (either the current * tasks mems_allowed, or node_states[N_HIGH_MEMORY].) * * If the zonelist cache is not available for this zonelist, does * nothing and returns NULL. * * If the fullzones BITMAP in the zonelist cache is stale (more than * a second since last zap'd) then we zap it out (clear its bits.) * * We hold off even calling zlc_setup, until after we've checked the * first zone in the zonelist, on the theory that most allocations will * be satisfied from that first zone, so best to examine that zone as * quickly as we can. */ static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags) { struct zonelist_cache *zlc; /* cached zonelist speedup info */ nodemask_t *allowednodes; /* zonelist_cache approximation */ zlc = zonelist->zlcache_ptr; if (!zlc) return NULL; if (time_after(jiffies, zlc->last_full_zap + HZ)) { bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST); zlc->last_full_zap = jiffies; } allowednodes = !in_interrupt() && (alloc_flags & ALLOC_CPUSET) ? &cpuset_current_mems_allowed : &node_states[N_HIGH_MEMORY]; return allowednodes; } /* * Given 'z' scanning a zonelist, run a couple of quick checks to see * if it is worth looking at further for free memory: * 1) Check that the zone isn't thought to be full (doesn't have its * bit set in the zonelist_cache fullzones BITMAP). * 2) Check that the zones node (obtained from the zonelist_cache * z_to_n[] mapping) is allowed in the passed in allowednodes mask. * Return true (non-zero) if zone is worth looking at further, or * else return false (zero) if it is not. * * This check -ignores- the distinction between various watermarks, * such as GFP_HIGH, GFP_ATOMIC, PF_MEMALLOC, ... If a zone is * found to be full for any variation of these watermarks, it will * be considered full for up to one second by all requests, unless * we are so low on memory on all allowed nodes that we are forced * into the second scan of the zonelist. * * In the second scan we ignore this zonelist cache and exactly * apply the watermarks to all zones, even it is slower to do so. * We are low on memory in the second scan, and should leave no stone * unturned looking for a free page. */ static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z, nodemask_t *allowednodes) { struct zonelist_cache *zlc; /* cached zonelist speedup info */ int i; /* index of *z in zonelist zones */ int n; /* node that zone *z is on */ zlc = zonelist->zlcache_ptr; if (!zlc) return 1; i = z - zonelist->_zonerefs; n = zlc->z_to_n[i]; /* This zone is worth trying if it is allowed but not full */ return node_isset(n, *allowednodes) && !test_bit(i, zlc->fullzones); } /* * Given 'z' scanning a zonelist, set the corresponding bit in * zlc->fullzones, so that subsequent attempts to allocate a page * from that zone don't waste time re-examining it. */ static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z) { struct zonelist_cache *zlc; /* cached zonelist speedup info */ int i; /* index of *z in zonelist zones */ zlc = zonelist->zlcache_ptr; if (!zlc) return; i = z - zonelist->_zonerefs; set_bit(i, zlc->fullzones); } #else /* CONFIG_NUMA */ static nodemask_t *zlc_setup(struct zonelist *zonelist, int alloc_flags) { return NULL; } static int zlc_zone_worth_trying(struct zonelist *zonelist, struct zoneref *z, nodemask_t *allowednodes) { return 1; } static void zlc_mark_zone_full(struct zonelist *zonelist, struct zoneref *z) { } #endif /* CONFIG_NUMA */ /* * get_page_from_freelist goes through the zonelist trying to allocate * a page. */ static struct page * get_page_from_freelist(gfp_t gfp_mask, nodemask_t *nodemask, unsigned int order, struct zonelist *zonelist, int high_zoneidx, int alloc_flags, struct zone *preferred_zone, int migratetype) { struct zoneref *z; struct page *page = NULL; int classzone_idx; struct zone *zone; nodemask_t *allowednodes = NULL;/* zonelist_cache approximation */ int zlc_active = 0; /* set if using zonelist_cache */ int did_zlc_setup = 0; /* just call zlc_setup() one time */ classzone_idx = zone_idx(preferred_zone); zonelist_scan: /* * Scan zonelist, looking for a zone with enough free. * See also cpuset_zone_allowed() comment in kernel/cpuset.c. */ for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx, nodemask) { if (NUMA_BUILD && zlc_active && !zlc_zone_worth_trying(zonelist, z, allowednodes)) continue; if ((alloc_flags & ALLOC_CPUSET) && !cpuset_zone_allowed_softwall(zone, gfp_mask)) goto try_next_zone; BUILD_BUG_ON(ALLOC_NO_WATERMARKS < NR_WMARK); if (!(alloc_flags & ALLOC_NO_WATERMARKS)) { unsigned long mark; int ret; mark = zone->watermark[alloc_flags & ALLOC_WMARK_MASK]; if (zone_watermark_ok(zone, order, mark, classzone_idx, alloc_flags)) goto try_this_zone; if (zone_reclaim_mode == 0) goto this_zone_full; ret = zone_reclaim(zone, gfp_mask, order); switch (ret) { case ZONE_RECLAIM_NOSCAN: /* did not scan */ goto try_next_zone; case ZONE_RECLAIM_FULL: /* scanned but unreclaimable */ goto this_zone_full; default: /* did we reclaim enough */ if (!zone_watermark_ok(zone, order, mark, classzone_idx, alloc_flags)) goto this_zone_full; } } try_this_zone: page = buffered_rmqueue(preferred_zone, zone, order, gfp_mask, migratetype); if (page) break; this_zone_full: if (NUMA_BUILD) zlc_mark_zone_full(zonelist, z); try_next_zone: if (NUMA_BUILD && !did_zlc_setup && nr_online_nodes > 1) { /* * we do zlc_setup after the first zone is tried but only * if there are multiple nodes make it worthwhile */ allowednodes = zlc_setup(zonelist, alloc_flags); zlc_active = 1; did_zlc_setup = 1; } } if (unlikely(NUMA_BUILD && page == NULL && zlc_active)) { /* Disable zlc cache for second zonelist scan */ zlc_active = 0; goto zonelist_scan; } return page; } static inline int should_alloc_retry(gfp_t gfp_mask, unsigned int order, unsigned long pages_reclaimed) { /* Do not loop if specifically requested */ if (gfp_mask & __GFP_NORETRY) return 0; /* * In this implementation, order <= PAGE_ALLOC_COSTLY_ORDER * means __GFP_NOFAIL, but that may not be true in other * implementations. */ if (order <= PAGE_ALLOC_COSTLY_ORDER) return 1; /* * For order > PAGE_ALLOC_COSTLY_ORDER, if __GFP_REPEAT is * specified, then we retry until we no longer reclaim any pages * (above), or we've reclaimed an order of pages at least as * large as the allocation's order. In both cases, if the * allocation still fails, we stop retrying. */ if (gfp_mask & __GFP_REPEAT && pages_reclaimed < (1 << order)) return 1; /* * Don't let big-order allocations loop unless the caller * explicitly requests that. */ if (gfp_mask & __GFP_NOFAIL) return 1; return 0; } static inline struct page * __alloc_pages_may_oom(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, struct zone *preferred_zone, int migratetype) { struct page *page; /* Acquire the OOM killer lock for the zones in zonelist */ if (!try_set_zone_oom(zonelist, gfp_mask)) { schedule_timeout_uninterruptible(1); return NULL; } /* * Go through the zonelist yet one more time, keep very high watermark * here, this is only to catch a parallel oom killing, we must fail if * we're still under heavy pressure. */ page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order, zonelist, high_zoneidx, ALLOC_WMARK_HIGH|ALLOC_CPUSET, preferred_zone, migratetype); if (page) goto out; if (!(gfp_mask & __GFP_NOFAIL)) { /* The OOM killer will not help higher order allocs */ if (order > PAGE_ALLOC_COSTLY_ORDER) goto out; /* The OOM killer does not needlessly kill tasks for lowmem */ if (high_zoneidx < ZONE_NORMAL) goto out; /* * GFP_THISNODE contains __GFP_NORETRY and we never hit this. * Sanity check for bare calls of __GFP_THISNODE, not real OOM. * The caller should handle page allocation failure by itself if * it specifies __GFP_THISNODE. * Note: Hugepage uses it but will hit PAGE_ALLOC_COSTLY_ORDER. */ if (gfp_mask & __GFP_THISNODE) goto out; } /* Exhausted what can be done so it's blamo time */ out_of_memory(zonelist, gfp_mask, order, nodemask); out: clear_zonelist_oom(zonelist, gfp_mask); return page; } #ifdef CONFIG_COMPACTION /* Try memory compaction for high-order allocations before reclaim */ static struct page * __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone, int migratetype, unsigned long *did_some_progress) { struct page *page; if (!order || compaction_deferred(preferred_zone)) return NULL; *did_some_progress = try_to_compact_pages(zonelist, order, gfp_mask, nodemask); if (*did_some_progress != COMPACT_SKIPPED) { /* Page migration frees to the PCP lists but we want merging */ drain_pages(get_cpu()); put_cpu(); page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist, high_zoneidx, alloc_flags, preferred_zone, migratetype); if (page) { preferred_zone->compact_considered = 0; preferred_zone->compact_defer_shift = 0; count_vm_event(COMPACTSUCCESS); return page; } /* * It's bad if compaction run occurs and fails. * The most likely reason is that pages exist, * but not enough to satisfy watermarks. */ count_vm_event(COMPACTFAIL); defer_compaction(preferred_zone); cond_resched(); } return NULL; } #else static inline struct page * __alloc_pages_direct_compact(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone, int migratetype, unsigned long *did_some_progress) { return NULL; } #endif /* CONFIG_COMPACTION */ /* The really slow allocator path where we enter direct reclaim */ static inline struct page * __alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, int alloc_flags, struct zone *preferred_zone, int migratetype, unsigned long *did_some_progress) { struct page *page = NULL; struct reclaim_state reclaim_state; struct task_struct *p = current; bool drained = false; cond_resched(); /* We now go into synchronous reclaim */ cpuset_memory_pressure_bump(); p->flags |= PF_MEMALLOC; lockdep_set_current_reclaim_state(gfp_mask); reclaim_state.reclaimed_slab = 0; p->reclaim_state = &reclaim_state; *did_some_progress = try_to_free_pages(zonelist, order, gfp_mask, nodemask); p->reclaim_state = NULL; lockdep_clear_current_reclaim_state(); p->flags &= ~PF_MEMALLOC; cond_resched(); if (unlikely(!(*did_some_progress))) return NULL; retry: page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist, high_zoneidx, alloc_flags, preferred_zone, migratetype); /* * If an allocation failed after direct reclaim, it could be because * pages are pinned on the per-cpu lists. Drain them and try again */ if (!page && !drained) { drain_all_pages(); drained = true; goto retry; } return page; } /* * This is called in the allocator slow-path if the allocation request is of * sufficient urgency to ignore watermarks and take other desperate measures */ static inline struct page * __alloc_pages_high_priority(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, struct zone *preferred_zone, int migratetype) { struct page *page; do { page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist, high_zoneidx, ALLOC_NO_WATERMARKS, preferred_zone, migratetype); if (!page && gfp_mask & __GFP_NOFAIL) congestion_wait(BLK_RW_ASYNC, HZ/50); } while (!page && (gfp_mask & __GFP_NOFAIL)); return page; } static inline void wake_all_kswapd(unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx) { struct zoneref *z; struct zone *zone; for_each_zone_zonelist(zone, z, zonelist, high_zoneidx) wakeup_kswapd(zone, order); } static inline int gfp_to_alloc_flags(gfp_t gfp_mask) { struct task_struct *p = current; int alloc_flags = ALLOC_WMARK_MIN | ALLOC_CPUSET; const gfp_t wait = gfp_mask & __GFP_WAIT; /* __GFP_HIGH is assumed to be the same as ALLOC_HIGH to save a branch. */ BUILD_BUG_ON(__GFP_HIGH != ALLOC_HIGH); /* * The caller may dip into page reserves a bit more if the caller * cannot run direct reclaim, or if the caller has realtime scheduling * policy or is asking for __GFP_HIGH memory. GFP_ATOMIC requests will * set both ALLOC_HARDER (!wait) and ALLOC_HIGH (__GFP_HIGH). */ alloc_flags |= (gfp_mask & __GFP_HIGH); if (!wait) { alloc_flags |= ALLOC_HARDER; /* * Ignore cpuset if GFP_ATOMIC (!wait) rather than fail alloc. * See also cpuset_zone_allowed() comment in kernel/cpuset.c. */ alloc_flags &= ~ALLOC_CPUSET; } else if (unlikely(rt_task(p)) && !in_interrupt()) alloc_flags |= ALLOC_HARDER; if (likely(!(gfp_mask & __GFP_NOMEMALLOC))) { if (!in_interrupt() && ((p->flags & PF_MEMALLOC) || unlikely(test_thread_flag(TIF_MEMDIE)))) alloc_flags |= ALLOC_NO_WATERMARKS; } return alloc_flags; } static inline struct page * __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, enum zone_type high_zoneidx, nodemask_t *nodemask, struct zone *preferred_zone, int migratetype) { const gfp_t wait = gfp_mask & __GFP_WAIT; struct page *page = NULL; int alloc_flags; unsigned long pages_reclaimed = 0; unsigned long did_some_progress; struct task_struct *p = current; /* * In the slowpath, we sanity check order to avoid ever trying to * reclaim >= MAX_ORDER areas which will never succeed. Callers may * be using allocators in order of preference for an area that is * too large. */ if (order >= MAX_ORDER) { WARN_ON_ONCE(!(gfp_mask & __GFP_NOWARN)); return NULL; } /* * GFP_THISNODE (meaning __GFP_THISNODE, __GFP_NORETRY and * __GFP_NOWARN set) should not cause reclaim since the subsystem * (f.e. slab) using GFP_THISNODE may choose to trigger reclaim * using a larger set of nodes after it has established that the * allowed per node queues are empty and that nodes are * over allocated. */ if (NUMA_BUILD && (gfp_mask & GFP_THISNODE) == GFP_THISNODE) goto nopage; restart: wake_all_kswapd(order, zonelist, high_zoneidx); /* * OK, we're below the kswapd watermark and have kicked background * reclaim. Now things get more complex, so set up alloc_flags according * to how we want to proceed. */ alloc_flags = gfp_to_alloc_flags(gfp_mask); rebalance: /* This is the last chance, in general, before the goto nopage. */ page = get_page_from_freelist(gfp_mask, nodemask, order, zonelist, high_zoneidx, alloc_flags & ~ALLOC_NO_WATERMARKS, preferred_zone, migratetype); if (page) goto got_pg; /* Allocate without watermarks if the context allows */ if (alloc_flags & ALLOC_NO_WATERMARKS) { page = __alloc_pages_high_priority(gfp_mask, order, zonelist, high_zoneidx, nodemask, preferred_zone, migratetype); if (page) goto got_pg; } /* Atomic allocations - we can't balance anything */ if (!wait) goto nopage; /* Avoid recursion of direct reclaim */ if (p->flags & PF_MEMALLOC) goto nopage; /* Avoid allocations with no watermarks from looping endlessly */ if (test_thread_flag(TIF_MEMDIE) && !(gfp_mask & __GFP_NOFAIL)) goto nopage; /* Try direct compaction */ page = __alloc_pages_direct_compact(gfp_mask, order, zonelist, high_zoneidx, nodemask, alloc_flags, preferred_zone, migratetype, &did_some_progress); if (page) goto got_pg; /* Try direct reclaim and then allocating */ page = __alloc_pages_direct_reclaim(gfp_mask, order, zonelist, high_zoneidx, nodemask, alloc_flags, preferred_zone, migratetype, &did_some_progress); if (page) goto got_pg; /* * If we failed to make any progress reclaiming, then we are * running out of options and have to consider going OOM */ if (!did_some_progress) { if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY)) { if (oom_killer_disabled) goto nopage; page = __alloc_pages_may_oom(gfp_mask, order, zonelist, high_zoneidx, nodemask, preferred_zone, migratetype); if (page) goto got_pg; if (!(gfp_mask & __GFP_NOFAIL)) { /* * The oom killer is not called for high-order * allocations that may fail, so if no progress * is being made, there are no other options and * retrying is unlikely to help. */ if (order > PAGE_ALLOC_COSTLY_ORDER) goto nopage; /* * The oom killer is not called for lowmem * allocations to prevent needlessly killing * innocent tasks. */ if (high_zoneidx < ZONE_NORMAL) goto nopage; } goto restart; } } /* Check if we should retry the allocation */ pages_reclaimed += did_some_progress; if (should_alloc_retry(gfp_mask, order, pages_reclaimed)) { /* Wait for some write requests to complete then retry */ congestion_wait(BLK_RW_ASYNC, HZ/50); goto rebalance; } nopage: if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit()) { printk(KERN_WARNING "%s: page allocation failure." " order:%d, mode:0x%x\n", p->comm, order, gfp_mask); dump_stack(); show_mem(); } return page; got_pg: if (kmemcheck_enabled) kmemcheck_pagealloc_alloc(page, order, gfp_mask); return page; } /* * This is the 'heart' of the zoned buddy allocator. */ struct page * __alloc_pages_nodemask(gfp_t gfp_mask, unsigned int order, struct zonelist *zonelist, nodemask_t *nodemask) { enum zone_type high_zoneidx = gfp_zone(gfp_mask); struct zone *preferred_zone; struct page *page; int migratetype = allocflags_to_migratetype(gfp_mask); gfp_mask &= gfp_allowed_mask; lockdep_trace_alloc(gfp_mask); might_sleep_if(gfp_mask & __GFP_WAIT); if (should_fail_alloc_page(gfp_mask, order)) return NULL; /* * Check the zones suitable for the gfp_mask contain at least one * valid zone. It's possible to have an empty zonelist as a result * of GFP_THISNODE and a memoryless node */ if (unlikely(!zonelist->_zonerefs->zone)) return NULL; get_mems_allowed(); /* The preferred zone is used for statistics later */ first_zones_zonelist(zonelist, high_zoneidx, nodemask, &preferred_zone); if (!preferred_zone) { put_mems_allowed(); return NULL; } /* First allocation attempt */ page = get_page_from_freelist(gfp_mask|__GFP_HARDWALL, nodemask, order, zonelist, high_zoneidx, ALLOC_WMARK_LOW|ALLOC_CPUSET, preferred_zone, migratetype); if (unlikely(!page)) page = __alloc_pages_slowpath(gfp_mask, order, zonelist, high_zoneidx, nodemask, preferred_zone, migratetype); put_mems_allowed(); trace_mm_page_alloc(page, order, gfp_mask, migratetype); return page; } EXPORT_SYMBOL(__alloc_pages_nodemask); /* * Common helper functions. */ unsigned long __get_free_pages(gfp_t gfp_mask, unsigned int order) { struct page *page; /* * __get_free_pages() returns a 32-bit address, which cannot represent * a highmem page */ VM_BUG_ON((gfp_mask & __GFP_HIGHMEM) != 0); page = alloc_pages(gfp_mask, order); if (!page) return 0; return (unsigned long) page_address(page); } EXPORT_SYMBOL(__get_free_pages); unsigned long get_zeroed_page(gfp_t gfp_mask) { return __get_free_pages(gfp_mask | __GFP_ZERO, 0); } EXPORT_SYMBOL(get_zeroed_page); void __pagevec_free(struct pagevec *pvec) { int i = pagevec_count(pvec); while (--i >= 0) { trace_mm_pagevec_free(pvec->pages[i], pvec->cold); free_hot_cold_page(pvec->pages[i], pvec->cold); } } void __free_pages(struct page *page, unsigned int order) { if (put_page_testzero(page)) { if (order == 0) free_hot_cold_page(page, 0); else __free_pages_ok(page, order); } } EXPORT_SYMBOL(__free_pages); void free_pages(unsigned long addr, unsigned int order) { if (addr != 0) { VM_BUG_ON(!virt_addr_valid((void *)addr)); __free_pages(virt_to_page((void *)addr), order); } } EXPORT_SYMBOL(free_pages); /** * alloc_pages_exact - allocate an exact number physically-contiguous pages. * @size: the number of bytes to allocate * @gfp_mask: GFP flags for the allocation * * This function is similar to alloc_pages(), except that it allocates the * minimum number of pages to satisfy the request. alloc_pages() can only * allocate memory in power-of-two pages. * * This function is also limited by MAX_ORDER. * * Memory allocated by this function must be released by free_pages_exact(). */ void *alloc_pages_exact(size_t size, gfp_t gfp_mask) { unsigned int order = get_order(size); unsigned long addr; addr = __get_free_pages(gfp_mask, order); if (addr) { unsigned long alloc_end = addr + (PAGE_SIZE << order); unsigned long used = addr + PAGE_ALIGN(size); split_page(virt_to_page((void *)addr), order); while (used < alloc_end) { free_page(used); used += PAGE_SIZE; } } return (void *)addr; } EXPORT_SYMBOL(alloc_pages_exact); /** * free_pages_exact - release memory allocated via alloc_pages_exact() * @virt: the value returned by alloc_pages_exact. * @size: size of allocation, same value as passed to alloc_pages_exact(). * * Release the memory allocated by a previous call to alloc_pages_exact. */ void free_pages_exact(void *virt, size_t size) { unsigned long addr = (unsigned long)virt; unsigned long end = addr + PAGE_ALIGN(size); while (addr < end) { free_page(addr); addr += PAGE_SIZE; } } EXPORT_SYMBOL(free_pages_exact); static unsigned int nr_free_zone_pages(int offset) { struct zoneref *z; struct zone *zone; /* Just pick one node, since fallback list is circular */ unsigned int sum = 0; struct zonelist *zonelist = node_zonelist(numa_node_id(), GFP_KERNEL); for_each_zone_zonelist(zone, z, zonelist, offset) { unsigned long size = zone->present_pages; unsigned long high = high_wmark_pages(zone); if (size > high) sum += size - high; } return sum; } /* * Amount of free RAM allocatable within ZONE_DMA and ZONE_NORMAL */ unsigned int nr_free_buffer_pages(void) { return nr_free_zone_pages(gfp_zone(GFP_USER)); } EXPORT_SYMBOL_GPL(nr_free_buffer_pages); /* * Amount of free RAM allocatable within all zones */ unsigned int nr_free_pagecache_pages(void) { return nr_free_zone_pages(gfp_zone(GFP_HIGHUSER_MOVABLE)); } static inline void show_node(struct zone *zone) { if (NUMA_BUILD) printk("Node %d ", zone_to_nid(zone)); } void si_meminfo(struct sysinfo *val) { val->totalram = totalram_pages; val->sharedram = 0; val->freeram = global_page_state(NR_FREE_PAGES); val->bufferram = nr_blockdev_pages(); val->totalhigh = totalhigh_pages; val->freehigh = nr_free_highpages(); val->mem_unit = PAGE_SIZE; } EXPORT_SYMBOL(si_meminfo); #ifdef CONFIG_NUMA void si_meminfo_node(struct sysinfo *val, int nid) { pg_data_t *pgdat = NODE_DATA(nid); val->totalram = pgdat->node_present_pages; val->freeram = node_page_state(nid, NR_FREE_PAGES); #ifdef CONFIG_HIGHMEM val->totalhigh = pgdat->node_zones[ZONE_HIGHMEM].present_pages; val->freehigh = zone_page_state(&pgdat->node_zones[ZONE_HIGHMEM], NR_FREE_PAGES); #else val->totalhigh = 0; val->freehigh = 0; #endif val->mem_unit = PAGE_SIZE; } #endif #define K(x) ((x) << (PAGE_SHIFT-10)) /* * Show free area list (used inside shift_scroll-lock stuff) * We also calculate the percentage fragmentation. We do this by counting the * memory on each free list with the exception of the first item on the list. */ void show_free_areas(void) { int cpu; struct zone *zone; for_each_populated_zone(zone) { show_node(zone); printk("%s per-cpu:\n", zone->name); for_each_online_cpu(cpu) { struct per_cpu_pageset *pageset; pageset = per_cpu_ptr(zone->pageset, cpu); printk("CPU %4d: hi:%5d, btch:%4d usd:%4d\n", cpu, pageset->pcp.high, pageset->pcp.batch, pageset->pcp.count); } } printk("active_anon:%lu inactive_anon:%lu isolated_anon:%lu\n" " active_file:%lu inactive_file:%lu isolated_file:%lu\n" " unevictable:%lu" " dirty:%lu writeback:%lu unstable:%lu\n" " free:%lu slab_reclaimable:%lu slab_unreclaimable:%lu\n" " mapped:%lu shmem:%lu pagetables:%lu bounce:%lu\n", global_page_state(NR_ACTIVE_ANON), global_page_state(NR_INACTIVE_ANON), global_page_state(NR_ISOLATED_ANON), global_page_state(NR_ACTIVE_FILE), global_page_state(NR_INACTIVE_FILE), global_page_state(NR_ISOLATED_FILE), global_page_state(NR_UNEVICTABLE), global_page_state(NR_FILE_DIRTY), global_page_state(NR_WRITEBACK), global_page_state(NR_UNSTABLE_NFS), global_page_state(NR_FREE_PAGES), global_page_state(NR_SLAB_RECLAIMABLE), global_page_state(NR_SLAB_UNRECLAIMABLE), global_page_state(NR_FILE_MAPPED), global_page_state(NR_SHMEM), global_page_state(NR_PAGETABLE), global_page_state(NR_BOUNCE)); for_each_populated_zone(zone) { int i; show_node(zone); printk("%s" " free:%lukB" " min:%lukB" " low:%lukB" " high:%lukB" " active_anon:%lukB" " inactive_anon:%lukB" " active_file:%lukB" " inactive_file:%lukB" " unevictable:%lukB" " isolated(anon):%lukB" " isolated(file):%lukB" " present:%lukB" " mlocked:%lukB" " dirty:%lukB" " writeback:%lukB" " mapped:%lukB" " shmem:%lukB" " slab_reclaimable:%lukB" " slab_unreclaimable:%lukB" " kernel_stack:%lukB" " pagetables:%lukB" " unstable:%lukB" " bounce:%lukB" " writeback_tmp:%lukB" " pages_scanned:%lu" " all_unreclaimable? %s" "\n", zone->name, K(zone_page_state(zone, NR_FREE_PAGES)), K(min_wmark_pages(zone)), K(low_wmark_pages(zone)), K(high_wmark_pages(zone)), K(zone_page_state(zone, NR_ACTIVE_ANON)), K(zone_page_state(zone, NR_INACTIVE_ANON)), K(zone_page_state(zone, NR_ACTIVE_FILE)), K(zone_page_state(zone, NR_INACTIVE_FILE)), K(zone_page_state(zone, NR_UNEVICTABLE)), K(zone_page_state(zone, NR_ISOLATED_ANON)), K(zone_page_state(zone, NR_ISOLATED_FILE)), K(zone->present_pages), K(zone_page_state(zone, NR_MLOCK)), K(zone_page_state(zone, NR_FILE_DIRTY)), K(zone_page_state(zone, NR_WRITEBACK)), K(zone_page_state(zone, NR_FILE_MAPPED)), K(zone_page_state(zone, NR_SHMEM)), K(zone_page_state(zone, NR_SLAB_RECLAIMABLE)), K(zone_page_state(zone, NR_SLAB_UNRECLAIMABLE)), zone_page_state(zone, NR_KERNEL_STACK) * THREAD_SIZE / 1024, K(zone_page_state(zone, NR_PAGETABLE)), K(zone_page_state(zone, NR_UNSTABLE_NFS)), K(zone_page_state(zone, NR_BOUNCE)), K(zone_page_state(zone, NR_WRITEBACK_TEMP)), zone->pages_scanned, (zone->all_unreclaimable ? "yes" : "no") ); printk("lowmem_reserve[]:"); for (i = 0; i < MAX_NR_ZONES; i++) printk(" %lu", zone->lowmem_reserve[i]); printk("\n"); } for_each_populated_zone(zone) { unsigned long nr[MAX_ORDER], flags, order, total = 0; show_node(zone); printk("%s: ", zone->name); spin_lock_irqsave(&zone->lock, flags); for (order = 0; order < MAX_ORDER; order++) { nr[order] = zone->free_area[order].nr_free; total += nr[order] << order; } spin_unlock_irqrestore(&zone->lock, flags); for (order = 0; order < MAX_ORDER; order++) printk("%lu*%lukB ", nr[order], K(1UL) << order); printk("= %lukB\n", K(total)); } printk("%ld total pagecache pages\n", global_page_state(NR_FILE_PAGES)); show_swap_cache_info(); } static void zoneref_set_zone(struct zone *zone, struct zoneref *zoneref) { zoneref->zone = zone; zoneref->zone_idx = zone_idx(zone); } /* * Builds allocation fallback zone lists. * * Add all populated zones of a node to the zonelist. */ static int build_zonelists_node(pg_data_t *pgdat, struct zonelist *zonelist, int nr_zones, enum zone_type zone_type) { struct zone *zone; BUG_ON(zone_type >= MAX_NR_ZONES); zone_type++; do { zone_type--; zone = pgdat->node_zones + zone_type; if (populated_zone(zone)) { zoneref_set_zone(zone, &zonelist->_zonerefs[nr_zones++]); check_highest_zone(zone_type); } } while (zone_type); return nr_zones; } /* * zonelist_order: * 0 = automatic detection of better ordering. * 1 = order by ([node] distance, -zonetype) * 2 = order by (-zonetype, [node] distance) * * If not NUMA, ZONELIST_ORDER_ZONE and ZONELIST_ORDER_NODE will create * the same zonelist. So only NUMA can configure this param. */ #define ZONELIST_ORDER_DEFAULT 0 #define ZONELIST_ORDER_NODE 1 #define ZONELIST_ORDER_ZONE 2 /* zonelist order in the kernel. * set_zonelist_order() will set this to NODE or ZONE. */ static int current_zonelist_order = ZONELIST_ORDER_DEFAULT; static char zonelist_order_name[3][8] = {"Default", "Node", "Zone"}; #ifdef CONFIG_NUMA /* The value user specified ....changed by config */ static int user_zonelist_order = ZONELIST_ORDER_DEFAULT; /* string for sysctl */ #define NUMA_ZONELIST_ORDER_LEN 16 char numa_zonelist_order[16] = "default"; /* * interface for configure zonelist ordering. * command line option "numa_zonelist_order" * = "[dD]efault - default, automatic configuration. * = "[nN]ode - order by node locality, then by zone within node * = "[zZ]one - order by zone, then by locality within zone */ static int __parse_numa_zonelist_order(char *s) { if (*s == 'd' || *s == 'D') { user_zonelist_order = ZONELIST_ORDER_DEFAULT; } else if (*s == 'n' || *s == 'N') { user_zonelist_order = ZONELIST_ORDER_NODE; } else if (*s == 'z' || *s == 'Z') { user_zonelist_order = ZONELIST_ORDER_ZONE; } else { printk(KERN_WARNING "Ignoring invalid numa_zonelist_order value: " "%s\n", s); return -EINVAL; } return 0; } static __init int setup_numa_zonelist_order(char *s) { if (s) return __parse_numa_zonelist_order(s); return 0; } early_param("numa_zonelist_order", setup_numa_zonelist_order); /* * sysctl handler for numa_zonelist_order */ int numa_zonelist_order_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { char saved_string[NUMA_ZONELIST_ORDER_LEN]; int ret; static DEFINE_MUTEX(zl_order_mutex); mutex_lock(&zl_order_mutex); if (write) strcpy(saved_string, (char*)table->data); ret = proc_dostring(table, write, buffer, length, ppos); if (ret) goto out; if (write) { int oldval = user_zonelist_order; if (__parse_numa_zonelist_order((char*)table->data)) { /* * bogus value. restore saved string */ strncpy((char*)table->data, saved_string, NUMA_ZONELIST_ORDER_LEN); user_zonelist_order = oldval; } else if (oldval != user_zonelist_order) { mutex_lock(&zonelists_mutex); build_all_zonelists(NULL); mutex_unlock(&zonelists_mutex); } } out: mutex_unlock(&zl_order_mutex); return ret; } #define MAX_NODE_LOAD (nr_online_nodes) static int node_load[MAX_NUMNODES]; /** * find_next_best_node - find the next node that should appear in a given node's fallback list * @node: node whose fallback list we're appending * @used_node_mask: nodemask_t of already used nodes * * We use a number of factors to determine which is the next node that should * appear on a given node's fallback list. The node should not have appeared * already in @node's fallback list, and it should be the next closest node * according to the distance array (which contains arbitrary distance values * from each node to each node in the system), and should also prefer nodes * with no CPUs, since presumably they'll have very little allocation pressure * on them otherwise. * It returns -1 if no node is found. */ static int find_next_best_node(int node, nodemask_t *used_node_mask) { int n, val; int min_val = INT_MAX; int best_node = -1; const struct cpumask *tmp = cpumask_of_node(0); /* Use the local node if we haven't already */ if (!node_isset(node, *used_node_mask)) { node_set(node, *used_node_mask); return node; } for_each_node_state(n, N_HIGH_MEMORY) { /* Don't want a node to appear more than once */ if (node_isset(n, *used_node_mask)) continue; /* Use the distance array to find the distance */ val = node_distance(node, n); /* Penalize nodes under us ("prefer the next node") */ val += (n < node); /* Give preference to headless and unused nodes */ tmp = cpumask_of_node(n); if (!cpumask_empty(tmp)) val += PENALTY_FOR_NODE_WITH_CPUS; /* Slight preference for less loaded node */ val *= (MAX_NODE_LOAD*MAX_NUMNODES); val += node_load[n]; if (val < min_val) { min_val = val; best_node = n; } } if (best_node >= 0) node_set(best_node, *used_node_mask); return best_node; } /* * Build zonelists ordered by node and zones within node. * This results in maximum locality--normal zone overflows into local * DMA zone, if any--but risks exhausting DMA zone. */ static void build_zonelists_in_node_order(pg_data_t *pgdat, int node) { int j; struct zonelist *zonelist; zonelist = &pgdat->node_zonelists[0]; for (j = 0; zonelist->_zonerefs[j].zone != NULL; j++) ; j = build_zonelists_node(NODE_DATA(node), zonelist, j, MAX_NR_ZONES - 1); zonelist->_zonerefs[j].zone = NULL; zonelist->_zonerefs[j].zone_idx = 0; } /* * Build gfp_thisnode zonelists */ static void build_thisnode_zonelists(pg_data_t *pgdat) { int j; struct zonelist *zonelist; zonelist = &pgdat->node_zonelists[1]; j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1); zonelist->_zonerefs[j].zone = NULL; zonelist->_zonerefs[j].zone_idx = 0; } /* * Build zonelists ordered by zone and nodes within zones. * This results in conserving DMA zone[s] until all Normal memory is * exhausted, but results in overflowing to remote node while memory * may still exist in local DMA zone. */ static int node_order[MAX_NUMNODES]; static void build_zonelists_in_zone_order(pg_data_t *pgdat, int nr_nodes) { int pos, j, node; int zone_type; /* needs to be signed */ struct zone *z; struct zonelist *zonelist; zonelist = &pgdat->node_zonelists[0]; pos = 0; for (zone_type = MAX_NR_ZONES - 1; zone_type >= 0; zone_type--) { for (j = 0; j < nr_nodes; j++) { node = node_order[j]; z = &NODE_DATA(node)->node_zones[zone_type]; if (populated_zone(z)) { zoneref_set_zone(z, &zonelist->_zonerefs[pos++]); check_highest_zone(zone_type); } } } zonelist->_zonerefs[pos].zone = NULL; zonelist->_zonerefs[pos].zone_idx = 0; } static int default_zonelist_order(void) { int nid, zone_type; unsigned long low_kmem_size,total_size; struct zone *z; int average_size; /* * ZONE_DMA and ZONE_DMA32 can be very small area in the system. * If they are really small and used heavily, the system can fall * into OOM very easily. * This function detect ZONE_DMA/DMA32 size and configures zone order. */ /* Is there ZONE_NORMAL ? (ex. ppc has only DMA zone..) */ low_kmem_size = 0; total_size = 0; for_each_online_node(nid) { for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) { z = &NODE_DATA(nid)->node_zones[zone_type]; if (populated_zone(z)) { if (zone_type < ZONE_NORMAL) low_kmem_size += z->present_pages; total_size += z->present_pages; } else if (zone_type == ZONE_NORMAL) { /* * If any node has only lowmem, then node order * is preferred to allow kernel allocations * locally; otherwise, they can easily infringe * on other nodes when there is an abundance of * lowmem available to allocate from. */ return ZONELIST_ORDER_NODE; } } } if (!low_kmem_size || /* there are no DMA area. */ low_kmem_size > total_size/2) /* DMA/DMA32 is big. */ return ZONELIST_ORDER_NODE; /* * look into each node's config. * If there is a node whose DMA/DMA32 memory is very big area on * local memory, NODE_ORDER may be suitable. */ average_size = total_size / (nodes_weight(node_states[N_HIGH_MEMORY]) + 1); for_each_online_node(nid) { low_kmem_size = 0; total_size = 0; for (zone_type = 0; zone_type < MAX_NR_ZONES; zone_type++) { z = &NODE_DATA(nid)->node_zones[zone_type]; if (populated_zone(z)) { if (zone_type < ZONE_NORMAL) low_kmem_size += z->present_pages; total_size += z->present_pages; } } if (low_kmem_size && total_size > average_size && /* ignore small node */ low_kmem_size > total_size * 70/100) return ZONELIST_ORDER_NODE; } return ZONELIST_ORDER_ZONE; } static void set_zonelist_order(void) { if (user_zonelist_order == ZONELIST_ORDER_DEFAULT) current_zonelist_order = default_zonelist_order(); else current_zonelist_order = user_zonelist_order; } static void build_zonelists(pg_data_t *pgdat) { int j, node, load; enum zone_type i; nodemask_t used_mask; int local_node, prev_node; struct zonelist *zonelist; int order = current_zonelist_order; /* initialize zonelists */ for (i = 0; i < MAX_ZONELISTS; i++) { zonelist = pgdat->node_zonelists + i; zonelist->_zonerefs[0].zone = NULL; zonelist->_zonerefs[0].zone_idx = 0; } /* NUMA-aware ordering of nodes */ local_node = pgdat->node_id; load = nr_online_nodes; prev_node = local_node; nodes_clear(used_mask); memset(node_order, 0, sizeof(node_order)); j = 0; while ((node = find_next_best_node(local_node, &used_mask)) >= 0) { int distance = node_distance(local_node, node); /* * If another node is sufficiently far away then it is better * to reclaim pages in a zone before going off node. */ if (distance > RECLAIM_DISTANCE) zone_reclaim_mode = 1; /* * We don't want to pressure a particular node. * So adding penalty to the first node in same * distance group to make it round-robin. */ if (distance != node_distance(local_node, prev_node)) node_load[node] = load; prev_node = node; load--; if (order == ZONELIST_ORDER_NODE) build_zonelists_in_node_order(pgdat, node); else node_order[j++] = node; /* remember order */ } if (order == ZONELIST_ORDER_ZONE) { /* calculate node order -- i.e., DMA last! */ build_zonelists_in_zone_order(pgdat, j); } build_thisnode_zonelists(pgdat); } /* Construct the zonelist performance cache - see further mmzone.h */ static void build_zonelist_cache(pg_data_t *pgdat) { struct zonelist *zonelist; struct zonelist_cache *zlc; struct zoneref *z; zonelist = &pgdat->node_zonelists[0]; zonelist->zlcache_ptr = zlc = &zonelist->zlcache; bitmap_zero(zlc->fullzones, MAX_ZONES_PER_ZONELIST); for (z = zonelist->_zonerefs; z->zone; z++) zlc->z_to_n[z - zonelist->_zonerefs] = zonelist_node_idx(z); } #ifdef CONFIG_HAVE_MEMORYLESS_NODES /* * Return node id of node used for "local" allocations. * I.e., first node id of first zone in arg node's generic zonelist. * Used for initializing percpu 'numa_mem', which is used primarily * for kernel allocations, so use GFP_KERNEL flags to locate zonelist. */ int local_memory_node(int node) { struct zone *zone; (void)first_zones_zonelist(node_zonelist(node, GFP_KERNEL), gfp_zone(GFP_KERNEL), NULL, &zone); return zone->node; } #endif #else /* CONFIG_NUMA */ static void set_zonelist_order(void) { current_zonelist_order = ZONELIST_ORDER_ZONE; } static void build_zonelists(pg_data_t *pgdat) { int node, local_node; enum zone_type j; struct zonelist *zonelist; local_node = pgdat->node_id; zonelist = &pgdat->node_zonelists[0]; j = build_zonelists_node(pgdat, zonelist, 0, MAX_NR_ZONES - 1); /* * Now we build the zonelist so that it contains the zones * of all the other nodes. * We don't want to pressure a particular node, so when * building the zones for node N, we make sure that the * zones coming right after the local ones are those from * node N+1 (modulo N) */ for (node = local_node + 1; node < MAX_NUMNODES; node++) { if (!node_online(node)) continue; j = build_zonelists_node(NODE_DATA(node), zonelist, j, MAX_NR_ZONES - 1); } for (node = 0; node < local_node; node++) { if (!node_online(node)) continue; j = build_zonelists_node(NODE_DATA(node), zonelist, j, MAX_NR_ZONES - 1); } zonelist->_zonerefs[j].zone = NULL; zonelist->_zonerefs[j].zone_idx = 0; } /* non-NUMA variant of zonelist performance cache - just NULL zlcache_ptr */ static void build_zonelist_cache(pg_data_t *pgdat) { pgdat->node_zonelists[0].zlcache_ptr = NULL; } #endif /* CONFIG_NUMA */ /* * Boot pageset table. One per cpu which is going to be used for all * zones and all nodes. The parameters will be set in such a way * that an item put on a list will immediately be handed over to * the buddy list. This is safe since pageset manipulation is done * with interrupts disabled. * * The boot_pagesets must be kept even after bootup is complete for * unused processors and/or zones. They do play a role for bootstrapping * hotplugged processors. * * zoneinfo_show() and maybe other functions do * not check if the processor is online before following the pageset pointer. * Other parts of the kernel may not check if the zone is available. */ static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch); static DEFINE_PER_CPU(struct per_cpu_pageset, boot_pageset); static void setup_zone_pageset(struct zone *zone); /* * Global mutex to protect against size modification of zonelists * as well as to serialize pageset setup for the new populated zone. */ DEFINE_MUTEX(zonelists_mutex); /* return values int ....just for stop_machine() */ static __init_refok int __build_all_zonelists(void *data) { int nid; int cpu; #ifdef CONFIG_NUMA memset(node_load, 0, sizeof(node_load)); #endif for_each_online_node(nid) { pg_data_t *pgdat = NODE_DATA(nid); build_zonelists(pgdat); build_zonelist_cache(pgdat); } #ifdef CONFIG_MEMORY_HOTPLUG /* Setup real pagesets for the new zone */ if (data) { struct zone *zone = data; setup_zone_pageset(zone); } #endif /* * Initialize the boot_pagesets that are going to be used * for bootstrapping processors. The real pagesets for * each zone will be allocated later when the per cpu * allocator is available. * * boot_pagesets are used also for bootstrapping offline * cpus if the system is already booted because the pagesets * are needed to initialize allocators on a specific cpu too. * F.e. the percpu allocator needs the page allocator which * needs the percpu allocator in order to allocate its pagesets * (a chicken-egg dilemma). */ for_each_possible_cpu(cpu) { setup_pageset(&per_cpu(boot_pageset, cpu), 0); #ifdef CONFIG_HAVE_MEMORYLESS_NODES /* * We now know the "local memory node" for each node-- * i.e., the node of the first zone in the generic zonelist. * Set up numa_mem percpu variable for on-line cpus. During * boot, only the boot cpu should be on-line; we'll init the * secondary cpus' numa_mem as they come on-line. During * node/memory hotplug, we'll fixup all on-line cpus. */ if (cpu_online(cpu)) set_cpu_numa_mem(cpu, local_memory_node(cpu_to_node(cpu))); #endif } return 0; } /* * Called with zonelists_mutex held always * unless system_state == SYSTEM_BOOTING. */ void build_all_zonelists(void *data) { set_zonelist_order(); if (system_state == SYSTEM_BOOTING) { __build_all_zonelists(NULL); mminit_verify_zonelist(); cpuset_init_current_mems_allowed(); } else { /* we have to stop all cpus to guarantee there is no user of zonelist */ stop_machine(__build_all_zonelists, data, NULL); /* cpuset refresh routine should be here */ } vm_total_pages = nr_free_pagecache_pages(); /* * Disable grouping by mobility if the number of pages in the * system is too low to allow the mechanism to work. It would be * more accurate, but expensive to check per-zone. This check is * made on memory-hotadd so a system can start with mobility * disabled and enable it later */ if (vm_total_pages < (pageblock_nr_pages * MIGRATE_TYPES)) page_group_by_mobility_disabled = 1; else page_group_by_mobility_disabled = 0; printk("Built %i zonelists in %s order, mobility grouping %s. " "Total pages: %ld\n", nr_online_nodes, zonelist_order_name[current_zonelist_order], page_group_by_mobility_disabled ? "off" : "on", vm_total_pages); #ifdef CONFIG_NUMA printk("Policy zone: %s\n", zone_names[policy_zone]); #endif } /* * Helper functions to size the waitqueue hash table. * Essentially these want to choose hash table sizes sufficiently * large so that collisions trying to wait on pages are rare. * But in fact, the number of active page waitqueues on typical * systems is ridiculously low, less than 200. So this is even * conservative, even though it seems large. * * The constant PAGES_PER_WAITQUEUE specifies the ratio of pages to * waitqueues, i.e. the size of the waitq table given the number of pages. */ #define PAGES_PER_WAITQUEUE 256 #ifndef CONFIG_MEMORY_HOTPLUG static inline unsigned long wait_table_hash_nr_entries(unsigned long pages) { unsigned long size = 1; pages /= PAGES_PER_WAITQUEUE; while (size < pages) size <<= 1; /* * Once we have dozens or even hundreds of threads sleeping * on IO we've got bigger problems than wait queue collision. * Limit the size of the wait table to a reasonable size. */ size = min(size, 4096UL); return max(size, 4UL); } #else /* * A zone's size might be changed by hot-add, so it is not possible to determine * a suitable size for its wait_table. So we use the maximum size now. * * The max wait table size = 4096 x sizeof(wait_queue_head_t). ie: * * i386 (preemption config) : 4096 x 16 = 64Kbyte. * ia64, x86-64 (no preemption): 4096 x 20 = 80Kbyte. * ia64, x86-64 (preemption) : 4096 x 24 = 96Kbyte. * * The maximum entries are prepared when a zone's memory is (512K + 256) pages * or more by the traditional way. (See above). It equals: * * i386, x86-64, powerpc(4K page size) : = ( 2G + 1M)byte. * ia64(16K page size) : = ( 8G + 4M)byte. * powerpc (64K page size) : = (32G +16M)byte. */ static inline unsigned long wait_table_hash_nr_entries(unsigned long pages) { return 4096UL; } #endif /* * This is an integer logarithm so that shifts can be used later * to extract the more random high bits from the multiplicative * hash function before the remainder is taken. */ static inline unsigned long wait_table_bits(unsigned long size) { return ffz(~size); } #define LONG_ALIGN(x) (((x)+(sizeof(long))-1)&~((sizeof(long))-1)) /* * Check if a pageblock contains reserved pages */ static int pageblock_is_reserved(unsigned long start_pfn) { unsigned long end_pfn = start_pfn + pageblock_nr_pages; unsigned long pfn; for (pfn = start_pfn; pfn < end_pfn; pfn++) if (PageReserved(pfn_to_page(pfn))) return 1; return 0; } /* * Mark a number of pageblocks as MIGRATE_RESERVE. The number * of blocks reserved is based on min_wmark_pages(zone). The memory within * the reserve will tend to store contiguous free pages. Setting min_free_kbytes * higher will lead to a bigger reserve which will get freed as contiguous * blocks as reclaim kicks in */ static void setup_zone_migrate_reserve(struct zone *zone) { unsigned long start_pfn, pfn, end_pfn; struct page *page; unsigned long block_migratetype; int reserve; /* Get the start pfn, end pfn and the number of blocks to reserve */ start_pfn = zone->zone_start_pfn; end_pfn = start_pfn + zone->spanned_pages; reserve = roundup(min_wmark_pages(zone), pageblock_nr_pages) >> pageblock_order; /* * Reserve blocks are generally in place to help high-order atomic * allocations that are short-lived. A min_free_kbytes value that * would result in more than 2 reserve blocks for atomic allocations * is assumed to be in place to help anti-fragmentation for the * future allocation of hugepages at runtime. */ reserve = min(2, reserve); for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) { if (!pfn_valid(pfn)) continue; page = pfn_to_page(pfn); /* Watch out for overlapping nodes */ if (page_to_nid(page) != zone_to_nid(zone)) continue; /* Blocks with reserved pages will never free, skip them. */ if (pageblock_is_reserved(pfn)) continue; block_migratetype = get_pageblock_migratetype(page); /* If this block is reserved, account for it */ if (reserve > 0 && block_migratetype == MIGRATE_RESERVE) { reserve--; continue; } /* Suitable for reserving if this block is movable */ if (reserve > 0 && block_migratetype == MIGRATE_MOVABLE) { set_pageblock_migratetype(page, MIGRATE_RESERVE); move_freepages_block(zone, page, MIGRATE_RESERVE); reserve--; continue; } /* * If the reserve is met and this is a previous reserved block, * take it back */ if (block_migratetype == MIGRATE_RESERVE) { set_pageblock_migratetype(page, MIGRATE_MOVABLE); move_freepages_block(zone, page, MIGRATE_MOVABLE); } } } /* * Initially all pages are reserved - free ones are freed * up by free_all_bootmem() once the early boot process is * done. Non-atomic initialization, single-pass. */ void __meminit memmap_init_zone(unsigned long size, int nid, unsigned long zone, unsigned long start_pfn, enum memmap_context context) { struct page *page; unsigned long end_pfn = start_pfn + size; unsigned long pfn; struct zone *z; if (highest_memmap_pfn < end_pfn - 1) highest_memmap_pfn = end_pfn - 1; z = &NODE_DATA(nid)->node_zones[zone]; for (pfn = start_pfn; pfn < end_pfn; pfn++) { /* * There can be holes in boot-time mem_map[]s * handed to this function. They do not * exist on hotplugged memory. */ if (context == MEMMAP_EARLY) { if (!early_pfn_valid(pfn)) continue; if (!early_pfn_in_nid(pfn, nid)) continue; } page = pfn_to_page(pfn); set_page_links(page, zone, nid, pfn); mminit_verify_page_links(page, zone, nid, pfn); init_page_count(page); reset_page_mapcount(page); SetPageReserved(page); /* * Mark the block movable so that blocks are reserved for * movable at startup. This will force kernel allocations * to reserve their blocks rather than leaking throughout * the address space during boot when many long-lived * kernel allocations are made. Later some blocks near * the start are marked MIGRATE_RESERVE by * setup_zone_migrate_reserve() * * bitmap is created for zone's valid pfn range. but memmap * can be created for invalid pages (for alignment) * check here not to call set_pageblock_migratetype() against * pfn out of zone. */ if ((z->zone_start_pfn <= pfn) && (pfn < z->zone_start_pfn + z->spanned_pages) && !(pfn & (pageblock_nr_pages - 1))) set_pageblock_migratetype(page, MIGRATE_MOVABLE); INIT_LIST_HEAD(&page->lru); #ifdef WANT_PAGE_VIRTUAL /* The shift won't overflow because ZONE_NORMAL is below 4G. */ if (!is_highmem_idx(zone)) set_page_address(page, __va(pfn << PAGE_SHIFT)); #endif } } static void __meminit zone_init_free_lists(struct zone *zone) { int order, t; for_each_migratetype_order(order, t) { INIT_LIST_HEAD(&zone->free_area[order].free_list[t]); zone->free_area[order].nr_free = 0; } } #ifndef __HAVE_ARCH_MEMMAP_INIT #define memmap_init(size, nid, zone, start_pfn) \ memmap_init_zone((size), (nid), (zone), (start_pfn), MEMMAP_EARLY) #endif static int zone_batchsize(struct zone *zone) { #ifdef CONFIG_MMU int batch; /* * The per-cpu-pages pools are set to around 1000th of the * size of the zone. But no more than 1/2 of a meg. * * OK, so we don't know how big the cache is. So guess. */ batch = zone->present_pages / 1024; if (batch * PAGE_SIZE > 512 * 1024) batch = (512 * 1024) / PAGE_SIZE; batch /= 4; /* We effectively *= 4 below */ if (batch < 1) batch = 1; /* * Clamp the batch to a 2^n - 1 value. Having a power * of 2 value was found to be more likely to have * suboptimal cache aliasing properties in some cases. * * For example if 2 tasks are alternately allocating * batches of pages, one task can end up with a lot * of pages of one half of the possible page colors * and the other with pages of the other colors. */ batch = rounddown_pow_of_two(batch + batch/2) - 1; return batch; #else /* The deferral and batching of frees should be suppressed under NOMMU * conditions. * * The problem is that NOMMU needs to be able to allocate large chunks * of contiguous memory as there's no hardware page translation to * assemble apparent contiguous memory from discontiguous pages. * * Queueing large contiguous runs of pages for batching, however, * causes the pages to actually be freed in smaller chunks. As there * can be a significant delay between the individual batches being * recycled, this leads to the once large chunks of space being * fragmented and becoming unavailable for high-order allocations. */ return 0; #endif } static void setup_pageset(struct per_cpu_pageset *p, unsigned long batch) { struct per_cpu_pages *pcp; int migratetype; memset(p, 0, sizeof(*p)); pcp = &p->pcp; pcp->count = 0; pcp->high = 6 * batch; pcp->batch = max(1UL, 1 * batch); for (migratetype = 0; migratetype < MIGRATE_PCPTYPES; migratetype++) INIT_LIST_HEAD(&pcp->lists[migratetype]); } /* * setup_pagelist_highmark() sets the high water mark for hot per_cpu_pagelist * to the value high for the pageset p. */ static void setup_pagelist_highmark(struct per_cpu_pageset *p, unsigned long high) { struct per_cpu_pages *pcp; pcp = &p->pcp; pcp->high = high; pcp->batch = max(1UL, high/4); if ((high/4) > (PAGE_SHIFT * 8)) pcp->batch = PAGE_SHIFT * 8; } static __meminit void setup_zone_pageset(struct zone *zone) { int cpu; zone->pageset = alloc_percpu(struct per_cpu_pageset); for_each_possible_cpu(cpu) { struct per_cpu_pageset *pcp = per_cpu_ptr(zone->pageset, cpu); setup_pageset(pcp, zone_batchsize(zone)); if (percpu_pagelist_fraction) setup_pagelist_highmark(pcp, (zone->present_pages / percpu_pagelist_fraction)); } } /* * Allocate per cpu pagesets and initialize them. * Before this call only boot pagesets were available. */ void __init setup_per_cpu_pageset(void) { struct zone *zone; for_each_populated_zone(zone) setup_zone_pageset(zone); } static noinline __init_refok int zone_wait_table_init(struct zone *zone, unsigned long zone_size_pages) { int i; struct pglist_data *pgdat = zone->zone_pgdat; size_t alloc_size; /* * The per-page waitqueue mechanism uses hashed waitqueues * per zone. */ zone->wait_table_hash_nr_entries = wait_table_hash_nr_entries(zone_size_pages); zone->wait_table_bits = wait_table_bits(zone->wait_table_hash_nr_entries); alloc_size = zone->wait_table_hash_nr_entries * sizeof(wait_queue_head_t); if (!slab_is_available()) { zone->wait_table = (wait_queue_head_t *) alloc_bootmem_node(pgdat, alloc_size); } else { /* * This case means that a zone whose size was 0 gets new memory * via memory hot-add. * But it may be the case that a new node was hot-added. In * this case vmalloc() will not be able to use this new node's * memory - this wait_table must be initialized to use this new * node itself as well. * To use this new node's memory, further consideration will be * necessary. */ zone->wait_table = vmalloc(alloc_size); } if (!zone->wait_table) return -ENOMEM; for(i = 0; i < zone->wait_table_hash_nr_entries; ++i) init_waitqueue_head(zone->wait_table + i); return 0; } static int __zone_pcp_update(void *data) { struct zone *zone = data; int cpu; unsigned long batch = zone_batchsize(zone), flags; for_each_possible_cpu(cpu) { struct per_cpu_pageset *pset; struct per_cpu_pages *pcp; pset = per_cpu_ptr(zone->pageset, cpu); pcp = &pset->pcp; local_irq_save(flags); free_pcppages_bulk(zone, pcp->count, pcp); setup_pageset(pset, batch); local_irq_restore(flags); } return 0; } void zone_pcp_update(struct zone *zone) { stop_machine(__zone_pcp_update, zone, NULL); } static __meminit void zone_pcp_init(struct zone *zone) { /* * per cpu subsystem is not up at this point. The following code * relies on the ability of the linker to provide the * offset of a (static) per cpu variable into the per cpu area. */ zone->pageset = &boot_pageset; if (zone->present_pages) printk(KERN_DEBUG " %s zone: %lu pages, LIFO batch:%u\n", zone->name, zone->present_pages, zone_batchsize(zone)); } __meminit int init_currently_empty_zone(struct zone *zone, unsigned long zone_start_pfn, unsigned long size, enum memmap_context context) { struct pglist_data *pgdat = zone->zone_pgdat; int ret; ret = zone_wait_table_init(zone, size); if (ret) return ret; pgdat->nr_zones = zone_idx(zone) + 1; zone->zone_start_pfn = zone_start_pfn; mminit_dprintk(MMINIT_TRACE, "memmap_init", "Initialising map node %d zone %lu pfns %lu -> %lu\n", pgdat->node_id, (unsigned long)zone_idx(zone), zone_start_pfn, (zone_start_pfn + size)); zone_init_free_lists(zone); return 0; } #ifdef CONFIG_ARCH_POPULATES_NODE_MAP /* * Basic iterator support. Return the first range of PFNs for a node * Note: nid == MAX_NUMNODES returns first region regardless of node */ static int __meminit first_active_region_index_in_nid(int nid) { int i; for (i = 0; i < nr_nodemap_entries; i++) if (nid == MAX_NUMNODES || early_node_map[i].nid == nid) return i; return -1; } /* * Basic iterator support. Return the next active range of PFNs for a node * Note: nid == MAX_NUMNODES returns next region regardless of node */ static int __meminit next_active_region_index_in_nid(int index, int nid) { for (index = index + 1; index < nr_nodemap_entries; index++) if (nid == MAX_NUMNODES || early_node_map[index].nid == nid) return index; return -1; } #ifndef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID /* * Required by SPARSEMEM. Given a PFN, return what node the PFN is on. * Architectures may implement their own version but if add_active_range() * was used and there are no special requirements, this is a convenient * alternative */ int __meminit __early_pfn_to_nid(unsigned long pfn) { int i; for (i = 0; i < nr_nodemap_entries; i++) { unsigned long start_pfn = early_node_map[i].start_pfn; unsigned long end_pfn = early_node_map[i].end_pfn; if (start_pfn <= pfn && pfn < end_pfn) return early_node_map[i].nid; } /* This is a memory hole */ return -1; } #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */ int __meminit early_pfn_to_nid(unsigned long pfn) { int nid; nid = __early_pfn_to_nid(pfn); if (nid >= 0) return nid; /* just returns 0 */ return 0; } #ifdef CONFIG_NODES_SPAN_OTHER_NODES bool __meminit early_pfn_in_nid(unsigned long pfn, int node) { int nid; nid = __early_pfn_to_nid(pfn); if (nid >= 0 && nid != node) return false; return true; } #endif /* Basic iterator support to walk early_node_map[] */ #define for_each_active_range_index_in_nid(i, nid) \ for (i = first_active_region_index_in_nid(nid); i != -1; \ i = next_active_region_index_in_nid(i, nid)) /** * free_bootmem_with_active_regions - Call free_bootmem_node for each active range * @nid: The node to free memory on. If MAX_NUMNODES, all nodes are freed. * @max_low_pfn: The highest PFN that will be passed to free_bootmem_node * * If an architecture guarantees that all ranges registered with * add_active_ranges() contain no holes and may be freed, this * this function may be used instead of calling free_bootmem() manually. */ void __init free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn) { int i; for_each_active_range_index_in_nid(i, nid) { unsigned long size_pages = 0; unsigned long end_pfn = early_node_map[i].end_pfn; if (early_node_map[i].start_pfn >= max_low_pfn) continue; if (end_pfn > max_low_pfn) end_pfn = max_low_pfn; size_pages = end_pfn - early_node_map[i].start_pfn; free_bootmem_node(NODE_DATA(early_node_map[i].nid), PFN_PHYS(early_node_map[i].start_pfn), size_pages << PAGE_SHIFT); } } int __init add_from_early_node_map(struct range *range, int az, int nr_range, int nid) { int i; u64 start, end; /* need to go over early_node_map to find out good range for node */ for_each_active_range_index_in_nid(i, nid) { start = early_node_map[i].start_pfn; end = early_node_map[i].end_pfn; nr_range = add_range(range, az, nr_range, start, end); } return nr_range; } #ifdef CONFIG_NO_BOOTMEM void * __init __alloc_memory_core_early(int nid, u64 size, u64 align, u64 goal, u64 limit) { int i; void *ptr; if (limit > get_max_mapped()) limit = get_max_mapped(); /* need to go over early_node_map to find out good range for node */ for_each_active_range_index_in_nid(i, nid) { u64 addr; u64 ei_start, ei_last; ei_last = early_node_map[i].end_pfn; ei_last <<= PAGE_SHIFT; ei_start = early_node_map[i].start_pfn; ei_start <<= PAGE_SHIFT; addr = find_early_area(ei_start, ei_last, goal, limit, size, align); if (addr == -1ULL) continue; #if 0 printk(KERN_DEBUG "alloc (nid=%d %llx - %llx) (%llx - %llx) %llx %llx => %llx\n", nid, ei_start, ei_last, goal, limit, size, align, addr); #endif ptr = phys_to_virt(addr); memset(ptr, 0, size); reserve_early_without_check(addr, addr + size, "BOOTMEM"); /* * The min_count is set to 0 so that bootmem allocated blocks * are never reported as leaks. */ kmemleak_alloc(ptr, size, 0, 0); return ptr; } return NULL; } #endif void __init work_with_active_regions(int nid, work_fn_t work_fn, void *data) { int i; int ret; for_each_active_range_index_in_nid(i, nid) { ret = work_fn(early_node_map[i].start_pfn, early_node_map[i].end_pfn, data); if (ret) break; } } /** * sparse_memory_present_with_active_regions - Call memory_present for each active range * @nid: The node to call memory_present for. If MAX_NUMNODES, all nodes will be used. * * If an architecture guarantees that all ranges registered with * add_active_ranges() contain no holes and may be freed, this * function may be used instead of calling memory_present() manually. */ void __init sparse_memory_present_with_active_regions(int nid) { int i; for_each_active_range_index_in_nid(i, nid) memory_present(early_node_map[i].nid, early_node_map[i].start_pfn, early_node_map[i].end_pfn); } /** * get_pfn_range_for_nid - Return the start and end page frames for a node * @nid: The nid to return the range for. If MAX_NUMNODES, the min and max PFN are returned. * @start_pfn: Passed by reference. On return, it will have the node start_pfn. * @end_pfn: Passed by reference. On return, it will have the node end_pfn. * * It returns the start and end page frame of a node based on information * provided by an arch calling add_active_range(). If called for a node * with no available memory, a warning is printed and the start and end * PFNs will be 0. */ void __meminit get_pfn_range_for_nid(unsigned int nid, unsigned long *start_pfn, unsigned long *end_pfn) { int i; *start_pfn = -1UL; *end_pfn = 0; for_each_active_range_index_in_nid(i, nid) { *start_pfn = min(*start_pfn, early_node_map[i].start_pfn); *end_pfn = max(*end_pfn, early_node_map[i].end_pfn); } if (*start_pfn == -1UL) *start_pfn = 0; } /* * This finds a zone that can be used for ZONE_MOVABLE pages. The * assumption is made that zones within a node are ordered in monotonic * increasing memory addresses so that the "highest" populated zone is used */ static void __init find_usable_zone_for_movable(void) { int zone_index; for (zone_index = MAX_NR_ZONES - 1; zone_index >= 0; zone_index--) { if (zone_index == ZONE_MOVABLE) continue; if (arch_zone_highest_possible_pfn[zone_index] > arch_zone_lowest_possible_pfn[zone_index]) break; } VM_BUG_ON(zone_index == -1); movable_zone = zone_index; } /* * The zone ranges provided by the architecture do not include ZONE_MOVABLE * because it is sized independant of architecture. Unlike the other zones, * the starting point for ZONE_MOVABLE is not fixed. It may be different * in each node depending on the size of each node and how evenly kernelcore * is distributed. This helper function adjusts the zone ranges * provided by the architecture for a given node by using the end of the * highest usable zone for ZONE_MOVABLE. This preserves the assumption that * zones within a node are in order of monotonic increases memory addresses */ static void __meminit adjust_zone_range_for_zone_movable(int nid, unsigned long zone_type, unsigned long node_start_pfn, unsigned long node_end_pfn, unsigned long *zone_start_pfn, unsigned long *zone_end_pfn) { /* Only adjust if ZONE_MOVABLE is on this node */ if (zone_movable_pfn[nid]) { /* Size ZONE_MOVABLE */ if (zone_type == ZONE_MOVABLE) { *zone_start_pfn = zone_movable_pfn[nid]; *zone_end_pfn = min(node_end_pfn, arch_zone_highest_possible_pfn[movable_zone]); /* Adjust for ZONE_MOVABLE starting within this range */ } else if (*zone_start_pfn < zone_movable_pfn[nid] && *zone_end_pfn > zone_movable_pfn[nid]) { *zone_end_pfn = zone_movable_pfn[nid]; /* Check if this whole range is within ZONE_MOVABLE */ } else if (*zone_start_pfn >= zone_movable_pfn[nid]) *zone_start_pfn = *zone_end_pfn; } } /* * Return the number of pages a zone spans in a node, including holes * present_pages = zone_spanned_pages_in_node() - zone_absent_pages_in_node() */ static unsigned long __meminit zone_spanned_pages_in_node(int nid, unsigned long zone_type, unsigned long *ignored) { unsigned long node_start_pfn, node_end_pfn; unsigned long zone_start_pfn, zone_end_pfn; /* Get the start and end of the node and zone */ get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn); zone_start_pfn = arch_zone_lowest_possible_pfn[zone_type]; zone_end_pfn = arch_zone_highest_possible_pfn[zone_type]; adjust_zone_range_for_zone_movable(nid, zone_type, node_start_pfn, node_end_pfn, &zone_start_pfn, &zone_end_pfn); /* Check that this node has pages within the zone's required range */ if (zone_end_pfn < node_start_pfn || zone_start_pfn > node_end_pfn) return 0; /* Move the zone boundaries inside the node if necessary */ zone_end_pfn = min(zone_end_pfn, node_end_pfn); zone_start_pfn = max(zone_start_pfn, node_start_pfn); /* Return the spanned pages */ return zone_end_pfn - zone_start_pfn; } /* * Return the number of holes in a range on a node. If nid is MAX_NUMNODES, * then all holes in the requested range will be accounted for. */ unsigned long __meminit __absent_pages_in_range(int nid, unsigned long range_start_pfn, unsigned long range_end_pfn) { int i = 0; unsigned long prev_end_pfn = 0, hole_pages = 0; unsigned long start_pfn; /* Find the end_pfn of the first active range of pfns in the node */ i = first_active_region_index_in_nid(nid); if (i == -1) return 0; prev_end_pfn = min(early_node_map[i].start_pfn, range_end_pfn); /* Account for ranges before physical memory on this node */ if (early_node_map[i].start_pfn > range_start_pfn) hole_pages = prev_end_pfn - range_start_pfn; /* Find all holes for the zone within the node */ for (; i != -1; i = next_active_region_index_in_nid(i, nid)) { /* No need to continue if prev_end_pfn is outside the zone */ if (prev_end_pfn >= range_end_pfn) break; /* Make sure the end of the zone is not within the hole */ start_pfn = min(early_node_map[i].start_pfn, range_end_pfn); prev_end_pfn = max(prev_end_pfn, range_start_pfn); /* Update the hole size cound and move on */ if (start_pfn > range_start_pfn) { BUG_ON(prev_end_pfn > start_pfn); hole_pages += start_pfn - prev_end_pfn; } prev_end_pfn = early_node_map[i].end_pfn; } /* Account for ranges past physical memory on this node */ if (range_end_pfn > prev_end_pfn) hole_pages += range_end_pfn - max(range_start_pfn, prev_end_pfn); return hole_pages; } /** * absent_pages_in_range - Return number of page frames in holes within a range * @start_pfn: The start PFN to start searching for holes * @end_pfn: The end PFN to stop searching for holes * * It returns the number of pages frames in memory holes within a range. */ unsigned long __init absent_pages_in_range(unsigned long start_pfn, unsigned long end_pfn) { return __absent_pages_in_range(MAX_NUMNODES, start_pfn, end_pfn); } /* Return the number of page frames in holes in a zone on a node */ static unsigned long __meminit zone_absent_pages_in_node(int nid, unsigned long zone_type, unsigned long *ignored) { unsigned long node_start_pfn, node_end_pfn; unsigned long zone_start_pfn, zone_end_pfn; get_pfn_range_for_nid(nid, &node_start_pfn, &node_end_pfn); zone_start_pfn = max(arch_zone_lowest_possible_pfn[zone_type], node_start_pfn); zone_end_pfn = min(arch_zone_highest_possible_pfn[zone_type], node_end_pfn); adjust_zone_range_for_zone_movable(nid, zone_type, node_start_pfn, node_end_pfn, &zone_start_pfn, &zone_end_pfn); return __absent_pages_in_range(nid, zone_start_pfn, zone_end_pfn); } #else static inline unsigned long __meminit zone_spanned_pages_in_node(int nid, unsigned long zone_type, unsigned long *zones_size) { return zones_size[zone_type]; } static inline unsigned long __meminit zone_absent_pages_in_node(int nid, unsigned long zone_type, unsigned long *zholes_size) { if (!zholes_size) return 0; return zholes_size[zone_type]; } #endif static void __meminit calculate_node_totalpages(struct pglist_data *pgdat, unsigned long *zones_size, unsigned long *zholes_size) { unsigned long realtotalpages, totalpages = 0; enum zone_type i; for (i = 0; i < MAX_NR_ZONES; i++) totalpages += zone_spanned_pages_in_node(pgdat->node_id, i, zones_size); pgdat->node_spanned_pages = totalpages; realtotalpages = totalpages; for (i = 0; i < MAX_NR_ZONES; i++) realtotalpages -= zone_absent_pages_in_node(pgdat->node_id, i, zholes_size); pgdat->node_present_pages = realtotalpages; printk(KERN_DEBUG "On node %d totalpages: %lu\n", pgdat->node_id, realtotalpages); } #ifndef CONFIG_SPARSEMEM /* * Calculate the size of the zone->blockflags rounded to an unsigned long * Start by making sure zonesize is a multiple of pageblock_order by rounding * up. Then use 1 NR_PAGEBLOCK_BITS worth of bits per pageblock, finally * round what is now in bits to nearest long in bits, then return it in * bytes. */ static unsigned long __init usemap_size(unsigned long zonesize) { unsigned long usemapsize; usemapsize = roundup(zonesize, pageblock_nr_pages); usemapsize = usemapsize >> pageblock_order; usemapsize *= NR_PAGEBLOCK_BITS; usemapsize = roundup(usemapsize, 8 * sizeof(unsigned long)); return usemapsize / 8; } static void __init setup_usemap(struct pglist_data *pgdat, struct zone *zone, unsigned long zonesize) { unsigned long usemapsize = usemap_size(zonesize); zone->pageblock_flags = NULL; if (usemapsize) zone->pageblock_flags = alloc_bootmem_node(pgdat, usemapsize); } #else static void inline setup_usemap(struct pglist_data *pgdat, struct zone *zone, unsigned long zonesize) {} #endif /* CONFIG_SPARSEMEM */ #ifdef CONFIG_HUGETLB_PAGE_SIZE_VARIABLE /* Return a sensible default order for the pageblock size. */ static inline int pageblock_default_order(void) { if (HPAGE_SHIFT > PAGE_SHIFT) return HUGETLB_PAGE_ORDER; return MAX_ORDER-1; } /* Initialise the number of pages represented by NR_PAGEBLOCK_BITS */ static inline void __init set_pageblock_order(unsigned int order) { /* Check that pageblock_nr_pages has not already been setup */ if (pageblock_order) return; /* * Assume the largest contiguous order of interest is a huge page. * This value may be variable depending on boot parameters on IA64 */ pageblock_order = order; } #else /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ /* * When CONFIG_HUGETLB_PAGE_SIZE_VARIABLE is not set, set_pageblock_order() * and pageblock_default_order() are unused as pageblock_order is set * at compile-time. See include/linux/pageblock-flags.h for the values of * pageblock_order based on the kernel config */ static inline int pageblock_default_order(unsigned int order) { return MAX_ORDER-1; } #define set_pageblock_order(x) do {} while (0) #endif /* CONFIG_HUGETLB_PAGE_SIZE_VARIABLE */ /* * Set up the zone data structures: * - mark all pages reserved * - mark all memory queues empty * - clear the memory bitmaps */ static void __paginginit free_area_init_core(struct pglist_data *pgdat, unsigned long *zones_size, unsigned long *zholes_size) { enum zone_type j; int nid = pgdat->node_id; unsigned long zone_start_pfn = pgdat->node_start_pfn; int ret; pgdat_resize_init(pgdat); pgdat->nr_zones = 0; init_waitqueue_head(&pgdat->kswapd_wait); pgdat->kswapd_max_order = 0; pgdat_page_cgroup_init(pgdat); for (j = 0; j < MAX_NR_ZONES; j++) { struct zone *zone = pgdat->node_zones + j; unsigned long size, realsize, memmap_pages; enum lru_list l; size = zone_spanned_pages_in_node(nid, j, zones_size); realsize = size - zone_absent_pages_in_node(nid, j, zholes_size); /* * Adjust realsize so that it accounts for how much memory * is used by this zone for memmap. This affects the watermark * and per-cpu initialisations */ memmap_pages = PAGE_ALIGN(size * sizeof(struct page)) >> PAGE_SHIFT; if (realsize >= memmap_pages) { realsize -= memmap_pages; if (memmap_pages) printk(KERN_DEBUG " %s zone: %lu pages used for memmap\n", zone_names[j], memmap_pages); } else printk(KERN_WARNING " %s zone: %lu pages exceeds realsize %lu\n", zone_names[j], memmap_pages, realsize); /* Account for reserved pages */ if (j == 0 && realsize > dma_reserve) { realsize -= dma_reserve; printk(KERN_DEBUG " %s zone: %lu pages reserved\n", zone_names[0], dma_reserve); } if (!is_highmem_idx(j)) nr_kernel_pages += realsize; nr_all_pages += realsize; zone->spanned_pages = size; zone->present_pages = realsize; #ifdef CONFIG_NUMA zone->node = nid; zone->min_unmapped_pages = (realsize*sysctl_min_unmapped_ratio) / 100; zone->min_slab_pages = (realsize * sysctl_min_slab_ratio) / 100; #endif zone->name = zone_names[j]; spin_lock_init(&zone->lock); spin_lock_init(&zone->lru_lock); zone_seqlock_init(zone); zone->zone_pgdat = pgdat; zone->prev_priority = DEF_PRIORITY; zone_pcp_init(zone); for_each_lru(l) { INIT_LIST_HEAD(&zone->lru[l].list); zone->reclaim_stat.nr_saved_scan[l] = 0; } zone->reclaim_stat.recent_rotated[0] = 0; zone->reclaim_stat.recent_rotated[1] = 0; zone->reclaim_stat.recent_scanned[0] = 0; zone->reclaim_stat.recent_scanned[1] = 0; zap_zone_vm_stats(zone); zone->flags = 0; if (!size) continue; set_pageblock_order(pageblock_default_order()); setup_usemap(pgdat, zone, size); ret = init_currently_empty_zone(zone, zone_start_pfn, size, MEMMAP_EARLY); BUG_ON(ret); memmap_init(size, nid, j, zone_start_pfn); zone_start_pfn += size; } } static void __init_refok alloc_node_mem_map(struct pglist_data *pgdat) { /* Skip empty nodes */ if (!pgdat->node_spanned_pages) return; #ifdef CONFIG_FLAT_NODE_MEM_MAP /* ia64 gets its own node_mem_map, before this, without bootmem */ if (!pgdat->node_mem_map) { unsigned long size, start, end; struct page *map; /* * The zone's endpoints aren't required to be MAX_ORDER * aligned but the node_mem_map endpoints must be in order * for the buddy allocator to function correctly. */ start = pgdat->node_start_pfn & ~(MAX_ORDER_NR_PAGES - 1); end = pgdat->node_start_pfn + pgdat->node_spanned_pages; end = ALIGN(end, MAX_ORDER_NR_PAGES); size = (end - start) * sizeof(struct page); map = alloc_remap(pgdat->node_id, size); if (!map) map = alloc_bootmem_node(pgdat, size); pgdat->node_mem_map = map + (pgdat->node_start_pfn - start); } #ifndef CONFIG_NEED_MULTIPLE_NODES /* * With no DISCONTIG, the global mem_map is just set as node 0's */ if (pgdat == NODE_DATA(0)) { mem_map = NODE_DATA(0)->node_mem_map; #ifdef CONFIG_ARCH_POPULATES_NODE_MAP if (page_to_pfn(mem_map) != pgdat->node_start_pfn) mem_map -= (pgdat->node_start_pfn - ARCH_PFN_OFFSET); #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */ } #endif #endif /* CONFIG_FLAT_NODE_MEM_MAP */ } void __paginginit free_area_init_node(int nid, unsigned long *zones_size, unsigned long node_start_pfn, unsigned long *zholes_size) { pg_data_t *pgdat = NODE_DATA(nid); pgdat->node_id = nid; pgdat->node_start_pfn = node_start_pfn; calculate_node_totalpages(pgdat, zones_size, zholes_size); alloc_node_mem_map(pgdat); #ifdef CONFIG_FLAT_NODE_MEM_MAP printk(KERN_DEBUG "free_area_init_node: node %d, pgdat %08lx, node_mem_map %08lx\n", nid, (unsigned long)pgdat, (unsigned long)pgdat->node_mem_map); #endif free_area_init_core(pgdat, zones_size, zholes_size); } #ifdef CONFIG_ARCH_POPULATES_NODE_MAP #if MAX_NUMNODES > 1 /* * Figure out the number of possible node ids. */ static void __init setup_nr_node_ids(void) { unsigned int node; unsigned int highest = 0; for_each_node_mask(node, node_possible_map) highest = node; nr_node_ids = highest + 1; } #else static inline void setup_nr_node_ids(void) { } #endif /** * add_active_range - Register a range of PFNs backed by physical memory * @nid: The node ID the range resides on * @start_pfn: The start PFN of the available physical memory * @end_pfn: The end PFN of the available physical memory * * These ranges are stored in an early_node_map[] and later used by * free_area_init_nodes() to calculate zone sizes and holes. If the * range spans a memory hole, it is up to the architecture to ensure * the memory is not freed by the bootmem allocator. If possible * the range being registered will be merged with existing ranges. */ void __init add_active_range(unsigned int nid, unsigned long start_pfn, unsigned long end_pfn) { int i; mminit_dprintk(MMINIT_TRACE, "memory_register", "Entering add_active_range(%d, %#lx, %#lx) " "%d entries of %d used\n", nid, start_pfn, end_pfn, nr_nodemap_entries, MAX_ACTIVE_REGIONS); mminit_validate_memmodel_limits(&start_pfn, &end_pfn); /* Merge with existing active regions if possible */ for (i = 0; i < nr_nodemap_entries; i++) { if (early_node_map[i].nid != nid) continue; /* Skip if an existing region covers this new one */ if (start_pfn >= early_node_map[i].start_pfn && end_pfn <= early_node_map[i].end_pfn) return; /* Merge forward if suitable */ if (start_pfn <= early_node_map[i].end_pfn && end_pfn > early_node_map[i].end_pfn) { early_node_map[i].end_pfn = end_pfn; return; } /* Merge backward if suitable */ if (start_pfn < early_node_map[i].start_pfn && end_pfn >= early_node_map[i].start_pfn) { early_node_map[i].start_pfn = start_pfn; return; } } /* Check that early_node_map is large enough */ if (i >= MAX_ACTIVE_REGIONS) { printk(KERN_CRIT "More than %d memory regions, truncating\n", MAX_ACTIVE_REGIONS); return; } early_node_map[i].nid = nid; early_node_map[i].start_pfn = start_pfn; early_node_map[i].end_pfn = end_pfn; nr_nodemap_entries = i + 1; } /** * remove_active_range - Shrink an existing registered range of PFNs * @nid: The node id the range is on that should be shrunk * @start_pfn: The new PFN of the range * @end_pfn: The new PFN of the range * * i386 with NUMA use alloc_remap() to store a node_mem_map on a local node. * The map is kept near the end physical page range that has already been * registered. This function allows an arch to shrink an existing registered * range. */ void __init remove_active_range(unsigned int nid, unsigned long start_pfn, unsigned long end_pfn) { int i, j; int removed = 0; printk(KERN_DEBUG "remove_active_range (%d, %lu, %lu)\n", nid, start_pfn, end_pfn); /* Find the old active region end and shrink */ for_each_active_range_index_in_nid(i, nid) { if (early_node_map[i].start_pfn >= start_pfn && early_node_map[i].end_pfn <= end_pfn) { /* clear it */ early_node_map[i].start_pfn = 0; early_node_map[i].end_pfn = 0; removed = 1; continue; } if (early_node_map[i].start_pfn < start_pfn && early_node_map[i].end_pfn > start_pfn) { unsigned long temp_end_pfn = early_node_map[i].end_pfn; early_node_map[i].end_pfn = start_pfn; if (temp_end_pfn > end_pfn) add_active_range(nid, end_pfn, temp_end_pfn); continue; } if (early_node_map[i].start_pfn >= start_pfn && early_node_map[i].end_pfn > end_pfn && early_node_map[i].start_pfn < end_pfn) { early_node_map[i].start_pfn = end_pfn; continue; } } if (!removed) return; /* remove the blank ones */ for (i = nr_nodemap_entries - 1; i > 0; i--) { if (early_node_map[i].nid != nid) continue; if (early_node_map[i].end_pfn) continue; /* we found it, get rid of it */ for (j = i; j < nr_nodemap_entries - 1; j++) memcpy(&early_node_map[j], &early_node_map[j+1], sizeof(early_node_map[j])); j = nr_nodemap_entries - 1; memset(&early_node_map[j], 0, sizeof(early_node_map[j])); nr_nodemap_entries--; } } /** * remove_all_active_ranges - Remove all currently registered regions * * During discovery, it may be found that a table like SRAT is invalid * and an alternative discovery method must be used. This function removes * all currently registered regions. */ void __init remove_all_active_ranges(void) { memset(early_node_map, 0, sizeof(early_node_map)); nr_nodemap_entries = 0; } /* Compare two active node_active_regions */ static int __init cmp_node_active_region(const void *a, const void *b) { struct node_active_region *arange = (struct node_active_region *)a; struct node_active_region *brange = (struct node_active_region *)b; /* Done this way to avoid overflows */ if (arange->start_pfn > brange->start_pfn) return 1; if (arange->start_pfn < brange->start_pfn) return -1; return 0; } /* sort the node_map by start_pfn */ void __init sort_node_map(void) { sort(early_node_map, (size_t)nr_nodemap_entries, sizeof(struct node_active_region), cmp_node_active_region, NULL); } /* Find the lowest pfn for a node */ static unsigned long __init find_min_pfn_for_node(int nid) { int i; unsigned long min_pfn = ULONG_MAX; /* Assuming a sorted map, the first range found has the starting pfn */ for_each_active_range_index_in_nid(i, nid) min_pfn = min(min_pfn, early_node_map[i].start_pfn); if (min_pfn == ULONG_MAX) { printk(KERN_WARNING "Could not find start_pfn for node %d\n", nid); return 0; } return min_pfn; } /** * find_min_pfn_with_active_regions - Find the minimum PFN registered * * It returns the minimum PFN based on information provided via * add_active_range(). */ unsigned long __init find_min_pfn_with_active_regions(void) { return find_min_pfn_for_node(MAX_NUMNODES); } /* * early_calculate_totalpages() * Sum pages in active regions for movable zone. * Populate N_HIGH_MEMORY for calculating usable_nodes. */ static unsigned long __init early_calculate_totalpages(void) { int i; unsigned long totalpages = 0; for (i = 0; i < nr_nodemap_entries; i++) { unsigned long pages = early_node_map[i].end_pfn - early_node_map[i].start_pfn; totalpages += pages; if (pages) node_set_state(early_node_map[i].nid, N_HIGH_MEMORY); } return totalpages; } /* * Find the PFN the Movable zone begins in each node. Kernel memory * is spread evenly between nodes as long as the nodes have enough * memory. When they don't, some nodes will have more kernelcore than * others */ static void __init find_zone_movable_pfns_for_nodes(unsigned long *movable_pfn) { int i, nid; unsigned long usable_startpfn; unsigned long kernelcore_node, kernelcore_remaining; /* save the state before borrow the nodemask */ nodemask_t saved_node_state = node_states[N_HIGH_MEMORY]; unsigned long totalpages = early_calculate_totalpages(); int usable_nodes = nodes_weight(node_states[N_HIGH_MEMORY]); /* * If movablecore was specified, calculate what size of * kernelcore that corresponds so that memory usable for * any allocation type is evenly spread. If both kernelcore * and movablecore are specified, then the value of kernelcore * will be used for required_kernelcore if it's greater than * what movablecore would have allowed. */ if (required_movablecore) { unsigned long corepages; /* * Round-up so that ZONE_MOVABLE is at least as large as what * was requested by the user */ required_movablecore = roundup(required_movablecore, MAX_ORDER_NR_PAGES); corepages = totalpages - required_movablecore; required_kernelcore = max(required_kernelcore, corepages); } /* If kernelcore was not specified, there is no ZONE_MOVABLE */ if (!required_kernelcore) goto out; /* usable_startpfn is the lowest possible pfn ZONE_MOVABLE can be at */ find_usable_zone_for_movable(); usable_startpfn = arch_zone_lowest_possible_pfn[movable_zone]; restart: /* Spread kernelcore memory as evenly as possible throughout nodes */ kernelcore_node = required_kernelcore / usable_nodes; for_each_node_state(nid, N_HIGH_MEMORY) { /* * Recalculate kernelcore_node if the division per node * now exceeds what is necessary to satisfy the requested * amount of memory for the kernel */ if (required_kernelcore < kernelcore_node) kernelcore_node = required_kernelcore / usable_nodes; /* * As the map is walked, we track how much memory is usable * by the kernel using kernelcore_remaining. When it is * 0, the rest of the node is usable by ZONE_MOVABLE */ kernelcore_remaining = kernelcore_node; /* Go through each range of PFNs within this node */ for_each_active_range_index_in_nid(i, nid) { unsigned long start_pfn, end_pfn; unsigned long size_pages; start_pfn = max(early_node_map[i].start_pfn, zone_movable_pfn[nid]); end_pfn = early_node_map[i].end_pfn; if (start_pfn >= end_pfn) continue; /* Account for what is only usable for kernelcore */ if (start_pfn < usable_startpfn) { unsigned long kernel_pages; kernel_pages = min(end_pfn, usable_startpfn) - start_pfn; kernelcore_remaining -= min(kernel_pages, kernelcore_remaining); required_kernelcore -= min(kernel_pages, required_kernelcore); /* Continue if range is now fully accounted */ if (end_pfn <= usable_startpfn) { /* * Push zone_movable_pfn to the end so * that if we have to rebalance * kernelcore across nodes, we will * not double account here */ zone_movable_pfn[nid] = end_pfn; continue; } start_pfn = usable_startpfn; } /* * The usable PFN range for ZONE_MOVABLE is from * start_pfn->end_pfn. Calculate size_pages as the * number of pages used as kernelcore */ size_pages = end_pfn - start_pfn; if (size_pages > kernelcore_remaining) size_pages = kernelcore_remaining; zone_movable_pfn[nid] = start_pfn + size_pages; /* * Some kernelcore has been met, update counts and * break if the kernelcore for this node has been * satisified */ required_kernelcore -= min(required_kernelcore, size_pages); kernelcore_remaining -= size_pages; if (!kernelcore_remaining) break; } } /* * If there is still required_kernelcore, we do another pass with one * less node in the count. This will push zone_movable_pfn[nid] further * along on the nodes that still have memory until kernelcore is * satisified */ usable_nodes--; if (usable_nodes && required_kernelcore > usable_nodes) goto restart; /* Align start of ZONE_MOVABLE on all nids to MAX_ORDER_NR_PAGES */ for (nid = 0; nid < MAX_NUMNODES; nid++) zone_movable_pfn[nid] = roundup(zone_movable_pfn[nid], MAX_ORDER_NR_PAGES); out: /* restore the node_state */ node_states[N_HIGH_MEMORY] = saved_node_state; } /* Any regular memory on that node ? */ static void check_for_regular_memory(pg_data_t *pgdat) { #ifdef CONFIG_HIGHMEM enum zone_type zone_type; for (zone_type = 0; zone_type <= ZONE_NORMAL; zone_type++) { struct zone *zone = &pgdat->node_zones[zone_type]; if (zone->present_pages) node_set_state(zone_to_nid(zone), N_NORMAL_MEMORY); } #endif } /** * free_area_init_nodes - Initialise all pg_data_t and zone data * @max_zone_pfn: an array of max PFNs for each zone * * This will call free_area_init_node() for each active node in the system. * Using the page ranges provided by add_active_range(), the size of each * zone in each node and their holes is calculated. If the maximum PFN * between two adjacent zones match, it is assumed that the zone is empty. * For example, if arch_max_dma_pfn == arch_max_dma32_pfn, it is assumed * that arch_max_dma32_pfn has no pages. It is also assumed that a zone * starts where the previous one ended. For example, ZONE_DMA32 starts * at arch_max_dma_pfn. */ void __init free_area_init_nodes(unsigned long *max_zone_pfn) { unsigned long nid; int i; /* Sort early_node_map as initialisation assumes it is sorted */ sort_node_map(); /* Record where the zone boundaries are */ memset(arch_zone_lowest_possible_pfn, 0, sizeof(arch_zone_lowest_possible_pfn)); memset(arch_zone_highest_possible_pfn, 0, sizeof(arch_zone_highest_possible_pfn)); arch_zone_lowest_possible_pfn[0] = find_min_pfn_with_active_regions(); arch_zone_highest_possible_pfn[0] = max_zone_pfn[0]; for (i = 1; i < MAX_NR_ZONES; i++) { if (i == ZONE_MOVABLE) continue; arch_zone_lowest_possible_pfn[i] = arch_zone_highest_possible_pfn[i-1]; arch_zone_highest_possible_pfn[i] = max(max_zone_pfn[i], arch_zone_lowest_possible_pfn[i]); } arch_zone_lowest_possible_pfn[ZONE_MOVABLE] = 0; arch_zone_highest_possible_pfn[ZONE_MOVABLE] = 0; /* Find the PFNs that ZONE_MOVABLE begins at in each node */ memset(zone_movable_pfn, 0, sizeof(zone_movable_pfn)); find_zone_movable_pfns_for_nodes(zone_movable_pfn); /* Print out the zone ranges */ printk("Zone PFN ranges:\n"); for (i = 0; i < MAX_NR_ZONES; i++) { if (i == ZONE_MOVABLE) continue; printk(" %-8s ", zone_names[i]); if (arch_zone_lowest_possible_pfn[i] == arch_zone_highest_possible_pfn[i]) printk("empty\n"); else printk("%0#10lx -> %0#10lx\n", arch_zone_lowest_possible_pfn[i], arch_zone_highest_possible_pfn[i]); } /* Print out the PFNs ZONE_MOVABLE begins at in each node */ printk("Movable zone start PFN for each node\n"); for (i = 0; i < MAX_NUMNODES; i++) { if (zone_movable_pfn[i]) printk(" Node %d: %lu\n", i, zone_movable_pfn[i]); } /* Print out the early_node_map[] */ printk("early_node_map[%d] active PFN ranges\n", nr_nodemap_entries); for (i = 0; i < nr_nodemap_entries; i++) printk(" %3d: %0#10lx -> %0#10lx\n", early_node_map[i].nid, early_node_map[i].start_pfn, early_node_map[i].end_pfn); /* Initialise every node */ mminit_verify_pageflags_layout(); setup_nr_node_ids(); for_each_online_node(nid) { pg_data_t *pgdat = NODE_DATA(nid); free_area_init_node(nid, NULL, find_min_pfn_for_node(nid), NULL); /* Any memory on that node */ if (pgdat->node_present_pages) node_set_state(nid, N_HIGH_MEMORY); check_for_regular_memory(pgdat); } } static int __init cmdline_parse_core(char *p, unsigned long *core) { unsigned long long coremem; if (!p) return -EINVAL; coremem = memparse(p, &p); *core = coremem >> PAGE_SHIFT; /* Paranoid check that UL is enough for the coremem value */ WARN_ON((coremem >> PAGE_SHIFT) > ULONG_MAX); return 0; } /* * kernelcore=size sets the amount of memory for use for allocations that * cannot be reclaimed or migrated. */ static int __init cmdline_parse_kernelcore(char *p) { return cmdline_parse_core(p, &required_kernelcore); } /* * movablecore=size sets the amount of memory for use for allocations that * can be reclaimed or migrated. */ static int __init cmdline_parse_movablecore(char *p) { return cmdline_parse_core(p, &required_movablecore); } early_param("kernelcore", cmdline_parse_kernelcore); early_param("movablecore", cmdline_parse_movablecore); #endif /* CONFIG_ARCH_POPULATES_NODE_MAP */ /** * set_dma_reserve - set the specified number of pages reserved in the first zone * @new_dma_reserve: The number of pages to mark reserved * * The per-cpu batchsize and zone watermarks are determined by present_pages. * In the DMA zone, a significant percentage may be consumed by kernel image * and other unfreeable allocations which can skew the watermarks badly. This * function may optionally be used to account for unfreeable pages in the * first zone (e.g., ZONE_DMA). The effect will be lower watermarks and * smaller per-cpu batchsize. */ void __init set_dma_reserve(unsigned long new_dma_reserve) { dma_reserve = new_dma_reserve; } #ifndef CONFIG_NEED_MULTIPLE_NODES struct pglist_data __refdata contig_page_data = { #ifndef CONFIG_NO_BOOTMEM .bdata = &bootmem_node_data[0] #endif }; EXPORT_SYMBOL(contig_page_data); #endif void __init free_area_init(unsigned long *zones_size) { free_area_init_node(0, zones_size, __pa(PAGE_OFFSET) >> PAGE_SHIFT, NULL); } static int page_alloc_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu) { int cpu = (unsigned long)hcpu; if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) { drain_pages(cpu); /* * Spill the event counters of the dead processor * into the current processors event counters. * This artificially elevates the count of the current * processor. */ vm_events_fold_cpu(cpu); /* * Zero the differential counters of the dead processor * so that the vm statistics are consistent. * * This is only okay since the processor is dead and cannot * race with what we are doing. */ refresh_cpu_vm_stats(cpu); } return NOTIFY_OK; } void __init page_alloc_init(void) { hotcpu_notifier(page_alloc_cpu_notify, 0); } /* * calculate_totalreserve_pages - called when sysctl_lower_zone_reserve_ratio * or min_free_kbytes changes. */ static void calculate_totalreserve_pages(void) { struct pglist_data *pgdat; unsigned long reserve_pages = 0; enum zone_type i, j; for_each_online_pgdat(pgdat) { for (i = 0; i < MAX_NR_ZONES; i++) { struct zone *zone = pgdat->node_zones + i; unsigned long max = 0; /* Find valid and maximum lowmem_reserve in the zone */ for (j = i; j < MAX_NR_ZONES; j++) { if (zone->lowmem_reserve[j] > max) max = zone->lowmem_reserve[j]; } /* we treat the high watermark as reserved pages. */ max += high_wmark_pages(zone); if (max > zone->present_pages) max = zone->present_pages; reserve_pages += max; } } totalreserve_pages = reserve_pages; } /* * setup_per_zone_lowmem_reserve - called whenever * sysctl_lower_zone_reserve_ratio changes. Ensures that each zone * has a correct pages reserved value, so an adequate number of * pages are left in the zone after a successful __alloc_pages(). */ static void setup_per_zone_lowmem_reserve(void) { struct pglist_data *pgdat; enum zone_type j, idx; for_each_online_pgdat(pgdat) { for (j = 0; j < MAX_NR_ZONES; j++) { struct zone *zone = pgdat->node_zones + j; unsigned long present_pages = zone->present_pages; zone->lowmem_reserve[j] = 0; idx = j; while (idx) { struct zone *lower_zone; idx--; if (sysctl_lowmem_reserve_ratio[idx] < 1) sysctl_lowmem_reserve_ratio[idx] = 1; lower_zone = pgdat->node_zones + idx; lower_zone->lowmem_reserve[j] = present_pages / sysctl_lowmem_reserve_ratio[idx]; present_pages += lower_zone->present_pages; } } } /* update totalreserve_pages */ calculate_totalreserve_pages(); } /** * setup_per_zone_wmarks - called when min_free_kbytes changes * or when memory is hot-{added|removed} * * Ensures that the watermark[min,low,high] values for each zone are set * correctly with respect to min_free_kbytes. */ void setup_per_zone_wmarks(void) { unsigned long pages_min = min_free_kbytes >> (PAGE_SHIFT - 10); unsigned long lowmem_pages = 0; struct zone *zone; unsigned long flags; /* Calculate total number of !ZONE_HIGHMEM pages */ for_each_zone(zone) { if (!is_highmem(zone)) lowmem_pages += zone->present_pages; } for_each_zone(zone) { u64 tmp; spin_lock_irqsave(&zone->lock, flags); tmp = (u64)pages_min * zone->present_pages; do_div(tmp, lowmem_pages); if (is_highmem(zone)) { /* * __GFP_HIGH and PF_MEMALLOC allocations usually don't * need highmem pages, so cap pages_min to a small * value here. * * The WMARK_HIGH-WMARK_LOW and (WMARK_LOW-WMARK_MIN) * deltas controls asynch page reclaim, and so should * not be capped for highmem. */ int min_pages; min_pages = zone->present_pages / 1024; if (min_pages < SWAP_CLUSTER_MAX) min_pages = SWAP_CLUSTER_MAX; if (min_pages > 128) min_pages = 128; zone->watermark[WMARK_MIN] = min_pages; } else { /* * If it's a lowmem zone, reserve a number of pages * proportionate to the zone's size. */ zone->watermark[WMARK_MIN] = tmp; } zone->watermark[WMARK_LOW] = min_wmark_pages(zone) + (tmp >> 2); zone->watermark[WMARK_HIGH] = min_wmark_pages(zone) + (tmp >> 1); setup_zone_migrate_reserve(zone); spin_unlock_irqrestore(&zone->lock, flags); } /* update totalreserve_pages */ calculate_totalreserve_pages(); } /* * The inactive anon list should be small enough that the VM never has to * do too much work, but large enough that each inactive page has a chance * to be referenced again before it is swapped out. * * The inactive_anon ratio is the target ratio of ACTIVE_ANON to * INACTIVE_ANON pages on this zone's LRU, maintained by the * pageout code. A zone->inactive_ratio of 3 means 3:1 or 25% of * the anonymous pages are kept on the inactive list. * * total target max * memory ratio inactive anon * ------------------------------------- * 10MB 1 5MB * 100MB 1 50MB * 1GB 3 250MB * 10GB 10 0.9GB * 100GB 31 3GB * 1TB 101 10GB * 10TB 320 32GB */ void calculate_zone_inactive_ratio(struct zone *zone) { unsigned int gb, ratio; /* Zone size in gigabytes */ gb = zone->present_pages >> (30 - PAGE_SHIFT); if (gb) ratio = int_sqrt(10 * gb); else ratio = 1; zone->inactive_ratio = ratio; } static void __init setup_per_zone_inactive_ratio(void) { struct zone *zone; for_each_zone(zone) calculate_zone_inactive_ratio(zone); } /* * Initialise min_free_kbytes. * * For small machines we want it small (128k min). For large machines * we want it large (64MB max). But it is not linear, because network * bandwidth does not increase linearly with machine size. We use * * min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy: * min_free_kbytes = sqrt(lowmem_kbytes * 16) * * which yields * * 16MB: 512k * 32MB: 724k * 64MB: 1024k * 128MB: 1448k * 256MB: 2048k * 512MB: 2896k * 1024MB: 4096k * 2048MB: 5792k * 4096MB: 8192k * 8192MB: 11584k * 16384MB: 16384k */ static int __init init_per_zone_wmark_min(void) { unsigned long lowmem_kbytes; lowmem_kbytes = nr_free_buffer_pages() * (PAGE_SIZE >> 10); min_free_kbytes = int_sqrt(lowmem_kbytes * 16); if (min_free_kbytes < 128) min_free_kbytes = 128; if (min_free_kbytes > 65536) min_free_kbytes = 65536; setup_per_zone_wmarks(); setup_per_zone_lowmem_reserve(); setup_per_zone_inactive_ratio(); return 0; } module_init(init_per_zone_wmark_min) /* * min_free_kbytes_sysctl_handler - just a wrapper around proc_dointvec() so * that we can call two helper functions whenever min_free_kbytes * changes. */ int min_free_kbytes_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { proc_dointvec(table, write, buffer, length, ppos); if (write) setup_per_zone_wmarks(); return 0; } #ifdef CONFIG_NUMA int sysctl_min_unmapped_ratio_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { struct zone *zone; int rc; rc = proc_dointvec_minmax(table, write, buffer, length, ppos); if (rc) return rc; for_each_zone(zone) zone->min_unmapped_pages = (zone->present_pages * sysctl_min_unmapped_ratio) / 100; return 0; } int sysctl_min_slab_ratio_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { struct zone *zone; int rc; rc = proc_dointvec_minmax(table, write, buffer, length, ppos); if (rc) return rc; for_each_zone(zone) zone->min_slab_pages = (zone->present_pages * sysctl_min_slab_ratio) / 100; return 0; } #endif /* * lowmem_reserve_ratio_sysctl_handler - just a wrapper around * proc_dointvec() so that we can call setup_per_zone_lowmem_reserve() * whenever sysctl_lowmem_reserve_ratio changes. * * The reserve ratio obviously has absolutely no relation with the * minimum watermarks. The lowmem reserve ratio can only make sense * if in function of the boot time zone sizes. */ int lowmem_reserve_ratio_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { proc_dointvec_minmax(table, write, buffer, length, ppos); setup_per_zone_lowmem_reserve(); return 0; } /* * percpu_pagelist_fraction - changes the pcp->high for each zone on each * cpu. It is the fraction of total pages in each zone that a hot per cpu pagelist * can have before it gets flushed back to buddy allocator. */ int percpu_pagelist_fraction_sysctl_handler(ctl_table *table, int write, void __user *buffer, size_t *length, loff_t *ppos) { struct zone *zone; unsigned int cpu; int ret; ret = proc_dointvec_minmax(table, write, buffer, length, ppos); if (!write || (ret == -EINVAL)) return ret; for_each_populated_zone(zone) { for_each_possible_cpu(cpu) { unsigned long high; high = zone->present_pages / percpu_pagelist_fraction; setup_pagelist_highmark( per_cpu_ptr(zone->pageset, cpu), high); } } return 0; } int hashdist = HASHDIST_DEFAULT; #ifdef CONFIG_NUMA static int __init set_hashdist(char *str) { if (!str) return 0; hashdist = simple_strtoul(str, &str, 0); return 1; } __setup("hashdist=", set_hashdist); #endif /* * allocate a large system hash table from bootmem * - it is assumed that the hash table must contain an exact power-of-2 * quantity of entries * - limit is the number of hash buckets, not the total allocation size */ void *__init alloc_large_system_hash(const char *tablename, unsigned long bucketsize, unsigned long numentries, int scale, int flags, unsigned int *_hash_shift, unsigned int *_hash_mask, unsigned long limit) { unsigned long long max = limit; unsigned long log2qty, size; void *table = NULL; /* allow the kernel cmdline to have a say */ if (!numentries) { /* round applicable memory size up to nearest megabyte */ numentries = nr_kernel_pages; numentries += (1UL << (20 - PAGE_SHIFT)) - 1; numentries >>= 20 - PAGE_SHIFT; numentries <<= 20 - PAGE_SHIFT; /* limit to 1 bucket per 2^scale bytes of low memory */ if (scale > PAGE_SHIFT) numentries >>= (scale - PAGE_SHIFT); else numentries <<= (PAGE_SHIFT - scale); /* Make sure we've got at least a 0-order allocation.. */ if (unlikely(flags & HASH_SMALL)) { /* Makes no sense without HASH_EARLY */ WARN_ON(!(flags & HASH_EARLY)); if (!(numentries >> *_hash_shift)) { numentries = 1UL << *_hash_shift; BUG_ON(!numentries); } } else if (unlikely((numentries * bucketsize) < PAGE_SIZE)) numentries = PAGE_SIZE / bucketsize; } numentries = roundup_pow_of_two(numentries); /* limit allocation size to 1/16 total memory by default */ if (max == 0) { max = ((unsigned long long)nr_all_pages << PAGE_SHIFT) >> 4; do_div(max, bucketsize); } if (numentries > max) numentries = max; log2qty = ilog2(numentries); do { size = bucketsize << log2qty; if (flags & HASH_EARLY) table = alloc_bootmem_nopanic(size); else if (hashdist) table = __vmalloc(size, GFP_ATOMIC, PAGE_KERNEL); else { /* * If bucketsize is not a power-of-two, we may free * some pages at the end of hash table which * alloc_pages_exact() automatically does */ if (get_order(size) < MAX_ORDER) { table = alloc_pages_exact(size, GFP_ATOMIC); kmemleak_alloc(table, size, 1, GFP_ATOMIC); } } } while (!table && size > PAGE_SIZE && --log2qty); if (!table) panic("Failed to allocate %s hash table\n", tablename); printk(KERN_INFO "%s hash table entries: %d (order: %d, %lu bytes)\n", tablename, (1U << log2qty), ilog2(size) - PAGE_SHIFT, size); if (_hash_shift) *_hash_shift = log2qty; if (_hash_mask) *_hash_mask = (1 << log2qty) - 1; return table; } /* Return a pointer to the bitmap storing bits affecting a block of pages */ static inline unsigned long *get_pageblock_bitmap(struct zone *zone, unsigned long pfn) { #ifdef CONFIG_SPARSEMEM return __pfn_to_section(pfn)->pageblock_flags; #else return zone->pageblock_flags; #endif /* CONFIG_SPARSEMEM */ } static inline int pfn_to_bitidx(struct zone *zone, unsigned long pfn) { #ifdef CONFIG_SPARSEMEM pfn &= (PAGES_PER_SECTION-1); return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS; #else pfn = pfn - zone->zone_start_pfn; return (pfn >> pageblock_order) * NR_PAGEBLOCK_BITS; #endif /* CONFIG_SPARSEMEM */ } /** * get_pageblock_flags_group - Return the requested group of flags for the pageblock_nr_pages block of pages * @page: The page within the block of interest * @start_bitidx: The first bit of interest to retrieve * @end_bitidx: The last bit of interest * returns pageblock_bits flags */ unsigned long get_pageblock_flags_group(struct page *page, int start_bitidx, int end_bitidx) { struct zone *zone; unsigned long *bitmap; unsigned long pfn, bitidx; unsigned long flags = 0; unsigned long value = 1; zone = page_zone(page); pfn = page_to_pfn(page); bitmap = get_pageblock_bitmap(zone, pfn); bitidx = pfn_to_bitidx(zone, pfn); for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1) if (test_bit(bitidx + start_bitidx, bitmap)) flags |= value; return flags; } /** * set_pageblock_flags_group - Set the requested group of flags for a pageblock_nr_pages block of pages * @page: The page within the block of interest * @start_bitidx: The first bit of interest * @end_bitidx: The last bit of interest * @flags: The flags to set */ void set_pageblock_flags_group(struct page *page, unsigned long flags, int start_bitidx, int end_bitidx) { struct zone *zone; unsigned long *bitmap; unsigned long pfn, bitidx; unsigned long value = 1; zone = page_zone(page); pfn = page_to_pfn(page); bitmap = get_pageblock_bitmap(zone, pfn); bitidx = pfn_to_bitidx(zone, pfn); VM_BUG_ON(pfn < zone->zone_start_pfn); VM_BUG_ON(pfn >= zone->zone_start_pfn + zone->spanned_pages); for (; start_bitidx <= end_bitidx; start_bitidx++, value <<= 1) if (flags & value) __set_bit(bitidx + start_bitidx, bitmap); else __clear_bit(bitidx + start_bitidx, bitmap); } /* * This is designed as sub function...plz see page_isolation.c also. * set/clear page block's type to be ISOLATE. * page allocater never alloc memory from ISOLATE block. */ int set_migratetype_isolate(struct page *page) { struct zone *zone; struct page *curr_page; unsigned long flags, pfn, iter; unsigned long immobile = 0; struct memory_isolate_notify arg; int notifier_ret; int ret = -EBUSY; int zone_idx; zone = page_zone(page); zone_idx = zone_idx(zone); spin_lock_irqsave(&zone->lock, flags); if (get_pageblock_migratetype(page) == MIGRATE_MOVABLE || zone_idx == ZONE_MOVABLE) { ret = 0; goto out; } pfn = page_to_pfn(page); arg.start_pfn = pfn; arg.nr_pages = pageblock_nr_pages; arg.pages_found = 0; /* * It may be possible to isolate a pageblock even if the * migratetype is not MIGRATE_MOVABLE. The memory isolation * notifier chain is used by balloon drivers to return the * number of pages in a range that are held by the balloon * driver to shrink memory. If all the pages are accounted for * by balloons, are free, or on the LRU, isolation can continue. * Later, for example, when memory hotplug notifier runs, these * pages reported as "can be isolated" should be isolated(freed) * by the balloon driver through the memory notifier chain. */ notifier_ret = memory_isolate_notify(MEM_ISOLATE_COUNT, &arg); notifier_ret = notifier_to_errno(notifier_ret); if (notifier_ret || !arg.pages_found) goto out; for (iter = pfn; iter < (pfn + pageblock_nr_pages); iter++) { if (!pfn_valid_within(pfn)) continue; curr_page = pfn_to_page(iter); if (!page_count(curr_page) || PageLRU(curr_page)) continue; immobile++; } if (arg.pages_found == immobile) ret = 0; out: if (!ret) { set_pageblock_migratetype(page, MIGRATE_ISOLATE); move_freepages_block(zone, page, MIGRATE_ISOLATE); } spin_unlock_irqrestore(&zone->lock, flags); if (!ret) drain_all_pages(); return ret; } void unset_migratetype_isolate(struct page *page) { struct zone *zone; unsigned long flags; zone = page_zone(page); spin_lock_irqsave(&zone->lock, flags); if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE) goto out; set_pageblock_migratetype(page, MIGRATE_MOVABLE); move_freepages_block(zone, page, MIGRATE_MOVABLE); out: spin_unlock_irqrestore(&zone->lock, flags); } #ifdef CONFIG_MEMORY_HOTREMOVE /* * All pages in the range must be isolated before calling this. */ void __offline_isolated_pages(unsigned long start_pfn, unsigned long end_pfn) { struct page *page; struct zone *zone; int order, i; unsigned long pfn; unsigned long flags; /* find the first valid pfn */ for (pfn = start_pfn; pfn < end_pfn; pfn++) if (pfn_valid(pfn)) break; if (pfn == end_pfn) return; zone = page_zone(pfn_to_page(pfn)); spin_lock_irqsave(&zone->lock, flags); pfn = start_pfn; while (pfn < end_pfn) { if (!pfn_valid(pfn)) { pfn++; continue; } page = pfn_to_page(pfn); BUG_ON(page_count(page)); BUG_ON(!PageBuddy(page)); order = page_order(page); #ifdef CONFIG_DEBUG_VM printk(KERN_INFO "remove from free list %lx %d %lx\n", pfn, 1 << order, end_pfn); #endif list_del(&page->lru); rmv_page_order(page); zone->free_area[order].nr_free--; __mod_zone_page_state(zone, NR_FREE_PAGES, - (1UL << order)); for (i = 0; i < (1 << order); i++) SetPageReserved((page+i)); pfn += (1 << order); } spin_unlock_irqrestore(&zone->lock, flags); } #endif #ifdef CONFIG_MEMORY_FAILURE bool is_free_buddy_page(struct page *page) { struct zone *zone = page_zone(page); unsigned long pfn = page_to_pfn(page); unsigned long flags; int order; spin_lock_irqsave(&zone->lock, flags); for (order = 0; order < MAX_ORDER; order++) { struct page *page_head = page - (pfn & ((1 << order) - 1)); if (PageBuddy(page_head) && page_order(page_head) >= order) break; } spin_unlock_irqrestore(&zone->lock, flags); return order < MAX_ORDER; } #endif static struct trace_print_flags pageflag_names[] = { {1UL << PG_locked, "locked" }, {1UL << PG_error, "error" }, {1UL << PG_referenced, "referenced" }, {1UL << PG_uptodate, "uptodate" }, {1UL << PG_dirty, "dirty" }, {1UL << PG_lru, "lru" }, {1UL << PG_active, "active" }, {1UL << PG_slab, "slab" }, {1UL << PG_owner_priv_1, "owner_priv_1" }, {1UL << PG_arch_1, "arch_1" }, {1UL << PG_reserved, "reserved" }, {1UL << PG_private, "private" }, {1UL << PG_private_2, "private_2" }, {1UL << PG_writeback, "writeback" }, #ifdef CONFIG_PAGEFLAGS_EXTENDED {1UL << PG_head, "head" }, {1UL << PG_tail, "tail" }, #else {1UL << PG_compound, "compound" }, #endif {1UL << PG_swapcache, "swapcache" }, {1UL << PG_mappedtodisk, "mappedtodisk" }, {1UL << PG_reclaim, "reclaim" }, {1UL << PG_buddy, "buddy" }, {1UL << PG_swapbacked, "swapbacked" }, {1UL << PG_unevictable, "unevictable" }, #ifdef CONFIG_MMU {1UL << PG_mlocked, "mlocked" }, #endif #ifdef CONFIG_ARCH_USES_PG_UNCACHED {1UL << PG_uncached, "uncached" }, #endif #ifdef CONFIG_MEMORY_FAILURE {1UL << PG_hwpoison, "hwpoison" }, #endif {-1UL, NULL }, }; static void dump_page_flags(unsigned long flags) { const char *delim = ""; unsigned long mask; int i; printk(KERN_ALERT "page flags: %#lx(", flags); /* remove zone id */ flags &= (1UL << NR_PAGEFLAGS) - 1; for (i = 0; pageflag_names[i].name && flags; i++) { mask = pageflag_names[i].mask; if ((flags & mask) != mask) continue; flags &= ~mask; printk("%s%s", delim, pageflag_names[i].name); delim = "|"; } /* check for left over flags */ if (flags) printk("%s%#lx", delim, flags); printk(")\n"); } void dump_page(struct page *page) { printk(KERN_ALERT "page:%p count:%d mapcount:%d mapping:%p index:%#lx\n", page, page_count(page), page_mapcount(page), page->mapping, page->index); dump_page_flags(page->flags); }
LeeDroid-/Shooter-2.6.35-MR
mm/page_alloc.c
C
gpl-2.0
155,435
#include "lolevel.h" #include "platform.h" #include "core.h" static long *nrflag = (long*)0x6CE0; #include "../../../generic/capt_seq.c" void __attribute__((naked,noinline)) sub_FFD39620_my(long p) { asm volatile ( "STMFD SP!, {R4,R5,LR}\n" "LDR R3, =0x73D34\n" "LDR R5, =0x6CDC\n" "SUB SP, SP, #4\n" "LDR R1, =0xFFFFFFFF\n" "STR R0, [R5]\n" "LDR R0, [R3]\n" "BL sub_FFC0FA60\n" "BL sub_FFD3F438\n" "BL wait_until_remote_button_is_released\n" "LDR R0, [R0,#0x7C]\n" "BL sub_FFD39594\n" // nr "BL capt_seq_hook_set_nr\n" "LDR R3, =0x6CE4\n" "LDR R0, [R3]\n" "BL sub_FFC8C088\n" "B sub_FFD3965C\n" // continue orig. func ); } void __attribute__((naked,noinline)) sub_FFD364B0_my(long p) { asm volatile ( "STMFD SP!, {R4,R5,LR}\n" "LDR R5, [R0,#0xC]\n" "BL sub_FFD3F1DC\n" "CMP R0, #0\n" "BNE 1f\n" "BL sub_FFD3F1E8\n" "1:\n" "MOV R0, R5\n" "BL sub_FFD3842C\n" "TST R0, #1\n" "MOV R2, R5\n" "MOV R1, #1\n" "BEQ 2f\n" "LDMFD SP!, {R4,R5,LR}\n" "B sub_FFD34A08\n" "2:\n" "BL sub_FFD74484\n" "BL sub_FFD33DF4\n" "MOV R4, R0\n" "BL sub_FFC143A4\n" "ADD R3, R5, R5,LSL#1\n" "ADD R4, R4, R3,LSL#5\n" "STR R0, [R4,#4]\n" "MOV R0, R5\n" "BL sub_FFD39E38\n" // ?? "BL sub_FFD38970\n" // tv related "BL sub_FFD38910\n" // ?? "MOV R0, R5\n" "BL sub_FFD39620_my\n" // make photo "BL capt_seq_hook_raw_here\n" "MOV R2, R5\n" "MOV R1, #1\n" "BL sub_FFD34A08\n" // save file ? "LDMFD SP!, {R4,R5,LR}\n" "B sub_FFD39820\n" ); } void __attribute__((naked,noinline)) capt_seq_task() { asm volatile ( "STMFD SP!, {R4,LR}\n" "SUB SP, SP, #4\n" "MOV R4, SP\n" "B loc_FFD36A08\n" // --------------------------------------------------------------------------- "loc_FFD368B4:\n" "LDR R2, [SP,#0xC-0xC]\n" "LDR R3, [R2]\n" "MOV R0, R2\n" "CMP R3, #0x15\n" "LDRLS PC, [PC,R3,LSL#2]\n" "B loc_FFD369E0\n" // --------------------------------------------------------------------------- ".long loc_FFD36924\n" ".long loc_FFD36930\n" ".long loc_FFD36938\n" ".long loc_FFD36948\n" ".long loc_FFD36940\n" ".long loc_FFD36950\n" ".long loc_FFD36958\n" ".long loc_FFD36964\n" ".long loc_FFD3696C\n" ".long loc_FFD36978\n" ".long loc_FFD36980\n" ".long loc_FFD36988\n" ".long loc_FFD36990\n" ".long loc_FFD36998\n" ".long loc_FFD369A0\n" ".long loc_FFD369AC\n" ".long loc_FFD369B4\n" ".long loc_FFD369BC\n" ".long loc_FFD369C4\n" ".long loc_FFD369D0\n" ".long loc_FFD369D8\n" ".long loc_FFD369F0\n" // --------------------------------------------------------------------------- "loc_FFD36924:\n" "BL sub_FFD38088\n" "BL shooting_expo_param_override\n" // + "BL sub_FFD34560\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36930:\n" "BL sub_FFD364B0_my\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36938:\n" "BL sub_FFD3841C\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36940:\n" "BL sub_FFD37344\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36948:\n" "BL sub_FFD373A0\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36950:\n" "BL sub_FFD37590\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36958:\n" "BL sub_FFD3817C\n" "BL sub_FFD34560\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36964:\n" "BL sub_FFD36598\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD3696C:\n" "BL sub_FFD381E4\n" "BL sub_FFD34560\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36978:\n" "BL sub_FFD373A0\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36980:\n" "BL sub_FFD38AA8\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36988:\n" "BL sub_FFD38D30\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36990:\n" "BL sub_FFD38DBC\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD36998:\n" "BL sub_FFD38E74\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369A0:\n" "MOV R0, #0\n" "BL sub_FFD38F24\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369AC:" "BL sub_FFD39074\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369B4:\n" "BL sub_FFD390E8\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369BC:\n" "BL sub_FFD391A0\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369C4:\n" "MOV R0, #1\n" "BL sub_FFD38F24\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369D0:\n" "BL sub_FFD392A0\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369D8:\n" "BL sub_FFD392CC\n" "B loc_FFD369EC\n" // --------------------------------------------------------------------------- "loc_FFD369E0:\n" "LDR R0, =0xFFD36234\n" "MOV R1, #0x2DC\n" "BL sub_FFC03AD0\n" "loc_FFD369EC:\n" "LDR R2, [SP,#0xC-0xC]\n" "loc_FFD369F0:\n" "LDR R3, =0x73CBC\n" "LDR R1, [R2,#4]\n" "LDR R0, [R3]\n" "BL sub_FFC0F8C4\n" "LDR R0, [SP,#0xC-0xC]\n" "BL sub_FFD362B0\n" "loc_FFD36A08:\n" "LDR R3, =0x73CC0\n" "MOV R1, R4\n" "LDR R0, [R3]\n" "MOV R2, #0\n" "BL sub_FFC10074\n" "TST R0, #1\n" "BEQ loc_FFD368B4\n" "MOV R1, #0x24C\n" "LDR R0, =0xFFD36234\n" "ADD R1, R1, #1\n" "BL sub_FFC03AD0\n" "BL sub_FFC11610\n" "ADD SP, SP, #4\n" "LDMFD SP!, {R4,PC}\n" ); }
vi/chdk-vi
platform/a610/sub/100e/capt_seq.c
C
gpl-2.0
8,935
/* This file is part of Warzone 2100. Copyright (C) 1999-2004 Eidos Interactive Copyright (C) 2005-2015 Warzone 2100 Project Warzone 2100 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Warzone 2100 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 General Public License for more details. You should have received a copy of the GNU General Public License along with Warzone 2100; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _netlog_h #define _netlog_h #include "lib/framework/frame.h" #include "netplay.h" bool NETstartLogging(); bool NETstopLogging(); WZ_DECL_NONNULL(1) bool NETlogEntry(const char *str, UDWORD a, UDWORD b); void NETlogPacket(uint8_t type, uint32_t size, bool received); #endif // _netlog_h
djeof-1/warzone2100
lib/netplay/netlog.h
C
gpl-2.0
1,117
import Base import VS import GUI import XGUITypes import XGUIDebug XGUIRootSingleton = None XGUIPythonScriptAPISingleton = None """----------------------------------------------------------------""" """ """ """ XGUIRoot - root management interface for the XML-GUI framework.""" """ """ """----------------------------------------------------------------""" class XGUIRoot: def __init__(self): self.templates = {} def getTemplate(self,type,name): if type in self.templates and name in self.templates[type]: return self.templates[type][name] else: return None def addTemplate(self,tpl): type = tpl.getType() name = tpl.getName() if not type in self.templates: XGUIDebug.trace(1,"XGUI: Initializing template category \"" + str(type) + "\"\n") self.templates[type] = {} XGUIDebug.trace(2,"XGUI: Loading template \"" + str(name) + "\" into category \"" + str(type) + "\"\n") self.templates[type][name] = tpl class XGUIPythonScript: def __init__(self,code,filename): code = code.replace("\r\n","\n") code += "\n" self.code = compile(code,filename,'exec') def execute(self,context): exec(self.code, context) return context """----------------------------------------------------------------""" """ """ """ XGUIPythonScriptAPI - through this class, all PythonScript """ """ API calls are routed. """ """ """ """----------------------------------------------------------------""" class XGUIPythonScriptAPI: def __init__(self,layout,room): self.layout = layout self.room = room """----------------------------------------------------------------""" """ """ """ XGUI global initialization """ """ """ """----------------------------------------------------------------""" def XGUIInit(): XGUIRootSingleton = XGUIRoot()
vegastrike/Assets-Production
modules/XGUI.py
Python
gpl-2.0
2,379
/* * voicecalldlg.cpp * Copyright (C) 2006 Remko Troncon * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "voicecalldlg.h" #include "voicecaller.h" #include <QLabel> #include <QPushButton> VoiceCallDlg::VoiceCallDlg(const Jid &jid, VoiceCaller *voiceCaller) : QDialog(nullptr), jid_(jid), voiceCaller_(voiceCaller) { setAttribute(Qt::WA_DeleteOnClose); ui_.setupUi(this); setModal(false); setWindowTitle(QString(tr("Voice Call (%1)")).arg(jid.full())); // Voice Caller signals connect(voiceCaller_, SIGNAL(accepted(const Jid &)), SLOT(accepted(const Jid &))); connect(voiceCaller_, SIGNAL(rejected(const Jid &)), SLOT(rejected(const Jid &))); connect(voiceCaller_, SIGNAL(in_progress(const Jid &)), SLOT(in_progress(const Jid &))); connect(voiceCaller_, SIGNAL(terminated(const Jid &)), SLOT(terminated(const Jid &))); // Buttons ui_.pb_hangup->setEnabled(false); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); connect(ui_.pb_hangup, SIGNAL(clicked()), SLOT(terminate_call())); connect(ui_.pb_accept, SIGNAL(clicked()), SLOT(accept_call())); connect(ui_.pb_reject, SIGNAL(clicked()), SLOT(reject_call())); } void VoiceCallDlg::call() { setStatus(CallStatus::Calling); voiceCaller_->call(jid_); } void VoiceCallDlg::accept_call() { setStatus(CallStatus::Accepting); voiceCaller_->accept(jid_); } void VoiceCallDlg::reject_call() { setStatus(CallStatus::Rejecting); voiceCaller_->reject(jid_); finalize(); close(); } void VoiceCallDlg::terminate_call() { setStatus(CallStatus::Terminating); voiceCaller_->terminate(jid_); finalize(); close(); } void VoiceCallDlg::accepted(const Jid &j) { if (jid_.compare(j)) { setStatus(CallStatus::Accepted); } } void VoiceCallDlg::rejected(const Jid &j) { if (jid_.compare(j)) { setStatus(CallStatus::Rejected); finalize(); } } void VoiceCallDlg::in_progress(const Jid &j) { if (jid_.compare(j)) { setStatus(CallStatus::InProgress); } } void VoiceCallDlg::terminated(const Jid &j) { if (jid_.compare(j)) { setStatus(CallStatus::Terminated); finalize(); } } void VoiceCallDlg::incoming() { setStatus(CallStatus::Incoming); } void VoiceCallDlg::setStatus(CallStatus s) { status_ = s; switch (s) { case CallStatus::Calling: ui_.lb_status->setText(tr("Calling")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(true); break; case CallStatus::Accepting: ui_.lb_status->setText(tr("Accepting")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(true); break; case CallStatus::Rejecting: ui_.lb_status->setText(tr("Rejecting")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(false); break; case CallStatus::Terminating: ui_.lb_status->setText(tr("Hanging up")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(false); break; case CallStatus::Accepted: ui_.lb_status->setText(tr("Accepted")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(true); break; case CallStatus::Rejected: ui_.lb_status->setText(tr("Rejected")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(false); break; case CallStatus::InProgress: ui_.lb_status->setText(tr("In progress")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(true); break; case CallStatus::Terminated: ui_.lb_status->setText(tr("Terminated")); ui_.pb_accept->setEnabled(false); ui_.pb_reject->setEnabled(false); ui_.pb_hangup->setEnabled(false); break; case CallStatus::Incoming: ui_.lb_status->setText(tr("Incoming Call")); ui_.pb_accept->setEnabled(true); ui_.pb_reject->setEnabled(true); ui_.pb_hangup->setEnabled(false); break; default: break; } } void VoiceCallDlg::reject() { finalize(); QDialog::reject(); } void VoiceCallDlg::finalize() { // Close connection if (status_ == CallStatus::Incoming) { reject_call(); } else if (status_ == CallStatus::InProgress || status_ == CallStatus::Calling || status_ == CallStatus::Accepting || status_ == CallStatus::Accepted) { terminate_call(); } // Disconnect signals disconnect(voiceCaller_, SIGNAL(accepted(const Jid &)), this, SLOT(accepted(const Jid &))); disconnect(voiceCaller_, SIGNAL(rejected(const Jid &)), this, SLOT(rejected(const Jid &))); disconnect(voiceCaller_, SIGNAL(in_progress(const Jid &)), this, SLOT(in_progress(const Jid &))); disconnect(voiceCaller_, SIGNAL(terminated(const Jid &)), this, SLOT(terminated(const Jid &))); }
drizt/psi
src/voicecalldlg.cpp
C++
gpl-2.0
5,855
<?php /** * This is the model class for table "customer_group". * * The followings are the available columns in table 'customer_group': * @property integer $customer_group_id * @property integer $approval * @property integer $company_id_display * @property integer $company_id_required * @property integer $tax_id_display * @property integer $tax_id_required * @property integer $sort_order */ class CustomerGroup extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return CustomerGroup the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'customer_group'; } /** * @return array validation rules for model attributes. */ public function rules() { return array( array('approval, company_id_display, company_id_required, tax_id_display, tax_id_required, sort_order', 'required'), array('approval, company_id_display, company_id_required, tax_id_display, tax_id_required, sort_order', 'numerical', 'integerOnly' => true), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('customer_group_id, approval, company_id_display, company_id_required, tax_id_display, tax_id_required, sort_order', 'safe', 'on' => 'search'), ); } /** * @return array relational rules. */ public function relations() { return array( // TODO: add locale 'description'=> array(self::HAS_ONE, 'CustomerGroupDescription', 'customer_group_id', 'condition'=>'language_id=1'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'customer_group_id' => 'Customer Group', 'approval' => 'Approval', 'company_id_display' => 'Company Id Display', 'company_id_required' => 'Company Id Required', 'tax_id_display' => 'Tax Id Display', 'tax_id_required' => 'Tax Id Required', 'sort_order' => 'Sort Order', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria = new CDbCriteria; $criteria->compare('customer_group_id', $this->customer_group_id); $criteria->compare('approval', $this->approval); $criteria->compare('company_id_display', $this->company_id_display); $criteria->compare('company_id_required', $this->company_id_required); $criteria->compare('tax_id_display', $this->tax_id_display); $criteria->compare('tax_id_required', $this->tax_id_required); $criteria->compare('sort_order', $this->sort_order); return new CActiveDataProvider($this, array( 'criteria' => $criteria, )); } }
lvduit/DYiiShop
protected/models/CustomerGroup.php
PHP
gpl-2.0
3,436
#pragma once #include "stdafx.h" #include "GLHelpers.h" #include "../Common/TextGlyphs.h" namespace gl { class text_writer { private: gl::glsl::program m_program; gl::glsl::shader m_vs; gl::glsl::shader m_fs; gl::vao m_vao; gl::buffer m_text_buffer; gl::buffer m_scale_offsets_buffer; std::unordered_map<u8, std::pair<u32, u32>> m_offsets; bool initialized = false; bool enabled = false; void init_program() { std::string vs = { "#version 420\n" "#extension GL_ARB_shader_draw_parameters: enable\n" "layout(location=0) in vec2 pos;\n" "uniform vec2 offsets[255];\n" "uniform vec2 scale;\n" "\n" "void main()\n" "{\n" " vec2 offset = offsets[gl_DrawIDARB];\n" " gl_Position = vec4(pos, 0., 1.);\n" " gl_Position.xy = gl_Position.xy * scale + offset;\n" "}\n" }; std::string fs = { "#version 420\n" "layout(location=0) out vec4 col0;\n" "uniform vec4 draw_color;\n" "\n" "void main()\n" "{\n" " col0 = draw_color;\n" "}\n" }; m_fs.create(gl::glsl::shader::type::fragment); m_fs.source(fs); m_fs.compile(); m_vs.create(gl::glsl::shader::type::vertex); m_vs.source(vs); m_vs.compile(); m_program.create(); m_program.attach(m_vs); m_program.attach(m_fs); m_program.make(); } void load_program(float scale_x, float scale_y, float *offsets, int nb_offsets, color4f color) { float scale[] = { scale_x, scale_y }; m_program.use(); m_program.uniforms["draw_color"] = color; glProgramUniform2fv(m_program.id(), m_program.uniforms["offsets"].location(), nb_offsets, offsets); glProgramUniform2fv(m_program.id(), m_program.uniforms["scale"].location(), 1, scale); } public: text_writer() {} ~text_writer(){} void init() { //Check for ARB_shader_draw_parameters //While it is possible to draw text without full multidraw support, issuing separate draw calls per character is not effecient int ext_count; glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count); for (int i = 0; i < ext_count; i++) { const char *ext = (const char*)glGetStringi(GL_EXTENSIONS, i); if (std::string(ext) == "GL_ARB_shader_draw_parameters") { enabled = true; break; } } if (!enabled) { LOG_ERROR(RSX, "Debug overlay could not start because ARB_shader_draw_parameters is not supported by your GPU"); return; } m_text_buffer.create(); m_scale_offsets_buffer.create(); GlyphManager glyph_source; auto points = glyph_source.generate_point_map(); const u32 buffer_size = points.size() * sizeof(GlyphManager::glyph_point); m_text_buffer.data(buffer_size, points.data()); m_offsets = glyph_source.get_glyph_offsets(); m_scale_offsets_buffer.data(512 * 4 * sizeof(float)); //Init VAO int old_vao; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &old_vao); m_vao.create(); m_vao.bind(); //This is saved as part of the bound VAO's state m_vao.array_buffer = m_text_buffer; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(GlyphManager::glyph_point), 0); glBindVertexArray(old_vao); init_program(); initialized = true; } void print_text(int x, int y, int target_w, int target_h, const std::string &text, color4f color = { 0.3f, 1.f, 0.3f, 1.f }) { if (!enabled) return; verify(HERE), initialized; std::vector<GLint> offsets; std::vector<GLsizei> counts; std::vector<float> shader_offsets; char *s = const_cast<char *>(text.c_str()); //Y is in raster coordinates: convert to bottom-left origin y = (target_h - y - 16); //Compress [0, w] and [0, h] into range [-1, 1] float scale_x = 2.f / target_w; float scale_y = 2.f / target_h; float base_offset = 0.f; shader_offsets.reserve(text.length() * 2); while (*s) { u8 offset = (u8)*s; bool to_draw = false; //Can be false for space or unsupported characters auto o = m_offsets.find(offset); if (o != m_offsets.end()) { if (o->second.second > 0) { to_draw = true; offsets.push_back(o->second.first); counts.push_back(o->second.second); } } if (to_draw) { //Generate a scale_offset pair for this entry float offset_x = scale_x * (x + base_offset); offset_x -= 1.f; float offset_y = scale_y * y; offset_y -= 1.f; shader_offsets.push_back(offset_x); shader_offsets.push_back(offset_y); } base_offset += 9.f; s++; } //TODO: Add drop shadow if deemed necessary for visibility int old_vao; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &old_vao); load_program(scale_x, scale_y, shader_offsets.data(), counts.size(), color); m_vao.bind(); glMultiDrawArrays(GL_POINTS, offsets.data(), counts.data(), counts.size()); glBindVertexArray(old_vao); } void close() { if (initialized) { m_scale_offsets_buffer.remove(); m_text_buffer.remove(); m_vao.remove(); m_program.remove(); m_fs.remove(); m_vs.remove(); initialized = false; } } }; }
al0xf/rpcs3
rpcs3/Emu/RSX/GL/GLTextOut.h
C
gpl-2.0
5,346