code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
# Simblocline DC. GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Simblocline/README.md | Markdown | apache-2.0 | 163 |
/* Source code for textbook:
Flexible Reliable Software, by Henrik B. Christensen
CRC Press 2010
***********************************
Project developped in java by Henrik B. Christensen
C++ port by Robert Benkoczi
***********************************
*/
#ifndef __ILLEGALCOINEXCEPTION_H
#define __ILLEGALCOINEXCEPTION_H
#include <exception>
#include <string>
/** Exception representing illegal coin entry.
*/
class IllegalCoinException : public std::exception {
public:
/**
* @param e is a description of the exception
*/
IllegalCoinException( std::string e ) {};
};
#endif
| roben777/payst-cc | include/IllegalCoinException.h | C | apache-2.0 | 591 |
# Security Templates for AWS CloudFormation
Find the documentation here: http://templates.cloudonaut.io/en/stable/security/
## Developer notes
### RegionMap
To update the region map execute the following lines in your terminal:
```
$ regions=$(aws ec2 describe-regions --query "Regions[].RegionName" --output text)
$ for region in $regions; do ami=$(aws --region $region ec2 describe-images --filters "Name=name,Values=amzn-ami-hvm-2017.03.1.20170623-x86_64-gp2" --query "Images[0].ImageId" --output "text"); printf "'$region':\n AMI: '$ami'\n"; done
```
## Premium Support
We offer Premium Support for our CloudFormation templates: setting up environments based on our templates, adopting templates to specific use cases, resolving issues in production environments. [Hire us!](https://widdix.net/)
## About
A [cloudonaut.io](https://cloudonaut.io/templates-for-aws-cloudformation/) project. Engineered by [widdix](https://widdix.net).
| cmr1/aws-cf-templates-1 | security/README.md | Markdown | apache-2.0 | 944 |
<!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 (1.8.0_151) on Sat Mar 16 04:11:58 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.messaging (BOM: * : All 2.3.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2019-03-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.wildfly.swarm.messaging (BOM: * : All 2.3.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.wildfly.swarm.messaging" class="title">Uses of Package<br>org.wildfly.swarm.messaging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.messaging">org.wildfly.swarm.messaging</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.messaging">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a> used by <a href="../../../../org/wildfly/swarm/messaging/package-summary.html">org.wildfly.swarm.messaging</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServer.html#org.wildfly.swarm.messaging">EnhancedServer</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/EnhancedServerConsumer.html#org.wildfly.swarm.messaging">EnhancedServerConsumer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingFraction.html#org.wildfly.swarm.messaging">MessagingFraction</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/MessagingServer.html#org.wildfly.swarm.messaging">MessagingServer</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.html#org.wildfly.swarm.messaging">RemoteConnection</a>
<div class="block">Details for a remote message-queue connection.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Consumer.html#org.wildfly.swarm.messaging">RemoteConnection.Consumer</a>
<div class="block">Configuration functional interface for container-supplied objects.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../org/wildfly/swarm/messaging/class-use/RemoteConnection.Supplier.html#org.wildfly.swarm.messaging">RemoteConnection.Supplier</a>
<div class="block">Supplier functional interface for user-supplied object.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.3.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/wildfly/swarm/messaging/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2.3.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/messaging/package-use.html | HTML | apache-2.0 | 7,266 |
<!DOCTYPE HTML>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta charset="utf-8">
<base href="../../../../../../">
<script src="resources/sap/ui/test/starter/runTest.js"
data-sap-ui-testsuite="test-resources/sap/ui/mdc/qunit/field/testsuite.field.qunit"
data-sap-ui-test="FieldValueHelpUITableWrapper"></script>
</head>
<body>
<div id="qunit"></div>
<div id="content"></div>
</body>
</html>
| SAP/openui5 | src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/FieldValueHelpUITableWrapper.qunit.html | HTML | apache-2.0 | 457 |
package org.jboss.resteasy.test;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.util.PortProvider;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import javax.ws.rs.client.ClientBuilder;
/**
* Test utility class
*
* @author <a href="[email protected]">Justin Edelson</a>
* @version $Revision$
*/
public class TestPortProvider
{
/**
* Creates a ResteasyWebTarget using base request path.
*/
public static ResteasyWebTarget createTarget(String path)
{
return (ResteasyWebTarget) ClientBuilder.newClient().target(generateURL(path));
}
/**
* Create a Resteasy client proxy with an empty base request path.
*
* @param clazz the client interface class
* @return the proxy object
*/
public static <T> T createProxy(Class<T> clazz)
{
return createProxy(clazz, generateBaseUrl());
}
/**
* Create a Resteasy client proxy.
*
* @param clazz the client interface class
* @return the proxy object
* @path the base request path
*/
public static <T> T createProxy(Class<T> clazz, String url)
{
ResteasyWebTarget target = (ResteasyWebTarget) ResteasyClientBuilder.newClient().target(url);
return target.proxy(clazz);
}
/**
* Create a URI for the provided path, using the configured port
*
* @param path the request path
* @return a full URI
*/
public static URI createURI(String path)
{
return URI.create(generateURL(path));
}
/**
* Create a URL for the provided path, using the configured port
*
* @param path the request path
* @return a full URL
*/
public static URL createURL(String path) throws MalformedURLException
{
return new URL(generateURL(path));
}
/**
* Generate a base URL incorporating the configured port.
*
* @return a full URL
*/
public static String generateBaseUrl()
{
return generateURL("");
}
/**
* Generate a URL incorporating the configured port.
*
* @param path the path
* @return a full URL
*/
public static String generateURL(String path)
{
return String.format("http://%s:%d%s", getHost(), getPort(), path);
}
/**
* Look up the configured port number, first checking an environment variable (RESTEASY_PORT),
* then a system property (org.jboss.resteasy.port), and finally the default port (8081).
*
* @return the port number specified in either the environment or system properties
*/
public static int getPort()
{
return PortProvider.getPort();
}
/**
* Look up the configured hostname, first checking an environment variable (RESTEASY_HOST),
* then a system property (org.jboss.resteasy.host), and finally the default hostname (localhost).
*
* @return the host specified in either the environment or system properties
*/
public static String getHost()
{
return PortProvider.getHost();
}
}
| awhitford/Resteasy | resteasy-client/src/main/java/org/jboss/resteasy/test/TestPortProvider.java | Java | apache-2.0 | 3,100 |
<!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 (1.8.0_111) on Wed Jan 04 22:31:13 EST 2017 -->
<title>FritzJohnMultipliers</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="FritzJohnMultipliers";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":9,"i4":10,"i5":10,"i6":10,"i7":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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="class-use/FritzJohnMultipliers.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>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/drip/optimization/constrained/NecessarySufficientConditions.html" title="class in org.drip.optimization.constrained"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/optimization/constrained/FritzJohnMultipliers.html" target="_top">Frames</a></li>
<li><a href="FritzJohnMultipliers.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: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </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">org.drip.optimization.constrained</div>
<h2 title="Class FritzJohnMultipliers" class="title">Class FritzJohnMultipliers</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.drip.optimization.constrained.FritzJohnMultipliers</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">FritzJohnMultipliers</span>
extends java.lang.Object</pre>
<div class="block">FritzJohnMultipliers holds the Array of the Fritz John/KKT Multipliers for the Array of the Equality and
the Inequality Constraints, one per each Constraint. The References are:
- Boyd, S., and L. van den Berghe (2009): Convex Optimization, Cambridge University Press, Cambridge UK.
- Eustaquio, R., E. Karas, and A. Ribeiro (2008): Constraint Qualification for Nonlinear Programming,
Technical Report, Federal University of Parana.
- Karush, A. (1939): Minima of Functions of Several Variables with Inequalities as Side Constraints,
M. Sc., University of Chicago, Chicago IL.
- Kuhn, H. W., and A. W. Tucker (1951): Nonlinear Programming, Proceedings of the Second Berkeley
Symposium, University of California, Berkeley CA 481-492.
- Ruszczynski, A. (2006): Nonlinear Optimization, Princeton University Press, Princeton NJ.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Lakshmi Krishnamurthy</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#FritzJohnMultipliers-double-double:A-double:A-">FritzJohnMultipliers</a></span>(double dblObjectiveCoefficient,
double[] adblEquality,
double[] adblInequality)</code>
<div class="block">FritzJohnMultipliers Constructor</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="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#dualFeasibilityCheck--">dualFeasibilityCheck</a></span>()</code>
<div class="block">Indicate of the Multipliers constitute Valid Dual Feasibility</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>double[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#equalityConstraintCoefficient--">equalityConstraintCoefficient</a></span>()</code>
<div class="block">Retrieve the Array of the Equality Constraint Coefficients</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>double[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#inequalityConstraintCoefficient--">inequalityConstraintCoefficient</a></span>()</code>
<div class="block">Retrieve the Array of the Inequality Constraint Coefficients</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html" title="class in org.drip.optimization.constrained">FritzJohnMultipliers</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#KarushKuhnTucker-double:A-double:A-">KarushKuhnTucker</a></span>(double[] adblEquality,
double[] adblInequality)</code>
<div class="block">Construct a Standard KarushKuhnTucker (KKT) Instance of the Fritz John Multipliers</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numEqualityCoefficients--">numEqualityCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Equality Multiplier Coefficients</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numInequalityCoefficients--">numInequalityCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Inequality Multiplier Coefficients</div>
</td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#numTotalCoefficients--">numTotalCoefficients</a></span>()</code>
<div class="block">Retrieve the Number of Total KKT Multiplier Coefficients</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>double</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html#objectiveCoefficient--">objectiveCoefficient</a></span>()</code>
<div class="block">Retrieve the Fritz John Objective Function Multiplier</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 java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="FritzJohnMultipliers-double-double:A-double:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>FritzJohnMultipliers</h4>
<pre>public FritzJohnMultipliers(double dblObjectiveCoefficient,
double[] adblEquality,
double[] adblInequality)
throws java.lang.Exception</pre>
<div class="block">FritzJohnMultipliers Constructor</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>dblObjectiveCoefficient</code> - The Objective Function Coefficient</dd>
<dd><code>adblEquality</code> - Array of the Equality Constraint Coefficients</dd>
<dd><code>adblInequality</code> - Array of the Inequality Constraint Coefficients</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code> - Thrown if the Inputs are Invalid</dd>
</dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="KarushKuhnTucker-double:A-double:A-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KarushKuhnTucker</h4>
<pre>public static final <a href="../../../../org/drip/optimization/constrained/FritzJohnMultipliers.html" title="class in org.drip.optimization.constrained">FritzJohnMultipliers</a> KarushKuhnTucker(double[] adblEquality,
double[] adblInequality)</pre>
<div class="block">Construct a Standard KarushKuhnTucker (KKT) Instance of the Fritz John Multipliers</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>adblEquality</code> - Array of the Equality Constraint Coefficients</dd>
<dd><code>adblInequality</code> - Array of the Inequality Constraint Coefficients</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The KKT Instance of Fritz John Multipliers</dd>
</dl>
</li>
</ul>
<a name="objectiveCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>objectiveCoefficient</h4>
<pre>public double objectiveCoefficient()</pre>
<div class="block">Retrieve the Fritz John Objective Function Multiplier</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Fritz John Objective Function Multiplier</dd>
</dl>
</li>
</ul>
<a name="equalityConstraintCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equalityConstraintCoefficient</h4>
<pre>public double[] equalityConstraintCoefficient()</pre>
<div class="block">Retrieve the Array of the Equality Constraint Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Array of the Equality Constraint Coefficients</dd>
</dl>
</li>
</ul>
<a name="inequalityConstraintCoefficient--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inequalityConstraintCoefficient</h4>
<pre>public double[] inequalityConstraintCoefficient()</pre>
<div class="block">Retrieve the Array of the Inequality Constraint Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Array of the Inequality Constraint Coefficients</dd>
</dl>
</li>
</ul>
<a name="numEqualityCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numEqualityCoefficients</h4>
<pre>public int numEqualityCoefficients()</pre>
<div class="block">Retrieve the Number of Equality Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Equality Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="numInequalityCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numInequalityCoefficients</h4>
<pre>public int numInequalityCoefficients()</pre>
<div class="block">Retrieve the Number of Inequality Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Inequality Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="numTotalCoefficients--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>numTotalCoefficients</h4>
<pre>public int numTotalCoefficients()</pre>
<div class="block">Retrieve the Number of Total KKT Multiplier Coefficients</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The Number of Total KKT Multiplier Coefficients</dd>
</dl>
</li>
</ul>
<a name="dualFeasibilityCheck--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>dualFeasibilityCheck</h4>
<pre>public boolean dualFeasibilityCheck()</pre>
<div class="block">Indicate of the Multipliers constitute Valid Dual Feasibility</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>TRUE - The Multipliers constitute Valid Dual Feasibility</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>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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="class-use/FritzJohnMultipliers.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>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../org/drip/optimization/constrained/NecessarySufficientConditions.html" title="class in org.drip.optimization.constrained"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/optimization/constrained/FritzJohnMultipliers.html" target="_top">Frames</a></li>
<li><a href="FritzJohnMultipliers.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: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| lakshmiDRIP/DRIP | Javadoc/org/drip/optimization/constrained/FritzJohnMultipliers.html | HTML | apache-2.0 | 17,937 |
# Ornithogalum transversale Pall. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Liliales/Liliaceae/Gagea/Gagea transversalis/ Syn. Ornithogalum transversale/README.md | Markdown | apache-2.0 | 188 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Syndication;
namespace DncShowcaseHub.DataModel
{
class FeedItemIterator
{
private SyndicationFeed feed;
private int index;
public FeedItemIterator()
{
this.feed = null;
this.index = 0;
}
public void AttachFeed(SyndicationFeed feed)
{
this.feed = feed;
this.index = 0;
}
public bool MoveNext()
{
if (feed != null && index < feed.Items.Count - 1)
{
index++;
return true;
}
return false;
}
public void MovePrevious()
{
if (feed != null && index > 0)
{
index--;
}
}
public bool HasElements()
{
return feed != null && feed.Items.Count > 0;
}
public string GetTitle()
{
// Nothing to return yet.
if (!HasElements())
{
return "(no title)";
}
if (feed.Items[index].Title != null)
{
return WebUtility.HtmlDecode(feed.Items[index].Title.Text);
}
return "(no title)";
}
public string GetContent()
{
// Nothing to return yet.
if (!HasElements())
{
return "(no value)";
}
if ((feed.Items[index].Content != null) && (feed.Items[index].Content.Text != null))
{
return feed.Items[index].Content.Text;
}
else if (feed.Items[index].Summary != null && !string.IsNullOrEmpty(feed.Items[index].Summary.Text))
{
return feed.Items[index].Summary.Text;
}
return "(no value)";
}
public string GetIndexDescription()
{
// Nothing to return yet.
if (!HasElements())
{
return "0 of 0";
}
return String.Format("{0} of {1}", index + 1, feed.Items.Count);
}
public Uri GetEditUri()
{
// Nothing to return yet.
if (!HasElements())
{
return null;
}
return feed.Items[index].EditUri;
}
public SyndicationItem GetSyndicationItem()
{
// Nothing to return yet.
if (!HasElements())
{
return null;
}
return feed.Items[index];
}
internal string GetAuthor()
{
if (feed.Items[index].Authors != null &&
feed.Items[index].Authors.Count > 0)
{
string authors = "";
foreach (var author in feed.Items[index].Authors)
{
authors += (author.NodeValue + ",");
}
return authors.TrimEnd(',');
}
return "";
}
internal string GetUrlPath()
{
if (feed.Items[index].Links != null &&
feed.Items[index].Links.Count > 0)
{
return feed.Items[index].Links[0].Uri.AbsoluteUri;
}
return "";
}
}
}
| dotnetcurry/winrt-81-hub-control | DncShowcaseHub/DncShowcaseHub/DataModel/FeedItemIterator.cs | C# | apache-2.0 | 3,497 |
<?php
namespace db2eav\Classes;
class Value extends ValueBase {
public function __construct(){
}
public function __destruct(){
}
} | arhouati/DB2EAV | src/db2eav/Classes/Value.php | PHP | apache-2.0 | 156 |
package com.xiaochen.progressroundbutton;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.animation.PathInterpolatorCompat;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* Created by tanfujun on 15/9/4.
*/
public class AnimDownloadProgressButton extends TextView {
private Context mContext;
//背景画笔
private Paint mBackgroundPaint;
//按钮文字画笔
private volatile Paint mTextPaint;
//第一个点画笔
private Paint mDot1Paint;
//第二个点画笔
private Paint mDot2Paint;
//背景颜色
private int[] mBackgroundColor;
private int[] mOriginBackgroundColor;
//下载中后半部分后面背景颜色
private int mBackgroundSecondColor;
//文字颜色
private int mTextColor;
//覆盖后颜色
private int mTextCoverColor;
//文字大小
private float mAboveTextSize = 50;
private float mProgress = -1;
private float mToProgress;
private int mMaxProgress;
private int mMinProgress;
private float mProgressPercent;
private float mButtonRadius;
//两个点向右移动距离
private float mDot1transX;
private float mDot2transX;
private RectF mBackgroundBounds;
private LinearGradient mFillBgGradient;
private LinearGradient mProgressBgGradient;
private LinearGradient mProgressTextGradient;
//点运动动画
private AnimatorSet mDotAnimationSet;
//下载平滑动画
private ValueAnimator mProgressAnimation;
//记录当前文字
private CharSequence mCurrentText;
//普通状态
public static final int NORMAL = 0;
//下载中
public static final int DOWNLOADING = 1;
//有点运动状态
public static final int INSTALLING = 2;
private ButtonController mDefaultController;
private ButtonController mCustomerController;
private int mState;
public AnimDownloadProgressButton(Context context) {
this(context, null);
}
public AnimDownloadProgressButton(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) {
mContext = context;
initController();
initAttrs(context, attrs);
init();
setupAnimations();
}else {
initController();
}
}
private void initController() {
mDefaultController = new DefaultButtonController();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
ButtonController buttonController = switchController();
if (buttonController.enablePress()) {
if (mOriginBackgroundColor == null) {
mOriginBackgroundColor = new int[2];
mOriginBackgroundColor[0] = mBackgroundColor[0];
mOriginBackgroundColor[1] = mBackgroundColor[1];
}
if (this.isPressed()) {
int pressColorleft = buttonController.getPressedColor(mBackgroundColor[0]);
int pressColorright = buttonController.getPressedColor(mBackgroundColor[1]);
if (buttonController.enableGradient()) {
initGradientColor(pressColorleft, pressColorright);
} else {
initGradientColor(pressColorleft, pressColorleft);
}
} else {
if (buttonController.enableGradient()) {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[1]);
} else {
initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[0]);
}
}
invalidate();
}
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimDownloadProgressButton);
int bgColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_color, Color.parseColor("#6699ff"));
//初始化背景颜色数组
initGradientColor(bgColor, bgColor);
mBackgroundSecondColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_second_color, Color.LTGRAY);
mButtonRadius = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_radius, getMeasuredHeight() / 2);
mAboveTextSize = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_text_size, 50);
mTextColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_color, bgColor);
mTextCoverColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_covercolor, Color.WHITE);
boolean enableGradient = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_gradient, false);
boolean enablePress = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_press, false);
((DefaultButtonController) mDefaultController).setEnableGradient(enableGradient).setEnablePress(enablePress);
if (enableGradient){
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
a.recycle();
}
private void init() {
mMaxProgress = 100;
mMinProgress = 0;
mProgress = 0;
//设置背景画笔
mBackgroundPaint = new Paint();
mBackgroundPaint.setAntiAlias(true);
mBackgroundPaint.setStyle(Paint.Style.FILL);
//设置文字画笔
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(mAboveTextSize);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//解决文字有时候画不出问题
setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint);
}
//设置第一个点画笔
mDot1Paint = new Paint();
mDot1Paint.setAntiAlias(true);
mDot1Paint.setTextSize(mAboveTextSize);
//设置第二个点画笔
mDot2Paint = new Paint();
mDot2Paint.setAntiAlias(true);
mDot2Paint.setTextSize(mAboveTextSize);
//初始化状态设为NORMAL
mState = NORMAL;
invalidate();
}
//初始化渐变色
private int[] initGradientColor(int leftColor, int rightColor) {
mBackgroundColor = new int[2];
mBackgroundColor[0] = leftColor;
mBackgroundColor[1] = rightColor;
return mBackgroundColor;
}
private void setupAnimations() {
//两个点向右移动动画
ValueAnimator dotMoveAnimation = ValueAnimator.ofFloat(0, 20);
TimeInterpolator pathInterpolator = PathInterpolatorCompat.create(0.11f, 0f, 0.12f, 1f);
dotMoveAnimation.setInterpolator(pathInterpolator);
dotMoveAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float transX = (float) animation.getAnimatedValue();
mDot1transX = transX;
mDot2transX = transX;
invalidate();
}
});
dotMoveAnimation.setDuration(1243);
dotMoveAnimation.setRepeatMode(ValueAnimator.RESTART);
dotMoveAnimation.setRepeatCount(ValueAnimator.INFINITE);
//两个点渐显渐隐动画
final ValueAnimator dotAlphaAnim = ValueAnimator.ofInt(0, 1243).setDuration(1243);
dotAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int time = (int) dotAlphaAnim.getAnimatedValue();
int dot1Alpha = calculateDot1AlphaByTime(time);
int dot2Alpha = calculateDot2AlphaByTime(time);
mDot1Paint.setColor(mTextCoverColor);
mDot2Paint.setColor(mTextCoverColor);
mDot1Paint.setAlpha(dot1Alpha);
mDot2Paint.setAlpha(dot2Alpha);
}
});
dotAlphaAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
mDot1Paint.setAlpha(0);
mDot2Paint.setAlpha(0);
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
dotAlphaAnim.setRepeatMode(ValueAnimator.RESTART);
dotAlphaAnim.setRepeatCount(ValueAnimator.INFINITE);
//两个点的动画集合
mDotAnimationSet = new AnimatorSet();
mDotAnimationSet.playTogether(dotAlphaAnim, dotMoveAnimation);
//ProgressBar的动画
mProgressAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500);
mProgressAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float timepercent = (float) animation.getAnimatedValue();
mProgress = ((mToProgress - mProgress) * timepercent + mProgress);
invalidate();
}
});
}
//第一个点透明度计算函数
private int calculateDot2AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 83) {
double DAlpha = 255.0 / 83.0 * time;
alpha = (int) DAlpha;
} else if (83 < time && time <= 1000) {
alpha = 255;
} else if (1000 < time && time <= 1083) {
double DAlpha = -255.0 / 83.0 * (time - 1083);
alpha = (int) DAlpha;
} else if (1083 < time && time <= 1243) {
alpha = 0;
} else {
alpha = 255;
}
return alpha;
}
//第二个点透明度计算函数
private int calculateDot1AlphaByTime(int time) {
int alpha;
if (0 <= time && time <= 160) {
alpha = 0;
} else if (160 < time && time <= 243) {
double DAlpha = 255.0 / 83.0 * (time - 160);
alpha = (int) DAlpha;
} else if (243 < time && time <= 1160) {
alpha = 255;
} else if (1160 < time && time <= 1243) {
double DAlpha = -255.0 / 83.0 * (time - 1243);
alpha = (int) DAlpha;
} else {
alpha = 255;
}
return alpha;
}
private ValueAnimator createDotAlphaAnimation(int i, Paint mDot1Paint, int i1, int i2, int i3) {
return new ValueAnimator();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isInEditMode()) {
drawing(canvas);
}
}
private void drawing(Canvas canvas) {
drawBackground(canvas);
drawTextAbove(canvas);
}
private void drawBackground(Canvas canvas) {
mBackgroundBounds = new RectF();
if (mButtonRadius == 0) {
mButtonRadius = getMeasuredHeight() / 2;
}
mBackgroundBounds.left = 2;
mBackgroundBounds.top = 2;
mBackgroundBounds.right = getMeasuredWidth() - 2;
mBackgroundBounds.bottom = getMeasuredHeight() - 2;
ButtonController buttonController = switchController();
//color
switch (mState) {
case NORMAL:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
if (mBackgroundPaint.getShader() != null) {
mBackgroundPaint.setShader(null);
}
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case DOWNLOADING:
if (buttonController.enableGradient()) {
mProgressPercent = mProgress / (mMaxProgress + 0f);
int[] colorList = new int[]{mBackgroundColor[0], mBackgroundColor[1], mBackgroundSecondColor};
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
colorList,
new float[]{0, mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setShader(mProgressBgGradient);
} else {
mProgressPercent = mProgress / (mMaxProgress + 0f);
mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0,
new int[]{mBackgroundColor[0], mBackgroundSecondColor},
new float[]{mProgressPercent, mProgressPercent + 0.001f},
Shader.TileMode.CLAMP
);
mBackgroundPaint.setColor(mBackgroundColor[0]);
mBackgroundPaint.setShader(mProgressBgGradient);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
case INSTALLING:
if (buttonController.enableGradient()) {
mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2,
mBackgroundColor,
null,
Shader.TileMode.CLAMP);
mBackgroundPaint.setShader(mFillBgGradient);
} else {
mBackgroundPaint.setShader(null);
mBackgroundPaint.setColor(mBackgroundColor[0]);
}
canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint);
break;
}
}
private void drawTextAbove(Canvas canvas) {
final float y = canvas.getHeight() / 2 - (mTextPaint.descent() / 2 + mTextPaint.ascent() / 2);
if (mCurrentText == null) {
mCurrentText = "";
}
final float textWidth = mTextPaint.measureText(mCurrentText.toString());
//color
switch (mState) {
case NORMAL:
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case DOWNLOADING:
//进度条压过距离
float coverlength = getMeasuredWidth() * mProgressPercent;
//开始渐变指示器
float indicator1 = getMeasuredWidth() / 2 - textWidth / 2;
//结束渐变指示器
float indicator2 = getMeasuredWidth() / 2 + textWidth / 2;
//文字变色部分的距离
float coverTextLength = textWidth / 2 - getMeasuredWidth() / 2 + coverlength;
float textProgress = coverTextLength / textWidth;
if (coverlength <= indicator1) {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextColor);
} else if (indicator1 < coverlength && coverlength <= indicator2) {
mProgressTextGradient = new LinearGradient((getMeasuredWidth() - textWidth) / 2, 0, (getMeasuredWidth() + textWidth) / 2, 0,
new int[]{mTextCoverColor, mTextColor},
new float[]{textProgress, textProgress + 0.001f},
Shader.TileMode.CLAMP);
mTextPaint.setColor(mTextColor);
mTextPaint.setShader(mProgressTextGradient);
} else {
mTextPaint.setShader(null);
mTextPaint.setColor(mTextCoverColor);
}
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
break;
case INSTALLING:
mTextPaint.setColor(mTextCoverColor);
canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 4 + mDot1transX, y, 4, mDot1Paint);
canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 24 + mDot2transX, y, 4, mDot2Paint);
break;
}
}
private ButtonController switchController() {
if (mCustomerController != null) {
return mCustomerController;
} else {
return mDefaultController;
}
}
public int getState() {
return mState;
}
public void setState(int state) {
if (mState != state) {//状态确实有改变
this.mState = state;
invalidate();
if (state == AnimDownloadProgressButton.INSTALLING) {
//开启两个点动画
mDotAnimationSet.start();
} else if (state == NORMAL) {
mDotAnimationSet.cancel();
} else if (state == DOWNLOADING) {
mDotAnimationSet.cancel();
}
}
}
/**
* 设置按钮文字
*/
public void setCurrentText(CharSequence charSequence) {
mCurrentText = charSequence;
invalidate();
}
/**
* 设置带下载进度的文字
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public void setProgressText(String text, float progress) {
if (progress >= mMinProgress && progress < mMaxProgress) {
mCurrentText = text + getResources().getString(R.string.downloaded, (int) progress);
mToProgress = progress;
if (mProgressAnimation.isRunning()) {
mProgressAnimation.start();
} else {
mProgressAnimation.start();
}
} else if (progress < mMinProgress) {
mProgress = 0;
} else if (progress >= mMaxProgress) {
mProgress = 100;
mCurrentText = text + getResources().getString(R.string.downloaded, (int) mProgress);
invalidate();
}
}
public float getProgress() {
return mProgress;
}
public void setProgress(float progress) {
this.mProgress = progress;
}
/**
* Sometimes you should use the method to avoid memory leak
*/
public void removeAllAnim() {
mDotAnimationSet.cancel();
mDotAnimationSet.removeAllListeners();
mProgressAnimation.cancel();
mProgressAnimation.removeAllListeners();
}
public void setProgressBtnBackgroundColor(int color){
initGradientColor(color, color);
}
public void setProgressBtnBackgroundSecondColor(int color){
mBackgroundSecondColor = color;
}
public float getButtonRadius() {
return mButtonRadius;
}
public void setButtonRadius(float buttonRadius) {
mButtonRadius = buttonRadius;
}
public int getTextColor() {
return mTextColor;
}
@Override
public void setTextColor(int textColor) {
mTextColor = textColor;
}
public int getTextCoverColor() {
return mTextCoverColor;
}
public void setTextCoverColor(int textCoverColor) {
mTextCoverColor = textCoverColor;
}
public int getMinProgress() {
return mMinProgress;
}
public void setMinProgress(int minProgress) {
mMinProgress = minProgress;
}
public int getMaxProgress() {
return mMaxProgress;
}
public void setMaxProgress(int maxProgress) {
mMaxProgress = maxProgress;
}
public void enabelDefaultPress(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnablePress(enable);
}
}
public void enabelDefaultGradient(boolean enable) {
if (mDefaultController != null) {
((DefaultButtonController) mDefaultController).setEnableGradient(enable);
initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]);
}
}
@Override
public void setTextSize(float size) {
mAboveTextSize = size;
mTextPaint.setTextSize(size);
}
@Override
public float getTextSize() {
return mAboveTextSize;
}
public AnimDownloadProgressButton setCustomerController(ButtonController customerController) {
mCustomerController = customerController;
return this;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mState = ss.state;
mProgress = ss.progress;
mCurrentText = ss.currentText;
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
return new SavedState(superState, (int) mProgress, mState, mCurrentText.toString());
}
public static class SavedState extends BaseSavedState {
private int progress;
private int state;
private String currentText;
public SavedState(Parcelable parcel, int progress, int state, String currentText) {
super(parcel);
this.progress = progress;
this.state = state;
this.currentText = currentText;
}
private SavedState(Parcel in) {
super(in);
progress = in.readInt();
state = in.readInt();
currentText = in.readString();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(progress);
out.writeInt(state);
out.writeString(currentText);
}
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| Ernest-su/ProgressRoundButton | library/src/main/java/com/xiaochen/progressroundbutton/AnimDownloadProgressButton.java | Java | apache-2.0 | 23,449 |
Getting started with the i3 window manager on Linux
======

In my article [5 reasons the i3 window manager makes Linux better][1], I shared the top five reasons I use and recommend the [i3 window manager][2] as an alternative Linux desktop experience.
In this post, I will walk through the installation and basic configuration of i3 on Fedora 28 Linux.
### 1\. Installation
Log into a Fedora workstation and open up a terminal. Use `dnf` to install the required package, like this:
```
[ricardo@f28i3 ~]$ sudo dnf install -y i3 i3-ipc i3status i3lock dmenu terminator --exclude=rxvt-unicode
Last metadata expiration check: 1:36:15 ago on Wed 08 Aug 2018 12:04:31 PM EDT.
Dependencies resolved.
================================================================================================
Package Arch Version Repository Size
================================================================================================
Installing:
dmenu x86_64 4.8-1.fc28 fedora 33 k
i3 x86_64 4.15-1.fc28 fedora 323 k
i3-ipc noarch 0.1.4-12.fc28 fedora 14 k
i3lock x86_64 2.9.1-2.fc28 fedora 33 k
i3status x86_64 2.12-1.fc28 updates 62 k
terminator noarch 1.91-4.fc28 fedora 570 k
Installing dependencies:
dzen2 x86_64 0.8.5-21.20100104svn.fc28 fedora 60 k
... Skipping dependencies/install messages
Complete!
[ricardo@f28i3 ~]$
```
**Note:** In this command, I'm explicitly excluding the package `rxvt-unicode` because I prefer `terminator` as my terminal emulator.
Depending on the status of your system, it may install many dependencies. Wait for the installation to complete successfully and then reboot your machine.
### 2. First login and initial setup
After your machine restarts, you're ready to log into i3 for the first time. In the GNOME Display Manager (GDM) screen, click on your username but—before typing the password to log in—click on the small gear icon and change the session to i3 instead of GNOME, like this:

Type your password and click `Sign In`. On your first login, you are presented with the i3 configuration screen:

Press `ENTER` to generate a config file in your `$HOME/.config/i3` directory. Later you can use this config file to further customize i3's behavior.
On the next screen, you need to select your `Mod` key. This is important, as the `Mod` key is used to trigger most of i3's keyboard shortcuts. Press `ENTER` to use the default `Win` key as the `Mod` key. If you don't have a `Win` key on your keyboard or prefer to use `Alt` instead, use the arrow key to select it and press `ENTER` to confirm.

You're now logged into your i3 session. Because i3 is a minimalist window manager, you see a black screen with the status bar on the bottom:

Next, let's look at navigating in i3.
### 3\. Basic shortcuts
Now that you're logged into an i3 session, you'll need a few basic keyboard shortcuts to get around.
The majority of i3 shortcuts use the `Mod` key you defined during the initial configuration. When I refer to `Mod` in the following examples, press the key you defined. This will usually be the `Win` key, but it can also be the `Alt` key.
First, to open up a terminal, use `Mod+ENTER`. Open more than one terminal and notice how i3 automatically tiles them to occupy all available space. By default, i3 splits the screen horizontally; use `Mod+v` to split vertically and press `Mod+h` to go back to the horizontal split.

To start other applications, press `Mod+d` to open `dmenu`, a simple text-based application menu. By default, `dmenu` presents a list of all applications available on your `$PATH`. Select the application you want to start by using the arrow keys or narrow down the search by typing parts of the application's name. Press `ENTER` to start the selected application.

If your application does not provide a way to close it, you can use i3 to kill a window by pressing `Mod+Shift+q`. Be careful, as you may lose unsaved work—this behavior depends on each application.
Finally, to end your session and exit i3, press `Mod+Shift+e`. You are presented with a confirmation message at the top of your screen. Click on `Yes, exit i3` to exit or `X` to cancel.

This is just an initial list of shortcuts you can use to get around i3. For many more, consult i3's official [documentation][3].
### 4\. Replacing GDM
Using i3 window manager reduces the memory utilization on your system; however, Fedora still uses the default GDM as its login screen. GDM loads several GNOME-related libraries and applications that consume memory.
If you want to further reduce your system's memory utilization, you can replace GDM with a more lightweight display manager, such as `lightdm`, like this:
```
[ricardo@f28i3 ~]$ sudo dnf install -y lightdm
[ricardo@f28i3 ~]$ sudo systemctl disable gdm
Removed /etc/systemd/system/display-manager.service.
[ricardo@f28i3 ~]$ sudo systemctl enable lightdm
Created symlink /etc/systemd/system/display-manager.service -> /usr/lib/systemd/system/lightdm.service.
[ricardo@f28i3 ~]$
```
Restart your machine to see the Lightdm login screen.
Now you're ready to log in and use i3.

--------------------------------------------------------------------------------
via: https://opensource.com/article/18/8/getting-started-i3-window-manager
作者:[Ricardo Gerardi][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/rgerardi
[1]: https://opensource.com/article/18/8/i3-tiling-window-manager
[2]: https://i3wm.org
[3]: https://i3wm.org/docs/userguide.html#_default_keybindings
| icecoobe/TranslateProject | sources/tech/20180929 Getting started with the i3 window manager on Linux.md | Markdown | apache-2.0 | 7,191 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2020 the original author or authors.
*/
package org.assertj.core.api.long_;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual;
import org.assertj.core.api.LongAssert;
import org.assertj.core.api.LongAssertBaseTest;
import org.assertj.core.internal.Longs;
import org.assertj.core.internal.Objects;
import org.junit.jupiter.api.DisplayName;
/**
* Tests for <code>{@link LongAssert#usingDefaultComparator()}</code>.
*
* @author Joel Costigliola
*/
@DisplayName("LongAssert usingDefaultComparator")
class LongAssert_usingDefaultComparator_Test extends LongAssertBaseTest {
@Override
protected LongAssert invoke_api_method() {
return assertions.usingComparator(alwaysEqual()).usingDefaultComparator();
}
@Override
protected void verify_internal_effects() {
assertThat(getObjects(assertions)).isSameAs(Objects.instance());
assertThat(getLongs(assertions)).isSameAs(Longs.instance());
}
}
| joel-costigliola/assertj-core | src/test/java/org/assertj/core/api/long_/LongAssert_usingDefaultComparator_Test.java | Java | apache-2.0 | 1,561 |
######################################################################
# tc_divmod.rb
#
# Test case for the Bignum#divmod instance method.
######################################################################
require 'test/unit'
class TC_Bignum_Divmod_InstanceMethod < Test::Unit::TestCase
def setup
@num_int = 9223372036854775808
@den_int = 8589934593
@num_flt = 9223372036854775808.0
@den_flt = 8589934593.0
end
def test_divmod_basic
assert_respond_to(@num_int, :divmod)
assert_nothing_raised{ @num_int.divmod(@den_int) }
assert_kind_of(Array, @num_int.divmod(@den_int))
end
def test_divmod_integers
assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_int))
assert_equal([0, 8589934593], @den_int.divmod(@num_int))
end
def test_divmod_integer_and_float
assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_int))
assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_flt))
end
def test_divmod_floats
assert_equal([1073741823, 7516192769.0], @num_flt.divmod(@den_flt))
assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_flt))
end
def test_divmod_expected_errors
assert_raises(ArgumentError){ @num_int.divmod }
assert_raises(ZeroDivisionError){ @num_int.divmod(0) }
assert_raises(TypeError){ @num_int.divmod(nil) }
assert_raises(TypeError){ @num_int.divmod('test') }
assert_raises(TypeError){ @num_int.divmod(true) }
end
def teardown
@num_int = nil
@den_int = nil
@num_flt = nil
@den_flt = nil
end
end
| google-code/android-scripting | jruby/src/test/externals/ruby_test/test/core/Bignum/instance/tc_divmod.rb | Ruby | apache-2.0 | 1,607 |
/*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.testing.sanity;
import static com.evolveum.midpoint.prism.util.PrismAsserts.assertEqualsPolyString;
import static com.evolveum.midpoint.prism.util.PrismAsserts.assertParentConsistency;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache;
import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty;
import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb;
import static com.evolveum.midpoint.test.IntegrationTestTools.getAttributeValues;
import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.path.ItemName;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.xnode.MapXNode;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.util.exception.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.opends.server.core.ModifyOperation;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.types.*;
import org.opends.server.types.ModificationType;
import org.opends.server.util.ChangeRecordEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.CapabilityUtil;
import com.evolveum.midpoint.schema.DeltaConvertor;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition;
import com.evolveum.midpoint.schema.processor.ResourceSchema;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.ObjectQueryUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.SchemaTestConstants;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskExecutionStatus;
import com.evolveum.midpoint.test.Checker;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.test.ObjectChecker;
import com.evolveum.midpoint.test.ldap.OpenDJController;
import com.evolveum.midpoint.test.util.DerbyController;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType;
import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectShadowChangeDescriptionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectTypeDefinitionType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SchemaHandlingType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SelectorQualifiedGetOptionsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultType;
import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectAlreadyExistsFaultType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType;
import com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType;
import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType;
import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
/**
* Sanity test suite.
* <p/>
* It tests the very basic representative test cases. It does not try to be
* complete. It rather should be quick to execute and pass through the most
* representative cases. It should test all the system components except for
* GUI. Therefore the test cases are selected to pass through most of the
* components.
* <p/>
* It is using embedded H2 repository and embedded OpenDJ instance as a testing
* resource. The repository is instantiated from the Spring context in the
* same way as all other components. OpenDJ instance is started explicitly using
* BeforeClass method. Appropriate resource definition to reach the OpenDJ
* instance is provided in the test data and is inserted in the repository as
* part of test initialization.
*
* @author Radovan Semancik
*/
@ContextConfiguration(locations = {"classpath:ctx-sanity-test-main.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestSanity extends AbstractModelIntegrationTest {
private static final String REPO_DIR_NAME = "src/test/resources/repo/";
private static final String REQUEST_DIR_NAME = "src/test/resources/request/";
private static final File REQUEST_DIR = new File(REQUEST_DIR_NAME);
private static final String SYSTEM_CONFIGURATION_FILENAME = REPO_DIR_NAME + "system-configuration.xml";
private static final String SYSTEM_CONFIGURATION_OID = "00000000-0000-0000-0000-000000000001";
private static final String ROLE_SUPERUSER_FILENAME = REPO_DIR_NAME + "role-superuser.xml";
private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004";
private static final String RESOURCE_OPENDJ_FILENAME = REPO_DIR_NAME + "resource-opendj.xml";
private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff";
private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff";
protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson");
private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID";
private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn";
private static final String RESOURCE_DERBY_FILENAME = REPO_DIR_NAME + "resource-derby.xml";
private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab";
private static final String RESOURCE_BROKEN_FILENAME = REPO_DIR_NAME + "resource-broken.xml";
private static final String RESOURCE_BROKEN_OID = "ef2bc95b-76e0-59e2-ffff-ffffffffffff";
private static final String RESOURCE_DUMMY_FILENAME = REPO_DIR_NAME + "resource-dummy.xml";
private static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004";
private static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector";
private static final String CONNECTOR_DBTABLE_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-databasetable/org.identityconnectors.databasetable.DatabaseTableConnector";
private static final String CONNECTOR_BROKEN_FILENAME = REPO_DIR_NAME + "connector-broken.xml";
private static final String CONNECTOR_BROKEN_OID = "cccccccc-76e0-59e2-ffff-ffffffffffff";
private static final String TASK_OPENDJ_SYNC_FILENAME = REPO_DIR_NAME + "task-opendj-sync.xml";
private static final String TASK_OPENDJ_SYNC_OID = "91919191-76e0-59e2-86d6-3d4f02d3ffff";
private static final String TASK_USER_RECOMPUTE_FILENAME = REPO_DIR_NAME + "task-user-recompute.xml";
private static final String TASK_USER_RECOMPUTE_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaaa";
private static final String TASK_OPENDJ_RECON_FILENAME = REPO_DIR_NAME + "task-opendj-reconciliation.xml";
private static final String TASK_OPENDJ_RECON_OID = "91919191-76e0-59e2-86d6-3d4f02d30000";
private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = REPO_DIR_NAME + "sample-configuration-object.xml";
private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111";
private static final String USER_TEMPLATE_FILENAME = REPO_DIR_NAME + "user-template.xml";
private static final String USER_TEMPLATE_OID = "c0c010c0-d34d-b33f-f00d-777111111111";
private static final String USER_ADMINISTRATOR_FILENAME = REPO_DIR_NAME + "user-administrator.xml";
private static final String USER_ADMINISTRATOR_NAME = "administrator";
private static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002";
private static final String USER_JACK_FILENAME = REPO_DIR_NAME + "user-jack.xml";
private static final File USER_JACK_FILE = new File(USER_JACK_FILENAME);
private static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111";
private static final String USER_JACK_LDAP_UID = "jack";
private static final String USER_JACK_LDAP_DN = "uid=" + USER_JACK_LDAP_UID
+ "," + OPENDJ_PEOPLE_SUFFIX;
private static final String USER_GUYBRUSH_FILENAME = REPO_DIR_NAME + "user-guybrush.xml";
private static final File USER_GUYBRUSH_FILE = new File(USER_GUYBRUSH_FILENAME);
private static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111222";
private static final String USER_GUYBRUSH_USERNAME = "guybrush";
private static final String USER_GUYBRUSH_LDAP_UID = "guybrush";
private static final String USER_GUYBRUSH_LDAP_DN = "uid=" + USER_GUYBRUSH_LDAP_UID
+ "," + OPENDJ_PEOPLE_SUFFIX;
private static final String USER_E_LINK_ACTION_FILENAME = REPO_DIR_NAME + "user-e.xml";
private static final File USER_E_LINK_ACTION_FILE = new File(USER_E_LINK_ACTION_FILENAME);
private static final String LDIF_E_FILENAME_LINK = "src/test/resources/request/e-create.ldif";
private static final String ROLE_PIRATE_FILENAME = REPO_DIR_NAME + "role-pirate.xml";
private static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-987987987988";
private static final String ROLE_SAILOR_FILENAME = REPO_DIR_NAME + "role-sailor.xml";
private static final String ROLE_SAILOR_OID = "12345678-d34d-b33f-f00d-987955553535";
private static final String ROLE_CAPTAIN_FILENAME = REPO_DIR_NAME + "role-captain.xml";
private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc";
private static final String ROLE_JUDGE_FILENAME = REPO_DIR_NAME + "role-judge.xml";
private static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111";
private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account.xml";
private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account-derby.xml";
private static final String USER_JACK_DERBY_LOGIN = "jsparrow";
private static final String REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME = REQUEST_DIR_NAME + "user-modify-fullname-locality.xml";
private static final String REQUEST_USER_MODIFY_GIVENNAME_FILENAME = REQUEST_DIR_NAME + "user-modify-givenname.xml";
private static final String REQUEST_USER_MODIFY_PASSWORD_FILENAME = REQUEST_DIR_NAME + "user-modify-password.xml";
private static final String REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-disable.xml";
private static final String REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-enable.xml";
private static final String REQUEST_USER_MODIFY_NAME_FILENAME = REQUEST_DIR_NAME + "user-modify-name.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-pirate.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-1.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-2.xml";
private static final String REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-judge.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-pirate.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-1.xml";
private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-2.xml";
private static final File REQUEST_ACCOUNT_MODIFY_ATTRS_FILE = new File(REQUEST_DIR, "account-modify-attrs.xml");
private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE = new File(REQUEST_DIR, "account-modify-roomnumber.xml");
private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE = new File(REQUEST_DIR, "account-modify-roomnumber-explicit-type.xml");
private static final File REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE = new File(REQUEST_DIR, "account-modify-bad-path.xml");
private static final String LDIF_WILL_FILENAME = REQUEST_DIR_NAME + "will.ldif";
private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif");
private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif";
private static final String WILL_NAME = "wturner";
private static final String LDIF_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "angelika.ldif";
private static final String ANGELIKA_NAME = "angelika";
private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml";
private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif";
private static final String ELAINE_NAME = "elaine";
private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif");
private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif";
private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class);
private static final String NS_MY = "http://whatever.com/my";
private static final ItemName MY_SHIP_STATE = new ItemName(NS_MY, "shipState");
private static final ItemName MY_DEAD = new ItemName(NS_MY, "dead");
private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000;
/**
* Unmarshalled resource definition to reach the embedded OpenDJ instance.
* Used for convenience - the tests method may find it handy.
*/
private static ResourceType resourceTypeOpenDjrepo;
private static ResourceType resourceDerby;
private static String accountShadowOidOpendj;
private static String accountShadowOidDerby;
private static String accountShadowOidGuybrushOpendj;
private static String accountGuybrushOpendjEntryUuuid = null;
private static String originalJacksLdapPassword;
private static String lastJacksLdapPassword = null;
private int lastSyncToken;
@Autowired(required = true)
private MatchingRuleRegistry matchingRuleRegistry;
// This will get called from the superclass to init the repository
// It will be called only once
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
LOGGER.trace("initSystem");
try{
super.initSystem(initTask, initResult);
repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult);
repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult);
// This should discover the connectors
LOGGER.trace("initSystem: trying modelService.postInit()");
modelService.postInit(initResult);
LOGGER.trace("initSystem: modelService.postInit() done");
login(USER_ADMINISTRATOR_NAME);
// We need to add config after calling postInit() so it will not be applied.
// we want original logging configuration from the test logback config file, not
// the one from the system config.
repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult);
// Add broken connector before importing resources
repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult);
// Need to import instead of add, so the (dynamic) connector reference
// will be resolved
// correctly
importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult);
importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult);
repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult);
repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult);
repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult);
repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult);
repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult);
} catch (Exception ex){
LOGGER.error("erro: {}", ex);
throw ex;
}
}
/**
* Initialize embedded OpenDJ instance Note: this is not in the abstract
* superclass so individual tests may avoid starting OpenDJ.
*/
@Override
public void startResources() throws Exception {
openDJController.startCleanServer();
derbyController.startCleanServer();
}
/**
* Shutdown embedded OpenDJ instance Note: this is not in the abstract
* superclass so individual tests may avoid starting OpenDJ.
*/
@AfterClass
public static void stopResources() throws Exception {
openDJController.stop();
derbyController.stop();
}
/**
* Test integrity of the test setup.
*
* @throws SchemaException
* @throws ObjectNotFoundException
* @throws CommunicationException
*/
@Test
public void test000Integrity() throws Exception {
final String TEST_NAME = "test000Integrity";
TestUtil.displayTestTitle(this, TEST_NAME);
assertNotNull(modelWeb);
assertNotNull(modelService);
assertNotNull(repositoryService);
assertTrue(isSystemInitialized());
assertNotNull(taskManager);
assertNotNull(prismContext);
SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry();
assertNotNull(schemaRegistry);
// This is defined in extra schema. So this effectively checks whether the extra schema was loaded
PrismPropertyDefinition shipStateDefinition = schemaRegistry.findPropertyDefinitionByElementName(MY_SHIP_STATE);
assertNotNull("No my:shipState definition", shipStateDefinition);
assertEquals("Wrong maxOccurs in my:shipState definition", 1, shipStateDefinition.getMaxOccurs());
assertNoRepoCache();
Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test000Integrity");
OperationResult result = task.getResult();
// Check if OpenDJ resource was imported correctly
PrismObject<ResourceType> openDjResource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result);
display("Imported OpenDJ resource (repository)", openDjResource);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, openDjResource.getOid());
assertNoRepoCache();
String ldapConnectorOid = openDjResource.asObjectable().getConnectorRef().getOid();
PrismObject<ConnectorType> ldapConnector = repositoryService.getObject(ConnectorType.class, ldapConnectorOid, null, result);
display("LDAP Connector: ", ldapConnector);
// TODO: test if OpenDJ and Derby are running
repositoryService.getObject(GenericObjectType.class, SAMPLE_CONFIGURATION_OBJECT_OID, null, result);
}
/**
* Repeat self-test when we have all the dependencies on the classpath.
*/
@Test
public void test001SelfTests() throws Exception {
final String TEST_NAME = "test001SelfTests";
displayTestTitle(TEST_NAME);
// GIVEN
Task task = taskManager.createTaskInstance(TestSanity.class.getName()+"."+TEST_NAME);
// WHEN
OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task);
// THEN
assertSuccess("Repository self test", repositorySelfTestResult);
// WHEN
OperationResult provisioningSelfTestResult = modelDiagnosticService.provisioningSelfTest(task);
// THEN
display("Repository self test result", provisioningSelfTestResult);
// There may be warning about illegal key size on some platforms. As far as it is warning and not error we are OK
// the system will fall back to a interoperable key size
if (provisioningSelfTestResult.getStatus() != OperationResultStatus.SUCCESS && provisioningSelfTestResult.getStatus() != OperationResultStatus.WARNING) {
AssertJUnit.fail("Provisioning self-test failed: "+provisioningSelfTestResult);
}
}
/**
* Test the testResource method. Expect a complete success for now.
*/
@Test
public void test001TestConnectionOpenDJ() throws Exception {
final String TEST_NAME = "test001TestConnectionOpenDJ";
displayTestTitle(TEST_NAME);
// GIVEN
try{
assertNoRepoCache();
// WHEN
OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID);
// THEN
assertNoRepoCache();
displayJaxb("testResource result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("testResource has failed", result);
OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ");
PrismObject<ResourceType> resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult);
resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable();
assertNoRepoCache();
assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid());
display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo);
assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema());
Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo);
assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement);
PrismObject<ResourceType> openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID,
null, null, opResult);
display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig);
PrismObject<ResourceType> openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult);
display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel);
checkOpenDjResource(resourceTypeOpenDjrepo, "repository");
System.out.println("------------------------------------------------------------------");
display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo)));
System.out.println("------------------------------------------------------------------");
checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning");
checkOpenDjResource(openDjResourceModel.asObjectable(), "model");
// TODO: model web
} catch (Exception ex){
LOGGER.info("exception: " + ex);
throw ex;
}
}
private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result);
checkOpenDjResource(resource.asObjectable(), "repository");
}
/**
* Checks if the resource is internally consistent, if it has everything it should have.
*
* @throws SchemaException
*/
private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException {
assertNotNull("Resource from " + source + " is null", resource);
ObjectReferenceType connectorRefType = resource.getConnectorRef();
assertNotNull("Resource from " + source + " has null connectorRef", connectorRefType);
assertFalse("Resource from " + source + " has no OID in connectorRef", StringUtils.isBlank(connectorRefType.getOid()));
assertNotNull("Resource from " + source + " has null description in connectorRef", connectorRefType.getDescription());
assertNotNull("Resource from " + source + " has null filter in connectorRef", connectorRefType.getFilter());
assertNotNull("Resource from " + source + " has null filter element in connectorRef", connectorRefType.getFilter().getFilterClauseXNode());
assertNotNull("Resource from " + source + " has null configuration", resource.getConnectorConfiguration());
assertNotNull("Resource from " + source + " has null schema", resource.getSchema());
checkOpenDjSchema(resource, source);
assertNotNull("Resource from " + source + " has null schemahandling", resource.getSchemaHandling());
checkOpenDjSchemaHandling(resource, source);
if (!source.equals("repository")) {
// This is generated on the fly in provisioning
assertNotNull("Resource from " + source + " has null nativeCapabilities", resource.getCapabilities().getNative());
assertFalse("Resource from " + source + " has empty nativeCapabilities",
resource.getCapabilities().getNative().getAny().isEmpty());
}
assertNotNull("Resource from " + source + " has null configured capabilities", resource.getCapabilities().getConfigured());
assertFalse("Resource from " + source + " has empty capabilities", resource.getCapabilities().getConfigured().getAny().isEmpty());
assertNotNull("Resource from " + source + " has null synchronization", resource.getSynchronization());
checkOpenDjConfiguration(resource.asPrismObject(), source);
}
private void checkOpenDjSchema(ResourceType resource, String source) throws SchemaException {
ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext);
ObjectClassComplexTypeDefinition accountDefinition = schema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS);
assertNotNull("Schema does not define any account (resource from " + source + ")", accountDefinition);
Collection<? extends ResourceAttributeDefinition> identifiers = accountDefinition.getPrimaryIdentifiers();
assertFalse("No account identifiers (resource from " + source + ")", identifiers == null || identifiers.isEmpty());
// TODO: check for naming attributes and display names, etc
ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class);
if (capActivation != null && capActivation.getStatus() != null && capActivation.getStatus().getAttribute() != null) {
// There is simulated activation capability, check if the attribute is in schema.
QName enableAttrName = capActivation.getStatus().getAttribute();
ResourceAttributeDefinition enableAttrDef = accountDefinition.findAttributeDefinition(enableAttrName);
display("Simulated activation attribute definition", enableAttrDef);
assertNotNull("No definition for enable attribute " + enableAttrName + " in account (resource from " + source + ")", enableAttrDef);
assertTrue("Enable attribute " + enableAttrName + " is not ignored (resource from " + source + ")", enableAttrDef.isIgnored());
}
}
private void checkOpenDjSchemaHandling(ResourceType resource, String source) {
SchemaHandlingType schemaHandling = resource.getSchemaHandling();
for (ResourceObjectTypeDefinitionType resObjectTypeDef: schemaHandling.getObjectType()) {
if (resObjectTypeDef.getKind() == ShadowKindType.ACCOUNT) {
String name = resObjectTypeDef.getIntent();
assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig account definition without intent", name);
assertNotNull("Account type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass());
}
if (resObjectTypeDef.getKind() == ShadowKindType.ENTITLEMENT) {
String name = resObjectTypeDef.getIntent();
assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig entitlement definition without intent", name);
assertNotNull("Entitlement type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass());
}
}
}
private void checkOpenDjConfiguration(PrismObject<ResourceType> resource, String source) {
checkOpenResourceConfiguration(resource, CONNECTOR_LDAP_NAMESPACE, "bindPassword", 8, source);
}
private void checkOpenResourceConfiguration(PrismObject<ResourceType> resource, String connectorNamespace, String credentialsPropertyName,
int numConfigProps, String source) {
PrismContainer<Containerable> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION);
assertNotNull("No configuration container in "+resource+" from "+source, configurationContainer);
PrismContainer<Containerable> configPropsContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES);
assertNotNull("No configuration properties container in "+resource+" from "+source, configPropsContainer);
Collection<? extends Item<?,?>> configProps = configPropsContainer.getValue().getItems();
assertEquals("Wrong number of config properties in "+resource+" from "+source, numConfigProps, configProps.size());
PrismProperty<Object> credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace,credentialsPropertyName));
if (credentialsProp == null) {
// The is the heisenbug we are looking for. Just dump the entire damn thing.
display("Configuration with the heisenbug", configurationContainer.debugDump());
}
assertNotNull("No "+credentialsPropertyName+" property in "+resource+" from "+source, credentialsProp);
assertEquals("Wrong number of "+credentialsPropertyName+" property value in "+resource+" from "+source, 1, credentialsProp.getValues().size());
PrismPropertyValue<Object> credentialsPropertyValue = credentialsProp.getValues().iterator().next();
assertNotNull("No "+credentialsPropertyName+" property value in "+resource+" from "+source, credentialsPropertyValue);
if (credentialsPropertyValue.isRaw()) {
Object rawElement = credentialsPropertyValue.getRawElement();
assertTrue("Wrong element class "+rawElement.getClass()+" in "+resource+" from "+source, rawElement instanceof MapXNode);
// Element rawDomElement = (Element)rawElement;
MapXNode xmap = (MapXNode) rawElement;
try{
ProtectedStringType protectedType = new ProtectedStringType();
prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext());
// display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement));
// assertEquals("Wrong credentials element namespace in "+resource+" from "+source, connectorNamespace, rawDomElement.getNamespaceURI());
// assertEquals("Wrong credentials element local name in "+resource+" from "+source, credentialsPropertyName, rawDomElement.getLocalName());
// Element encryptedDataElement = DOMUtil.getChildElement(rawDomElement, new QName(DOMUtil.NS_XML_ENC, "EncryptedData"));
EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType();
assertNotNull("No EncryptedData element", encryptedDataType);
} catch (SchemaException ex){
throw new IllegalArgumentException(ex);
}
// assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI());
// assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName());
} else {
Object credentials = credentialsPropertyValue.getValue();
assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType);
ProtectedStringType credentialsPs = (ProtectedStringType)credentials;
EncryptedDataType encryptedData = credentialsPs.getEncryptedDataType();
assertNotNull("No EncryptedData element", encryptedData);
}
}
@Test
public void test002AddDerbyResource() throws Exception {
final String TEST_NAME = "test002AddDerbyResource";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME);
checkRepoOpenDjResource();
assertNoRepoCache();
PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DERBY_FILENAME));
assertParentConsistency(resource);
fillInConnectorRef(resource, IntegrationTestTools.DBTABLE_CONNECTOR_TYPE, result);
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<String> oidHolder = new Holder<>();
display("Adding Derby Resource", resource);
// WHEN
addObjectViaModelWS(resource.asObjectable(), null, oidHolder, resultHolder);
// THEN
// Check if Derby resource was imported correctly
PrismObject<ResourceType> derbyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result);
AssertJUnit.assertEquals(RESOURCE_DERBY_OID, derbyResource.getOid());
assertNoRepoCache();
String dbConnectorOid = derbyResource.asObjectable().getConnectorRef().getOid();
PrismObject<ConnectorType> dbConnector = repositoryService.getObject(ConnectorType.class, dbConnectorOid, null, result);
display("DB Connector: ", dbConnector);
// Check if password was encrypted during import
// via JAXB
Object configurationPropertiesElement = JAXBUtil.findElement(derbyResource.asObjectable().getConnectorConfiguration().getAny(),
new QName(dbConnector.asObjectable().getNamespace(), "configurationProperties"));
Object passwordElement = JAXBUtil.findElement(JAXBUtil.listChildElements(configurationPropertiesElement),
new QName(dbConnector.asObjectable().getNamespace(), "password"));
System.out.println("Password element: " + passwordElement);
// via prisms
PrismContainerValue configurationProperties = derbyResource.findContainer(
ItemPath.create(
ResourceType.F_CONNECTOR_CONFIGURATION,
new QName("configurationProperties")))
.getValue();
PrismProperty password = configurationProperties.findProperty(new ItemName(dbConnector.asObjectable().getNamespace(), "password"));
System.out.println("Password property: " + password);
}
private void addObjectViaModelWS(ObjectType objectType, ModelExecuteOptionsType options, Holder<String> oidHolder, Holder<OperationResultType> resultHolder) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
ObjectDeltaType objectDelta = new ObjectDeltaType();
objectDelta.setObjectToAdd(objectType);
QName type = objectType.asPrismObject().getDefinition().getTypeName();
objectDelta.setObjectType(type);
objectDelta.setChangeType(ChangeTypeType.ADD);
deltaList.getDelta().add(objectDelta);
ObjectDeltaOperationListType objectDeltaOperationListType = modelWeb.executeChanges(deltaList, options);
ObjectDeltaOperationType objectDeltaOperationType = getOdoFromDeltaOperationList(objectDeltaOperationListType, objectDelta);
resultHolder.value = objectDeltaOperationType.getExecutionResult();
oidHolder.value = ((ObjectType) objectDeltaOperationType.getObjectDelta().getObjectToAdd()).getOid();
}
// ugly hack...
private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDeltaOperationListType operationListType, ObjectDeltaType originalDelta) {
Validate.notNull(operationListType);
Validate.notNull(originalDelta);
for (ObjectDeltaOperationType operationType : operationListType.getDeltaOperation()) {
ObjectDeltaType objectDeltaType = operationType.getObjectDelta();
if (originalDelta.getChangeType() == ChangeTypeType.ADD) {
if (objectDeltaType.getChangeType() == originalDelta.getChangeType() &&
objectDeltaType.getObjectToAdd() != null) {
ObjectType objectAdded = (ObjectType) objectDeltaType.getObjectToAdd();
if (objectAdded.getClass().equals(originalDelta.getObjectToAdd().getClass())) {
return operationType;
}
}
} else {
if (objectDeltaType.getChangeType() == originalDelta.getChangeType() &&
originalDelta.getOid().equals(objectDeltaType.getOid())) {
return operationType;
}
}
}
throw new IllegalStateException("No suitable ObjectDeltaOperationType found");
}
private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoDerbyResource");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result);
checkDerbyResource(resource, "repository");
}
private void checkDerbyResource(PrismObject<ResourceType> resource, String source) {
checkDerbyConfiguration(resource, source);
}
private void checkDerbyConfiguration(PrismObject<ResourceType> resource, String source) {
checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source);
}
/**
* Test the testResource method. Expect a complete success for now.
*/
@Test
public void test003TestConnectionDerby() throws Exception {
TestUtil.displayTestTitle("test003TestConnectionDerby");
// GIVEN
checkRepoDerbyResource();
assertNoRepoCache();
// WHEN
OperationResultType result = modelWeb.testResource(RESOURCE_DERBY_OID);
// THEN
assertNoRepoCache();
displayJaxb("testResource result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("testResource has failed", result.getPartialResults().get(0));
OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test002TestConnectionDerby");
PrismObject<ResourceType> rObject = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, opResult);
resourceDerby = rObject.asObjectable();
checkDerbyResource(rObject, "repository(after test)");
assertNoRepoCache();
assertEquals(RESOURCE_DERBY_OID, resourceDerby.getOid());
display("Initialized Derby resource (respository)", resourceDerby);
assertNotNull("Resource schema was not generated", resourceDerby.getSchema());
Element resourceDerbyXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceDerby);
assertNotNull("Resource schema was not generated", resourceDerbyXsdSchemaElement);
PrismObject<ResourceType> derbyResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID,
null, null, opResult);
display("Initialized Derby resource (provisioning)", derbyResourceProvisioninig);
PrismObject<ResourceType> derbyResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID,
null, null, opResult);
display("Initialized Derby resource (model)", derbyResourceModel);
// TODO: check
// checkOpenDjResource(resourceOpenDj,"repository");
// checkOpenDjResource(openDjResourceProvisioninig,"provisioning");
// checkOpenDjResource(openDjResourceModel,"model");
// TODO: model web
}
@Test
public void test004Capabilities() throws ObjectNotFoundException, CommunicationException, SchemaException,
FaultMessage {
TestUtil.displayTestTitle("test004Capabilities");
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID,
options , objectHolder, resultHolder);
ResourceType resource = (ResourceType) objectHolder.value;
// THEN
display("Resource", resource);
assertNoRepoCache();
CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative();
List<Object> capabilities = nativeCapabilities.getAny();
assertFalse("Empty capabilities returned", capabilities.isEmpty());
for (Object capability : nativeCapabilities.getAny()) {
System.out.println("Native Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
if (resource.getCapabilities() != null) {
for (Object capability : resource.getCapabilities().getConfigured().getAny()) {
System.out.println("Configured Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
}
List<Object> effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource);
for (Object capability : effectiveCapabilities) {
System.out.println("Efective Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability);
}
CredentialsCapabilityType capCred = CapabilityUtil.getCapability(capabilities, CredentialsCapabilityType.class);
assertNotNull("password capability not present", capCred.getPassword());
// Connector cannot do activation, this should be null
ActivationCapabilityType capAct = CapabilityUtil.getCapability(capabilities, ActivationCapabilityType.class);
assertNull("Found activation capability while not expecting it", capAct);
capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class);
assertNotNull("password capability not found", capCred.getPassword());
// Although connector does not support activation, the resource specifies a way how to simulate it.
// Therefore the following should succeed
capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class);
assertNotNull("activation capability not found", capAct);
}
@Test
public void test005resolveConnectorRef() throws Exception{
TestUtil.displayTestTitle("test005resolveConnectorRef");
PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME));
ModelExecuteOptionsType options = new ModelExecuteOptionsType();
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>());
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ResourceType> uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult);
assertNotNull(uObject);
ResourceType resourceType = uObject.asObjectable();
assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef());
assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid());
}
@Test
public void test006reimportResourceDummy() throws Exception{
TestUtil.displayTestTitle("test006reimportResourceDummy");
//get object from repo (with version set and try to add it - it should be re-added, without error)
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult);
assertNotNull(resource);
ModelExecuteOptionsType options = new ModelExecuteOptionsType();
options.setOverwrite(Boolean.TRUE);
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>());
//TODO: add some asserts
//parse object from file again and try to add it - this should fail, becasue the same object already exists)
resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME));
try {
Holder<OperationResultType> resultHolder = new Holder<>();
options = new ModelExecuteOptionsType();
options.setIsImport(Boolean.TRUE);
addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(),
resultHolder);
OperationResultType result = resultHolder.value;
TestUtil.assertFailure(result);
fail("Expected object already exists exception, but haven't got one.");
} catch (FaultMessage ex) {
LOGGER.info("fault {}", ex.getFaultInfo());
LOGGER.info("fault {}", ex.getCause());
if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) {
// this is OK, we expect this
} else{
fail("Expected object already exists exception, but got: " + ex.getFaultInfo());
}
}
// ResourceType resourceType = uObject.asObjectable();
// assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef());
// assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid());
}
/**
* Attempt to add new user. It is only added to the repository, so check if
* it is in the repository after the operation.
*/
@Test
public void test010AddUser() throws Exception {
final String TEST_NAME = "test010AddUser";
displayTestTitle(TEST_NAME);
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_JACK_FILE);
UserType userType = user.asObjectable();
assertParentConsistency(user);
// Encrypt Jack's password
protector.encrypt(userType.getCredentials().getPassword().getValue());
assertParentConsistency(user);
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
display("Adding user object", userType);
// WHEN
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
// AssertJUnit.assertEquals(USER_JACK_OID, oid);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("repository.getObject result", repoResult);
TestUtil.assertSuccess("getObject has failed", repoResult);
AssertJUnit.assertEquals(USER_JACK_OID, repoUser.getOid());
assertEqualsPolyString("fullName", userType.getFullName(), repoUser.getFullName());
// TODO: better checks
}
/**
* Add account to user. This should result in account provisioning. Check if
* that happens in repo and in LDAP.
*/
@Test
public void test013AddOpenDjAccountToUser() throws Exception {
final String TEST_NAME = "test013AddOpenDjAccountToUser";
displayTestTitle(TEST_NAME);
try{
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
// IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE!
setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE);
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class);
// WHEN
displayWhen(TEST_NAME);
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals("No accountRefs", 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidOpendj = accountRef.getOid();
assertFalse(accountShadowOidOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
assertNotNull("Shadow stored in repository has no name", repoShadowType.getName());
// Check the "name" property, it should be set to DN, not entryUUID
assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "jack");
OpenDJController.assertAttribute(entry, "givenName", "Jack");
OpenDJController.assertAttribute(entry, "sn", "Sparrow");
OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow");
OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Black Pearl");
assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry));
originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", originalJacksLdapPassword);
System.out.println("password after create: " + originalJacksLdapPassword);
// Use getObject to test fetch of complete shadow
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl");
assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense"));
assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress"));
assertNotNull("Activation is null (model)", modelShadow.getActivation());
assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus());
} catch (Exception ex){
LOGGER.info("ERROR: {}", ex);
throw ex;
}
}
private OperationResultType modifyObjectViaModelWS(ObjectDeltaType objectChange) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
deltaList.getDelta().add(objectChange);
ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null);
return getOdoFromDeltaOperationList(list, objectChange).getExecutionResult();
}
/**
* Add Derby account to user. This should result in account provisioning. Check if
* that happens in repo and in Derby.
*/
@Test
public void test014AddDerbyAccountToUser() throws IOException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test014AddDerbyAccountToUser");
// GIVEN
checkRepoDerbyResource();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
// OpenDJ account was added in previous test, hence 2 accounts
assertEquals(2, accountRefs.size());
ObjectReferenceType accountRef = null;
for (ObjectReferenceType ref : accountRefs) {
if (!ref.getOid().equals(accountShadowOidOpendj)) {
accountRef = ref;
}
}
accountShadowOidDerby = accountRef.getOid();
assertFalse(accountShadowOidDerby.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidDerby,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("addObject has failed", repoResult);
display("Shadow (repository)", repoShadowType);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_DERBY_OID, repoShadowType.getResourceRef().getOid());
// Check the "name" property, it should be set to DN, not entryUUID
assertEquals("Wrong name property", PrismTestUtil.createPolyStringType(USER_JACK_DERBY_LOGIN),
repoShadowType.getName());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// check if account was created in DB Table
Statement stmt = derbyController.getExecutedStatementWhereLoginName(uid);
ResultSet rs = stmt.getResultSet();
System.out.println("RS: " + rs);
assertTrue("No records found for login name " + uid, rs.next());
assertEquals(USER_JACK_DERBY_LOGIN, rs.getString(DerbyController.COLUMN_LOGIN));
assertEquals("Cpt. Jack Sparrow", rs.getString(DerbyController.COLUMN_FULL_NAME));
// TODO: check password
//assertEquals("3lizab3th",rs.getString(DerbyController.COLUMN_PASSWORD));
System.out.println("Password: " + rs.getString(DerbyController.COLUMN_PASSWORD));
assertFalse("Too many records found for login name " + uid, rs.next());
rs.close();
stmt.close();
// Use getObject to test fetch of complete shadow
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType ();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_DERBY_OID, modelShadow.getResourceRef().getOid());
assertAttribute(modelShadow, SchemaConstants.ICFS_UID, USER_JACK_DERBY_LOGIN);
assertAttribute(modelShadow, SchemaConstants.ICFS_NAME, USER_JACK_DERBY_LOGIN);
assertAttribute(resourceDerby, modelShadow, "FULL_NAME", "Cpt. Jack Sparrow");
}
@Test
public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException {
TestUtil.displayTestTitle("test015AccountOwner");
// GIVEN
checkRepoOpenDjResource();
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<UserType> userHolder = new Holder<>();
// WHEN
modelWeb.findShadowOwner(accountShadowOidOpendj, userHolder, resultHolder);
// THEN
display("listAccountShadowOwner result", resultHolder.value);
TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value);
UserType user = userHolder.value;
assertNotNull("No owner", user);
assertEquals(USER_JACK_OID, user.getOid());
System.out.println("Account " + accountShadowOidOpendj + " has owner " + ObjectTypeUtil.toShortString(user));
}
@Test
public void test016ProvisioningSearchAccountsIterative() throws Exception {
TestUtil.displayTestTitle("test016ProvisioningSearchAccountsIterative");
// GIVEN
OperationResult result = new OperationResult(TestSanity.class.getName() + ".test016ProvisioningSearchAccountsIterative");
RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceTypeOpenDjrepo, prismContext);
final RefinedObjectClassDefinition refinedAccountDefinition = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT);
QName objectClass = refinedAccountDefinition.getObjectClassDefinition().getTypeName();
ObjectQuery q = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceTypeOpenDjrepo.getOid(), objectClass, prismContext);
final Collection<ObjectType> objects = new HashSet<>();
final MatchingRule caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME, DOMUtil.XSD_STRING);
ResultHandler handler = new ResultHandler<ObjectType>() {
@Override
public boolean handle(PrismObject<ObjectType> prismObject, OperationResult parentResult) {
ObjectType objectType = prismObject.asObjectable();
objects.add(objectType);
display("Found object", objectType);
assertTrue(objectType instanceof ShadowType);
ShadowType shadow = (ShadowType) objectType;
assertNotNull(shadow.getOid());
assertNotNull(shadow.getName());
assertEquals(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, shadow.getObjectClass());
assertEquals(RESOURCE_OPENDJ_OID, shadow.getResourceRef().getOid());
String icfUid = getAttributeValue(shadow, getOpenDjPrimaryIdentifierQName());
assertNotNull("No ICF UID", icfUid);
String icfName = getNormalizedAttributeValue(shadow, refinedAccountDefinition, getOpenDjSecondaryIdentifierQName());
assertNotNull("No ICF NAME", icfName);
try {
PrismAsserts.assertEquals("Wrong shadow name", caseIgnoreMatchingRule, shadow.getName().getOrig(), icfName);
} catch (SchemaException e) {
throw new IllegalArgumentException(e.getMessage(),e);
}
assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "uid")));
assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "cn")));
assertNotNull("Missing LDAP sn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "sn")));
assertNotNull("Missing activation", shadow.getActivation());
assertNotNull("Missing activation status", shadow.getActivation().getAdministrativeStatus());
return true;
}
};
// WHEN
provisioningService.searchObjectsIterative(ShadowType.class, q, null, handler, null, result);
// THEN
display("Count", objects.size());
}
/**
* We are going to modify the user. As the user has an account, the user
* changes should be also applied to the account (by schemaHandling).
*/
@Test
public void test020ModifyUser() throws Exception {
final String TEST_NAME = "test020ModifyUser";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong value for locality", "somewhere", repoUserType.getLocality());
assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUserType,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
assertOpenDJAccountJack(uid, "jack");
}
private Entry assertOpenDJAccountJack(String entryUuid, String uid) throws DirectoryException {
Entry entry = openDJController.searchAndAssertByEntryUuid(entryUuid);
return assertOpenDJAccountJack(entry, uid);
}
private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryException {
return assertOpenDJAccountJack(entry, uid, "Jack");
}
private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException {
display(entry);
OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com");
OpenDJController.assertAttribute(entry, "uid", uid);
if (givenName == null) {
OpenDJController.assertAttribute(entry, "givenName");
} else {
OpenDJController.assertAttribute(entry, "givenName", givenName);
}
OpenDJController.assertAttribute(entry, "sn", "Sparrow");
// These two should be assigned from the User modification by
// schemaHandling
OpenDJController.assertAttribute(entry, "cn", "Cpt. Jack Sparrow");
OpenDJController.assertAttribute(entry, "displayName", "Cpt. Jack Sparrow");
// This will get translated from "somewhere" to this (outbound
// expression in schemeHandling) -> this is not more supported...we
// don't support complex run-time properties. the value will be
// evaluated from outbound expression
OpenDJController.assertAttribute(entry, "l", "somewhere");
OpenDJController.assertAttribute(entry, "postalAddress", "Number 1");
return entry;
}
/**
* We are going to change user's password. As the user has an account, the password change
* should be also applied to the account (by schemaHandling).
*/
@Test
public void test022ChangeUserPassword() throws Exception {
final String TEST_NAME = "test022ChangeUserPassword";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_PASSWORD_FILENAME, ObjectDeltaType.class);
System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0));
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertUserPasswordChange("butUnd3dM4yT4lkAL0t", result);
}
/**
* Similar to previous test just the request is constructed a bit differently.
*/
@Test
public void test023ChangeUserPasswordJAXB() throws Exception {
final String TEST_NAME = "test023ChangeUserPasswordJAXB";
displayTestTitle(TEST_NAME);
// GIVEN
final String NEW_PASSWORD = "abandonSHIP";
Document doc = ModelClientUtil.getDocumnent();
ObjectDeltaType userDelta = new ObjectDeltaType();
userDelta.setOid(USER_JACK_OID);
userDelta.setChangeType(ChangeTypeType.MODIFY);
userDelta.setObjectType(UserType.COMPLEX_TYPE);
ItemDeltaType passwordDelta = new ItemDeltaType();
passwordDelta.setModificationType(ModificationTypeType.REPLACE);
passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext));
ProtectedStringType pass = new ProtectedStringType();
pass.setClearValue(NEW_PASSWORD);
XNode passValue = prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(pass).getSubnode();
System.out.println("PASSWORD VALUE: " + passValue.debugDump());
RawType passwordValue = new RawType(passValue, prismContext);
passwordDelta.getValue().add(passwordValue);
userDelta.getItemDelta().add(passwordDelta);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(userDelta);
// THEN
assertUserPasswordChange(NEW_PASSWORD, result);
}
private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException {
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
// Check if nothing else was modified
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality());
// Check if appropriate accountRef is still there
assertLinks(repoUser, 2);
assertLinked(repoUser, accountShadowOidOpendj);
assertLinked(repoUser, accountShadowOidDerby);
assertPassword(repoUser, expectedUserPassword);
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
display("repository shadow", repoShadow);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry entry = assertOpenDJAccountJack(uid, "jack");
String ldapPasswordAfter = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull(ldapPasswordAfter);
display("LDAP password after change", ldapPasswordAfter);
assertFalse("No change in password (original)", ldapPasswordAfter.equals(originalJacksLdapPassword));
if (lastJacksLdapPassword != null) {
assertFalse("No change in password (last)", ldapPasswordAfter.equals(lastJacksLdapPassword));
}
lastJacksLdapPassword = ldapPasswordAfter;
}
@Test
public void test027ModifyAccountDj() throws Exception {
final String TEST_NAME = "test027ModifyAccountDj";
testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck");
}
@Test
public void test028ModifyAccountDjExplicitType() throws Exception {
final String TEST_NAME = "test028ModifyAccountDjExplicitType";
testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck");
}
public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception {
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(reqFile, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidOpendj);
// WHEN
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack");
OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal);
}
@Test
public void test029ModifyAccountDjBadPath() throws Exception {
final String TEST_NAME = "test029ModifyAccountDjBadPath";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidOpendj);
OperationResultType result;
try {
// WHEN
result = modifyObjectViaModelWS(objectChange);
AssertJUnit.fail("Unexpected success");
} catch (FaultMessage f) {
// this is expected
FaultType faultInfo = f.getFaultInfo();
result = faultInfo.getOperationResult();
}
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertFailure(result);
OperationResult repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack");
OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", "upperdeck");
}
/**
* Try to disable user. As the user has an account, the account should be disabled as well.
*/
@Test
public void test030DisableUser() throws Exception {
final String TEST_NAME = "test030DisableUser";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class);
Entry entry = openDJController.searchByUid("jack");
assertOpenDJAccountJack(entry, "jack");
String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
display("ds-pwp-account-disabled before change", pwpAccountDisabled);
assertTrue("LDAP account is not enabled (precondition)", openDJController.isAccountEnabled(entry));
assertNoRepoCache();
// WHEN
displayWhen(TEST_NAME);
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
display("repository user", repoUser);
UserType repoUserType = repoUser.asObjectable();
// Check if nothing else was modified
assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUserType,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
display("repo shadow", repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jack");
pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
display("ds-pwp-account-disabled after change", pwpAccountDisabled);
assertFalse("LDAP account was not disabled", openDJController.isAccountEnabled(entry));
// Use getObject to test fetch of complete shadow
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
// WHEN
displayWhen(TEST_NAME);
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere");
assertNotNull("The account activation is null in the shadow", modelShadow.getActivation());
assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus());
assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, modelShadow.getActivation().getAdministrativeStatus());
}
/**
* Try to enable user after it has been disabled. As the user has an account, the account should be enabled as well.
*/
@Test
public void test031EnableUser() throws Exception {
final String TEST_NAME = "test031EnableUser";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class);
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
display("repo user", repoUser);
// Check if nothing else was modified
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUser.getFullName());
PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUser.getLocality());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(2, accountRefs.size());
for (ObjectReferenceType accountRef : accountRefs) {
assertTrue("No OID in "+accountRef+" in "+repoUser,
accountRef.getOid().equals(accountShadowOidOpendj) ||
accountRef.getOid().equals(accountShadowOidDerby));
}
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repo shadow", repoShadowType);
AssertJUnit.assertNotNull(repoShadowType);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Use getObject to test fetch of complete shadow
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
// WHEN
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj,
options, objectHolder, resultHolder);
// THEN
assertNoRepoCache();
displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
ShadowType modelShadow = (ShadowType) objectHolder.value;
display("Shadow (model)", modelShadow);
AssertJUnit.assertNotNull(modelShadow);
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid());
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow");
assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere");
assertNotNull("The account activation is null in the shadow", modelShadow.getActivation());
assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus());
assertEquals("The account was not enabled in the shadow", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus());
// Check if LDAP account was updated
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jack");
// The value of ds-pwp-account-disabled should have been removed
String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled");
System.out.println("ds-pwp-account-disabled after change: " + pwpAccountDisabled);
assertTrue("LDAP account was not enabled", openDJController.isAccountEnabled(entry));
}
/**
* Unlink account by removing the accountRef from the user.
* The account will not be deleted, just the association to user will be broken.
*/
@Test
public void test040UnlinkDerbyAccountFromUser() throws FileNotFoundException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test040UnlinkDerbyAccountFromUser");
// GIVEN
ObjectDeltaType objectChange = new ObjectDeltaType();
objectChange.setOid(USER_JACK_OID);
ItemDeltaType modificationDeleteAccountRef = new ItemDeltaType();
modificationDeleteAccountRef.setModificationType(ModificationTypeType.DELETE);
ObjectReferenceType accountRefToDelete = new ObjectReferenceType();
accountRefToDelete.setOid(accountShadowOidDerby);
RawType modificationValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(accountRefToDelete).getSubnode(), prismContext);
modificationDeleteAccountRef.getValue().add(modificationValue);
modificationDeleteAccountRef.setPath(new ItemPathType(UserType.F_LINK_REF));
objectChange.getItemDelta().add(modificationDeleteAccountRef);
objectChange.setChangeType(ChangeTypeType.MODIFY);
objectChange.setObjectType(UserType.COMPLEX_TYPE);
displayJaxb("modifyObject input", objectChange, new QName(SchemaConstants.NS_C, "change"));
assertNoRepoCache();
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
// only OpenDJ account should be left now
assertEquals(1, accountRefs.size());
ObjectReferenceType ref = accountRefs.get(0);
assertEquals("Wrong OID in accountRef in "+repoUser, accountShadowOidOpendj, ref.getOid());
}
/**
* Delete the shadow which will cause deletion of associated account.
* The account was unlinked in the previous test, therefore no operation with user is needed.
*/
@Test
public void test041DeleteDerbyAccount() throws FileNotFoundException, JAXBException, FaultMessage,
ObjectNotFoundException, SchemaException, DirectoryException, SQLException {
TestUtil.displayTestTitle("test041DeleteDerbyAccount");
// GIVEN
assertNoRepoCache();
// WHEN
OperationResultType result = deleteObjectViaModelWS(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby);
// THEN
assertNoRepoCache();
displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("deleteObject has failed", result);
// Check if shadow was deleted
OperationResult repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(ShadowType.class, accountShadowOidDerby,
null, repoResult);
AssertJUnit.fail("Shadow was not deleted");
} catch (ObjectNotFoundException ex) {
display("Caught expected exception from getObject(shadow): " + ex);
}
// check if account was deleted in DB Table
Statement stmt = derbyController.getExecutedStatementWhereLoginName(USER_JACK_DERBY_LOGIN);
ResultSet rs = stmt.getResultSet();
System.out.println("RS: " + rs);
assertFalse("Account was not deleted in database", rs.next());
}
private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage {
ObjectDeltaListType deltaList = new ObjectDeltaListType();
ObjectDeltaType objectDelta = new ObjectDeltaType();
objectDelta.setOid(oid);
objectDelta.setObjectType(typeQName);
objectDelta.setChangeType(ChangeTypeType.DELETE);
deltaList.getDelta().add(objectDelta);
ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null);
return getOdoFromDeltaOperationList(list, objectDelta).getExecutionResult();
}
@Test
public void test047RenameUser() throws Exception {
final String TEST_NAME = "test047RenameUser";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for User name", "jsparrow", repoUserType.getName());
PrismAsserts.assertEqualsPolyString("wrong value for User fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
PrismAsserts.assertEqualsPolyString("wrong value for User locality", "somewhere", repoUserType.getLocality());
assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.iterator().next();
assertEquals("Wrong OID in "+accountRef+" in "+repoUserType,
accountShadowOidOpendj, accountRef.getOid());
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
assertOpenDJAccountJack(uid, "jsparrow");
}
/**
* We are going to modify the user. As the user has an account, the user
* changes should be also applied to the account (by schemaHandling).
*
* @throws DirectoryException
*/
@Test
public void test048ModifyUserRemoveGivenName() throws Exception {
final String TEST_NAME = "test048ModifyUserRemoveGivenName";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class);
displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
display("repository user", repoUser);
PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName());
assertNull("Value for givenName still present", repoUserType.getGivenName());
// Check if appropriate accountRef is still there
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.iterator().next();
accountRef.getOid().equals(accountShadowOidOpendj);
// Check if shadow is still in the repo and that it is untouched
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
repoResult.computeStatus();
TestUtil.assertSuccess("getObject(repo) has failed", repoResult);
display("repository shadow", repoShadow);
AssertJUnit.assertNotNull(repoShadow);
ShadowType repoShadowType = repoShadow.asObjectable();
AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check attributes in the shadow: should be only identifiers (ICF UID)
String uid = checkRepoShadow(repoShadow);
// Check if LDAP account was updated
Entry entry = openDJController.searchAndAssertByEntryUuid(uid);
assertOpenDJAccountJack(entry, "jsparrow", null);
}
/**
* The user should have an account now. Let's try to delete the user. The
* account should be gone as well.
*
* @throws JAXBException
*/
@Test
public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException, JAXBException {
TestUtil.displayTestTitle("test049DeleteUser");
// GIVEN
assertNoRepoCache();
// WHEN
OperationResultType result = deleteObjectViaModelWS(ObjectTypes.USER.getTypeQName(), USER_JACK_OID);
// THEN
assertNoRepoCache();
displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("deleteObject has failed", result);
// User should be gone from the repository
OperationResult repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult);
AssertJUnit.fail("User still exists in repo after delete");
} catch (ObjectNotFoundException e) {
// This is expected
}
// Account shadow should be gone from the repository
repoResult = new OperationResult("getObject");
try {
repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult);
AssertJUnit.fail("Shadow still exists in repo after delete");
} catch (ObjectNotFoundException e) {
// This is expected, but check also the result
AssertJUnit.assertFalse("getObject failed as expected, but the result indicates success",
repoResult.isSuccess());
}
// Account should be deleted from LDAP
InternalSearchOperation op = openDJController.getInternalConnection().processSearch(
"dc=example,dc=com", SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100,
100, false, "(uid=" + USER_JACK_LDAP_UID + ")", null);
AssertJUnit.assertEquals(0, op.getEntriesSent());
}
@Test
public void test100AssignRolePirate() throws Exception {
final String TEST_NAME = "test100AssignRolePirate";
displayTestTitle(TEST_NAME);
// GIVEN
// IMPORTANT! Assignment enforcement is FULL now
setAssignmentEnforcement(AssignmentPolicyEnforcementType.FULL);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.FULL);
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_GUYBRUSH_FILE);
UserType userType = user.asObjectable();
// Encrypt the password
protector.encrypt(userType.getCredentials().getPassword().getValue());
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
assertNoRepoCache();
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
assertNoRepoCache();
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadowType);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
// TODO: Derby
}
@Test
public void test101AccountOwnerAfterRole() throws Exception {
final String TEST_NAME = "test101AccountOwnerAfterRole";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<UserType> userHolder = new Holder<>();
// WHEN
modelWeb.findShadowOwner(accountShadowOidGuybrushOpendj, userHolder, resultHolder);
// THEN
TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value);
UserType user = userHolder.value;
assertNotNull("No owner", user);
assertEquals(USER_GUYBRUSH_OID, user.getOid());
System.out.println("Account " + accountShadowOidGuybrushOpendj + " has owner " + ObjectTypeUtil.toShortString(user));
}
@Test
public void test102AssignRoleCaptain() throws Exception {
final String TEST_NAME = "test102AssignRoleCaptain";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignment
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
/**
* Assign the same "captain" role again, this time with a slightly different assignment parameters.
*/
@Test
public void test103AssignRoleCaptainAgain() throws Exception {
final String TEST_NAME = "test103AssignRoleCaptainAgain";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
@Test
public void test105ModifyAccount() throws Exception {
final String TEST_NAME = "test105ModifyAccount";
displayTestTitle(TEST_NAME);
// GIVEN
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class);
objectChange.setOid(accountShadowOidGuybrushOpendj);
// WHEN ObjectTypes.SHADOW.getTypeQName(),
OperationResultType result = modifyObjectViaModelWS(objectChange);
Task task = taskManager.createTaskInstance();
OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify");
PrismObject<ShadowType> shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult);
assertNotNull("shadow must not be null", shadow);
ShadowType shadowType = shadow.asObjectable();
QName employeeTypeQName = new QName(resourceTypeOpenDjrepo.getNamespace(), "employeeType");
ItemPath employeeTypePath = ItemPath.create(ShadowType.F_ATTRIBUTES, employeeTypeQName);
PrismProperty item = shadow.findProperty(employeeTypePath);
PropertyDelta deleteDelta = prismContext.deltaFactory().property().create(ShadowType.F_ATTRIBUTES, item.getDefinition().getItemName(), item.getDefinition());
// PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition());
// PrismPropertyValue valToDelte = new PrismPropertyValue("A");
// valToDelte.setParent(deleteDelta);
Collection<PrismPropertyValue> values= item.getValues();
for (PrismPropertyValue val : values){
if ("A".equals(val.getValue())){
deleteDelta.addValueToDelete(val.clone());
}
}
ObjectDelta delta = prismContext.deltaFactory().object().create(ShadowType.class, ChangeType.MODIFY);
delta.addModification(deleteDelta);
delta.setOid(accountShadowOidGuybrushOpendj);
Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
deltas.add(delta);
LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------");
modelService.executeChanges(deltas, null, task, parentResult);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// check if LDAP account was modified
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
OpenDJController.assertAttribute(entry, "roomNumber", "captain's cabin");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
}
/**
* Judge role excludes pirate role. This assignment should fail.
*/
@Test
public void test104AssignRoleJudge() throws Exception {
final String TEST_NAME = "test104AssignRoleJudge";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<String> oidHolder = new Holder<>();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class);
try {
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
AssertJUnit.fail("Expected a failure after assigning conflicting roles but nothing happened and life goes on");
} catch (FaultMessage f) {
// This is expected
// TODO: check if the fault is the right one
}
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object remain unmodified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Unexpected number or accountRefs", 1, accountRefs.size());
}
@Test
public void test107UnassignRolePirate() throws Exception {
final String TEST_NAME = "test107UnassignRolePirate";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadow = aObject.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadow);
assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
@Test
public void test108UnassignRoleCaptain() throws Exception {
final String TEST_NAME = "test108UnassignRoleCaptain";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUser);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid());
// Check if shadow is still in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
display("Shadow (repository)", repoShadow);
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
// check if account is still in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize");
// Expression in the role taking that from the user
OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush");
// Expression in the role taking that from the assignments (both of them)
OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Dainty Lady");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword disappeared", guybrushPassword);
// TODO: Derby
}
/**
* Captain role was assigned twice. It has to also be unassigned twice.
*/
@Test
public void test109UnassignRoleCaptainAgain() throws Exception {
final String TEST_NAME = "test109UnassignRoleCaptainAgain";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
assertNoRepoCache();
ObjectDeltaType objectChange = unmarshallValueFromFile(
REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class);
// WHEN ObjectTypes.USER.getTypeQName(),
result = modifyObjectViaModelWS(objectChange);
// THEN
assertNoRepoCache();
displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT);
//TODO TODO TODO TODO operation result from repostiory.getObject is unknown...find out why..
// assertSuccess("modifyObject has failed", result);
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PropertyReferenceListType resolve = new PropertyReferenceListType();
PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUserType = repoUser.asObjectable();
repoResult.computeStatus();
display("User (repository)", repoUserType);
List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef();
assertEquals(0, accountRefs.size());
// Check if shadow was deleted from the repo
repoResult = new OperationResult("getObject");
try {
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
AssertJUnit.fail("Account shadow was not deleted from repo");
} catch (ObjectNotFoundException ex) {
// This is expected
}
// check if account was deleted from LDAP
Entry entry = openDJController.searchByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
assertNull("LDAP account was not deleted", entry);
// TODO: Derby
}
// Synchronization tests
/**
* Test initialization of synchronization. It will create a cycle task and
* check if the cycle executes No changes are synchronized yet.
*/
@Test
public void test300LiveSyncInit() throws Exception {
final String TEST_NAME = "test300LiveSyncInit";
displayTestTitle(TEST_NAME);
// Now it is the right time to add task definition to the repository
// We don't want it there any sooner, as it may interfere with the
// previous tests
checkAllShadows();
// IMPORTANT! Assignment enforcement is POSITIVE now
setAssignmentEnforcement(AssignmentPolicyEnforcementType.POSITIVE);
// This is not redundant. It checks that the previous command set the policy correctly
assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task manager to pick up the task", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
display("Task while waiting for task manager to pick up the task", task);
// wait until the task is picked up
return task.getLastRunFinishTimestamp() != null;
// if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) {
// // wait until the first run is finished
// if (task.getLastRunFinishTimestamp() == null) {
// return false;
// }
// return true;
// }
// return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 20000);
// Check task status
Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, retrieveTaskResult(), result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after pickup", task);
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_SYNC_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and claimed
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
// .. and last run should not be zero
assertNotNull("No lastRunStartTimestamp", task.getLastRunStartTimestamp());
assertFalse("Zero lastRunStartTimestamp", task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull("No lastRunFinishedTimestamp", task.getLastRunFinishTimestamp());
assertFalse("Zero lastRunFinishedTimestamp", task.getLastRunFinishTimestamp().longValue() == 0);
// Test for extension. This will also roughly test extension processor
// and schema processor
PrismContainer<?> taskExtension = task.getExtensionOrClone();
AssertJUnit.assertNotNull(taskExtension);
display("Task extension", taskExtension);
PrismProperty<String> shipStateProp = taskExtension.findProperty(MY_SHIP_STATE);
AssertJUnit.assertEquals("Wrong 'shipState' property value", "capsized", shipStateProp.getValue().getValue());
PrismProperty<Integer> deadProp = taskExtension.findProperty(MY_DEAD);
PrismPropertyValue<Integer> deadPVal = deadProp.getValues().iterator().next();
AssertJUnit.assertEquals("Wrong 'dead' property class", Integer.class, deadPVal.getValue().getClass());
AssertJUnit.assertEquals("Wrong 'dead' property value", Integer.valueOf(42), deadPVal.getValue());
// The progress should be 0, as there were no changes yet
AssertJUnit.assertEquals(0, task.getProgress());
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
AssertJUnit.assertNotNull(taskResult);
assertTrue("Task result is not a success, it is "+taskResult, taskResult.isSuccess());
final Object tokenAfter = findSyncToken(task);
display("Sync token after", tokenAfter.toString());
lastSyncToken = (Integer)tokenAfter;
checkAllShadows();
// Try without options. The results should NOT be there
// MID-4670
task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result);
taskResult = task.getResult();
AssertJUnit.assertNull("Unexpected task result", taskResult);
}
/**
* Create LDAP object. That should be picked up by liveSync and a user
* should be created in repo.
*/
@Test
public void test301LiveSyncCreate() throws Exception {
final String TEST_NAME = "test301LiveSyncCreate";
displayTestTitle(TEST_NAME);
// Sync task should be running (tested in previous test), so just create
// new LDAP object.
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
final Object tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore.toString());
// WHEN
displayWhen(TEST_NAME);
Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_FILENAME);
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 2, result);
// THEN
displayThen(TEST_NAME);
// Search for the user that should be created now
UserType user = searchUserByName(WILL_NAME);
PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName());
assertNotNull(user.getLinkRef());
assertFalse(user.getLinkRef().isEmpty());
// AssertJUnit.assertEquals(user.getName(), WILL_NAME);
// TODO: more checks
assertAndStoreSyncTokenIncrement(syncCycle, 2);
checkAllShadows();
}
@Test
public void test302LiveSyncModify() throws Exception {
final String TEST_NAME = "test302LiveSyncModify";
displayTestTitle(TEST_NAME);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
// WHEN
display("Modifying LDAP entry");
ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_WILL_MODIFY_FILE);
// THEN
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result);
// Search for the user that should be created now
UserType user = searchUserByName (WILL_NAME);
// AssertJUnit.assertEquals(WILL_NAME, user.getName());
PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName());
PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName());
assertAndStoreSyncTokenIncrement(syncCycle, 1);
checkAllShadows();
}
@Test
public void test303LiveSyncLink() throws Exception {
final String TEST_NAME = "test303LiveSyncLink";
displayTestTitle(TEST_NAME);
// GIVEN
assertNoRepoCache();
PrismObject<UserType> user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE);
UserType userType = user.asObjectable();
final String userOid = userType.getOid();
// Encrypt e's password
protector.encrypt(userType.getCredentials().getPassword().getValue());
// create user in repository
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<String> oidHolder = new Holder<>();
display("Adding user object", userType);
addObjectViaModelWS(userType, null, oidHolder, resultHolder);
//check results
assertNoRepoCache();
displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT);
TestUtil.assertSuccess("addObject has failed", resultHolder.value);
// AssertJUnit.assertEquals(userOid, oidHolder.value);
//WHEN
displayWhen(TEST_NAME);
//create account for e which should be correlated
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
Entry entry = openDJController.addEntryFromLdifFile(LDIF_E_FILENAME_LINK);
display("Entry from LDIF", entry);
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result);
// THEN
displayThen(TEST_NAME);
//check user and account ref
userType = searchUserByName("e");
List<ObjectReferenceType> accountRefs = userType.getLinkRef();
assertEquals("Account ref not found, or found too many", 1, accountRefs.size());
//check account defined by account ref
String accountOid = accountRefs.get(0).getOid();
ShadowType account = searchAccountByOid(accountOid);
assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName());
assertAndStoreSyncTokenIncrement(syncCycle, 1);
checkAllShadows();
}
/**
* Create LDAP object. That should be picked up by liveSync and a user
* should be created in repo.
* Also location (ldap l) should be updated through outbound
*/
@Test
public void test304LiveSyncCreateNoLocation() throws Exception {
final String TEST_NAME = "test304LiveSyncCreateNoLocation";
displayTestTitle(TEST_NAME);
// Sync task should be running (tested in previous test), so just create
// new LDAP object.
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result);
AssertJUnit.assertNotNull(syncCycle);
int tokenBefore = findSyncToken(syncCycle);
display("Sync token before", tokenBefore);
// WHEN
Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_WITHOUT_LOCATION_FILENAME);
display("Entry from LDIF", entry);
// THEN
// Wait a bit to give the sync cycle time to detect the change
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 3, result, 60000);
// Search for the user that should be created now
final String userName = "wturner1";
UserType user = searchUserByName(userName);
List<ObjectReferenceType> accountRefs = user.getLinkRef();
assertEquals("Account ref not found, or found too many", 1, accountRefs.size());
//check account defined by account ref
String accountOid = accountRefs.get(0).getOid();
ShadowType account = searchAccountByOid(accountOid);
assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName());
// assertEquals("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName());
Collection<String> localities = getAttributeValues(account, new QName(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS.getNamespaceURI(), "l"));
assertNotNull("null value list for attribute 'l'", localities);
assertEquals("unexpected number of values of attribute 'l'", 1, localities.size());
assertEquals("Locality doesn't match", "middle of nowhere", localities.iterator().next());
assertAndStoreSyncTokenIncrement(syncCycle, 3);
checkAllShadows();
}
private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) {
final Object tokenAfter = findSyncToken(syncCycle);
display("Sync token after", tokenAfter.toString());
int tokenAfterInt = (Integer)tokenAfter;
int expectedToken = lastSyncToken + increment;
lastSyncToken = tokenAfterInt;
assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt);
}
private int findSyncToken(Task syncCycle) {
return (Integer)findSyncTokenObject(syncCycle);
}
private Object findSyncTokenObject(Task syncCycle) {
Object token = null;
PrismProperty<?> tokenProperty = syncCycle.getExtensionOrClone().findProperty(SchemaConstants.SYNC_TOKEN);
if (tokenProperty != null) {
Collection<?> values = tokenProperty.getRealValues();
if (values.size() > 1) {
throw new IllegalStateException("Too must values in token "+tokenProperty);
}
token = values.iterator().next();
}
return token;
}
/**
* Not really a test. Just cleans up after live sync.
*/
@Test
public void test399LiveSyncCleanup() throws Exception {
final String TEST_NAME = "test399LiveSyncCleanup";
displayTestTitle(TEST_NAME);
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result);
// TODO: check if the task is really stopped
}
@Test
public void test400ImportFromResource() throws Exception {
final String TEST_NAME = "test400ImportFromResource";
displayTestTitle(TEST_NAME);
// GIVEN
checkAllShadows();
assertNoRepoCache();
OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting
ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE);
display("Entry from LDIF", entry);
// Let's add an entry with multiple uids.
Entry addEntry = openDJController.addEntryFromLdifFile(LDIF_HERMAN_FILENAME);
display("Entry from LDIF", addEntry);
// WHEN
displayWhen(TEST_NAME);
TaskType taskType = modelWeb.importFromResource(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS);
// THEN
displayThen(TEST_NAME);
assertNoRepoCache();
displayJaxb("importFromResource result", taskType.getResult(), SchemaConstants.C_RESULT);
AssertJUnit.assertEquals("importFromResource has failed", OperationResultStatusType.IN_PROGRESS, taskType.getResult().getStatus());
// Convert the returned TaskType to a more usable Task
Task task = taskManager.createTaskInstance(taskType.asPrismObject(), result);
AssertJUnit.assertNotNull(task);
assertNotNull(task.getOid());
AssertJUnit.assertTrue(task.isAsynchronous());
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
display("Import task after launch", task);
PrismObject<TaskType> tObject = repositoryService.getObject(TaskType.class, task.getOid(), null, result);
TaskType taskAfter = tObject.asObjectable();
display("Import task in repo after launch", taskAfter);
result.computeStatus();
TestUtil.assertSuccess("getObject has failed", result);
final String taskOid = task.getOid();
waitFor("Waiting for import to complete", new Checker() {
@Override
public boolean check() throws CommonException {
Holder<OperationResultType> resultHolder = new Holder<>();
Holder<ObjectType> objectHolder = new Holder<>();
OperationResult opResult = new OperationResult("import check");
assertNoRepoCache();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
try {
modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), taskOid,
options, objectHolder, resultHolder);
} catch (FaultMessage faultMessage) {
throw new SystemException(faultMessage);
}
assertNoRepoCache();
// display("getObject result (wait loop)",resultHolder.value);
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
Task task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), opResult);
System.out.println(new Date() + ": Import task status: " + task.getExecutionStatus() + ", progress: " + task.getProgress());
if (task.getExecutionStatus() == TaskExecutionStatus.CLOSED) {
// Task closed, wait finished
return true;
}
// IntegrationTestTools.display("Task result while waiting: ", task.getResult());
return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 180000);
// wait a second until the task will be definitely saved
Thread.sleep(1000);
//### Check task state after the task is finished ###
Holder<ObjectType> objectHolder = new Holder<>();
Holder<OperationResultType> resultHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
assertNoRepoCache();
modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), task.getOid(),
options, objectHolder, resultHolder);
assertNoRepoCache();
TestUtil.assertSuccess("getObject has failed", resultHolder.value);
task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), result);
display("Import task after finish (fetched from model)", task);
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp());
assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp());
long importDuration = task.getLastRunFinishTimestamp() - task.getLastRunStartTimestamp();
double usersPerSec = (task.getProgress() * 1000) / importDuration;
display("Imported " + task.getProgress() + " users in " + importDuration + " milliseconds (" + usersPerSec + " users/sec)");
OperationResultStatusType taskResultStatus = task.getResultStatus();
AssertJUnit.assertNotNull("Task has no result status", taskResultStatus);
assertEquals("Import task result is not success", OperationResultStatusType.SUCCESS, taskResultStatus);
AssertJUnit.assertTrue("No progress", task.getProgress() > 0);
//### Check if the import created users and shadows ###
// Listing of shadows is not supported by the provisioning. So we need
// to look directly into repository
List<PrismObject<ShadowType>> sobjects = repositoryService.searchObjects(ShadowType.class, null, null, result);
result.computeStatus();
TestUtil.assertSuccess("listObjects has failed", result);
AssertJUnit.assertFalse("No shadows created", sobjects.isEmpty());
for (PrismObject<ShadowType> aObject : sobjects) {
ShadowType shadow = aObject.asObjectable();
display("Shadow object after import (repo)", shadow);
assertNotEmpty("No OID in shadow", shadow.getOid()); // This would be really strange ;-)
assertNotEmpty("No name in shadow", shadow.getName());
AssertJUnit.assertNotNull("No objectclass in shadow", shadow.getObjectClass());
AssertJUnit.assertNotNull("Null attributes in shadow", shadow.getAttributes());
String resourceOid = shadow.getResourceRef().getOid();
if (resourceOid.equals(RESOURCE_OPENDJ_OID)) {
assertAttributeNotNull("No identifier in shadow", shadow, getOpenDjPrimaryIdentifierQName());
} else {
assertAttributeNotNull("No UID in shadow", shadow, SchemaConstants.ICFS_UID);
}
}
Holder<ObjectListType> listHolder = new Holder<>();
assertNoRepoCache();
modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), null, null,
listHolder, resultHolder);
assertNoRepoCache();
ObjectListType uobjects = listHolder.value;
TestUtil.assertSuccess("listObjects has failed", resultHolder.value);
AssertJUnit.assertFalse("No users created", uobjects.getObject().isEmpty());
// TODO: use another account, not guybrush
display("Users after import "+uobjects.getObject().size());
for (ObjectType oo : uobjects.getObject()) {
UserType user = (UserType) oo;
if (SystemObjectsType.USER_ADMINISTRATOR.value().equals(user.getOid())) {
//skip administrator check
continue;
}
display("User after import (repo)", user);
assertNotEmpty("No OID in user", user.getOid()); // This would be
// really
// strange ;-)
assertNotEmpty("No name in user", user.getName());
assertNotNull("No fullName in user", user.getFullName());
assertNotEmpty("No fullName in user", user.getFullName().getOrig());
assertNotEmpty("No familyName in user", user.getFamilyName().getOrig());
// givenName is not mandatory in LDAP, therefore givenName may not
// be present on user
if (user.getName().getOrig().equals(USER_GUYBRUSH_USERNAME)) {
// skip the rest of checks for guybrush, he does not have LDAP account now
continue;
}
assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null ||
user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED);
List<ObjectReferenceType> accountRefs = user.getLinkRef();
AssertJUnit.assertEquals("Wrong accountRef for user " + user.getName(), 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
boolean found = false;
for (PrismObject<ShadowType> aObject : sobjects) {
ShadowType acc = aObject.asObjectable();
if (accountRef.getOid().equals(acc.getOid())) {
found = true;
break;
}
}
if (!found) {
AssertJUnit.fail("accountRef does not point to existing account " + accountRef.getOid());
}
PrismObject<ShadowType> aObject = modelService.getObject(ShadowType.class, accountRef.getOid(), null, task, result);
ShadowType account = aObject.asObjectable();
display("Account after import ", account);
String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account,
new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "l"));
// assertEquals("Unexcpected value of l", "middle of nowhere", attributeValueL);
assertEquals("Unexcpected value of l", getUserLocality(user), attributeValueL);
}
// This also includes "idm" user imported from LDAP. Later we need to ignore that one.
assertEquals("Wrong number of users after import", 10, uobjects.getObject().size());
checkAllShadows();
}
private String getUserLocality(UserType user){
return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere";
}
@Test
public void test420RecomputeUsers() throws Exception {
final String TEST_NAME = "test420RecomputeUsers";
displayTestTitle(TEST_NAME);
// GIVEN
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Assign role to a user, but we do this using a repository instead of model.
// The role assignment will not be executed and this created an inconsistent state.
ObjectDeltaType changeAddRoleCaptain = unmarshallValueFromFile(
REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class);
Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(changeAddRoleCaptain.getItemDelta(),
getUserDefinition());
repositoryService.modifyObject(UserType.class, changeAddRoleCaptain.getOid(), modifications, result);
// TODO: setup more "inconsistent" state
// Add reconciliation task. This will trigger reconciliation
importObjectFromFile(TASK_USER_RECOMPUTE_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task to finish", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, result);
//display("Task while waiting for task manager to pick up the task", task);
// wait until the task is finished
if (TaskExecutionStatus.CLOSED == task.getExecutionStatus()) {
return true;
}
return false;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 40000);
// wait a second until the task will be definitely saved
Thread.sleep(1000);
// Check task status
Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, retrieveTaskResult(), result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after finish", task);
AssertJUnit.assertNotNull(task.getTaskIdentifier());
assertFalse(task.getTaskIdentifier().isEmpty());
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_USER_RECOMPUTE_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus());
// .. and last run should not be zero
assertNotNull(task.getLastRunStartTimestamp());
AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull(task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0);
AssertJUnit.assertEquals(10, task.getProgress());
// Test for presence of a result. It should be there and it should
// indicate success
OperationResult taskResult = task.getResult();
display("Recompute task result", taskResult);
AssertJUnit.assertNotNull(taskResult);
TestUtil.assertSuccess("Recompute task result", taskResult);
// STOP the task. We don't need it any more and we don't want to give it a chance to run more than once
taskManager.deleteTask(TASK_USER_RECOMPUTE_OID, result);
// CHECK RESULT: account created for user guybrush
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> object = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = object.asObjectable();
repoResult.computeStatus();
displayJaxb("User (repository)", repoUser, new QName("user"));
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Wrong number of accountRefs after recompute for user "+repoUser.getName(), 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
OpenDJController.assertAttribute(entry, "title", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
checkAllShadows();
}
@Test
public void test440ReconcileResourceOpenDj() throws Exception {
final String TEST_NAME = "test440ReconcileResourceOpenDj";
displayTestTitle(TEST_NAME);
// GIVEN
final OperationResult result = new OperationResult(TestSanity.class.getName()
+ "." + TEST_NAME);
// Create LDAP account without an owner. The liveSync is off, so it will not be picked up
Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILENAME);
display("Entry from LDIF", ldifEntry);
// Guybrush's attributes were set up by a role in the previous test. Let's mess the up a bit. Recon should sort it out.
List<RawModification> modifications = new ArrayList<>();
// Expect that a correct title will be added to this one
RawModification titleMod = RawModification.create(ModificationType.REPLACE, "title", "Scurvy earthworm");
modifications.add(titleMod);
// Expect that the correct location will replace this one
RawModification lMod = RawModification.create(ModificationType.REPLACE, "l", "Davie Jones' locker");
modifications.add(lMod);
// Expect that this will be untouched
RawModification poMod = RawModification.create(ModificationType.REPLACE, "postOfficeBox", "X marks the spot");
modifications.add(poMod);
ModifyOperation modifyOperation = openDJController.getInternalConnection().processModify(USER_GUYBRUSH_LDAP_DN, modifications);
if (ResultCode.SUCCESS != modifyOperation.getResultCode()) {
AssertJUnit.fail("LDAP operation failed: " + modifyOperation.getErrorMessage());
}
// TODO: setup more "inconsistent" state
// Add reconciliation task. This will trigger reconciliation
repoAddObjectFromFile(TASK_OPENDJ_RECON_FILENAME, result);
// We need to wait for a sync interval, so the task scanner has a chance
// to pick up this
// task
waitFor("Waiting for task to finish first run", new Checker() {
public boolean check() throws ObjectNotFoundException, SchemaException {
Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result);
display("Task while waiting for task manager to pick up the task", task);
// wait until the task is finished
return task.getLastRunFinishTimestamp() != null;
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 180000);
// Check task status
Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result);
result.computeStatus();
display("getTask result", result);
TestUtil.assertSuccess("getTask has failed", result);
AssertJUnit.assertNotNull(task);
display("Task after pickup", task);
PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_RECON_OID, null, result);
display("Task after pickup in the repository", o.asObjectable());
// .. it should be running
AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
// .. and claimed
// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus());
// .. and last run should not be zero
assertNotNull("Null last run start in recon task", task.getLastRunStartTimestamp());
AssertJUnit.assertFalse("Zero last run start in recon task", task.getLastRunStartTimestamp().longValue() == 0);
assertNotNull("Null last run finish in recon task", task.getLastRunFinishTimestamp());
AssertJUnit.assertFalse("Zero last run finish in recon task", task.getLastRunFinishTimestamp().longValue() == 0);
// The progress should be 0, as there were no changes yet
// [pm] commented out, as progress in recon task is now determined not only using # of changes
//AssertJUnit.assertEquals(0, task.getProgress());
// Test for presence of a result. It was not fetched - so it should NOT be there
OperationResult taskResult = task.getResult();
AssertJUnit.assertNull(taskResult);
// However, the task should indicate success
AssertJUnit.assertEquals(OperationResultStatusType.SUCCESS, task.getResultStatus());
// STOP the task. We don't need it any more and we don't want to give it a chance to run more than once
taskManager.deleteTask(TASK_OPENDJ_RECON_OID, result);
// CHECK RESULT: account for user guybrush should be still there and unchanged
// Check if user object was modified in the repo
OperationResult repoResult = new OperationResult("getObject");
PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult);
UserType repoUser = uObject.asObjectable();
repoResult.computeStatus();
displayJaxb("User (repository)", repoUser, new QName("user"));
List<ObjectReferenceType> accountRefs = repoUser.getLinkRef();
assertEquals("Guybrush has wrong number of accounts", 1, accountRefs.size());
ObjectReferenceType accountRef = accountRefs.get(0);
accountShadowOidGuybrushOpendj = accountRef.getOid();
assertFalse(accountShadowOidGuybrushOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj,
null, repoResult);
ShadowType repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account was created in LDAP
Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", "guybrush");
OpenDJController.assertAttribute(entry, "givenName", "Guybrush");
OpenDJController.assertAttribute(entry, "sn", "Threepwood");
OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood");
OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object. It is not tolerant, therefore the other value should be gone now
OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "sailor");
// "title" is tolerant, so it will retain the original value as well as the one provided by the role
OpenDJController.assertAttribute(entry, "title", "Scurvy earthworm", "Honorable Captain");
OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N");
OpenDJController.assertAttribute(entry, "businessCategory", "cruise");
// No setting for "postOfficeBox", so the value should be unchanged
OpenDJController.assertAttribute(entry, "postOfficeBox", "X marks the spot");
String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Pasword was not set on create", guybrushPassword);
// QueryType query = QueryUtil.createNameQuery(ELAINE_NAME);
// ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(UserType.class, prismContext, UserType.F_NAME, ELAINE_NAME));
ObjectQuery query = ObjectQueryUtil.createNameQuery(ELAINE_NAME, prismContext);
List<PrismObject<UserType>> users = repositoryService.searchObjects(UserType.class, query, null, repoResult);
assertEquals("Wrong number of Elaines", 1, users.size());
repoUser = users.get(0).asObjectable();
repoResult.computeStatus();
displayJaxb("User Elaine (repository)", repoUser, new QName("user"));
assertNotNull(repoUser.getOid());
assertEquals(PrismTestUtil.createPolyStringType(ELAINE_NAME), repoUser.getName());
PrismAsserts.assertEqualsPolyString("wrong repo givenName", "Elaine", repoUser.getGivenName());
PrismAsserts.assertEqualsPolyString("wrong repo familyName", "Marley", repoUser.getFamilyName());
PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Elaine Marley", repoUser.getFullName());
accountRefs = repoUser.getLinkRef();
assertEquals("Elaine has wrong number of accounts", 1, accountRefs.size());
accountRef = accountRefs.get(0);
String accountShadowOidElaineOpendj = accountRef.getOid();
assertFalse(accountShadowOidElaineOpendj.isEmpty());
// Check if shadow was created in the repo
repoResult = new OperationResult("getObject");
repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidElaineOpendj,
null, repoResult);
repoShadowType = repoShadow.asObjectable();
repoResult.computeStatus();
TestUtil.assertSuccess("getObject has failed", repoResult);
displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow"));
assertNotNull(repoShadowType);
assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid());
String accountElainehOpendjEntryUuuid = checkRepoShadow(repoShadow);
// check if account is still in LDAP
entry = openDJController.searchAndAssertByEntryUuid(accountElainehOpendjEntryUuuid);
display("LDAP account", entry);
OpenDJController.assertAttribute(entry, "uid", ELAINE_NAME);
OpenDJController.assertAttribute(entry, "givenName", "Elaine");
OpenDJController.assertAttribute(entry, "sn", "Marley");
OpenDJController.assertAttribute(entry, "cn", "Elaine Marley");
OpenDJController.assertAttribute(entry, "displayName", "Elaine Marley");
// The "l" attribute is assigned indirectly through schemaHandling and
// config object
// FIXME
//OpenDJController.assertAttribute(entry, "l", "middle of nowhere");
// Set by the role
OpenDJController.assertAttribute(entry, "employeeType", "governor");
OpenDJController.assertAttribute(entry, "title", "Governor");
OpenDJController.assertAttribute(entry, "businessCategory", "state");
String elainePassword = OpenDJController.getAttributeValue(entry, "userPassword");
assertNotNull("Password of Elaine has disappeared", elainePassword);
checkAllShadows();
}
@Test
public void test480ListResources() throws Exception {
final String TEST_NAME = "test480ListResources";
displayTestTitle(TEST_NAME);
// GIVEN
OperationResultType result = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(result);
Holder<ObjectListType> objectListHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
// WHEN
modelWeb.searchObjects(ObjectTypes.RESOURCE.getTypeQName(), null, options, objectListHolder, resultHolder);
// THEN
display("Resources", objectListHolder.value);
assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size());
// TODO
for(ObjectType object: objectListHolder.value.getObject()) {
// Marshalling may fail even though the Java object is OK so test for it
String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML);
}
}
@Test
public void test485ListResourcesWithBrokenResource() throws Exception {
TestUtil.displayTestTitle("test485ListResourcesWithBrokenResource");
// GIVEN
Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test410ListResourcesWithBrokenResource");
final OperationResult result = task.getResult();
// WHEN
List<PrismObject<ResourceType>> resources = modelService.searchObjects(ResourceType.class, null, null, task, result);
// THEN
assertNotNull("listObjects returned null list", resources);
for (PrismObject<ResourceType> object : resources) {
ResourceType resource = object.asObjectable();
//display("Resource found",resource);
display("Found " + ObjectTypeUtil.toShortString(resource) + ", result " + (resource.getFetchResult() == null ? "null" : resource.getFetchResult().getStatus()));
assertNotNull(resource.getOid());
assertNotNull(resource.getName());
if (resource.getOid().equals(RESOURCE_BROKEN_OID)) {
assertTrue("No error in fetchResult in " + ObjectTypeUtil.toShortString(resource),
resource.getFetchResult() != null &&
(resource.getFetchResult().getStatus() == OperationResultStatusType.PARTIAL_ERROR ||
resource.getFetchResult().getStatus() == OperationResultStatusType.FATAL_ERROR));
} else {
assertTrue("Unexpected error in fetchResult in " + ObjectTypeUtil.toShortString(resource),
resource.getFetchResult() == null || resource.getFetchResult().getStatus() == OperationResultStatusType.SUCCESS);
}
}
}
@Test
public void test500NotifyChangeCreateAccount() throws Exception{
final String TEST_NAME = "test500NotifyChangeCreateAccount";
displayTestTitle(TEST_NAME);
Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME);
display("Entry from LDIF", ldifEntry);
List<Attribute> attributes = ldifEntry.getAttributes();
List<Attribute> attrs = ldifEntry.getAttribute("entryUUID");
AttributeValue val = null;
if (attrs == null){
for (Attribute a : attributes){
if (a.getName().equals("entryUUID")){
val = a.iterator().next();
}
}
} else{
val = attrs.get(0).iterator().next();
}
String entryUuid = val.toString();
ShadowType anglicaAccount = parseObjectType(new File(ACCOUNT_ANGELIKA_FILENAME), ShadowType.class);
PrismProperty<String> prop = anglicaAccount.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES).getValue().createProperty(
prismContext.definitionFactory().createPropertyDefinition(getOpenDjPrimaryIdentifierQName(), DOMUtil.XSD_STRING));
prop.setRealValue(entryUuid);
anglicaAccount.setResourceRef(ObjectTypeUtil.createObjectRef(RESOURCE_OPENDJ_OID, ObjectTypes.RESOURCE));
display("Angelica shadow: ", anglicaAccount.asPrismObject().debugDump());
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.ADD);
delta.setObjectToAdd(anglicaAccount);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
changeDescription.setObjectDelta(delta);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
PrismObject<ShadowType> modelShadow = modelService.getObject(ShadowType.class, oid, null, taskManager.createTaskInstance(), result);
assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName());
assertAttribute(modelShadow, "uid", "angelika");
assertAttribute(modelShadow, "givenName", "Angelika");
assertAttribute(modelShadow, "sn", "Marley");
assertAttribute(modelShadow, "cn", "Angelika Marley");
}
@Test
public void test501NotifyChangeModifyAccount() throws Exception{
final String TEST_NAME = "test501NotifyChangeModifyAccount";
displayTestTitle(TEST_NAME);
OperationResult parentResult = new OperationResult(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.MODIFY);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
ItemDeltaType mod1 = new ItemDeltaType();
mod1.setModificationType(ModificationTypeType.REPLACE);
ItemPathType path = new ItemPathType(ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceTypeOpenDjrepo.getNamespace(), "givenName")));
mod1.setPath(path);
RawType value = new RawType(prismContext.xnodeFactory().primitive("newAngelika"), prismContext);
mod1.getValue().add(value);
delta.getItemDelta().add(mod1);
delta.setOid(oid);
LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1));
LOGGER.info("delta: {}", DebugUtil.dump(mod1));
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
UserType userAfterSync = userAngelikaAfterSync.asObjectable();
PrismAsserts.assertEqualsPolyString("wrong given name in user angelika", PrismTestUtil.createPolyStringType("newAngelika"), userAfterSync.getGivenName());
}
@Test
public void test502NotifyChangeModifyAccountPassword() throws Exception{
final String TEST_NAME = "test502NotifyChangeModifyAccountPassword";
displayTestTitle(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
String newPassword = "newPassword";
openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword);
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.MODIFY);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
ItemDeltaType passwordDelta = new ItemDeltaType();
passwordDelta.setModificationType(ModificationTypeType.REPLACE);
passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext));
RawType passwordValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(ModelClientUtil.createProtectedString(newPassword)).getSubnode(), prismContext);
passwordDelta.getValue().add(passwordValue);
delta.getItemDelta().add(passwordDelta);
delta.setOid(oid);
LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta));
LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta));
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
// changeDescription.setCurrentShadow(angelicaShadowType);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertSuccess(result);
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
assertUserLdapPassword(userAngelikaAfterSync, newPassword);
}
@Test
public void test503NotifyChangeDeleteAccount() throws Exception{
final String TEST_NAME = "test503NotifyChangeDeleteAccount";
displayTestTitle(TEST_NAME);
PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME);
assertNotNull("User with the name angelika must exist.", userAngelika);
UserType user = userAngelika.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef());
assertEquals("Expected one account ref in user", 1, user.getLinkRef().size());
String oid = user.getLinkRef().get(0).getOid();
ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType();
ObjectDeltaType delta = new ObjectDeltaType();
delta.setChangeType(ChangeTypeType.DELETE);
delta.setObjectType(ShadowType.COMPLEX_TYPE);
delta.setOid(oid);
changeDescription.setObjectDelta(delta);
changeDescription.setOldShadowOid(oid);
changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI);
// WHEN
TaskType task = modelWeb.notifyChange(changeDescription);
// THEN
OperationResult result = OperationResult.createOperationResult(task.getResult());
display(result);
assertTrue(result.isAcceptable());
PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME);
display("User after", userAngelikaAfterSync);
assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync);
UserType userType = userAngelikaAfterSync.asObjectable();
assertNotNull("User with the name angelika must have one link ref.", userType.getLinkRef());
assertEquals("Expected no account ref in user", 0, userType.getLinkRef().size());
}
@Test
public void test999Shutdown() throws Exception {
taskManager.shutdown();
waitFor("waiting for task manager shutdown", new Checker() {
@Override
public boolean check() {
return taskManager.getLocallyRunningTasks(new OperationResult("dummy")).isEmpty();
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, 10000);
AssertJUnit.assertEquals("Some tasks left running after shutdown", new HashSet<Task>(),
new HashSet<>(taskManager.getLocallyRunningTasks(new OperationResult("dummy"))));
}
// TODO: test for missing/corrupt system configuration
// TODO: test for missing sample config (bad reference in expression
// arguments)
private String checkRepoShadow(PrismObject<ShadowType> repoShadow) {
ShadowType repoShadowType = repoShadow.asObjectable();
String uid = null;
boolean hasOthers = false;
List<Object> xmlAttributes = repoShadowType.getAttributes().getAny();
for (Object element : xmlAttributes) {
if (SchemaConstants.ICFS_UID.equals(JAXBUtil.getElementQName(element)) || getOpenDjPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) {
if (uid != null) {
AssertJUnit.fail("Multiple values for ICF UID in shadow attributes");
} else {
uid = ((Element) element).getTextContent();
}
} else if (SchemaConstants.ICFS_NAME.equals(JAXBUtil.getElementQName(element)) || getOpenDjSecondaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) {
// This is OK
} else {
hasOthers = true;
}
}
assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers);
assertNotNull(uid);
return uid;
}
private QName getOpenDjPrimaryIdentifierQName() {
return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME);
}
private QName getOpenDjSecondaryIdentifierQName() {
return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME);
}
private ShadowType searchAccountByOid(final String accountOid) throws Exception {
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<ObjectType> accountHolder = new Holder<>();
SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType();
modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountOid, options, accountHolder, resultHolder);
ObjectType object = accountHolder.value;
TestUtil.assertSuccess("searchObjects has failed", resultHolder.value);
assertNotNull("Account is null", object);
if (!(object instanceof ShadowType)) {
fail("Object is not account.");
}
ShadowType account = (ShadowType) object;
assertEquals(accountOid, account.getOid());
return account;
}
private UserType searchUserByName(String name) throws Exception {
// Document doc = DOMUtil.getDocument();
// Element nameElement = doc.createElementNS(SchemaConstants.C_NAME.getNamespaceURI(),
// SchemaConstants.C_NAME.getLocalPart());
// nameElement.setTextContent(name);
// Element filter = QueryUtil.createEqualFilter(doc, null, nameElement);
//
// QueryType query = new QueryType();
// query.setFilter(filter);
ObjectQuery q = ObjectQueryUtil.createNameQuery(UserType.class, prismContext, name);
QueryType query = prismContext.getQueryConverter().createQueryType(q);
OperationResultType resultType = new OperationResultType();
Holder<OperationResultType> resultHolder = new Holder<>(resultType);
Holder<ObjectListType> listHolder = new Holder<>();
assertNoRepoCache();
modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), query, null, listHolder, resultHolder);
assertNoRepoCache();
ObjectListType objects = listHolder.value;
TestUtil.assertSuccess("searchObjects has failed", resultHolder.value);
AssertJUnit.assertEquals("User not found (or found too many)", 1, objects.getObject().size());
UserType user = (UserType) objects.getObject().get(0);
AssertJUnit.assertEquals(user.getName(), PrismTestUtil.createPolyStringType(name));
return user;
}
private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, int increment,
final OperationResult result) throws Exception {
basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result);
}
private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment,
final OperationResult result) throws Exception {
basicWaitForSyncChangeDetection(syncCycle, tokenBefore, increment, result, 40000);
}
private void basicWaitForSyncChangeDetection(final Task syncCycle, final int tokenBefore, final int increment,
final OperationResult result, int timeout) throws Exception {
waitFor("Waiting for sync cycle to detect change", new Checker() {
@Override
public boolean check() throws CommonException {
syncCycle.refresh(result);
display("SyncCycle while waiting for sync cycle to detect change", syncCycle);
if (syncCycle.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) {
throw new IllegalStateException("Task not runnable: "+syncCycle.getExecutionStatus()+"; "+syncCycle);
}
int tokenNow = findSyncToken(syncCycle);
display("tokenNow = " + tokenNow);
if (tokenNow >= tokenBefore + increment) {
return true;
} else {
return false;
}
}
@Override
public void timeout() {
// No reaction, the test will fail right after return from this
}
}, timeout, WAIT_FOR_LOOP_SLEEP_MILIS);
}
private void setAssignmentEnforcement(AssignmentPolicyEnforcementType enforcementType) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
assumeAssignmentPolicy(enforcementType);
// AccountSynchronizationSettingsType syncSettings = new AccountSynchronizationSettingsType();
// syncSettings.setAssignmentPolicyEnforcement(enforcementType);
// applySyncSettings(SystemConfigurationType.class, syncSettings);
}
private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType assignmentPolicy) throws
ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult("Asserting sync settings");
PrismObject<SystemConfigurationType> systemConfigurationType = repositoryService.getObject(SystemConfigurationType.class,
SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result);
result.computeStatus();
TestUtil.assertSuccess("Asserting sync settings failed (result)", result);
ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.asObjectable().getGlobalAccountSynchronizationSettings();
assertNotNull("globalAccountSynchronizationSettings is null", globalAccountSynchronizationSettings);
AssignmentPolicyEnforcementType assignmentPolicyEnforcement = globalAccountSynchronizationSettings.getAssignmentPolicyEnforcement();
assertNotNull("assignmentPolicyEnforcement is null", assignmentPolicyEnforcement);
assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement);
}
private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException {
LOGGER.trace("Checking all shadows");
System.out.println("Checking all shadows");
ObjectChecker<ShadowType> checker = null;
IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext);
}
public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedObjectClassDefinition objClassDef, QName name) {
String value = getAttributeValue(repoShadow, name);
RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next();
if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)){
return value.toLowerCase();
}
return value;
}
protected <T> void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) {
assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues);
}
protected <T> void assertAttribute(PrismObject<ShadowType> shadow, String attrName, T... expectedValues) {
assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues);
}
}
| bshp/midPoint | testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java | Java | apache-2.0 | 199,213 |
/*
* Copyright 2017 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stroom.security.identity.authenticate;
import stroom.security.identity.authenticate.api.AuthenticationService;
import stroom.util.guice.RestResourcesBinder;
import com.google.inject.AbstractModule;
public final class AuthenticateModule extends AbstractModule {
@Override
protected void configure() {
bind(AuthenticationService.class).to(AuthenticationServiceImpl.class);
RestResourcesBinder.create(binder())
.bind(AuthenticationResourceImpl.class);
}
}
| gchq/stroom | stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/authenticate/AuthenticateModule.java | Java | apache-2.0 | 1,110 |
<?php
namespace DCarbone\PHPFHIRGenerated\STU3\FHIRElement;
/*!
* This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using
* class definitions from HL7 FHIR (https://www.hl7.org/fhir/)
*
* Class creation date: December 26th, 2019 15:43+0000
*
* PHPFHIR Copyright:
*
* Copyright 2016-2019 Daniel Carbone ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* FHIR Copyright Notice:
*
* Copyright (c) 2011+, HL7, 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 HL7 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.
*
*
* Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1
*
* Note: the schemas & schematrons do not contain all of the rules about what makes resources
* valid. Implementers will still need to be familiar with the content of the specification and with
* any profiles that apply to the resources in order to make a conformant implementation.
*
*/
use DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList;
use DCarbone\PHPFHIRGenerated\STU3\FHIRElement;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTypeInterface;
/**
* Different measurement principle supported by the device.
* If the element is present, it must have either a \@value, an \@id, or extensions
*
* Class FHIRMeasmntPrinciple
* @package \DCarbone\PHPFHIRGenerated\STU3\FHIRElement
*/
class FHIRMeasmntPrinciple extends FHIRElement
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE;
const FIELD_VALUE = 'value';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList
*/
protected $value = null;
/**
* Validation map for fields in type MeasmntPrinciple
* @var array
*/
private static $_validationRules = [ ];
/**
* FHIRMeasmntPrinciple Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (is_scalar($data)) {
$this->setValue(new FHIRMeasmntPrincipleList($data));
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIRMeasmntPrinciple::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_VALUE])) {
$this->setValue($data[self::FIELD_VALUE]);
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<MeasmntPrinciple{$xmlns}></MeasmntPrinciple>";
}
/**
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList
*/
public function getValue()
{
return $this->value;
}
/**
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList $value
* @return static
*/
public function setValue($value = null)
{
if (null === $value) {
$this->value = null;
return $this;
}
if ($value instanceof FHIRMeasmntPrincipleList) {
$this->value = $value;
return $this;
}
$this->value = new FHIRMeasmntPrincipleList($value);
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if (null !== ($v = $this->getValue())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_VALUE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_VALUE])) {
$v = $this->getValue();
foreach($validationRules[self::FIELD_VALUE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE, self::FIELD_VALUE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_VALUE])) {
$errs[self::FIELD_VALUE] = [];
}
$errs[self::FIELD_VALUE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_EXTENSION])) {
$v = $this->getExtension();
foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_EXTENSION])) {
$errs[self::FIELD_EXTENSION] = [];
}
$errs[self::FIELD_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIRMeasmntPrinciple;
} elseif (!is_object($type) || !($type instanceof FHIRMeasmntPrinciple)) {
throw new \RuntimeException(sprintf(
'FHIRMeasmntPrinciple::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRElement::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->value)) {
$type->setValue(FHIRMeasmntPrincipleList::xmlUnserialize($children->value));
}
if (isset($attributes->value)) {
$pt = $type->getValue();
if (null !== $pt) {
$pt->setValue((string)$attributes->value);
} else {
$type->setValue((string)$attributes->value);
}
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if (null !== ($v = $this->getValue())) {
$sxe->addAttribute(self::FIELD_VALUE, (string)$v);
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if (null !== ($v = $this->getValue())) {
$a[self::FIELD_VALUE] = $v;
}
return $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
} | dcarbone/php-fhir-generated | src/DCarbone/PHPFHIRGenerated/STU3/FHIRElement/FHIRMeasmntPrinciple.php | PHP | apache-2.0 | 11,892 |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive;
using Xamarin.Forms;
using RxObservable = System.Reactive.Linq.Observable;
using System.Reactive.Linq;
namespace RxApp.XamarinForms
{
public static class Bindings
{
public static IDisposable BindTo(
this IObservable<NavigationStack> This,
RxFormsApplication application,
Func<INavigationViewModel,Page> createPage)
{
var navigationPage = application.MainPage;
var popping = false;
var stack = This
.ObserveOnMainThread()
.Scan(Tuple.Create(RxApp.NavigationStack.Empty, RxApp.NavigationStack.Empty), (acc, navStack) => Tuple.Create(acc.Item2, navStack))
.SelectMany(async x =>
{
var previousNavStack = x.Item1;
var currentNavStack = x.Item2;
var currentPage = (navigationPage.CurrentPage as IReadOnlyViewFor);
var navPageModel = (currentPage != null) ? (currentPage.ViewModel as INavigationViewModel) : null;
var head = currentNavStack.FirstOrDefault();
if (currentNavStack.IsEmpty)
{
// Do nothing. Can only happen on Android. Android handles the stack being empty by
// killing the activity.
}
else if (head == navPageModel)
{
// Do nothing, means the user clicked the back button which we cant intercept,
// so we let forms pop the view, listen for the popping event, and then popped the view model.
}
else if (currentNavStack.Pop().Equals(previousNavStack))
{
var view = createPage(head);
await navigationPage.PushAsync(view, true);
}
else if (previousNavStack.Pop().Equals(currentNavStack))
{
// Programmatic back button was clicked
popping = true;
await navigationPage.PopAsync(true);
popping = false;
}
else if (previousNavStack.Up().Equals(currentNavStack))
{
// Programmatic up button was clicked
popping = true;
await navigationPage.PopToRootAsync(true);
popping = false;
}
return currentNavStack;
})
.Publish();
return Disposable.Compose(
stack.Where(x => x.IsEmpty).Subscribe(_ => application.SendDone()),
// Handle the user clicking the back button
RxObservable.FromEventPattern<NavigationEventArgs>(navigationPage, "Popped")
.Where(_ => !popping)
.Subscribe(e =>
{
var vm = ((e.EventArgs.Page as IReadOnlyViewFor).ViewModel as INavigationViewModel);
vm.Activate.Execute();
vm.Back.Execute();
vm.Deactivate.Execute();
}),
stack.Connect()
);
}
public static IDisposable BindTo<T, TView>(this IObservable<T> This, TView target, Expression<Func<TView, T>> property)
{
return This.BindTo(target, property, Scheduler.MainThreadScheduler);
}
public static IDisposable BindTo(this IObservable<Unit> This, Action action)
{
return This.ObserveOnMainThread().Subscribe(_ => action());
}
public static IDisposable BindTo<T>(this IObservable<T> This, Action<T> action)
{
return This.ObserveOnMainThread().Subscribe(action);
}
public static IDisposable Bind(this IRxCommand This, Button button)
{
return Disposable.Compose(
This.CanExecute.ObserveOnMainThread().Subscribe(x => button.IsEnabled = x),
RxObservable.FromEventPattern(button, "Clicked").InvokeCommand(This)
);
}
}
}
| bordoley/RxApp | RxApp.XamarinForms/Bindings.cs | C# | apache-2.0 | 4,570 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require([
'common',
'lodash',
'moment',
'async',
'text!resource/add_wsdlg.html',
'text!resource/remove_wsdlg.html'
], function (common, _, moment, async, addDlg, removeDlg) {
'use strict';
/* global webidaFs, webidaApp, webidaAuth, webidaHost: true */
var WORKSPACE_PATH = '.profile/workspace.json';
var WORKSPACE_INFO;
//var _menuSettings = $('#menu-settings');
var _wsContents = $('.ws-body');
var _dimming = $('.dimming');
var _uniqId;
function _dimmingOn() {
_dimming.addClass('active');
}
function _dimmingOff() {
_dimming.removeClass('active');
}
function _checkValidWSFile(cb) {
webidaFs.readFile(WORKSPACE_PATH, function (err, data) {
if (err) {
cb('_checkValidWSFile() - readFile Error: ' + err);
} else {
var wsMeta = JSON.parse(data);
var wsMetaCount = Object.keys(wsMeta).length;
_getWSList(function (err, wslist) {
if (err) {
cb('_checkValidWSFile() - _getWSList Error: ' + err);
} else {
var wsCount = wslist.length;
if (wsMetaCount === wsCount) {
cb(null, true);
} else {
cb(null, false);
}
}
});
}
});
}
function _launchIDE(domObj) {
console.log($(domObj).attr('data-wsname'));
var workspace = '?workspace=' + webidaFs.fsid + '/' + domObj.attr('data-wsname');
webidaApp.launchApp('devenv', true, workspace);
}
function _registerDefaultEvent() {
// register dimming cancel event
_dimming.on('click', function () {
_dimming.removeClass('active');
var addWSDlg = $('.add_wsdlg');
var removeWSDlg = $('.remove_wsdlg');
if (addWSDlg) {
addWSDlg.remove();
}
if (removeWSDlg) {
removeWSDlg.remove();
}
});
$('#menu-logo').on('click', function () {
webidaApp.launchApp('desktop', false, null);
});
// register workspace event
$('#menu-ws').on('click', function () {
var wswrap = $('.ws-wrap');
var settingwrap = $('.settings-wrap');
if (wswrap.hasClass('acitve')) {
settingwrap.removeClass('active');
} else {
wswrap.addClass('active');
settingwrap.removeClass('active');
}
});
// register setting event
$('#menu-settings').on('click', function () {
var wswrap = $('.ws-wrap');
var settingwrap = $('.settings-wrap');
if (settingwrap.hasClass('acitve')) {
wswrap.removeClass('active');
} else {
settingwrap.addClass('active');
wswrap.removeClass('active');
}
});
// register logout event
$('#menu-logout').on('click', function () {
_setLogout();
});
// register workspace add event
$('.ws-icon-add').on('click', function () {
_addWSList();
});
}
// WORKSPACE_PATH 파일이 있는지 없는지 여부 확인 후 없으면 생성.
function _initialize() {
_registerDefaultEvent();
webidaFs.exists(WORKSPACE_PATH, function (err, exist) {
if (err) {
console.log('_checkWSFile() - exists Error: ' + err);
}
if (!exist) {
_setWorkspace(function (err) {
if (err) {
console.log(err);
}
_renderWSList();
});
} else {
_checkValidWSFile(function (err, bool) {
if (err) {
console.log(err);
} else {
if (bool) {
_renderWSList();
} else {
console.log('workspace meta-info is invalid.');
_renderWSList();
}
}
});
}
});
}
// WORKSPACE 목록 생성 및 WORKSPACE_PATH에 정보 저장.
function _setWorkspace(cb) {
webidaFs.list('/', function (err, data) {
if (err) {
console.log('setWorkspace() - list Error: ' + err);
cb(err);
} else {
var WSList =
_.chain(data).filter(function (fileObj) {
if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; }
}).map(function (fileObj) { return '/' + fileObj.name; }).value();
webidaFs.stat(WSList, function (err, stats) {
if (err) {
console.log('setWorkspace() - stat Error: ' + err);
cb(err);
} else {
var wsObj = {};
_.forEach(stats, function (fileObj) {
fileObj.birth = '';
fileObj.desc = '';
wsObj[fileObj.name] = fileObj;
});
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(wsObj), function (err) {
if (err) {
console.log('setWorkspace() - writeFile Error: ' + err);
cb(err);
} else {
cb(null, true);
}
});
}
});
}
});
}
// 유니크 id 생성.
function _genUniuqeId() {
_uniqId = _.uniqueId();
return _uniqId;
}
// 로그아웃
function _setLogout() {
webidaAuth.logout(function (err) {
if (err) {
alert('Failed to logout');
} else {
location.href = '//' + webidaHost;
}
});
}
function _getWSList(cb) {
webidaFs.list('/', function (err, data) {
if (err) {
cb(err);
} else {
var WSList =
_.chain(data).filter(function (fileObj) {
if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; }
}).map(function (fileObj) { return '/' + fileObj.name; }).value();
webidaFs.stat(WSList, function (err, stats) {
if (err) {
cb(err);
} else {
cb(null, stats);
}
});
}
});
}
// 프로젝트 목록 얻어오기
function _getPJListPath(WSPath, cb) {
webidaFs.list(WSPath, function (err, pjList) {
if (err) {
cb(err);
} else {
var filteredPJList =
_.chain(pjList).filter(function (file) {
if (!file.name.match('.workspace') && file.isDirectory) {
return true;
}
}).map(function (file) {
return WSPath + '/' + file.name + '/.project/project.json';
}).value();
return cb(null, filteredPJList);
}
});
}
// 프로젝트 목록 그리기
function _renderPJList(domObj) {
var ws = domObj.attr('data-wspath');
var wsRow = domObj.parent();
if (wsRow.hasClass('ws-closed')) {
wsRow.addClass('ws-opened');
wsRow.removeClass('ws-closed');
wsRow.after('<div class="pj-body" data-id="' + wsRow.attr('data-id') + '"></div>');
var proRow = wsRow.next();
_getPJListPath(ws, function (err, pjPathList) {
if (err) {
console.log('_renderPJList() - _getPJListPath Error: ' + err);
} else {
_.forEach(pjPathList, function (pjPath) {
webidaFs.exists(pjPath, function (err, exist) {
if (err) {
console.log('_renderPJList() - exists Error: ' + err);
}
if (exist) {
webidaFs.readFile(pjPath, function (err, data) {
if (err) {
console.log('_renderPJList() - read Error: ' + err);
} else {
var projInfo = JSON.parse(data);
/* jshint maxlen : 200 */
var template =
'<div class="pj-row"">' +
'<div class="pj-content">' +
'<div class="pj-item pj-arrow"></div>' +
'<div class="pj-item pj-name">' + projInfo.name + '</div>' +
'<div class="pj-item pj-ltime"></div>' +
'<div class="pj-item pj-birth">' + moment(projInfo.created).fromNow() + '</div>' +
'<div class="pj-item pj-desc">' + projInfo.description + '</div>' +
'</div>' +
'<div class="pj-content-icon">' +
'</div>' +
'</div>';
/* jshint maxlen:120 */
proRow.append(template);
}
});
}
});
});
}
});
} else {
var projRow = wsRow.next();
if (projRow.hasClass('pj-body') && (projRow.attr('data-id') === wsRow.attr('data-id'))) {
projRow.remove();
wsRow.removeClass('ws-opened');
wsRow.addClass('ws-closed');
}
}
}
// 워크스페이스 목록 그리기
function _renderWSList() {
if (_wsContents.children.length) {
_wsContents.empty();
}
webidaFs.readFile(WORKSPACE_PATH, function (err, data) {
if (err) {
console.log('_renderWSList() - readFile Error: ' + err);
} else {
var wsObj = JSON.parse(data);
WORKSPACE_INFO = wsObj;
_.forEach(wsObj, function (ws) {
var id = _genUniuqeId();
var birth = '';
var desc = '';
if (ws.birth) {
birth = moment(ws.birth).fromNow();
}
if (ws.desc) {
desc = ws.desc;
}
/* jshint maxlen : 200 */
var template =
'<div class="ws-row ws-closed" data-id="' + id + '">' +
'<div class="ws-content" data-wspath="' + ws.path + '">' +
'<div class="ws-item ws-arrow"></div>' +
'<div class="ws-item ws-name">' + ws.name + '</div>' +
'<div class="ws-item ws-ltime">' + moment(ws.mtime).fromNow() + '</div>' +
'<div class="ws-item ws-birth">' + birth + '</div>' +
'<div class="ws-item ws-desc">' + desc + '</div>' +
'</div>' +
'<div class="ws-content-icon">' +
'<div class="ws-launch">' +
'<div class="ws-icon-launch" title="Launch IDE" data-wsname="' + ws.name + '"></div>' +
'</div>' +
'<div class="ws-delete">' +
'<div class="ws-icon-delete" title="Delete Workspace" data-wsname="' + ws.name + '" data-id="' + id + '"></div>' +
'</div>' +
'</div>' +
'</div>';
/* jshint maxlen : 120 */
_wsContents.append(template);
});
// register get project event
$('.ws-body .ws-content').on('click', function (evt) {
var domObj = $(evt.target).parent();
_renderPJList(domObj);
});
// register launch event
$('.ws-icon-launch').on('click', function (evt) {
var domObj = $(evt.target);
_launchIDE(domObj);
});
$('.ws-icon-delete').on('click', function (evt) {
var domObj = $(evt.target);
_removeWSList(domObj);
});
}
});
}
function _addWSList() {
_dimmingOn();
$('body').append(addDlg);
// register dialog close event
$('.adddlg_close').on('click', function () {
$('.add_wsdlg').remove();
_dimmingOff();
});
// input에 포커스
$('#workspace_name').focus();
$('#workspace_name').on('keyup', function () {
var wsname = this.value;
if (wsname) {
$('#adddlg_message').text('');
}
});
// register create workspace event
$('#adddlg_confirm').on('click', function (evt) {
evt.preventDefault();
var wsname = $('#workspace_name').val();
var wsdesc = $('#workspace_desc').val();
var message = $('#adddlg_message');
if (!wsname) {
message.text('Please enter workspace name.');
return;
}
_getWSList(function (err, wslist) {
if (err) {
console.log('_addWSList()' + err);
} else {
var isExist = _.find(wslist, { 'name' : wsname });
if (isExist) {
message.text('\'' + wsname + '\' worskpace is already existed.');
return;
} else {
// create workspace
var WS_META_PATH = wsname + '/.workspace';
var WS_META_FILE = WS_META_PATH + '/workspace.json';
async.waterfall([
function (next) {
webidaFs.createDirectory(wsname, false, function (err) {
if (err) {
next('_addWSList() - 1st createDirectory Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.createDirectory(WS_META_PATH, false, function (err) {
if (err) {
next('_addWSList() - 2nd createDirectory Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.writeFile(WS_META_FILE, '', function (err) {
if (err) {
next('_addWSList() - 1st writeFile Error:' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.stat([wsname], function (err, stats) {
if (err) {
next('_addWSList() - stat Error:' + err);
} else {
stats[0].birth = new Date().toJSON();
stats[0].desc = wsdesc;
WORKSPACE_INFO[wsname] = stats[0];
next();
}
});
},
function (next) {
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) {
if (err) {
next('_addWSList() - 2nd writeFile Error:' + err);
} else {
next();
}
});
}
], function (err) {
if (err) {
console.log(err);
} else {
$('.add_wsdlg').remove();
_dimmingOff();
_renderWSList();
}
});
}
}
});
});
}
function _removeWSList(domObj) {
_dimmingOn();
$('body').append(removeDlg);
$('.removedlg_close').on('click', function () {
$('.remove_wsdlg').remove();
_dimmingOff();
});
var deleteWSname = domObj.attr('data-wsname');
var msg = '<p>This action <strong style="color:#fff">CANNOT</strong> be undone. ' +
'This will delete the <span style="color:#fff; font-weight:bold;">' +
deleteWSname + '</span> workspace and projects permanetly.</p>' +
'<p>Please type in the name of the workspace to confirm.</p>';
$('.removedlg_warning_text').html(msg);
// input에 포커스
$('#workspace_name').focus();
$('#workspace_name').on('keyup', function () {
var wsname = this.value;
if (wsname) {
$('#removedlg_message').text('');
}
});
$('#removedlg_confirm').on('click', function (evt) {
evt.preventDefault();
var wsname = $('#workspace_name').val();
var message = $('#removedlg_message');
if (!wsname) {
message.text('Please enter workspace name.');
return;
} else if (wsname !== deleteWSname) {
message.text('workspace name doesn\'t match.');
return;
}
if (WORKSPACE_INFO[deleteWSname]) {
delete WORKSPACE_INFO[deleteWSname];
async.waterfall([
function (next) {
webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) {
if (err) {
err('_removeWSList() - writeFile Error: ' + err);
} else {
next();
}
});
},
function (next) {
webidaFs.delete(deleteWSname, true, function (err) {
if (err) {
next('_removeWSList() - delete Error:' + err);
} else {
next();
}
});
}
], function (err) {
if (err) {
console.log(err);
} else {
var id = domObj.attr('data-id');
var selectorWS = '.ws-row[data-id=' + id + ']';
var selectorProj = '.pj-body[data-id=' + id + ']';
$(selectorWS).remove();
if ($(selectorProj)) {
$(selectorProj).remove();
}
$('.remove_wsdlg').remove();
_dimmingOff();
}
});
}
});
}
common.getFS(function (exist) {
if (exist) {
_initialize();
} else {
location.href = '//' + webidaHost;
}
});
});
| 5hk/webida-client | apps/dashboard/src/js/main_bak.js | JavaScript | apache-2.0 | 22,004 |
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `KBOOpenData_activity`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_activity`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_activity` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`ActivityGroup` varchar(6) NOT NULL COMMENT '(6)X',
`NaceVersion` enum('2003','2008') NOT NULL,
`NaceCode` varchar(9) NOT NULL COMMENT '(5)9 of (7)9',
`Classification` char(4) NOT NULL COMMENT 'XXXX',
PRIMARY KEY (`EntityNumber`,`ActivityGroup`,`NaceVersion`,`NaceCode`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_address`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_address`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_address` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`TypeOfAddress` char(4) NOT NULL COMMENT 'XXXX',
`CountryNL` varchar(100) DEFAULT NULL COMMENT '100(X)',
`CountryFR` varchar(100) DEFAULT NULL COMMENT '100(X)',
`Zipcode` varchar(20) DEFAULT NULL COMMENT '20(X)',
`MunicipalityNL` varchar(200) DEFAULT NULL COMMENT '200(X)',
`MunicipalityFR` varchar(200) DEFAULT NULL COMMENT '200(X)',
`StreetNL` varchar(200) DEFAULT NULL COMMENT '200(X)',
`StreetFR` varchar(200) DEFAULT NULL COMMENT '200(X)',
`HouseNumber` varchar(22) DEFAULT NULL COMMENT '22(X)',
`Box` varchar(20) DEFAULT NULL COMMENT '20(X)',
`ExtraAddressInfo` varchar(80) DEFAULT NULL COMMENT '80(X)',
`DateStrikingOff` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
PRIMARY KEY (`EntityNumber`,`TypeOfAddress`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_code`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_code`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_code` (
`Category` varchar(255) NOT NULL,
`Code` varchar(255) NOT NULL,
`Language` enum('DE','EN','FR','NL') NOT NULL,
`Description` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_contact`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_contact`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_contact` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`EntityContact` varchar(3) NOT NULL COMMENT '(3)X',
`ContactType` varchar(5) NOT NULL COMMENT '5(X)',
`Value` varchar(254) NOT NULL COMMENT '(254)X',
PRIMARY KEY (`EntityNumber`,`EntityContact`,`ContactType`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_denomination`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_denomination`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_denomination` (
`EntityNumber` varchar(13) NOT NULL COMMENT '9999.999.999 of 9.999.999.999',
`Language` char(1) NOT NULL COMMENT 'X',
`TypeOfDenomination` char(3) NOT NULL COMMENT 'XXX',
`Denomination` varchar(320) NOT NULL COMMENT '(320)X',
PRIMARY KEY (`EntityNumber`,`TypeOfDenomination`,`Language`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_enterprise`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_enterprise`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_enterprise` (
`EnterpriseNumber` varchar(12) NOT NULL COMMENT '9999.999.999',
`Status` char(2) NOT NULL COMMENT 'XX',
`JuridicalSituation` char(3) NOT NULL COMMENT 'XXX',
`TypeOfEnterprise` char(1) NOT NULL COMMENT 'X',
`JuridicalForm` char(3) DEFAULT NULL COMMENT 'XXX',
`StartDate` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
PRIMARY KEY (`EnterpriseNumber`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_establishment`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_establishment`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_establishment` (
`EstablishmentNumber` varchar(13) NOT NULL DEFAULT '' COMMENT '9.999.999.999',
`StartDate` char(10) NOT NULL COMMENT 'XX-XX-XXXX',
`EnterpriseNumber` varchar(12) NOT NULL COMMENT '9999.999.999',
PRIMARY KEY (`EstablishmentNumber`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_meta`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_meta`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_meta` (
`Variable` varchar(255) NOT NULL,
`Value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Variable`),
UNIQUE KEY `metaUnique` (`Variable`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for `KBOOpenData_mutationlog`
-- ----------------------------
-- DROP TABLE IF EXISTS `KBOOpenData_mutationlog`;
CREATE TABLE IF NOT EXISTS `KBOOpenData_mutationlog` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`tableName` varchar(64) NOT NULL,
`recordKey` varchar(32) NOT NULL,
`data_old` text,
`data_new` text,
`action` enum('insert','update','delete') NOT NULL,
`mutationTimestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=ARCHIVE AUTO_INCREMENT=64756 DEFAULT CHARSET=utf8;
| TomLous/datatools | v1/lib/Tool/KBOOpenData/sql/db-000.sql | SQL | apache-2.0 | 5,288 |
package com.example.android.bluetoothlegatt.ble_service;
/**
* @author Sopheak Tuon
* @created on 04-Oct-17
*/
import java.util.Locale;
public class CountryUtils {
public static boolean getMonthAndDayFormate() {
Locale locale = Locale.getDefault();
String lang = locale.getLanguage();
String contr = locale.getCountry();
if (lang == null || (!lang.equals("zh") && !lang.equals("ja") && !lang.equals("ko") && (!lang.equals("en") || contr == null || !contr.equals("US")))) {
return false;
}
return true;
}
public static boolean getLanguageFormate() {
String language = Locale.getDefault().getLanguage();
if (language == null || !language.equals("zh")) {
return false;
}
return true;
}
}
| SopheakTuon/Smart-Bracelet | Application/src/main/java/com/example/android/bluetoothlegatt/ble_service/CountryUtils.java | Java | apache-2.0 | 812 |
# coding=utf8
from django.views.generic import ListView, DetailView, CreateView
from django.db.models import Q
from django.http import JsonResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from pure_pagination.mixins import PaginationMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from books.models import Publish, Author, Book
from books.forms import PublishForm
import json
import logging
logger = logging.getLogger('opsweb')
class PublishListView(LoginRequiredMixin, PaginationMixin, ListView):
'''
动作:getlist, create
'''
model = Publish
template_name = "books/publish_list.html"
context_object_name = "publish_list"
paginate_by = 5
keyword = ''
def get_queryset(self):
queryset = super(PublishListView, self).get_queryset()
self.keyword = self.request.GET.get('keyword', '').strip()
if self.keyword:
queryset = queryset.filter(Q(name__icontains=self.keyword) |
Q(address__icontains=self.keyword) |
Q(city__icontains=self.keyword))
return queryset
def get_context_data(self, **kwargs):
context = super(PublishListView, self).get_context_data(**kwargs)
context['keyword'] = self.keyword
return context
def post(self, request):
form = PublishForm(request.POST)
if form.is_valid():
form.save()
res = {'code': 0, 'result': '添加出版商成功'}
else:
# form.errors会把验证不通过的信息以对象的形式传到前端,前端直接渲染即可
res = {'code': 1, 'errmsg': form.errors}
print form.errors
return JsonResponse(res, safe=True)
class PublishDetailView(LoginRequiredMixin, DetailView):
'''
动作:getone, update, delete
'''
model = Publish
template_name = "books/publish_detail.html"
context_object_name = 'publish'
next_url = '/books/publishlist/'
def post(self, request, *args, **kwargs):
pk = kwargs.get('pk')
p = self.model.objects.get(pk=pk)
form = PublishForm(request.POST, instance=p)
if form.is_valid():
form.save()
res = {"code": 0, "result": "更新出版商成功", 'next_url': self.next_url}
else:
res = {"code": 1, "errmsg": form.errors, 'next_url': self.next_url}
return render(request, settings.JUMP_PAGE, res)
# return HttpResponseRedirect(reverse('books:publish_detail',args=[pk]))
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
# 通过出版社对象查所在该出版社的书籍,如果有关联书籍不可以删除,没有关联书籍可以删除
try:
obj = self.model.objects.get(pk=pk)
if not obj.book_set.all():
self.model.objects.filter(pk=pk).delete()
res = {"code": 0, "result": "删除出版商成功"}
else:
res = {"code": 1, "errmsg": "该出版社有关联书籍,请联系管理员"}
except:
res = {"code": 1, "errmsg": "删除错误请联系管理员"}
return JsonResponse(res, safe=True)
| 1032231418/python | lesson10/apps/books/publish/__init__.py | Python | apache-2.0 | 3,345 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.workmailmessageflow.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.workmailmessageflow.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* MessageRejectedException JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MessageRejectedExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller {
private MessageRejectedExceptionUnmarshaller() {
super(com.amazonaws.services.workmailmessageflow.model.MessageRejectedException.class, "MessageRejected");
}
@Override
public com.amazonaws.services.workmailmessageflow.model.MessageRejectedException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {
com.amazonaws.services.workmailmessageflow.model.MessageRejectedException messageRejectedException = new com.amazonaws.services.workmailmessageflow.model.MessageRejectedException(
null);
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return messageRejectedException;
}
private static MessageRejectedExceptionUnmarshaller instance;
public static MessageRejectedExceptionUnmarshaller getInstance() {
if (instance == null)
instance = new MessageRejectedExceptionUnmarshaller();
return instance;
}
}
| aws/aws-sdk-java | aws-java-sdk-workmailmessageflow/src/main/java/com/amazonaws/services/workmailmessageflow/model/transform/MessageRejectedExceptionUnmarshaller.java | Java | apache-2.0 | 2,934 |
<!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_75) on Sat May 16 22:22:30 CEST 2015 -->
<title>StreamMessage.Type</title>
<meta name="date" content="2015-05-16">
<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="StreamMessage.Type";
}
//-->
</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-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/streaming/messages/StreamMessage.Type.html" target="_top">Frames</a></li>
<li><a href="StreamMessage.Type.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: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li><a href="#field_detail">Field</a> | </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">org.apache.cassandra.streaming.messages</div>
<h2 title="Enum StreamMessage.Type" class="title">Enum StreamMessage.Type</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.streaming.messages.StreamMessage.Type</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">StreamMessage.Type</span>
extends java.lang.Enum<<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>></pre>
<div class="block">StreamMessage types</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#COMPLETE">COMPLETE</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#FILE">FILE</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#PREPARE">PREPARE</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#RECEIVED">RECEIVED</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#RETRY">RETRY</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#SESSION_FAILED">SESSION_FAILED</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- =========== 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"> </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><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#inSerializer">inSerializer</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#outSerializer">outSerializer</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#priority">priority</a></strong></code> </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"> </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>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#get(byte)">get</a></strong>(byte type)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="PREPARE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PREPARE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> PREPARE</pre>
</li>
</ul>
<a name="FILE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>FILE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> FILE</pre>
</li>
</ul>
<a name="RECEIVED">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RECEIVED</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> RECEIVED</pre>
</li>
</ul>
<a name="RETRY">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RETRY</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> RETRY</pre>
</li>
</ul>
<a name="COMPLETE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>COMPLETE</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> COMPLETE</pre>
</li>
</ul>
<a name="SESSION_FAILED">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SESSION_FAILED</h4>
<pre>public static final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> SESSION_FAILED</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="priority">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>priority</h4>
<pre>public final int priority</pre>
</li>
</ul>
<a name="inSerializer">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inSerializer</h4>
<pre>public final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>> inSerializer</pre>
</li>
</ul>
<a name="outSerializer">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>outSerializer</h4>
<pre>public final <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages">StreamMessage.Serializer</a><<a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.html" title="class in org.apache.cassandra.streaming.messages">StreamMessage</a>> outSerializer</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (StreamMessage.Type c : StreamMessage.Type.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
<a name="get(byte)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre>public static <a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Type.html" title="enum in org.apache.cassandra.streaming.messages">StreamMessage.Type</a> get(byte type)</pre>
</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-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/streaming/messages/StreamMessage.Serializer.html" title="interface in org.apache.cassandra.streaming.messages"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/streaming/messages/StreamMessage.Type.html" target="_top">Frames</a></li>
<li><a href="StreamMessage.Type.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: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| sayanh/ViewMaintenanceCassandra | doc/org/apache/cassandra/streaming/messages/StreamMessage.Type.html | HTML | apache-2.0 | 18,851 |
"use strict";
var router_1 = require('@angular/router');
var authorize_component_1 = require('./authorize/authorize-component');
var user_component_1 = require('./User/user-component');
var welcome_component_1 = require('./welcome-component');
exports.routes = [
{ path: '', component: welcome_component_1.welcome },
{ path: 'login', component: authorize_component_1.AuthorizeComponent },
{ path: 'dashboard', component: user_component_1.UserComponent },
];
exports.APP_ROUTER_PROVIDERS = [
router_1.provideRouter(exports.routes)
];
//# sourceMappingURL=app.route.js.map | devilsuraj/openiddict-samples | Samples/resource-owner-password-credential/Angualar2-Client-ROPC/app/app.route.js | JavaScript | apache-2.0 | 586 |
<?php
namespace Home\Controller;
class EmptyController extends HomeController{
public function _empty($action){
$resource = strtolower(CONTROLLER_NAME);
$this->assign('type', $resource);
if(in_array($resource, array('text', 'picture', 'music', 'video'))){
if(in_array($action, array('new', 'edit'))){
if('edit' == $action){
$id = intval(I('id'));
if($post = M('post')->find($id))
$this->assign('post', $post);
else
$this->error('错误的记录');
}
$this->display('Post/'.$resource);
}else{
$this->error('错误的请求');
}
}else{
switch (strtolower(CONTROLLER_NAME)) {
case 'post':
echo 'post';die;
$Index = new IndexController();
$Index->detail(ACTION_NAME);
break;
case 'search':
$Index = new IndexController();
$Index->search();
break;
case 'feed':
$type = I('get.type');
$this->feed($type);
break;
case 'mine':
if(!is_login())
$this->error('尚未登录,请登录后再访问', "User/login");
$Index = new IndexController();
$Index->mine();
break;
default:
$Index = new IndexController();
if (is_numeric(CONTROLLER_NAME) && is_numeric(ACTION_NAME)) {
$Index->archive(CONTROLLER_NAME,ACTION_NAME);
}else{
$this->error('错误的请求');
}
break;
}
}
}
} | cokeboL/freeblog | App/Home/Controller/EmptyController.class.php | PHP | apache-2.0 | 1,592 |
/*
* Copyright 2015 Suprema([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <UIKit/UIKit.h>
@interface TimeCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *expireTimeLabel;
@end
| BioStar2/BioStar2IOS | BiostarMobile/BiostarMobile/Classes/Popup/Cells/TimeCell.h | C | apache-2.0 | 869 |
<?php
/*------------------------------------------------------------------------
# TZ Portfolio Extension
# ------------------------------------------------------------------------
# author DuongTVTemPlaza
# copyright Copyright (C) 2012 templaza.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.templaza.com
# Technical Support: Forum - http://templaza.com/Forum
-------------------------------------------------------------------------*/
defined('_JEXEC') or die();
$item = $this -> item;
$media = $this -> listMedia;
$params = $this -> mediaParams;
if($params -> get('portfolio_image_size','S')){
if(!empty($media[0] -> images)){
$src = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),'_'.$params -> get('portfolio_image_size','S')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
}
}
?>
<?php if($media):?>
<?php if($media[0] -> type == 'image'):?>
<?php
$src2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),
'_'.$params -> get('detail_article_image_size','XL')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
?>
<?php if($params -> get('show_image',1) == 1 AND !empty($media[0] -> images)):?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $src;?>" data-largesrc="<?php echo$src2;?>"
alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"
title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php if($media[0] -> type == 'imagegallery'):?>
<?php
$srcGallery2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),
'_'.$params -> get('detail_article_image_gallery_size','XL')
.'.'.JFile::getExt($media[0] -> images),$media[0] -> images);
?>
<?php if($params -> get('show_image_gallery',1) == 1 AND !empty($media[0] -> images)):?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $src;?>" data-largesrc="<?php echo $srcGallery2;?>"
alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"
title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php
if($media[0] -> type == 'video'):
if($params -> get('show_video',1) == 1 AND !empty($media[0] -> thumb)):
$srcVideo = str_replace('.'.JFile::getExt($media[0] -> thumb),'_'
.$params -> get('portfolio_image_size','M')
.'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb);
$srcVideo2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> thumb),
'_'.$params -> get('detail_article_image_size','XL')
.'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb);
?>
<a class="ib-image" href="<?php echo $item ->link;?>">
<img src="<?php echo $srcVideo;?>"
data-largesrc="<?php echo $srcVideo2;?>"
title="<?php echo $media[0] -> imagetitle;?>"
alt="<?php echo $media[0] -> imagetitle;?>"/>
<span><?php echo $item -> title;?></span>
</a>
<?php endif;?>
<?php endif;?>
<?php endif;?> | doomchocolate/dreame-mall | templates/tz_dreame/html/com_tz_portfolio/gallery/default_media.php | PHP | apache-2.0 | 4,020 |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Gallio.Model.Filters
{
internal class FilterToken
{
private readonly FilterTokenType type;
private readonly string text;
private readonly int position;
internal FilterToken(FilterTokenType type, string text, int position)
{
this.type = type;
this.text = text;
this.position = position;
}
public FilterTokenType Type
{
get { return type; }
}
public string Text
{
get { return text; }
}
public int Position
{
get { return position; }
}
}
}
| citizenmatt/gallio | src/Gallio/Gallio/Model/Filters/FilterToken.cs | C# | apache-2.0 | 1,333 |
package org.jetbrains.plugins.scala.lang.psi.api.base
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement
/**
* @author Alexander Podkhalyuzin
* Date: 22.02.2008
*/
trait ScIdList extends ScalaPsiElement {
def fieldIds: Seq[ScFieldId]
} | gtache/intellij-lsp | intellij-lsp-dotty/src/org/jetbrains/plugins/scala/lang/psi/api/base/ScIdList.scala | Scala | apache-2.0 | 249 |
<?php
/**
* Unbind ...
*
* @phpstub
*
* @param resource $connection
* @param string $trigger_name
*
* @return bool
*/
function cyrus_unbind($connection, $trigger_name)
{
} | schmittjoh/php-stubs | res/php/cyrus/functions/cyrus-unbind.php | PHP | apache-2.0 | 182 |
ngDefine(
'cockpit.plugin.statistics-plugin.controllers',
function(module) {
module
.controller(
'processDefinitionCtrl',
[
'$scope',
'DataFactory',
'Uri',
function($scope, DataFactory, Uri) {
$scope.options = {
chart : {
type : 'pieChart',
height : 500,
x : function(d) {
return d.key;
},
y : function(d) {
return d.y;
},
showLabels : true,
transitionDuration : 500,
labelThreshold : 0.01,
tooltips : true,
tooltipContent : function(key, y, e, graph) {
if (key == "finished") {
return '<h3>' + key + '</h3>' + '<p>count:<b>' + y
+ '</b><br/>' + 'average Duration:<b>'
+ (e.point.avg / 1000 / 60).toFixed(2)
+ ' min</b><br/>minimal Duration:<b>'
+ (e.point.min / 1000 / 60).toFixed(2)
+ ' min</b><br/>maximal Duration:<b>'
+ (e.point.max / 1000 / 60).toFixed(2)
+ ' min</b></p>'
} else {
return '<h3>' + key + '</h3>' + '<p>' + y + '</p>'
}
},
noData : "No Processes met the requirements",
legend : {
margin : {
top : 5,
right : 5,
bottom : 5,
left : 5
}
}
}
};
DataFactory
.getAllProcessInstanceCountsByState(
$scope.processDefinition.key)
.then(
function() {
var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key];
var counts = [];
counts
.push({
"key" : "running",
"y" : processDefinitionCounts[0].runningInstanceCount
});
counts
.push({
"key" : "failed",
"y" : processDefinitionCounts[0].failedInstanceCount
});
counts
.push({
"key" : "finished",
"y" : processDefinitionCounts[0].endedInstanceCount,
"avg" : processDefinitionCounts[0].duration,
"min" : processDefinitionCounts[0].minDuration,
"max" : processDefinitionCounts[0].maxDuration
});
$scope.statesOfDefinition = counts;
});
} ]);
}); | nagyistoce/camunda-cockpit-plugin-statistics | src/main/resources/plugin-webapp/statistics-plugin/app/controllers/processDefinitionCtrl.js | JavaScript | apache-2.0 | 3,679 |
# Pedicularis rotundifolia C.E.C.Fisch. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Pedicularis/Pedicularis rotundifolia/README.md | Markdown | apache-2.0 | 187 |
/* Copyright 2015 ETH Zurich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include "Mutex.h"
#include "PathState.h"
#include "Utils.h"
/* calculate the cubic root of x using a table lookup followed by one
* Newton-Raphson iteration.
* Avg err ~= 0.195%
*
* Taken (and slightly modified) from Linux TCP Cubic implementation
*/
static uint32_t cubeRoot(uint64_t a)
{
uint32_t x, b, shift;
uint64_t c;
/*
* cbrt(x) MSB values for x MSB values in [0..63].
* Precomputed then refined by hand - Willy Tarreau
*
* For x in [0..63],
* v = cbrt(x << 18) - 1
* cbrt(x) = (v[x] + 10) >> 6
*/
static const uint8_t v[] = {
/* 0x00 */ 0, 54, 54, 54, 118, 118, 118, 118,
/* 0x08 */ 123, 129, 134, 138, 143, 147, 151, 156,
/* 0x10 */ 157, 161, 164, 168, 170, 173, 176, 179,
/* 0x18 */ 181, 185, 187, 190, 192, 194, 197, 199,
/* 0x20 */ 200, 202, 204, 206, 209, 211, 213, 215,
/* 0x28 */ 217, 219, 221, 222, 224, 225, 227, 229,
/* 0x30 */ 231, 232, 234, 236, 237, 239, 240, 242,
/* 0x38 */ 244, 245, 246, 248, 250, 251, 252, 254,
};
/* Probably not the fastest way but works without using asm */
b = 0;
c = a;
while (c >>= 1)
b++;
b++;
if (b < 7) {
/* a in [0..63] */
return ((uint32_t)v[(uint32_t)a] + 35) >> 6;
}
b = ((b * 84) >> 8) - 1;
shift = (a >> (b * 3));
x = ((uint32_t)(((uint32_t)v[shift] + 10) << b)) >> 6;
/*
* Newton-Raphson iteration
* 2
* x = ( 2 * x + a / x ) / 3
* k+1 k k
*/
x = 2 * x + (uint32_t)(a / ((uint64_t)x * (uint64_t)(x - 1)));
x = ((x * 341) >> 10);
return x;
}
PathState::PathState(int rtt, int mtu)
: mPathIndex(-1),
mMTU(mtu),
mSRTT(rtt),
mLastRTT(rtt),
mSendWindow(2),
mCongestionWindow(1),
mWindow(1),
mInFlight(0),
mCurrentBurst(0),
mInLoss(false),
mTotalSent(0),
mTotalAcked(0),
mLastTotalAcked(0),
mTotalLost(0),
mAverageLossInterval(0)
{
mVAR = rtt >> VAR_SHIFT;
mRTO = mSRTT + (mVAR << 2);
mSRTT = 0; // initial RTT estimate used for RTO only
memset(mLossBursts, 0, sizeof(mLossBursts));
Mutex mMutex;
}
PathState::~PathState()
{
}
void PathState::setIndex(int index)
{
mPathIndex = index;
}
void PathState::setRemoteWindow(uint32_t sendWindow)
{
mSendWindow = sendWindow;
DEBUG("send window set to %d\n", mSendWindow);
}
int PathState::timeUntilReady()
{
return 0;
}
int PathState::bandwidth()
{
if (mSRTT == 0)
return 0;
return mWindow * mMTU / mSRTT * 1000000;
}
int PathState::estimatedRTT() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mSRTT;
mMutex.Unlock();
return ret;
}
int PathState::getRTO() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mRTO;
mMutex.Unlock();
return ret;
}
int PathState::packetsInFlight() EXCLUDES(mMutex)
{
int ret;
mMutex.Lock();
ret = mInFlight;
mMutex.Unlock();
return ret;
}
double PathState::getLossRate() EXCLUDES(mMutex)
{
mMutex.Lock();
uint64_t currentInterval = mTotalAcked - mLastTotalAcked;
if (currentInterval > mAverageLossInterval) {
if (currentInterval > 2 * mAverageLossInterval)
calculateLoss(ALI_HISTORY_DISCOUNTING);
else
calculateLoss(ALI_FROM_INTERVAL_0);
}
mMutex.Unlock();
if (mAverageLossInterval == 0)
return 0.0;
return 1.0 / mAverageLossInterval;
}
void PathState::addLoss(uint64_t packetNum) EXCLUDES(mMutex)
{
mTotalLost++;
mMutex.Lock();
mInFlight--;
mMutex.Unlock();
mCurrentBurst++;
mInLoss = true;
if (mCurrentBurst == SSP_MAX_LOSS_BURST) {
mLossBursts[SSP_MAX_LOSS_BURST - 1]++;
mCurrentBurst = 0;
mInLoss = false;
}
}
void PathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMutex)
{
mTotalAcked++;
mMutex.Lock();
mInFlight--;
DEBUG("path %d: receive ack: %d packets now in flight\n", mPathIndex, mInFlight);
if (rtt > 0) {
mLastRTT = rtt;
if (mSRTT == 0) {
mSRTT = rtt;
mVAR = rtt >> 1;
} else {
int err = rtt - mSRTT;
mSRTT += err >> ERR_SHIFT;
err = err >= 0 ? err : -err;
mVAR += (err - mVAR) >> VAR_SHIFT;
}
mRTO = mSRTT + (mVAR << 2);
if (mRTO > SSP_MAX_RTO)
mRTO = SSP_MAX_RTO;
DEBUG("path %d: RTT sample %d us, sRTT = %d us, RTO = %d us\n", mPathIndex, rtt, mSRTT, mRTO);
}
if (mInLoss) {
mLossBursts[mCurrentBurst]++;
mCurrentBurst = 0;
mInLoss = false;
}
mMutex.Unlock();
}
void PathState::addRetransmit() EXCLUDES(mMutex)
{
mMutex.Lock();
mLossIntervals.push_front(mTotalAcked - mLastTotalAcked);
if (mLossIntervals.size() > MAX_LOSS_INTERVALS)
mLossIntervals.pop_back();
DEBUG("loss on path %d: new loss interval = %ld, %d/%d in flight\n",
mPathIndex, mTotalAcked - mLastTotalAcked, mInFlight, mWindow);
mLastTotalAcked = mTotalAcked;
calculateLoss(ALI_FROM_INTERVAL_1);
mMutex.Unlock();
}
void PathState::handleSend(uint64_t packetNum) EXCLUDES(mMutex)
{
mMutex.Lock();
mInFlight++;
mTotalSent++;
DEBUG("path %d: send: %d/%d packets now in flight\n", mPathIndex, mInFlight, mWindow);
mMutex.Unlock();
}
void PathState::handleTimeout() EXCLUDES(mMutex)
{
mMutex.Lock();
mRTO = mRTO << 1;
if (mRTO > SSP_MAX_RTO)
mRTO = SSP_MAX_RTO;
DEBUG("timeout: new rto = %d\n", mRTO);
mMutex.Unlock();
}
void PathState::handleDupAck()
{
}
void PathState::calculateLoss(ALIType type)
{
if (mLossIntervals.empty())
return;
uint64_t currentInterval = mTotalAcked - mLastTotalAcked;
size_t i;
list<uint64_t>::iterator it;
size_t n = mLossIntervals.size();
double ws = 0.0;
double w = 0.0;
double d[MAX_LOSS_INTERVALS + 1];
double di = 2.0 * mAverageLossInterval / currentInterval;
double wi;
DEBUG("calculate average loss interval (%d), currentInterval = %ld\n", type, currentInterval);
if (di < 0.5)
di = 0.5;
for (i = 0; i <= MAX_LOSS_INTERVALS; i++)
d[i] = 1.0;
switch (type) {
case ALI_HISTORY_DISCOUNTING:
for (i = 1; i < MAX_LOSS_INTERVALS; i++)
d[i] = di;
case ALI_FROM_INTERVAL_0:
mLossIntervals.push_front(currentInterval);
case ALI_FROM_INTERVAL_1:
for (it = mLossIntervals.begin(), i = 1; it != mLossIntervals.end() && i < MAX_LOSS_INTERVALS; it++, i++) {
if (i <= n / 2) {
ws += d[i - 1] * (*it);
w += d[i - 1];
} else {
wi = 1 - (i - n / 2.0) / (n / 2.0 + 1);
ws += d[i - 1] * wi * (*it);
w += d[i - 1] * wi;
}
}
break;
default:
break;
}
if (type != ALI_FROM_INTERVAL_1)
mLossIntervals.pop_front();
mAverageLossInterval = ws / w;
DEBUG("average loss interval = %ld\n", mAverageLossInterval);
}
bool PathState::isWindowBased()
{
return false;
}
int PathState::window()
{
return 0;
}
int PathState::profileLoss()
{
double p, q;
int m = 0;
for (int i = 1; i < SSP_MAX_LOSS_BURST; i++)
m += mLossBursts[i];
p = (double)m / mTotalAcked;
int mi1 = 0, mi2 = 0;
for (int i = 2; i < SSP_MAX_LOSS_BURST; i++)
mi2 += mLossBursts[i] * (i - 1);
for (int i = 1; i < SSP_MAX_LOSS_BURST; i++)
mi1 += mLossBursts[i] * i;
q = 1 - (double)mi2 / mi1;
printf("p = %f, q = %f\n", p, q);
return 0;
}
// CBR
CBRPathState::CBRPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mSendInterval(SSP_SEND_INTERVAL)
{
memset(&mLastSendTime, 0, sizeof(mLastSendTime));
}
int CBRPathState::timeUntilReady()
{
if (mLastSendTime.tv_sec == 0)
return 0;
struct timeval current;
gettimeofday(¤t, NULL);
DEBUG("%ld us since last send\n", elapsedTime(&mLastSendTime, ¤t));
int time = mSendInterval - elapsedTime(&mLastSendTime, ¤t);
if (time < 0)
time = 0;
return time;
}
int CBRPathState::bandwidth()
{
return mMTU / mSendInterval * 1000000;
}
void CBRPathState::handleSend(uint64_t packetNum)
{
PathState::handleSend(packetNum);
gettimeofday(&mLastSendTime, NULL);
}
// PCC
PCCPathState::PCCPathState(int rtt, int mtu)
: CBRPathState(rtt, mtu),
mLastSendInterval(SSP_SEND_INTERVAL),
mMonitorRTT(0.0),
mMonitorReceived(0),
mMonitorLost(0),
mMonitoring(false),
mUtility(0.0),
mCurrentTrial(0),
mAdjustCount(0),
mDirection(0),
mState(PCC_START)
{
memset(&mMonitorStartTime, 0, sizeof(mMonitorStartTime));
memset(&mMonitorEndTime, 0, sizeof(mMonitorEndTime));
memset(mTrialResults, 0, sizeof(mTrialResults));
memset(mTrialIntervals, 0, sizeof(mTrialIntervals));
Mutex mMonitorMutex;
}
int PCCPathState::timeUntilReady()
{
int currentInterval = mSendInterval;
if (mState == PCC_DECISION)
mSendInterval = mTrialIntervals[mCurrentTrial];
int res = CBRPathState::timeUntilReady();
mSendInterval = currentInterval;
return res;
}
void PCCPathState::handleSend(uint64_t packetNum) EXCLUDES(mMonitorMutex)
{
struct timeval t;
gettimeofday(&t, NULL);
CBRPathState::handleSend(packetNum);
if (!mMonitoring) {
DEBUG("%ld.%06ld: current state = %d, begin monitoring\n", t.tv_sec, t.tv_usec, mState);
mMonitorStartTime = t;
srand(t.tv_usec);
double x = (double)rand() / RAND_MAX; // 0 ~ 1.0
x /= 2.0; // 0 ~ 0.5
x += 1.7; // 1.7 ~ 2.2
mMonitorDuration = x * mSRTT;
if (mMonitorDuration < PCC_MIN_PACKETS * mSendInterval)
mMonitorDuration = PCC_MIN_PACKETS * mSendInterval;
mMonitorRTT = 0;
mMonitorReceived = 0;
mMonitorLost = 0;
mMonitoring = true;
}
if (mMonitoring) {
if (elapsedTime(&mMonitorStartTime, &t) < mMonitorDuration ) {
mMonitorMutex.Lock();
mMonitoredPackets.insert(packetNum);
mMonitorMutex.Unlock();
}
}
}
void PCCPathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMonitorMutex)
{
PathState::addRTTSample(rtt, packetNum);
if (mMonitoring) {
bool found = false;
mMonitorMutex.Lock();
found = mMonitoredPackets.find(packetNum) != mMonitoredPackets.end();
mMonitorMutex.Unlock();
if (found) {
mMonitorReceived++;
mMonitorRTT += rtt;
DEBUG("current state = %d: got ack %ld\n", mState, packetNum);
}
}
struct timeval t;
gettimeofday(&t, NULL);
if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT)
handleMonitorEnd();
}
void PCCPathState::addLoss(uint64_t packetNum)
{
PathState::addLoss(packetNum);
struct timeval t;
gettimeofday(&t, NULL);
if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT)
handleMonitorEnd();
}
void PCCPathState::handleMonitorEnd() EXCLUDES(mMonitorMutex)
{
if (!mMonitoring)
return;
mMonitorMutex.Lock();
gettimeofday(&mMonitorEndTime, NULL);
DEBUG("%ld.%06ld: monitor end\n", mMonitorEndTime.tv_sec, mMonitorEndTime.tv_usec);
long monitorTime = elapsedTime(&mMonitorStartTime, &mMonitorEndTime);
if (mMonitorReceived == 0) {
mMonitorRTT = SSP_MAX_RTO;
} else {
mMonitorRTT /= mMonitorReceived;
}
DEBUG("%lu packets sent during this interval, %lu received\n", mMonitoredPackets.size(), mMonitorReceived);
mMonitorLost = mMonitoredPackets.size() - mMonitorReceived;
double u = utility(mMonitorReceived, mMonitorLost, monitorTime / 1000000.0, mMonitorRTT);
DEBUG("utility %f\n", u);
if (mState == PCC_DECISION) {
DEBUG("decision phase, trial %d\n", mCurrentTrial);
mTrialResults[mCurrentTrial++] = u;
if (mCurrentTrial == PCC_TRIALS) {
int direction = 0;
for (int i = 0; i < PCC_TRIALS - 1; i += 2) {
if (mTrialIntervals[i] < mSendInterval) {
// i: shorter period, i + 1: longer period
if (mTrialResults[i] > mTrialResults[i + 1])
direction--;
else if (mTrialResults[i] < mTrialResults[i + 1])
direction++;
} else {
// i: longer period, i + 1: shorter period
if (mTrialResults[i] > mTrialResults[i + 1])
direction++;
else if (mTrialResults[i] < mTrialResults[i + 1])
direction--;
}
}
if (direction == 0) {
DEBUG("inconclusive, do over with larger deltas\n");
mAdjustCount++;
if (mAdjustCount > PCC_MAX_ADJUST_COUNT)
mAdjustCount = PCC_MAX_ADJUST_COUNT;
startDecision();
} else {
mDirection = direction / 2; // direction = +-2, mDirection = +-1
mState = PCC_ADJUST;
mLastSendInterval = mSendInterval;
mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE;
DEBUG("switched to adjust phase, direction = %d with %d us period\n", mDirection, mSendInterval);
}
}
} else if (mState == PCC_ADJUST) {
if (u >= mUtility) {
mAdjustCount++;
if (mAdjustCount > PCC_MAX_ADJUST_COUNT)
mAdjustCount = PCC_MAX_ADJUST_COUNT;
mLastSendInterval = mSendInterval;
mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE;
DEBUG("utility increased, keep going in direction %d with %d us period\n", mDirection, mSendInterval);
} else {
mSendInterval = mLastSendInterval;
mAdjustCount = 1;
DEBUG("utility decreased, drop back to decision phase with %d us period\n", mSendInterval);
startDecision();
}
mUtility = u;
} else if (mState == PCC_START) {
if (u >= mUtility) {
mLastSendInterval = mSendInterval;
mSendInterval /= 2;
DEBUG("utility increased, double speed: %d us period\n", mSendInterval);
} else {
mSendInterval = mLastSendInterval;
mAdjustCount = 1;
DEBUG("utility decreased, drop down to decision phase with %d us period\n", mSendInterval);
startDecision();
}
mUtility = u;
}
if (mSendInterval > SSP_MAX_SEND_INTERVAL)
mSendInterval = SSP_MAX_SEND_INTERVAL;
mMonitoredPackets.clear();
mMonitoring = false;
if (mMonitorReceived == 0)
mSendInterval *= 2;
mMonitorMutex.Unlock();
}
void PCCPathState::startDecision()
{
srand(time(NULL));
for (int i = 0; i < PCC_TRIALS - 1; i += 2) {
int delta = (rand() % 2) * 2 - 1;
delta *= mAdjustCount * PCC_ADJUST_RATE * mSendInterval;
mTrialIntervals[i] = mSendInterval + delta;
mTrialIntervals[i + 1] = mSendInterval - delta;
}
mCurrentTrial = 0;
mState = PCC_DECISION;
}
double PCCPathState::utility(int received, int lost, double time, double rtt)
{
DEBUG("%d %d %f %f\n", received, lost, time, rtt);
//utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))-1*l/time);
//utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))* (1-1/(1+exp(-10*(1-previous_rtt/rtt)))) -1*l/time)/rtt*1000;
return received / time * (1 - 1 / (1 + exp(-100 * (lost / (received + lost) - 0.05)))) - lost / time;
}
// TCP Reno
RenoPathState::RenoPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mState(TCP_STATE_START),
mThreshold(-1),
mDupAckCount(0),
mAckCount(0)
{
}
int RenoPathState::timeUntilReady()
{
if (mInFlight < mWindow) {
DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow);
return 0;
} else {
DEBUG("path %d: window full, wait about 1 RTT (%d us)\n", mPathIndex, mSRTT);
return mSRTT ? mSRTT : mRTO;
}
}
void RenoPathState::handleTimeout()
{
PathState::handleTimeout();
mState = TCP_STATE_TIMEOUT;
mCongestionWindow = 1;
DEBUG("path %d: timeout: congestion window set to 1\n", mPathIndex);
}
void RenoPathState::handleDupAck()
{
mDupAckCount++;
if (mState > SSP_FR_THRESHOLD && mState == TCP_STATE_FAST_RETRANSMIT) {
mCongestionWindow++;
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: duplicate ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
}
void RenoPathState::addRTTSample(int rtt, uint64_t packetNum)
{
PathState::addRTTSample(rtt, packetNum);
mDupAckCount = 0;
mAckCount++;
switch (mState) {
case TCP_STATE_START:
case TCP_STATE_TIMEOUT:
DEBUG("path %d: slow start: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1);
mCongestionWindow++;
if (mCongestionWindow == mThreshold) {
DEBUG("path %d: reached threshold: %d\n", mPathIndex, mThreshold);
mState = TCP_STATE_NORMAL;
}
break;
case TCP_STATE_FAST_RETRANSMIT:
mState = TCP_STATE_NORMAL;
mCongestionWindow = mThreshold;
break;
case TCP_STATE_NORMAL:
if (mAckCount == mCongestionWindow) {
DEBUG("path %d: congestion avoidance: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1);
mAckCount = 0;
mCongestionWindow++;
}
break;
default:
break;
}
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
void RenoPathState::addRetransmit()
{
PathState::addRetransmit();
mThreshold = mWindow >> 1;
if (mThreshold < 2)
mThreshold = 2;
mAckCount = 0;
if (mState != TCP_STATE_TIMEOUT && mState != TCP_STATE_FAST_RETRANSMIT) {
mState = TCP_STATE_FAST_RETRANSMIT;
mCongestionWindow = mThreshold + 3;
}
mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow;
DEBUG("path %d: packet loss: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
bool RenoPathState::isWindowBased()
{
return true;
}
int RenoPathState::window()
{
return mWindow;
}
// TCP CUBIC
CUBICPathState::CUBICPathState(int rtt, int mtu)
: PathState(rtt, mtu),
mThreshold(-1),
mTimeout(false)
{
reset();
}
int CUBICPathState::timeUntilReady() EXCLUDES(mMutex)
{
mMutex.Lock();
if (mInFlight < mWindow) {
DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow);
mMutex.Unlock();
return 0;
} else {
DEBUG("path %d: window full (%d/%d), wait about 1 RTT (%d us)\n", mPathIndex, mInFlight, mWindow, mSRTT);
mMutex.Unlock();
return mSRTT ? mSRTT : mRTO;
}
}
void CUBICPathState::addRTTSample(int rtt, uint64_t packetNum)
{
PathState::addRTTSample(rtt, packetNum);
if (rtt == 0)
return;
mTimeout = false;
if (mMinDelay == 0 || mMinDelay > rtt)
mMinDelay = rtt;
mAckCount++;
int thresh = mThreshold > 0 ? mThreshold : CUBIC_SSTHRESH;
if (mCongestionWindow < thresh) {
mCongestionWindow++;
DEBUG("path %d: slow start, increase to %d\n", mPathIndex, mCongestionWindow);
} else {
update();
DEBUG("path %d: congestion avoidance (%d/%d)\n", mPathIndex, mWindowCount, mCount);
if (mWindowCount > mCount) {
mCongestionWindow++;
DEBUG("path %d: increase window to %d\n", mPathIndex, mCongestionWindow);
mWindowCount = 0;
} else {
mWindowCount++;
}
}
mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow;
DEBUG("path %d: ack received: window set to %d (%d|%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow);
}
void CUBICPathState::addRetransmit() EXCLUDES(mMutex)
{
PathState::addRetransmit();
mEpochStart = 0;
if (mCongestionWindow < mMaxWindow)
mMaxWindow = mCongestionWindow * (2 - BETA) / 2;
else
mMaxWindow = mCongestionWindow;
mCongestionWindow *= (1 - BETA);
if (mCongestionWindow < 1)
mCongestionWindow = 1;
mThreshold = mCongestionWindow;
if (mTimeout)
mCongestionWindow = 1;
mMutex.Lock();
mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow;
mMutex.Unlock();
DEBUG("path %d: packet loss: window set to %d (last max window %d)\n", mPathIndex, mWindow, mMaxWindow);
}
void CUBICPathState::handleSend(uint64_t packetNum)
{
PathState::handleSend(packetNum);
}
void CUBICPathState::handleTimeout()
{
PathState::handleTimeout();
mTimeout = true;
mThreshold = (1 - BETA) * mCongestionWindow;
reset();
DEBUG("path %d: timeout: congestion window dropped to 1\n", mPathIndex);
}
void CUBICPathState::reset()
{
mWindowCount = 0;
mAckCount = 0;
mMinDelay = 0;
mMaxWindow = 0;
mTCPWindow = 0;
mOrigin = 0;
mCount = 0;
mK = 0;
mEpochStart = 0;
}
void CUBICPathState::doTCPFriendly()
{
mTCPWindow += 3 * BETA / (2 - BETA) * mAckCount / mCongestionWindow;
mAckCount = 0;
if (mTCPWindow > mCongestionWindow) {
if (mCount > mCongestionWindow / (mTCPWindow - mCongestionWindow))
mCount = mCongestionWindow / (mTCPWindow - mCongestionWindow);
}
}
void CUBICPathState::update()
{
time_t timestamp = time(NULL);
if (mEpochStart == 0) {
mEpochStart = timestamp;
if (mCongestionWindow < mMaxWindow) {
mK = cubeRoot((mMaxWindow - mCongestionWindow) / C);
mOrigin = mMaxWindow;
} else {
mK = 0;
mOrigin = mCongestionWindow;
}
mAckCount = 1;
mTCPWindow = mCongestionWindow;
}
int t = timestamp + mMinDelay / 1000000 - mEpochStart;
int x = t - mK;
int target = mOrigin + C * x * x * x;
if (target > mCongestionWindow)
mCount = mCongestionWindow / (target - mCongestionWindow);
else
mCount = 100 * mCongestionWindow;
doTCPFriendly();
}
bool CUBICPathState::isWindowBased()
{
return true;
}
int CUBICPathState::window()
{
return mWindow;
}
| dmpiergiacomo/scion | c/ssp/PathState.cpp | C++ | apache-2.0 | 23,627 |
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { UserData } from './user-data';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
@Injectable()
export class ConferenceData {
data: any;
constructor(public http: Http, public user: UserData) { }
load(): any {
if (this.data) {
return Observable.of(this.data);
} else {
return this.http.get('assets/data/data.json')
.map(this.processData, this);
}
}
processData(data: any) {
// just some good 'ol JS fun with objects and arrays
// build up the data by linking employees to sessions
this.data = data.json();
this.data.tracks = [];
// loop through each day in the schedule
this.data.schedule.forEach((day: any) => {
// loop through each timeline group in the day
day.groups.forEach((group: any) => {
// loop through each session in the timeline group
group.sessions.forEach((session: any) => {
session.employees = [];
if (session.employeeNames) {
session.employeeNames.forEach((employeeName: any) => {
let employee = this.data.employees.find((s: any) => s.name === employeeName);
if (employee) {
session.employees.push(employee);
employee.sessions = employee.sessions || [];
employee.sessions.push(session);
}
});
}
if (session.tracks) {
session.tracks.forEach((track: any) => {
if (this.data.tracks.indexOf(track) < 0) {
this.data.tracks.push(track);
}
});
}
});
});
});
return this.data;
}
getTimeline(dayIndex: number, queryText = '', excludeTracks: any[] = [], segment = 'all') {
return this.load().map((data: any) => {
let day = data.schedule[dayIndex];
day.shownSessions = 0;
queryText = queryText.toLowerCase().replace(/,|\.|-/g, ' ');
let queryWords = queryText.split(' ').filter(w => !!w.trim().length);
day.groups.forEach((group: any) => {
group.hide = true;
group.sessions.forEach((session: any) => {
// check if this session should show or not
this.filterSession(session, queryWords, excludeTracks, segment);
if (!session.hide) {
// if this session is not hidden then this group should show
group.hide = false;
day.shownSessions++;
}
});
});
return day;
});
}
filterSession(session: any, queryWords: string[], excludeTracks: any[], segment: string) {
let matchesQueryText = false;
if (queryWords.length) {
// of any query word is in the session name than it passes the query test
queryWords.forEach((queryWord: string) => {
if (session.name.toLowerCase().indexOf(queryWord) > -1) {
matchesQueryText = true;
}
});
} else {
// if there are no query words then this session passes the query test
matchesQueryText = true;
}
// if any of the sessions tracks are not in the
// exclude tracks then this session passes the track test
let matchesTracks = false;
session.tracks.forEach((trackName: string) => {
if (excludeTracks.indexOf(trackName) === -1) {
matchesTracks = true;
}
});
// if the segement is 'favorites', but session is not a user favorite
// then this session does not pass the segment test
let matchesSegment = false;
if (segment === 'favorites') {
if (this.user.hasFavorite(session.name)) {
matchesSegment = true;
}
} else {
matchesSegment = true;
}
// all tests must be true if it should not be hidden
session.hide = !(matchesQueryText && matchesTracks && matchesSegment);
}
getEmployees() {
return this.load().map((data: any) => {
return data.employees.sort((a: any, b: any) => {
let aName = a.name.split(' ').pop();
let bName = b.name.split(' ').pop();
return aName.localeCompare(bName);
});
});
}
getTracks() {
return this.load().map((data: any) => {
return data.tracks.sort();
});
}
getMap() {
return this.load().map((data: any) => {
return data.map;
});
}
}
| josephjohn136/logonfly | Ionic/src/providers/conference-data.ts | TypeScript | apache-2.0 | 4,422 |
/**
* Red Hat Open Innovation Labs API
* A generic model to support automation at all levels of the application and infrastructure lifecycle.
*
* OpenAPI spec version: 0.3.0-alpha
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Port'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Port'));
} else {
// Browser globals (root is window)
if (!root.RedHatOpenInnovationLabsApi) {
root.RedHatOpenInnovationLabsApi = {};
}
root.RedHatOpenInnovationLabsApi.Service = factory(root.RedHatOpenInnovationLabsApi.ApiClient, root.RedHatOpenInnovationLabsApi.Port);
}
}(this, function(ApiClient, Port) {
'use strict';
/**
* The Service model module.
* @module model/Service
* @version 0.3.0-alpha
*/
/**
* Constructs a new <code>Service</code>.
* @alias module:model/Service
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>Service</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Service} obj Optional instance to populate.
* @return {module:model/Service} The populated <code>Service</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('ports')) {
obj['ports'] = ApiClient.convertToType(data['ports'], [Port]);
}
}
return obj;
}
/**
* @member {Number} id
*/
exports.prototype['id'] = undefined;
/**
* @member {String} name
*/
exports.prototype['name'] = undefined;
/**
* @member {Array.<module:model/Port>} ports
*/
exports.prototype['ports'] = undefined;
return exports;
}));
| priley86/labs-console | app/automation/model/Service.js | JavaScript | apache-2.0 | 3,193 |
package nl.esciencecenter.e3dchem.modifiedtanimoto;
import org.knime.base.util.flowvariable.FlowVariableProvider;
import org.knime.core.data.DataTableSpec;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.util.CheckUtils;
import org.knime.distance.category.DistanceCategoryConfig;
import org.knime.distance.util.propertyresolver.Configuration;
import org.knime.distance.util.propertyresolver.Property;
@Configuration
public final class ModifiedTanimotoDistanceConfig extends
DistanceCategoryConfig<ModifiedTanimotoDistance> {
@Property("meanBitDensity")
private double meanBitDensity = 0.01;
/**
* Framework constructor.
*/
ModifiedTanimotoDistanceConfig() {
}
public ModifiedTanimotoDistanceConfig(final double meanBitDensity,
String column) throws InvalidSettingsException {
super(column);
this.meanBitDensity = meanBitDensity;
CheckUtils.checkSetting(meanBitDensity >= 0,
"mean bit density is not positive: %f ", meanBitDensity);
}
@Override
protected DistanceCategoryConfig<?> clone(String... columns)
throws InvalidSettingsException {
CheckUtils.checkSetting(columns != null && columns.length == 1,
"Exactly one column must be selected.");
return new ModifiedTanimotoDistanceConfig(meanBitDensity, columns[0]);
}
@Override
public String getFactoryId() {
return ModifiedTanimotoDistanceFactory.ID;
}
/**
* {@inheritDoc}
*/
@Override
public ModifiedTanimotoDistance createDistanceMeasure(DataTableSpec spec,
FlowVariableProvider flowVariableProvider)
throws InvalidSettingsException {
return new ModifiedTanimotoDistance(this, spec);
}
public double getMeanBitDensity() {
return meanBitDensity;
}
public void setMeanBitDensity(final double meanBitDensity) {
this.meanBitDensity = meanBitDensity;
}
}
| 3D-e-Chem/knime-modified-tanimoto | nl.esciencecenter.e3dchem.modifiedtanimoto/src/nl/esciencecenter/e3dchem/modifiedtanimoto/ModifiedTanimotoDistanceConfig.java | Java | apache-2.0 | 1,815 |
# Zygophyllum novae-zeelandiae Steud. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Zygophyllales/Zygophyllaceae/Zygophyllum/Zygophyllum novae-zeelandiae/README.md | Markdown | apache-2.0 | 185 |
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using RElmah.Common.Model;
using RElmah.Errors;
using RElmah.Services.Nulls;
namespace RElmah.Services.Inbox
{
public class SerializedErrorsInbox : IErrorsInbox
{
private readonly IErrorsBacklog _errorsBacklog;
private readonly Subject<ErrorPayload> _errors;
private readonly IObservable<ErrorPayload> _publishedErrors;
public SerializedErrorsInbox() : this(NullErrorsBacklog.Instance) { }
public SerializedErrorsInbox(IErrorsBacklog errorsBacklog)
{
_errorsBacklog = errorsBacklog;
_errors = new Subject<ErrorPayload>();
_publishedErrors = _errors.Publish().RefCount();
}
public Task Post(ErrorPayload payload)
{
return _errorsBacklog
.Store(payload)
.ContinueWith(_ => _errors.OnNext(payload));
}
public IObservable<ErrorPayload> GetErrorsStream()
{
return _publishedErrors;
}
}
}
| wasphub/RElmah | relmah/src/RElmah/Services/Inbox/SerializedErrorsInbox.cs | C# | apache-2.0 | 1,105 |
# Lichtheimia hongkongensis K.Y. Yuen, 2009 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Fungi/Zygomycota/Mucorales/Lichtheimiaceae/Lichtheimia/Lichtheimia ramosa/ Syn. Lichtheimia hongkongensis/README.md | Markdown | apache-2.0 | 198 |
# AUTOGENERATED FILE
FROM balenalib/orange-pi-one-debian:buster-run
ENV NODE_VERSION 15.14.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "1cef461a73a124dd3f212e2b8230638f4d16b5cc0915425ffad8aabac050d9fb node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/node/orange-pi-one/debian/buster/15.14.0/run/Dockerfile | Dockerfile | apache-2.0 | 2,945 |
#!/usr/bin/env sh
set -e
exit 0
SCALA_VERSION=${SCALA_VERSION:-2_12}
sbt \
grpcRuntimeJVM${SCALA_VERSION}/mimaReportBinaryIssues \
lensesJVM${SCALA_VERSION}/mimaReportBinaryIssues \
runtimeJVM${SCALA_VERSION}/mimaReportBinaryIssues \
compilerPluginJVM${SCALA_VERSION}/mimaReportBinaryIssues
| trueaccord/ScalaPB | mima.sh | Shell | apache-2.0 | 294 |
#!/usr/bin/env bash
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#
#
# A script to run multiple GPU tests in parallel controlled with an environment
# variable.
#
# Required environment variables:
# TF_GPU_COUNT = Number of GPUs available.
TF_GPU_COUNT=${TF_GPU_COUNT:-4}
TF_TESTS_PER_GPU=${TF_TESTS_PER_GPU:-8}
# We want to allow running one of the following configs:
# - 4 tests per GPU on k80
# - 8 tests per GPU on p100
# p100 has minimum 12G memory. Therefore, we should limit each test to 1.5G.
# To leave some room in case we want to run more tests in parallel in the
# future and to use a rounder number, we set it to 1G.
export TF_PER_DEVICE_MEMORY_LIMIT_MB=${TF_PER_DEVICE_MEMORY_LIMIT_MB:-1024}
# *******************************************************************
# This section of the script is needed to
# make things work on windows under msys.
# *******************************************************************
RUNFILES_MANIFEST_FILE="${TEST_SRCDIR}/MANIFEST"
function rlocation() {
if is_absolute "$1" ; then
# If the file path is already fully specified, simply return it.
echo "$1"
elif [[ -e "$TEST_SRCDIR/$1" ]]; then
# If the file exists in the $TEST_SRCDIR then just use it.
echo "$TEST_SRCDIR/$1"
elif [[ -e "$RUNFILES_MANIFEST_FILE" ]]; then
# If a runfiles manifest file exists then use it.
echo "$(grep "^$1 " "$RUNFILES_MANIFEST_FILE" | sed 's/[^ ]* //')"
fi
}
TEST_BINARY="$(rlocation $TEST_WORKSPACE/${1#./})"
shift
# *******************************************************************
mkdir -p /var/lock
# Try to acquire any of the TF_GPU_COUNT * TF_TESTS_PER_GPU
# slots to run a test at.
#
# Prefer to allocate 1 test per GPU over 4 tests on 1 GPU.
# So, we iterate over TF_TESTS_PER_GPU first.
for j in `seq 0 $((TF_TESTS_PER_GPU-1))`; do
for i in `seq 0 $((TF_GPU_COUNT-1))`; do
exec {lock_fd}>/var/lock/gpulock${i}_${j} || exit 1
if flock -n "$lock_fd";
then
(
# This export only works within the brackets, so it is isolated to one
# single command.
export CUDA_VISIBLE_DEVICES=$i
export HIP_VISIBLE_DEVICES=$i
echo "Running test $TEST_BINARY $* on GPU $CUDA_VISIBLE_DEVICES"
"$TEST_BINARY" $@
)
return_code=$?
flock -u "$lock_fd"
exit $return_code
fi
done
done
echo "Cannot find a free GPU to run the test $* on, exiting with failure..."
exit 1
| tensorflow/recommenders-addons | tools/testing/parallel_gpu_execute.sh | Shell | apache-2.0 | 3,086 |
MApps
=====
Mobile App
| cveggalam/MApps | README.md | Markdown | apache-2.0 | 24 |
(function($) {
module("referenceReads1");
// Test case : Reference Reads 1
_asyncTest("Reference Reads 1", function()
{
expect(6);
GitanaTest.authenticateFullOAuth().then(function() {
var platform = this;
// create a few things
var repository = null;
this.createRepository().then(function() {
repository = this;
});
var domain = null;
this.createDomain().then(function() {
domain = this;
});
var registrar = null;
this.createRegistrar().then(function() {
registrar = this;
});
var stack = null;
this.createStack().then(function() {
stack = this;
});
var team = null;
this.then(function() {
this.subchain(stack).createTeam("abc-" + new Date().getTime()).then(function() {
team = this;
});
});
this.then(function() {
var repositoryReference = "repository://" + platform.getId() + "/" + repository.getId();
var domainReference = "domain://" + platform.getId() + "/" + domain.getId();
var registrarReference = "registrar://" + platform.getId() + "/" + registrar.getId();
var stackReference = "stack://" + platform.getId() + "/" + stack.getId();
var teamReference = "team://stack/" + platform.getId() + "/" + stack.getId() + "/" + team.getKey();
var entries = [{
"ref": repositoryReference
}, {
"ref": domainReference
}, {
"ref": registrarReference
}, {
"ref": stackReference
}, {
"ref": teamReference
}];
this.referenceReads(entries, function(results) {
// check that they all came back
ok(results.length == entries.length, "Found the right number of results");
for (var i = 0; i < results.length; i++)
{
ok(results[i].entry, "Found entry #" + i);
}
// done
start();
});
});
});
});
}(jQuery) );
| gitana/gitana-javascript-driver | tests/js/testReferenceReads1.js | JavaScript | apache-2.0 | 2,469 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<title>Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format (ARX API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format (ARX API Documentation)";
}
//-->
</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><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/deidentifier/arx/aggregates/class-use/HierarchyBuilderDate.Format.html" target="_top">Frames</a></li>
<li><a href="HierarchyBuilderDate.Format.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">
<h2 title="Uses of Class org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format" class="title">Uses of Class<br>org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.deidentifier.arx.aggregates">org.deidentifier.arx.aggregates</a></td>
<td class="colLast">
<div class="block">This package provides methods for aggregating data.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.deidentifier.arx.aggregates">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a> that return <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#getFormat()">getFormat</a></strong>()</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/deidentifier/arx/aggregates/package-summary.html">org.deidentifier.arx.aggregates</a> with parameters of type <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilder.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilder</a><java.util.Date></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#create(org.deidentifier.arx.DataType, java.util.TimeZone, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format, java.util.Date, java.util.Date, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Granularity...)">create</a></strong>(<a href="../../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a><java.util.Date> type,
java.util.TimeZone timeZone,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format,
java.util.Date bottomCoding,
java.util.Date topCoding,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Granularity.html" title="enum in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Granularity</a>... granularities)</code>
<div class="block">Creates an hierarchy reflecting the given granularities</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilder.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilder</a><java.util.Date></code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#create(org.deidentifier.arx.DataType, java.util.TimeZone, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format, org.deidentifier.arx.aggregates.HierarchyBuilderDate.Granularity...)">create</a></strong>(<a href="../../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a><java.util.Date> type,
java.util.TimeZone timeZone,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format,
<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Granularity.html" title="enum in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Granularity</a>... granularities)</code>
<div class="block">Creates an hierarchy reflecting the given granularities</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">HierarchyBuilderDate.</span><code><strong><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.html#setFormat(org.deidentifier.arx.aggregates.HierarchyBuilderDate.Format)">setFormat</a></strong>(<a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">HierarchyBuilderDate.Format</a> format)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/deidentifier/arx/aggregates/HierarchyBuilderDate.Format.html" title="class in org.deidentifier.arx.aggregates">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/deidentifier/arx/aggregates/class-use/HierarchyBuilderDate.Format.html" target="_top">Frames</a></li>
<li><a href="HierarchyBuilderDate.Format.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>
| jgaupp/arx | doc/api/org/deidentifier/arx/aggregates/class-use/HierarchyBuilderDate.Format.html | HTML | apache-2.0 | 10,656 |
<html>
<body>
<table width="100%" height="100%" border="1">
<tr height="18">
<td width="20">_</td><td>_</td><td width="8">_</td><td width="50%">_</td><td width="50%">_</td><td width="20">_</td>
</tr>
<tr>
<td></td><td colspan="4" align="full">description</td>
</tr>
<tr height="8"></tr>
<tr>
<td></td><td colspan="4" align="full">error_lbl</td>
</tr>
<tr height="8"></tr>
<tr>
<td></td><td align="right">address_lbl</td><td></td><td align="full" colspan="2">address</td>
</tr>
<tr height="8"></tr>
<tr>
<td></td><td align="right">name_lbl</td><td></td><td align="full" colspan="2">name</td>
</tr>
<tr height="8"></tr>
<tr>
<td></td><td align="right">title_lbl</td><td></td><td align="full" colspan="2">title</td>
</tr>
<tr height="8"></tr>
<tr>
<td></td><td></td><td></td><td></td><td align="right">separate_vm</td>
</tr>
<tr height="100%"><td>_</td></tr>
</table>
</body>
</html>
| drichan/xito | modules/launcher/src/main/resources/org/xito/launcher/jnlp/java_remote_layout.html | HTML | apache-2.0 | 1,062 |
-- CREATE DATABASE
CREATE DATABASE agile_metrics
WITH ENCODING='UTF8'
OWNER=postgres
CONNECTION LIMIT=-1;
-- Table: "user"
-- DROP TABLE "user";
CREATE TABLE "user"
(
id bigserial NOT NULL,
asana_id bigint,
name character varying(200),
email character varying(200),
photo_url character varying(500),
created_at timestamp with time zone NOT NULL DEFAULT now(),
updated_at timestamp with time zone,
deleted_at timestamp with time zone,
username character varying(100),
password character varying(100),
CONSTRAINT pk_user_id PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "user"
OWNER TO postgres;
-- Table: token
-- DROP TABLE token;
CREATE TABLE token
(
id bigserial NOT NULL,
user_id bigint,
created_at timestamp with time zone NOT NULL DEFAULT now(),
updated_at timestamp with time zone,
deleted_at timestamp with time zone,
expiry timestamp with time zone,
access_token character varying(500),
refresh_token character varying(60),
token_type character varying(50),
CONSTRAINT pk_token_id PRIMARY KEY (id),
CONSTRAINT fk_token_user_id FOREIGN KEY (user_id)
REFERENCES "user" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE token
OWNER TO postgres;
-- Index: fki_token_user_id
-- DROP INDEX fki_token_user_id;
CREATE INDEX fki_token_user_id
ON token
USING btree
(user_id);
| brewinvaz/agile-metrics | database/ddl/create.sql | SQL | apache-2.0 | 1,422 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc (1.8.0_60) on Tue Mar 29 13:02:11 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>play.db.jpa (Play! API)</title>
<meta name="date" content="2016-03-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="play.db.jpa (Play! API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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="../../../play/db/helper/package-summary.html">Prev Package</a></li>
<li><a href="../../../play/deps/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?play/db/jpa/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 play.db.jpa</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </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="../../../play/db/jpa/Blob.html" title="class in play.db.jpa">Blob</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/FileAttachment.html" title="class in play.db.jpa">FileAttachment</a></td>
<td class="colLast">Deprecated</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/GenericModel.html" title="class in play.db.jpa">GenericModel</a></td>
<td class="colLast">
<div class="block">A super class for JPA entities</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/GenericModel.JPAQuery.html" title="class in play.db.jpa">GenericModel.JPAQuery</a></td>
<td class="colLast">
<div class="block">A JPAQuery</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/HibernateInterceptor.html" title="class in play.db.jpa">HibernateInterceptor</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPA.html" title="class in play.db.jpa">JPA</a></td>
<td class="colLast">
<div class="block">JPA Support</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPA.JPAContext.html" title="class in play.db.jpa">JPA.JPAContext</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPABase.html" title="class in play.db.jpa">JPABase</a></td>
<td class="colLast">
<div class="block">A super class for JPA entities</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPAEnhancer.html" title="class in play.db.jpa">JPAEnhancer</a></td>
<td class="colLast">
<div class="block">Enhance JPABase entities classes</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPAModelLoader.html" title="class in play.db.jpa">JPAModelLoader</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPAPlugin.html" title="class in play.db.jpa">JPAPlugin</a></td>
<td class="colLast">
<div class="block">JPA Plugin</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPASupport.html" title="class in play.db.jpa">JPASupport</a></td>
<td class="colLast">Deprecated</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPASupport.JPAQuery.html" title="class in play.db.jpa">JPASupport.JPAQuery</a></td>
<td class="colLast">Deprecated</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPQL.html" title="class in play.db.jpa">JPQL</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/Model.html" title="class in play.db.jpa">Model</a></td>
<td class="colLast">
<div class="block">Base class for JPA model objects
Automatically provide a @Id Long id field</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/MySQLDialect.html" title="class in play.db.jpa">MySQLDialect</a></td>
<td class="colLast">
<div class="block">InnoDB, UTF-8 dialect for Mysql</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Exception Summary table, listing exceptions, and an explanation">
<caption><span>Exception Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Exception</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/JPABase.JPAQueryException.html" title="class in play.db.jpa">JPABase.JPAQueryException</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Annotation Types Summary table, listing annotation types, and an explanation">
<caption><span>Annotation Types Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Annotation Type</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../play/db/jpa/NoTransaction.html" title="annotation in play.db.jpa">NoTransaction</a></td>
<td class="colLast">
<div class="block">Annotation to be used on methods telling JPA
that it should not create a Transaction at all</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../play/db/jpa/Transactional.html" title="annotation in play.db.jpa">Transactional</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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="../../../play/db/helper/package-summary.html">Prev Package</a></li>
<li><a href="../../../play/deps/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?play/db/jpa/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><a href="http://guillaume.bort.fr">Guillaume Bort</a> & <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p>
</body>
</html>
| play1-maven-plugin/play1-maven-plugin.github.io | external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.3.4/play/db/jpa/package-summary.html | HTML | apache-2.0 | 9,628 |
/* Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "absl/container/flat_hash_map.h"
#include "struct2tensor/kernels/parquet/parquet_reader.h"
#include "struct2tensor/kernels/parquet/parquet_reader_util.h"
#include "struct2tensor/kernels/vector_to_tensor.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.h"
namespace struct2tensor {
namespace parquet_dataset {
class Dataset : public tensorflow::data::DatasetBase {
public:
explicit Dataset(tensorflow::OpKernelContext* ctx,
const std::vector<std::string>& filenames,
const std::vector<std::string>& value_paths,
const tensorflow::DataTypeVector& value_dtypes,
const std::vector<std::vector<int>>& segregated_path_indices,
const tensorflow::int64 batch_size,
const tensorflow::DataTypeVector& output_dtypes)
: DatasetBase(tensorflow::data::DatasetContext(ctx)),
filenames_(filenames),
value_paths_(value_paths),
value_dtypes_(value_dtypes),
segregated_path_indices_(segregated_path_indices),
batch_size_(batch_size),
output_dtypes_(output_dtypes),
output_shapes_([this]() {
// The first output tensor is always the root size (number of messages
// read) which is a scalar. Other output tensors are parent indices
// so they are 1-D.
std::vector<tensorflow::PartialTensorShape> shapes(
output_dtypes_.size(), tensorflow::PartialTensorShape({-1}));
shapes[0] = tensorflow::PartialTensorShape({});
return shapes;
}()) {}
std::unique_ptr<tensorflow::data::IteratorBase> MakeIteratorInternal(
const std::string& prefix) const override {
return absl::WrapUnique(new Iterator(
{this, tensorflow::strings::StrCat(prefix, "::Parquet")}, filenames_,
value_paths_, value_dtypes_, segregated_path_indices_, batch_size_));
}
const tensorflow::DataTypeVector& output_dtypes() const override {
return output_dtypes_;
}
const std::vector<tensorflow::PartialTensorShape>& output_shapes()
const override {
return output_shapes_;
}
std::string DebugString() const override {
return "ParquetDatasetOp::Dataset";
}
tensorflow::Status CheckExternalState() const
{
return tensorflow::Status::OK();
}
protected:
// TODO(andylou): Implement saving dataset state.
tensorflow::Status AsGraphDefInternal(
tensorflow::data::SerializationContext* ctx, DatasetGraphDefBuilder* b,
tensorflow::Node** output) const override {
return tensorflow::errors::Unimplemented(
DebugString(), " does not support serialization.");
}
private:
class Iterator : public tensorflow::data::DatasetIterator<Dataset> {
public:
explicit Iterator(
const Params& params, const std::vector<std::string>& filenames,
const std::vector<std::string>& value_paths,
const tensorflow::DataTypeVector& value_dtypes,
const std::vector<std::vector<int>>& segregated_path_indices,
const tensorflow::int64 batch_size)
: DatasetIterator<Dataset>(params),
filenames_(filenames),
value_paths_(value_paths),
value_dtypes_(value_dtypes),
segregated_path_indices_(segregated_path_indices),
batch_size_(batch_size),
current_file_index_(0) {}
// For a deeper understanding of what tensors are returned in out_tensors,
// see parquet_dataset_op.cc.
tensorflow::Status GetNextInternal(
tensorflow::data::IteratorContext* ctx,
std::vector<tensorflow::Tensor>* out_tensors,
bool* end_of_sequence) override {
tensorflow::mutex_lock l(mu_);
if (current_file_index_ >= filenames_.size()) {
*end_of_sequence = true;
return tensorflow::Status::OK();
}
if (!parquet_reader_) {
// Once a file is finished reading, this will create a ParquetReader
// for the next file in file_names_.
TF_RETURN_IF_ERROR(
ValidateFileAndSchema(filenames_[current_file_index_]));
TF_RETURN_IF_ERROR(ParquetReader::Create(
filenames_[current_file_index_], value_paths_, value_dtypes_,
batch_size_, &parquet_reader_));
}
bool end_of_file = false;
std::vector<ParquetReader::ParentIndicesAndValues>
parent_indices_and_values;
TF_RETURN_IF_ERROR(parquet_reader_->ReadMessages(
ctx, &parent_indices_and_values, &end_of_file));
if (end_of_file) {
++current_file_index_;
parquet_reader_.reset();
}
// pushes the number of messages read as the first output tensor.
tensorflow::Tensor root_tensor(ctx->allocator({}), tensorflow::DT_INT64,
{});
if (parent_indices_and_values.size() != value_paths_.size()) {
return tensorflow::errors::Internal(absl::StrCat(
parent_indices_and_values.size(),
" messages read, expected to read ", value_paths_.size()));
}
if (parent_indices_and_values[0].parent_indices.empty()) {
return tensorflow::errors::Internal(
absl::StrCat("0 messages read, expected to read ", batch_size_));
}
root_tensor.flat<tensorflow::int64>()(0) =
parent_indices_and_values[0].parent_indices[0].size();
out_tensors->push_back(std::move(root_tensor));
for (int column_index = 0; column_index < value_paths_.size();
++column_index) {
for (int path_index : segregated_path_indices_[column_index]) {
tensorflow::Tensor res(
ctx->allocator({}), tensorflow::DT_INT64,
{static_cast<long long>(parent_indices_and_values[column_index]
.parent_indices[path_index]
.size())});
struct2tensor::VectorToTensor(parent_indices_and_values[column_index]
.parent_indices[path_index],
&res,
/*produce_string_view=*/false);
out_tensors->push_back(std::move(res));
}
out_tensors->push_back(
std::move(parent_indices_and_values[column_index].values));
}
return tensorflow::Status::OK();
}
protected:
// TODO(b/139440495): Implement saving and restoring iterator state.
tensorflow::Status SaveInternal(
tensorflow::data::SerializationContext* ctx,
tensorflow::data::IteratorStateWriter* writer)
{
return tensorflow::errors::Unimplemented(
"Parquet Dataset Iterator does not support checkpointing.");
}
tensorflow::Status RestoreInternal(
tensorflow::data::IteratorContext* ctx,
tensorflow::data::IteratorStateReader* reader)
{
return tensorflow::errors::Unimplemented(
"Parquet Dataset Iterator does not support checkpointing.");
}
private:
// validates that the file exists and can be opened as a parquet file.
// validates that the schema is the expected schema.
tensorflow::Status ValidateFileAndSchema(const std::string& filename) {
std::unique_ptr<parquet::ParquetFileReader> file_reader;
tensorflow::Status s = OpenFileWithStatus(filename, &file_reader);
absl::flat_hash_map<std::string, tensorflow::DataType> paths;
std::shared_ptr<parquet::FileMetaData> file_metadata =
file_reader->metadata();
for (int i = 0; i < file_metadata->num_columns(); ++i) {
std::string path =
file_metadata->schema()->Column(i)->path()->ToDotString();
switch (file_metadata->schema()->Column(i)->physical_type()) {
case parquet::Type::INT32:
paths[path] = tensorflow::DT_INT32;
break;
case parquet::Type::INT64:
paths[path] = tensorflow::DT_INT64;
break;
case parquet::Type::FLOAT:
paths[path] = tensorflow::DT_FLOAT;
break;
case parquet::Type::DOUBLE:
paths[path] = tensorflow::DT_DOUBLE;
break;
case parquet::Type::BOOLEAN:
paths[path] = tensorflow::DT_BOOL;
break;
case parquet::Type::BYTE_ARRAY:
paths[path] = tensorflow::DT_STRING;
break;
default:
return tensorflow::errors::Unimplemented(absl::StrCat(
"This Parquet Data Type is unimplemented ",
file_metadata->schema()->Column(i)->physical_type()));
}
}
for (int i = 0; i < value_dtypes_.size(); ++i) {
auto paths_iter = paths.find(value_paths_[i]);
if (paths_iter == paths.end()) {
return tensorflow::errors::InvalidArgument(
absl::StrCat("path not found ", value_paths_[i]));
} else if (paths_iter->second != value_dtypes_[i]) {
return tensorflow::errors::InvalidArgument(
absl::StrCat("This dtype is incorrect: ", value_dtypes_[i],
". dtype should be: ", paths_iter->second));
}
}
return s;
}
const std::vector<std::string>& filenames_;
const std::vector<std::string>& value_paths_;
const tensorflow::DataTypeVector& value_dtypes_;
const std::vector<std::vector<int>>& segregated_path_indices_;
const tensorflow::int64 batch_size_;
int current_file_index_ ABSL_GUARDED_BY(mu_);
std::unique_ptr<ParquetReader> parquet_reader_ ABSL_GUARDED_BY(mu_);
tensorflow::mutex mu_;
};
const std::vector<std::string> filenames_;
const std::vector<std::string> value_paths_;
const tensorflow::DataTypeVector value_dtypes_;
// 2D vectore to tell us which parent_indices from the path we want. i.e.
// [[0,1],[0]] means we want the 0th field and 1st field of the 0th path, and
// the 0th field of the 1st path.
const std::vector<std::vector<int>> segregated_path_indices_;
const tensorflow::int64 batch_size_;
const tensorflow::DataTypeVector output_dtypes_;
const std::vector<tensorflow::PartialTensorShape> output_shapes_;
};
class ParquetDatasetOp : public tensorflow::data::DatasetOpKernel {
public:
ParquetDatasetOp(tensorflow::OpKernelConstruction* ctx)
: DatasetOpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("value_paths", &value_paths_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("value_dtypes", &value_dtypes_));
OP_REQUIRES_OK(ctx,
ctx->GetAttr("parent_index_paths", &parent_index_paths_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("path_index", &path_index_));
OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_));
}
void MakeDataset(tensorflow::OpKernelContext* ctx,
tensorflow::data::DatasetBase** output) override {
const tensorflow::Tensor* filenames_tensor;
OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor));
std::vector<std::string> filenames;
filenames.reserve(filenames_tensor->NumElements());
for (int i = 0; i < filenames_tensor->NumElements(); ++i) {
filenames.push_back(filenames_tensor->flat<tensorflow::tstring>()(i));
}
tensorflow::DataTypeVector output_dtypes = tensorflow::DataTypeVector();
int column_counter = 0;
std::string prev = parent_index_paths_[0];
output_dtypes.push_back(tensorflow::DT_INT64);
for (int i = 1; i < parent_index_paths_.size(); ++i) {
std::string curr = parent_index_paths_[i];
output_dtypes.push_back(tensorflow::DT_INT64);
if (curr != prev) {
output_dtypes.push_back(value_dtypes_[column_counter]);
++column_counter;
prev = curr;
}
}
output_dtypes.push_back(tensorflow::DT_INT64);
output_dtypes.push_back(value_dtypes_[column_counter]);
// This validates that parent_index_paths is aligned with value_paths,
// so segregated_path_indices can correctly be constructed.
for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) {
while (parent_index_paths_[i] != value_paths_[j]) {
++j;
if (j >= value_paths_.size()) {
ctx->CtxFailure(tensorflow::errors::InvalidArgument(
"parent_index_paths is not aligned with value_paths"));
return;
}
}
}
std::vector<std::vector<int>> segregated_path_indices(value_paths_.size());
// This is used to transform path_index to a 2d vector, splitting it up
// by clustering the same paths. for example: [0, 1, 2, 0, 1, 0, 1, 2, 3]
// becomes: [[0, 1, 2], [0, 1], [0, 1, 2, 3]]
for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) {
if (parent_index_paths_[i] == value_paths_[j]) {
segregated_path_indices[j].push_back(path_index_[i] + 1);
}
if (i < parent_index_paths_.size() - 1 &&
parent_index_paths_[i + 1] != parent_index_paths_[i]) {
++j;
}
}
*output = new Dataset(ctx, filenames, value_paths_, value_dtypes_,
segregated_path_indices, batch_size_, output_dtypes);
}
private:
std::vector<std::string> value_paths_;
tensorflow::DataTypeVector value_dtypes_;
// Paths of parent indices that we want. For example:
// ["DocId", "Name.Language.Code", "Name.Language.Code", "Name.Language.Code"]
std::vector<std::string> parent_index_paths_;
std::vector<int> path_index_;
int batch_size_;
};
// Register the kernel implementation for ParquetDataset.
REGISTER_KERNEL_BUILDER(Name("ParquetDataset").Device(tensorflow::DEVICE_CPU),
ParquetDatasetOp);
} // namespace parquet_dataset
} // namespace struct2tensor
| google/struct2tensor | struct2tensor/kernels/parquet/parquet_dataset_kernel.cc | C++ | apache-2.0 | 14,363 |
/*=========================================================================
Program: GDCM (Grassroots DICOM). A DICOM library
Copyright (c) 2006-2011 Mathieu Malaterre
All rights reserved.
See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef GDCMMD5_H
#define GDCMMD5_H
#include "gdcmTypes.h"
namespace gdcm
{
//-----------------------------------------------------------------------------
class MD5Internals;
/**
* \brief Class for MD5
*
* \warning this class is able to pick from two implementations:
*
* 1. a lightweight md5 implementation (when GDCM_BUILD_TESTING is turned ON)
* 2. the one from OpenSSL (when GDCM_USE_SYSTEM_OPENSSL is turned ON)
*
* In all other cases it will return an error
*/
class GDCM_EXPORT MD5
{
public :
MD5();
~MD5();
static bool Compute(const char *buffer, unsigned long buf_len, char digest_str[33]);
static bool ComputeFile(const char *filename, char digest_str[33]);
private:
MD5Internals *Internals;
private:
MD5(const MD5&); // Not implemented.
void operator=(const MD5&); // Not implemented.
};
} // end namespace gdcm
//-----------------------------------------------------------------------------
#endif //GDCMMD5_H
| RayRuizhiLiao/ITK_4D | Modules/ThirdParty/GDCM/src/gdcm/Source/Common/gdcmMD5.h | C | apache-2.0 | 1,568 |
$(function () {
var controller = new ScrollMagic.Controller({
globalSceneOptions: {
triggerHook: 'onLeave',
reverse: true
}
});
// $('.homepage .panel').each(function () {
// var element = $(this);
// console.log(element);
// new ScrollMagic.Scene({triggerElement: element})
// .setPin(element)
// .setClassToggle(element,'active')
// .addTo(controller)
// })
// var actual_positions = [0];
// var mid_points = [];
// var all_scenes = [];
// $('.services .panel').each(function (index) {
// if($(this).hasClass('main')) {
// new ScrollMagic.Scene({triggerElement: '.services .main'})
// .setPin('.services .main')
// .setClassToggle('.services .main','active')
// .addTo(controller)
// }
// else {
// var element_id = $(this).attr('id');
// var element_id_with_hash = '#' + $(this).attr('id');
// var scene = new ScrollMagic.Scene({triggerElement: element_id_with_hash})
// .setPin(element_id_with_hash)
// .setClassToggle(element_id_with_hash,'show-bottom-nav')
// .addTo(controller)
// all_scenes.push({
// id: element_id,
// scene: scene
// });
// actual_positions.push(Math.ceil(scene.triggerPosition()));
// if(actual_positions.length > 1) {
// mid_points.push((actual_positions[index] + actual_positions [index-1]) / 2)
// }
// }
// })
// $('a[href*=#]:not([href=#])').click(function () {
// var id = $(this).attr('href').replace('#','');
// if($(this).parent().parent().parent().hasClass('bottom-nav')) {
// var index = $('.bottom-nav ul li a').index($(this));
// }else {
// var index = $('ul.wrap li a').index($(this));
// }
// if(id == 'down') {
// setTimeout(function () {
// $('.bottom-nav').addClass('fixed')
// },1100)
// }
// else {
// var targetted_scene = all_scenes[index];
// if(targetted_scene.id == id) {
// $('html,body').animate({scrollTop: targetted_scene.scene.scrollOffset()},1000);
// return false;
// }
// }
// })
// var add_and_remove_active_class = function (index) {
// $('.bottom-nav').addClass('fixed')
// $('.bottom-nav ul li').removeClass('active');
// $('.bottom-nav ul li:nth-child(' + index + ')').children('a').parent().last().addClass('active');
// }
// $(window).scroll(function () {
// if ($(".show-bottom-nav")[0]){
// $('.bottom-nav').addClass('fixed')
// }else{
// $('.bottom-nav').removeClass('fixed')
// }
// for(var index=0; index<mid_points.length; index++) {
// var next_index = index+1;
// var last_index = mid_points.length-1
// /* check between mid point ranges and set active class to the respective nav item. */
// if($(window).scrollTop() > mid_points[index] && $(window).scrollTop() < mid_points[next_index]) {
// add_and_remove_active_class(next_index);
// break;
// /* if nothing matches and reaches to last index then set active active to last nav item. */
// }else if ($(window).scrollTop() > mid_points[last_index]) {
// add_and_remove_active_class(mid_points.length);
// /* remove from all if its rolled back to the top*/
// }else {
// $('.bottom-nav ul li').removeClass('active');
// }
// }
// });
});
//change navigation color on scroll
/*
var offset_top_news_section = $('.color-light').offset().top;
var offset_top_contact_section = $('.pattern').offset().top;
console.log(offset_top_contact_section, offset_top_news_section);
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
console.log(scroll);
if(scroll < offset_top_contact_section && scroll >= offset_top_news_section) {
$('.homepage nav').addClass('change-color');
} else {
$('.homepage nav').removeClass('change-color');
}
});
*/ | shamroze/squarespace-gulp-scaffolding | sqs_template/scripts/parallax.js | JavaScript | apache-2.0 | 4,557 |
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.jmeter.protocol.http.sampler;
import java.io.IOException;
import java.net.Socket;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpHost;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.jmeter.util.HostNameSetter;
/**
* Custom implementation of {@link DefaultClientConnectionOperator} to fix SNI Issue
* @see "https://bz.apache.org/bugzilla/show_bug.cgi?id=57935"
* @since 3.0
* TODO Remove it when full upgrade to 4.5.X is done and cleanup is made in the Socket Factory of JMeter that handles client certificates and Slow socket
*/
public class JMeterClientConnectionOperator extends
DefaultClientConnectionOperator {
/**
* @param schemes
* the scheme registry
*/
public JMeterClientConnectionOperator(final SchemeRegistry schemes) {
super(schemes);
}
/**
* @param schemes
* the scheme registry
* @param dnsResolver
* the custom DNS lookup mechanism
*/
public JMeterClientConnectionOperator(final SchemeRegistry schemes,
final DnsResolver dnsResolver) {
super(schemes, dnsResolver);
}
@Override
public OperatedClientConnection createConnection() {
return new JMeterDefaultClientConnection();
}
private static class JMeterDefaultClientConnection extends DefaultClientConnection {
public JMeterDefaultClientConnection() {
super();
}
/* (non-Javadoc)
* @see org.apache.http.impl.conn.DefaultClientConnection#opening(java.net.Socket, org.apache.http.HttpHost)
*/
@Override
public void opening(Socket sock, HttpHost target) throws IOException {
super.opening(sock, target);
if(sock instanceof SSLSocket) {
HostNameSetter.setServerNameIndication(target.getHostName(), (SSLSocket) sock);
}
}
}
}
| ra0077/jmeter | src/protocol/http/org/apache/jmeter/protocol/http/sampler/JMeterClientConnectionOperator.java | Java | apache-2.0 | 3,341 |
angular.module('aac.controllers.main', [])
/**
* Main layout controller
* @param $scope
*/
.controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) {
$scope.go = function(v) {
$location.path(v);
}
$scope.activeView = function(view) {
return view == $rootScope.currentView ? 'active' : '';
};
$scope.signOut = function() {
window.document.location = "./logout";
};
Data.getProfile().then(function(data) {
data.fullname = data.name + ' ' + data.surname;
$rootScope.user = data;
}).catch(function(err) {
Utils.showError(err);
});
})
.controller('HomeController', function($scope, $rootScope, $location) {
})
.controller('AccountsController', function($scope, $rootScope, $location, Data, Utils) {
Data.getAccounts().then(function(data) {
Data.getProviders().then(function(providers) {
providers.sort(function(a,b) {
if (data.accounts[a] && !data.accounts[b]) return -1;
if (data.accounts[b] && !data.accounts[a]) return 1;
return a.localeCompare(b);
});
$scope.providers = providers;
var accounts = {};
for (var p in data.accounts) {
var amap = {};
for (var k in data.accounts[p]) {
if (k === 'it.smartcommunitylab.aac.surname') amap['surname'] = data.accounts[p][k];
else if (k === 'it.smartcommunitylab.aac.givenname') amap['givenname'] = data.accounts[p][k];
else if (k === 'it.smartcommunitylab.aac.username') amap['username'] = data.accounts[p][k];
else amap[k] = data.accounts[p][k];
}
accounts[p] = amap;
}
$scope.accounts = accounts;
}).catch(function(err) {
Utils.showError(err);
});
}).catch(function(err) {
Utils.showError(err);
});
$scope.confirmDeleteAccount = function() {
$('#deleteConfirm').modal({keyboard: false});
}
$scope.deleteAccount = function() {
$('#deleteConfirm').modal('hide');
Data.deleteAccount().then(function() {
window.location.href = './logout';
}).catch(function(err) {
Utils.showError(err);
});
}
})
.controller('ConnectionsController', function($scope, $rootScope, $location, Data, Utils) {
Data.getConnections().then(function(connections) {
$scope.connections = connections;
}).catch(function(err) {
Utils.showError(err);
});
$scope.confirmDeleteApp = function(app) {
$scope.clientId = app.clientId;
$('#deleteConfirm').modal({keyboard: false});
}
$scope.deleteApp = function() {
$('#deleteConfirm').modal('hide');
Data.removeConnection($scope.clientId).then(function(connections) {
$scope.connections = connections;
Utils.showSuccess();
}).catch(function(err) {
Utils.showError(err);
});
}
})
.controller('ProfileController', function($scope, $rootScope, $location, Data, Utils) {
$scope.profile = Object.assign($rootScope.user);
Data.getAccounts().then(function(data) {
if (!data.accounts.internal) {
$scope.password_required = true;
}
}).catch(function(err) {
Utils.showError(err);
});
$scope.cancel = function() {
window.history.back();
}
$scope.save = function() {
if (!$scope.profile.name ||
!$scope.profile.surname ||
!$scope.profile.username ||
$scope.profile.password && $scope.profile.password != $scope.profile.password2)
{
return;
}
Data.saveAccount($scope.profile).then(function(data) {
data.fullname = data.name + ' ' + data.surname;
$rootScope.user = data;
$scope.profile = Object.assign($rootScope.user);
$scope.password_required = false;
Utils.showSuccess();
}).catch(function(err) {
Utils.showError(err);
});
}
Utils.initUI();
})
; | smartcommunitylab/AAC | src/main/resources/public/js/account/main.js | JavaScript | apache-2.0 | 3,561 |
# Callitris arenosa A. Cunn. ex R.T. Baker & H.G. Smith SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Pinophyta/Pinopsida/Pinales/Cupressaceae/Callitris/Callitris columellaris/ Syn. Callitris arenosa/README.md | Markdown | apache-2.0 | 210 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Generic values</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="index.html" title="GObject Reference Manual">
<link rel="up" href="rn01.html" title="API Reference">
<link rel="prev" href="gobject-Boxed-Types.html" title="Boxed Types">
<link rel="next" href="gobject-Standard-Parameter-and-Value-Types.html" title="Parameters and Values">
<meta name="generator" content="GTK-Doc V1.18 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2">
<tr valign="middle">
<td><a accesskey="p" href="gobject-Boxed-Types.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td>
<td><a accesskey="u" href="rn01.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td>
<td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td>
<th width="100%" align="center">GObject Reference Manual</th>
<td><a accesskey="n" href="gobject-Standard-Parameter-and-Value-Types.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td>
</tr>
<tr><td colspan="5" class="shortcuts">
<a href="#gobject-Generic-values.synopsis" class="shortcut">Top</a>
|
<a href="#gobject-Generic-values.description" class="shortcut">Description</a>
</td></tr>
</table>
<div class="refentry">
<a name="gobject-Generic-values"></a><div class="titlepage"></div>
<div class="refnamediv"><table width="100%"><tr>
<td valign="top">
<h2><span class="refentrytitle"><a name="gobject-Generic-values.top_of_page"></a>Generic values</span></h2>
<p>Generic values — A polymorphic type that can hold values of any
other type</p>
</td>
<td valign="top" align="right"></td>
</tr></table></div>
<div class="refsynopsisdiv">
<a name="gobject-Generic-values.synopsis"></a><h2>Synopsis</h2>
<pre class="synopsis">
#include <glib-object.h>
#define <a class="link" href="gobject-Generic-values.html#G-VALUE-INIT:CAPS" title="G_VALUE_INIT">G_VALUE_INIT</a>
#define <a class="link" href="gobject-Generic-values.html#G-VALUE-HOLDS:CAPS" title="G_VALUE_HOLDS()">G_VALUE_HOLDS</a> (value,
type)
#define <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE:CAPS" title="G_VALUE_TYPE()">G_VALUE_TYPE</a> (value)
#define <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE-NAME:CAPS" title="G_VALUE_TYPE_NAME()">G_VALUE_TYPE_NAME</a> (value)
#define <a class="link" href="gobject-Generic-values.html#G-TYPE-IS-VALUE:CAPS" title="G_TYPE_IS_VALUE()">G_TYPE_IS_VALUE</a> (type)
#define <a class="link" href="gobject-Generic-values.html#G-TYPE-IS-VALUE-ABSTRACT:CAPS" title="G_TYPE_IS_VALUE_ABSTRACT()">G_TYPE_IS_VALUE_ABSTRACT</a> (type)
#define <a class="link" href="gobject-Generic-values.html#G-IS-VALUE:CAPS" title="G_IS_VALUE()">G_IS_VALUE</a> (value)
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue">GValue</a>;
#define <a class="link" href="gobject-Generic-values.html#G-TYPE-VALUE:CAPS" title="G_TYPE_VALUE">G_TYPE_VALUE</a>
#define <a class="link" href="gobject-Generic-values.html#G-TYPE-VALUE-ARRAY:CAPS" title="G_TYPE_VALUE_ARRAY">G_TYPE_VALUE_ARRAY</a>
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()">g_value_init</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> g_type</code></em>);
<span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-copy" title="g_value_copy ()">g_value_copy</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * <a class="link" href="gobject-Generic-values.html#g-value-reset" title="g_value_reset ()">g_value_reset</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);
<span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-unset" title="g_value_unset ()">g_value_unset</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);
<span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-set-instance" title="g_value_set_instance ()">g_value_set_instance</a> (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>,
<em class="parameter"><code><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> instance</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-fits-pointer" title="g_value_fits_pointer ()">g_value_fits_pointer</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="returnvalue">gpointer</span></a> <a class="link" href="gobject-Generic-values.html#g-value-peek-pointer" title="g_value_peek_pointer ()">g_value_peek_pointer</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-type-compatible" title="g_value_type_compatible ()">g_value_type_compatible</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-type-transformable" title="g_value_type_transformable ()">g_value_type_transformable</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()">g_value_transform</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);
<span class="returnvalue">void</span> (<a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()">*GValueTransform</a>) (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);
<span class="returnvalue">void</span> <a class="link" href="gobject-Generic-values.html#g-value-register-transform-func" title="g_value_register_transform_func ()">g_value_register_transform_func</a> (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()"><span class="type">GValueTransform</span></a> transform_func</code></em>);
<a href="./../glib/glib/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * <a class="link" href="gobject-Generic-values.html#g-strdup-value-contents" title="g_strdup_value_contents ()">g_strdup_value_contents</a> (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);
</pre>
</div>
<div class="refsect1">
<a name="gobject-Generic-values.description"></a><h2>Description</h2>
<p>
The <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure is basically a variable container that consists
of a type identifier and a specific value of that type.
The type identifier within a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure always determines the
type of the associated value.
To create a undefined <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure, simply create a zero-filled
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure. To initialize the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>, use the <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a>
function. A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> cannot be used until it is initialized.
The basic type operations (such as freeing and copying) are determined
by the <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> associated with the type ID stored in the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>.
Other <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> operations (such as converting values between types) are
provided by this interface.
</p>
<p>
The code in the example program below demonstrates <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>'s
features.
</p>
<p>
</p>
<div class="informalexample">
<table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="listing_lines" align="right"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54</pre></td>
<td class="listing_code"><pre class="programlisting"><span class="preproc">#include</span><span class="normal"> </span><span class="string"><glib-object.h></span>
<span class="keyword">static</span><span class="normal"> </span><span class="type">void</span>
<span class="function">int2string</span><span class="normal"> </span><span class="symbol">(</span><span class="keyword">const</span><span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">src_value</span><span class="symbol">,</span>
<span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">dest_value</span><span class="symbol">)</span>
<span class="cbracket">{</span>
<span class="normal"> </span><span class="keyword">if</span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-int">g_value_get_int</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">src_value</span><span class="symbol">)</span><span class="normal"> </span><span class="symbol">==</span><span class="normal"> </span><span class="number">42</span><span class="symbol">)</span>
<span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">dest_value</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"An important number"</span><span class="symbol">);</span>
<span class="normal"> </span><span class="keyword">else</span>
<span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal">dest_value</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"What's that?"</span><span class="symbol">);</span>
<span class="cbracket">}</span>
<span class="type">int</span>
<span class="function">main</span><span class="normal"> </span><span class="symbol">(</span><span class="type">int</span><span class="normal"> argc</span><span class="symbol">,</span>
<span class="normal"> </span><span class="type">char</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">argv</span><span class="symbol">[])</span>
<span class="cbracket">{</span>
<span class="normal"> </span><span class="comment">/* GValues must be initialized */</span>
<span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> a </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span>
<span class="normal"> </span><span class="usertype">GValue</span><span class="normal"> b </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span>
<span class="normal"> </span><span class="keyword">const</span><span class="normal"> </span><span class="usertype">gchar</span><span class="normal"> </span><span class="symbol">*</span><span class="normal">message</span><span class="symbol">;</span>
<span class="normal"> </span><span class="function"><a href="gobject-Type-Information.html#g-type-init">g_type_init</a></span><span class="normal"> </span><span class="symbol">();</span>
<span class="normal"> </span><span class="comment">/* The GValue starts empty */</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(!</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#G-VALUE-HOLDS-STRING:CAPS">G_VALUE_HOLDS_STRING</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">));</span>
<span class="normal"> </span><span class="comment">/* Put a string in it */</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#G-VALUE-HOLDS-STRING:CAPS">G_VALUE_HOLDS_STRING</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">));</span>
<span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-static-string">g_value_set_static_string</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="string">"Hello, world!"</span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">));</span>
<span class="normal"> </span><span class="comment">/* Reset it to its pristine state */</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-unset">g_value_unset</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">);</span>
<span class="normal"> </span><span class="comment">/* It can then be reused for another type */</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-set-int">g_value_set_int</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="number">42</span><span class="symbol">);</span>
<span class="normal"> </span><span class="comment">/* Attempt to transform it into a GValue of type STRING */</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-init">g_value_init</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">b</span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">);</span>
<span class="normal"> </span><span class="comment">/* An INT is transformable to a STRING */</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-Testing.html#g-assert">g_assert</a></span><span class="normal"> </span><span class="symbol">(</span><span class="function"><a href="gobject-Generic-values.html#g-value-type-transformable">g_value_type_transformable</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal"><a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">));</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-transform">g_value_transform</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">&</span><span class="normal">b</span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">b</span><span class="symbol">));</span>
<span class="normal"> </span><span class="comment">/* Attempt to transform it again using a custom transform function */</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-register-transform-func">g_value_register_transform_func</a></span><span class="normal"> </span><span class="symbol">(</span><span class="normal"><a href="gobject-Type-Information.html#G-TYPE-INT:CAPS">G_TYPE_INT</a></span><span class="symbol">,</span><span class="normal"> <a href="gobject-Type-Information.html#G-TYPE-STRING:CAPS">G_TYPE_STRING</a></span><span class="symbol">,</span><span class="normal"> int2string</span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="gobject-Generic-values.html#g-value-transform">g_value_transform</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">a</span><span class="symbol">,</span><span class="normal"> </span><span class="symbol">&</span><span class="normal">b</span><span class="symbol">);</span>
<span class="normal"> </span><span class="function"><a href="./../glib/glib/glib-String-Utility-Functions.html#g-printf">g_printf</a></span><span class="normal"> </span><span class="symbol">(</span><span class="string">"%s</span><span class="specialchar">\n</span><span class="string">"</span><span class="symbol">,</span><span class="normal"> </span><span class="function"><a href="gobject-Standard-Parameter-and-Value-Types.html#g-value-get-string">g_value_get_string</a></span><span class="normal"> </span><span class="symbol">(&</span><span class="normal">b</span><span class="symbol">));</span>
<span class="normal"> </span><span class="keyword">return</span><span class="normal"> </span><span class="number">0</span><span class="symbol">;</span>
<span class="cbracket">}</span></pre></td>
</tr>
</tbody>
</table>
</div>
<p>
</p>
</div>
<div class="refsect1">
<a name="gobject-Generic-values.details"></a><h2>Details</h2>
<div class="refsect2">
<a name="G-VALUE-INIT:CAPS"></a><h3>G_VALUE_INIT</h3>
<pre class="programlisting">#define G_VALUE_INIT { 0, { { 0 } } }
</pre>
<p>
A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> must be initialized before it can be used.
This macro can be used as initializer instead of an explicit
<code class="literal">{ 0 }</code> when declaring a variable,
but it cannot be assigned to a variable.
</p>
<p>
</p>
<div class="informalexample">
<table class="listing_frame" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="listing_lines" align="right"><pre>1</pre></td>
<td class="listing_code"><pre class="programlisting"><span class="usertype">GValue</span><span class="normal"> value </span><span class="symbol">=</span><span class="normal"> <a href="gobject-Generic-values.html#G-VALUE-INIT:CAPS">G_VALUE_INIT</a></span><span class="symbol">;</span></pre></td>
</tr>
</tbody>
</table>
</div>
<p>
</p>
<p class="since">Since 2.30</p>
</div>
<hr>
<div class="refsect2">
<a name="G-VALUE-HOLDS:CAPS"></a><h3>G_VALUE_HOLDS()</h3>
<pre class="programlisting">#define G_VALUE_HOLDS(value,type) (G_TYPE_CHECK_VALUE_TYPE ((value), (type)))
</pre>
<p>
Checks if <em class="parameter"><code>value</code></em> holds (or contains) a value of <em class="parameter"><code>type</code></em>.
This macro will also check for <em class="parameter"><code>value</code></em> != <a href="./../glib/glib/glib-Standard-Macros.html#NULL:CAPS"><code class="literal">NULL</code></a> and issue a
warning if the check fails.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <em class="parameter"><code>value</code></em> holds the <em class="parameter"><code>type</code></em>.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="G-VALUE-TYPE:CAPS"></a><h3>G_VALUE_TYPE()</h3>
<pre class="programlisting">#define G_VALUE_TYPE(value) (((GValue*) (value))->g_type)
</pre>
<p>
Get the type identifier of <em class="parameter"><code>value</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>the <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a>.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="G-VALUE-TYPE-NAME:CAPS"></a><h3>G_VALUE_TYPE_NAME()</h3>
<pre class="programlisting">#define G_VALUE_TYPE_NAME(value) (g_type_name (G_VALUE_TYPE (value)))
</pre>
<p>
Gets the type name of <em class="parameter"><code>value</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>the type name.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="G-TYPE-IS-VALUE:CAPS"></a><h3>G_TYPE_IS_VALUE()</h3>
<pre class="programlisting">#define G_TYPE_IS_VALUE(type) (g_type_check_is_value_type (type))
</pre>
<p>
Checks whether the passed in type ID can be used for <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a>.
That is, this macro checks whether this type provides an implementation
of the <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> functions required for a type to create a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>Whether <em class="parameter"><code>type</code></em> is suitable as a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> type.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="G-TYPE-IS-VALUE-ABSTRACT:CAPS"></a><h3>G_TYPE_IS_VALUE_ABSTRACT()</h3>
<pre class="programlisting">#define G_TYPE_IS_VALUE_ABSTRACT(type) (g_type_test_flags ((type), G_TYPE_FLAG_VALUE_ABSTRACT))
</pre>
<p>
Checks if <em class="parameter"><code>type</code></em> is an abstract value type. An abstract value type introduces
a value table, but can't be used for <a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a> and is normally used as
an abstract base type for derived value types.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>type</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> value.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="G-IS-VALUE:CAPS"></a><h3>G_IS_VALUE()</h3>
<pre class="programlisting">#define G_IS_VALUE(value) (G_TYPE_CHECK_VALUE (value))
</pre>
<p>
Checks if <em class="parameter"><code>value</code></em> is a valid and initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>A <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> on success.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="GValue"></a><h3>GValue</h3>
<pre class="programlisting">typedef struct {
} GValue;
</pre>
<p>
An opaque structure used to hold different types of values.
The data within the structure has protected scope: it is accessible only
to functions within a <a class="link" href="gobject-Type-Information.html#GTypeValueTable" title="struct GTypeValueTable"><span class="type">GTypeValueTable</span></a> structure, or implementations of
the g_value_*() API. That is, code portions which implement new fundamental
types.
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> users cannot make any assumptions about how data is stored
within the 2 element <em class="parameter"><code>data</code></em> union, and the <em class="parameter"><code>g_type</code></em> member should
only be accessed through the <a class="link" href="gobject-Generic-values.html#G-VALUE-TYPE:CAPS" title="G_VALUE_TYPE()"><code class="function">G_VALUE_TYPE()</code></a> macro.
</p>
</div>
<hr>
<div class="refsect2">
<a name="G-TYPE-VALUE:CAPS"></a><h3>G_TYPE_VALUE</h3>
<pre class="programlisting">#define G_TYPE_VALUE (g_value_get_type ())
</pre>
<p>
The type ID of the "GValue" type which is a boxed type,
used to pass around pointers to GValues.
</p>
</div>
<hr>
<div class="refsect2">
<a name="G-TYPE-VALUE-ARRAY:CAPS"></a><h3>G_TYPE_VALUE_ARRAY</h3>
<pre class="programlisting">#define G_TYPE_VALUE_ARRAY (g_value_array_get_type ())
</pre>
<div class="warning" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Warning</h3>
<p><code class="literal">G_TYPE_VALUE_ARRAY</code> has been deprecated since version 2.32 and should not be used in newly-written code. Use <a href="./../glib/glib/glib-Arrays.html#GArray"><span class="type">GArray</span></a> instead of <a class="link" href="gobject-Value-arrays.html#GValueArray" title="struct GValueArray"><span class="type">GValueArray</span></a></p>
</div>
<p>
The type ID of the "GValueArray" type which is a boxed type,
used to pass around pointers to GValueArrays.
</p>
</div>
<hr>
<div class="refsect2">
<a name="g-value-init"></a><h3>g_value_init ()</h3>
<pre class="programlisting"><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * g_value_init (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> g_type</code></em>);</pre>
<p>
Initializes <em class="parameter"><code>value</code></em> with the default value of <em class="parameter"><code>type</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>A zero-filled (uninitialized) <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>g_type</code></em> :</span></p></td>
<td>Type the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> should hold values of.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure that has been passed in. <span class="annotation">[<acronym title="Don't free data after the code is done."><span class="acronym">transfer none</span></acronym>]</span>
</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-copy"></a><h3>g_value_copy ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span> g_value_copy (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre>
<p>
Copies the value of <em class="parameter"><code>src_value</code></em> into <em class="parameter"><code>dest_value</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure of the same type as <em class="parameter"><code>src_value</code></em>.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-reset"></a><h3>g_value_reset ()</h3>
<pre class="programlisting"><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="returnvalue">GValue</span></a> * g_value_reset (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre>
<p>
Clears the current value in <em class="parameter"><code>value</code></em> and resets it to the default value
(as if the value had just been initialized).
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>the <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure that has been passed in</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-unset"></a><h3>g_value_unset ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span> g_value_unset (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre>
<p>
Clears the current value in <em class="parameter"><code>value</code></em> and "unsets" the type,
this releases all resources associated with this GValue.
An unset value is the same as an uninitialized (zero-filled)
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody><tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr></tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-set-instance"></a><h3>g_value_set_instance ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span> g_value_set_instance (<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>,
<em class="parameter"><code><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="type">gpointer</span></a> instance</code></em>);</pre>
<p>
Sets <em class="parameter"><code>value</code></em> from an instantiatable type via the
value_table's <code class="function">collect_value()</code> function.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>instance</code></em> :</span></p></td>
<td>the instance. <span class="annotation">[<acronym title="NULL is ok, both for passing and for returning."><span class="acronym">allow-none</span></acronym>]</span>
</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-fits-pointer"></a><h3>g_value_fits_pointer ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_fits_pointer (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre>
<p>
Determines if <em class="parameter"><code>value</code></em> will fit inside the size of a pointer value.
This is an internal function introduced mainly for C marshallers.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <em class="parameter"><code>value</code></em> will fit inside a pointer value.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-peek-pointer"></a><h3>g_value_peek_pointer ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gpointer"><span class="returnvalue">gpointer</span></a> g_value_peek_pointer (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>An initialized <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> structure.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>the value contents as pointer. This
function asserts that <a class="link" href="gobject-Generic-values.html#g-value-fits-pointer" title="g_value_fits_pointer ()"><code class="function">g_value_fits_pointer()</code></a> returned <a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> for the
passed in value. This is an internal function introduced mainly
for C marshallers. <span class="annotation">[<acronym title="Don't free data after the code is done."><span class="acronym">transfer none</span></acronym>]</span>
</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-type-compatible"></a><h3>g_value_type_compatible ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_type_compatible (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);</pre>
<p>
Returns whether a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of type <em class="parameter"><code>src_type</code></em> can be copied into
a <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> of type <em class="parameter"><code>dest_type</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td>
<td>source type to be copied.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td>
<td>destination type for copying.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if <a class="link" href="gobject-Generic-values.html#g-value-copy" title="g_value_copy ()"><code class="function">g_value_copy()</code></a> is possible with <em class="parameter"><code>src_type</code></em> and <em class="parameter"><code>dest_type</code></em>.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-type-transformable"></a><h3>g_value_type_transformable ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_type_transformable (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>);</pre>
<p>
Check whether <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()"><code class="function">g_value_transform()</code></a> is able to transform values
of type <em class="parameter"><code>src_type</code></em> into values of type <em class="parameter"><code>dest_type</code></em>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td>
<td>Source type.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td>
<td>Target type.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>
<a href="./../glib/glib/glib-Standard-Macros.html#TRUE:CAPS"><code class="literal">TRUE</code></a> if the transformation is possible, <a href="./../glib/glib/glib-Standard-Macros.html#FALSE:CAPS"><code class="literal">FALSE</code></a> otherwise.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-transform"></a><h3>g_value_transform ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gboolean"><span class="returnvalue">gboolean</span></a> g_value_transform (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre>
<p>
Tries to cast the contents of <em class="parameter"><code>src_value</code></em> into a type appropriate
to store in <em class="parameter"><code>dest_value</code></em>, e.g. to transform a <a class="link" href="gobject-Type-Information.html#G-TYPE-INT:CAPS" title="G_TYPE_INT"><code class="literal">G_TYPE_INT</code></a> value
into a <a class="link" href="gobject-Type-Information.html#G-TYPE-FLOAT:CAPS" title="G_TYPE_FLOAT"><code class="literal">G_TYPE_FLOAT</code></a> value. Performing transformations between
value types might incur precision lossage. Especially
transformations into strings might reveal seemingly arbitrary
results and shouldn't be relied upon for production code (such
as rcfile value or object property serialization).
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td>
<td>Source value.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td>
<td>Target value.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>Whether a transformation rule was found and could be applied.
Upon failing transformations, <em class="parameter"><code>dest_value</code></em> is left untouched.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="GValueTransform"></a><h3>GValueTransform ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span> (*GValueTransform) (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *src_value</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *dest_value</code></em>);</pre>
<p>
The type of value transformation functions which can be registered with
<a class="link" href="gobject-Generic-values.html#g-value-register-transform-func" title="g_value_register_transform_func ()"><code class="function">g_value_register_transform_func()</code></a>.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_value</code></em> :</span></p></td>
<td>Source value.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_value</code></em> :</span></p></td>
<td>Target value.</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-value-register-transform-func"></a><h3>g_value_register_transform_func ()</h3>
<pre class="programlisting"><span class="returnvalue">void</span> g_value_register_transform_func (<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> src_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Type-Information.html#GType" title="GType"><span class="type">GType</span></a> dest_type</code></em>,
<em class="parameter"><code><a class="link" href="gobject-Generic-values.html#GValueTransform" title="GValueTransform ()"><span class="type">GValueTransform</span></a> transform_func</code></em>);</pre>
<p>
Registers a value transformation function for use in <a class="link" href="gobject-Generic-values.html#g-value-transform" title="g_value_transform ()"><code class="function">g_value_transform()</code></a>.
A previously registered transformation function for <em class="parameter"><code>src_type</code></em> and <em class="parameter"><code>dest_type</code></em>
will be replaced.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>src_type</code></em> :</span></p></td>
<td>Source type.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>dest_type</code></em> :</span></p></td>
<td>Target type.</td>
</tr>
<tr>
<td><p><span class="term"><em class="parameter"><code>transform_func</code></em> :</span></p></td>
<td>a function which transforms values of type <em class="parameter"><code>src_type</code></em>
into value of type <em class="parameter"><code>dest_type</code></em>
</td>
</tr>
</tbody>
</table></div>
</div>
<hr>
<div class="refsect2">
<a name="g-strdup-value-contents"></a><h3>g_strdup_value_contents ()</h3>
<pre class="programlisting"><a href="./../glib/glib/glib-Basic-Types.html#gchar"><span class="returnvalue">gchar</span></a> * g_strdup_value_contents (<em class="parameter"><code>const <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> *value</code></em>);</pre>
<p>
Return a newly allocated string, which describes the contents of a
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>. The main purpose of this function is to describe <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>
contents for debugging output, the way in which the contents are
described may change between different GLib versions.
</p>
<div class="variablelist"><table border="0" class="variablelist">
<colgroup>
<col align="left" valign="top">
<col>
</colgroup>
<tbody>
<tr>
<td><p><span class="term"><em class="parameter"><code>value</code></em> :</span></p></td>
<td>
<a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a> which contents are to be described.</td>
</tr>
<tr>
<td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td>
<td>Newly allocated string.</td>
</tr>
</tbody>
</table></div>
</div>
</div>
<div class="refsect1">
<a name="gobject-Generic-values.see-also"></a><h2>See Also</h2>
The fundamental types which all support <a class="link" href="gobject-Generic-values.html#GValue" title="GValue"><span class="type">GValue</span></a>
operations and thus can be used as a type initializer for
<a class="link" href="gobject-Generic-values.html#g-value-init" title="g_value_init ()"><code class="function">g_value_init()</code></a> are defined by a separate interface. See the <a class="link" href="gobject-Standard-Parameter-and-Value-Types.html" title="Parameters and Values">Standard
Values API</a> for details.
</div>
</div>
<div class="footer">
<hr>
Generated by GTK-Doc V1.18</div>
</body>
</html> | jonnyniv/boost_converter | host/gui/GTK+/share/gtk-doc/html/gobject/gobject-Generic-values.html | HTML | apache-2.0 | 56,463 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.rdd
import java.io.{IOException, ObjectOutputStream}
import scala.reflect.ClassTag
import org.apache.spark._
import org.apache.spark.util.Utils
private[spark]
/**
* Cartesian 笛卡尔积
*/
class CartesianPartition(
idx: Int,
@transient rdd1: RDD[_],
@transient rdd2: RDD[_],
s1Index: Int,
s2Index: Int
) extends Partition {
var s1 = rdd1.partitions(s1Index)
var s2 = rdd2.partitions(s2Index)
override val index: Int = idx
@throws(classOf[IOException])
private def writeObject(oos: ObjectOutputStream): Unit = Utils.tryOrIOException {
// Update the reference to parent split at the time of task serialization
s1 = rdd1.partitions(s1Index)
s2 = rdd2.partitions(s2Index)
oos.defaultWriteObject()
}
}
private[spark]
class CartesianRDD[T: ClassTag, U: ClassTag](
sc: SparkContext,
var rdd1 : RDD[T],
var rdd2 : RDD[U])
extends RDD[Pair[T, U]](sc, Nil)
with Serializable {
val numPartitionsInRdd2 = rdd2.partitions.length
override def getPartitions: Array[Partition] = {
// create the cross product split 创建交叉产品拆分
val array = new Array[Partition](rdd1.partitions.length * rdd2.partitions.length)
for (s1 <- rdd1.partitions; s2 <- rdd2.partitions) {
val idx = s1.index * numPartitionsInRdd2 + s2.index
array(idx) = new CartesianPartition(idx, rdd1, rdd2, s1.index, s2.index)
}
array
}
override def getPreferredLocations(split: Partition): Seq[String] = {
val currSplit = split.asInstanceOf[CartesianPartition]
(rdd1.preferredLocations(currSplit.s1) ++ rdd2.preferredLocations(currSplit.s2)).distinct
}
override def compute(split: Partition, context: TaskContext): Iterator[(T, U)] = {
val currSplit = split.asInstanceOf[CartesianPartition]
for (x <- rdd1.iterator(currSplit.s1, context);
y <- rdd2.iterator(currSplit.s2, context)) yield (x, y)
}
override def getDependencies: Seq[Dependency[_]] = List(
new NarrowDependency(rdd1) {
def getParents(id: Int): Seq[Int] = List(id / numPartitionsInRdd2)
},
new NarrowDependency(rdd2) {
def getParents(id: Int): Seq[Int] = List(id % numPartitionsInRdd2)
}
)
override def clearDependencies() {
super.clearDependencies()
rdd1 = null
rdd2 = null
}
}
| tophua/spark1.52 | core/src/main/scala/org/apache/spark/rdd/CartesianRDD.scala | Scala | apache-2.0 | 3,128 |
#!/bin/env python
import itertools
import collections
def read_table(filename):
with open(filename) as fp:
header = next(fp).split()
rows = [line.split()[1:] for line in fp if line.strip()]
columns = zip(*rows)
data = dict(zip(header, columns))
return data
table = read_table("../../data/colldata.txt")
pots = sorted(table)
alphabet = "+-?"
for num in range(2, len(table) + 1):
for group in itertools.combinations(pots, num):
patterns = zip(*[table[p] for p in group])
counts = collections.Counter(patterns)
for poss in itertools.product(alphabet, repeat=num):
print ', '.join(group) + ':',
print ''.join(poss), counts[poss]
| ketancmaheshwari/hello-goog | src/python/collectionsexample.py | Python | apache-2.0 | 718 |
package com.jota.patterns.singleton;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jota.patterns.singleton.singleton.User;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.user1) TextView user1Text;
@BindView(R.id.user2) TextView user2Text;
@BindView(R.id.user3) TextView user3Text;
private User user, user1, user2, user3;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
user = User.getInstance();
user.setToken("token");
user.setSocialNetwork("Facebook");
user1 = User.getInstance();
user2 = User.getInstance();
user3 = User.getInstance();
}
private void showUsers() {
user1Text.setText(user1.getSocialNetwork() + " - " + user1.getToken());
user2Text.setText(user2.getSocialNetwork() + " - " + user2.getToken());
user3Text.setText(user3.getSocialNetwork() + " - " + user3.getToken());
}
@OnClick(R.id.change_social_button) public void changeSocial() {
user.setSocialNetwork("Twitter");
showUsers();
}
@OnClick(R.id.change_token_button) public void changeToken() {
user.setToken("Token token");
showUsers();
}
}
| jotaramirez90/Android-DesignPatterns | singleton/src/main/java/com/jota/patterns/singleton/MainActivity.java | Java | apache-2.0 | 1,406 |
# This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import with_statement
import operator
import threading
from mapproxy.grid import bbox_intersects, bbox_contains
from mapproxy.util.py import cached_property
from mapproxy.util.geom import (
require_geom_support,
load_polygon_lines,
transform_geometry,
bbox_polygon,
)
from mapproxy.srs import SRS
import logging
log_config = logging.getLogger('mapproxy.config.coverage')
try:
import shapely.geometry
import shapely.prepared
except ImportError:
# missing Shapely is handled by require_geom_support
pass
def coverage(geom, srs):
if isinstance(geom, (list, tuple)):
return BBOXCoverage(geom, srs)
else:
return GeomCoverage(geom, srs)
def load_limited_to(limited_to):
require_geom_support()
srs = SRS(limited_to['srs'])
geom = limited_to['geometry']
if not hasattr(geom, 'type'): # not a Shapely geometry
if isinstance(geom, (list, tuple)):
geom = bbox_polygon(geom)
else:
polygons = load_polygon_lines(geom.split('\n'))
if len(polygons) == 1:
geom = polygons[0]
else:
geom = shapely.geometry.MultiPolygon(polygons)
return GeomCoverage(geom, srs, clip=True)
class MultiCoverage(object):
clip = False
"""Aggregates multiple coverages"""
def __init__(self, coverages):
self.coverages = coverages
self.bbox = self.extent.bbox
@cached_property
def extent(self):
return reduce(operator.add, [c.extent for c in self.coverages])
def intersects(self, bbox, srs):
return any(c.intersects(bbox, srs) for c in self.coverages)
def contains(self, bbox, srs):
return any(c.contains(bbox, srs) for c in self.coverages)
def transform_to(self, srs):
return MultiCoverage([c.transform_to(srs) for c in self.coverages])
def __eq__(self, other):
if not isinstance(other, MultiCoverage):
return NotImplemented
if self.bbox != other.bbox:
return False
if len(self.coverages) != len(other.coverages):
return False
for a, b in zip(self.coverages, other.coverages):
if a != b:
return False
return True
def __ne__(self, other):
if not isinstance(other, MultiCoverage):
return NotImplemented
return not self.__eq__(other)
def __repr__(self):
return '<MultiCoverage %r: %r>' % (self.extent.llbbox, self.coverages)
class BBOXCoverage(object):
clip = False
def __init__(self, bbox, srs):
self.bbox = bbox
self.srs = srs
self.geom = None
@property
def extent(self):
from mapproxy.layer import MapExtent
return MapExtent(self.bbox, self.srs)
def _bbox_in_coverage_srs(self, bbox, srs):
if srs != self.srs:
bbox = srs.transform_bbox_to(self.srs, bbox)
return bbox
def intersects(self, bbox, srs):
bbox = self._bbox_in_coverage_srs(bbox, srs)
return bbox_intersects(self.bbox, bbox)
def intersection(self, bbox, srs):
bbox = self._bbox_in_coverage_srs(bbox, srs)
intersection = (
max(self.bbox[0], bbox[0]),
max(self.bbox[1], bbox[1]),
min(self.bbox[2], bbox[2]),
min(self.bbox[3], bbox[3]),
)
if intersection[0] >= intersection[2] or intersection[1] >= intersection[3]:
return None
return BBOXCoverage(intersection, self.srs)
def contains(self, bbox, srs):
bbox = self._bbox_in_coverage_srs(bbox, srs)
return bbox_contains(self.bbox, bbox)
def transform_to(self, srs):
if srs == self.srs:
return self
bbox = self.srs.transform_bbox_to(srs, self.bbox)
return BBOXCoverage(bbox, srs)
def __eq__(self, other):
if not isinstance(other, BBOXCoverage):
return NotImplemented
if self.srs != other.srs:
return False
if self.bbox != other.bbox:
return False
return True
def __ne__(self, other):
if not isinstance(other, BBOXCoverage):
return NotImplemented
return not self.__eq__(other)
def __repr__(self):
return '<BBOXCoverage %r/%r>' % (self.extent.llbbox, self.bbox)
class GeomCoverage(object):
def __init__(self, geom, srs, clip=False):
self.geom = geom
self.bbox = geom.bounds
self.srs = srs
self.clip = clip
self._prep_lock = threading.Lock()
self._prepared_geom = None
self._prepared_counter = 0
self._prepared_max = 10000
@property
def extent(self):
from mapproxy.layer import MapExtent
return MapExtent(self.bbox, self.srs)
@property
def prepared_geom(self):
# GEOS internal data structure for prepared geometries grows over time,
# recreate to limit memory consumption
if not self._prepared_geom or self._prepared_counter > self._prepared_max:
self._prepared_geom = shapely.prepared.prep(self.geom)
self._prepared_counter = 0
self._prepared_counter += 1
return self._prepared_geom
def _geom_in_coverage_srs(self, geom, srs):
if isinstance(geom, shapely.geometry.base.BaseGeometry):
if srs != self.srs:
geom = transform_geometry(srs, self.srs, geom)
elif len(geom) == 2:
if srs != self.srs:
geom = srs.transform_to(self.srs, geom)
geom = shapely.geometry.Point(geom)
else:
if srs != self.srs:
geom = srs.transform_bbox_to(self.srs, geom)
geom = bbox_polygon(geom)
return geom
def transform_to(self, srs):
if srs == self.srs:
return self
geom = transform_geometry(self.srs, srs, self.geom)
return GeomCoverage(geom, srs)
def intersects(self, bbox, srs):
bbox = self._geom_in_coverage_srs(bbox, srs)
with self._prep_lock:
return self.prepared_geom.intersects(bbox)
def intersection(self, bbox, srs):
bbox = self._geom_in_coverage_srs(bbox, srs)
return GeomCoverage(self.geom.intersection(bbox), self.srs)
def contains(self, bbox, srs):
bbox = self._geom_in_coverage_srs(bbox, srs)
with self._prep_lock:
return self.prepared_geom.contains(bbox)
def __eq__(self, other):
if not isinstance(other, GeomCoverage):
return NotImplemented
if self.srs != other.srs:
return False
if self.bbox != other.bbox:
return False
if not self.geom.equals(other.geom):
return False
return True
def __ne__(self, other):
if not isinstance(other, GeomCoverage):
return NotImplemented
return not self.__eq__(other)
def __repr__(self):
return '<GeomCoverage %r: %r>' % (self.extent.llbbox, self.geom) | Anderson0026/mapproxy | mapproxy/util/coverage.py | Python | apache-2.0 | 7,709 |
# Quamoclit multifida Raf. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
New Fl. 4:57. 1838 "<I>Quamoctita</I>"
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Ipomoea/Ipomoea multifida/ Syn. Quamoclit multifida/README.md | Markdown | apache-2.0 | 215 |
package ru.maizy.ambient7.core.data
/**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2016-2017
* See LICENSE.txt for details.
*/
import java.time.ZonedDateTime
case class Co2AggregatedLevels(
lowLevel: Int,
mediumLevel: Int,
highLevel: Int,
unknownLevel: Int,
from: ZonedDateTime,
to: ZonedDateTime,
agentId: Co2Agent
) {
override def toString: String = s"Co2AggregatedLevels(low=$lowLevel, med=$mediumLevel, high=$highLevel, " +
s"unknown=$unknownLevel, $from->$to, agent=${agentId.agentName}, tags=${agentId.tags})"
def hasAnyResult: Boolean =
lowLevel > 0 || mediumLevel > 0 || highLevel > 0
def combine(other: Co2AggregatedLevels): Co2AggregatedLevels =
copy(
lowLevel = lowLevel + other.lowLevel,
mediumLevel = mediumLevel + other.mediumLevel,
highLevel = highLevel + other.highLevel,
unknownLevel = unknownLevel + other.unknownLevel,
if (other.from.compareTo(from) < 0) other.from else from,
if (other.to.compareTo(to) > 0) other.to else to
)
}
| maizy/ambient7 | core/src/main/scala/ru/maizy/ambient7/core/data/Co2AggregatedLevels.scala | Scala | apache-2.0 | 1,045 |
jQuery(function($) {
//smooth scroll
$('.navbar-nav > li.anchor').click(function(event) {
//event.preventDefault();
var target = $(this).find('>a').prop('hash');
$('#navbar .active').removeClass('active');
$(this).addClass('active');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 500);
});
//scrollspy
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
});
$(function() {
$(".navbar-btn").click(function() {
$("#options").toggle();
$(".navbar-btn .glyphicon").toggleClass("glyphicon-plus")
.toggleClass("glyphicon-minus");
});
});
}); | clinm/visu-regions-autonomes-france | js/main.js | JavaScript | apache-2.0 | 656 |
// Licensed under the Apache License, Version 2.0
// Details: https://raw.githubusercontent.com/square/quotaservice/master/LICENSE
// Package memory implements token buckets in memory, inspired by the algorithms used in Guava's
// RateLimiter library - https://github.com/google/guava/blob/master/guava/src/com/google/common/util/concurrent/RateLimiter.java
// Note that this implementation spins up a goroutine *per bucket* that's created. That can get
// expensive, and is not recommended for production use, with a large number of static or dynamic
// buckets.
package memory
import (
"context"
"time"
"github.com/square/quotaservice"
"github.com/square/quotaservice/config"
"github.com/square/quotaservice/logging"
pbconfig "github.com/square/quotaservice/protos/config"
)
type bucketFactory struct {
cfg *pbconfig.ServiceConfig
}
func (bf *bucketFactory) Init(cfg *pbconfig.ServiceConfig) {
bf.cfg = cfg
}
func (bf *bucketFactory) Client() interface{} {
return nil
}
func (bf *bucketFactory) NewBucket(namespace, bucketName string, cfg *pbconfig.BucketConfig, dyn bool) quotaservice.Bucket {
// fill rate is tokens-per-second.
bucket := &tokenBucket{
dynamic: dyn,
cfg: cfg,
nanosBetweenTokens: 1e9 / cfg.FillRate,
accumulatedTokens: cfg.Size, // Start full
fullName: config.FullyQualifiedName(namespace, bucketName),
waitTimer: make(chan *waitTimeReq),
closer: make(chan struct{})}
go bucket.waitTimeLoop()
return bucket
}
func NewBucketFactory() quotaservice.BucketFactory {
return &bucketFactory{}
}
// tokenBucket is a single-threaded implementation. A single goroutine updates the values of
// tokensNextAvailable and accumulatedTokens. When requesting tokens, Take() puts a request on
// the waitTimer channel, and listens on the response channel in the request for a result. The
// goroutine is shut down when Destroy() is called on this bucket. In-flight requests will be
// served, but new requests will not.
type tokenBucket struct {
dynamic bool
cfg *pbconfig.BucketConfig
nanosBetweenTokens int64
tokensNextAvailableNanos int64
accumulatedTokens int64
fullName string
waitTimer chan *waitTimeReq
closer chan struct{}
quotaservice.DefaultBucket // Extension for default methods on interface
}
// waitTimeReq is a request that you put on the channel for the waitTimer goroutine to pick up and
// process.
type waitTimeReq struct {
requested, maxWaitTimeNanos int64
response chan int64
}
func (b *tokenBucket) Take(_ context.Context, numTokens int64, maxWaitTime time.Duration) (time.Duration, bool) {
rsp := make(chan int64, 1)
b.waitTimer <- &waitTimeReq{numTokens, maxWaitTime.Nanoseconds(), rsp}
waitTimeNanos := <-rsp
if waitTimeNanos < 0 {
// Timed out
return 0, false
}
return time.Duration(waitTimeNanos) * time.Nanosecond, true
}
// calcWaitTime is designed to run in a single event loop and is not thread-safe.
func (b *tokenBucket) calcWaitTime(requested, maxWaitTimeNanos int64) (waitTimeNanos int64) {
currentTimeNanos := time.Now().UnixNano()
tna := b.tokensNextAvailableNanos
ac := b.accumulatedTokens
var freshTokens int64
if currentTimeNanos > tna {
freshTokens = (currentTimeNanos - tna) / b.nanosBetweenTokens
ac = min(b.cfg.Size, ac+freshTokens)
tna = currentTimeNanos
}
waitTimeNanos = tna - currentTimeNanos
accumulatedTokensUsed := min(ac, requested)
tokensToWaitFor := requested - accumulatedTokensUsed
futureWaitNanos := tokensToWaitFor * b.nanosBetweenTokens
tna += futureWaitNanos
ac -= accumulatedTokensUsed
if (tna-currentTimeNanos > b.cfg.MaxDebtMillis*1e6) || (waitTimeNanos > 0 && waitTimeNanos > maxWaitTimeNanos) {
waitTimeNanos = -1
} else {
b.tokensNextAvailableNanos = tna
b.accumulatedTokens = ac
}
return waitTimeNanos
}
func min(x, y int64) int64 {
if x < y {
return x
}
return y
}
// waitTimeLoop is the single event loop that claims tokens on a given bucket.
func (b *tokenBucket) waitTimeLoop() {
for {
select {
case req := <-b.waitTimer:
req.response <- b.calcWaitTime(req.requested, req.maxWaitTimeNanos)
case <-b.closer:
logging.Printf("Garbage collecting bucket %v", b.fullName)
// TODO(manik) properly notify goroutines who are currently trying to write to waitTimer
return
}
}
}
func (b *tokenBucket) Config() *pbconfig.BucketConfig {
return b.cfg
}
func (b *tokenBucket) Dynamic() bool {
return b.dynamic
}
func (b *tokenBucket) Destroy() {
// Signal the waitTimeLoop to exit
close(b.closer)
}
| maniksurtani/quotaservice | buckets/memory/bucket.go | GO | apache-2.0 | 4,687 |
<?php
namespace Academe\Instructions;
use Academe\Contracts\Mapper\Executable;
abstract class BaseExecutable implements Executable
{
} | AaronJan/Academe | src/Academe/Instructions/BaseExecutable.php | PHP | apache-2.0 | 147 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/;
var VER_REG = /[\W][\d\w]+(?=\.\w+$)/;
var _default = function _default(req, res, next) {
var filePaths = req.url.split('/');
if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') {
filePaths.splice(2, 1);
req.url = filePaths.join('/').replace(VER_REG, '');
}
next();
};
exports["default"] = _default; | angrytoro/fetool | lib/server/middlewares/webpackStatic.js | JavaScript | apache-2.0 | 497 |
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function toSnakeCase(camelCase) {
if (!camelCase) {
throw new Error("Please provide camelCase.");
}
return camelCase.replace(/([A-Z])/g, "-$1").toLowerCase();
}
exports_1("toSnakeCase", toSnakeCase);
return {
setters: [],
execute: function () {
}
};
});
//# sourceMappingURL=to.snake.case.js.map | roelvanlisdonk/dev | apps/sportersonline/www/libraries/am/common/text/to.snake.case.js | JavaScript | apache-2.0 | 497 |
package com.gotcreations.emojilibrary.controller;
import android.animation.Animator;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import androidx.annotation.DrawableRes;
import androidx.appcompat.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.gotcreations.emojilibrary.R;
import com.gotcreations.emojilibrary.model.layout.EmojiCompatActivity;
import com.gotcreations.emojilibrary.model.layout.EmojiEditText;
import com.gotcreations.emojilibrary.model.layout.AppPanelEventListener;
import com.gotcreations.emojilibrary.model.layout.TelegramPanelView;
import com.gotcreations.emojilibrary.util.AbstractAnimatorListener;
import static android.view.View.GONE;
import static android.view.View.getDefaultSize;
/**
* Created by edgar on 18/02/2016.
*/
public class TelegramPanel extends AppPanel{
private static final String TAG = "TelegramPanel";
public static final int EMPTY_MESSAGE = 0;
public static final int EMPTY_MESSAGE_EMOJI_KEYBOARD = 1;
public static final int EMPTY_MESSAGE_KEYBOARD = 2;
public static final int PREPARED_MESSAGE = 3;
public static final int PREPARED_MESSAGE_EMOJI_KEYBOARD = 4;
public static final int PREPARED_MESSAGE_KEYBOARD = 5;
public static final int AUDIO = 6;
private Toolbar mBottomPanel;
private TextView audioTime;
private TelegramPanelView panelView;
private int state;
// CONSTRUCTOR
public TelegramPanel(EmojiCompatActivity activity, AppPanelEventListener listener) {
super(activity);
this.mActivity = activity;
init();
this.mEmojiKeyboard = new EmojiKeyboard(this.mActivity, this.mInput);
this.mListener = listener;
}
public TelegramPanel(EmojiCompatActivity activity) {
this(activity, null);
}
// INITIALIZATION
@Override
protected void initBottomPanel() {
this.audioTime = (TextView) this.mActivity.findViewById(R.id.audio_time);
this.mBottomPanel = (Toolbar) this.mActivity.findViewById(R.id.panel);
this.panelView = (TelegramPanelView) this.mActivity.findViewById(R.id.panel_container).getParent();
this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji);
this.mBottomPanel.inflateMenu(R.menu.telegram_menu);
this.mBottomPanel.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (state == AUDIO) {
fireOnMicOffClicked();
showAudioPanel(false);
} else if (TelegramPanel.this.isEmojiKeyboardVisible) {
TelegramPanel.this.closeCurtain();
if (TelegramPanel.this.mInput.isSoftKeyboardVisible()) {
TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard);
TelegramPanel.this.mInput.hideSoftKeyboard();
} else {
TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji);
TelegramPanel.this.mInput.showSoftKeyboard();
}
} else {
TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard);
TelegramPanel.this.closeCurtain();
TelegramPanel.this.showEmojiKeyboard(0);
}
}
});
this.mBottomPanel.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.action_attach) {
fireOnAttachClicked();
} else if (item.getItemId() == R.id.action_mic) {
switch (state) {
case AUDIO:
fireOnSendClicked();
showAudioPanel(false);
break;
default:
if (TelegramPanel.this.mInput.getText().toString().equals("")) {
showAudioPanel(true);
} else {
fireOnSendClicked();
}
}
}
return Boolean.TRUE;
}
});
this.mCurtain = (LinearLayout) this.mActivity.findViewById(R.id.curtain);
this.state = EMPTY_MESSAGE;
}
@Override
protected void setInputConfig() {
this.mInput = (EmojiEditText) this.mBottomPanel.findViewById(R.id.input);
mInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
this.mInput.addOnSoftKeyboardListener(new EmojiEditText.OnSoftKeyboardListener() {
@Override
public void onSoftKeyboardDisplay() {
if (!TelegramPanel.this.isEmojiKeyboardVisible) {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(new Runnable() {
@Override
public void run() {
Handler mainHandler = new Handler(TelegramPanel.this.mActivity.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
TelegramPanel.this.openCurtain();
TelegramPanel.this.showEmojiKeyboard(0);
}
};
mainHandler.post(myRunnable);
}
}, 150, TimeUnit.MILLISECONDS);
}
}
@Override
public void onSoftKeyboardHidden() {
if (TelegramPanel.this.isEmojiKeyboardVisible) {
TelegramPanel.this.closeCurtain();
TelegramPanel.this.hideEmojiKeyboard(200);
}
}
});
this.mInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
showSendOptions(true);
}
@Override
public void afterTextChanged(Editable s) {
}
});
audioTime.setTextColor(panelView.getAudioTextColor());
mInput.setTextColor(panelView.getTextColor());
mInput.setHint(panelView.getHintText());
mInput.setHintTextColor(panelView.getTextColorHint());
setIcon(R.id.action_attach, panelView.getAttachIconColor(), R.drawable.ic_attachment);
setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic);
}
private void setIcon(int itemId, int color, @DrawableRes int drawableId) {
Drawable icon = mActivity.getResources().getDrawable(drawableId);
icon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
setIcon(itemId, icon);
}
private void setIcon(int itemId, Drawable icon) {
Menu menu = this.mBottomPanel.getMenu();
MenuItem mi = menu.findItem(itemId);
mi.setIcon(icon);
}
@Override
public void showAudioPanel(final boolean show) {
if (show) {
state = AUDIO;
hideEmojiKeyboard(0);
this.mInput.hideSoftKeyboard();
this.mInput.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
Log.d(TAG, "Hide mInput");
mInput.setVisibility(GONE);
}
}).start();
this.audioTime.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
Log.d(TAG, "show audioTime");
audioTime.setVisibility(View.VISIBLE);
}
}).start();
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() {
@Override
public void run() {
setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send);
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start();
}
}).start();
}
Drawable icCircle = mActivity.getResources().getDrawable(R.drawable.ic_circle);
icCircle.setColorFilter(panelView.getAudioIconColor(), PorterDuff.Mode.SRC_ATOP);
this.mBottomPanel.setNavigationIcon(icCircle);
fireOnMicOnClicked();
} else {
this.audioTime.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
Log.d(TAG, "Hide audioInput");
audioTime.setVisibility(GONE);
}
}).start();
this.mInput.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
Log.d(TAG, "Show mInput");
mInput.setVisibility(View.VISIBLE);
}
}).start();
showSendOptions(true);
}
}
public void showSendOptions(boolean show) {
final MenuItem micButton = TelegramPanel.this.mBottomPanel.getMenu().findItem(R.id.action_mic);
if (isEmojiKeyboardVisible) {
this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard);
} else {
this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji);
}
if (!this.mInput.getText().toString().equals("") && show) {
if (state != PREPARED_MESSAGE && state != PREPARED_MESSAGE_EMOJI_KEYBOARD && state != PREPARED_MESSAGE_KEYBOARD) {
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() {
@Override
public void run() {
setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send);
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start();
}
}).start();
}
}
state = PREPARED_MESSAGE;
if (mInput.isSoftKeyboardVisible()) {
state = PREPARED_MESSAGE_KEYBOARD;
} else if (isEmojiKeyboardVisible) {
state = PREPARED_MESSAGE_EMOJI_KEYBOARD;
}
} else {
state = EMPTY_MESSAGE;
if (mInput.isSoftKeyboardVisible()) {
state = EMPTY_MESSAGE_KEYBOARD;
} else if (isEmojiKeyboardVisible) {
state = EMPTY_MESSAGE_EMOJI_KEYBOARD;
}
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(1).scaleY(1).setDuration(150).start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() {
@Override
public void run() {
setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic);
TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start();
}
}).start();
}
}
}
public int getState() {
return state;
}
public boolean isInState(int state) {
return this.state == state;
}
public boolean isInAudioState() {
return isInState(AUDIO);
}
public boolean isInMessageState() {
return !isInAudioState();
}
@Override
public void hideEmojiKeyboard(int delay) {
super.hideEmojiKeyboard(delay);
this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji);
}
public void setAudioTime(CharSequence time) {
this.audioTime.setText(time);
}
}
| ander7agar/emoji-keyboard | emoji-library/src/main/java/com/gotcreations/emojilibrary/controller/TelegramPanel.java | Java | apache-2.0 | 13,759 |
/**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.controller.server.eventProcessor.requesthandlers;
import com.google.common.annotations.VisibleForTesting;
import io.pravega.common.Timer;
import io.pravega.common.concurrent.Futures;
import io.pravega.common.tracing.TagLogger;
import io.pravega.controller.eventProcessor.impl.SerializedRequestHandler;
import io.pravega.controller.metrics.TransactionMetrics;
import io.pravega.controller.server.ControllerService;
import io.pravega.controller.store.stream.OperationContext;
import io.pravega.controller.store.stream.StreamMetadataStore;
import io.pravega.controller.store.stream.records.StreamSegmentRecord;
import io.pravega.controller.task.Stream.StreamMetadataTasks;
import io.pravega.shared.controller.event.AbortEvent;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import org.slf4j.LoggerFactory;
/**
* This actor processes commit txn events.
* It does the following 2 operations in order.
* 1. Send abort txn message to active segments of the stream.
* 2. Change txn state from aborting to aborted.
*/
public class AbortRequestHandler extends SerializedRequestHandler<AbortEvent> {
private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(AbortRequestHandler.class));
private final StreamMetadataStore streamMetadataStore;
private final StreamMetadataTasks streamMetadataTasks;
private final ScheduledExecutorService executor;
private final BlockingQueue<AbortEvent> processedEvents;
@VisibleForTesting
public AbortRequestHandler(final StreamMetadataStore streamMetadataStore,
final StreamMetadataTasks streamMetadataTasks,
final ScheduledExecutorService executor,
final BlockingQueue<AbortEvent> queue) {
super(executor);
this.streamMetadataStore = streamMetadataStore;
this.streamMetadataTasks = streamMetadataTasks;
this.executor = executor;
this.processedEvents = queue;
}
public AbortRequestHandler(final StreamMetadataStore streamMetadataStore,
final StreamMetadataTasks streamMetadataTasks,
final ScheduledExecutorService executor) {
super(executor);
this.streamMetadataStore = streamMetadataStore;
this.streamMetadataTasks = streamMetadataTasks;
this.executor = executor;
this.processedEvents = null;
}
@Override
public CompletableFuture<Void> processEvent(AbortEvent event) {
String scope = event.getScope();
String stream = event.getStream();
int epoch = event.getEpoch();
UUID txId = event.getTxid();
long requestId = event.getRequestId();
if (requestId == 0L) {
requestId = ControllerService.nextRequestId();
}
Timer timer = new Timer();
OperationContext context = streamMetadataStore.createStreamContext(scope, stream, requestId);
log.info(requestId, "Aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(),
event.getStream());
return Futures.toVoid(streamMetadataStore.getSegmentsInEpoch(event.getScope(), event.getStream(), epoch, context,
executor)
.thenApply(segments -> segments.stream().map(StreamSegmentRecord::segmentId)
.collect(Collectors.toList()))
.thenCompose(segments -> streamMetadataTasks.notifyTxnAbort(scope, stream, segments, txId, context.getRequestId()))
.thenCompose(x -> streamMetadataStore.abortTransaction(scope, stream, txId, context, executor))
.whenComplete((result, error) -> {
if (error != null) {
log.warn(context.getRequestId(), "Failed aborting transaction {} on stream {}/{}", event.getTxid(),
event.getScope(), event.getStream());
TransactionMetrics.getInstance().abortTransactionFailed(scope, stream);
} else {
log.info(context.getRequestId(), "Successfully aborted transaction {} on stream {}/{}", event.getTxid(),
event.getScope(), event.getStream());
if (processedEvents != null) {
processedEvents.offer(event);
}
TransactionMetrics.getInstance().abortTransaction(scope, stream, timer.getElapsed());
}
}));
}
}
| pravega/pravega | controller/src/main/java/io/pravega/controller/server/eventProcessor/requesthandlers/AbortRequestHandler.java | Java | apache-2.0 | 5,395 |
# Halanthium purpureum (Moq.) Bunge SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Chenopodiaceae/Halanthium/Halanthium purpureum/README.md | Markdown | apache-2.0 | 191 |
# Copyright (c) 2019 Infortrend Technology, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
class InfortrendNASTestData(object):
fake_share_id = ['5a0aa06e-1c57-4996-be46-b81e360e8866', # NFS
'aac4fe64-7a9c-472a-b156-9adbb50b4d29'] # CIFS
fake_share_name = [fake_share_id[0].replace('-', ''),
fake_share_id[1].replace('-', '')]
fake_channel_ip = ['172.27.112.223', '172.27.113.209']
fake_service_status_data = ('(64175, 1234, 272, 0)\n\n'
'{"cliCode": '
'[{"Return": "0x0000", "CLI": "Successful"}], '
'"returnCode": [], '
'"data": '
'[{"A": '
'{"NFS": '
'{"displayName": "NFS", '
'"state_time": "2017-05-04 14:19:53", '
'"enabled": true, '
'"cpu_rate": "0.0", '
'"mem_rate": "0.0", '
'"state": "exited", '
'"type": "share"}}}]}\n\n')
fake_folder_status_data = ('(64175, 1234, 1017, 0)\n\n'
'{"cliCode": '
'[{"Return": "0x0000", "CLI": "Successful"}], '
'"returnCode": [], '
'"data": '
'[{"utility": "1.00", '
'"used": "33886208", '
'"subshare": true, '
'"share": false, '
'"worm": "", '
'"free": "321931374592", '
'"fsType": "xfs", '
'"owner": "A", '
'"readOnly": false, '
'"modifyTime": "2017-04-27 16:16", '
'"directory": "/share-pool-01/LV-1", '
'"volumeId": "6541BAFB2E6C57B6", '
'"mounted": true, '
'"size": "321965260800"}, '
'{"utility": "1.00", '
'"used": "33779712", '
'"subshare": false, '
'"share": false, '
'"worm": "", '
'"free": "107287973888", '
'"fsType": "xfs", '
'"owner": "A", '
'"readOnly": false, '
'"modifyTime": "2017-04-27 15:45", '
'"directory": "/share-pool-02/LV-1", '
'"volumeId": "147A8FB67DA39914", '
'"mounted": true, '
'"size": "107321753600"}]}\n\n')
fake_nfs_status_off = [{
'A': {
'NFS': {
'displayName': 'NFS',
'state_time': '2017-05-04 14:19:53',
'enabled': False,
'cpu_rate': '0.0',
'mem_rate': '0.0',
'state': 'exited',
'type': 'share',
}
}
}]
fake_folder_status = [{
'utility': '1.00',
'used': '33886208',
'subshare': True,
'share': False,
'worm': '',
'free': '321931374592',
'fsType': 'xfs',
'owner': 'A',
'readOnly': False,
'modifyTime': '2017-04-27 16:16',
'directory': '/share-pool-01/LV-1',
'volumeId': '6541BAFB2E6C57B6',
'mounted': True,
'size': '321965260800'}, {
'utility': '1.00',
'used': '33779712',
'subshare': False,
'share': False,
'worm': '',
'free': '107287973888',
'fsType': 'xfs',
'owner': 'A',
'readOnly': False,
'modifyTime': '2017-04-27 15:45',
'directory': '/share-pool-02/LV-1',
'volumeId': '147A8FB67DA39914',
'mounted': True,
'size': '107321753600',
}]
def fake_get_channel_status(self, ch1_status='UP'):
return [{
'datalink': 'mgmt0',
'status': 'UP',
'typeConfig': 'DHCP',
'IP': '172.27.112.125',
'MAC': '00:d0:23:00:15:a6',
'netmask': '255.255.240.0',
'type': 'dhcp',
'gateway': '172.27.127.254'}, {
'datalink': 'CH0',
'status': 'UP',
'typeConfig': 'DHCP',
'IP': self.fake_channel_ip[0],
'MAC': '00:d0:23:80:15:a6',
'netmask': '255.255.240.0',
'type': 'dhcp',
'gateway': '172.27.127.254'}, {
'datalink': 'CH1',
'status': ch1_status,
'typeConfig': 'DHCP',
'IP': self.fake_channel_ip[1],
'MAC': '00:d0:23:40:15:a6',
'netmask': '255.255.240.0',
'type': 'dhcp',
'gateway': '172.27.127.254'}, {
'datalink': 'CH2',
'status': 'DOWN',
'typeConfig': 'DHCP',
'IP': '',
'MAC': '00:d0:23:c0:15:a6',
'netmask': '',
'type': '',
'gateway': ''}, {
'datalink': 'CH3',
'status': 'DOWN',
'typeConfig': 'DHCP',
'IP': '',
'MAC': '00:d0:23:20:15:a6',
'netmask': '',
'type': '',
'gateway': '',
}]
fake_fquota_status = [{
'quota': '21474836480',
'used': '0',
'name': 'test-folder',
'type': 'subfolder',
'id': '537178178'}, {
'quota': '32212254720',
'used': '0',
'name': fake_share_name[0],
'type': 'subfolder',
'id': '805306752'}, {
'quota': '53687091200',
'used': '21474836480',
'name': fake_share_name[1],
'type': 'subfolder',
'id': '69'}, {
'quota': '94091997184',
'used': '0',
'type': 'subfolder',
'id': '70',
"name": 'test-folder-02'
}]
fake_fquota_status_with_no_settings = []
def fake_get_share_status_nfs(self, status=False):
fake_share_status_nfs = [{
'ftp': False,
'cifs': False,
'oss': False,
'sftp': False,
'nfs': status,
'directory': '/LV-1/share-pool-01/' + self.fake_share_name[0],
'exist': True,
'afp': False,
'webdav': False
}]
if status:
fake_share_status_nfs[0]['nfs_detail'] = {
'hostList': [{
'uid': '65534',
'insecure': 'insecure',
'squash': 'all',
'access': 'ro',
'host': '*',
'gid': '65534',
'mode': 'async',
'no_subtree_check': 'no_subtree_check',
}]
}
return fake_share_status_nfs
def fake_get_share_status_cifs(self, status=False):
fake_share_status_cifs = [{
'ftp': False,
'cifs': status,
'oss': False,
'sftp': False,
'nfs': False,
'directory': '/share-pool-01/LV-1/' + self.fake_share_name[1],
'exist': True,
'afp': False,
'webdav': False
}]
if status:
fake_share_status_cifs[0]['cifs_detail'] = {
'available': True,
'encrypt': False,
'description': '',
'sharename': 'cifs-01',
'failover': '',
'AIO': True,
'priv': 'None',
'recycle_bin': False,
'ABE': True,
}
return fake_share_status_cifs
fake_subfolder_data = [{
'size': '6',
'index': '34',
'description': '',
'encryption': '',
'isEnd': False,
'share': False,
'volumeId': '6541BAFB2E6C57B6',
'quota': '',
'modifyTime': '2017-04-06 11:35',
'owner': 'A',
'path': '/share-pool-01/LV-1/UserHome',
'subshare': True,
'type': 'subfolder',
'empty': False,
'name': 'UserHome'}, {
'size': '6',
'index': '39',
'description': '',
'encryption': '',
'isEnd': False,
'share': False,
'volumeId': '6541BAFB2E6C57B6',
'quota': '21474836480',
'modifyTime': '2017-04-27 15:44',
'owner': 'A',
'path': '/share-pool-01/LV-1/test-folder',
'subshare': False,
'type': 'subfolder',
'empty': True,
'name': 'test-folder'}, {
'size': '6',
'index': '45',
'description': '',
'encryption': '',
'isEnd': False,
'share': True,
'volumeId': '6541BAFB2E6C57B6',
'quota': '32212254720',
'modifyTime': '2017-04-27 16:15',
'owner': 'A',
'path': '/share-pool-01/LV-1/' + fake_share_name[0],
'subshare': False,
'type': 'subfolder',
'empty': True,
'name': fake_share_name[0]}, {
'size': '6',
'index': '512',
'description': '',
'encryption': '',
'isEnd': True,
'share': True,
'volumeId': '6541BAFB2E6C57B6',
'quota': '53687091200',
'modifyTime': '2017-04-27 16:16',
'owner': 'A',
'path': '/share-pool-01/LV-1/' + fake_share_name[1],
'subshare': False,
'type': 'subfolder',
'empty': True,
'name': fake_share_name[1]}, {
'size': '6',
'index': '777',
'description': '',
'encryption': '',
'isEnd': False,
'share': False,
'volumeId': '6541BAFB2E6C57B6',
'quota': '94091997184',
'modifyTime': '2017-04-28 15:44',
'owner': 'A',
'path': '/share-pool-01/LV-1/test-folder-02',
'subshare': False,
'type': 'subfolder',
'empty': True,
'name': 'test-folder-02'
}]
fake_cifs_user_list = [{
'Superuser': 'No',
'Group': 'users',
'Description': '',
'Quota': 'none',
'PWD Expiry Date': '2291-01-19',
'Home Directory': '/share-pool-01/LV-1/UserHome/user01',
'UID': '100001',
'Type': 'Local',
'Name': 'user01'}, {
'Superuser': 'No',
'Group': 'users',
'Description': '',
'Quota': 'none',
'PWD Expiry Date': '2017-08-07',
'Home Directory': '/share-pool-01/LV-1/UserHome/user02',
'UID': '100002',
'Type': 'Local',
'Name': 'user02'
}]
fake_share_status_nfs_with_rules = [{
'ftp': False,
'cifs': False,
'oss': False,
'sftp': False,
'nfs': True,
'directory': '/share-pool-01/LV-1/' + fake_share_name[0],
'exist': True,
'nfs_detail': {
'hostList': [{
'uid': '65534',
'insecure': 'insecure',
'squash': 'all',
'access': 'ro',
'host': '*',
'gid': '65534',
'mode': 'async',
'no_subtree_check':
'no_subtree_check'}, {
'uid': '65534',
'insecure': 'insecure',
'squash': 'all',
'access': 'rw',
'host': '172.27.1.1',
'gid': '65534',
'mode': 'async',
'no_subtree_check': 'no_subtree_check'}, {
'uid': '65534',
'insecure': 'insecure',
'squash': 'all',
'access': 'rw',
'host': '172.27.1.2',
'gid': '65534',
'mode': 'async',
'no_subtree_check': 'no_subtree_check'}]
},
'afp': False,
'webdav': False,
}]
fake_share_status_cifs_with_rules = [
{
'permission': {
'Read': True,
'Write': True,
'Execute': True},
'type': 'user',
'id': '100001',
'name': 'user01'
}, {
'permission': {
'Read': True,
'Write': False,
'Execute': True},
'type': 'user',
'id': '100002',
'name': 'user02'
}, {
'permission': {
'Read': True,
'Write': False,
'Execute': True},
'type': 'group@',
'id': '100',
'name': 'users'
}, {
'permission': {
'Read': True,
'Write': False,
'Execute': True},
'type': 'other@',
'id': '',
'name': ''
}
]
| openstack/manila | manila/tests/share/drivers/infortrend/fake_infortrend_nas_data.py | Python | apache-2.0 | 13,722 |
import { createStore, applyMiddleware, compose } from 'redux'
import logger from 'redux-logger'
import thunkMiddleware from 'redux-thunk'
import rootReducer from './reducers'
const configureStore = () => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
return createStore(rootReducer, /* preloadedState, */ composeEnhancers(
applyMiddleware(thunkMiddleware)
// applyMiddleware(logger)
));
}
export default configureStore
| AleksandrRogachev94/chat-vote-go-frontend | src/configureStore.js | JavaScript | apache-2.0 | 471 |
(function outer(modules, cache, entries){
/**
* Global
*/
var global = (function(){ return this; })();
/**
* Require `name`.
*
* @param {String} name
* @param {Boolean} jumped
* @api public
*/
function require(name, jumped){
if (cache[name]) return cache[name].exports;
if (modules[name]) return call(name, require);
throw new Error('cannot find module "' + name + '"');
}
/**
* Call module `id` and cache it.
*
* @param {Number} id
* @param {Function} require
* @return {Function}
* @api private
*/
function call(id, require){
var m = cache[id] = { exports: {} };
var mod = modules[id];
var name = mod[2];
var fn = mod[0];
fn.call(m.exports, function(req){
var dep = modules[id][1][req];
return require(dep ? dep : req);
}, m, m.exports, outer, modules, cache, entries);
// expose as `name`.
if (name) cache[name] = cache[id];
return cache[id].exports;
}
/**
* Require all entries exposing them on global if needed.
*/
for (var id in entries) {
if (entries[id]) {
global[entries[id]] = require(id);
} else {
require(id);
}
}
/**
* Duo flag.
*/
require.duo = true;
/**
* Expose cache.
*/
require.cache = cache;
/**
* Expose modules
*/
require.modules = modules;
/**
* Return newest require.
*/
return require;
})({
1: [function(require, module, exports) {
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, "Hello, world!"),
document.getElementById('example')
);
}, {}]}, {}, {"1":""})
| wdamron/duo-jsx | test/exp_react.js | JavaScript | apache-2.0 | 1,625 |
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.directio.hive.serde;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.apache.hadoop.hive.common.type.HiveChar;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.serde2.io.HiveCharWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable;
import org.apache.hadoop.hive.serde2.io.TimestampWritable;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector;
import org.apache.hadoop.io.Text;
import org.junit.Test;
import com.asakusafw.runtime.value.Date;
import com.asakusafw.runtime.value.DateOption;
import com.asakusafw.runtime.value.DateTime;
import com.asakusafw.runtime.value.DateTimeOption;
import com.asakusafw.runtime.value.DecimalOption;
import com.asakusafw.runtime.value.StringOption;
/**
* Test for {@link ValueSerdeFactory}.
*/
public class ValueSerdeFactoryTest {
/**
* constants.
*/
@Test
public void constants() {
for (ValueSerdeFactory serde : ValueSerdeFactory.values()) {
serde.getDriver(serde.getInspector());
}
}
/**
* char.
*/
@Test
public void getChar() {
ValueSerde serde = ValueSerdeFactory.getChar(10);
HiveCharObjectInspector inspector = (HiveCharObjectInspector) serde.getInspector();
StringOption option = new StringOption("hello");
HiveChar value = new HiveChar("hello", 10);
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveCharWritable(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
StringOption copy = new StringOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* varchar.
*/
@Test
public void getVarchar() {
ValueSerde serde = ValueSerdeFactory.getVarchar(10);
HiveVarcharObjectInspector inspector = (HiveVarcharObjectInspector) serde.getInspector();
StringOption option = new StringOption("hello");
HiveVarchar value = new HiveVarchar("hello", 10);
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
// HiveVarchar cannot compare by equals
assertThat(inspector.getPrimitiveJavaObject(option).compareTo(value), is(0));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveVarcharWritable(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
StringOption copy = new StringOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* qualified decimal.
*/
@Test
public void getDecimal() {
ValueSerde serde = ValueSerdeFactory.getDecimal(10, 2);
HiveDecimalObjectInspector inspector = (HiveDecimalObjectInspector) serde.getInspector();
DecimalOption option = new DecimalOption(new BigDecimal("123.45"));
HiveDecimal value = HiveDecimal.create(new BigDecimal("123.45"));
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveDecimalWritable(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DecimalOption copy = new DecimalOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* decimal by string.
*/
@Test
public void decimal_by_string() {
ValueSerde serde = StringValueSerdeFactory.DECIMAL;
StringObjectInspector inspector = (StringObjectInspector) serde.getInspector();
DecimalOption option = new DecimalOption(new BigDecimal("123.45"));
String value = "123.45";
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DecimalOption copy = new DecimalOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* date by string.
*/
@Test
public void date_by_string() {
ValueSerde serde = StringValueSerdeFactory.DATE;
StringObjectInspector inspector = (StringObjectInspector) serde.getInspector();
DateOption option = new DateOption(new Date(2014, 7, 1));
String value = "2014-07-01";
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DateOption copy = new DateOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* date-time by string.
*/
@Test
public void datetime_by_string() {
ValueSerde serde = StringValueSerdeFactory.DATETIME;
StringObjectInspector inspector = (StringObjectInspector) serde.getInspector();
DateTimeOption option = new DateTimeOption(new DateTime(2014, 7, 1, 12, 5, 59));
String value = "2014-07-01 12:05:59";
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DateTimeOption copy = new DateTimeOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* date-time by string.
*/
@Test
public void datetime_by_string_w_zeros() {
ValueSerde serde = StringValueSerdeFactory.DATETIME;
StringObjectInspector inspector = (StringObjectInspector) serde.getInspector();
DateTimeOption option = new DateTimeOption(new DateTime(1, 1, 1, 0, 0, 0));
String value = "0001-01-01 00:00:00";
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DateTimeOption copy = new DateTimeOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
/**
* date by timestamp.
*/
@SuppressWarnings("deprecation")
@Test
public void date_by_timestamp() {
ValueSerde serde = TimestampValueSerdeFactory.DATE;
TimestampObjectInspector inspector = (TimestampObjectInspector) serde.getInspector();
DateOption option = new DateOption(new Date(2014, 7, 1));
Timestamp value = new Timestamp(2014 - 1900, 7 - 1, 1, 0, 0, 0, 0);
assertThat(inspector.copyObject(option), is((Object) option));
assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option))));
assertThat(inspector.copyObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveJavaObject(option), is(value));
assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue()));
assertThat(inspector.getPrimitiveWritableObject(option), is(new TimestampWritable(value)));
assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue()));
ValueDriver driver = serde.getDriver(inspector);
DateOption copy = new DateOption();
driver.set(copy, option);
assertThat(copy, is(option));
driver.set(copy, null);
assertThat(copy.isNull(), is(true));
}
}
| asakusafw/asakusafw | hive-project/core-v2/src/test/java/com/asakusafw/directio/hive/serde/ValueSerdeFactoryTest.java | Java | apache-2.0 | 11,792 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare module '*.less';
declare function la(textToLocalize: string): string;
| dremio/dremio-oss | dac/ui/src/modules.d.ts | TypeScript | apache-2.0 | 689 |
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Embeds an instagram photo. The data-shortcode attribute can be
* easily copied from a normal instagram URL. Example: <code> <amp-instagram
* data-shortcode="fBwFP" data-captioned data-default-framing alt="Fastest page
* in the west." width="320" height="392" layout="responsive"> </amp-instagram>
* </code>
*
* For responsive embedding the width and height can be left unchanged from the
* example above and should produce the correct aspect ratio. amp-instagram will
* attempt to resize on load based on the height reported by the embedded frame.
* If captions are specified (data-captioned) then a resize will be requested
* every time due to the fact that it's not possible to know the height of the
* caption in advance.
*
* If captions are included it is stringly reccomended that an overflow element
* is also included. See description of overflow in amp-iframe.
*
* If data-default-framing is present will apply the default instagram frame
* style without changing the layout/size.
*/
import {CSS} from '../../../build/amp-instagram-0.1.css';
import {getData, listen} from '../../../src/event-helper';
import {isLayoutSizeDefined} from '../../../src/layout';
import {isObject} from '../../../src/types';
import {removeElement} from '../../../src/dom';
import {setStyles} from '../../../src/style';
import {startsWith} from '../../../src/string';
import {tryParseJson} from '../../../src/json';
import {user} from '../../../src/log';
class AmpInstagram extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?Element} */
this.iframe_ = null;
/** @private {?string} */
this.shortcode_ = '';
/** @private {?Function} */
this.unlistenMessage_ = null;
/** @private {string} */
this.captioned_ = '';
/**
* @private {?Promise}
* @visibleForTesting
*/
this.iframePromise_ = null;
}
/**
* @param {boolean=} opt_onLayout
* @override
*/
preconnectCallback(opt_onLayout) {
// See
// https://instagram.com/developer/embedding/?hl=en
this.preconnect.url('https://www.instagram.com', opt_onLayout);
// Host instagram used for image serving. While the host name is
// funky this appears to be stable in the post-domain sharding era.
this.preconnect.url('https://instagram.fsnc1-1.fna.fbcdn.net',
opt_onLayout);
}
/** @override */
renderOutsideViewport() {
return false;
}
/** @override */
buildCallback() {
this.shortcode_ = user().assert(
(this.element.getAttribute('data-shortcode') ||
this.element.getAttribute('shortcode')),
'The data-shortcode attribute is required for <amp-instagram> %s',
this.element);
this.captioned_ = this.element.hasAttribute('data-captioned') ?
'captioned/' : '';
}
/** @override */
createPlaceholderCallback() {
const placeholder = this.win.document.createElement('div');
placeholder.setAttribute('placeholder', '');
const image = this.win.document.createElement('amp-img');
image.setAttribute('noprerender', '');
// This will redirect to the image URL. By experimentation this is
// always the same URL that is actually used inside of the embed.
image.setAttribute('src', 'https://www.instagram.com/p/' +
encodeURIComponent(this.shortcode_) + '/media/?size=l');
image.setAttribute('layout', 'fill');
image.setAttribute('referrerpolicy', 'origin');
this.propagateAttributes(['alt'], image);
/*
* Add instagram default styling
*/
if (this.element.hasAttribute('data-default-framing')) {
this.element.classList.add('amp-instagram-default-framing');
}
// This makes the non-iframe image appear in the exact same spot
// where it will be inside of the iframe.
setStyles(image, {
'top': '0 px',
'bottom': '0 px',
'left': '0 px',
'right': '0 px',
});
placeholder.appendChild(image);
return placeholder;
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
layoutCallback() {
const iframe = this.element.ownerDocument.createElement('iframe');
this.iframe_ = iframe;
this.unlistenMessage_ = listen(
this.win,
'message',
this.handleInstagramMessages_.bind(this)
);
iframe.setAttribute('scrolling', 'no');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowtransparency', 'true');
//Add title to the iframe for better accessibility.
iframe.setAttribute('title', 'Instagram: ' +
this.element.getAttribute('alt'));
iframe.src = 'https://www.instagram.com/p/' +
encodeURIComponent(this.shortcode_) + '/embed/' +
this.captioned_ + '?cr=1&v=7';
this.applyFillContent(iframe);
this.element.appendChild(iframe);
setStyles(iframe, {
'opacity': 0,
});
return this.iframePromise_ = this.loadPromise(iframe).then(() => {
this.getVsync().mutate(() => {
setStyles(iframe, {
'opacity': 1,
});
});
});
}
/**
* @param {!Event} event
* @private
*/
handleInstagramMessages_(event) {
if (event.origin != 'https://www.instagram.com' ||
event.source != this.iframe_.contentWindow) {
return;
}
const eventData = getData(event);
if (!eventData || !(isObject(eventData)
|| startsWith(/** @type {string} */ (eventData), '{'))) {
return; // Doesn't look like JSON.
}
const data = isObject(eventData) ? eventData : tryParseJson(eventData);
if (data === undefined) {
return; // We only process valid JSON.
}
if (data['type'] == 'MEASURE' && data['details']) {
const height = data['details']['height'];
this.getVsync().measure(() => {
if (this.iframe_ && this.iframe_./*OK*/offsetHeight !== height) {
this./*OK*/changeHeight(height);
}
});
}
}
/** @override */
unlayoutOnPause() {
return true;
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
this.iframePromise_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
}
return true; // Call layoutCallback again.
}
}
AMP.extension('amp-instagram', '0.1', AMP => {
AMP.registerElement('amp-instagram', AmpInstagram, CSS);
});
| aghassemi/amphtml | extensions/amp-instagram/0.1/amp-instagram.js | JavaScript | apache-2.0 | 7,111 |
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.ObservableValue;
import arez.SafeProcedure;
import arez.component.DisposeNotifier;
import arez.component.Identifiable;
import arez.component.internal.ComponentKernel;
import java.text.ParseException;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.braincheck.Guards;
@Generated("arez.processor.ArezProcessor")
final class Arez_ObservableWithSpecificExceptionModel extends ObservableWithSpecificExceptionModel implements Disposable, Identifiable<Integer>, DisposeNotifier {
private static volatile int $$arezi$$_nextId;
private final ComponentKernel $$arezi$$_kernel;
@Nonnull
private final ObservableValue<Long> $$arez$$_time;
Arez_ObservableWithSpecificExceptionModel() {
super();
final ArezContext $$arezv$$_context = Arez.context();
final int $$arezv$$_id = ++$$arezi$$_nextId;
final String $$arezv$$_name = Arez.areNamesEnabled() ? "ObservableWithSpecificExceptionModel." + $$arezv$$_id : null;
final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "ObservableWithSpecificExceptionModel", $$arezv$$_id, $$arezv$$_name, this::$$arezi$$_nativeComponentPreDispose ) : null;
this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, null, Arez.areNativeComponentsEnabled() ? null : this::$$arezi$$_dispose, null, true, false, false );
this.$$arez$$_time = $$arezv$$_context.observable( Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, Arez.areNamesEnabled() ? $$arezv$$_name + ".time" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> super.getTime() : null, Arez.arePropertyIntrospectorsEnabled() ? v -> super.setTime( v ) : null );
this.$$arezi$$_kernel.componentConstructed();
this.$$arezi$$_kernel.componentReady();
}
private int $$arezi$$_id() {
return this.$$arezi$$_kernel.getId();
}
@Override
@Nonnull
public Integer getArezId() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
return $$arezi$$_id();
}
private void $$arezi$$_nativeComponentPreDispose() {
this.$$arezi$$_kernel.notifyOnDisposeListeners();
}
@Override
public void addOnDisposeListener(@Nonnull final Object key, @Nonnull final SafeProcedure action) {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'addOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" );
}
this.$$arezi$$_kernel.addOnDisposeListener( key, action );
}
@Override
public void removeOnDisposeListener(@Nonnull final Object key) {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'removeOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'removeOnDisposeListener' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
this.$$arezi$$_kernel.removeOnDisposeListener( key );
}
@Override
public boolean isDisposed() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
return this.$$arezi$$_kernel.isDisposed();
}
@Override
public void dispose() {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" );
}
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" );
}
this.$$arezi$$_kernel.dispose();
}
private void $$arezi$$_dispose() {
this.$$arez$$_time.dispose();
}
@Override
public long getTime() throws ParseException {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'getTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" );
}
this.$$arez$$_time.reportObserved();
return super.getTime();
}
@Override
public void setTime(final long time) throws ParseException {
if ( Arez.shouldCheckApiInvariants() ) {
Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'setTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" );
}
this.$$arez$$_time.preReportChanged();
final long $$arezv$$_currentValue = super.getTime();
if ( time != $$arezv$$_currentValue ) {
super.setTime( time );
this.$$arez$$_time.reportChanged();
}
}
@Override
public String toString() {
if ( Arez.areNamesEnabled() ) {
return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]";
} else {
return super.toString();
}
}
}
| realityforge/arez | processor/src/test/fixtures/expected/Arez_ObservableWithSpecificExceptionModel.java | Java | apache-2.0 | 6,870 |
namespace RoslynPad.Roslyn.Snippets
{
public sealed class SnippetInfo
{
public string Shortcut { get; }
public string Title { get; }
public string Description { get; }
public SnippetInfo(string shortcut, string title, string description)
{
Shortcut = shortcut;
Title = title;
Description = description;
}
}
} | aelij/roslynpad | src/RoslynPad.Roslyn/Snippets/SnippetInfo.cs | C# | apache-2.0 | 407 |
/**
* Licensing arrangement (from website FAQ):
*
* The software is completely free for any purpose, unless notes at the
* head of the program text indicates otherwise (which is rare). In any
* case, the notes about licensing are never more restrictive than the
* BSD License.
*
*/
package com.novartis.pcs.ontology.service.mapper;
/*
Porter stemmer in Java. The original paper is in
Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
no. 3, pp 130-137,
See also http://www.tartarus.org/~martin/PorterStemmer/index.html
Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below.
Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1]
is then out outside the bounds of b.
Similarly,
Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below.
'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and
b[j] is then outside the bounds of b.
Release 3.
[ This version is derived from Release 3, modified by Brian Goetz to
optimize for fewer object creations. ]
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* Stemmer, implementing the Porter Stemming Algorithm
*
* The Stemmer class transforms a word into its root form. The input
* word can be provided a character at time (by calling add()), or at once
* by calling one of the various stem(something) methods.
*/
class PorterStemmer
{
private char[] b;
private int i, /* offset into b */
j, k, k0;
private boolean dirty = false;
private static final int INC = 50; /* unit of size whereby b is increased */
private static final int EXTRA = 1;
public PorterStemmer() {
b = new char[INC];
i = 0;
}
/**
* reset() resets the stemmer so it can stem another word. If you invoke
* the stemmer by calling add(char) and then stem(), you must call reset()
* before starting another word.
*/
public void reset() { i = 0; dirty = false; }
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to process the word.
*/
public void add(char ch) {
if (b.length <= i + EXTRA) {
char[] new_b = new char[b.length+INC];
System.arraycopy(b, 0, new_b, 0, b.length);
b = new_b;
}
b[i++] = ch;
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
@Override
public String toString() { return new String(b,0,i); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i) {
switch (b[i]) {
case 'a': case 'e': case 'i': case 'o': case 'u':
return false;
case 'y':
return (i==k0) ? true : !cons(i-1);
default:
return true;
}
}
/* m() measures the number of consonant sequences between k0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m() {
int n = 0;
int i = k0;
while(true) {
if (i > j)
return n;
if (! cons(i))
break;
i++;
}
i++;
while(true) {
while(true) {
if (i > j)
return n;
if (cons(i))
break;
i++;
}
i++;
n++;
while(true) {
if (i > j)
return n;
if (! cons(i))
break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> k0,...j contains a vowel */
private final boolean vowelinstem() {
int i;
for (i = k0; i <= j; i++)
if (! cons(i))
return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j) {
if (j < k0+1)
return false;
if (b[j] != b[j-1])
return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i) {
if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2))
return false;
else {
int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s) {
int l = s.length();
int o = k-l+1;
if (o < k0)
return false;
for (int i = 0; i < l; i++)
if (b[o+i] != s.charAt(i))
return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
void setto(String s) {
int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++)
b[o+i] = s.charAt(i);
k = j+l;
dirty = true;
}
/* r(s) is used further down. */
void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1() {
if (b[k] == 's') {
if (ends("sses")) k -= 2;
else if (ends("ies")) setto("i");
else if (b[k-1] != 's') k--;
}
if (ends("eed")) {
if (m() > 0)
k--;
}
else if ((ends("ed") || ends("ing")) && vowelinstem()) {
k = j;
if (ends("at")) setto("ate");
else if (ends("bl")) setto("ble");
else if (ends("iz")) setto("ize");
else if (doublec(k)) {
int ch = b[k--];
if (ch == 'l' || ch == 's' || ch == 'z')
k++;
}
else if (m() == 1 && cvc(k))
setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() {
if (ends("y") && vowelinstem()) {
b[k] = 'i';
dirty = true;
}
}
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() {
if (k == k0) return; /* For Bug 1 */
switch (b[k-1]) {
case 'a':
if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c':
if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e':
if (ends("izer")) { r("ize"); break; }
break;
case 'l':
if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o':
if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's':
if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't':
if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g':
if (ends("logi")) { r("log"); break; }
}
}
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() {
switch (b[k]) {
case 'e':
if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i':
if (ends("iciti")) { r("ic"); break; }
break;
case 'l':
if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's':
if (ends("ness")) { r(""); break; }
break;
}
}
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5() {
if (k == k0) return; /* for Bug 1 */
switch (b[k-1]) {
case 'a':
if (ends("al")) break;
return;
case 'c':
if (ends("ance")) break;
if (ends("ence")) break;
return;
case 'e':
if (ends("er")) break; return;
case 'i':
if (ends("ic")) break; return;
case 'l':
if (ends("able")) break;
if (ends("ible")) break; return;
case 'n':
if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break;
return;
case 'o':
if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break;
return;
/* takes care of -ous */
case 's':
if (ends("ism")) break;
return;
case 't':
if (ends("ate")) break;
if (ends("iti")) break;
return;
case 'u':
if (ends("ous")) break;
return;
case 'v':
if (ends("ive")) break;
return;
case 'z':
if (ends("ize")) break;
return;
default:
return;
}
if (m() > 1)
k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6() {
j = k;
if (b[k] == 'e') {
int a = m();
if (a > 1 || a == 1 && !cvc(k-1))
k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1)
k--;
}
/**
* Stem a word provided as a String. Returns the result as a String.
*/
public String stem(String s) {
if (stem(s.toCharArray(), s.length()))
return toString();
else
return s;
}
/** Stem a word contained in a char[]. Returns true if the stemming process
* resulted in a word different from the input. You can retrieve the
* result with getResultLength()/getResultBuffer() or toString().
*/
public boolean stem(char[] word) {
return stem(word, word.length);
}
/** Stem a word contained in a portion of a char[] array. Returns
* true if the stemming process resulted in a word different from
* the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public boolean stem(char[] wordBuffer, int offset, int wordLen) {
reset();
if (b.length < wordLen) {
char[] new_b = new char[wordLen + EXTRA];
b = new_b;
}
System.arraycopy(wordBuffer, offset, b, 0, wordLen);
i = wordLen;
return stem(0);
}
/** Stem a word contained in a leading portion of a char[] array.
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public boolean stem(char[] word, int wordLen) {
return stem(word, 0, wordLen);
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public boolean stem() {
return stem(0);
}
public boolean stem(int i0) {
k = i - 1;
k0 = i0;
if (k > k0+1) {
step1(); step2(); step3(); step4(); step5(); step6();
}
// Also, a word is considered dirty if we lopped off letters
// Thanks to Ifigenia Vairelles for pointing this out.
if (i != k+1)
dirty = true;
i = k+1;
return dirty;
}
/** Test program for demonstrating the Stemmer. It reads a file and
* stems each word, writing the result to standard out.
* Usage: Stemmer file-name
*/
public static void main(String[] args) {
PorterStemmer s = new PorterStemmer();
for (int i = 0; i < args.length; i++) {
try {
InputStream in = new FileInputStream(args[i]);
byte[] buffer = new byte[1024];
int bufferLen, offset, ch;
bufferLen = in.read(buffer);
offset = 0;
s.reset();
while(true) {
if (offset < bufferLen)
ch = buffer[offset++];
else {
bufferLen = in.read(buffer);
offset = 0;
if (bufferLen < 0)
ch = -1;
else
ch = buffer[offset++];
}
if (Character.isLetter((char) ch)) {
s.add(Character.toLowerCase((char) ch));
}
else {
s.stem();
System.out.print(s.toString());
s.reset();
if (ch < 0)
break;
else {
System.out.print((char) ch);
}
}
}
in.close();
}
catch (IOException e) {
System.out.println("error reading " + args[i]);
}
}
}
}
| Novartis/ontobrowser | src/main/java/com/novartis/pcs/ontology/service/mapper/PorterStemmer.java | Java | apache-2.0 | 13,830 |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for GetTagKey
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-resourcemanager
# [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
from google.cloud import resourcemanager_v3
async def sample_get_tag_key():
# Create a client
client = resourcemanager_v3.TagKeysAsyncClient()
# Initialize request argument(s)
request = resourcemanager_v3.GetTagKeyRequest(
name="name_value",
)
# Make the request
response = await client.get_tag_key(request=request)
# Handle the response
print(response)
# [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
| googleapis/python-resource-manager | samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py | Python | apache-2.0 | 1,477 |
<?php
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
namespace Magento\Sales\Model\Grid;
class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface
{
/**
* @var \Magento\Framework\Registry
*/
protected $registryManager;
/**
* @param \Magento\Framework\Registry $registryManager
*/
public function __construct(\Magento\Framework\Registry $registryManager)
{
$this->registryManager = $registryManager;
}
/**
* Update grid collection according to chosen order
*
* @param \Magento\Sales\Model\Resource\Transaction\Grid\Collection $argument
* @return \Magento\Sales\Model\Resource\Transaction\Grid\Collection
*/
public function update($argument)
{
$order = $this->registryManager->registry('current_order');
if ($order) {
$argument->setOrderFilter($order->getId());
}
$argument->addOrderInformation(['increment_id']);
return $argument;
}
}
| webadvancedservicescom/magento | app/code/Magento/Sales/Model/Grid/CollectionUpdater.php | PHP | apache-2.0 | 1,062 |
<!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 (1.8.0_112) on Mon Nov 06 11:57:26 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup (BOM: * : All 2017.11.0 API)</title>
<meta name="date" content="2017-11-06">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup (BOM: * : All 2017.11.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2017.11.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BroadcastGroup.html" target="_top">Frames</a></li>
<li><a href="BroadcastGroup.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">
<h2 title="Uses of Class org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup" class="title">Uses of Class<br>org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq">org.wildfly.swarm.config.messaging.activemq</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.messaging.activemq.server">org.wildfly.swarm.config.messaging.activemq.server</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#broadcastGroup-java.lang.String-">broadcastGroup</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> that return types with arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Server.ServerResources.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.ServerResources.html#broadcastGroups--">broadcastGroups</a></span>()</code>
<div class="block">Get the list of BroadcastGroup resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#broadcastGroup-org.wildfly.swarm.config.messaging.activemq.server.BroadcastGroup-">broadcastGroup</a></span>(<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a> value)</code>
<div class="block">Add the BroadcastGroup object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/package-summary.html">org.wildfly.swarm.config.messaging.activemq</a> with type arguments of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html" title="type parameter in Server">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/Server.html#broadcastGroups-java.util.List-">broadcastGroups</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>> value)</code>
<div class="block">Add all BroadcastGroup objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.messaging.activemq.server">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a> in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> with type parameters of type <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a><T>></span></code>
<div class="block">A broadcast group is the means by which a server broadcasts connectors over
the network.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroupConsumer</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupSupplier.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroupSupplier</a><T extends <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/package-summary.html">org.wildfly.swarm.config.messaging.activemq.server</a> that return <a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">BroadcastGroup</a></code></td>
<td class="colLast"><span class="typeNameLabel">BroadcastGroupSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroupSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of BroadcastGroup resource</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/BroadcastGroup.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2017.11.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/class-use/BroadcastGroup.html" target="_top">Frames</a></li>
<li><a href="BroadcastGroup.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>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2017.11.0/apidocs/org/wildfly/swarm/config/messaging/activemq/server/class-use/BroadcastGroup.html | HTML | apache-2.0 | 17,090 |
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resolve
import (
"context"
"fmt"
"github.com/google/gapid/core/data/id"
"github.com/google/gapid/core/log"
"github.com/google/gapid/gapis/api"
"github.com/google/gapid/gapis/api/sync"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/database"
"github.com/google/gapid/gapis/resolve/initialcmds"
"github.com/google/gapid/gapis/service/path"
)
// ResolvedResources contains all of the resolved resources for a
// particular point in the trace.
type ResolvedResources struct {
resourceMap api.ResourceMap
resources map[id.ID]api.Resource
resourceData map[id.ID]interface{}
}
// Resolve builds a ResolvedResources object for all of the resources
// at the path r.After
func (r *AllResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) {
ctx = SetupContext(ctx, r.After.Capture, r.Config)
resources, err := buildResources(ctx, r.After)
if err != nil {
return nil, err
}
return resources, nil
}
func buildResources(ctx context.Context, p *path.Command) (*ResolvedResources, error) {
cmdIdx := p.Indices[0]
capture, err := capture.Resolve(ctx)
if err != nil {
return nil, err
}
allCmds, err := Cmds(ctx, p.Capture)
if err != nil {
return nil, err
}
s, err := SyncData(ctx, p.Capture)
if err != nil {
return nil, err
}
cmds, err := sync.MutationCmdsFor(ctx, p.Capture, s, allCmds, api.CmdID(cmdIdx), p.Indices[1:], false)
if err != nil {
return nil, err
}
initialCmds, ranges, err := initialcmds.InitialCommands(ctx, p.Capture)
if err != nil {
return nil, err
}
state := capture.NewUninitializedState(ctx).ReserveMemory(ranges)
var currentCmdIndex uint64
var currentCmdResourceCount int
idMap := api.ResourceMap{}
resources := make(map[id.ID]api.Resource)
state.OnResourceCreated = func(r api.Resource) {
currentCmdResourceCount++
i := genResourceID(currentCmdIndex, currentCmdResourceCount)
idMap[r] = i
resources[i] = r
}
api.ForeachCmd(ctx, initialCmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error {
if err := cmd.Mutate(ctx, id, state, nil, nil); err != nil {
log.W(ctx, "Get resources at %v: Initial cmd [%v]%v - %v", p.Indices, id, cmd, err)
}
return nil
})
err = api.ForeachCmd(ctx, cmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error {
currentCmdResourceCount = 0
currentCmdIndex = uint64(id)
cmd.Mutate(ctx, id, state, nil, nil)
return nil
})
if err != nil {
return nil, err
}
resourceData := make(map[id.ID]interface{})
for k, v := range resources {
res, err := v.ResourceData(ctx, state)
if err != nil {
resourceData[k] = err
} else {
resourceData[k] = res
}
}
return &ResolvedResources{idMap, resources, resourceData}, nil
}
// ResourceData resolves the data of the specified resource at the specified
// point in the capture.
func ResourceData(ctx context.Context, p *path.ResourceData, r *path.ResolveConfig) (interface{}, error) {
obj, err := database.Build(ctx, &ResourceDataResolvable{Path: p, Config: r})
if err != nil {
return nil, err
}
return obj, nil
}
// Resolve implements the database.Resolver interface.
func (r *ResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) {
resources, err := database.Build(ctx, &AllResourceDataResolvable{After: r.Path.After, Config: r.Config})
if err != nil {
return nil, err
}
res, ok := resources.(*ResolvedResources)
if !ok {
return nil, fmt.Errorf("Cannot resolve resources at command: %v", r.Path.After)
}
id := r.Path.ID.ID()
if val, ok := res.resourceData[id]; ok {
if err, isErr := val.(error); isErr {
return nil, err
}
return val, nil
}
return nil, fmt.Errorf("Cannot find resource with id: %v", id)
}
| Qining/gapid | gapis/resolve/resource_data.go | GO | apache-2.0 | 4,307 |
<style type="text/css">
.placeholder {
display: none;
}
</style>
<div class="contentRight">
<div class="sanpham" style=" height: 100%; margin-top: 0">
<div class="row" style="margin: 5px">
<div class="page-header">
<h2><?php echo lang('form_checkout'); ?></h2>
</div>
<?php if (validation_errors()): ?>
<div class="alert alert-error">
<a class="close" data-dismiss="alert">×</a>
<?php echo validation_errors(); ?>
</div>
<?php endif; ?>
<script type="text/javascript">
$(document).ready(function () {
//if we support placeholder text, remove all the labels
if (!supports_placeholder()) {
$('.placeholder').show();
}
<?php
// Restore previous selection, if we are on a validation page reload
$zone_id = set_value('zone_id');
echo "\$('#zone_id').val($zone_id);\n";
?>
});
function supports_placeholder() {
return 'placeholder' in document.createElement('input');
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#country_id').change(function () {
populate_zone_menu();
});
});
// context is ship or bill
function populate_zone_menu(value) {
$.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) {
$('#zone_id').html(data);
});
}
</script>
<?php /* Only show this javascript if the user is logged in */ ?>
<?php if ($this->Customer_model->is_logged_in(false, false)) : ?>
<script type="text/javascript">
<?php
$add_list = array();
foreach($customer_addresses as $row) {
// build a new array
$add_list[$row['id']] = $row['field_data'];
}
$add_list = json_encode($add_list);
echo "eval(addresses=$add_list);";
?>
function populate_address(address_id) {
if (address_id == '') {
return;
}
// - populate the fields
$.each(addresses[address_id], function (key, value) {
$('.address[name=' + key + ']').val(value);
// repopulate the zone menu and set the right value if we change the country
if (key == 'zone_id') {
zone_id = value;
}
});
// repopulate the zone list, set the right value, then copy all to billing
$.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) {
$('#zone_id').html(data);
$('#zone_id').val(zone_id);
});
}
</script>
<?php endif; ?>
<?php
$countries = $this->Location_model->get_countries_menu();
if (!empty($customer[$address_form_prefix . '_address']['country_id'])) {
$zone_menu = $this->Location_model->get_zones_menu($customer[$address_form_prefix . '_address']['country_id']);
} else {
$zone_menu = array('' => '') + $this->Location_model->get_zones_menu(array_shift(array_keys($countries)));
}
//form elements
$company = array('placeholder' => lang('address_company'), 'class' => 'address span8', 'name' => 'company', 'value' => set_value('company', @$customer[$address_form_prefix . '_address']['company']));
$address1 = array('placeholder' => lang('address1'), 'class' => 'address span8', 'name' => 'address1', 'value' => set_value('address1', @$customer[$address_form_prefix . '_address']['address1']));
$address2 = array('placeholder' => lang('address2'), 'class' => 'address span8', 'name' => 'address2', 'value' => set_value('address2', @$customer[$address_form_prefix . '_address']['address2']));
$first = array('placeholder' => lang('address_firstname'), 'class' => 'address span4', 'name' => 'firstname', 'value' => set_value('firstname', @$customer[$address_form_prefix . '_address']['firstname']));
$last = array('placeholder' => lang('address_lastname'), 'class' => 'address span4', 'name' => 'lastname', 'value' => set_value('lastname', @$customer[$address_form_prefix . '_address']['lastname']));
$email = array('placeholder' => lang('address_email'), 'class' => 'address span4', 'name' => 'email', 'value' => set_value('email', @$customer[$address_form_prefix . '_address']['email']));
$phone = array('placeholder' => lang('address_phone'), 'class' => 'address span4', 'name' => 'phone', 'value' => set_value('phone', @$customer[$address_form_prefix . '_address']['phone']));
$city = array('placeholder' => lang('address_city'), 'class' => 'address span3', 'name' => 'city', 'value' => set_value('city', @$customer[$address_form_prefix . '_address']['city']));
$zip = array('placeholder' => lang('address_zip'), 'maxlength' => '10', 'class' => 'address span2', 'name' => 'zip', 'value' => set_value('zip', @$customer[$address_form_prefix . '_address']['zip']));
?>
<?php
//post to the correct place.
echo ($address_form_prefix == 'bill') ? form_open('checkout/step_1', 'style = "padding-left: 60px;"') : form_open('checkout/shipping_address', 'style = "padding-left: 60px;"');?>
<div class="row">
<?php // Address form ?>
<div class="span8">
<div class="row">
<div class="span4">
<h2 style="margin:0px;">
<?php echo ($address_form_prefix == 'bill') ? lang('address') : lang('shipping_address'); ?>
</h2>
</div>
<div class="span4">
<?php if ($this->Customer_model->is_logged_in(false, false)) : ?>
<button class="btn btn-inverse pull-right" onclick="$('#address_manager').modal().modal('show');"
type="button"><i class="icon-envelope icon-white"></i> <?php echo lang('choose_address'); ?>
</button>
<?php endif; ?>
</div>
</div>
<div class="row">
<div class="span8">
<label class="placeholder"><?php echo lang('address_company'); ?></label>
<?php echo form_input($company); ?>
</div>
</div>
<div class="row">
<div class="span4">
<label class="placeholder"><?php echo lang('address_firstname'); ?><b class="r"> *</b></label>
<?php echo form_input($first); ?>
</div>
<div class="span4">
<label class="placeholder"><?php echo lang('address_lastname'); ?><b class="r"> *</b></label>
<?php echo form_input($last); ?>
</div>
</div>
<div class="row">
<div class="span4">
<label class="placeholder"><?php echo lang('address_email'); ?><b class="r"> *</b></label>
<?php echo form_input($email); ?>
</div>
<div class="span4">
<label class="placeholder"><?php echo lang('address_phone'); ?><b class="r"> *</b></label>
<?php echo form_input($phone); ?>
</div>
</div>
<div class="row">
<div class="span8">
<label class="placeholder"><?php echo lang('address_country'); ?><b class="r"> *</b></label>
<?php echo form_dropdown('country_id', $countries, @$customer[$address_form_prefix . '_address']['country_id'], 'id="country_id" class="address span8"'); ?>
</div>
</div>
<div class="row">
<div class="span8">
<label class="placeholder"><?php echo lang('address1'); ?><b class="r"> *</b></label>
<?php echo form_input($address1); ?>
</div>
</div>
<div class="row">
<div class="span8">
<label class="placeholder"><?php echo lang('address2'); ?></label>
<?php echo form_input($address2); ?>
</div>
</div>
<div class="row">
<div class="span3">
<label class="placeholder"><?php echo lang('address_city'); ?><b class="r"> *</b></label>
<?php echo form_input($city); ?>
</div>
<div class="span3">
<label class="placeholder"><?php echo lang('address_state'); ?><b class="r"> *</b></label>
<?php
echo form_dropdown('zone_id', $zone_menu, @$customer[$address_form_prefix . '_address']['zone_id'], 'id="zone_id" class="address span3" ');?>
</div>
<div class="span2">
<label class="placeholder"><?php echo lang('address_zip'); ?><b class="r"> *</b></label>
<?php echo form_input($zip); ?>
</div>
</div>
<?php if ($address_form_prefix == 'bill') : ?>
<div class="row">
<div class="span3">
<label class="checkbox inline" for="use_shipping">
<?php echo form_checkbox(array('name' => 'use_shipping', 'value' => 'yes', 'id' => 'use_shipping', 'checked' => $use_shipping)) ?>
<?php echo lang('ship_to_address') ?>
</label>
</div>
</div>
<?php endif ?>
<div class="row">
<div class="span8">
<?php if ($address_form_prefix == 'ship') : ?>
<input class="btn btn-block btn-large btn-secondary" type="button"
value="<?php echo lang('form_previous'); ?>"
onclick="window.location='<?php echo base_url('checkout/step_1') ?>'"/>
<?php endif; ?>
<input class="btn btn-block btn-large btn-primary" type="submit"
value="<?php echo lang('form_continue'); ?>"/>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<?php if ($this->Customer_model->is_logged_in(false, false)) : ?>
<div class="modal hide" id="address_manager">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3><?php echo lang('your_addresses'); ?></h3>
</div>
<div class="modal-body">
<p>
<table class="table table-striped">
<?php
$c = 1;
foreach ($customer_addresses as $a):?>
<tr>
<td>
<?php
$b = $a['field_data'];
echo nl2br(format_address($b));
?>
</td>
<td style="width:100px;"><input type="button" class="btn btn-primary choose_address pull-right"
onclick="populate_address(<?php echo $a['id']; ?>);"
data-dismiss="modal"
value="<?php echo lang('form_choose'); ?>"/></td>
</tr>
<?php endforeach; ?>
</table>
</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal">Close</a>
</div>
</div>
<?php endif; ?> | CaoLP/tranhviet | Code/tranhviet/gocart/themes/default/views/checkout/address_form.php | PHP | apache-2.0 | 11,288 |
/*
* Copyright 2014-2021 Sayi
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.deepoove.poi.xwpf;
import java.util.List;
import org.apache.poi.xwpf.usermodel.IRunBody;
import org.apache.poi.xwpf.usermodel.XWPFFieldRun;
import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlObject;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
public class ParagraphContext implements RunBodyContext {
private XWPFParagraphWrapper paragraphWrapper;
public ParagraphContext(XWPFParagraphWrapper paragraphWrapper) {
this.paragraphWrapper = paragraphWrapper;
}
@Override
public IRunBody getTarget() {
return paragraphWrapper.getParagraph();
}
@Override
public List<XWPFRun> getRuns() {
return paragraphWrapper.getParagraph().getRuns();
}
@Override
public void setAndUpdateRun(XWPFRun xwpfRun, XWPFRun sourceRun, int insertPostionCursor) {
paragraphWrapper.setAndUpdateRun(xwpfRun, sourceRun, insertPostionCursor);
}
@Override
public XWPFRun insertNewRun(XWPFRun xwpfRun, int insertPostionCursor) {
if (xwpfRun instanceof XWPFHyperlinkRun) {
return paragraphWrapper.insertNewHyperLinkRun(insertPostionCursor, "");
} else if (xwpfRun instanceof XWPFFieldRun) {
return paragraphWrapper.insertNewField(insertPostionCursor);
} else {
return paragraphWrapper.insertNewRun(insertPostionCursor);
}
}
@Override
public XWPFRun createRun(XWPFRun xwpfRun, IRunBody p) {
if (xwpfRun instanceof XWPFHyperlinkRun) {
return new XWPFHyperlinkRun((CTHyperlink) ((XWPFHyperlinkRun) xwpfRun).getCTHyperlink().copy(),
(CTR) ((XWPFHyperlinkRun) xwpfRun).getCTR().copy(), p);
} else if (xwpfRun instanceof XWPFFieldRun) {
return new XWPFFieldRun((CTSimpleField) ((XWPFFieldRun) xwpfRun).getCTField().copy(),
(CTR) ((XWPFFieldRun) xwpfRun).getCTR().copy(), p);
} else {
return new XWPFRun((CTR) xwpfRun.getCTR().copy(), p);
}
}
@Override
public XWPFRun createRun(XmlObject object, IRunBody p) {
if (object instanceof CTHyperlink) {
return new XWPFHyperlinkRun((CTHyperlink) object, ((CTHyperlink) object).getRArray(0), p);
} else if (object instanceof CTSimpleField) {
return new XWPFFieldRun((CTSimpleField) object, ((CTSimpleField) object).getRArray(0), p);
} else {
return new XWPFRun((CTR) object, p);
}
}
@Override
public void removeRun(int pos) {
paragraphWrapper.removeRun(pos);
}
}
| Sayi/poi-tl | poi-tl/src/main/java/com/deepoove/poi/xwpf/ParagraphContext.java | Java | apache-2.0 | 3,416 |
<!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 (1.8.0_151) on Mon Jan 15 08:36:52 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources (BOM: * : All 2018.1.0 API)</title>
<meta name="date" content="2018-01-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources (BOM: * : All 2018.1.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2018.1.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/undertow/class-use/Server.ServerResources.html" target="_top">Frames</a></li>
<li><a href="Server.ServerResources.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">
<h2 title="Uses of Class org.wildfly.swarm.config.undertow.Server.ServerResources" class="title">Uses of Class<br>org.wildfly.swarm.config.undertow.Server.ServerResources</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.undertow">org.wildfly.swarm.config.undertow</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.undertow">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a> in <a href="../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/undertow/package-summary.html">org.wildfly.swarm.config.undertow</a> that return <a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Server.ServerResources</a></code></td>
<td class="colLast"><span class="typeNameLabel">Server.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.html#subresources--">subresources</a></span>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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><a href="../../../../../../org/wildfly/swarm/config/undertow/Server.ServerResources.html" title="class in org.wildfly.swarm.config.undertow">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-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 class="aboutLanguage">WildFly Swarm API, 2018.1.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/undertow/class-use/Server.ServerResources.html" target="_top">Frames</a></li>
<li><a href="Server.ServerResources.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>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2018.1.0/apidocs/org/wildfly/swarm/config/undertow/class-use/Server.ServerResources.html | HTML | apache-2.0 | 7,292 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.portable;
import org.apache.ignite.internal.portable.streams.*;
import org.apache.ignite.internal.util.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import sun.misc.*;
import static org.apache.ignite.IgniteSystemProperties.*;
/**
* Thread-local memory allocator.
*/
public class PortableThreadLocalMemoryAllocator implements PortableMemoryAllocator {
/** Memory allocator instance. */
public static final PortableThreadLocalMemoryAllocator THREAD_LOCAL_ALLOC =
new PortableThreadLocalMemoryAllocator();
/** Holders. */
private static final ThreadLocal<ByteArrayHolder> holders = new ThreadLocal<>();
/** Unsafe instance. */
protected static final Unsafe UNSAFE = GridUnsafe.unsafe();
/** Array offset: byte. */
protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
/**
* Ensures singleton.
*/
private PortableThreadLocalMemoryAllocator() {
// No-op.
}
/** {@inheritDoc} */
@Override public byte[] allocate(int size) {
ByteArrayHolder holder = holders.get();
if (holder == null)
holders.set(holder = new ByteArrayHolder());
if (holder.acquired)
return new byte[size];
holder.acquired = true;
if (holder.data == null || size > holder.data.length)
holder.data = new byte[size];
return holder.data;
}
/** {@inheritDoc} */
@Override public byte[] reallocate(byte[] data, int size) {
ByteArrayHolder holder = holders.get();
assert holder != null;
byte[] newData = new byte[size];
if (holder.data == data)
holder.data = newData;
UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length);
return newData;
}
/** {@inheritDoc} */
@Override public void release(byte[] data, int maxMsgSize) {
ByteArrayHolder holder = holders.get();
assert holder != null;
if (holder.data != data)
return;
holder.maxMsgSize = maxMsgSize;
holder.acquired = false;
holder.shrink();
}
/** {@inheritDoc} */
@Override public long allocateDirect(int size) {
return 0;
}
/** {@inheritDoc} */
@Override public long reallocateDirect(long addr, int size) {
return 0;
}
/** {@inheritDoc} */
@Override public void releaseDirect(long addr) {
// No-op
}
/**
* Checks whether a thread-local array is acquired or not.
* The function is used by Unit tests.
*
* @return {@code true} if acquired {@code false} otherwise.
*/
public boolean isThreadLocalArrayAcquired() {
ByteArrayHolder holder = holders.get();
return holder != null && holder.acquired;
}
/**
* Thread-local byte array holder.
*/
private static class ByteArrayHolder {
/** */
private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000);
/** Data array */
private byte[] data;
/** Max message size detected between checks. */
private int maxMsgSize;
/** Last time array size is checked. */
private long lastCheck = U.currentTimeMillis();
/** Whether the holder is acquired or not. */
private boolean acquired;
/**
* Shrinks array size if needed.
*/
private void shrink() {
long now = U.currentTimeMillis();
if (now - lastCheck >= CHECK_FREQ) {
int halfSize = data.length >> 1;
if (maxMsgSize < halfSize)
data = new byte[halfSize];
lastCheck = now;
}
}
}
} | avinogradovgg/ignite | modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java | Java | apache-2.0 | 4,612 |
package BinaryTreeLevelOrderTraversal;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class BinaryTreeLevelOrderTraversalSolutionTest {
private BinaryTreeLevelOrderTraversalSolution solution = new BinaryTreeLevelOrderTraversalSolution();
@Test
public void nullInput() {
List<List<Integer>> result = solution.levelOrder(null);
assertThat(result).isEmpty();
}
@Test
public void singleNodeInput() {
TreeNode root = new TreeNode(1);
List<List<Integer>> result = solution.levelOrder(root);
assertThat(result).hasSize(1);
assertThat(result.get(0)).containsExactly(1);
}
@Test
public void twoNodesInput() {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
List<List<Integer>> result = solution.levelOrder(root);
assertThat(result).hasSize(2);
assertThat(result.get(0)).containsExactly(1);
assertThat(result.get(1)).containsExactly(2);
}
@Test
public void threeNodesInput() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
List<List<Integer>> result = solution.levelOrder(root);
assertThat(result).hasSize(2);
assertThat(result.get(0)).containsExactly(1);
assertThat(result.get(1)).containsExactly(2, 3);
}
@Test
public void fiveNodesInput() {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
TreeNode rightTree = new TreeNode(20);
rightTree.left = new TreeNode(15);
rightTree.right = new TreeNode(7);
root.right = rightTree;
List<List<Integer>> result = solution.levelOrder(root);
assertThat(result).hasSize(3);
assertThat(result.get(0)).containsExactly(3);
assertThat(result.get(1)).containsExactly(9, 20);
assertThat(result.get(2)).containsExactly(15, 7);
}
} | mengdd/LeetCode | algorithms/src/test/java/BinaryTreeLevelOrderTraversal/BinaryTreeLevelOrderTraversalSolutionTest.java | Java | apache-2.0 | 2,013 |
package cn.aezo.spring.base.annotation.combineannotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by smalle on 2017/6/11.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface WiselyConfiguration {
String[] value() default {};
}
| oldinaction/smjava | javaee/spring/src/main/java/cn/aezo/spring/base/annotation/combineannotation/WiselyConfiguration.java | Java | apache-2.0 | 607 |
.ff0{font-family:sans-serif;visibility:hidden;}
@font-face{font-family:ff1;src:url(f1.woff)format("woff");}.ff1{font-family:ff1;line-height:1.534180;font-style:normal;font-weight:normal;visibility:visible;}
@font-face{font-family:ff2;src:url(f2.woff)format("woff");}.ff2{font-family:ff2;line-height:1.456055;font-style:normal;font-weight:normal;visibility:visible;}
@font-face{font-family:ff3;src:url(f3.woff)format("woff");}.ff3{font-family:ff3;line-height:1.695312;font-style:normal;font-weight:normal;visibility:visible;}
@font-face{font-family:ff4;src:url(f4.woff)format("woff");}.ff4{font-family:ff4;line-height:0.910645;font-style:normal;font-weight:normal;visibility:visible;}
.m0{transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);-ms-transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);-webkit-transform:matrix(0.250000,0.000000,0.000000,0.250000,0,0);}
.m1{transform:none;-ms-transform:none;-webkit-transform:none;}
.v0{vertical-align:0.000000px;}
.ls2{letter-spacing:-0.096000px;}
.ls0{letter-spacing:0.000000px;}
.ls1{letter-spacing:0.096000px;}
.sc_{text-shadow:none;}
.sc0{text-shadow:-0.015em 0 transparent,0 0.015em transparent,0.015em 0 transparent,0 -0.015em transparent;}
@media screen and (-webkit-min-device-pixel-ratio:0){
.sc_{-webkit-text-stroke:0px transparent;}
.sc0{-webkit-text-stroke:0.015em transparent;text-shadow:none;}
}
.ws0{word-spacing:0.000000px;}
._0{margin-left:-1.008000px;}
._1{width:1.016000px;}
.fc1{color:rgb(255,0,0);}
.fc0{color:rgb(0,0,0);}
.fs0{font-size:48.000000px;}
.fs1{font-size:56.000000px;}
.y26{bottom:16.000000px;}
.y52{bottom:79.584000px;}
.y25{bottom:88.464000px;}
.y4e{bottom:90.144000px;}
.y51{bottom:95.544000px;}
.y24{bottom:104.420000px;}
.y4d{bottom:105.980000px;}
.y4f{bottom:108.500000px;}
.y50{bottom:108.620000px;}
.y23{bottom:120.260000px;}
.y4c{bottom:121.820000px;}
.y22{bottom:136.100000px;}
.y4b{bottom:137.660000px;}
.y21{bottom:151.940000px;}
.y4a{bottom:153.620000px;}
.y20{bottom:167.900000px;}
.y49{bottom:169.460000px;}
.y1f{bottom:183.740000px;}
.y48{bottom:185.300000px;}
.y1e{bottom:199.580000px;}
.y47{bottom:201.140000px;}
.y1d{bottom:215.450000px;}
.y46{bottom:217.130000px;}
.y1c{bottom:231.410000px;}
.y45{bottom:232.970000px;}
.y1b{bottom:247.250000px;}
.y44{bottom:248.810000px;}
.y1a{bottom:263.090000px;}
.y43{bottom:264.650000px;}
.y19{bottom:278.930000px;}
.y42{bottom:280.610000px;}
.y18{bottom:294.770000px;}
.y41{bottom:296.450000px;}
.y17{bottom:310.730000px;}
.y40{bottom:312.290000px;}
.y16{bottom:326.570000px;}
.y3f{bottom:328.130000px;}
.y15{bottom:342.410000px;}
.y3e{bottom:344.090000px;}
.y14{bottom:358.250000px;}
.y3d{bottom:359.930000px;}
.y13{bottom:374.230000px;}
.y3c{bottom:375.790000px;}
.y12{bottom:390.070000px;}
.y3b{bottom:391.630000px;}
.y11{bottom:405.910000px;}
.y3a{bottom:407.470000px;}
.y10{bottom:421.750000px;}
.y39{bottom:423.430000px;}
.yf{bottom:437.710000px;}
.y38{bottom:439.270000px;}
.ye{bottom:453.550000px;}
.y37{bottom:455.110000px;}
.yd{bottom:469.150000px;}
.y36{bottom:470.950000px;}
.yc{bottom:484.990000px;}
.y35{bottom:486.910000px;}
.yb{bottom:500.950000px;}
.y34{bottom:502.750000px;}
.ya{bottom:516.790000px;}
.y33{bottom:518.590000px;}
.y9{bottom:532.630000px;}
.y32{bottom:534.430000px;}
.y8{bottom:548.500000px;}
.y31{bottom:550.420000px;}
.y7{bottom:564.460000px;}
.y30{bottom:566.260000px;}
.y6{bottom:580.300000px;}
.y2f{bottom:582.100000px;}
.y5{bottom:596.140000px;}
.y2e{bottom:597.940000px;}
.y4{bottom:611.980000px;}
.y2d{bottom:613.900000px;}
.y3{bottom:627.940000px;}
.y2c{bottom:629.740000px;}
.y2{bottom:643.780000px;}
.y2b{bottom:645.580000px;}
.y0{bottom:656.500000px;}
.y1{bottom:656.980000px;}
.y2a{bottom:661.420000px;}
.y29{bottom:677.380000px;}
.y28{bottom:693.220000px;}
.y27{bottom:709.080000px;}
.h3{height:53.250000px;}
.h2{height:54.960938px;}
.h1{height:63.500000px;}
.h4{height:69.015625px;}
.h5{height:183.500000px;}
.h0{height:792.000000px;}
.w1{width:208.000000px;}
.w2{width:468.000000px;}
.w0{width:612.000000px;}
.x0{left:72.000000px;}
.x4{left:186.980000px;}
.x6{left:253.000000px;}
.x5{left:277.010000px;}
.x1{left:279.890000px;}
.x2{left:286.010000px;}
.x3{left:306.050000px;}
.x7{left:539.980000px;}
@media print{
.v0{vertical-align:0.000000pt;}
.ls2{letter-spacing:-0.128000pt;}
.ls0{letter-spacing:0.000000pt;}
.ls1{letter-spacing:0.128000pt;}
.ws0{word-spacing:0.000000pt;}
._0{margin-left:-1.344000pt;}
._1{width:1.354667pt;}
.fs0{font-size:64.000000pt;}
.fs1{font-size:74.666667pt;}
.y26{bottom:21.333333pt;}
.y52{bottom:106.112000pt;}
.y25{bottom:117.952000pt;}
.y4e{bottom:120.192000pt;}
.y51{bottom:127.392000pt;}
.y24{bottom:139.226667pt;}
.y4d{bottom:141.306667pt;}
.y4f{bottom:144.666667pt;}
.y50{bottom:144.826667pt;}
.y23{bottom:160.346667pt;}
.y4c{bottom:162.426667pt;}
.y22{bottom:181.466667pt;}
.y4b{bottom:183.546667pt;}
.y21{bottom:202.586667pt;}
.y4a{bottom:204.826667pt;}
.y20{bottom:223.866667pt;}
.y49{bottom:225.946667pt;}
.y1f{bottom:244.986667pt;}
.y48{bottom:247.066667pt;}
.y1e{bottom:266.106667pt;}
.y47{bottom:268.186667pt;}
.y1d{bottom:287.266667pt;}
.y46{bottom:289.506667pt;}
.y1c{bottom:308.546667pt;}
.y45{bottom:310.626667pt;}
.y1b{bottom:329.666667pt;}
.y44{bottom:331.746667pt;}
.y1a{bottom:350.786667pt;}
.y43{bottom:352.866667pt;}
.y19{bottom:371.906667pt;}
.y42{bottom:374.146667pt;}
.y18{bottom:393.026667pt;}
.y41{bottom:395.266667pt;}
.y17{bottom:414.306667pt;}
.y40{bottom:416.386667pt;}
.y16{bottom:435.426667pt;}
.y3f{bottom:437.506667pt;}
.y15{bottom:456.546667pt;}
.y3e{bottom:458.786667pt;}
.y14{bottom:477.666667pt;}
.y3d{bottom:479.906667pt;}
.y13{bottom:498.973333pt;}
.y3c{bottom:501.053333pt;}
.y12{bottom:520.093333pt;}
.y3b{bottom:522.173333pt;}
.y11{bottom:541.213333pt;}
.y3a{bottom:543.293333pt;}
.y10{bottom:562.333333pt;}
.y39{bottom:564.573333pt;}
.yf{bottom:583.613333pt;}
.y38{bottom:585.693333pt;}
.ye{bottom:604.733333pt;}
.y37{bottom:606.813333pt;}
.yd{bottom:625.533333pt;}
.y36{bottom:627.933333pt;}
.yc{bottom:646.653333pt;}
.y35{bottom:649.213333pt;}
.yb{bottom:667.933333pt;}
.y34{bottom:670.333333pt;}
.ya{bottom:689.053333pt;}
.y33{bottom:691.453333pt;}
.y9{bottom:710.173333pt;}
.y32{bottom:712.573333pt;}
.y8{bottom:731.333333pt;}
.y31{bottom:733.893333pt;}
.y7{bottom:752.613333pt;}
.y30{bottom:755.013333pt;}
.y6{bottom:773.733333pt;}
.y2f{bottom:776.133333pt;}
.y5{bottom:794.853333pt;}
.y2e{bottom:797.253333pt;}
.y4{bottom:815.973333pt;}
.y2d{bottom:818.533333pt;}
.y3{bottom:837.253333pt;}
.y2c{bottom:839.653333pt;}
.y2{bottom:858.373333pt;}
.y2b{bottom:860.773333pt;}
.y0{bottom:875.333333pt;}
.y1{bottom:875.973333pt;}
.y2a{bottom:881.893333pt;}
.y29{bottom:903.173333pt;}
.y28{bottom:924.293333pt;}
.y27{bottom:945.440000pt;}
.h3{height:71.000000pt;}
.h2{height:73.281250pt;}
.h1{height:84.666667pt;}
.h4{height:92.020833pt;}
.h5{height:244.666667pt;}
.h0{height:1056.000000pt;}
.w1{width:277.333333pt;}
.w2{width:624.000000pt;}
.w0{width:816.000000pt;}
.x0{left:96.000000pt;}
.x4{left:249.306667pt;}
.x6{left:337.333333pt;}
.x5{left:369.346667pt;}
.x1{left:373.186667pt;}
.x2{left:381.346667pt;}
.x3{left:408.066667pt;}
.x7{left:719.973333pt;}
}
| braindumps/all_braindumps | 300-209.css | CSS | apache-2.0 | 7,131 |
var addressBar = element(by.css("#addressBar")),
url = 'http://www.example.com/base/ratingList.html#!/path?a=b#h';
it("should show fake browser info on load", function(){
expect(addressBar.getAttribute('value')).toBe(url);
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/path');
expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
expect(element(by.binding('$location.hash()')).getText()).toBe('h');
});
it("should change $location accordingly", function(){
var navigation = element.all(by.css("#navigation a"));
navigation.get(0).click();
expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/first?a=b");
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/first');
expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
expect(element(by.binding('$location.hash()')).getText()).toBe('');
navigation.get(1).click();
expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/sec/ond?flag#hash");
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond');
expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}');
expect(element(by.binding('$location.hash()')).getText()).toBe('hash');
}); | lvkklemo/shopApp | library/angular-1.4.9/docs/examples/example-location-hashbang-mode/protractor.js | JavaScript | apache-2.0 | 2,038 |
/*
* Copyright 2006-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.xml.export;
import org.kuali.rice.core.api.CoreApiServiceLocator;
import org.kuali.rice.kew.export.KewExportDataSet;
import org.kuali.rice.kim.api.group.Group;
import org.kuali.rice.kim.api.group.GroupService;
import org.kuali.rice.kim.api.identity.IdentityService;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.test.BaselineTestCase;
import java.util.List;
import static org.junit.Assert.assertTrue;
/**
* This is a description of what this class does - jjhanso don't forget to fill this in.
*
* @author Kuali Rice Team ([email protected])
*
*/
@BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE)
public class GroupXmlExporterTest extends XmlExporterTestCase {
/**
* This overridden method ...
*
* @see org.kuali.rice.kew.xml.export.XmlExporterTestCase#assertExport()
*/
@Override
protected void assertExport() throws Exception {
IdentityService identityService = KimApiServiceLocator.getIdentityService();
GroupService groupService = KimApiServiceLocator.getGroupService();
List<? extends Group> oldGroups = groupService.getGroupsByPrincipalId(
identityService.getPrincipalByPrincipalName("ewestfal").getPrincipalId());
KewExportDataSet dataSet = new KewExportDataSet();
dataSet.getGroups().addAll(oldGroups);
byte[] xmlBytes = CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet());
assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0);
StringBuffer output = new StringBuffer();
for (int i=0; i < xmlBytes.length; i++){
output.append((char)xmlBytes[i]);
}
System.out.print(output.toString());
// now clear the tables
//ClearDatabaseLifecycle clearLifeCycle = new ClearDatabaseLifecycle();
//clearLifeCycle.getTablesToClear().add("EN_RULE_BASE_VAL_T");
//clearLifeCycle.getTablesToClear().add("EN_RULE_ATTRIB_T");
//clearLifeCycle.getTablesToClear().add("EN_RULE_TMPL_T");
//clearLifeCycle.getTablesToClear().add("EN_DOC_TYP_T");
//clearLifeCycle.start();
//new ClearCacheLifecycle().stop();
//KimImplServiceLocator.getGroupService().
// import the exported xml
//loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes)));
/*
List newRules = KEWServiceLocator.getRuleService().fetchAllRules(true);
assertEquals("Should have same number of old and new Rules.", oldRules.size(), newRules.size());
for (Iterator iterator = oldRules.iterator(); iterator.hasNext();) {
RuleBaseValues oldRule = (RuleBaseValues) iterator.next();
boolean foundRule = false;
for (Iterator iterator2 = newRules.iterator(); iterator2.hasNext();) {
RuleBaseValues newRule = (RuleBaseValues) iterator2.next();
if (oldRule.getDescription().equals(newRule.getDescription())) {
assertRuleExport(oldRule, newRule);
foundRule = true;
}
}
assertTrue("Could not locate the new rule for description " + oldRule.getDescription(), foundRule);
}
*/
}
}
| sbower/kuali-rice-1 | it/kew/src/test/java/org/kuali/rice/kew/xml/export/GroupXmlExporterTest.java | Java | apache-2.0 | 4,009 |
# AUTOGENERATED FILE
FROM balenalib/imx8m-var-dart-ubuntu:xenial-run
ENV NODE_VERSION 15.14.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "6d5e0074fe4a45d444bc581aa1fd7ce7081b8491b0f785414a6e5cc30c42854a node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu xenial \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/node/imx8m-var-dart/ubuntu/xenial/15.14.0/run/Dockerfile | Dockerfile | apache-2.0 | 2,918 |
/**
* Copyright 2015 Smart Society Services B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.alliander.osgp.core.infra.jms.protocol.in;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.ConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jms.core.JmsTemplate;
import com.alliander.osgp.core.infra.jms.JmsTemplateSettings;
import com.alliander.osgp.domain.core.entities.ProtocolInfo;
public class ProtocolResponseMessageJmsTemplateFactory implements InitializingBean {
private final ConnectionFactory connectionFactory;
private final JmsTemplateSettings jmsTemplateSettings;
private Map<String, JmsTemplate> jmsTemplateMap = new HashMap<>();
public ProtocolResponseMessageJmsTemplateFactory(final ConnectionFactory connectionFactory,
final JmsTemplateSettings jmsTemplateSettings, final List<ProtocolInfo> protocolInfos) {
this.connectionFactory = connectionFactory;
this.jmsTemplateSettings = jmsTemplateSettings;
for (final ProtocolInfo protocolInfo : protocolInfos) {
this.jmsTemplateMap.put(protocolInfo.getKey(), this.createJmsTemplate(protocolInfo));
}
}
public JmsTemplate getJmsTemplate(final String key) {
return this.jmsTemplateMap.get(key);
}
@Override
public void afterPropertiesSet() {
for (final JmsTemplate jmsTemplate : this.jmsTemplateMap.values()) {
jmsTemplate.afterPropertiesSet();
}
}
private JmsTemplate createJmsTemplate(final ProtocolInfo protocolInfo) {
final JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setDefaultDestination(new ActiveMQQueue(protocolInfo.getOutgoingProtocolResponsesQueue()));
// Enable the use of deliveryMode, priority, and timeToLive
jmsTemplate.setExplicitQosEnabled(this.jmsTemplateSettings.isExplicitQosEnabled());
jmsTemplate.setTimeToLive(this.jmsTemplateSettings.getTimeToLive());
jmsTemplate.setDeliveryPersistent(this.jmsTemplateSettings.isDeliveryPersistent());
jmsTemplate.setConnectionFactory(this.connectionFactory);
return jmsTemplate;
}
}
| wernerb/Platform | osgp-core/src/main/java/com/alliander/osgp/core/infra/jms/protocol/in/ProtocolResponseMessageJmsTemplateFactory.java | Java | apache-2.0 | 2,471 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>About</title>
<style>
a:link {
color: #1976d2;
text-decoration: none;
}
</style>
</head>
<body>
<ul>
<li><code>Delete icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li>
<li><code>Add alarm icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li>
<li><code>Alarm icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li>
<li><code>Forward icon</code> by <a href="https://www.iconfinder.com/DesignRevision">Design Revision</a>, free for commercial use.</li>
<li><code>Time icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li>
<li><code>Alarm off icon</code> by <a href="https://design.google.com/">Google</a>, licensed under <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons (Attribution-Share Alike 3.0 Unported)</a></li>
</ul>
</body>
</html>
| CarloRodriguez/AlarmOn | app/src/main/assets/art.html | HTML | apache-2.0 | 1,601 |
package com.codedpoetry.maven.dockerplugin.templates;
import java.io.StringWriter;
import java.util.Map;
public interface TemplateRenderer {
StringWriter renderTemplate(String templateUrl, Map context);
} | fllaca/docker-maven-plugin | src/main/java/com/codedpoetry/maven/dockerplugin/templates/TemplateRenderer.java | Java | apache-2.0 | 209 |
package st.domain.quitanda.client.model.contract;
/**
* Created by Daniel Costa at 8/27/16.
* Using user computer xdata
*/
public interface TypePayment
{
public int getDataBaseId();
}
| danie555costa/Quitanda | app/src/main/java/st/domain/quitanda/client/model/contract/TypePayment.java | Java | apache-2.0 | 192 |
package example.repo;
import example.model.Customer1794;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer1794Repository extends CrudRepository<Customer1794, Long> {
List<Customer1794> findByLastName(String lastName);
}
| spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/repo/Customer1794Repository.java | Java | apache-2.0 | 284 |
"use strict";
define(["lib/three.min"], function() {
var Reality = function(sourceCanvas){
// Create a default camera and scene.
var camera = new THREE.Camera();
var scene = new THREE.Scene();
// Create a plane geometry to hold the sourceCanvas texture
var geometry = new THREE.PlaneGeometry(2, 2, 0);
// Create a material textured with the contents of sourceCanvas.
var texture = new THREE.Texture(sourceCanvas);
var material = new THREE.MeshBasicMaterial({
map: texture,
depthTest: false,
depthWrite: false
});
// Build a mesh and add it to the scene.
var mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
// We need to notify ThreeJS when the texture has changed.
function update() {
texture.needsUpdate = true;
}
return {
camera: camera,
scene: scene,
update: update,
}
}
var Scene = function() {
var scene = new THREE.Scene();
var camera = new THREE.Camera();
function add(object) {
scene.add(object);
}
function remove(object) {
scene.remove(object);
}
function setProjectionMatrix(matrix) {
camera.projectionMatrix.setFromArray( matrix );
}
return {
scene:scene,
camera:camera,
add:add,
remove:remove,
setProjectionMatrix:setProjectionMatrix,
}
}
var create = function(dimensions, sourceCanvas) {
// Create a canvas which will be used for WebGL
var glCanvas = document.createElement('canvas');
// Initialize the renderer and attach it to the canvas
var renderer = new THREE.WebGLRenderer({canvas:glCanvas});
renderer.setSize(dimensions.width, dimensions.height);
renderer.autoClear = false;
// Create a reality scene
var reality = new Reality(sourceCanvas);
var virtual = new Scene();
var light = new THREE.SpotLight(0xffffff);
light.position.set(0, 0, 9000);
light.lookAt( new THREE.Vector3(0,0,0) );
virtual.scene.add(light);
function render() {
// Render the reality scene
renderer.render(reality.scene, reality.camera);
// Render the augmented components on top of the reality scene.
renderer.render(virtual.scene, virtual.camera);
}
function update() {
// Notify the reality scene to update it's texture
reality.update();
}
function setCameraMatrix( matrix ) {
virtual.setProjectionMatrix( matrix );
}
function add( object ) {
virtual.add( object.model );
}
function remove( object ) {
virtual.remove( object.model );
}
return {
add: add,
remove: remove,
update: update,
render: render,
glCanvas: glCanvas,
setCameraMatrix: setCameraMatrix,
}
}
return {
create: create,
}
});
| xsoh/3DKabah | arview.js | JavaScript | apache-2.0 | 3,251 |
# Agrimonia viscidula Bunge SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Agrimonia/Agrimonia viscidula/README.md | Markdown | apache-2.0 | 175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.